code
stringlengths
10
749k
repo_name
stringlengths
5
108
path
stringlengths
7
333
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
10
749k
/* * Hibernate OGM, Domain model persistence for NoSQL datastores * * License: GNU Lesser General Public License (LGPL), version 2.1 or later * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.ogm.datastore.redis.options.navigation; import java.util.concurrent.TimeUnit; import org.hibernate.ogm.datastore.document.options.navigation.DocumentStoreGlobalContext; import org.hibernate.ogm.datastore.keyvalue.options.navigation.KeyValueStoreGlobalContext; /** * Allows to configure Redis-specific options applying on a global level. These options may be overridden for single * entities or properties. * * @author Mark Paluch */ public interface RedisGlobalContext extends KeyValueStoreGlobalContext<RedisGlobalContext, RedisEntityContext>, DocumentStoreGlobalContext<RedisGlobalContext, RedisEntityContext> { /** * Specifies the TTL for keys. See also {@link org.hibernate.ogm.datastore.redis.options.TTL} * * @param value the TTL duration * @param timeUnit the TTL time unit * * @return this context, allowing for further fluent API invocations */ RedisGlobalContext ttl(long value, TimeUnit timeUnit); }
gunnarmorling/hibernate-ogm
redis/src/main/java/org/hibernate/ogm/datastore/redis/options/navigation/RedisGlobalContext.java
Java
lgpl-2.1
1,204
/* * eXist-db Open Source Native XML Database * Copyright (C) 2001 The eXist-db Authors * * info@exist-db.org * http://www.exist-db.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.exist.xquery.functions.securitymanager; import java.util.Collections; import java.util.List; import org.exist.dom.QName; import org.exist.security.SecurityManager; import org.exist.security.Subject; import org.exist.storage.DBBroker; import org.exist.xquery.BasicFunction; import org.exist.xquery.Cardinality; import org.exist.xquery.FunctionSignature; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.value.BooleanValue; import org.exist.xquery.value.FunctionParameterSequenceType; import org.exist.xquery.value.FunctionReturnSequenceType; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.SequenceType; import org.exist.xquery.value.StringValue; import org.exist.xquery.value.Type; import org.exist.xquery.value.ValueSequence; /** * * @author <a href="mailto:adam@existsolutions.com">Adam Retter</a> */ public class FindUserFunction extends BasicFunction { private final static QName qnFindUsersByUsername = new QName("find-users-by-username", SecurityManagerModule.NAMESPACE_URI, SecurityManagerModule.PREFIX); private final static QName qnFindUsersByName = new QName("find-users-by-name", SecurityManagerModule.NAMESPACE_URI, SecurityManagerModule.PREFIX); private final static QName qnFindUsersByNamePart = new QName("find-users-by-name-part", SecurityManagerModule.NAMESPACE_URI, SecurityManagerModule.PREFIX); private final static QName qnListUsers = new QName("list-users", SecurityManagerModule.NAMESPACE_URI, SecurityManagerModule.PREFIX); private final static QName qnUserExists = new QName("user-exists", SecurityManagerModule.NAMESPACE_URI, SecurityManagerModule.PREFIX); public final static FunctionSignature FNS_FIND_USERS_BY_USERNAME = new FunctionSignature( qnFindUsersByUsername, "Finds users whoose username starts with a matching string", new SequenceType[] { new FunctionParameterSequenceType("starts-with", Type.STRING, Cardinality.EXACTLY_ONE, "The starting string against which to match usernames") }, new FunctionReturnSequenceType(Type.STRING, Cardinality.ZERO_OR_MORE, "The list of matching usernames") ); public final static FunctionSignature FNS_FIND_USERS_BY_NAME = new FunctionSignature( qnFindUsersByName, "Finds users whoose personal name starts with a matching string", new SequenceType[] { new FunctionParameterSequenceType("starts-with", Type.STRING, Cardinality.EXACTLY_ONE, "The starting string against which to match a personal name") }, new FunctionReturnSequenceType(Type.STRING, Cardinality.ZERO_OR_MORE, "The list of matching usernames") ); public final static FunctionSignature FNS_FIND_USERS_BY_NAME_PART = new FunctionSignature( qnFindUsersByNamePart, "Finds users whoose first name or last name starts with a matching string", new SequenceType[] { new FunctionParameterSequenceType("starts-with", Type.STRING, Cardinality.EXACTLY_ONE, "The starting string against which to match a first or last name") }, new FunctionReturnSequenceType(Type.STRING, Cardinality.ZERO_OR_MORE, "The list of matching usernames") ); public final static FunctionSignature FNS_LIST_USERS = new FunctionSignature( qnListUsers, "List all users. You must be a DBA to enumerate all users, if you are not a DBA you will just get the username of the currently logged in user.", null, new FunctionReturnSequenceType(Type.STRING, Cardinality.ONE_OR_MORE, "The list of users.") ); public final static FunctionSignature FNS_USER_EXISTS = new FunctionSignature( qnUserExists, "Determines whether a user exists.", new SequenceType[] { new FunctionParameterSequenceType("user", Type.STRING, Cardinality.EXACTLY_ONE, "The username to check for existence.") }, new FunctionReturnSequenceType(Type.BOOLEAN, Cardinality.EXACTLY_ONE, "true if the user account exists, false otherwise.") ); public FindUserFunction(XQueryContext context, FunctionSignature signature) { super(context, signature); } @Override public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { final DBBroker broker = getContext().getBroker(); final Subject currentUser = broker.getCurrentSubject(); final SecurityManager securityManager = broker.getBrokerPool().getSecurityManager(); final Sequence result; if(isCalledAs(qnListUsers.getLocalPart())) { result = new ValueSequence(); if(currentUser.getName().equals(SecurityManager.GUEST_USER)) { result.add(new StringValue(SecurityManager.GUEST_USER)); } else { addUserNamesToSequence(securityManager.findAllUserNames(), result); } } else { if(currentUser.getName().equals(SecurityManager.GUEST_USER)) { throw new XPathException("You must be an authenticated user"); } if(isCalledAs(qnUserExists.getLocalPart())) { final String username = args[0].getStringValue(); result = BooleanValue.valueOf(securityManager.hasAccount(username)); } else { result = new ValueSequence(); final String startsWith = args[0].getStringValue(); final List<String> usernames; if(isCalledAs(qnFindUsersByUsername.getLocalPart())) { usernames = securityManager.findUsernamesWhereUsernameStarts(startsWith); } else if(isCalledAs(qnFindUsersByName.getLocalPart())) { usernames = securityManager.findUsernamesWhereNameStarts(startsWith); } else if(isCalledAs(qnFindUsersByNamePart.getLocalPart())) { usernames = securityManager.findUsernamesWhereNamePartStarts(startsWith); } else { throw new XPathException("Unknown function"); } addUserNamesToSequence(usernames, result); } } return result; } private void addUserNamesToSequence(final List<String> userNames, final Sequence sequence) throws XPathException { //order a-z Collections.sort(userNames); for(final String userName : userNames) { sequence.add(new StringValue(userName)); } } }
eXist-db/exist
exist-core/src/main/java/org/exist/xquery/functions/securitymanager/FindUserFunction.java
Java
lgpl-2.1
7,496
/* ------------------------------------------------------------------- * Copyright (c) 2006 Wael Chatila / Icegreen Technologies. All Rights Reserved. * This software is released under the LGPL which is available at http://www.gnu.org/copyleft/lesser.html * This file has been modified by the copyright holder. Original file can be found at http://james.apache.org * ------------------------------------------------------------------- */ package com.icegreen.greenmail.imap.commands; import com.icegreen.greenmail.imap.ImapRequestLineReader; import com.icegreen.greenmail.imap.ImapResponse; import com.icegreen.greenmail.imap.ImapSession; import com.icegreen.greenmail.imap.ProtocolException; /** * Handles processeing for the LOGOUT imap command. * * @author Darrell DeBoer <darrell@apache.org> * @version $Revision: 109034 $ */ class LogoutCommand extends CommandTemplate { public static final String NAME = "LOGOUT"; public static final String ARGS = null; public static final String BYE_MESSAGE = VERSION + SP + "Server logging out"; /** * @see CommandTemplate#doProcess */ protected void doProcess(ImapRequestLineReader request, ImapResponse response, ImapSession session) throws ProtocolException { parser.endLine(request); response.byeResponse(BYE_MESSAGE); response.commandComplete(this); session.closeConnection(); } /** * @see ImapCommand#getName */ public String getName() { return NAME; } /** * @see CommandTemplate#getArgSyntax */ public String getArgSyntax() { return ARGS; } } /* 6.1.3. LOGOUT Command Arguments: none Responses: REQUIRED untagged response: BYE Result: OK - logout completed BAD - command unknown or arguments invalid The LOGOUT command informs the server that the client is done with the connection. The server MUST send a BYE untagged response before the (tagged) OK response, and then close the network connection. Example: C: A023 LOGOUT S: * BYE IMAP4rev1 Server logging out S: A023 OK LOGOUT completed (Server and client then close the connection) */
Tybion/community-edition
projects/3rd-party/greenmail/source/java/com/icegreen/greenmail/imap/commands/LogoutCommand.java
Java
lgpl-3.0
2,373
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.connector.system; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import io.trino.metadata.InternalNode; import io.trino.metadata.InternalNodeManager; import io.trino.spi.HostAddress; import io.trino.spi.connector.ColumnHandle; import io.trino.spi.connector.ConnectorSession; import io.trino.spi.connector.ConnectorSplit; import io.trino.spi.connector.ConnectorSplitManager; import io.trino.spi.connector.ConnectorSplitSource; import io.trino.spi.connector.ConnectorTableHandle; import io.trino.spi.connector.ConnectorTransactionHandle; import io.trino.spi.connector.DynamicFilter; import io.trino.spi.connector.FixedSplitSource; import io.trino.spi.connector.SystemTable; import io.trino.spi.connector.SystemTable.Distribution; import io.trino.spi.connector.TableNotFoundException; import io.trino.spi.predicate.TupleDomain; import java.util.Set; import static io.trino.metadata.NodeState.ACTIVE; import static io.trino.spi.connector.SystemTable.Distribution.ALL_COORDINATORS; import static io.trino.spi.connector.SystemTable.Distribution.ALL_NODES; import static io.trino.spi.connector.SystemTable.Distribution.SINGLE_COORDINATOR; import static java.util.Objects.requireNonNull; public class SystemSplitManager implements ConnectorSplitManager { private final InternalNodeManager nodeManager; private final SystemTablesProvider tables; public SystemSplitManager(InternalNodeManager nodeManager, SystemTablesProvider tables) { this.nodeManager = requireNonNull(nodeManager, "nodeManager is null"); this.tables = requireNonNull(tables, "tables is null"); } @Override public ConnectorSplitSource getSplits( ConnectorTransactionHandle transaction, ConnectorSession session, ConnectorTableHandle tableHandle, SplitSchedulingStrategy splitSchedulingStrategy, DynamicFilter dynamicFilter) { SystemTableHandle table = (SystemTableHandle) tableHandle; TupleDomain<ColumnHandle> constraint = table.getConstraint(); SystemTable systemTable = tables.getSystemTable(session, table.getSchemaTableName()) // table might disappear in the meantime .orElseThrow(() -> new TableNotFoundException(table.getSchemaTableName())); Distribution tableDistributionMode = systemTable.getDistribution(); if (tableDistributionMode == SINGLE_COORDINATOR) { HostAddress address = nodeManager.getCurrentNode().getHostAndPort(); ConnectorSplit split = new SystemSplit(address, constraint); return new FixedSplitSource(ImmutableList.of(split)); } ImmutableList.Builder<ConnectorSplit> splits = ImmutableList.builder(); ImmutableSet.Builder<InternalNode> nodes = ImmutableSet.builder(); if (tableDistributionMode == ALL_COORDINATORS) { nodes.addAll(nodeManager.getCoordinators()); } else if (tableDistributionMode == ALL_NODES) { nodes.addAll(nodeManager.getNodes(ACTIVE)); } Set<InternalNode> nodeSet = nodes.build(); for (InternalNode node : nodeSet) { splits.add(new SystemSplit(node.getHostAndPort(), constraint)); } return new FixedSplitSource(splits.build()); } }
electrum/presto
core/trino-main/src/main/java/io/trino/connector/system/SystemSplitManager.java
Java
apache-2.0
3,923
/* * Copyright (c) Facebook, Inc. and 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 com.facebook.buck.intellij.ideabuck.ws.buckevents.consumers; import com.intellij.util.messages.Topic; public interface RulesParsingEndConsumer { Topic<RulesParsingEndConsumer> BUCK_PARSE_RULE_END = Topic.create("buck.parse-rule.end", RulesParsingEndConsumer.class); void consumeParseRuleEnd(long timestamp); }
facebook/buck
tools/ideabuck/src/com/facebook/buck/intellij/ideabuck/ws/buckevents/consumers/RulesParsingEndConsumer.java
Java
apache-2.0
949
/** * 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.yarn.server.timelineservice.storage.flow; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.CellUtil; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.Tag; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.regionserver.HRegionServer; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.yarn.api.records.timelineservice.TimelineEntities; import org.apache.hadoop.yarn.api.records.timelineservice.TimelineEntity; import org.apache.hadoop.yarn.server.timelineservice.collector.TimelineCollectorContext; import org.apache.hadoop.yarn.server.timelineservice.storage.DataGeneratorForTest; import org.apache.hadoop.yarn.server.timelineservice.storage.HBaseTimelineWriterImpl; import org.apache.hadoop.yarn.server.timelineservice.storage.common.BaseTableRW; import org.apache.hadoop.yarn.server.timelineservice.storage.common.ColumnHelper; import org.apache.hadoop.yarn.server.timelineservice.storage.common.HBaseTimelineServerUtils; import org.apache.hadoop.yarn.server.timelineservice.storage.common.LongConverter; import org.apache.hadoop.yarn.server.timelineservice.storage.common.TimestampGenerator; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; /** * Tests the FlowRun and FlowActivity Tables. */ public class TestHBaseStorageFlowRunCompaction { private static HBaseTestingUtility util; private static final String METRIC1 = "MAP_SLOT_MILLIS"; private static final String METRIC2 = "HDFS_BYTES_READ"; private final byte[] aRowKey = Bytes.toBytes("a"); private final byte[] aFamily = Bytes.toBytes("family"); private final byte[] aQualifier = Bytes.toBytes("qualifier"); @BeforeClass public static void setupBeforeClass() throws Exception { util = new HBaseTestingUtility(); Configuration conf = util.getConfiguration(); conf.setInt("hfile.format.version", 3); util.startMiniCluster(); DataGeneratorForTest.createSchema(util.getConfiguration()); } /** * writes non numeric data into flow run table. * reads it back * * @throws Exception */ @Test public void testWriteNonNumericData() throws Exception { String rowKey = "nonNumericRowKey"; String column = "nonNumericColumnName"; String value = "nonNumericValue"; byte[] rowKeyBytes = Bytes.toBytes(rowKey); byte[] columnNameBytes = Bytes.toBytes(column); byte[] valueBytes = Bytes.toBytes(value); Put p = new Put(rowKeyBytes); p.addColumn(FlowRunColumnFamily.INFO.getBytes(), columnNameBytes, valueBytes); Configuration hbaseConf = util.getConfiguration(); Connection conn = null; conn = ConnectionFactory.createConnection(hbaseConf); Table flowRunTable = conn.getTable( BaseTableRW.getTableName(hbaseConf, FlowRunTableRW.TABLE_NAME_CONF_NAME, FlowRunTableRW.DEFAULT_TABLE_NAME)); flowRunTable.put(p); Get g = new Get(rowKeyBytes); Result r = flowRunTable.get(g); assertNotNull(r); assertTrue(r.size() >= 1); Cell actualValue = r.getColumnLatestCell( FlowRunColumnFamily.INFO.getBytes(), columnNameBytes); assertNotNull(CellUtil.cloneValue(actualValue)); assertEquals(Bytes.toString(CellUtil.cloneValue(actualValue)), value); } @Test public void testWriteScanBatchLimit() throws Exception { String rowKey = "nonNumericRowKey"; String column = "nonNumericColumnName"; String value = "nonNumericValue"; String column2 = "nonNumericColumnName2"; String value2 = "nonNumericValue2"; String column3 = "nonNumericColumnName3"; String value3 = "nonNumericValue3"; String column4 = "nonNumericColumnName4"; String value4 = "nonNumericValue4"; byte[] rowKeyBytes = Bytes.toBytes(rowKey); byte[] columnNameBytes = Bytes.toBytes(column); byte[] valueBytes = Bytes.toBytes(value); byte[] columnName2Bytes = Bytes.toBytes(column2); byte[] value2Bytes = Bytes.toBytes(value2); byte[] columnName3Bytes = Bytes.toBytes(column3); byte[] value3Bytes = Bytes.toBytes(value3); byte[] columnName4Bytes = Bytes.toBytes(column4); byte[] value4Bytes = Bytes.toBytes(value4); Put p = new Put(rowKeyBytes); p.addColumn(FlowRunColumnFamily.INFO.getBytes(), columnNameBytes, valueBytes); p.addColumn(FlowRunColumnFamily.INFO.getBytes(), columnName2Bytes, value2Bytes); p.addColumn(FlowRunColumnFamily.INFO.getBytes(), columnName3Bytes, value3Bytes); p.addColumn(FlowRunColumnFamily.INFO.getBytes(), columnName4Bytes, value4Bytes); Configuration hbaseConf = util.getConfiguration(); Connection conn = null; conn = ConnectionFactory.createConnection(hbaseConf); Table flowRunTable = conn.getTable( BaseTableRW.getTableName(hbaseConf, FlowRunTableRW.TABLE_NAME_CONF_NAME, FlowRunTableRW.DEFAULT_TABLE_NAME)); flowRunTable.put(p); String rowKey2 = "nonNumericRowKey2"; byte[] rowKey2Bytes = Bytes.toBytes(rowKey2); p = new Put(rowKey2Bytes); p.addColumn(FlowRunColumnFamily.INFO.getBytes(), columnNameBytes, valueBytes); p.addColumn(FlowRunColumnFamily.INFO.getBytes(), columnName2Bytes, value2Bytes); p.addColumn(FlowRunColumnFamily.INFO.getBytes(), columnName3Bytes, value3Bytes); p.addColumn(FlowRunColumnFamily.INFO.getBytes(), columnName4Bytes, value4Bytes); flowRunTable.put(p); String rowKey3 = "nonNumericRowKey3"; byte[] rowKey3Bytes = Bytes.toBytes(rowKey3); p = new Put(rowKey3Bytes); p.addColumn(FlowRunColumnFamily.INFO.getBytes(), columnNameBytes, valueBytes); p.addColumn(FlowRunColumnFamily.INFO.getBytes(), columnName2Bytes, value2Bytes); p.addColumn(FlowRunColumnFamily.INFO.getBytes(), columnName3Bytes, value3Bytes); p.addColumn(FlowRunColumnFamily.INFO.getBytes(), columnName4Bytes, value4Bytes); flowRunTable.put(p); Scan s = new Scan(); s.addFamily(FlowRunColumnFamily.INFO.getBytes()); s.setStartRow(rowKeyBytes); // set number of cells to fetch per scanner next invocation int batchLimit = 2; s.setBatch(batchLimit); ResultScanner scanner = flowRunTable.getScanner(s); for (Result result : scanner) { assertNotNull(result); assertTrue(!result.isEmpty()); assertTrue(result.rawCells().length <= batchLimit); Map<byte[], byte[]> values = result .getFamilyMap(FlowRunColumnFamily.INFO.getBytes()); assertTrue(values.size() <= batchLimit); } s = new Scan(); s.addFamily(FlowRunColumnFamily.INFO.getBytes()); s.setStartRow(rowKeyBytes); // set number of cells to fetch per scanner next invocation batchLimit = 3; s.setBatch(batchLimit); scanner = flowRunTable.getScanner(s); for (Result result : scanner) { assertNotNull(result); assertTrue(!result.isEmpty()); assertTrue(result.rawCells().length <= batchLimit); Map<byte[], byte[]> values = result .getFamilyMap(FlowRunColumnFamily.INFO.getBytes()); assertTrue(values.size() <= batchLimit); } s = new Scan(); s.addFamily(FlowRunColumnFamily.INFO.getBytes()); s.setStartRow(rowKeyBytes); // set number of cells to fetch per scanner next invocation batchLimit = 1000; s.setBatch(batchLimit); scanner = flowRunTable.getScanner(s); int rowCount = 0; for (Result result : scanner) { assertNotNull(result); assertTrue(!result.isEmpty()); assertTrue(result.rawCells().length <= batchLimit); Map<byte[], byte[]> values = result .getFamilyMap(FlowRunColumnFamily.INFO.getBytes()); assertTrue(values.size() <= batchLimit); // we expect all back in one next call assertEquals(4, values.size()); rowCount++; } // should get back 1 row with each invocation // if scan batch is set sufficiently high assertEquals(3, rowCount); // test with a negative number // should have same effect as setting it to a high number s = new Scan(); s.addFamily(FlowRunColumnFamily.INFO.getBytes()); s.setStartRow(rowKeyBytes); // set number of cells to fetch per scanner next invocation batchLimit = -2992; s.setBatch(batchLimit); scanner = flowRunTable.getScanner(s); rowCount = 0; for (Result result : scanner) { assertNotNull(result); assertTrue(!result.isEmpty()); assertEquals(4, result.rawCells().length); Map<byte[], byte[]> values = result .getFamilyMap(FlowRunColumnFamily.INFO.getBytes()); // we expect all back in one next call assertEquals(4, values.size()); rowCount++; } // should get back 1 row with each invocation // if scan batch is set sufficiently high assertEquals(3, rowCount); } @Test public void testWriteFlowRunCompaction() throws Exception { String cluster = "kompaction_cluster1"; String user = "kompaction_FlowRun__user1"; String flow = "kompaction_flowRun_flow_name"; String flowVersion = "AF1021C19F1351"; long runid = 1449526652000L; int start = 10; int count = 2000; int appIdSuffix = 1; HBaseTimelineWriterImpl hbi = null; long insertTs = System.currentTimeMillis() - count; Configuration c1 = util.getConfiguration(); TimelineEntities te1 = null; TimelineEntity entityApp1 = null; UserGroupInformation remoteUser = UserGroupInformation.createRemoteUser(user); try { hbi = new HBaseTimelineWriterImpl(); hbi.init(c1); // now insert count * ( 100 + 100) metrics // each call to getEntityMetricsApp1 brings back 100 values // of metric1 and 100 of metric2 for (int i = start; i < start + count; i++) { String appName = "application_10240000000000_" + appIdSuffix; insertTs++; te1 = new TimelineEntities(); entityApp1 = TestFlowDataGenerator.getEntityMetricsApp1(insertTs, c1); te1.addEntity(entityApp1); hbi.write(new TimelineCollectorContext(cluster, user, flow, flowVersion, runid, appName), te1, remoteUser); appName = "application_2048000000000_7" + appIdSuffix; insertTs++; te1 = new TimelineEntities(); entityApp1 = TestFlowDataGenerator.getEntityMetricsApp2(insertTs); te1.addEntity(entityApp1); hbi.write(new TimelineCollectorContext(cluster, user, flow, flowVersion, runid, appName), te1, remoteUser); } } finally { String appName = "application_10240000000000_" + appIdSuffix; te1 = new TimelineEntities(); entityApp1 = TestFlowDataGenerator.getEntityMetricsApp1Complete( insertTs + 1, c1); te1.addEntity(entityApp1); if (hbi != null) { hbi.write(new TimelineCollectorContext(cluster, user, flow, flowVersion, runid, appName), te1, remoteUser); hbi.flush(); hbi.close(); } } // check in flow run table TableName flowRunTable = BaseTableRW.getTableName(c1, FlowRunTableRW.TABLE_NAME_CONF_NAME, FlowRunTableRW.DEFAULT_TABLE_NAME); HRegionServer server = util.getRSForFirstRegionInTable(flowRunTable); // flush and compact all the regions of the primary table int regionNum = HBaseTimelineServerUtils.flushCompactTableRegions( server, flowRunTable); assertTrue("Didn't find any regions for primary table!", regionNum > 0); // check flow run for one flow many apps checkFlowRunTable(cluster, user, flow, runid, c1, 4); } private void checkFlowRunTable(String cluster, String user, String flow, long runid, Configuration c1, int valueCount) throws IOException { Scan s = new Scan(); s.addFamily(FlowRunColumnFamily.INFO.getBytes()); byte[] startRow = new FlowRunRowKey(cluster, user, flow, runid).getRowKey(); s.setStartRow(startRow); String clusterStop = cluster + "1"; byte[] stopRow = new FlowRunRowKey(clusterStop, user, flow, runid).getRowKey(); s.setStopRow(stopRow); Connection conn = ConnectionFactory.createConnection(c1); Table table1 = conn.getTable( BaseTableRW.getTableName(c1, FlowRunTableRW.TABLE_NAME_CONF_NAME, FlowRunTableRW.DEFAULT_TABLE_NAME)); ResultScanner scanner = table1.getScanner(s); int rowCount = 0; for (Result result : scanner) { assertNotNull(result); assertTrue(!result.isEmpty()); Map<byte[], byte[]> values = result.getFamilyMap(FlowRunColumnFamily.INFO .getBytes()); assertEquals(valueCount, values.size()); rowCount++; // check metric1 byte[] q = ColumnHelper.getColumnQualifier( FlowRunColumnPrefix.METRIC.getColumnPrefixBytes(), METRIC1); assertTrue(values.containsKey(q)); assertEquals(141, Bytes.toLong(values.get(q))); // check metric2 q = ColumnHelper.getColumnQualifier( FlowRunColumnPrefix.METRIC.getColumnPrefixBytes(), METRIC2); assertTrue(values.containsKey(q)); assertEquals(57, Bytes.toLong(values.get(q))); } assertEquals(1, rowCount); } private FlowScanner getFlowScannerForTestingCompaction() { // create a FlowScanner object with the sole purpose of invoking a process // summation; // okay to pass in nulls for the constructor arguments // because all we want to do is invoke the process summation FlowScanner fs = new FlowScanner(null, null, FlowScannerOperation.MAJOR_COMPACTION); assertNotNull(fs); return fs; } @Test public void checkProcessSummationMoreCellsSumFinal2() throws IOException { long cellValue1 = 1236L; long cellValue2 = 28L; long cellValue3 = 1236L; long cellValue4 = 1236L; FlowScanner fs = getFlowScannerForTestingCompaction(); // note down the current timestamp long currentTimestamp = System.currentTimeMillis(); long cell1Ts = 1200120L; long cell2Ts = TimestampGenerator.getSupplementedTimestamp( System.currentTimeMillis(), "application_123746661110_11202"); long cell3Ts = 1277719L; long cell4Ts = currentTimestamp - 10; SortedSet<Cell> currentColumnCells = new TreeSet<Cell>(KeyValue.COMPARATOR); List<Tag> tags = new ArrayList<>(); Tag t = HBaseTimelineServerUtils.createTag( AggregationOperation.SUM_FINAL.getTagType(), "application_1234588888_91188"); tags.add(t); byte[] tagByteArray = HBaseTimelineServerUtils.convertTagListToByteArray(tags); // create a cell with a VERY old timestamp and attribute SUM_FINAL Cell c1 = HBaseTimelineServerUtils.createNewCell(aRowKey, aFamily, aQualifier, cell1Ts, Bytes.toBytes(cellValue1), tagByteArray); currentColumnCells.add(c1); tags = new ArrayList<>(); t = HBaseTimelineServerUtils.createTag( AggregationOperation.SUM_FINAL.getTagType(), "application_12700000001_29102"); tags.add(t); tagByteArray = HBaseTimelineServerUtils.convertTagListToByteArray(tags); // create a cell with a recent timestamp and attribute SUM_FINAL Cell c2 = HBaseTimelineServerUtils.createNewCell(aRowKey, aFamily, aQualifier, cell2Ts, Bytes.toBytes(cellValue2), tagByteArray); currentColumnCells.add(c2); tags = new ArrayList<>(); t = HBaseTimelineServerUtils.createTag( AggregationOperation.SUM.getTagType(), "application_191780000000001_8195"); tags.add(t); tagByteArray = HBaseTimelineServerUtils.convertTagListToByteArray(tags); // create a cell with a VERY old timestamp but has attribute SUM Cell c3 = HBaseTimelineServerUtils.createNewCell(aRowKey, aFamily, aQualifier, cell3Ts, Bytes.toBytes(cellValue3), tagByteArray); currentColumnCells.add(c3); tags = new ArrayList<>(); t = HBaseTimelineServerUtils.createTag( AggregationOperation.SUM.getTagType(), "application_191780000000001_98104"); tags.add(t); tagByteArray = HBaseTimelineServerUtils.convertTagListToByteArray(tags); // create a cell with a VERY old timestamp but has attribute SUM Cell c4 = HBaseTimelineServerUtils.createNewCell(aRowKey, aFamily, aQualifier, cell4Ts, Bytes.toBytes(cellValue4), tagByteArray); currentColumnCells.add(c4); List<Cell> cells = fs.processSummationMajorCompaction(currentColumnCells, new LongConverter(), currentTimestamp); assertNotNull(cells); // we should be getting back 4 cells // one is the flow sum cell // two are the cells with SUM attribute // one cell with SUM_FINAL assertEquals(4, cells.size()); for (int i = 0; i < cells.size(); i++) { Cell returnedCell = cells.get(0); assertNotNull(returnedCell); long returnTs = returnedCell.getTimestamp(); long returnValue = Bytes.toLong(CellUtil .cloneValue(returnedCell)); if (returnValue == cellValue2) { assertTrue(returnTs == cell2Ts); } else if (returnValue == cellValue3) { assertTrue(returnTs == cell3Ts); } else if (returnValue == cellValue4) { assertTrue(returnTs == cell4Ts); } else if (returnValue == cellValue1) { assertTrue(returnTs != cell1Ts); assertTrue(returnTs > cell1Ts); assertTrue(returnTs >= currentTimestamp); } else { // raise a failure since we expect only these two values back Assert.fail(); } } } // tests with many cells // of type SUM and SUM_FINAL // all cells of SUM_FINAL will expire @Test public void checkProcessSummationMoreCellsSumFinalMany() throws IOException { FlowScanner fs = getFlowScannerForTestingCompaction(); int count = 200000; long cellValueFinal = 1000L; long cellValueNotFinal = 28L; // note down the current timestamp long currentTimestamp = System.currentTimeMillis(); long cellTsFinalStart = 10001120L; long cellTsFinal = cellTsFinalStart; long cellTsNotFinalStart = currentTimestamp - 5; long cellTsNotFinal = cellTsNotFinalStart; SortedSet<Cell> currentColumnCells = new TreeSet<Cell>(KeyValue.COMPARATOR); List<Tag> tags = null; Tag t = null; Cell c1 = null; // insert SUM_FINAL cells for (int i = 0; i < count; i++) { tags = new ArrayList<>(); t = HBaseTimelineServerUtils.createTag( AggregationOperation.SUM_FINAL.getTagType(), "application_123450000" + i + "01_19" + i); tags.add(t); byte[] tagByteArray = HBaseTimelineServerUtils.convertTagListToByteArray(tags); // create a cell with a VERY old timestamp and attribute SUM_FINAL c1 = HBaseTimelineServerUtils.createNewCell(aRowKey, aFamily, aQualifier, cellTsFinal, Bytes.toBytes(cellValueFinal), tagByteArray); currentColumnCells.add(c1); cellTsFinal++; } // add SUM cells for (int i = 0; i < count; i++) { tags = new ArrayList<>(); t = HBaseTimelineServerUtils.createTag( AggregationOperation.SUM.getTagType(), "application_1987650000" + i + "83_911" + i); tags.add(t); byte[] tagByteArray = HBaseTimelineServerUtils.convertTagListToByteArray(tags); // create a cell with attribute SUM c1 = HBaseTimelineServerUtils.createNewCell(aRowKey, aFamily, aQualifier, cellTsNotFinal, Bytes.toBytes(cellValueNotFinal), tagByteArray); currentColumnCells.add(c1); cellTsNotFinal++; } List<Cell> cells = fs.processSummationMajorCompaction(currentColumnCells, new LongConverter(), currentTimestamp); assertNotNull(cells); // we should be getting back count + 1 cells // one is the flow sum cell // others are the cells with SUM attribute assertEquals(count + 1, cells.size()); for (int i = 0; i < cells.size(); i++) { Cell returnedCell = cells.get(0); assertNotNull(returnedCell); long returnTs = returnedCell.getTimestamp(); long returnValue = Bytes.toLong(CellUtil .cloneValue(returnedCell)); if (returnValue == (count * cellValueFinal)) { assertTrue(returnTs > (cellTsFinalStart + count)); assertTrue(returnTs >= currentTimestamp); } else if ((returnValue >= cellValueNotFinal) && (returnValue <= cellValueNotFinal * count)) { assertTrue(returnTs >= cellTsNotFinalStart); assertTrue(returnTs <= cellTsNotFinalStart * count); } else { // raise a failure since we expect only these values back Assert.fail(); } } } // tests with many cells // of type SUM and SUM_FINAL // NOT cells of SUM_FINAL will expire @Test public void checkProcessSummationMoreCellsSumFinalVariedTags() throws IOException { FlowScanner fs = getFlowScannerForTestingCompaction(); int countFinal = 20100; int countNotFinal = 1000; int countFinalNotExpire = 7009; long cellValueFinal = 1000L; long cellValueNotFinal = 28L; // note down the current timestamp long currentTimestamp = System.currentTimeMillis(); long cellTsFinalStart = 10001120L; long cellTsFinal = cellTsFinalStart; long cellTsFinalStartNotExpire = TimestampGenerator .getSupplementedTimestamp(System.currentTimeMillis(), "application_10266666661166_118821"); long cellTsFinalNotExpire = cellTsFinalStartNotExpire; long cellTsNotFinalStart = currentTimestamp - 5; long cellTsNotFinal = cellTsNotFinalStart; SortedSet<Cell> currentColumnCells = new TreeSet<Cell>(KeyValue.COMPARATOR); List<Tag> tags = null; Tag t = null; Cell c1 = null; // insert SUM_FINAL cells which will expire for (int i = 0; i < countFinal; i++) { tags = new ArrayList<>(); t = HBaseTimelineServerUtils.createTag( AggregationOperation.SUM_FINAL.getTagType(), "application_123450000" + i + "01_19" + i); tags.add(t); byte[] tagByteArray = HBaseTimelineServerUtils.convertTagListToByteArray(tags); // create a cell with a VERY old timestamp and attribute SUM_FINAL c1 = HBaseTimelineServerUtils.createNewCell(aRowKey, aFamily, aQualifier, cellTsFinal, Bytes.toBytes(cellValueFinal), tagByteArray); currentColumnCells.add(c1); cellTsFinal++; } // insert SUM_FINAL cells which will NOT expire for (int i = 0; i < countFinalNotExpire; i++) { tags = new ArrayList<>(); t = HBaseTimelineServerUtils.createTag( AggregationOperation.SUM_FINAL.getTagType(), "application_123450000" + i + "01_19" + i); tags.add(t); byte[] tagByteArray = HBaseTimelineServerUtils.convertTagListToByteArray(tags); // create a cell with a VERY old timestamp and attribute SUM_FINAL c1 = HBaseTimelineServerUtils.createNewCell(aRowKey, aFamily, aQualifier, cellTsFinalNotExpire, Bytes.toBytes(cellValueFinal), tagByteArray); currentColumnCells.add(c1); cellTsFinalNotExpire++; } // add SUM cells for (int i = 0; i < countNotFinal; i++) { tags = new ArrayList<>(); t = HBaseTimelineServerUtils.createTag( AggregationOperation.SUM.getTagType(), "application_1987650000" + i + "83_911" + i); tags.add(t); byte[] tagByteArray = HBaseTimelineServerUtils.convertTagListToByteArray(tags); // create a cell with attribute SUM c1 = HBaseTimelineServerUtils.createNewCell(aRowKey, aFamily, aQualifier, cellTsNotFinal, Bytes.toBytes(cellValueNotFinal), tagByteArray); currentColumnCells.add(c1); cellTsNotFinal++; } List<Cell> cells = fs.processSummationMajorCompaction(currentColumnCells, new LongConverter(), currentTimestamp); assertNotNull(cells); // we should be getting back // countNotFinal + countFinalNotExpire + 1 cells // one is the flow sum cell // count = the cells with SUM attribute // count = the cells with SUM_FINAL attribute but not expired assertEquals(countFinalNotExpire + countNotFinal + 1, cells.size()); for (int i = 0; i < cells.size(); i++) { Cell returnedCell = cells.get(0); assertNotNull(returnedCell); long returnTs = returnedCell.getTimestamp(); long returnValue = Bytes.toLong(CellUtil .cloneValue(returnedCell)); if (returnValue == (countFinal * cellValueFinal)) { assertTrue(returnTs > (cellTsFinalStart + countFinal)); assertTrue(returnTs >= currentTimestamp); } else if (returnValue == cellValueNotFinal) { assertTrue(returnTs >= cellTsNotFinalStart); assertTrue(returnTs <= cellTsNotFinalStart + countNotFinal); } else if (returnValue == cellValueFinal){ assertTrue(returnTs >= cellTsFinalStartNotExpire); assertTrue(returnTs <= cellTsFinalStartNotExpire + countFinalNotExpire); } else { // raise a failure since we expect only these values back Assert.fail(); } } } @Test public void testProcessSummationMoreCellsSumFinal() throws IOException { FlowScanner fs = getFlowScannerForTestingCompaction(); // note down the current timestamp long currentTimestamp = System.currentTimeMillis(); long cellValue1 = 1236L; long cellValue2 = 28L; List<Tag> tags = new ArrayList<>(); Tag t = HBaseTimelineServerUtils.createTag( AggregationOperation.SUM_FINAL.getTagType(), "application_1234588888_999888"); tags.add(t); byte[] tagByteArray = HBaseTimelineServerUtils.convertTagListToByteArray(tags); SortedSet<Cell> currentColumnCells = new TreeSet<Cell>(KeyValue.COMPARATOR); // create a cell with a VERY old timestamp and attribute SUM_FINAL Cell c1 = HBaseTimelineServerUtils.createNewCell(aRowKey, aFamily, aQualifier, 120L, Bytes.toBytes(cellValue1), tagByteArray); currentColumnCells.add(c1); tags = new ArrayList<>(); t = HBaseTimelineServerUtils.createTag( AggregationOperation.SUM.getTagType(), "application_100000000001_119101"); tags.add(t); tagByteArray = HBaseTimelineServerUtils.convertTagListToByteArray(tags); // create a cell with a VERY old timestamp but has attribute SUM Cell c2 = HBaseTimelineServerUtils.createNewCell(aRowKey, aFamily, aQualifier, 130L, Bytes.toBytes(cellValue2), tagByteArray); currentColumnCells.add(c2); List<Cell> cells = fs.processSummationMajorCompaction(currentColumnCells, new LongConverter(), currentTimestamp); assertNotNull(cells); // we should be getting back two cells // one is the flow sum cell // another is the cell with SUM attribute assertEquals(2, cells.size()); Cell returnedCell = cells.get(0); assertNotNull(returnedCell); long inputTs1 = c1.getTimestamp(); long inputTs2 = c2.getTimestamp(); long returnTs = returnedCell.getTimestamp(); long returnValue = Bytes.toLong(CellUtil .cloneValue(returnedCell)); // the returned Ts will be far greater than input ts as well as the noted // current timestamp if (returnValue == cellValue2) { assertTrue(returnTs == inputTs2); } else if (returnValue == cellValue1) { assertTrue(returnTs >= currentTimestamp); assertTrue(returnTs != inputTs1); } else { // raise a failure since we expect only these two values back Assert.fail(); } } @Test public void testProcessSummationOneCellSumFinal() throws IOException { FlowScanner fs = getFlowScannerForTestingCompaction(); // note down the current timestamp long currentTimestamp = System.currentTimeMillis(); List<Tag> tags = new ArrayList<>(); Tag t = HBaseTimelineServerUtils.createTag( AggregationOperation.SUM_FINAL.getTagType(), "application_123458888888_999888"); tags.add(t); byte[] tagByteArray = HBaseTimelineServerUtils.convertTagListToByteArray(tags); SortedSet<Cell> currentColumnCells = new TreeSet<Cell>(KeyValue.COMPARATOR); // create a cell with a VERY old timestamp Cell c1 = HBaseTimelineServerUtils.createNewCell(aRowKey, aFamily, aQualifier, 120L, Bytes.toBytes(1110L), tagByteArray); currentColumnCells.add(c1); List<Cell> cells = fs.processSummationMajorCompaction(currentColumnCells, new LongConverter(), currentTimestamp); assertNotNull(cells); // we should not get the same cell back // but we get back the flow cell assertEquals(1, cells.size()); Cell returnedCell = cells.get(0); // it's NOT the same cell assertNotEquals(c1, returnedCell); long inputTs = c1.getTimestamp(); long returnTs = returnedCell.getTimestamp(); // the returned Ts will be far greater than input ts as well as the noted // current timestamp assertTrue(returnTs > inputTs); assertTrue(returnTs >= currentTimestamp); } @Test public void testProcessSummationOneCell() throws IOException { FlowScanner fs = getFlowScannerForTestingCompaction(); // note down the current timestamp long currentTimestamp = System.currentTimeMillis(); // try for 1 cell with tag SUM List<Tag> tags = new ArrayList<>(); Tag t = HBaseTimelineServerUtils.createTag( AggregationOperation.SUM.getTagType(), "application_123458888888_999888"); tags.add(t); byte[] tagByteArray = HBaseTimelineServerUtils.convertTagListToByteArray(tags); SortedSet<Cell> currentColumnCells = new TreeSet<Cell>(KeyValue.COMPARATOR); Cell c1 = HBaseTimelineServerUtils.createNewCell(aRowKey, aFamily, aQualifier, currentTimestamp, Bytes.toBytes(1110L), tagByteArray); currentColumnCells.add(c1); List<Cell> cells = fs.processSummationMajorCompaction(currentColumnCells, new LongConverter(), currentTimestamp); assertNotNull(cells); // we expect the same cell back assertEquals(1, cells.size()); Cell c2 = cells.get(0); assertEquals(c1, c2); assertEquals(currentTimestamp, c2.getTimestamp()); } @Test public void testProcessSummationEmpty() throws IOException { FlowScanner fs = getFlowScannerForTestingCompaction(); long currentTimestamp = System.currentTimeMillis(); LongConverter longConverter = new LongConverter(); SortedSet<Cell> currentColumnCells = null; List<Cell> cells = fs.processSummationMajorCompaction(currentColumnCells, longConverter, currentTimestamp); assertNotNull(cells); assertEquals(0, cells.size()); currentColumnCells = new TreeSet<Cell>(KeyValue.COMPARATOR); cells = fs.processSummationMajorCompaction(currentColumnCells, longConverter, currentTimestamp); assertNotNull(cells); assertEquals(0, cells.size()); } @AfterClass public static void tearDownAfterClass() throws Exception { if (util != null) { util.shutdownMiniCluster(); } } }
xiao-chen/hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice-hbase-tests/src/test/java/org/apache/hadoop/yarn/server/timelineservice/storage/flow/TestHBaseStorageFlowRunCompaction.java
Java
apache-2.0
32,789
public class JKJK extends KJK { @Override public void te<caret>st() { } }
jwren/intellij-community
plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/hierarchy/kotlin/JKJK/JKJK.java
Java
apache-2.0
86
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.cluster.failover.remote; import org.apache.activemq.artemis.api.core.ActiveMQException; import org.apache.activemq.artemis.api.core.ActiveMQNotConnectedException; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.api.core.client.ActiveMQClient; import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnectorFactory; import org.apache.activemq.artemis.tests.integration.cluster.distribution.ClusterTestBase; import org.junit.Test; public class FailoverWithSharedStoreTest extends ClusterTestBase { @Test public void testNoConnection() throws Exception { ServerLocator locator = ActiveMQClient.createServerLocatorWithHA(new TransportConfiguration(NettyConnectorFactory.class.getName())); try { createSessionFactory(locator); fail(); } catch (ActiveMQNotConnectedException nce) { //ok } catch (ActiveMQException e) { fail("Invalid Exception type:" + e.getType()); } } }
lburgazzoli/apache-activemq-artemis
tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/remote/FailoverWithSharedStoreTest.java
Java
apache-2.0
1,942
/** * Copyright 2013 LinkedIn, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package voldemort.tools.admin; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Properties; import org.junit.After; import org.junit.Before; import org.junit.Test; import voldemort.ServerTestUtils; import voldemort.TestUtils; import voldemort.client.protocol.admin.AdminClient; import voldemort.cluster.Cluster; import voldemort.cluster.Node; import voldemort.server.VoldemortConfig; import voldemort.server.VoldemortServer; import voldemort.store.StoreDefinition; import voldemort.store.StoreDefinitionBuilder; import voldemort.store.socket.SocketStoreFactory; import voldemort.store.socket.clientrequest.ClientRequestExecutorPool; import voldemort.tools.admin.command.AdminCommand; import voldemort.xml.StoreDefinitionsMapper; import com.google.common.base.Joiner; import com.google.common.collect.Lists; /* * This class tests that the quota operations work properly. * It starts with a cluster that has several stores, generates new stores by copy-and-modify * the store names, adds the new stores to the cluster and checks if all new stores are added. * Then it deletes the new stores and checks if the new stores are deleted correctly. */ public class StoreOperationsTest { HashMap<Integer, VoldemortServer> vservers = new HashMap<Integer, VoldemortServer>(); HashMap<Integer, SocketStoreFactory> socketStoreFactories = new HashMap<Integer, SocketStoreFactory>(); String bsURL; Cluster cluster; List<StoreDefinition> stores; AdminClient adminClient; @Before public void setup() throws IOException { // setup cluster cluster = ServerTestUtils.getLocalCluster(2); stores = ServerTestUtils.getStoreDefs(2); bsURL = cluster.getNodes().iterator().next().getSocketUrl().toString(); for(Node node: cluster.getNodes()) { SocketStoreFactory ssf = new ClientRequestExecutorPool(2, 10000, 100000, 1024); VoldemortConfig config = ServerTestUtils.createServerConfigWithDefs(true, node.getId(), TestUtils.createTempDir() .getAbsolutePath(), cluster, stores, new Properties()); VoldemortServer vs = ServerTestUtils.startVoldemortServer(ssf, config, cluster); vservers.put(node.getId(), vs); socketStoreFactories.put(node.getId(), ssf); } adminClient = new AdminClient(cluster); } @Test public void testStoreAddAndDelete() throws Exception { // create new stores_key object final String newStoreXMLFilePrefix = "updated.stores"; final String newStoreXMLFileSuffix = "xml"; List<StoreDefinition> newStores = new ArrayList<StoreDefinition>(); List<String> newStoreNames = Lists.newArrayList(); for(StoreDefinition storeDef: stores) { StoreDefinitionBuilder sb = AdminToolTestUtils.storeDefToBuilder(storeDef); sb.setName(sb.getName() + "_new"); newStores.add(sb.build()); newStoreNames.add(sb.getName()); } // create stores.xml File newStoresXMLFolder = TestUtils.createTempDir(); File newStoreXMLFile = File.createTempFile(newStoreXMLFilePrefix, newStoreXMLFileSuffix, newStoresXMLFolder); FileWriter fwriter = new FileWriter(newStoreXMLFile); fwriter.write(new StoreDefinitionsMapper().writeStoreList(newStores)); fwriter.close(); // execute store-add command AdminCommand.executeCommand(new String[] { "store", "add", "-f", newStoreXMLFile.getAbsolutePath(), "-u", bsURL }); // check if stores have been added Integer nodeId = adminClient.getAdminClientCluster().getNodes().iterator().next().getId(); List<StoreDefinition> newStoresToVerify = adminClient.metadataMgmtOps.getRemoteStoreDefList(nodeId) .getValue(); for(StoreDefinition newStore: newStores) { assertTrue(newStoresToVerify.contains(newStore)); } // execute store-delete command AdminCommand.executeCommand(new String[] { "store", "delete", "-s", Joiner.on(",").join(newStoreNames), "-u", bsURL, "--confirm" }); // check if stores have been deleted newStoresToVerify = adminClient.metadataMgmtOps.getRemoteStoreDefList(nodeId).getValue(); for(StoreDefinition newStore: newStores) { assertTrue(!newStoresToVerify.contains(newStore)); } } @After public void teardown() throws IOException { // shutdown for(VoldemortServer vs: vservers.values()) { ServerTestUtils.stopVoldemortServer(vs); } for(SocketStoreFactory ssf: socketStoreFactories.values()) { ssf.close(); } } }
FelixGV/voldemort
test/unit/voldemort/tools/admin/StoreOperationsTest.java
Java
apache-2.0
6,125
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.query.h2.opt; import org.apache.ignite.internal.cache.query.index.sorted.IndexKeyTypes; import org.apache.ignite.internal.cache.query.index.sorted.keys.IndexKey; import org.h2.value.ValueGeometry; import org.locationtech.jts.geom.Geometry; /** */ public class GeometryIndexKey implements IndexKey { /** */ private final ValueGeometry geometry; /** */ public GeometryIndexKey(Geometry g) { geometry = ValueGeometry.getFromGeometry(g); } /** {@inheritDoc} */ @Override public Object key() { return geometry.getGeometry(); } /** {@inheritDoc} */ @Override public int type() { return IndexKeyTypes.GEOMETRY; } /** {@inheritDoc} */ @Override public int compare(IndexKey o) { return geometry.compareTo(((GeometryIndexKey)o).geometry, null); } }
NSAmelchev/ignite
modules/geospatial/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GeometryIndexKey.java
Java
apache-2.0
1,683
/* This file is part of SableCC ( http://sablecc.org ). * * See the NOTICE file distributed with this work for copyright information. * * 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.sablecc.sablecc.core.transformation; import java.math.*; import java.util.*; import org.sablecc.exception.*; import org.sablecc.sablecc.core.*; import org.sablecc.sablecc.core.Parser.ParserElement.ElementType; import org.sablecc.sablecc.core.analysis.*; import org.sablecc.sablecc.core.interfaces.*; import org.sablecc.sablecc.syntax3.node.*; import org.sablecc.util.*; public abstract class AlternativeTransformationListElement implements IVisitableGrammarPart { private final Grammar grammar; public AlternativeTransformationListElement( Grammar grammar) { if (grammar == null) { throw new InternalException("grammar may not be null"); } this.grammar = grammar; } public Grammar getGrammar() { return this.grammar; } public abstract Type.SimpleType getType(); public abstract void constructType(); public abstract String getElement(); public abstract IReferencable getTargetReference(); public abstract Token getLocation(); public static abstract class ReferenceElement extends AlternativeTransformationListElement { private Type.SimpleType type; private IReferencable targetReference; private Parser.ParserElement originReference; public ReferenceElement( Grammar grammar) { super(grammar); } @Override public Type.SimpleType getType() { if (this.type == null) { throw new InternalException( "type shouldn't be null, use constructType()"); } return this.type; } @Override public IReferencable getTargetReference() { return this.targetReference; } protected void addTargetReference( IReferencable reference) { this.targetReference = reference; } public Parser.ParserElement getOriginReference() { return this.originReference; } protected void addOriginReference( Parser.ParserElement reference) { this.originReference = reference; } @Override public void constructType() { if (this.type != null) { throw new InternalException( "constructType shouldn't be used twice"); } if (this.targetReference == null) { throw new InternalException( "constructType shouldn't be called before reference resolution"); } if (this.targetReference instanceof Parser.ParserElement) { this.type = ((Parser.ParserElement) this.targetReference) .getType(); } else { this.type = ((ProductionTransformationElement) this.targetReference) .getType(); } } public boolean isTransformed() { return this.targetReference instanceof ProductionTransformationElement; } } public static class ImplicitReferenceElement extends AlternativeTransformationListElement.ReferenceElement { private String element; public ImplicitReferenceElement( Parser.ParserElement reference, Grammar grammar) { super(grammar); if (reference == null) { throw new InternalException("referenceText may not be null"); } super.addOriginReference(reference); super.addTargetReference(reference); } @Override public void apply( IGrammarVisitor visitor) { visitor.visitAlternativeTransformationReferenceListElement(this); } @Override public String getElement() { if (getTargetReference() instanceof INameDeclaration) { this.element = ((INameDeclaration) getTargetReference()) .getName(); } else if (getTargetReference() instanceof Parser.ParserAlternative) { this.element = ((Parser.ParserAlternative) getTargetReference()) .getName(); if (this.element == null) { this.element = "{" + ((Parser.ParserAlternative) getTargetReference()) .getIndex() + "}"; } } else if (getTargetReference() instanceof Tree.TreeAlternative) { this.element = ((Tree.TreeAlternative) getTargetReference()) .getName(); if (this.element == null) { this.element = "{" + ((Tree.TreeAlternative) getTargetReference()) .getIndex() + "}"; } } else if (getTargetReference() instanceof Parser.ParserElement) { this.element = ((Parser.ParserElement) getTargetReference()) .getElement(); } else if (getTargetReference() instanceof Tree.TreeElement) { this.element = ((Tree.TreeElement) getTargetReference()) .getElement(); } return this.element; } @Override public Token getLocation() { return getTargetReference().getLocation(); } } public static class ExplicitReferenceElement extends AlternativeTransformationListElement.ReferenceElement { private final AReferenceListElement declaration; private String element; public ExplicitReferenceElement( AReferenceListElement declaration, Grammar grammar) { super(grammar); if (declaration == null) { throw new InternalException("declaration may not be null"); } this.declaration = declaration; } public AReferenceListElement getDeclaration() { return this.declaration; } @Override public IReferencable getTargetReference() { if (super.getTargetReference() == null) { throw new InternalException( "reference should have been initialized using addReference"); } return super.getTargetReference(); } @Override public void addTargetReference( IReferencable reference) { if (super.getTargetReference() != null) { throw new InternalException( "addReference shouldn't be used twice"); } super.addTargetReference(reference); } @Override public void addOriginReference( Parser.ParserElement reference) { if (super.getOriginReference() != null) { throw new InternalException( "addReference shouldn't be used twice"); } super.addOriginReference(reference); } @Override public void apply( IGrammarVisitor visitor) { visitor.visitAlternativeTransformationReferenceListElement(this); } @Override public String getElement() { if (this.element == null) { if (this.declaration.getElementReference() instanceof ANaturalElementReference) { ANaturalElementReference naturalRef = (ANaturalElementReference) this.declaration .getElementReference(); this.element = naturalRef.getElement().getText(); } else { ATransformedElementReference naturalRef = (ATransformedElementReference) this.declaration .getElementReference(); this.element = naturalRef.getElement().getText() + naturalRef.getDot().getText() + naturalRef.getPart().getText(); } } return this.element; } @Override public Token getLocation() { if (this.declaration.getElementReference() instanceof ANaturalElementReference) { return ((ANaturalElementReference) this.declaration .getElementReference()).getElement(); } else { return ((ATransformedElementReference) this.declaration .getElementReference()).getElement(); } } } public static abstract class NewElement extends AlternativeTransformationListElement { private Type.SimpleType type; private Tree.TreeAlternative reference; public NewElement( Grammar grammar) { super(grammar); } protected void addReference( Tree.TreeAlternative reference) { this.reference = reference; } public abstract List<AlternativeTransformationElement> getParameters(); @Override public Tree.TreeAlternative getTargetReference() { return this.reference; } @Override public void constructType() { if (this.type != null) { throw new InternalException( "constructType shouldn't be used twice"); } if (this.reference == null) { throw new InternalException( "constructType shouldn't be called before reference resolution"); } this.type = new Type.SimpleType.SeparatedType(this.reference .getProduction().getName(), CardinalityInterval.ONE_ONE); } @Override public Type.SimpleType getType() { if (this.type == null) { throw new InternalException( "type shouldn't be null, use constructType()"); } return this.type; } } public static class ImplicitNewElement extends AlternativeTransformationListElement.NewElement { private final List<AlternativeTransformationElement> transformationElements; public ImplicitNewElement( Tree.TreeAlternative reference, Grammar grammar, List<AlternativeTransformationElement> transformationElements) { super(grammar); if (transformationElements == null) { throw new InternalException("declaration may not be null"); } if (reference == null) { throw new InternalException( "transformationElements may not be null"); } super.addReference(reference); this.transformationElements = transformationElements; } @Override public List<AlternativeTransformationElement> getParameters() { return this.transformationElements; } @Override public void apply( IGrammarVisitor visitor) { visitor.visitAlternativeTransformationNewListElement(this); } @Override public String getElement() { return getTargetReference().getName(); } @Override public Token getLocation() { return getTargetReference().getLocation(); } } public static class ExplicitNewElement extends AlternativeTransformationListElement.NewElement { private final ANewListElement declaration; private final List<AlternativeTransformationElement> transformationElements; public ExplicitNewElement( ANewListElement declaration, Grammar grammar, List<AlternativeTransformationElement> transformationElements) { super(grammar); if (transformationElements == null) { throw new InternalException("declaration may not be null"); } if (declaration == null) { throw new InternalException( "transformationElements may not be null"); } this.declaration = declaration; this.transformationElements = transformationElements; } public ANewListElement getDeclaration() { return this.declaration; } @Override public List<AlternativeTransformationElement> getParameters() { return this.transformationElements; } @Override public Tree.TreeAlternative getTargetReference() { if (super.getTargetReference() == null) { throw new InternalException( "reference should have been initialized using addReference"); } return super.getTargetReference(); } @Override public void addReference( Tree.TreeAlternative reference) { if (super.getTargetReference() != null) { throw new InternalException( "addReference shouldn't be used twice"); } super.addReference(reference); } @Override public void apply( IGrammarVisitor visitor) { visitor.visitAlternativeTransformationNewListElement(this); } @Override public String getElement() { if (this.declaration.getAlternativeReference() instanceof ANamedAlternativeReference) { ANamedAlternativeReference namedRef = (ANamedAlternativeReference) this.declaration .getAlternativeReference(); return namedRef.getProduction().getText() + namedRef.getDot().getText() + namedRef.getAlternative().getText(); } else { return ((AUnnamedAlternativeReference) this.declaration .getAlternativeReference()).getProduction().getText(); } } @Override public Token getLocation() { return this.declaration.getNewKeyword(); } } public static abstract class NormalListElement extends AlternativeTransformationListElement { private Type.SimpleType type; private IReferencable targetReference; private Parser.ParserElement originReference; public NormalListElement( Grammar grammar) { super(grammar); } @Override public Type.SimpleType getType() { if (this.type == null) { throw new InternalException( "type shouldn't be null, use constructType()"); } return this.type; } @Override public IReferencable getTargetReference() { return this.targetReference; } public Parser.ParserElement getOriginReference() { return this.originReference; } protected void addTargetReference( IReferencable reference) { this.targetReference = reference; } protected void addOriginReference( Parser.ParserElement reference) { this.originReference = reference; } @Override public void constructType() { if (this.type != null) { throw new InternalException( "constructType shouldn't be used twice"); } if (this.targetReference == null) { throw new InternalException( "constructType shouldn't be called before reference resolution"); } CardinalityInterval cardinality; String rightName; String leftName = null; if (this.targetReference instanceof Parser.ParserElement) { Parser.ParserElement parserElement = (Parser.ParserElement) this.targetReference; cardinality = parserElement.getCardinality(); switch (parserElement.getElementType()) { case NORMAL: rightName = ((Parser.ParserElement.SingleElement) this.targetReference) .getElement(); break; case SEPARATED: rightName = ((Parser.ParserElement.DoubleElement) this.targetReference) .getRight(); leftName = ((Parser.ParserElement.DoubleElement) this.targetReference) .getLeft(); break; case ALTERNATED: rightName = ((Parser.ParserElement.DoubleElement) this.targetReference) .getRight(); leftName = ((Parser.ParserElement.DoubleElement) this.targetReference) .getLeft(); break; default: throw new InternalException("Unhandled element type " + parserElement.getNameType()); } } else { ProductionTransformationElement transformationElement = (ProductionTransformationElement) this.targetReference; cardinality = transformationElement.getCardinality(); if (transformationElement instanceof ProductionTransformationElement.SingleElement) { rightName = ((ProductionTransformationElement) this.targetReference) .getElement(); } else { rightName = ((ProductionTransformationElement.DoubleElement) transformationElement) .getRight(); leftName = ((ProductionTransformationElement.DoubleElement) transformationElement) .getLeft(); } } if (this.targetReference instanceof Parser.ParserElement && ((Parser.ParserElement) this.targetReference) .getElementType() == Parser.ParserElement.ElementType.SEPARATED || this.targetReference instanceof ProductionTransformationElement && ((ProductionTransformationElement) this.targetReference) .getElementType() == ProductionTransformationElement.ElementType.SEPARATED) { if (leftName == null) { this.type = new Type.SimpleType.SeparatedType(rightName, cardinality); } else { this.type = new Type.SimpleType.SeparatedType(leftName, rightName, cardinality); } } else if (this.targetReference instanceof Parser.ParserElement && ((Parser.ParserElement) this.targetReference) .getElementType() == ElementType.ALTERNATED || this.targetReference instanceof ProductionTransformationElement && ((ProductionTransformationElement) this.targetReference) .getElementType() == ProductionTransformationElement.ElementType.ALTERNATED) { if (leftName == null) { this.type = new Type.SimpleType.AlternatedType(rightName, cardinality); } else { this.type = new Type.SimpleType.AlternatedType(leftName, rightName, cardinality); } } else { Bound upperBound = cardinality.getUpperBound(); if (cardinality.upperBoundIsInfinite() || !upperBound.equals(cardinality.getLowerBound())) { this.type = new Type.SimpleType.HomogeneousType(rightName, cardinality); } else { Bound newCardinality; CardinalityInterval newInterval; BigInteger upperBoundValue = upperBound.getValue(); if (upperBoundValue.mod(BigInteger.valueOf(2L)).compareTo( BigInteger.ZERO) == 0) { newCardinality = new Bound( upperBoundValue.divide(BigInteger.valueOf(2L))); newInterval = new CardinalityInterval(newCardinality, newCardinality); this.type = new Type.SimpleType.AlternatedType( rightName, newInterval); } else { if (upperBoundValue.compareTo(BigInteger.ONE) > 0) { newCardinality = new Bound(upperBoundValue.divide( BigInteger.valueOf(2L)).add(BigInteger.ONE)); } else { newCardinality = upperBound; } newInterval = new CardinalityInterval(newCardinality, newCardinality); if (leftName == null) { this.type = new Type.SimpleType.SeparatedType( rightName, newInterval); } else { this.type = new Type.SimpleType.SeparatedType( leftName, rightName, newInterval); } } } } } public boolean isTransformed() { return this.targetReference instanceof ProductionTransformationElement; } } public static class ImplicitNormalListElement extends AlternativeTransformationListElement.NormalListElement { private String element; public ImplicitNormalListElement( Parser.ParserElement reference, Grammar grammar) { super(grammar); if (reference == null) { throw new InternalException("reference may not be null"); } super.addTargetReference(reference); super.addOriginReference(reference); } @Override public void apply( IGrammarVisitor visitor) { visitor.visitAlternativeTransformationNormalListReferenceListElement(this); } @Override public String getElement() { if (getTargetReference() instanceof INameDeclaration) { this.element = ((INameDeclaration) getTargetReference()) .getName(); } else if (getTargetReference() instanceof Parser.ParserAlternative) { this.element = ((Parser.ParserAlternative) getTargetReference()) .getName(); if (this.element == null) { this.element = "{" + ((Parser.ParserAlternative) getTargetReference()) .getIndex() + "}"; } } else if (getTargetReference() instanceof Tree.TreeAlternative) { this.element = ((Tree.TreeAlternative) getTargetReference()) .getName(); if (this.element == null) { this.element = "{" + ((Tree.TreeAlternative) getTargetReference()) .getIndex() + "}"; } } else if (getTargetReference() instanceof Parser.ParserElement) { this.element = ((Parser.ParserElement) getTargetReference()) .getElement(); } else if (getTargetReference() instanceof Tree.TreeElement) { this.element = ((Tree.TreeElement) getTargetReference()) .getElement(); } this.element += "..."; return this.element; } @Override public Token getLocation() { return getTargetReference().getLocation(); } } public static class ExplicitNormalListElement extends AlternativeTransformationListElement.NormalListElement { private final AListReferenceListElement declaration; private String element; public ExplicitNormalListElement( AListReferenceListElement declaration, Grammar grammar) { super(grammar); if (declaration == null) { throw new InternalException("declaration may not be null"); } this.declaration = declaration; } public AListReferenceListElement getDeclaration() { return this.declaration; } @Override public IReferencable getTargetReference() { if (super.getTargetReference() == null) { throw new InternalException( "reference should have been initialized using addReference"); } return super.getTargetReference(); } @Override public void addTargetReference( IReferencable reference) { if (super.getTargetReference() != null) { throw new InternalException( "addReference shouldn't be used twice"); } super.addTargetReference(reference); } @Override public Parser.ParserElement getOriginReference() { if (super.getOriginReference() == null) { throw new InternalException( "reference should have been initialized using addReference"); } return super.getOriginReference(); } @Override public void addOriginReference( Parser.ParserElement reference) { if (super.getOriginReference() != null) { throw new InternalException( "addReference shouldn't be used twice"); } super.addOriginReference(reference); } @Override public void apply( IGrammarVisitor visitor) { visitor.visitAlternativeTransformationNormalListReferenceListElement(this); } @Override public String getElement() { if (this.element == null) { if (this.declaration.getElementReference() instanceof ANaturalElementReference) { ANaturalElementReference naturalRef = (ANaturalElementReference) this.declaration .getElementReference(); this.element = naturalRef.getElement().getText(); } else { ATransformedElementReference naturalRef = (ATransformedElementReference) this.declaration .getElementReference(); this.element = naturalRef.getElement().getText() + naturalRef.getDot().getText() + naturalRef.getPart().getText(); } this.element += "..."; } return this.element; } @Override public Token getLocation() { if (this.declaration.getElementReference() instanceof ANaturalElementReference) { return ((ANaturalElementReference) this.declaration .getElementReference()).getElement(); } else { return ((ATransformedElementReference) this.declaration .getElementReference()).getElement(); } } } public static abstract class LeftListElement extends AlternativeTransformationListElement { private IReferencable targetReference; private Parser.ParserElement originReference; private Type.SimpleType type; public LeftListElement( Grammar grammar) { super(grammar); } @Override public Type.SimpleType getType() { if (this.type == null) { throw new InternalException( "type shouldn't be null, use constructType()"); } return this.type; } @Override public IReferencable getTargetReference() { return this.targetReference; } public Parser.ParserElement getOriginReference() { return this.originReference; } protected void addTargetReference( IReferencable reference) { this.targetReference = reference; } protected void addOriginReference( Parser.ParserElement reference) { this.originReference = reference; } @Override public void constructType() { if (this.type != null) { throw new InternalException( "constructType shouldn't be used twice"); } if (this.targetReference == null) { throw new InternalException( "constructType shouldn't be called before reference resolution"); } Type referencedType; if (this.targetReference instanceof Parser.ParserElement) { referencedType = ((Parser.ParserElement) this.targetReference) .getType(); } else { referencedType = ((ProductionTransformationElement) this.targetReference) .getType(); } // Calculate the cardinality of the left element String elementName; CardinalityInterval intermediateInterval; if (referencedType instanceof Type.SimpleType.AlternatedType) { elementName = ((Type.SimpleType.AlternatedType) referencedType) .getLeftElementName(); intermediateInterval = ((Type.SimpleType.AlternatedType) referencedType) .getCardinality(); } else if (referencedType instanceof Type.SimpleType.SeparatedType) { elementName = ((Type.SimpleType.SeparatedType) referencedType) .getLeftElementName(); CardinalityInterval referencedInteval = ((Type.SimpleType.SeparatedType) referencedType) .getCardinality(); Bound lowerBound; Bound upperBound; if (referencedInteval.getUpperBound().equals(Bound.MAX)) { upperBound = Bound.MAX; } else { upperBound = referencedInteval.getUpperBound().subtract( BigInteger.ONE); } if (referencedInteval.getLowerBound().equals(Bound.ZERO)) { lowerBound = Bound.ZERO; } else { lowerBound = referencedInteval.getLowerBound().subtract( BigInteger.ONE); } intermediateInterval = new CardinalityInterval(lowerBound, upperBound); } else { throw new InternalException( "Type shouldn't be different than Alternated or Separated"); } // Calculate the type of the left element Bound upperBound = intermediateInterval.getUpperBound(); if (intermediateInterval.upperBoundIsInfinite() || !upperBound.equals(intermediateInterval.getLowerBound())) { this.type = new Type.SimpleType.HomogeneousType(elementName, intermediateInterval); } else { BigInteger upperBoundValue = upperBound.getValue(); Bound newCardinality; CardinalityInterval newInterval; if (upperBoundValue.mod(BigInteger.valueOf(2L)).compareTo( BigInteger.ZERO) == 0) { newCardinality = new Bound( upperBoundValue.divide(BigInteger.valueOf(2L))); newInterval = new CardinalityInterval(newCardinality, newCardinality); this.type = new Type.SimpleType.AlternatedType(elementName, newInterval); } else { if (upperBoundValue.compareTo(BigInteger.ONE) > 0) { newCardinality = new Bound(upperBoundValue.divide( BigInteger.valueOf(2L)).add(BigInteger.ONE)); } else { newCardinality = upperBound; } newInterval = new CardinalityInterval(newCardinality, newCardinality); this.type = new Type.SimpleType.AlternatedType(elementName, newInterval); } } } public boolean isTransformed() { return this.targetReference instanceof ProductionTransformationElement; } } public static class ImplicitLeftListElement extends AlternativeTransformationListElement.LeftListElement { private String element; public ImplicitLeftListElement( Parser.ParserElement reference, Grammar grammar) { super(grammar); if (reference == null) { throw new InternalException("reference may not be null"); } super.addTargetReference(reference); super.addOriginReference(reference); } @Override public void apply( IGrammarVisitor visitor) { visitor.visitAlternativeTransformationLeftListReferenceListElement(this); } @Override public String getElement() { if (getTargetReference() instanceof INameDeclaration) { this.element = ((INameDeclaration) getTargetReference()) .getName(); } else if (getTargetReference() instanceof Parser.ParserAlternative) { this.element = ((Parser.ParserAlternative) getTargetReference()) .getName(); if (this.element == null) { this.element = "{" + ((Parser.ParserAlternative) getTargetReference()) .getIndex() + "}"; } } else if (getTargetReference() instanceof Tree.TreeAlternative) { this.element = ((Tree.TreeAlternative) getTargetReference()) .getName(); if (this.element == null) { this.element = "{" + ((Tree.TreeAlternative) getTargetReference()) .getIndex() + "}"; } } else if (getTargetReference() instanceof Parser.ParserElement) { this.element = ((Parser.ParserElement) getTargetReference()) .getElement(); } else if (getTargetReference() instanceof Tree.TreeElement) { this.element = ((Tree.TreeElement) getTargetReference()) .getElement(); } this.element += ".Left..."; return this.element; } @Override public Token getLocation() { return getTargetReference().getLocation(); } } public static class ExplicitLeftListElement extends AlternativeTransformationListElement.LeftListElement { private final ALeftListReferenceListElement declaration; private String element; public ExplicitLeftListElement( ALeftListReferenceListElement declaration, Grammar grammar) { super(grammar); if (declaration == null) { throw new InternalException("declaration may not be null"); } this.declaration = declaration; } public ALeftListReferenceListElement getDeclaration() { return this.declaration; } @Override public IReferencable getTargetReference() { if (super.getTargetReference() == null) { throw new InternalException( "reference should have been initialized using addReference"); } return super.getTargetReference(); } @Override public void addTargetReference( IReferencable reference) { if (super.getTargetReference() != null) { throw new InternalException( "addReference shouldn't be used twice"); } super.addTargetReference(reference); } @Override public Parser.ParserElement getOriginReference() { if (super.getOriginReference() == null) { throw new InternalException( "reference should have been initialized using addReference"); } return super.getOriginReference(); } @Override public void addOriginReference( Parser.ParserElement reference) { if (super.getOriginReference() != null) { throw new InternalException( "addReference shouldn't be used twice"); } super.addOriginReference(reference); } @Override public void apply( IGrammarVisitor visitor) { visitor.visitAlternativeTransformationLeftListReferenceListElement(this); } @Override public String getElement() { if (this.element == null) { if (this.declaration.getElementReference() instanceof ANaturalElementReference) { ANaturalElementReference naturalRef = (ANaturalElementReference) this.declaration .getElementReference(); this.element = naturalRef.getElement().getText(); } else { ATransformedElementReference naturalRef = (ATransformedElementReference) this.declaration .getElementReference(); this.element = naturalRef.getElement().getText() + naturalRef.getDot().getText() + naturalRef.getPart().getText(); } this.element += ".Left..."; } return this.element; } @Override public Token getLocation() { if (this.declaration.getElementReference() instanceof ANaturalElementReference) { return ((ANaturalElementReference) this.declaration .getElementReference()).getElement(); } else { return ((ATransformedElementReference) this.declaration .getElementReference()).getElement(); } } } public static abstract class RightListElement extends AlternativeTransformationListElement { private IReferencable targetReference; private Parser.ParserElement originReference; private Type.SimpleType type; public RightListElement( Grammar grammar) { super(grammar); } @Override public Type.SimpleType getType() { if (this.type == null) { throw new InternalException( "type shouldn't be null, use constructType()"); } return this.type; } @Override public IReferencable getTargetReference() { return this.targetReference; } public Parser.ParserElement getOriginReference() { return this.originReference; } protected void addTargetReference( IReferencable reference) { this.targetReference = reference; } protected void addOriginReference( Parser.ParserElement reference) { this.originReference = reference; } @Override public void constructType() { if (this.type != null) { throw new InternalException( "constructType shouldn't be used twice"); } if (this.targetReference == null) { throw new InternalException( "constructType shouldn't be called before reference resolution"); } Type referencedType; if (this.targetReference instanceof Parser.ParserElement) { referencedType = ((Parser.ParserElement) this.targetReference) .getType(); } else { referencedType = ((ProductionTransformationElement) this.targetReference) .getType(); } // Calculate the cardinality of the left element String elementName; CardinalityInterval intermediateInterval; if (referencedType instanceof Type.SimpleType.AlternatedType) { elementName = ((Type.SimpleType.AlternatedType) referencedType) .getRightElementName(); intermediateInterval = ((Type.SimpleType.AlternatedType) referencedType) .getCardinality(); } else if (referencedType instanceof Type.SimpleType.SeparatedType) { elementName = ((Type.SimpleType.SeparatedType) referencedType) .getRightElementName(); intermediateInterval = ((Type.SimpleType.SeparatedType) referencedType) .getCardinality(); } else { throw new InternalException( "Type shouldn't be different than Alternated or Separated"); } // Calculate the type of the left element Bound upperBound = intermediateInterval.getUpperBound(); if (intermediateInterval.upperBoundIsInfinite() || !upperBound.equals(intermediateInterval.getLowerBound())) { this.type = new Type.SimpleType.HomogeneousType(elementName, intermediateInterval); } else { BigInteger upperBoundValue = upperBound.getValue(); Bound newCardinality; CardinalityInterval newInterval; if (upperBoundValue.mod(BigInteger.valueOf(2L)).compareTo( BigInteger.ZERO) == 0) { newCardinality = new Bound( upperBoundValue.divide(BigInteger.valueOf(2L))); newInterval = new CardinalityInterval(newCardinality, newCardinality); this.type = new Type.SimpleType.AlternatedType(elementName, newInterval); } else { if (upperBoundValue.compareTo(BigInteger.ONE) > 0) { newCardinality = new Bound(upperBoundValue.divide( BigInteger.valueOf(2L)).add(BigInteger.ONE)); } else { newCardinality = upperBound; } newInterval = new CardinalityInterval(newCardinality, newCardinality); this.type = new Type.SimpleType.SeparatedType(elementName, newInterval); } } } public boolean isTransformed() { return this.targetReference instanceof ProductionTransformationElement; } } public static class ImplicitRightListElement extends AlternativeTransformationListElement.RightListElement { private String element; public ImplicitRightListElement( Parser.ParserElement reference, Grammar grammar) { super(grammar); if (reference == null) { throw new InternalException("reference may not be null"); } super.addTargetReference(reference); super.addOriginReference(reference); } @Override public void apply( IGrammarVisitor visitor) { visitor.visitAlternativeTransformationRightListReferenceListElement(this); } @Override public String getElement() { if (getTargetReference() instanceof INameDeclaration) { this.element = ((INameDeclaration) getTargetReference()) .getName(); } else if (getTargetReference() instanceof Parser.ParserAlternative) { this.element = ((Parser.ParserAlternative) getTargetReference()) .getName(); if (this.element == null) { this.element = "{" + ((Parser.ParserAlternative) getTargetReference()) .getIndex() + "}"; } } else if (getTargetReference() instanceof Tree.TreeAlternative) { this.element = ((Tree.TreeAlternative) getTargetReference()) .getName(); if (this.element == null) { this.element = "{" + ((Tree.TreeAlternative) getTargetReference()) .getIndex() + "}"; } } else if (getTargetReference() instanceof Parser.ParserElement) { this.element = ((Parser.ParserElement) getTargetReference()) .getElement(); } else if (getTargetReference() instanceof Tree.TreeElement) { this.element = ((Tree.TreeElement) getTargetReference()) .getElement(); } this.element += ".Right..."; return this.element; } @Override public Token getLocation() { return getTargetReference().getLocation(); } } public static class ExplicitRightListElement extends AlternativeTransformationListElement.RightListElement { private final ARightListReferenceListElement declaration; private String element; public ExplicitRightListElement( ARightListReferenceListElement declaration, Grammar grammar) { super(grammar); if (declaration == null) { throw new InternalException("declaration may not be null"); } this.declaration = declaration; } public ARightListReferenceListElement getDeclaration() { return this.declaration; } @Override public IReferencable getTargetReference() { if (super.getTargetReference() == null) { throw new InternalException( "reference should have been initialized using addReference"); } return super.getTargetReference(); } @Override public void addTargetReference( IReferencable reference) { if (super.getTargetReference() != null) { throw new InternalException( "addReference shouldn't be used twice"); } super.addTargetReference(reference); } @Override public Parser.ParserElement getOriginReference() { if (super.getOriginReference() == null) { throw new InternalException( "reference should have been initialized using addReference"); } return super.getOriginReference(); } @Override public void addOriginReference( Parser.ParserElement reference) { if (super.getOriginReference() != null) { throw new InternalException( "addReference shouldn't be used twice"); } super.addOriginReference(reference); } @Override public void apply( IGrammarVisitor visitor) { visitor.visitAlternativeTransformationRightListReferenceListElement(this); } @Override public String getElement() { if (this.element == null) { if (this.declaration.getElementReference() instanceof ANaturalElementReference) { ANaturalElementReference naturalRef = (ANaturalElementReference) this.declaration .getElementReference(); this.element = naturalRef.getElement().getText(); } else { ATransformedElementReference naturalRef = (ATransformedElementReference) this.declaration .getElementReference(); this.element = naturalRef.getElement().getText() + naturalRef.getDot().getText() + naturalRef.getPart().getText(); } this.element += ".Right..."; } return this.element; } @Override public Token getLocation() { if (this.declaration.getElementReference() instanceof ANaturalElementReference) { return ((ANaturalElementReference) this.declaration .getElementReference()).getElement(); } else { return ((ATransformedElementReference) this.declaration .getElementReference()).getElement(); } } } }
SableCC/sablecc
src/org/sablecc/sablecc/core/transformation/AlternativeTransformationListElement.java
Java
apache-2.0
51,978
package net.jawr.web.test.servlet.mapping.standard; import static org.junit.Assert.assertEquals; import java.util.Collections; import java.util.List; import net.jawr.web.test.AbstractPageTest; import net.jawr.web.test.JawrTestConfigFiles; import net.jawr.web.test.utils.Utils; import org.junit.Test; import com.gargoylesoftware.htmlunit.JavaScriptPage; import com.gargoylesoftware.htmlunit.TextPage; import com.gargoylesoftware.htmlunit.html.HtmlImage; import com.gargoylesoftware.htmlunit.html.HtmlImageInput; import com.gargoylesoftware.htmlunit.html.HtmlLink; import com.gargoylesoftware.htmlunit.html.HtmlScript; /** * Test case for page using JS and CSS servlet mapping in production mode. * * @author ibrahim Chaehoi */ @JawrTestConfigFiles(webXml = "net/jawr/web/servlet/mapping/config/web-js-css-servlet-mapping.xml", jawrConfig = "net/jawr/web/servlet/mapping/config/jawr.properties") public class MainPageJsCssServletMappingTest extends AbstractPageTest { /** * Returns the page URL to test * @return the page URL to test */ protected String getPageUrl() { return getServerUrlPrefix() + getUrlPrefix()+"/index.jsp"; } @Test public void testPageLoad() throws Exception { final List<String> expectedAlerts = Collections .singletonList("A little message retrieved from the message bundle : Hello $ world!"); assertEquals(expectedAlerts, collectedAlerts); assertContentEquals("/net/jawr/web/servlet/mapping/resources/standard/index-jsp-js-css-servlet-mapping-result-expected.txt", page); } @Test public void checkGeneratedJsLinks() { // Test generated Script link final List<?> scripts = getJsScriptTags(); assertEquals(1, scripts.size()); final HtmlScript script = (HtmlScript) scripts.get(0); assertEquals( getUrlPrefix()+"/jsJawr/690372103.en_US/js/bundle/msg.js", script.getSrcAttribute()); } @Test public void testJsBundleContent() throws Exception { final List<?> scripts = getJsScriptTags(); final HtmlScript script = (HtmlScript) scripts.get(0); final JavaScriptPage page = getJavascriptPage(script); assertContentEquals("/net/jawr/web/servlet/mapping/resources/standard/msg-bundle.js", page); } @Test public void checkGeneratedCssLinks() { // Test generated Css link final List<?> styleSheets = getHtmlLinkTags(); assertEquals(1, styleSheets.size()); final HtmlLink css = (HtmlLink) styleSheets.get(0); assertEquals( getUrlPrefix()+"/cssJawr/2049149885/fwk/core/component.css", css.getHrefAttribute()); } @Test public void testCssBundleContent() throws Exception { final List<?> styleSheets = getHtmlLinkTags(); final HtmlLink css = (HtmlLink) styleSheets.get(0); final TextPage page = getCssPage(css); assertContentEquals("/net/jawr/web/servlet/mapping/resources/standard/component-js-css-servlet-mapping-expected.css", page); } @Test public void checkGeneratedHtmlImageLinks() { // Test generated HTML image link final List<?> images = getHtmlImageTags(); assertEquals(1, images.size()); final HtmlImage img = (HtmlImage) images.get(0); Utils.assertGeneratedLinkEquals(getUrlPrefix()+"/cbfc517da02d6a64a68e5fea9a5de472f1/img/appIcons/application.png", img.getSrcAttribute()); } @Test public void checkGeneratedHtmlImageInputLinks() { // Test generated HTML image link final List<?> images = getHtmlImageInputTags(); assertEquals(1, images.size()); final HtmlImageInput img = (HtmlImageInput) images.get(0); Utils.assertGeneratedLinkEquals(getUrlPrefix()+"/cb30a18063ef42b090194a7e936086960f/img/cog.png", img.getSrcAttribute()); } }
davidwebster48/jawr-main-repo
jawr/jawr-integration-test/src/test/java/net/jawr/web/test/servlet/mapping/standard/MainPageJsCssServletMappingTest.java
Java
apache-2.0
3,601
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.spi.communication.tcp; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.atomic.AtomicInteger; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteException; import org.apache.ignite.IgniteSystemProperties; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.events.Event; import org.apache.ignite.internal.IgniteEx; import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.internal.util.nio.GridCommunicationClient; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.lang.IgniteBiPredicate; import org.apache.ignite.lang.IgnitePredicate; import org.apache.ignite.lang.IgniteRunnable; import org.apache.ignite.spi.IgniteSpiException; import org.apache.ignite.spi.discovery.tcp.internal.TcpDiscoveryNode; import org.apache.ignite.testframework.GridTestUtils; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.junit.Test; import static org.apache.ignite.events.EventType.EVT_NODE_FAILED; /** * Tests grid node kicking on communication failure. */ public class TcpCommunicationSpiDropNodesTest extends GridCommonAbstractTest { /** Nodes count. */ private static final int NODES_CNT = 4; /** Block. */ private static volatile boolean block; /** Predicate. */ private static IgniteBiPredicate<ClusterNode, ClusterNode> pred; /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(gridName); cfg.setFailureDetectionTimeout(1000); TestCommunicationSpi spi = new TestCommunicationSpi(); spi.setIdleConnectionTimeout(100); spi.setSharedMemoryPort(-1); cfg.setCommunicationSpi(spi); return cfg; } /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { super.beforeTestsStarted(); System.setProperty(IgniteSystemProperties.IGNITE_ENABLE_FORCIBLE_NODE_KILL, "true"); } /** {@inheritDoc} */ @Override protected void afterTestsStopped() throws Exception { System.clearProperty(IgniteSystemProperties.IGNITE_ENABLE_FORCIBLE_NODE_KILL); } /** {@inheritDoc} */ @Override protected void beforeTest() throws Exception { super.beforeTest(); block = false; } /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { super.afterTest(); stopAllGrids(); } /** * Server node shouldn't be failed by other server node if IGNITE_ENABLE_FORCIBLE_NODE_KILL=true. * * @throws Exception If failed. */ @Test public void testOneNode() throws Exception { pred = new IgniteBiPredicate<ClusterNode, ClusterNode>() { @Override public boolean apply(ClusterNode locNode, ClusterNode rmtNode) { return block && rmtNode.order() == 3; } }; startGrids(NODES_CNT); AtomicInteger evts = new AtomicInteger(); grid(0).events().localListen(new IgnitePredicate<Event>() { @Override public boolean apply(Event evt) { evts.incrementAndGet(); return true; } }, EVT_NODE_FAILED); U.sleep(1000); // Wait for write timeout and closing idle connections. block = true; try { grid(0).compute().broadcast(new IgniteRunnable() { @Override public void run() { // No-op. } }); fail("Should have exception here."); } catch (IgniteException e) { assertTrue(e.getCause() instanceof IgniteSpiException); } block = false; assertEquals(NODES_CNT, grid(0).cluster().nodes().size()); assertEquals(0, evts.get()); } /** * Servers shouldn't fail each other if IGNITE_ENABLE_FORCIBLE_NODE_KILL=true. * @throws Exception If failed. */ @Test public void testTwoNodesEachOther() throws Exception { pred = new IgniteBiPredicate<ClusterNode, ClusterNode>() { @Override public boolean apply(ClusterNode locNode, ClusterNode rmtNode) { return block && (locNode.order() == 2 || locNode.order() == 4) && (rmtNode.order() == 2 || rmtNode.order() == 4); } }; startGrids(NODES_CNT); AtomicInteger evts = new AtomicInteger(); grid(0).events().localListen(new IgnitePredicate<Event>() { @Override public boolean apply(Event evt) { evts.incrementAndGet(); return true; } }, EVT_NODE_FAILED); U.sleep(1000); // Wait for write timeout and closing idle connections. block = true; final CyclicBarrier barrier = new CyclicBarrier(2); IgniteInternalFuture<Void> fut1 = GridTestUtils.runAsync(new Callable<Void>() { @Override public Void call() throws Exception { barrier.await(); grid(1).compute().withNoFailover().broadcast(new IgniteRunnable() { @Override public void run() { // No-op. } }); return null; } }); IgniteInternalFuture<Void> fut2 = GridTestUtils.runAsync(new Callable<Void>() { @Override public Void call() throws Exception { barrier.await(); grid(3).compute().withNoFailover().broadcast(new IgniteRunnable() { @Override public void run() { // No-op. } }); return null; } }); try { fut1.get(); fail("Should fail with SpiException"); } catch (IgniteCheckedException e) { assertTrue(e.getCause().getCause() instanceof IgniteSpiException); } try { fut2.get(); fail("Should fail with SpiException"); } catch (IgniteCheckedException e) { assertTrue(e.getCause().getCause() instanceof IgniteSpiException); } assertEquals(NODES_CNT, grid(0).cluster().nodes().size()); assertEquals(0, evts.get()); for (int j = 0; j < NODES_CNT; j++) { IgniteEx ignite; try { ignite = grid(j); log.info("Checking topology for grid(" + j + "): " + ignite.cluster().nodes()); assertEquals(NODES_CNT, ignite.cluster().nodes().size()); } catch (Exception e) { log.info("Checking topology for grid(" + j + "): no grid in topology."); } } } /** * */ private static class TestCommunicationSpi extends TcpCommunicationSpi { /** {@inheritDoc} */ @Override protected GridCommunicationClient createTcpClient(ClusterNode node, int connIdx) throws IgniteCheckedException { if (pred.apply(getLocalNode(), node)) { Map<String, Object> attrs = new HashMap<>(node.attributes()); attrs.put(createAttributeName(ATTR_ADDRS), Collections.singleton("127.0.0.1")); attrs.put(createAttributeName(ATTR_PORT), 47200); attrs.put(createAttributeName(ATTR_EXT_ADDRS), Collections.emptyList()); attrs.put(createAttributeName(ATTR_HOST_NAMES), Collections.emptyList()); ((TcpDiscoveryNode)node).setAttributes(attrs); } return super.createTcpClient(node, connIdx); } /** * @param name Name. */ private String createAttributeName(String name) { return getClass().getSimpleName() + '.' + name; } } }
NSAmelchev/ignite
modules/core/src/test/java/org/apache/ignite/spi/communication/tcp/TcpCommunicationSpiDropNodesTest.java
Java
apache-2.0
8,980
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.projectView.impl; import com.intellij.ide.DeleteProvider; import com.intellij.ide.IdeBundle; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.LibraryOrderEntry; import com.intellij.openapi.roots.ModifiableRootModel; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.OrderEntry; import com.intellij.openapi.ui.Messages; import org.jetbrains.annotations.NotNull; final class DetachLibraryDeleteProvider implements DeleteProvider { private final Project myProject; private final LibraryOrderEntry myOrderEntry; DetachLibraryDeleteProvider(@NotNull Project project, @NotNull LibraryOrderEntry orderEntry) { myProject = project; myOrderEntry = orderEntry; } @Override public boolean canDeleteElement(@NotNull DataContext dataContext) { return true; } @Override public void deleteElement(@NotNull DataContext dataContext) { final Module module = myOrderEntry.getOwnerModule(); String message = IdeBundle.message("detach.library.from.module", myOrderEntry.getPresentableName(), module.getName()); String title = IdeBundle.message("detach.library"); int ret = Messages.showOkCancelDialog(myProject, message, title, Messages.getQuestionIcon()); if (ret != Messages.OK) return; CommandProcessor.getInstance().executeCommand(module.getProject(), () -> { final Runnable action = () -> { ModuleRootManager rootManager = ModuleRootManager.getInstance(module); OrderEntry[] orderEntries = rootManager.getOrderEntries(); ModifiableRootModel model = rootManager.getModifiableModel(); OrderEntry[] modifiableEntries = model.getOrderEntries(); for (int i = 0; i < orderEntries.length; i++) { OrderEntry entry = orderEntries[i]; if (entry instanceof LibraryOrderEntry && ((LibraryOrderEntry)entry).getLibrary() == myOrderEntry.getLibrary()) { model.removeOrderEntry(modifiableEntries[i]); } } model.commit(); }; ApplicationManager.getApplication().runWriteAction(action); }, title, null); } }
siosio/intellij-community
platform/lang-impl/src/com/intellij/ide/projectView/impl/DetachLibraryDeleteProvider.java
Java
apache-2.0
2,517
/* * Copyright 2015 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.apiman.gateway.engine.impl; import io.apiman.common.datastructures.map.LRUMap; import io.apiman.gateway.engine.components.ldap.LdapConfigBean; import java.util.Map; import javax.net.ssl.SSLSocketFactory; import com.unboundid.ldap.sdk.LDAPConnection; import com.unboundid.ldap.sdk.LDAPConnectionPool; import com.unboundid.ldap.sdk.LDAPException; /** * @author Marc Savy {@literal <msavy@redhat.com>} */ public class LDAPConnectionFactory { private static final int MAX_CONNECTIONS_PER_POOL = 20; private static final int MAX_POOLS = 20; private LDAPConnectionFactory() { } protected static Map<LdapConfigBean, LDAPConnectionPool> connectionPoolCache = new LRUMap<LdapConfigBean, LDAPConnectionPool>(MAX_POOLS) { private static final long serialVersionUID = 1L; @Override protected void handleRemovedElem(Map.Entry<LdapConfigBean, LDAPConnectionPool> eldest) { eldest.getValue().close(); } }; public static LDAPConnection build(SSLSocketFactory socketFactory, LdapConfigBean config) throws LDAPException { if (isLdaps(config.getScheme()) || socketFactory == null) { return getConnection(connectionPoolCache, socketFactory, config); } else { return getConnection(connectionPoolCache, null, config); } } public static void releaseConnection(LDAPConnection connection) { if (connection != null && connection.getConnectionPool() != null) connection.getConnectionPool().releaseConnection(connection); } public static void releaseDefunct(LDAPConnection connection) { if (connection != null && connection.getConnectionPool() != null) connection.getConnectionPool().releaseDefunctConnection(connection); } public static void releaseConnectionAfterException(LDAPConnection connection, LDAPException e) { if (connection != null && connection.getConnectionPool() != null) connection.getConnectionPool().releaseConnectionAfterException(connection, e); } private static LDAPConnection getConnection(Map<LdapConfigBean, LDAPConnectionPool> map, SSLSocketFactory socketFactory, LdapConfigBean config) throws LDAPException { if (!map.containsKey(config)) { LDAPConnection template = new LDAPConnection(config.getHost(), config.getPort()); if (socketFactory != null) template.setSocketFactory(socketFactory); map.put(config, new LDAPConnectionPool(template, MAX_CONNECTIONS_PER_POOL)); } return map.get(config).getConnection(); } private static boolean isLdaps(String scheme) { return scheme.toLowerCase().startsWith("ldaps"); //$NON-NLS-1$ } }
cmoulliard/apiman
gateway/engine/core/src/main/java/io/apiman/gateway/engine/impl/LDAPConnectionFactory.java
Java
apache-2.0
3,382
/* * Copyright (C) 2015 Pedro Paulo de Amorim * * 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.github.ppamorim.dragger; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.view.LayoutInflater; import butterknife.InjectView; import com.github.ksoichiro.android.observablescrollview.ObservableRecyclerView; import com.github.ppamorim.dragger.app.R; import com.github.ppamorim.dragger.model.Home; import com.github.ppamorim.dragger.renderers.factory.Factory; import com.github.ppamorim.recyclerrenderers.adapter.RendererAdapter; import com.github.ppamorim.recyclerrenderers.builder.RendererBuilder; import com.github.ppamorim.recyclerrenderers.interfaces.Renderable; import java.util.ArrayList; public class BaseActivity extends AbstractToolbarActivity { @InjectView(R.id.recycler_view) ObservableRecyclerView observableRecyclerView; @Override protected String getToolbarTitle() { return getResources().getString(R.string.app_name); } @Override protected int getContentViewId() { return R.layout.activity_base; } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); String[] items = getResources().getStringArray(R.array.home); ArrayList<Renderable> renderables = new ArrayList<>(items.length); for (String text : items) { renderables.add(new Home(text)); } observableRecyclerView.setHasFixedSize(true); observableRecyclerView.setItemAnimator(new DefaultItemAnimator()); GridLayoutManager layoutManager = new GridLayoutManager(this, 2); layoutManager.setOrientation(LinearLayoutManager.VERTICAL); observableRecyclerView.setLayoutManager(layoutManager); observableRecyclerView.setAdapter( new RendererAdapter(renderables, new RendererBuilder(new Factory()), LayoutInflater.from(this))); } public void onItemClick(int position) { switch (position) { case 0: startDraggerActivity(DraggerPosition.LEFT); break; case 1: startDraggerActivity(DraggerPosition.RIGHT); break; case 2: startDraggerActivity(DraggerPosition.TOP); break; case 3: startDraggerActivity(DraggerPosition.BOTTOM); break; case 4: startActivityNoAnimation(new Intent(this, PanelActivity.class)); break; case 5: startActivityNoAnimation(new Intent(this, DraggingActivity.class)); break; case 6: startActivityNoAnimation(new Intent(this, EditTextActivity.class)); break; case 7: startActivityNoAnimation(new Intent(this, ActivityListActivity.class)); break; case 8: startActivityNoAnimation(new Intent(this, LazyActivity.class)); break; default: break; } } private void startDraggerActivity(DraggerPosition dragPosition) { Intent intent = new Intent(this, ImageActivity.class); intent.putExtra(ImageActivity.DRAG_POSITION, dragPosition); startActivityNoAnimation(intent); } private void startActivityNoAnimation(Intent intent) { intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); startActivity(intent); } }
RyanTech/Dragger
app/src/main/java/com/github/ppamorim/dragger/BaseActivity.java
Java
apache-2.0
3,874
/** * 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.mahout.clustering.lda.cvb; import com.google.common.collect.Lists; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.mahout.common.Pair; import org.apache.mahout.common.RandomUtils; import org.apache.mahout.common.iterator.sequencefile.SequenceFileIterable; import org.apache.mahout.math.DenseMatrix; import org.apache.mahout.math.DenseVector; import org.apache.mahout.math.DistributedRowMatrixWriter; import org.apache.mahout.math.Matrix; import org.apache.mahout.math.MatrixSlice; import org.apache.mahout.math.SequentialAccessSparseVector; import org.apache.mahout.math.Vector; import org.apache.mahout.math.VectorWritable; import org.apache.mahout.math.function.Functions; import org.apache.mahout.math.stats.Sampler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * Thin wrapper around a {@link Matrix} of counts of occurrences of (topic, term) pairs. Dividing * {code topicTermCount.viewRow(topic).get(term)} by the sum over the values for all terms in that * row yields p(term | topic). Instead dividing it by all topic columns for that term yields * p(topic | term). * * Multithreading is enabled for the {@code update(Matrix)} method: this method is async, and * merely submits the matrix to a work queue. When all work has been submitted, * {@code awaitTermination()} should be called, which will block until updates have been * accumulated. */ public class TopicModel implements Configurable, Iterable<MatrixSlice> { private static final Logger log = LoggerFactory.getLogger(TopicModel.class); private final String[] dictionary; private final Matrix topicTermCounts; private final Vector topicSums; private final int numTopics; private final int numTerms; private final double eta; private final double alpha; private Configuration conf; private final Sampler sampler; private final int numThreads; private Updater[] updaters; public int getNumTerms() { return numTerms; } public int getNumTopics() { return numTopics; } public TopicModel(int numTopics, int numTerms, double eta, double alpha, String[] dictionary, double modelWeight) { this(numTopics, numTerms, eta, alpha, null, dictionary, 1, modelWeight); } public TopicModel(Configuration conf, double eta, double alpha, String[] dictionary, int numThreads, double modelWeight, Path... modelpath) throws IOException { this(loadModel(conf, modelpath), eta, alpha, dictionary, numThreads, modelWeight); } public TopicModel(int numTopics, int numTerms, double eta, double alpha, String[] dictionary, int numThreads, double modelWeight) { this(new DenseMatrix(numTopics, numTerms), new DenseVector(numTopics), eta, alpha, dictionary, numThreads, modelWeight); } public TopicModel(int numTopics, int numTerms, double eta, double alpha, Random random, String[] dictionary, int numThreads, double modelWeight) { this(randomMatrix(numTopics, numTerms, random), eta, alpha, dictionary, numThreads, modelWeight); } private TopicModel(Pair<Matrix, Vector> model, double eta, double alpha, String[] dict, int numThreads, double modelWeight) { this(model.getFirst(), model.getSecond(), eta, alpha, dict, numThreads, modelWeight); } public TopicModel(Matrix topicTermCounts, Vector topicSums, double eta, double alpha, String[] dictionary, double modelWeight) { this(topicTermCounts, topicSums, eta, alpha, dictionary, 1, modelWeight); } public TopicModel(Matrix topicTermCounts, double eta, double alpha, String[] dictionary, int numThreads, double modelWeight) { this(topicTermCounts, viewRowSums(topicTermCounts), eta, alpha, dictionary, numThreads, modelWeight); } public TopicModel(Matrix topicTermCounts, Vector topicSums, double eta, double alpha, String[] dictionary, int numThreads, double modelWeight) { this.dictionary = dictionary; this.topicTermCounts = topicTermCounts; this.topicSums = topicSums; this.numTopics = topicSums.size(); this.numTerms = topicTermCounts.numCols(); this.eta = eta; this.alpha = alpha; this.sampler = new Sampler(RandomUtils.getRandom()); this.numThreads = numThreads; if (modelWeight != 1) { topicSums.assign(Functions.mult(modelWeight)); for (int x = 0; x < numTopics; x++) { topicTermCounts.viewRow(x).assign(Functions.mult(modelWeight)); } } initializeThreadPool(); } private static Vector viewRowSums(Matrix m) { Vector v = new DenseVector(m.numRows()); for (MatrixSlice slice : m) { v.set(slice.index(), slice.vector().norm(1)); } return v; } private void initializeThreadPool() { ThreadPoolExecutor threadPool = new ThreadPoolExecutor(numThreads, numThreads, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(numThreads * 10)); threadPool.allowCoreThreadTimeOut(false); updaters = new Updater[numThreads]; for (int i = 0; i < numThreads; i++) { updaters[i] = new Updater(); threadPool.submit(updaters[i]); } } Matrix topicTermCounts() { return topicTermCounts; } @Override public Iterator<MatrixSlice> iterator() { return topicTermCounts.iterateAll(); } public Vector topicSums() { return topicSums; } private static Pair<Matrix,Vector> randomMatrix(int numTopics, int numTerms, Random random) { Matrix topicTermCounts = new DenseMatrix(numTopics, numTerms); Vector topicSums = new DenseVector(numTopics); if (random != null) { for (int x = 0; x < numTopics; x++) { for (int term = 0; term < numTerms; term++) { topicTermCounts.viewRow(x).set(term, random.nextDouble()); } } } for (int x = 0; x < numTopics; x++) { topicSums.set(x, random == null ? 1.0 : topicTermCounts.viewRow(x).norm(1)); } return Pair.of(topicTermCounts, topicSums); } public static Pair<Matrix, Vector> loadModel(Configuration conf, Path... modelPaths) throws IOException { int numTopics = -1; int numTerms = -1; List<Pair<Integer, Vector>> rows = Lists.newArrayList(); for (Path modelPath : modelPaths) { for (Pair<IntWritable, VectorWritable> row : new SequenceFileIterable<IntWritable, VectorWritable>(modelPath, true, conf)) { rows.add(Pair.of(row.getFirst().get(), row.getSecond().get())); numTopics = Math.max(numTopics, row.getFirst().get()); if (numTerms < 0) { numTerms = row.getSecond().get().size(); } } } if (rows.isEmpty()) { throw new IOException(Arrays.toString(modelPaths) + " have no vectors in it"); } numTopics++; Matrix model = new DenseMatrix(numTopics, numTerms); Vector topicSums = new DenseVector(numTopics); for (Pair<Integer, Vector> pair : rows) { model.viewRow(pair.getFirst()).assign(pair.getSecond()); topicSums.set(pair.getFirst(), pair.getSecond().norm(1)); } return Pair.of(model, topicSums); } // NOTE: this is purely for debug purposes. It is not performant to "toString()" a real model @Override public String toString() { StringBuilder buf = new StringBuilder(); for (int x = 0; x < numTopics; x++) { String v = dictionary != null ? vectorToSortedString(topicTermCounts.viewRow(x).normalize(1), dictionary) : topicTermCounts.viewRow(x).asFormatString(); buf.append(v).append('\n'); } return buf.toString(); } public int sampleTerm(Vector topicDistribution) { return sampler.sample(topicTermCounts.viewRow(sampler.sample(topicDistribution))); } public int sampleTerm(int topic) { return sampler.sample(topicTermCounts.viewRow(topic)); } public void reset() { for (int x = 0; x < numTopics; x++) { topicTermCounts.assignRow(x, new SequentialAccessSparseVector(numTerms)); } topicSums.assign(1.0); initializeThreadPool(); } public void awaitTermination() { for (Updater updater : updaters) { updater.shutdown(); } } public void renormalize() { for (int x = 0; x < numTopics; x++) { topicTermCounts.assignRow(x, topicTermCounts.viewRow(x).normalize(1)); topicSums.assign(1.0); } } public void trainDocTopicModel(Vector original, Vector topics, Matrix docTopicModel) { // first calculate p(topic|term,document) for all terms in original, and all topics, // using p(term|topic) and p(topic|doc) pTopicGivenTerm(original, topics, docTopicModel); normalizeByTopic(docTopicModel); // now multiply, term-by-term, by the document, to get the weighted distribution of // term-topic pairs from this document. Iterator<Vector.Element> it = original.iterateNonZero(); while (it.hasNext()) { Vector.Element e = it.next(); for (int x = 0; x < numTopics; x++) { Vector docTopicModelRow = docTopicModel.viewRow(x); docTopicModelRow.setQuick(e.index(), docTopicModelRow.getQuick(e.index()) * e.get()); } } // now recalculate p(topic|doc) by summing contributions from all of pTopicGivenTerm topics.assign(0.0); for (int x = 0; x < numTopics; x++) { topics.set(x, docTopicModel.viewRow(x).norm(1)); } // now renormalize so that sum_x(p(x|doc)) = 1 topics.assign(Functions.mult(1/topics.norm(1))); } public Vector infer(Vector original, Vector docTopics) { Vector pTerm = original.like(); Iterator<Vector.Element> it = original.iterateNonZero(); while (it.hasNext()) { Vector.Element e = it.next(); int term = e.index(); // p(a) = sum_x (p(a|x) * p(x|i)) double pA = 0; for (int x = 0; x < numTopics; x++) { pA += (topicTermCounts.viewRow(x).get(term) / topicSums.get(x)) * docTopics.get(x); } pTerm.set(term, pA); } return pTerm; } public void update(Matrix docTopicCounts) { for (int x = 0; x < numTopics; x++) { updaters[x % updaters.length].update(x, docTopicCounts.viewRow(x)); } } public void updateTopic(int topic, Vector docTopicCounts) { topicTermCounts.viewRow(topic).assign(docTopicCounts, Functions.PLUS); topicSums.set(topic, topicSums.get(topic) + docTopicCounts.norm(1)); } public void update(int termId, Vector topicCounts) { for (int x = 0; x < numTopics; x++) { Vector v = topicTermCounts.viewRow(x); v.set(termId, v.get(termId) + topicCounts.get(x)); } topicSums.assign(topicCounts, Functions.PLUS); } public void persist(Path outputDir, boolean overwrite) throws IOException { FileSystem fs = outputDir.getFileSystem(conf); if (overwrite) { fs.delete(outputDir, true); // CHECK second arg } DistributedRowMatrixWriter.write(outputDir, conf, topicTermCounts); } /** * Computes {@code p(topic x|term a, document i)} distributions given input document {@code i}. * {@code pTGT[x][a]} is the (un-normalized) {@code p(x|a,i)}, or if docTopics is {@code null}, * {@code p(a|x)} (also un-normalized). * * @param document doc-term vector encoding {@code w(term a|document i)}. * @param docTopics {@code docTopics[x]} is the overall weight of topic {@code x} in given * document. If {@code null}, a topic weight of {@code 1.0} is used for all topics. * @param termTopicDist storage for output {@code p(x|a,i)} distributions. */ private void pTopicGivenTerm(Vector document, Vector docTopics, Matrix termTopicDist) { // for each topic x for (int x = 0; x < numTopics; x++) { // get p(topic x | document i), or 1.0 if docTopics is null double topicWeight = docTopics == null ? 1.0 : docTopics.get(x); // get w(term a | topic x) Vector topicTermRow = topicTermCounts.viewRow(x); // get \sum_a w(term a | topic x) double topicSum = topicSums.get(x); // get p(topic x | term a) distribution to update Vector termTopicRow = termTopicDist.viewRow(x); // for each term a in document i with non-zero weight Iterator<Vector.Element> it = document.iterateNonZero(); while (it.hasNext()) { Vector.Element e = it.next(); int termIndex = e.index(); // calc un-normalized p(topic x | term a, document i) double termTopicLikelihood = (topicTermRow.get(termIndex) + eta) * (topicWeight + alpha) / (topicSum + eta * numTerms); termTopicRow.set(termIndex, termTopicLikelihood); } } } /** * sum_x sum_a (c_ai * log(p(x|i) * p(a|x))) */ public double perplexity(Vector document, Vector docTopics) { double perplexity = 0; double norm = docTopics.norm(1) + (docTopics.size() * alpha); Iterator<Vector.Element> it = document.iterateNonZero(); while (it.hasNext()) { Vector.Element e = it.next(); int term = e.index(); double prob = 0; for (int x = 0; x < numTopics; x++) { double d = (docTopics.get(x) + alpha) / norm; double p = d * (topicTermCounts.viewRow(x).get(term) + eta) / (topicSums.get(x) + eta * numTerms); prob += p; } perplexity += e.get() * Math.log(prob); } return -perplexity; } private void normalizeByTopic(Matrix perTopicSparseDistributions) { Iterator<Vector.Element> it = perTopicSparseDistributions.viewRow(0).iterateNonZero(); // then make sure that each of these is properly normalized by topic: sum_x(p(x|t,d)) = 1 while (it.hasNext()) { Vector.Element e = it.next(); int a = e.index(); double sum = 0; for (int x = 0; x < numTopics; x++) { sum += perTopicSparseDistributions.viewRow(x).get(a); } for (int x = 0; x < numTopics; x++) { perTopicSparseDistributions.viewRow(x).set(a, perTopicSparseDistributions.viewRow(x).get(a) / sum); } } } public static String vectorToSortedString(Vector vector, String[] dictionary) { List<Pair<String,Double>> vectorValues = new ArrayList<Pair<String, Double>>(vector.getNumNondefaultElements()); Iterator<Vector.Element> it = vector.iterateNonZero(); while (it.hasNext()) { Vector.Element e = it.next(); vectorValues.add(Pair.of(dictionary != null ? dictionary[e.index()] : String.valueOf(e.index()), e.get())); } Collections.sort(vectorValues, new Comparator<Pair<String, Double>>() { @Override public int compare(Pair<String, Double> x, Pair<String, Double> y) { return y.getSecond().compareTo(x.getSecond()); } }); Iterator<Pair<String,Double>> listIt = vectorValues.iterator(); StringBuilder bldr = new StringBuilder(2048); bldr.append('{'); int i = 0; while (listIt.hasNext() && i < 25) { i++; Pair<String,Double> p = listIt.next(); bldr.append(p.getFirst()); bldr.append(':'); bldr.append(p.getSecond()); bldr.append(','); } if (bldr.length() > 1) { bldr.setCharAt(bldr.length() - 1, '}'); } return bldr.toString(); } @Override public void setConf(Configuration configuration) { this.conf = configuration; } @Override public Configuration getConf() { return conf; } private final class Updater implements Runnable { private final ArrayBlockingQueue<Pair<Integer, Vector>> queue = new ArrayBlockingQueue<Pair<Integer, Vector>>(100); private boolean shutdown = false; private boolean shutdownComplete = false; public void shutdown() { try { synchronized (this) { while (!shutdownComplete) { shutdown = true; wait(10000L); // Arbitrarily, wait 10 seconds rather than forever for this } } } catch (InterruptedException e) { log.warn("Interrupted waiting to shutdown() : ", e); } } public boolean update(int topic, Vector v) { if (shutdown) { // maybe don't do this? throw new IllegalStateException("In SHUTDOWN state: cannot submit tasks"); } while (true) { // keep trying if interrupted try { // start async operation by submitting to the queue queue.put(Pair.of(topic, v)); // return once you got access to the queue return true; } catch (InterruptedException e) { log.warn("Interrupted trying to queue update:", e); } } } @Override public void run() { while (!shutdown) { try { Pair<Integer, Vector> pair = queue.poll(1, TimeUnit.SECONDS); if (pair != null) { updateTopic(pair.getFirst(), pair.getSecond()); } } catch (InterruptedException e) { log.warn("Interrupted waiting to poll for update", e); } } // in shutdown mode, finish remaining tasks! for (Pair<Integer, Vector> pair : queue) { updateTopic(pair.getFirst(), pair.getSecond()); } synchronized (this) { shutdownComplete = true; notifyAll(); } } } }
BigData-Lab-Frankfurt/HiBench-DSE
common/mahout-distribution-0.7-hadoop1/core/src/main/java/org/apache/mahout/clustering/lda/cvb/TopicModel.java
Java
apache-2.0
18,433
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.replication; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.Abortable; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.exceptions.DeserializationException; import org.apache.hadoop.hbase.protobuf.ProtobufUtil; import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.zookeeper.ZKUtil; import org.apache.hadoop.hbase.zookeeper.ZooKeeperNodeTracker; import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.KeeperException.NodeExistsException; import com.google.protobuf.InvalidProtocolBufferException; /** * This class acts as a wrapper for all the objects used to identify and * communicate with remote peers and is responsible for answering to expired * sessions and re-establishing the ZK connections. */ @InterfaceAudience.Private public class ReplicationPeer implements Abortable, Closeable { private static final Log LOG = LogFactory.getLog(ReplicationPeer.class); private final String clusterKey; private final String id; private List<ServerName> regionServers = new ArrayList<ServerName>(0); private final AtomicBoolean peerEnabled = new AtomicBoolean(); private volatile Map<String, List<String>> tableCFs = new HashMap<String, List<String>>(); // Cannot be final since a new object needs to be recreated when session fails private ZooKeeperWatcher zkw; private final Configuration conf; private long lastRegionserverUpdate; private PeerStateTracker peerStateTracker; private TableCFsTracker tableCFsTracker; /** * Constructor that takes all the objects required to communicate with the * specified peer, except for the region server addresses. * @param conf configuration object to this peer * @param key cluster key used to locate the peer * @param id string representation of this peer's identifier */ public ReplicationPeer(Configuration conf, String key, String id) throws ReplicationException { this.conf = conf; this.clusterKey = key; this.id = id; try { this.reloadZkWatcher(); } catch (IOException e) { throw new ReplicationException("Error connecting to peer cluster with peerId=" + id, e); } } /** * start a state tracker to check whether this peer is enabled or not * * @param zookeeper zk watcher for the local cluster * @param peerStateNode path to zk node which stores peer state * @throws KeeperException */ public void startStateTracker(ZooKeeperWatcher zookeeper, String peerStateNode) throws KeeperException { ensurePeerEnabled(zookeeper, peerStateNode); this.peerStateTracker = new PeerStateTracker(peerStateNode, zookeeper, this); this.peerStateTracker.start(); try { this.readPeerStateZnode(); } catch (DeserializationException e) { throw ZKUtil.convert(e); } } private void readPeerStateZnode() throws DeserializationException { this.peerEnabled.set(isStateEnabled(this.peerStateTracker.getData(false))); } /** * start a table-cfs tracker to listen the (table, cf-list) map change * * @param zookeeper zk watcher for the local cluster * @param tableCFsNode path to zk node which stores table-cfs * @throws KeeperException */ public void startTableCFsTracker(ZooKeeperWatcher zookeeper, String tableCFsNode) throws KeeperException { this.tableCFsTracker = new TableCFsTracker(tableCFsNode, zookeeper, this); this.tableCFsTracker.start(); this.readTableCFsZnode(); } static Map<String, List<String>> parseTableCFsFromConfig(String tableCFsConfig) { if (tableCFsConfig == null || tableCFsConfig.trim().length() == 0) { return null; } Map<String, List<String>> tableCFsMap = null; // parse out (table, cf-list) pairs from tableCFsConfig // format: "table1:cf1,cf2;table2:cfA,cfB" String[] tables = tableCFsConfig.split(";"); for (String tab : tables) { // 1 ignore empty table config tab = tab.trim(); if (tab.length() == 0) { continue; } // 2 split to "table" and "cf1,cf2" // for each table: "table:cf1,cf2" or "table" String[] pair = tab.split(":"); String tabName = pair[0].trim(); if (pair.length > 2 || tabName.length() == 0) { LOG.error("ignore invalid tableCFs setting: " + tab); continue; } // 3 parse "cf1,cf2" part to List<cf> List<String> cfs = null; if (pair.length == 2) { String[] cfsList = pair[1].split(","); for (String cf : cfsList) { String cfName = cf.trim(); if (cfName.length() > 0) { if (cfs == null) { cfs = new ArrayList<String>(); } cfs.add(cfName); } } } // 4 put <table, List<cf>> to map if (tableCFsMap == null) { tableCFsMap = new HashMap<String, List<String>>(); } tableCFsMap.put(tabName, cfs); } return tableCFsMap; } private void readTableCFsZnode() { String currentTableCFs = Bytes.toString(tableCFsTracker.getData(false)); this.tableCFs = parseTableCFsFromConfig(currentTableCFs); } /** * Get the cluster key of that peer * @return string consisting of zk ensemble addresses, client port * and root znode */ public String getClusterKey() { return clusterKey; } /** * Get the state of this peer * @return atomic boolean that holds the status */ public AtomicBoolean getPeerEnabled() { return peerEnabled; } /** * Get replicable (table, cf-list) map of this peer * @return the replicable (table, cf-list) map */ public Map<String, List<String>> getTableCFs() { return this.tableCFs; } /** * Get a list of all the addresses of all the region servers * for this peer cluster * @return list of addresses */ public List<ServerName> getRegionServers() { return regionServers; } /** * Set the list of region servers for that peer * @param regionServers list of addresses for the region servers */ public void setRegionServers(List<ServerName> regionServers) { this.regionServers = regionServers; lastRegionserverUpdate = System.currentTimeMillis(); } /** * Get the ZK connection to this peer * @return zk connection */ public ZooKeeperWatcher getZkw() { return zkw; } /** * Get the timestamp at which the last change occurred to the list of region servers to replicate * to. * @return The System.currentTimeMillis at the last time the list of peer region servers changed. */ public long getLastRegionserverUpdate() { return lastRegionserverUpdate; } /** * Get the identifier of this peer * @return string representation of the id (short) */ public String getId() { return id; } /** * Get the configuration object required to communicate with this peer * @return configuration object */ public Configuration getConfiguration() { return conf; } @Override public void abort(String why, Throwable e) { LOG.fatal("The ReplicationPeer coresponding to peer " + clusterKey + " was aborted for the following reason(s):" + why, e); } /** * Closes the current ZKW (if not null) and creates a new one * @throws IOException If anything goes wrong connecting */ public void reloadZkWatcher() throws IOException { if (zkw != null) zkw.close(); zkw = new ZooKeeperWatcher(conf, "connection to cluster: " + id, this); } @Override public boolean isAborted() { // Currently the replication peer is never "Aborted", we just log when the // abort method is called. return false; } @Override public void close() throws IOException { if (zkw != null){ zkw.close(); } } /** * Parse the raw data from ZK to get a peer's state * @param bytes raw ZK data * @return True if the passed in <code>bytes</code> are those of a pb serialized ENABLED state. * @throws DeserializationException */ public static boolean isStateEnabled(final byte[] bytes) throws DeserializationException { ZooKeeperProtos.ReplicationState.State state = parseStateFrom(bytes); return ZooKeeperProtos.ReplicationState.State.ENABLED == state; } /** * @param bytes Content of a state znode. * @return State parsed from the passed bytes. * @throws DeserializationException */ private static ZooKeeperProtos.ReplicationState.State parseStateFrom(final byte[] bytes) throws DeserializationException { ProtobufUtil.expectPBMagicPrefix(bytes); int pblen = ProtobufUtil.lengthOfPBMagic(); ZooKeeperProtos.ReplicationState.Builder builder = ZooKeeperProtos.ReplicationState.newBuilder(); ZooKeeperProtos.ReplicationState state; try { state = builder.mergeFrom(bytes, pblen, bytes.length - pblen).build(); return state.getState(); } catch (InvalidProtocolBufferException e) { throw new DeserializationException(e); } } /** * Utility method to ensure an ENABLED znode is in place; if not present, we create it. * @param zookeeper * @param path Path to znode to check * @return True if we created the znode. * @throws NodeExistsException * @throws KeeperException */ private static boolean ensurePeerEnabled(final ZooKeeperWatcher zookeeper, final String path) throws NodeExistsException, KeeperException { if (ZKUtil.checkExists(zookeeper, path) == -1) { // There is a race b/w PeerWatcher and ReplicationZookeeper#add method to create the // peer-state znode. This happens while adding a peer. // The peer state data is set as "ENABLED" by default. ZKUtil.createNodeIfNotExistsAndWatch(zookeeper, path, ReplicationStateZKBase.ENABLED_ZNODE_BYTES); return true; } return false; } /** * Tracker for state of this peer */ public class PeerStateTracker extends ZooKeeperNodeTracker { public PeerStateTracker(String peerStateZNode, ZooKeeperWatcher watcher, Abortable abortable) { super(watcher, peerStateZNode, abortable); } @Override public synchronized void nodeDataChanged(String path) { if (path.equals(node)) { super.nodeDataChanged(path); try { readPeerStateZnode(); } catch (DeserializationException e) { LOG.warn("Failed deserializing the content of " + path, e); } } } } /** * Tracker for (table, cf-list) map of this peer */ public class TableCFsTracker extends ZooKeeperNodeTracker { public TableCFsTracker(String tableCFsZNode, ZooKeeperWatcher watcher, Abortable abortable) { super(watcher, tableCFsZNode, abortable); } @Override public synchronized void nodeDataChanged(String path) { if (path.equals(node)) { super.nodeDataChanged(path); readTableCFsZnode(); } } } }
throughsky/lywebank
hbase-client/src/main/java/org/apache/hadoop/hbase/replication/ReplicationPeer.java
Java
apache-2.0
12,268
package com.koushikdutta.async.parser; import com.koushikdutta.async.ByteBufferList; import com.koushikdutta.async.DataEmitter; import com.koushikdutta.async.DataSink; import com.koushikdutta.async.callback.CompletedCallback; import com.koushikdutta.async.future.Future; import com.koushikdutta.async.future.TransformFuture; import com.koushikdutta.async.http.body.DocumentBody; import com.koushikdutta.async.stream.ByteBufferListInputStream; import org.w3c.dom.Document; import java.lang.reflect.Type; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; /** * Created by koush on 8/3/13. */ public class DocumentParser implements AsyncParser<Document> { @Override public Future<Document> parse(DataEmitter emitter) { return new ByteBufferListParser().parse(emitter) .then(new TransformFuture<Document, ByteBufferList>() { @Override protected void transform(ByteBufferList result) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); setComplete(db.parse(new ByteBufferListInputStream(result))); } }); } @Override public void write(DataSink sink, Document value, CompletedCallback completed) { new DocumentBody(value).write(null, sink, completed); } @Override public Type getType() { return Document.class; } }
adri14590/darkCamera
src/AndroidAsync/src/com/koushikdutta/async/parser/DocumentParser.java
Java
apache-2.0
1,499
/* ListPreference to store/load integer values Copyright 2013 Thincast Technologies GmbH, Author: Martin Fleisz 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/. */ package com.freerdp.freerdpcore.utils; import android.content.Context; import android.preference.ListPreference; import android.util.AttributeSet; public class IntListPreference extends ListPreference { public IntListPreference(Context context) { super(context); } public IntListPreference(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected String getPersistedString(String defaultReturnValue) { return String.valueOf(getPersistedInt(-1)); } @Override protected boolean persistString(String value) { return persistInt(Integer.parseInt(value)); } }
akallabeth/FreeRDP
client/Android/Studio/freeRDPCore/src/main/java/com/freerdp/freerdpcore/utils/IntListPreference.java
Java
apache-2.0
933
package org.apereo.cas.config; import org.apereo.cas.configuration.CasConfigurationProperties; import org.apereo.cas.configuration.model.support.saml.sps.AbstractSamlSPProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Configuration; /** * This is {@link CasSamlSPSunshineStateEdResearchAllianceConfiguration}. * * @author Misagh Moayyed * @since 5.2.0 */ @Configuration("casSamlSPSunshineStateEdResearchAllianceConfiguration") @EnableConfigurationProperties(CasConfigurationProperties.class) public class CasSamlSPSunshineStateEdResearchAllianceConfiguration extends BaseCasSamlSPConfiguration { @Override protected AbstractSamlSPProperties getServiceProvider() { return casProperties.getSamlSp().getSserca(); } }
robertoschwald/cas
support/cas-server-support-saml-sp-integrations/src/main/java/org/apereo/cas/config/CasSamlSPSunshineStateEdResearchAllianceConfiguration.java
Java
apache-2.0
833
// Generated by xsd compiler for android/java // DO NOT CHANGE! package com.ebay.trading.api; import java.io.Serializable; import com.leansoft.nano.annotation.*; /** * * Contains the Store preferences retrieved for a user. * */ @RootElement(name = "GetStorePreferencesResponse", namespace = "urn:ebay:apis:eBLBaseComponents") public class GetStorePreferencesResponseType extends AbstractResponseType implements Serializable { private static final long serialVersionUID = -1L; @Element(name = "StorePreferences") @Order(value=0) public StorePreferencesType storePreferences; }
bulldog2011/nano
sample/webservice/eBayDemoApp/src/com/ebay/trading/api/GetStorePreferencesResponseType.java
Java
apache-2.0
600
/* * Copyright 1999-2011 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.durid.sql.ast; public interface SQLStatement extends SQLObject { }
treejames/elasticsearch-sql
src/main/java/org/durid/sql/ast/SQLStatement.java
Java
apache-2.0
717
/* * Copyright 2015 Netflix, 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.netflix.discovery.shared.transport.decorator; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.atomic.AtomicReference; import com.netflix.discovery.shared.resolver.ClusterResolver; import com.netflix.discovery.shared.resolver.EurekaEndpoint; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.EurekaHttpClientFactory; import com.netflix.discovery.shared.transport.EurekaHttpResponse; import com.netflix.discovery.shared.transport.EurekaTransportConfig; import com.netflix.discovery.shared.transport.TransportClientFactory; import com.netflix.discovery.shared.transport.TransportException; import com.netflix.discovery.shared.transport.TransportUtils; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.annotations.Monitor; import com.netflix.servo.monitor.Monitors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.netflix.discovery.EurekaClientNames.METRIC_TRANSPORT_PREFIX; /** * {@link RetryableEurekaHttpClient} retries failed requests on subsequent servers in the cluster. * It maintains also simple quarantine list, so operations are not retried again on servers * that are not reachable at the moment. * <h3>Quarantine</h3> * All the servers to which communication failed are put on the quarantine list. First successful execution * clears this list, which makes those server eligible for serving future requests. * The list is also cleared once all available servers are exhausted. * <h3>5xx</h3> * If 5xx status code is returned, {@link ServerStatusEvaluator} predicate evaluates if the retries should be * retried on another server, or the response with this status code returned to the client. * * @author Tomasz Bak * @author Li gang */ public class RetryableEurekaHttpClient extends EurekaHttpClientDecorator { private static final Logger logger = LoggerFactory.getLogger(RetryableEurekaHttpClient.class); public static final int DEFAULT_NUMBER_OF_RETRIES = 3; private final String name; private final EurekaTransportConfig transportConfig; private final ClusterResolver clusterResolver; private final TransportClientFactory clientFactory; private final ServerStatusEvaluator serverStatusEvaluator; private final int numberOfRetries; private final AtomicReference<EurekaHttpClient> delegate = new AtomicReference<>(); private final Set<EurekaEndpoint> quarantineSet = new ConcurrentSkipListSet<>(); public RetryableEurekaHttpClient(String name, EurekaTransportConfig transportConfig, ClusterResolver clusterResolver, TransportClientFactory clientFactory, ServerStatusEvaluator serverStatusEvaluator, int numberOfRetries) { this.name = name; this.transportConfig = transportConfig; this.clusterResolver = clusterResolver; this.clientFactory = clientFactory; this.serverStatusEvaluator = serverStatusEvaluator; this.numberOfRetries = numberOfRetries; Monitors.registerObject(name, this); } @Override public void shutdown() { TransportUtils.shutdown(delegate.get()); if(Monitors.isObjectRegistered(name, this)) { Monitors.unregisterObject(name, this); } } @Override protected <R> EurekaHttpResponse<R> execute(RequestExecutor<R> requestExecutor) { List<EurekaEndpoint> candidateHosts = null; int endpointIdx = 0; for (int retry = 0; retry < numberOfRetries; retry++) { EurekaHttpClient currentHttpClient = delegate.get(); EurekaEndpoint currentEndpoint = null; if (currentHttpClient == null) { if (candidateHosts == null) { candidateHosts = getHostCandidates(); if (candidateHosts.isEmpty()) { throw new TransportException("There is no known eureka server; cluster server list is empty"); } } if (endpointIdx >= candidateHosts.size()) { throw new TransportException("Cannot execute request on any known server"); } currentEndpoint = candidateHosts.get(endpointIdx++); currentHttpClient = clientFactory.newClient(currentEndpoint); } try { EurekaHttpResponse<R> response = requestExecutor.execute(currentHttpClient); if (serverStatusEvaluator.accept(response.getStatusCode(), requestExecutor.getRequestType())) { delegate.set(currentHttpClient); if (retry > 0) { logger.info("Request execution succeeded on retry #{}", retry); } return response; } logger.warn("Request execution failure with status code {}; retrying on another server if available", response.getStatusCode()); } catch (Exception e) { logger.warn("Request execution failed with message: {}", e.getMessage()); // just log message as the underlying client should log the stacktrace } // Connection error or 5xx from the server that must be retried on another server delegate.compareAndSet(currentHttpClient, null); if (currentEndpoint != null) { quarantineSet.add(currentEndpoint); } } throw new TransportException("Retry limit reached; giving up on completing the request"); } public static EurekaHttpClientFactory createFactory(final String name, final EurekaTransportConfig transportConfig, final ClusterResolver<EurekaEndpoint> clusterResolver, final TransportClientFactory delegateFactory, final ServerStatusEvaluator serverStatusEvaluator) { return new EurekaHttpClientFactory() { @Override public EurekaHttpClient newClient() { return new RetryableEurekaHttpClient(name, transportConfig, clusterResolver, delegateFactory, serverStatusEvaluator, DEFAULT_NUMBER_OF_RETRIES); } @Override public void shutdown() { delegateFactory.shutdown(); } }; } private List<EurekaEndpoint> getHostCandidates() { List<EurekaEndpoint> candidateHosts = clusterResolver.getClusterEndpoints(); quarantineSet.retainAll(candidateHosts); // If enough hosts are bad, we have no choice but start over again int threshold = (int) (candidateHosts.size() * transportConfig.getRetryableClientQuarantineRefreshPercentage()); //Prevent threshold is too large if (threshold > candidateHosts.size()) { threshold = candidateHosts.size(); } if (quarantineSet.isEmpty()) { // no-op } else if (quarantineSet.size() >= threshold) { logger.debug("Clearing quarantined list of size {}", quarantineSet.size()); quarantineSet.clear(); } else { List<EurekaEndpoint> remainingHosts = new ArrayList<>(candidateHosts.size()); for (EurekaEndpoint endpoint : candidateHosts) { if (!quarantineSet.contains(endpoint)) { remainingHosts.add(endpoint); } } candidateHosts = remainingHosts; } return candidateHosts; } @Monitor(name = METRIC_TRANSPORT_PREFIX + "quarantineSize", description = "number of servers quarantined", type = DataSourceType.GAUGE) public long getQuarantineSetSize() { return quarantineSet.size(); } }
brharrington/eureka
eureka-client/src/main/java/com/netflix/discovery/shared/transport/decorator/RetryableEurekaHttpClient.java
Java
apache-2.0
8,790
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.parquet.filter2.predicate; import org.junit.Test; import org.apache.parquet.hadoop.metadata.ColumnPath; import org.apache.parquet.filter2.predicate.Operators.BinaryColumn; import org.apache.parquet.filter2.predicate.Operators.BooleanColumn; import org.apache.parquet.filter2.predicate.Operators.Column; import org.apache.parquet.filter2.predicate.Operators.DoubleColumn; import org.apache.parquet.filter2.predicate.Operators.FloatColumn; import org.apache.parquet.filter2.predicate.Operators.IntColumn; import org.apache.parquet.filter2.predicate.Operators.LongColumn; import org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.apache.parquet.filter2.predicate.FilterApi.binaryColumn; import static org.apache.parquet.filter2.predicate.FilterApi.booleanColumn; import static org.apache.parquet.filter2.predicate.FilterApi.doubleColumn; import static org.apache.parquet.filter2.predicate.FilterApi.floatColumn; import static org.apache.parquet.filter2.predicate.FilterApi.intColumn; import static org.apache.parquet.filter2.predicate.FilterApi.longColumn; import static org.apache.parquet.filter2.predicate.ValidTypeMap.assertTypeValid; public class TestValidTypeMap { public static IntColumn intColumn = intColumn("int.column"); public static LongColumn longColumn = longColumn("long.column"); public static FloatColumn floatColumn = floatColumn("float.column"); public static DoubleColumn doubleColumn = doubleColumn("double.column"); public static BooleanColumn booleanColumn = booleanColumn("boolean.column"); public static BinaryColumn binaryColumn = binaryColumn("binary.column"); private static class InvalidColumnType implements Comparable<InvalidColumnType> { @Override public int compareTo(InvalidColumnType o) { return 0; } } public static Column<InvalidColumnType> invalidColumn = new Column<InvalidColumnType>(ColumnPath.get("invalid.column"), InvalidColumnType.class) { }; @Test public void testValidTypes() { assertTypeValid(intColumn, PrimitiveTypeName.INT32); assertTypeValid(longColumn, PrimitiveTypeName.INT64); assertTypeValid(floatColumn, PrimitiveTypeName.FLOAT); assertTypeValid(doubleColumn, PrimitiveTypeName.DOUBLE); assertTypeValid(booleanColumn, PrimitiveTypeName.BOOLEAN); assertTypeValid(binaryColumn, PrimitiveTypeName.BINARY); assertTypeValid(binaryColumn, PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY); assertTypeValid(binaryColumn, PrimitiveTypeName.INT96); } @Test public void testMismatchedTypes() { try { assertTypeValid(intColumn, PrimitiveTypeName.DOUBLE); fail("This should throw!"); } catch (IllegalArgumentException e) { assertEquals("FilterPredicate column: int.column's declared type (java.lang.Integer) does not match the " + "schema found in file metadata. Column int.column is of type: " + "DOUBLE\n" + "Valid types for this column are: [class java.lang.Double]", e.getMessage()); } } @Test public void testUnsupportedType() { try { assertTypeValid(invalidColumn, PrimitiveTypeName.INT32); fail("This should throw!"); } catch (IllegalArgumentException e) { assertEquals("Column invalid.column was declared as type: " + "org.apache.parquet.filter2.predicate.TestValidTypeMap$InvalidColumnType which is not supported " + "in FilterPredicates. Supported types for this column are: [class java.lang.Integer]", e.getMessage()); } } }
HyukjinKwon/parquet-mr-1
parquet-column/src/test/java/org/apache/parquet/filter2/predicate/TestValidTypeMap.java
Java
apache-2.0
4,415
// Copyright 2000-2021 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 git4idea.commands; import com.intellij.credentialStore.CredentialAttributes; import com.intellij.credentialStore.CredentialPromptDialog; import com.intellij.credentialStore.Credentials; import com.intellij.ide.passwordSafe.PasswordSafe; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.NlsSafe; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ssh.SSHUtil; import com.intellij.util.PathUtil; import git4idea.i18n.GitBundle; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.regex.Matcher; import static com.intellij.credentialStore.CredentialAttributesKt.generateServiceName; import static git4idea.commands.GitAuthenticationMode.FULL; class GitNativeSshGuiAuthenticator implements GitNativeSshAuthenticator { @NotNull private final Project myProject; @NotNull private final GitAuthenticationGate myAuthenticationGate; @NotNull private final GitAuthenticationMode myAuthenticationMode; private final boolean myDoNotRememberPasswords; @Nullable private String myLastAskedKeyPath = null; @Nullable private String myLastAskedUserName = null; @Nullable private String myLastAskedConfirmationInput = null; GitNativeSshGuiAuthenticator(@NotNull Project project, @NotNull GitAuthenticationGate authenticationGate, @NotNull GitAuthenticationMode authenticationMode, boolean doNotRememberPasswords) { myProject = project; myAuthenticationGate = authenticationGate; myAuthenticationMode = authenticationMode; myDoNotRememberPasswords = doNotRememberPasswords; } @Nullable @Override public String handleInput(@NotNull @NlsSafe String description) { if(myAuthenticationMode == GitAuthenticationMode.NONE) return null; return myAuthenticationGate.waitAndCompute(() -> { if (isKeyPassphrase(description)) return askKeyPassphraseInput(description); if (isSshPassword(description)) return askSshPasswordInput(description); if (isConfirmation(description)) return askConfirmationInput(description); return askGenericInput(description); }); } private static boolean isKeyPassphrase(@NotNull String description) { return SSHUtil.PASSPHRASE_PROMPT.matcher(description).matches(); } @Nullable private String askKeyPassphraseInput(@NotNull String description) { Matcher matcher = SSHUtil.PASSPHRASE_PROMPT.matcher(description); if (!matcher.matches()) throw new IllegalStateException(description); String keyPath = matcher.group(1); boolean resetPassword = keyPath.equals(myLastAskedKeyPath); myLastAskedKeyPath = keyPath; if (myDoNotRememberPasswords) { return askUser(() -> { String message = GitBundle.message("ssh.ask.passphrase.message", PathUtil.getFileName(keyPath)); return Messages.showPasswordDialog(myProject, message, GitBundle.message("ssh.ask.passphrase.title"), null); }); } else { return askPassphrase(myProject, keyPath, resetPassword, myAuthenticationMode); } } private static boolean isSshPassword(@NotNull String description) { return SSHUtil.PASSWORD_PROMPT.matcher(description).matches(); } @Nullable private String askSshPasswordInput(@NotNull String description) { Matcher matcher = SSHUtil.PASSWORD_PROMPT.matcher(description); if (!matcher.matches()) throw new IllegalStateException(description); String username = matcher.group(1); boolean resetPassword = username.equals(myLastAskedUserName); myLastAskedUserName = username; if (myDoNotRememberPasswords) { return askUser(() -> { String message = GitBundle.message("ssh.password.message", username); return Messages.showPasswordDialog(myProject, message, GitBundle.message("ssh.password.title"), null); }); } else { return askPassword(myProject, username, resetPassword, myAuthenticationMode); } } private static boolean isConfirmation(@NotNull @NlsSafe String description) { return description.contains(SSHUtil.CONFIRM_CONNECTION_PROMPT); } @Nullable private String askConfirmationInput(@NotNull @NlsSafe String description) { return askUser(() -> { @NlsSafe String message = StringUtil.replace(description, SSHUtil.CONFIRM_CONNECTION_PROMPT + " (yes/no)?", SSHUtil.CONFIRM_CONNECTION_PROMPT + "?"); String knownAnswer = myAuthenticationGate.getSavedInput(message); if (knownAnswer != null && myLastAskedConfirmationInput == null) { myLastAskedConfirmationInput = knownAnswer; return knownAnswer; } int answer = Messages.showYesNoDialog(myProject, message, GitBundle.message("title.ssh.confirmation"), null); String textAnswer; if (answer == Messages.YES) { textAnswer = "yes"; } else if (answer == Messages.NO) { textAnswer = "no"; } else { throw new AssertionError(answer); } myAuthenticationGate.saveInput(message, textAnswer); return textAnswer; }); } @Nullable private String askGenericInput(@NotNull @Nls String description) { return askUser(() -> Messages.showPasswordDialog(myProject, description, GitBundle.message("ssh.keyboard.interactive.title"), null)); } @Nullable private String askUser(@NotNull Computable<String> query) { if (myAuthenticationMode != FULL) return null; Ref<String> answerRef = new Ref<>(); ApplicationManager.getApplication().invokeAndWait(() -> answerRef.set(query.compute()), ModalityState.any()); return answerRef.get(); } @NonNls @Nullable private static String askPassphrase(@Nullable Project project, @NotNull @NlsSafe String keyPath, boolean resetPassword, @NotNull GitAuthenticationMode authenticationMode) { if (authenticationMode == GitAuthenticationMode.NONE) return null; CredentialAttributes newAttributes = passphraseCredentialAttributes(keyPath); Credentials credentials = PasswordSafe.getInstance().get(newAttributes); if (credentials != null && !resetPassword) { String password = credentials.getPasswordAsString(); if (password != null && !password.isEmpty()) return password; } if (authenticationMode == GitAuthenticationMode.SILENT) return null; return CredentialPromptDialog.askPassword(project, GitBundle.message("ssh.ask.passphrase.title"), GitBundle.message("ssh.ask.passphrase.message", PathUtil.getFileName(keyPath)), newAttributes, true); } @NonNls @Nullable private static String askPassword(@Nullable Project project, @NotNull @NlsSafe String username, boolean resetPassword, @NotNull GitAuthenticationMode authenticationMode) { if (authenticationMode == GitAuthenticationMode.NONE) return null; CredentialAttributes newAttributes = passwordCredentialAttributes(username); Credentials credentials = PasswordSafe.getInstance().get(newAttributes); if (credentials != null && !resetPassword) { String password = credentials.getPasswordAsString(); if (password != null) return password; } if (authenticationMode == GitAuthenticationMode.SILENT) return null; return CredentialPromptDialog.askPassword(project, GitBundle.message("ssh.password.title"), GitBundle.message("ssh.password.message", username), newAttributes, true); } @NotNull private static CredentialAttributes passphraseCredentialAttributes(@NotNull @Nls String key) { return new CredentialAttributes(generateServiceName(GitBundle.message("label.credential.store.key.ssh.passphrase"), key), key); } @NotNull private static CredentialAttributes passwordCredentialAttributes(@NotNull @Nls String key) { return new CredentialAttributes(generateServiceName(GitBundle.message("label.credential.store.key.ssh.password"), key), key); } }
siosio/intellij-community
plugins/git4idea/src/git4idea/commands/GitNativeSshGuiAuthenticator.java
Java
apache-2.0
8,938
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.asterix.dataflow.data.nontagged.printers.adm; import java.io.PrintStream; import org.apache.hyracks.algebricks.data.IPrinter; import org.apache.hyracks.algebricks.data.IPrinterFactory; public class ANullPrinterFactory implements IPrinterFactory { private static final long serialVersionUID = 1L; public static final ANullPrinterFactory INSTANCE = new ANullPrinterFactory(); public static final IPrinter PRINTER = (byte[] b, int s, int l, PrintStream ps) -> ps.print("null"); @Override public IPrinter createPrinter() { return PRINTER; } }
ty1er/incubator-asterixdb
asterixdb/asterix-om/src/main/java/org/apache/asterix/dataflow/data/nontagged/printers/adm/ANullPrinterFactory.java
Java
apache-2.0
1,404
/** * LanguageEncoding.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.dfa.axis.v1_20; public class LanguageEncoding extends com.google.api.ads.dfa.axis.v1_20.Base implements java.io.Serializable { public LanguageEncoding() { } public LanguageEncoding( long id, java.lang.String name) { super( id, name); } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof LanguageEncoding)) return false; LanguageEncoding other = (LanguageEncoding) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = super.equals(obj); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = super.hashCode(); __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(LanguageEncoding.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("http://www.doubleclick.net/dfa-api/v1.20", "LanguageEncoding")); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
raja15792/googleads-java-lib
modules/dfa_axis/src/main/java/com/google/api/ads/dfa/axis/v1_20/LanguageEncoding.java
Java
apache-2.0
2,537
package org.jgroups.auth.sasl; import org.jgroups.Address; import org.jgroups.Message; import org.jgroups.protocols.SASL; import org.jgroups.protocols.SaslHeader; import org.jgroups.protocols.SaslHeader.Type; import javax.security.auth.Subject; import javax.security.auth.callback.CallbackHandler; import javax.security.sasl.Sasl; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; import javax.security.sasl.SaslServerFactory; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; public class SaslServerContext implements SaslContext { SaslServer server; CountDownLatch latch = new CountDownLatch(1); Subject subject; public SaslServerContext(final SaslServerFactory saslServerFactory, final String mech, final String serverName, final CallbackHandler callback_handler, final Map<String, String> props, final Subject subject) throws SaslException { this.subject = subject; if (this.subject != null) { try { server = Subject.doAs(this.subject, (PrivilegedExceptionAction<SaslServer>)() -> saslServerFactory.createSaslServer(mech, SASL.SASL_PROTOCOL_NAME, serverName, props, callback_handler)); } catch (PrivilegedActionException e) { throw (SaslException)e.getCause(); // The createSaslServer will only throw this type of exception } } else { server = saslServerFactory.createSaslServer(mech, SASL.SASL_PROTOCOL_NAME, serverName, props, callback_handler); } } @Override public boolean isSuccessful() { return server.isComplete(); } @Override public boolean needsWrapping() { if (server.isComplete()) { String qop = (String) server.getNegotiatedProperty(Sasl.QOP); return (qop != null && (qop.equalsIgnoreCase("auth-int") || qop.equalsIgnoreCase("auth-conf"))); } else { return false; } } @Override public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException { return server.wrap(outgoing, offset, len); } @Override public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException { return server.unwrap(incoming, offset, len); } @Override public Message nextMessage(Address address, SaslHeader header) throws SaslException { Message message = new Message(address).setFlag(Message.Flag.OOB); byte[] challenge = server.evaluateResponse(header.getPayload()); if (server.isComplete()) { latch.countDown(); } if (challenge != null) { return message.putHeader(SASL.SASL_ID, new SaslHeader(Type.CHALLENGE, challenge)); } else { return null; } } public void awaitCompletion(long timeout) throws InterruptedException { latch.await(timeout, TimeUnit.MILLISECONDS); } public String getAuthorizationID() { return server.getAuthorizationID(); } @Override public void dispose() { try { server.dispose(); } catch (SaslException e) { } } }
dimbleby/JGroups
src/org/jgroups/auth/sasl/SaslServerContext.java
Java
apache-2.0
3,314
/* * 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.common; /* * TestNodesYamlParser.java * * User: Greg Schueler <a href="mailto:greg@dtosolutions.com">greg@dtosolutions.com</a> * Created: Jan 19, 2011 4:18:19 PM * */ import junit.framework.*; import com.dtolabs.rundeck.core.common.NodesYamlParser; import java.util.HashMap; import java.io.File; import java.io.ByteArrayInputStream; import org.yaml.snakeyaml.error.YAMLException; public class TestNodesYamlParser extends TestCase { public TestNodesYamlParser(String name) { super(name); } public static Test suite() { return new TestSuite(TestNodesYamlParser.class); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } public static void main(String args[]) { junit.textui.TestRunner.run(suite()); } public void testParse() throws Exception { { testReceiver recv = new testReceiver(); NodesYamlParser nodesYamlParser = new NodesYamlParser((File) null, recv); try { nodesYamlParser.parse(); fail("Should have thrown an Exception"); } catch (NullPointerException ex) { } } { testReceiver recv = new testReceiver(); ByteArrayInputStream is = new ByteArrayInputStream( "test: \n hostname: test\n".getBytes()); NodesYamlParser nodesYamlParser = new NodesYamlParser(is, recv); nodesYamlParser.parse(); assertEquals(1, recv.nodes.size()); assertTrue(recv.nodes.containsKey("test")); INodeEntry entry = recv.nodes.get("test"); assertNotNull(entry); assertEquals("test", entry.getNodename()); assertEquals("test", entry.getHostname()); assertNotNull(entry.getTags()); assertEquals(0, entry.getTags().size()); assertNull(entry.getOsArch()); assertNull(entry.getOsFamily()); assertNull(entry.getOsVersion()); assertNull(entry.getOsName()); assertNotNull(entry.getAttributes()); assertNull(entry.getDescription()); assertNull(entry.getFrameworkProject()); assertNull(entry.getUsername()); } { //test key for map data always overrides node name testReceiver recv = new testReceiver(); ByteArrayInputStream is = new ByteArrayInputStream( "test: \n nodename: bill\n hostname: test\n".getBytes()); NodesYamlParser nodesYamlParser = new NodesYamlParser(is, recv); nodesYamlParser.parse(); assertEquals(1, recv.nodes.size()); assertTrue(recv.nodes.containsKey("test")); INodeEntry entry = recv.nodes.get("test"); assertNotNull(entry); assertEquals("test", entry.getNodename()); assertEquals("test", entry.getHostname()); assertNotNull(entry.getTags()); assertEquals(0, entry.getTags().size()); assertNull(entry.getOsArch()); assertNull(entry.getOsFamily()); assertNull(entry.getOsVersion()); assertNull(entry.getOsName()); assertNotNull(entry.getAttributes()); assertNull(entry.getDescription()); assertNull(entry.getFrameworkProject()); assertNull(entry.getUsername()); } { testReceiver recv = new testReceiver(); ByteArrayInputStream is = new ByteArrayInputStream( ("test: \n" + " hostname: test\n" + " description: a description\n" + " tags: a, b, c\n" + " osArch: x86_64\n" + " osFamily: unix\n" + " osVersion: 10.6.5\n" + " osName: Mac OS X\n" + " username: a user\n" //following should be ignored + " nodename: bill\n" + " attributes: test\n" + " settings: test2\n" + " type: blahtype\n" + " frameworkProject: ignored\n").getBytes()); NodesYamlParser nodesYamlParser = new NodesYamlParser(is, recv); nodesYamlParser.parse(); assertEquals(1, recv.nodes.size()); assertTrue(recv.nodes.containsKey("test")); INodeEntry entry = recv.nodes.get("test"); assertNotNull(entry); assertEquals("test", entry.getNodename()); assertEquals("test", entry.getHostname()); assertNotNull(entry.getTags()); assertEquals(3,entry.getTags().size()); assertTrue(entry.getTags().contains("a")); assertTrue(entry.getTags().contains("b")); assertTrue(entry.getTags().contains("c")); assertEquals("x86_64", entry.getOsArch()); assertEquals("unix", entry.getOsFamily()); assertEquals("10.6.5", entry.getOsVersion()); assertEquals("Mac OS X", entry.getOsName()); assertEquals("a description",entry.getDescription()); assertEquals("a user", entry.getUsername()); //null values should be ignored assertNotNull(entry.getAttributes()); assertNull(entry.getFrameworkProject()); } { //test tags receiving Sequence data explicitly testReceiver recv = new testReceiver(); ByteArrayInputStream is = new ByteArrayInputStream( ("test: \n" + " nodename: bill\n" + " hostname: test\n" + " tags: [ a, b, c ]\n" ).getBytes()); NodesYamlParser nodesYamlParser = new NodesYamlParser(is, recv); nodesYamlParser.parse(); assertEquals(1, recv.nodes.size()); assertTrue(recv.nodes.containsKey("test")); INodeEntry entry = recv.nodes.get("test"); assertNotNull(entry); assertEquals("test", entry.getNodename()); assertEquals("test", entry.getHostname()); assertNotNull(entry.getTags()); assertEquals(3,entry.getTags().size()); assertTrue(entry.getTags().contains("a")); assertTrue(entry.getTags().contains("b")); assertTrue(entry.getTags().contains("c")); } { //test flow style data testReceiver recv = new testReceiver(); ByteArrayInputStream is = new ByteArrayInputStream( ("ubuntu: {description: \"Ubuntu server node\", hostname: \"192.168.1.101\"," + " osFamily: \"unix\", osName: \"Linux\", username: \"demo\", tags: \"dev\"}").getBytes()); NodesYamlParser nodesYamlParser = new NodesYamlParser(is, recv); nodesYamlParser.parse(); assertEquals(1, recv.nodes.size()); assertTrue(recv.nodes.containsKey("ubuntu")); INodeEntry entry = recv.nodes.get("ubuntu"); assertNotNull(entry); assertEquals("ubuntu", entry.getNodename()); assertEquals("192.168.1.101", entry.getHostname()); assertNotNull(entry.getTags()); assertEquals(1, entry.getTags().size()); assertTrue(entry.getTags().contains("dev")); assertEquals("Ubuntu server node", entry.getDescription()); assertEquals("unix", entry.getOsFamily()); assertEquals("Linux", entry.getOsName()); assertEquals("demo", entry.getUsername()); } } public void testParseAnyAttribute() throws Exception{ { //test flow style data testReceiver recv = new testReceiver(); ByteArrayInputStream is = new ByteArrayInputStream( ("test: \n" + " nodename: bill\n" + " hostname: test\n" + " tags: [ a, b, c ]\n" + " my-attribute: some value\n" ).getBytes()); NodesYamlParser nodesYamlParser = new NodesYamlParser(is, recv); nodesYamlParser.parse(); assertEquals(1, recv.nodes.size()); assertTrue(recv.nodes.containsKey("test")); INodeEntry entry = recv.nodes.get("test"); assertNotNull(entry); assertEquals("test", entry.getNodename()); assertNotNull(entry.getAttributes()); assertNotNull(entry.getAttributes().get("my-attribute")); assertEquals("some value", entry.getAttributes().get("my-attribute")); } } public void testShouldReadEditUrls() throws Exception{ { testReceiver recv = new testReceiver(); ByteArrayInputStream is = new ByteArrayInputStream( ("test: \n" + " hostname: test\n" + " description: a description\n" + " tags: a, b, c\n" + " osArch: x86_64\n" + " osFamily: unix\n" + " osVersion: 10.6.5\n" + " osName: Mac OS X\n" + " username: a user\n" + " editUrl: http://a.com/url\n" + " remoteUrl: http://b.com/aurl\n").getBytes()); NodesYamlParser nodesYamlParser = new NodesYamlParser(is, recv); nodesYamlParser.parse(); assertEquals(1, recv.nodes.size()); assertTrue(recv.nodes.containsKey("test")); INodeEntry entry = recv.nodes.get("test"); assertNotNull(entry); assertEquals("test", entry.getNodename()); assertEquals("test", entry.getHostname()); assertNotNull(entry.getTags()); assertEquals(3, entry.getTags().size()); assertTrue(entry.getTags().contains("a")); assertTrue(entry.getTags().contains("b")); assertTrue(entry.getTags().contains("c")); assertEquals("x86_64", entry.getOsArch()); assertEquals("unix", entry.getOsFamily()); assertEquals("10.6.5", entry.getOsVersion()); assertEquals("Mac OS X", entry.getOsName()); assertEquals("a description", entry.getDescription()); assertEquals("a user", entry.getUsername()); //null values should be ignored assertNull(entry.getFrameworkProject()); assertNotNull(entry.getAttributes()); assertNotNull(entry.getAttributes().get("editUrl")); assertNotNull(entry.getAttributes().get("remoteUrl")); assertEquals("http://a.com/url",entry.getAttributes().get("editUrl")); assertEquals("http://b.com/aurl",entry.getAttributes().get("remoteUrl")); } } public void testParseInvalid_require_nodename() throws Exception { //no nodename value testReceiver recv = new testReceiver(); ByteArrayInputStream is = new ByteArrayInputStream( "- \n hostname: bill\n blah: test\n".getBytes()); NodesYamlParser nodesYamlParser = new NodesYamlParser(is, recv); try { nodesYamlParser.parse(); fail("parsing should fail"); } catch (NodeFileParserException e) { assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals("Required property 'nodename' was not specified", e.getCause().getMessage()); } } public void testParseInvalid_allow_missing_hostname() throws Exception { //allow no hostname value testReceiver recv = new testReceiver(); ByteArrayInputStream is = new ByteArrayInputStream( "bill: \n nodename: bill\n blah: test\n".getBytes()); NodesYamlParser nodesYamlParser = new NodesYamlParser(is, recv); nodesYamlParser.parse(); Assert.assertEquals(1, recv.nodes.size()); Assert.assertNotNull(recv.nodes.get("bill")); Assert.assertEquals("bill", recv.nodes.get("bill").getNodename()); Assert.assertEquals(null, recv.nodes.get("bill").getHostname()); } public void testParseInvalid_unexpecteddatatype() throws Exception { //unexpected data type for string field testReceiver recv = new testReceiver(); ByteArrayInputStream is = new ByteArrayInputStream( ("test: \n" + " nodename: bill\n" + " hostname: test\n" + " username: {test:value, a:b}\n").getBytes()); NodesYamlParser nodesYamlParser = new NodesYamlParser(is, recv); try { nodesYamlParser.parse(); fail("parsing should fail: " + recv.nodes); } catch (NodeFileParserException e) { assertTrue(e.getCause() instanceof YAMLException); } } public void testParseInvalid_no_javaclass() throws Exception { //don't allow arbitrary java class testReceiver recv = new testReceiver(); ByteArrayInputStream is = new ByteArrayInputStream( ("test: \n" + " nodename: bill\n" + " hostname: test\n" + " username: !!java.io.File [woops.txt]\n").getBytes()); NodesYamlParser nodesYamlParser = new NodesYamlParser(is, recv); try { nodesYamlParser.parse(); fail("parsing should fail: " + recv.nodes); } catch (NodeFileParserException e) { assertTrue(e.getCause() instanceof YAMLException); } } public static class testReceiver implements NodeReceiver{ HashMap<String,INodeEntry> nodes = new HashMap<String, INodeEntry>(); public void putNode(final INodeEntry iNodeEntry) { nodes.put(iNodeEntry.getNodename(), iNodeEntry); } } }
variacode/rundeck
core/src/test/java/com/dtolabs/rundeck/core/common/TestNodesYamlParser.java
Java
apache-2.0
14,693
/* * Copyright 2001-2010 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.juddi.xlt.test; import org.apache.juddi.xlt.action.SOAP.FindServices; import org.apache.juddi.xlt.action.SOAP.GetAuthenticationToken; import org.apache.juddi.xlt.util.AbstractUDDIClientTestCase; import org.junit.Test; public class TFindServiceByName extends AbstractUDDIClientTestCase { @Test public void findBusiness() throws Throwable { GetAuthenticationToken getAuthenticationToken = new GetAuthenticationToken(); getAuthenticationToken.run(); FindServices findServices = new FindServices(getAuthenticationToken.getAuthenticationToken()); findServices.run(); } }
KurtStam/juddi
qa/juddi-xlt/src/org/apache/juddi/xlt/test/TFindServiceByName.java
Java
apache-2.0
1,265
/** * @copyright * ==================================================================== * 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. * ==================================================================== * @endcopyright */ package org.tigris.subversion.javahl; /** * Encapsulates version information about the underlying native * libraries. Basically a wrapper for <a * href="http://svn.apache.org/repos/asf/subversion/trunk/subversion/include/svn_version.h"><code>svn_version.h</code></a>. */ public class Version { private org.apache.subversion.javahl.types.Version aVersion; public Version() { aVersion = new org.apache.subversion.javahl.types.Version(); } public Version(org.apache.subversion.javahl.types.Version aVersion) { this.aVersion = aVersion; } /** * @return The full version string for the loaded JavaHL library, * as defined by <code>MAJOR.MINOR.PATCH INFO</code>. * @since 1.4.0 */ public String toString() { return aVersion.toString(); } /** * @return The major version number for the loaded JavaHL library. * @since 1.4.0 */ public int getMajor() { return aVersion.getMajor(); } /** * @return The minor version number for the loaded JavaHL library. * @since 1.4.0 */ public int getMinor() { return aVersion.getMinor(); } /** * @return The patch-level version number for the loaded JavaHL * library. * @since 1.4.0 */ public int getPatch() { return aVersion.getPatch(); } /** * @return Whether the JavaHL native library version is at least * of <code>major.minor.patch</code> level. * @since 1.5.0 */ public boolean isAtLeast(int major, int minor, int patch) { return aVersion.isAtLeast(major, minor, patch); } }
YueLinHo/Subversion
subversion/bindings/javahl/src/org/tigris/subversion/javahl/Version.java
Java
apache-2.0
2,701
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.keycloak.models.mongo.keycloak.entities; /** * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a> */ public class PersistentClientSessionEntity { private String clientSessionId; private String clientId; private int timestamp; private String data; public String getClientSessionId() { return clientSessionId; } public void setClientSessionId(String clientSessionId) { this.clientSessionId = clientSessionId; } public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public int getTimestamp() { return timestamp; } public void setTimestamp(int timestamp) { this.timestamp = timestamp; } public String getData() { return data; } public void setData(String data) { this.data = data; } }
didiez/keycloak
model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/PersistentClientSessionEntity.java
Java
apache-2.0
1,603
public class JavaRead { public static void main(String[] args) { new Main().isVariable(); } }
smmribeiro/intellij-community
plugins/kotlin/refIndex/tests/testData/compilerIndex/properties/members/isVariable/JavaRead.java
Java
apache-2.0
109
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.plugin.hive.metastore; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableList; import javax.annotation.concurrent.Immutable; import java.util.List; import java.util.Objects; import java.util.Optional; import static com.google.common.base.MoreObjects.toStringHelper; import static io.trino.plugin.hive.util.HiveUtil.toPartitionValues; import static java.util.Objects.requireNonNull; @Immutable public class HivePartitionName { private final HiveTableName hiveTableName; private final List<String> partitionValues; private final Optional<String> partitionName; // does not participate in hashCode/equals @JsonCreator public HivePartitionName( @JsonProperty("hiveTableName") HiveTableName hiveTableName, @JsonProperty("partitionValues") List<String> partitionValues, @JsonProperty("partitionName") Optional<String> partitionName) { this.hiveTableName = requireNonNull(hiveTableName, "hiveTableName is null"); this.partitionValues = ImmutableList.copyOf(requireNonNull(partitionValues, "partitionValues is null")); this.partitionName = requireNonNull(partitionName, "partitionName is null"); } public static HivePartitionName hivePartitionName(HiveTableName hiveTableName, String partitionName) { return new HivePartitionName(hiveTableName, toPartitionValues(partitionName), Optional.of(partitionName)); } public static HivePartitionName hivePartitionName(HiveTableName hiveTableName, List<String> partitionValues) { return new HivePartitionName(hiveTableName, partitionValues, Optional.empty()); } @JsonProperty public HiveTableName getHiveTableName() { return hiveTableName; } @JsonProperty public List<String> getPartitionValues() { return partitionValues; } @JsonProperty public Optional<String> getPartitionName() { return partitionName; } @Override public String toString() { return toStringHelper(this) .add("hiveTableName", hiveTableName) .add("partitionValues", partitionValues) .add("partitionName", partitionName) .toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } HivePartitionName other = (HivePartitionName) o; return Objects.equals(hiveTableName, other.hiveTableName) && Objects.equals(partitionValues, other.partitionValues); } @Override public int hashCode() { return Objects.hash(hiveTableName, partitionValues); } }
ebyhr/presto
plugin/trino-hive/src/main/java/io/trino/plugin/hive/metastore/HivePartitionName.java
Java
apache-2.0
3,443
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server.balancer; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hdfs.protocol.DatanodeInfo; import org.apache.hadoop.hdfs.server.balancer.Balancer.BalancerDatanode; import org.apache.hadoop.hdfs.server.balancer.Balancer.NodeTask; import org.apache.hadoop.hdfs.server.balancer.Balancer.Source; import org.apache.hadoop.hdfs.server.balancer.Balancer.Target; import org.apache.hadoop.net.NetworkTopology; import org.apache.hadoop.net.Node; /** Keeps the plan of pipelines to create between nodes and how much data must be sent */ class BalancePlan { protected static final Log LOG = LogFactory.getLog(BalancePlan.class.getName()); /** Number of bytes to be moved in order to make the cluster balanced. */ public long bytesLeftToMove; public long bytesToMove; public NetworkTopology cluster = new NetworkTopology(); /** Maps datanode's storage ID to itself */ public Map<String, BalancerDatanode> datanodes = new HashMap<String, BalancerDatanode>(); /** All nodes that will participate in balancing as sources */ public Collection<Source> sources = new HashSet<Source>(); /** All nodes that will participate in balancing as targets */ public Collection<Target> targets = new HashSet<Target>(); /** If remaining < lowerRemainingThreshold then DataNode is considered overutilized */ private double lowerRemainingThreshold; /** If remaining > upperRemainingThreshold then DataNode is considered underutilized */ private double upperRemainingThreshold; /** Cluster-wide remaining capacity percentage */ private double avgRemaining; /** Compute balance plan */ public BalancePlan(Balancer balancer, List<DatanodeInfo> datanodes) { if (datanodes == null || datanodes.isEmpty()) { throw new IllegalArgumentException("cannot prepare plan for empty cluster"); } avgRemaining = computeAvgRemaining(datanodes); lowerRemainingThreshold = Math.max(avgRemaining / 2, avgRemaining - balancer.threshold); upperRemainingThreshold = Math.min(PERCENTAGE_BASE, avgRemaining + balancer.threshold); if (lowerRemainingThreshold > upperRemainingThreshold) { throw new IllegalStateException("lowerThresh > upperThresh"); } LOG.info("balanced range: [ " + lowerRemainingThreshold + ", " + upperRemainingThreshold + " ], average remaining: " + avgRemaining); long overLoadedBytes = 0L, underLoadedBytes = 0L; Bucket clusterBucket = new Bucket(); Map<Node, Bucket> rackBuckets = new HashMap<Node, Bucket>(); for (DatanodeInfo datanode : datanodes) { // Update network topology cluster.add(datanode); // Create bucket if none assert datanode.getParent() != null : "node outside of any rack"; Bucket bucket = rackBuckets.get(datanode.getParent()); if (bucket == null) { bucket = new Bucket(); rackBuckets.put(datanode.getParent(), bucket); } // Put DataNode into chosen bucket BalancerDatanode datanodeS; if (getRemaining(datanode) < avgRemaining) { // Above average utilized datanodeS = balancer.getSource(datanode, avgRemaining); bucket.addSource((Source) datanodeS); clusterBucket.addSource((Source) datanodeS); if (isOverUtilized(datanodeS)) { overLoadedBytes += (long) ((lowerRemainingThreshold - datanodeS.getCurrentRemaining()) * datanodeS.getDatanode().getCapacity() / PERCENTAGE_BASE); } } else { // Below average utilized datanodeS = new Target(datanode, avgRemaining); bucket.addTarget((Target) datanodeS); clusterBucket.addTarget((Target) datanodeS); if (isUnderUtilized(datanodeS)) { underLoadedBytes += (long) ((datanodeS.getCurrentRemaining() - upperRemainingThreshold) * datanodeS.getDatanode().getCapacity() / PERCENTAGE_BASE); } } // Update all DataNodes list this.datanodes.put(datanode.getStorageID(), datanodeS); } bytesLeftToMove = Math.max(overLoadedBytes, underLoadedBytes); logImbalancedNodes(); // Balance each rack bucket separately for (Bucket bucket : rackBuckets.values()) { double rackAverage = bucket.computeAvgRemaining(); if (lowerRemainingThreshold <= rackAverage && rackAverage <= upperRemainingThreshold) { bucket.updatePlan(); } // If perfectly balanced rack renders only over or underutilized DataNodes // we do not bother balancing it } // Balance cluster-wide afterwards clusterBucket.externalUpdate(); clusterBucket.updatePlan(); bytesToMove = 0L; for (Source src : sources) { bytesToMove += src.scheduledSize; } logPlanOutcome(); } /** Log the over utilized & under utilized nodes */ private void logImbalancedNodes() { if (LOG.isInfoEnabled()) { int underUtilized = 0, overUtilized = 0; for (BalancerDatanode node : this.datanodes.values()) { if (isUnderUtilized(node)) underUtilized++; else if (isOverUtilized(node)) overUtilized++; } StringBuilder msg = new StringBuilder(); msg.append(overUtilized); msg.append(" over utilized nodes:"); for (BalancerDatanode node : this.datanodes.values()) { if (isOverUtilized(node)) { msg.append(" "); msg.append(node.getName()); } } LOG.info(msg); msg = new StringBuilder(); msg.append(underUtilized); msg.append(" under utilized nodes: "); for (BalancerDatanode node : this.datanodes.values()) { if (isUnderUtilized(node)) { msg.append(" "); msg.append(node.getName()); } } LOG.info(msg); } } /** Log node utilization after the plan execution */ private void logPlanOutcome() { if (LOG.isInfoEnabled()) { LOG.info("Predicted plan outcome: bytesLeftToMove: " + bytesLeftToMove + ", bytesToMove: " + bytesToMove); for (BalancerDatanode node : this.datanodes.values()) { LOG.info(node.getName() + " remaining: " + node.getCurrentRemaining()); } } } /** Pairs up given nodes in balancing plan */ private void scheduleTask(Source source, long size, Target target) { NodeTask nodeTask = new NodeTask(target, size); source.addNodeTask(nodeTask); target.addNodeTask(nodeTask); sources.add(source); targets.add(target); LOG.info("scheduled " + size + " bytes : " + source.getName() + " -> " + target.getName()); } /** Determines if the node is overutilized */ private boolean isOverUtilized(BalancerDatanode datanode) { return datanode.getCurrentRemaining() < lowerRemainingThreshold; } /** Determines if the node is underutilized */ private boolean isUnderUtilized(BalancerDatanode datanode) { return datanode.getCurrentRemaining() > upperRemainingThreshold; } /** True iff the DataNode was over or underutilized before balancing */ private boolean wasUrgent(BalancerDatanode datanode) { // Note that no node can become urgent during balancing if it was not before return datanode.initialRemaining < lowerRemainingThreshold || datanode.initialRemaining > upperRemainingThreshold; } /** Remaining ratio is expressed in percents */ static final double PERCENTAGE_BASE = 100.0; static double computeAvgRemaining(Iterable<DatanodeInfo> datanodes) { long totalCapacity = 0L, totalRemainingSpace = 0L; for (DatanodeInfo datanode : datanodes) { totalCapacity += datanode.getCapacity(); totalRemainingSpace += datanode.getRemaining(); } return (double) totalRemainingSpace / totalCapacity * PERCENTAGE_BASE; } static double getRemaining(DatanodeInfo datanode) { return (double) datanode.getRemaining() / datanode.getCapacity() * PERCENTAGE_BASE; } /** Set of nodes which can interchange data for balancing */ private class Bucket { private PriorityQueue<Source> sources = new PriorityQueue<Source>(10, new SourceComparator()); private PriorityQueue<Target> targets = new PriorityQueue<Target>(10, new TargetComparator()); public void addSource(Source node) { this.sources.add(node); } public void addTarget(Target node) { this.targets.add(node); } public double computeAvgRemaining() { long totalCapacity = 0L, totalRemainingSpace = 0L; for (BalancerDatanode node : sources) { totalCapacity += node.getDatanode().getCapacity(); totalRemainingSpace += node.getDatanode().getRemaining(); } for (BalancerDatanode node : targets) { totalCapacity += node.getDatanode().getCapacity(); totalRemainingSpace += node.getDatanode().getRemaining(); } return ((double) totalRemainingSpace) / totalCapacity * PERCENTAGE_BASE; } /** Updates the plan with all pairs of nodes from this bucket which need to be connected */ public void updatePlan() { while (!this.sources.isEmpty() && !this.targets.isEmpty()) { Source source = this.sources.poll(); Target target = this.targets.poll(); if (!wasUrgent(source) && !wasUrgent(target)) { // Due to ordering of DataNodes we can skip the rest break; } long size = moveSize(source, target); if (size > 0) { scheduleTask(source, size, target); } if (source.getAvailableMoveSize() > 0) { this.sources.add(source); } if (target.getAvailableMoveSize() > 0) { this.targets.add(target); } // Loop termination: // In each step we either scheduleTask, therefore decreasing sum (over // all nodes) of availableMoveSize, or decrease number of nodes in // sources or targets queue, all of them are bounded by 0. } } /** Determines how much data to move between given nodes */ private long moveSize(Source source, BalancerDatanode target) { // TODO balancing concurrency return Math.min(source.getAvailableMoveSize(), target.getAvailableMoveSize()); } /** Sort internal queues again in case DataNodes was changed externally */ public void externalUpdate() { // sources and targets might no longer be a proper priority queues this.sources = new PriorityQueue<Source>((Collection<Source>) this.sources); this.targets = new PriorityQueue<Target>((Collection<Target>) this.targets); } /** * We rely on this ordering in Bucket#updatePlan loop termination condition, * additional priorities should be expressed in proper (source/target) comparator below. * Because of this condition SourceComparator and TargetComparator are not reverse of each * other. */ private abstract class BalancerDatanodeComparator implements Comparator<BalancerDatanode> { @Override public int compare(BalancerDatanode o1, BalancerDatanode o2) { return Boolean.valueOf(wasUrgent(o2)).compareTo(wasUrgent(o1)); } } private final class SourceComparator extends BalancerDatanodeComparator { @Override public int compare(BalancerDatanode o1, BalancerDatanode o2) { int ret = super.compare(o1, o2); if (ret == 0) { ret = Double.valueOf(o1.getCurrentRemaining()).compareTo(o2.getCurrentRemaining()); } // TODO concurrency level can also be taken into consideration return ret; } } private final class TargetComparator extends BalancerDatanodeComparator { @Override public int compare(BalancerDatanode o1, BalancerDatanode o2) { int ret = super.compare(o1, o2); if (ret == 0) { ret = Double.valueOf(o2.getCurrentRemaining()).compareTo(o1.getCurrentRemaining()); } // TODO concurrency level can also be taken into consideration return ret; } } } /** Prints data distribution based on report from NameNode */ public static void logDataDistribution(DatanodeInfo[] report) { if (LOG.isInfoEnabled()) { double avgRemaining = computeAvgRemaining(Arrays.asList(report)); StringBuilder msg = new StringBuilder("Data distribution report: avgRemaining " + avgRemaining); for (DatanodeInfo node : report) { msg.append("\n").append(node.getName()); msg.append(" remaining ").append(getRemaining(node)); msg.append(" raw ").append(node.getRemaining()).append(" / ").append(node.getCapacity()); } LOG.info(msg); } } }
nvoron23/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/server/balancer/BalancePlan.java
Java
apache-2.0
13,640
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.debugger.ui.tree; import com.intellij.debugger.DebuggerContext; import com.intellij.debugger.engine.DebugProcess; import com.intellij.debugger.engine.evaluation.EvaluateException; import com.intellij.psi.PsiExpression; import com.intellij.xdebugger.impl.ui.tree.ValueMarkup; import com.sun.jdi.Value; import org.jetbrains.annotations.Nullable; import javax.swing.*; public interface ValueDescriptor extends NodeDescriptor{ PsiExpression getDescriptorEvaluation(DebuggerContext context) throws EvaluateException; Value getValue(); String setValueLabel(String label); String setValueLabelFailed(EvaluateException e); Icon setValueIcon(Icon icon); boolean isArray(); boolean isLvalue(); boolean isNull(); boolean isPrimitive(); boolean isString(); @Nullable ValueMarkup getMarkup(final DebugProcess debugProcess); void setMarkup(final DebugProcess debugProcess, @Nullable ValueMarkup markup); }
android-ia/platform_tools_idea
java/debugger/impl/src/com/intellij/debugger/ui/tree/ValueDescriptor.java
Java
apache-2.0
1,554
/* -*- mode: java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2013 Real Logic Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.real_logic.sbe.xml; import java.io.PrintStream; /** * Class to hold error handling state while parsing an XML message schema. */ public class ErrorHandler { private final PrintStream out; private final boolean stopOnError; private final boolean warningsFatal; private final boolean suppressOutput; private int errors = 0; private int warnings = 0; /** * Construct a new {@link ErrorHandler} that outputs to a provided {@link PrintStream}. * * @param stream to which output should be sent. * @param options the parsing options. */ public ErrorHandler(final PrintStream stream, final ParserOptions options) { out = stream; stopOnError = options.stopOnError(); warningsFatal = options.warningsFatal(); suppressOutput = options.suppressOutput(); } /** * Default {@link ErrorHandler} that outputs to {@link System#err}. * * @param options the parsing options. */ public ErrorHandler(final ParserOptions options) { this(System.err, options); } /** * Record a message signifying an error condition. * * @param msg signifying an error. */ public void error(final String msg) { errors++; if (!suppressOutput) { out.println("ERROR: " + msg); } if (stopOnError) { throw new IllegalArgumentException(msg); } } /** * Record a message signifying an warning condition. * * @param msg signifying an warning. */ public void warning(final String msg) { warnings++; if (!suppressOutput) { out.println("WARNING: " + msg); } if (warningsFatal && stopOnError) { throw new IllegalArgumentException(msg); } } /** * Check if the parser should exit. * * @throws IllegalStateException if there are errors or warnings recorded. */ public void checkIfShouldExit() { if (errors > 0) { throw new IllegalStateException("had " + errors + " errors"); } else if (warnings > 0 && warningsFatal) { throw new IllegalStateException("had " + warnings + " warnings"); } } /** * The count of errors encountered. * * @return the count of errors encountered. */ public int errorCount() { return errors; } /** * The count of warnings encountered. * * @return the count of warnings encountered. */ public int warningCount() { return warnings; } public String toString() { return "ErrorHandler{" + "out=" + out + ", stopOnError=" + stopOnError + ", warningsFatal=" + warningsFatal + ", suppressOutput=" + suppressOutput + ", errors=" + errors + ", warnings=" + warnings + '}'; } }
tfgm-bud/simple-binary-encoding
main/java/uk/co/real_logic/sbe/xml/ErrorHandler.java
Java
apache-2.0
3,713
/* See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * Esri Inc. licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.esri.gpt.control.filter; import com.esri.gpt.framework.util.LogUtil; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; /** * HTTP servlet request wrapper for a multipart requests. * <p> * The wrapper uses the org.apache.commons.fileupload package for * parsing and handling the incoming request. * <p> * The typical usage is based upon an incoming form with * an enctype of multipart/form-data. * <p> * org.apache.commons.fileupload.FileUploadBase$FileSizeLimitExceededException * is the exception thrown when the uploaded file size exceeds the limit. */ public class MultipartWrapper extends HttpServletRequestWrapper { // class variables ============================================================= // instance variables ========================================================== private Map<String,FileItem> _fileParameters; private Map<String,String[]> _formParameters; // constructors ================================================================ /** * Construct with a current HTTP servlet request. * @param request the current HTTP servlet request * @throws FileUploadException if an exception occurs during file upload */ public MultipartWrapper(HttpServletRequest request) throws FileUploadException { super(request); getLogger().finer("Handling multipart content."); // initialize parameters _fileParameters = new HashMap<String,FileItem>(); _formParameters = new HashMap<String,String[]>(); int nFileSizeMax = 100000000; int nSizeThreshold = 500000; String sTmpFolder = ""; // make the file item factory DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(nSizeThreshold); if (sTmpFolder.length() > 0) { File fTmpFolder = new File(sTmpFolder); factory.setRepository(fTmpFolder); } // make the file upload object ServletFileUpload fileUpload = new ServletFileUpload(); fileUpload.setFileItemFactory(factory); fileUpload.setFileSizeMax(nFileSizeMax); // parse the parameters associated with the request List items = fileUpload.parseRequest(request); String[] aValues; ArrayList<String> lValues; for(int i=0;i<items.size();i++){ FileItem item = (FileItem)items.get(i); getLogger().finer("FileItem="+item); if (item.isFormField()) { String sName = item.getFieldName(); String sValue = item.getString(); if (_formParameters.containsKey(sName)) { aValues = _formParameters.get(sName); lValues = new ArrayList<String>(Arrays.asList(aValues)); lValues.add(sValue); aValues = lValues.toArray(new String[0]); } else { aValues = new String[1]; aValues[0] = sValue; } _formParameters.put(sName,aValues); } else { _fileParameters.put(item.getFieldName(),item); request.setAttribute(item.getFieldName(),item); } } } // properties ================================================================== // methods ===================================================================== /** * Gets the logger. * @return the logger */ private static Logger getLogger() { return LogUtil.getLogger(); } /** * Gets the form parameter value associated with a name. * @param name the subject parameter name * @return the associated value (null if none) */ @Override public String getParameter(String name) { String[] aValues = _formParameters.get(name); if (aValues == null) { return super.getParameter(name); } else { return aValues[0]; } } /** * Gets the form parameter map. * @return the form parameter map */ @Override public Map getParameterMap() { return _formParameters; } /** * Gets the form parameter names. * @return the form parameter names */ @Override public Enumeration getParameterNames() { return Collections.enumeration(_formParameters.keySet()); } /** * Gets the form parameter values associated with a name. * @param name the subject parameter name * @return the associated values (null if none) */ @Override public String[] getParameterValues(String name) { return _formParameters.get(name); } /** * Determine if a request contains multipart content. * @param request the current request * @return true if the request contains multipart content */ public static boolean isMultipartContent(ServletRequest request) { boolean bMultipart = false; if ((request != null) && (request instanceof HttpServletRequest)) { HttpServletRequest httpReq = (HttpServletRequest)request; bMultipart = ServletFileUpload.isMultipartContent(httpReq); } getLogger().finest("isMultipartContent="+bMultipart); return bMultipart; } }
GeoinformationSystems/GeoprocessingAppstore
src/com/esri/gpt/control/filter/MultipartWrapper.java
Java
apache-2.0
5,908
/* $Id$ */ /** * 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.documentum.fc.client; import com.documentum.fc.common.*; /** Stub interface to allow the connector to build fully. */ public interface IDfQuery { public final static int DF_EXECREAD_QUERY = 4; public IDfCollection execute(IDfSession session, int type) throws DfException; public void setBatchSize(int size); public void setDQL(String dql); }
cogfor/mcf-cogfor
connectors/documentum/build-stub/src/main/java/com/documentum/fc/client/IDfQuery.java
Java
apache-2.0
1,163
/* * Artificial Intelligence for Humans * Volume 1: Fundamental Algorithms * Java Version * http://www.aifh.org * http://www.jeffheaton.com * * Code repository: * https://github.com/jeffheaton/aifh * Copyright 2013 by Jeff Heaton * * 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. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package com.heatonresearch.aifh.general.fns.link; import com.heatonresearch.aifh.AIFHError; import com.heatonresearch.aifh.general.fns.Fn; /** * The log link function for a GLM. * <p/> * http://en.wikipedia.org/wiki/Generalized_linear_model */ public class LogLinkFunction implements Fn { /** * {@inheritDoc} */ @Override public double evaluate(final double[] x) { if (x.length > 1) { throw new AIFHError("The logistic link function can only accept one parameter."); } return Math.log(x[0]); } }
PeterLauris/aifh
vol1/java-examples/src/main/java/com/heatonresearch/aifh/general/fns/link/LogLinkFunction.java
Java
apache-2.0
1,503
package com.intellij.remoteServer.configuration.deployment; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.util.xmlb.XmlSerializerUtil; import org.jetbrains.annotations.Nullable; /** * @author nik */ public class DeploymentConfigurationBase<Self extends DeploymentConfigurationBase> extends DeploymentConfiguration implements PersistentStateComponent<Self> { @Override public PersistentStateComponent<?> getSerializer() { return this; } @Nullable @Override public Self getState() { return (Self)this; } @Override public void loadState(Self state) { XmlSerializerUtil.copyBean(state, this); } }
android-ia/platform_tools_idea
platform/remote-servers/api/src/com/intellij/remoteServer/configuration/deployment/DeploymentConfigurationBase.java
Java
apache-2.0
670
/* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.zeppelin.ksql; import org.apache.zeppelin.interpreter.Interpreter; import org.apache.zeppelin.interpreter.InterpreterContext; import org.apache.zeppelin.interpreter.InterpreterException; import org.apache.zeppelin.interpreter.InterpreterOutput; import org.apache.zeppelin.interpreter.InterpreterResult; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.mockito.stubbing.Stubber; import java.io.IOException; import java.util.AbstractMap; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import static org.junit.Assert.assertEquals; public class KSQLInterpreterTest { private InterpreterContext context; private static final Map<String, String> PROPS = new HashMap<String, String>() {{ put("ksql.url", "http://localhost:8088"); put("ksql.streams.auto.offset.reset", "earliest"); }}; @Before public void setUpZeppelin() throws IOException { context = InterpreterContext.builder() .setInterpreterOut(new InterpreterOutput()) .setParagraphId("ksql-test") .build(); } @Test public void shouldRenderKSQLSelectAsTable() throws InterpreterException, IOException, InterruptedException { // given Properties p = new Properties(); p.putAll(PROPS); KSQLRestService service = Mockito.mock(KSQLRestService.class); Stubber stubber = Mockito.doAnswer((invocation) -> { Consumer< KSQLResponse> callback = (Consumer< KSQLResponse>) invocation.getArguments()[2]; IntStream.range(1, 5) .forEach(i -> { Map<String, Object> map = new HashMap<>(); if (i == 4) { map.put("row", null); map.put("terminal", true); } else { map.put("row", Collections.singletonMap("columns", Arrays.asList("value " + i))); map.put("terminal", false); } callback.accept(new KSQLResponse(Arrays.asList("fieldName"), map)); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } }); return null; }); stubber.when(service).executeQuery(Mockito.any(String.class), Mockito.anyString(), Mockito.any(Consumer.class)); Interpreter interpreter = new KSQLInterpreter(p, service); // when String query = "select * from orders"; interpreter.interpret(query, context); // then String expected = "%table fieldName\n" + "value 1\n" + "value 2\n" + "value 3\n"; context.out.flush(); assertEquals(1, context.out.toInterpreterResultMessage().size()); assertEquals(expected, context.out.toInterpreterResultMessage().get(0).toString()); assertEquals(InterpreterResult.Type.TABLE, context.out .toInterpreterResultMessage().get(0).getType()); interpreter.close(); } @Test public void shouldRenderKSQLNonSelectAsTable() throws InterpreterException, IOException, InterruptedException { // given Properties p = new Properties(); p.putAll(PROPS); KSQLRestService service = Mockito.mock(KSQLRestService.class); Map<String, Object> row1 = new HashMap<>(); row1.put("name", "orders"); row1.put("registered", "false"); row1.put("replicaInfo", "[1]"); row1.put("consumerCount", "0"); row1.put("consumerGroupCount", "0"); Map<String, Object> row2 = new HashMap<>(); row2.put("name", "orders"); row2.put("registered", "false"); row2.put("replicaInfo", "[1]"); row2.put("consumerCount", "0"); row2.put("consumerGroupCount", "0"); Stubber stubber = Mockito.doAnswer((invocation) -> { Consumer< KSQLResponse> callback = (Consumer< KSQLResponse>) invocation.getArguments()[2]; callback.accept(new KSQLResponse(row1)); callback.accept(new KSQLResponse(row2)); return null; }); stubber.when(service).executeQuery( Mockito.any(String.class), Mockito.anyString(), Mockito.any(Consumer.class)); Interpreter interpreter = new KSQLInterpreter(p, service); // when String query = "show topics"; interpreter.interpret(query, context); // then List<Map<String, Object>> expected = Arrays.asList(row1, row2); context.out.flush(); String[] lines = context.out.toInterpreterResultMessage() .get(0).toString() .replace("%table ", "") .trim() .split("\n"); List<String[]> rows = Stream.of(lines) .map(line -> line.split("\t")) .collect(Collectors.toList()); List<Map<String, String>> actual = rows.stream() .skip(1) .map(row -> IntStream.range(0, row.length) .mapToObj(index -> new AbstractMap.SimpleEntry<>(rows.get(0)[index], row[index])) .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()))) .collect(Collectors.toList()); assertEquals(1, context.out.toInterpreterResultMessage().size()); assertEquals(expected, actual); assertEquals(InterpreterResult.Type.TABLE, context.out .toInterpreterResultMessage().get(0).getType()); } }
apache/zeppelin
ksql/src/test/java/org/apache/zeppelin/ksql/KSQLInterpreterTest.java
Java
apache-2.0
5,965
// 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.jtx.data; import jodd.exception.UncheckedException; /** * Transactional resource, encapsulates working session. */ public class WorkSession { static String persistedValue = "The big bang theory"; public static String getPersistedValue() { return persistedValue; } public WorkSession() { } public WorkSession(int txno) { this.txno = txno; } String sessionValue; boolean readOnly; int txno; public void writeValue(String value) { if (txno == 0) { // no transaction persistedValue = value; return; } // under transaction if (readOnly == true) { throw new UncheckedException(); } sessionValue = "[" + txno + "] " + value; } public String readValue() { if (sessionValue != null) { return sessionValue; } return persistedValue; } // aka commit public void done() { if (sessionValue != null) { persistedValue = sessionValue; } sessionValue = null; } // aka rollback public void back() { sessionValue = null; } }
mohanaraosv/jodd
jodd-jtx/src/test/java/jodd/jtx/data/WorkSession.java
Java
bsd-2-clause
2,462
package org.hisp.dhis.common; /* * Copyright (c) 2004-2017, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * Marker interface for marking an object to not be treated as a id object (even * if the class itself implements id object), this object will not be treated as * normal metadata (no refs etc) but instead need to be contained in the entity * that owns it. * <p> * Embedded objects should also always be implemented as cascade="delete-all-orphan". * * @author Morten Olav Hansen <mortenoh@gmail.com> */ public interface EmbeddedObject { }
vmluan/dhis2-core
dhis-2/dhis-api/src/main/java/org/hisp/dhis/common/EmbeddedObject.java
Java
bsd-3-clause
2,039
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.tabmodel; import android.content.Context; import android.os.Handler; import org.chromium.base.metrics.RecordHistogram; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.Tab; import org.chromium.chrome.browser.compositor.layouts.OverviewModeBehavior; import org.chromium.chrome.browser.compositor.layouts.content.TabContentManager; import org.chromium.chrome.browser.ntp.NativePageFactory; import org.chromium.chrome.browser.tab.TabIdManager; import org.chromium.chrome.browser.tabmodel.OffTheRecordTabModel.OffTheRecordTabModelDelegate; import org.chromium.chrome.browser.tabmodel.TabModel.TabLaunchType; import org.chromium.chrome.browser.tabmodel.TabModel.TabSelectionType; import org.chromium.chrome.browser.tabmodel.TabPersistentStore.TabPersistentStoreObserver; import org.chromium.content_public.browser.LoadUrlParams; import org.chromium.ui.base.WindowAndroid; import java.util.concurrent.atomic.AtomicBoolean; /** * This class manages all the ContentViews in the app. As it manipulates views, it must be * instantiated and used in the UI Thread. It acts as a TabModel which delegates all * TabModel methods to the active model that it contains. */ public class TabModelSelectorImpl extends TabModelSelectorBase implements TabModelDelegate { private final ChromeActivity mActivity; /** Flag set to false when the asynchronous loading of tabs is finished. */ private final AtomicBoolean mSessionRestoreInProgress = new AtomicBoolean(true); private final TabPersistentStore mTabSaver; // This flag signifies the object has gotten an onNativeReady callback and // has not been destroyed. private boolean mActiveState = false; private final TabModelOrderController mOrderController; private OverviewModeBehavior mOverviewModeBehavior; private TabContentManager mTabContentManager; private Tab mVisibleTab; private final TabModelSelectorUma mUma; private CloseAllTabsDelegate mCloseAllTabsDelegate; private ChromeTabCreator mRegularTabCreator; private ChromeTabCreator mIncognitoTabCreator; private static class TabModelImplCreator implements OffTheRecordTabModelDelegate { private final ChromeActivity mActivity; private final TabModelSelectorUma mUma; private final TabModelOrderController mOrderController; private final TabContentManager mTabContentManager; private final TabPersistentStore mTabSaver; private final TabModelDelegate mModelDelegate; /** * Constructor for an Incognito TabModelImpl. * * @param activity The activity owning this TabModel. * @param uma Handles UMA tracking for the model. * @param orderController Determines the order for inserting new Tabs. * @param tabContentManager Manages the display content of the tab. * @param tabSaver Handler for saving tabs. * @param modelDelegate Delegate to handle external dependencies and interactions. */ public TabModelImplCreator(ChromeActivity activity, TabModelSelectorUma uma, TabModelOrderController orderController, TabContentManager tabContentManager, TabPersistentStore tabSaver, TabModelDelegate modelDelegate) { mActivity = activity; mUma = uma; mOrderController = orderController; mTabContentManager = tabContentManager; mTabSaver = tabSaver; mModelDelegate = modelDelegate; } @Override public TabModel createTabModel() { return new TabModelImpl(true, mActivity, mUma, mOrderController, mTabContentManager, mTabSaver, mModelDelegate); } @Override public boolean doOffTheRecordTabsExist() { return TabWindowManager.getInstance().getIncognitoTabCount() > 0; } } /** * Builds a {@link TabModelSelectorImpl} instance. * @param activity The {@link ChromeActivity} this model selector lives in. * @param selectorIndex The index this selector represents in the list of selectors. * @param windowAndroid The {@link WindowAndroid} associated with this model selector. */ public TabModelSelectorImpl(ChromeActivity activity, int selectorIndex, WindowAndroid windowAndroid) { super(); mActivity = activity; mUma = new TabModelSelectorUma(mActivity); final TabPersistentStoreObserver persistentStoreObserver = new TabPersistentStoreObserver() { @Override public void onStateLoaded(Context context) { markTabStateInitialized(); } @Override public void onDetailsRead(int index, int id, String url, boolean isStandardActiveIndex, boolean isIncognitoActiveIndex) { } @Override public void onInitialized(int tabCountAtStartup) { RecordHistogram.recordCountHistogram("Tabs.CountAtStartup", tabCountAtStartup); } }; mTabSaver = new TabPersistentStore(this, selectorIndex, mActivity, mActivity, persistentStoreObserver); mOrderController = new TabModelOrderController(this); mRegularTabCreator = new ChromeTabCreator( mActivity, windowAndroid, mOrderController, mTabSaver, false); mIncognitoTabCreator = new ChromeTabCreator( mActivity, windowAndroid, mOrderController, mTabSaver, true); mActivity.setTabCreators(mRegularTabCreator, mIncognitoTabCreator); } @Override protected void markTabStateInitialized() { super.markTabStateInitialized(); if (!mSessionRestoreInProgress.getAndSet(false)) return; // This is the first time we set // |mSessionRestoreInProgress|, so we need to broadcast. TabModelImpl model = (TabModelImpl) getModel(false); if (model != null) { model.broadcastSessionRestoreComplete(); } else { assert false : "Normal tab model is null after tab state loaded."; } } private void handleOnPageLoadStopped(Tab tab) { if (tab != null) mTabSaver.addTabToSaveQueue(tab); } /** * * @param overviewModeBehavior The {@link OverviewModeBehavior} that should be used to determine * when the app is in overview mode or not. */ public void setOverviewModeBehavior(OverviewModeBehavior overviewModeBehavior) { assert overviewModeBehavior != null; mOverviewModeBehavior = overviewModeBehavior; } /** * Should be called when the app starts showing a view with multiple tabs. */ public void onTabsViewShown() { mUma.onTabsViewShown(); } /** * Should be called once the native library is loaded so that the actual internals of this * class can be initialized. * @param tabContentProvider A {@link TabContentManager} instance. */ public void onNativeLibraryReady(TabContentManager tabContentProvider) { assert !mActiveState : "onNativeLibraryReady called twice!"; mTabContentManager = tabContentProvider; TabModel normalModel = new TabModelImpl(false, mActivity, mUma, mOrderController, mTabContentManager, mTabSaver, this); TabModel incognitoModel = new OffTheRecordTabModel(new TabModelImplCreator( mActivity, mUma, mOrderController, mTabContentManager, mTabSaver, this)); initialize(isIncognitoSelected(), normalModel, incognitoModel); mRegularTabCreator.setTabModel(normalModel, mTabContentManager); mIncognitoTabCreator.setTabModel(incognitoModel, mTabContentManager); mTabSaver.setTabContentManager(tabContentProvider); addObserver(new EmptyTabModelSelectorObserver() { @Override public void onNewTabCreated(Tab tab) { // Only invalidate if the tab exists in the currently selected model. if (TabModelUtils.getTabById(getCurrentModel(), tab.getId()) != null) { mTabContentManager.invalidateIfChanged(tab.getId(), tab.getUrl()); } } }); mActiveState = true; new TabModelSelectorTabObserver(this) { @Override public void onUrlUpdated(Tab tab) { TabModel model = getModelForTabId(tab.getId()); if (model == getCurrentModel()) { mTabContentManager.invalidateIfChanged(tab.getId(), tab.getUrl()); } } @Override public void onLoadStopped(Tab tab) { handleOnPageLoadStopped(tab); } @Override public void onPageLoadStarted(Tab tab, String url) { String previousUrl = tab.getUrl(); if (NativePageFactory.isNativePageUrl(previousUrl, tab.isIncognito())) { mTabContentManager.invalidateTabThumbnail(tab.getId(), previousUrl); } else { mTabContentManager.removeTabThumbnail(tab.getId()); } } @Override public void onPageLoadFinished(Tab tab) { mUma.onPageLoadFinished(tab.getId()); } @Override public void onPageLoadFailed(Tab tab, int errorCode) { mUma.onPageLoadFailed(tab.getId()); } @Override public void onCrash(Tab tab, boolean sadTabShown) { if (sadTabShown) { mTabContentManager.removeTabThumbnail(tab.getId()); } mUma.onTabCrashed(tab.getId()); } }; } @Override public void setCloseAllTabsDelegate(CloseAllTabsDelegate delegate) { mCloseAllTabsDelegate = delegate; } @Override public TabModel getModelAt(int index) { return mActiveState ? super.getModelAt(index) : EmptyTabModel.getInstance(); } @Override public void selectModel(boolean incognito) { TabModel oldModel = getCurrentModel(); super.selectModel(incognito); TabModel newModel = getCurrentModel(); if (oldModel != newModel) { TabModelUtils.setIndex(newModel, newModel.index()); // Make the call to notifyDataSetChanged() after any delayed events // have had a chance to fire. Otherwise, this may result in some // drawing to occur before animations have a chance to work. new Handler().post(new Runnable() { @Override public void run() { notifyChanged(); } }); } } /** * Commits all pending tab closures for all {@link TabModel}s in this {@link TabModelSelector}. */ @Override public void commitAllTabClosures() { for (int i = 0; i < getModels().size(); i++) { getModelAt(i).commitAllTabClosures(); } } @Override public boolean closeAllTabsRequest(boolean incognito) { return mCloseAllTabsDelegate.closeAllTabsRequest(incognito); } public void saveState() { commitAllTabClosures(); mTabSaver.saveState(); } /** * Load the saved tab state. This should be called before any new tabs are created. The saved * tabs shall not be restored until {@link #restoreTabs} is called. */ public void loadState() { int nextId = mTabSaver.loadState(); if (nextId >= 0) TabIdManager.getInstance().incrementIdCounterTo(nextId); } /** * Restore the saved tabs which were loaded by {@link #loadState}. * * @param setActiveTab If true, synchronously load saved active tab and set it as the current * active tab. */ public void restoreTabs(boolean setActiveTab) { mTabSaver.restoreTabs(setActiveTab); } /** * If there is an asynchronous session restore in-progress, try to synchronously restore * the state of a tab with the given url as a frozen tab. This method has no effect if * there isn't a tab being restored with this url, or the tab has already been restored. * * @return true if there exists a tab with the url. */ public boolean tryToRestoreTabStateForUrl(String url) { if (!isSessionRestoreInProgress()) return false; return mTabSaver.restoreTabStateForUrl(url); } /** * If there is an asynchronous session restore in-progress, try to synchronously restore * the state of a tab with the given id as a frozen tab. This method has no effect if * there isn't a tab being restored with this id, or the tab has already been restored. * * @return true if there exists a tab with the id. */ public boolean tryToRestoreTabStateForId(int id) { if (!isSessionRestoreInProgress()) return false; return mTabSaver.restoreTabStateForId(id); } public void clearState() { mTabSaver.clearState(); } public void clearEncryptedState() { mTabSaver.clearEncryptedState(); } @Override public void destroy() { mTabSaver.destroy(); mUma.destroy(); super.destroy(); mActiveState = false; } @Override public Tab openNewTab(LoadUrlParams loadUrlParams, TabLaunchType type, Tab parent, boolean incognito) { return mActivity.getTabCreator(incognito).createNewTab(loadUrlParams, type, parent); } /** * @return Number of restored tabs on cold startup. */ public int getRestoredTabCount() { return mTabSaver.getRestoredTabCount(); } @Override public void requestToShowTab(Tab tab, TabSelectionType type) { boolean isFromExternalApp = tab != null && tab.getLaunchType() == TabLaunchType.FROM_EXTERNAL_APP; if (mVisibleTab != tab && tab != null && !tab.isNativePage()) { TabModelBase.startTabSwitchLatencyTiming(type); } if (mVisibleTab != null && mVisibleTab != tab && !mVisibleTab.needsReload()) { if (mVisibleTab.isInitialized()) { // TODO(dtrainor): Once we figure out why we can't grab a snapshot from the current // tab when we have other tabs loading from external apps remove the checks for // FROM_EXTERNAL_APP/FROM_NEW. if (!mVisibleTab.isClosing() && (!isFromExternalApp || type != TabSelectionType.FROM_NEW)) { cacheTabBitmap(mVisibleTab); } mVisibleTab.hide(); mVisibleTab.setFullscreenManager(null); mTabSaver.addTabToSaveQueue(mVisibleTab); } mVisibleTab = null; } if (tab == null) { notifyChanged(); return; } // We hit this case when the user enters tab switcher and comes back to the current tab // without actual tab switch. if (mVisibleTab == tab && !mVisibleTab.isHidden()) { // The current tab might have been killed by the os while in tab switcher. tab.loadIfNeeded(); return; } tab.setFullscreenManager(mActivity.getFullscreenManager()); mVisibleTab = tab; // Don't execute the tab display part if Chrome has just been sent to background. This // avoids uneccessary work (tab restore) and prevents pollution of tab display metrics - see // http://crbug.com/316166. if (type != TabSelectionType.FROM_EXIT) { tab.show(type); mUma.onShowTab(tab.getId(), tab.isBeingRestored()); } } private void cacheTabBitmap(Tab tabToCache) { // Trigger a capture of this tab. if (tabToCache == null) return; mTabContentManager.cacheTabThumbnail(tabToCache); } @Override public boolean isInOverviewMode() { return mOverviewModeBehavior != null && mOverviewModeBehavior.overviewVisible(); } @Override public boolean isSessionRestoreInProgress() { return mSessionRestoreInProgress.get(); } // TODO(tedchoc): Remove the need for this to be exposed. @Override public void notifyChanged() { super.notifyChanged(); } }
SaschaMester/delicium
chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabModelSelectorImpl.java
Java
bsd-3-clause
16,822
package hep.aida.bin; import cern.colt.list.DoubleArrayList; import cern.jet.stat.Descriptive; /** * Static and the same as its superclass, except that it can do more: Additionally computes moments of arbitrary integer order, harmonic mean, geometric mean, etc. * * Constructors need to be told what functionality is required for the given use case. * Only maintains aggregate measures (incrementally) - the added elements themselves are not kept. * * @author wolfgang.hoschek@cern.ch * @version 0.9, 03-Jul-99 */ public class MightyStaticBin1D extends StaticBin1D { protected boolean hasSumOfLogarithms = false; protected double sumOfLogarithms = 0.0; // Sum( Log(x[i]) ) protected boolean hasSumOfInversions = false; protected double sumOfInversions = 0.0; // Sum( 1/x[i] ) protected double[] sumOfPowers = null; // Sum( x[i]^3 ) .. Sum( x[i]^max_k ) /** * Constructs and returns an empty bin with limited functionality but good performance; equivalent to <tt>MightyStaticBin1D(false,false,4)</tt>. */ public MightyStaticBin1D() { this(false, false, 4); } /** * Constructs and returns an empty bin with the given capabilities. * * @param hasSumOfLogarithms Tells whether {@link #sumOfLogarithms()} can return meaningful results. * Set this parameter to <tt>false</tt> if measures of sum of logarithms, geometric mean and product are not required. * <p> * @param hasSumOfInversions Tells whether {@link #sumOfInversions()} can return meaningful results. * Set this parameter to <tt>false</tt> if measures of sum of inversions, harmonic mean and sumOfPowers(-1) are not required. * <p> * @param maxOrderForSumOfPowers The maximum order <tt>k</tt> for which {@link #sumOfPowers(int)} can return meaningful results. * Set this parameter to at least 3 if the skew is required, to at least 4 if the kurtosis is required. * In general, if moments are required set this parameter at least as large as the largest required moment. * This method always substitutes <tt>Math.max(2,maxOrderForSumOfPowers)</tt> for the parameter passed in. * Thus, <tt>sumOfPowers(0..2)</tt> always returns meaningful results. * * @see #hasSumOfPowers(int) * @see #moment(int,double) */ public MightyStaticBin1D(boolean hasSumOfLogarithms, boolean hasSumOfInversions, int maxOrderForSumOfPowers) { setMaxOrderForSumOfPowers(maxOrderForSumOfPowers); this.hasSumOfLogarithms = hasSumOfLogarithms; this.hasSumOfInversions = hasSumOfInversions; this.clear(); } /** * Adds the part of the specified list between indexes <tt>from</tt> (inclusive) and <tt>to</tt> (inclusive) to the receiver. * * @param list the list of which elements shall be added. * @param from the index of the first element to be added (inclusive). * @param to the index of the last element to be added (inclusive). * @throws IndexOutOfBoundsException if <tt>list.size()&gt;0 && (from&lt;0 || from&gt;to || to&gt;=list.size())</tt>. */ public synchronized void addAllOfFromTo(DoubleArrayList list, int from, int to) { super.addAllOfFromTo(list, from, to); if (this.sumOfPowers != null) { //int max_k = this.min_k + this.sumOfPowers.length-1; Descriptive.incrementalUpdateSumsOfPowers(list, from, to, 3, getMaxOrderForSumOfPowers(), this.sumOfPowers); } if (this.hasSumOfInversions) { this.sumOfInversions += Descriptive.sumOfInversions(list, from, to); } if (this.hasSumOfLogarithms) { this.sumOfLogarithms += Descriptive.sumOfLogarithms(list, from, to); } } /** * Resets the values of all measures. */ protected void clearAllMeasures() { super.clearAllMeasures(); this.sumOfLogarithms = 0.0; this.sumOfInversions = 0.0; if (this.sumOfPowers != null) { for (int i=this.sumOfPowers.length; --i >=0; ) { this.sumOfPowers[i] = 0.0; } } } /** * Returns a deep copy of the receiver. * * @return a deep copy of the receiver. */ public synchronized Object clone() { MightyStaticBin1D clone = (MightyStaticBin1D) super.clone(); if (this.sumOfPowers != null) clone.sumOfPowers = (double[]) clone.sumOfPowers.clone(); return clone; } /** * Computes the deviations from the receiver's measures to another bin's measures. * @param other the other bin to compare with * @return a summary of the deviations. */ public String compareWith(AbstractBin1D other) { StringBuffer buf = new StringBuffer(super.compareWith(other)); if (other instanceof MightyStaticBin1D) { MightyStaticBin1D m = (MightyStaticBin1D) other; if (hasSumOfLogarithms() && m.hasSumOfLogarithms()) buf.append("geometric mean: "+relError(geometricMean(),m.geometricMean()) +" %\n"); if (hasSumOfInversions() && m.hasSumOfInversions()) buf.append("harmonic mean: "+relError(harmonicMean(),m.harmonicMean()) +" %\n"); if (hasSumOfPowers(3) && m.hasSumOfPowers(3)) buf.append("skew: "+relError(skew(),m.skew()) +" %\n"); if (hasSumOfPowers(4) && m.hasSumOfPowers(4)) buf.append("kurtosis: "+relError(kurtosis(),m.kurtosis()) +" %\n"); buf.append("\n"); } return buf.toString(); } /** * Returns the geometric mean, which is <tt>Product( x[i] )<sup>1.0/size()</sup></tt>. * * This method tries to avoid overflows at the expense of an equivalent but somewhat inefficient definition: * <tt>geoMean = exp( Sum( Log(x[i]) ) / size())</tt>. * Note that for a geometric mean to be meaningful, the minimum of the data sequence must not be less or equal to zero. * @return the geometric mean; <tt>Double.NaN</tt> if <tt>!hasSumOfLogarithms()</tt>. */ public synchronized double geometricMean() { return Descriptive.geometricMean(size(), sumOfLogarithms()); } /** * Returns the maximum order <tt>k</tt> for which sums of powers are retrievable, as specified upon instance construction. * @see #hasSumOfPowers(int) * @see #sumOfPowers(int) */ public synchronized int getMaxOrderForSumOfPowers() { /* order 0..2 is always recorded. order 0 is size() order 1 is sum() order 2 is sum_xx() */ if (this.sumOfPowers == null) return 2; return 2 + this.sumOfPowers.length; } /** * Returns the minimum order <tt>k</tt> for which sums of powers are retrievable, as specified upon instance construction. * @see #hasSumOfPowers(int) * @see #sumOfPowers(int) */ public synchronized int getMinOrderForSumOfPowers() { int minOrder = 0; if (hasSumOfInversions()) minOrder = -1; return minOrder; } /** * Returns the harmonic mean, which is <tt>size() / Sum( 1/x[i] )</tt>. * Remember: If the receiver contains at least one element of <tt>0.0</tt>, the harmonic mean is <tt>0.0</tt>. * @return the harmonic mean; <tt>Double.NaN</tt> if <tt>!hasSumOfInversions()</tt>. * @see #hasSumOfInversions() */ public synchronized double harmonicMean() { return Descriptive.harmonicMean(size(), sumOfInversions()); } /** * Returns whether <tt>sumOfInversions()</tt> can return meaningful results. * @return <tt>false</tt> if the bin was constructed with insufficient parametrization, <tt>true</tt> otherwise. * See the constructors for proper parametrization. */ public boolean hasSumOfInversions() { return this.hasSumOfInversions; } /** * Tells whether <tt>sumOfLogarithms()</tt> can return meaningful results. * @return <tt>false</tt> if the bin was constructed with insufficient parametrization, <tt>true</tt> otherwise. * See the constructors for proper parametrization. */ public boolean hasSumOfLogarithms() { return this.hasSumOfLogarithms; } /** * Tells whether <tt>sumOfPowers(k)</tt> can return meaningful results. * Defined as <tt>hasSumOfPowers(k) <==> getMinOrderForSumOfPowers() <= k && k <= getMaxOrderForSumOfPowers()</tt>. * A return value of <tt>true</tt> implies that <tt>hasSumOfPowers(k-1) .. hasSumOfPowers(0)</tt> will also return <tt>true</tt>. * See the constructors for proper parametrization. * <p> * <b>Details</b>: * <tt>hasSumOfPowers(0..2)</tt> will always yield <tt>true</tt>. * <tt>hasSumOfPowers(-1) <==> hasSumOfInversions()</tt>. * * @return <tt>false</tt> if the bin was constructed with insufficient parametrization, <tt>true</tt> otherwise. * @see #getMinOrderForSumOfPowers() * @see #getMaxOrderForSumOfPowers() */ public boolean hasSumOfPowers(int k) { return getMinOrderForSumOfPowers() <= k && k <= getMaxOrderForSumOfPowers(); } /** * Returns the kurtosis (aka excess), which is <tt>-3 + moment(4,mean()) / standardDeviation()<sup>4</sup></tt>. * @return the kurtosis; <tt>Double.NaN</tt> if <tt>!hasSumOfPowers(4)</tt>. * @see #hasSumOfPowers(int) */ public synchronized double kurtosis() { return Descriptive.kurtosis( moment(4,mean()), standardDeviation() ); } /** * Returns the moment of <tt>k</tt>-th order with value <tt>c</tt>, * which is <tt>Sum( (x[i]-c)<sup>k</sup> ) / size()</tt>. * * @param k the order; must be greater than or equal to zero. * @param c any number. * @throws IllegalArgumentException if <tt>k < 0</tt>. * @return <tt>Double.NaN</tt> if <tt>!hasSumOfPower(k)</tt>. */ public synchronized double moment(int k, double c) { if (k<0) throw new IllegalArgumentException("k must be >= 0"); //checkOrder(k); if (!hasSumOfPowers(k)) return Double.NaN; int maxOrder = Math.min(k,getMaxOrderForSumOfPowers()); DoubleArrayList sumOfPows = new DoubleArrayList(maxOrder+1); sumOfPows.add(size()); sumOfPows.add(sum()); sumOfPows.add(sumOfSquares()); for (int i=3; i<=maxOrder; i++) sumOfPows.add(sumOfPowers(i)); return Descriptive.moment(k, c, size(), sumOfPows.elements()); } /** * Returns the product, which is <tt>Prod( x[i] )</tt>. * In other words: <tt>x[0]*x[1]*...*x[size()-1]</tt>. * @return the product; <tt>Double.NaN</tt> if <tt>!hasSumOfLogarithms()</tt>. * @see #hasSumOfLogarithms() */ public double product() { return Descriptive.product(size(), sumOfLogarithms()); } /** * Sets the range of orders in which sums of powers are to be computed. * In other words, <tt>sumOfPower(k)</tt> will return <tt>Sum( x[i]^k )</tt> if <tt>min_k <= k <= max_k || 0 <= k <= 2</tt> * and throw an exception otherwise. * @see #isLegalOrder(int) * @see #sumOfPowers(int) * @see #getRangeForSumOfPowers() */ protected void setMaxOrderForSumOfPowers(int max_k) { //if (max_k < ) throw new IllegalArgumentException(); if (max_k <=2) { this.sumOfPowers = null; } else { this.sumOfPowers = new double[max_k - 2]; } } /** * Returns the skew, which is <tt>moment(3,mean()) / standardDeviation()<sup>3</sup></tt>. * @return the skew; <tt>Double.NaN</tt> if <tt>!hasSumOfPowers(3)</tt>. * @see #hasSumOfPowers(int) */ public synchronized double skew() { return Descriptive.skew( moment(3,mean()), standardDeviation() ); } /** * Returns the sum of inversions, which is <tt>Sum( 1 / x[i] )</tt>. * @return the sum of inversions; <tt>Double.NaN</tt> if <tt>!hasSumOfInversions()</tt>. * @see #hasSumOfInversions() */ public double sumOfInversions() { if (! this.hasSumOfInversions) return Double.NaN; //if (! this.hasSumOfInversions) throw new IllegalOperationException("You must specify upon instance construction that the sum of inversions shall be computed."); return this.sumOfInversions; } /** * Returns the sum of logarithms, which is <tt>Sum( Log(x[i]) )</tt>. * @return the sum of logarithms; <tt>Double.NaN</tt> if <tt>!hasSumOfLogarithms()</tt>. * @see #hasSumOfLogarithms() */ public synchronized double sumOfLogarithms() { if (! this.hasSumOfLogarithms) return Double.NaN; //if (! this.hasSumOfLogarithms) throw new IllegalOperationException("You must specify upon instance construction that the sum of logarithms shall be computed."); return this.sumOfLogarithms; } /** * Returns the <tt>k-th</tt> order sum of powers, which is <tt>Sum( x[i]<sup>k</sup> )</tt>. * @param k the order of the powers. * @return the sum of powers; <tt>Double.NaN</tt> if <tt>!hasSumOfPowers(k)</tt>. * @see #hasSumOfPowers(int) */ public synchronized double sumOfPowers(int k) { if (!hasSumOfPowers(k)) return Double.NaN; //checkOrder(k); if (k == -1) return sumOfInversions(); if (k == 0) return size(); if (k == 1) return sum(); if (k == 2) return sumOfSquares(); return this.sumOfPowers[k-3]; } /** * Returns a String representation of the receiver. */ public synchronized String toString() { StringBuffer buf = new StringBuffer(super.toString()); if (hasSumOfLogarithms()) { buf.append("Geometric mean: "+geometricMean()); buf.append("\nProduct: "+product()+"\n"); } if (hasSumOfInversions()) { buf.append("Harmonic mean: "+harmonicMean()); buf.append("\nSum of inversions: "+sumOfInversions()+"\n"); } int maxOrder = getMaxOrderForSumOfPowers(); int maxPrintOrder = Math.min(6,maxOrder); // don't print tons of measures if (maxOrder>2) { if (maxOrder>=3) { buf.append("Skew: "+skew()+"\n"); } if (maxOrder>=4) { buf.append("Kurtosis: "+kurtosis()+"\n"); } for (int i=3; i<=maxPrintOrder; i++) { buf.append("Sum of powers("+i+"): "+sumOfPowers(i)+"\n"); } for (int k=0; k<=maxPrintOrder; k++) { buf.append("Moment("+k+",0): "+moment(k,0)+"\n"); } for (int k=0; k<=maxPrintOrder; k++) { buf.append("Moment("+k+",mean()): "+moment(k,mean())+"\n"); } } return buf.toString(); } /** * @throws IllegalOperationException if <tt>! isLegalOrder(k)</tt>. */ protected void xcheckOrder(int k) { //if (! isLegalOrder(k)) return Double.NaN; //if (! xisLegalOrder(k)) throw new IllegalOperationException("Illegal order of sum of powers: k="+k+". Upon instance construction legal range was fixed to be "+getMinOrderForSumOfPowers()+" <= k <= "+getMaxOrderForSumOfPowers()); } /** * Returns whether two bins are equal; * They are equal if the other object is of the same class or a subclass of this class and both have the same size, minimum, maximum, sum, sumOfSquares, sumOfInversions and sumOfLogarithms. */ protected boolean xequals(Object object) { if (!(object instanceof MightyStaticBin1D)) return false; MightyStaticBin1D other = (MightyStaticBin1D) object; return super.equals(other) && sumOfInversions()==other.sumOfInversions() && sumOfLogarithms()==other.sumOfLogarithms(); } /** * Tells whether <tt>sumOfPowers(fromK) .. sumOfPowers(toK)</tt> can return meaningful results. * @return <tt>false</tt> if the bin was constructed with insufficient parametrization, <tt>true</tt> otherwise. * See the constructors for proper parametrization. * @throws IllegalArgumentException if <tt>fromK > toK</tt>. */ protected boolean xhasSumOfPowers(int fromK, int toK) { if (fromK > toK) throw new IllegalArgumentException("fromK must be less or equal to toK"); return getMinOrderForSumOfPowers() <= fromK && toK <= getMaxOrderForSumOfPowers(); } /** * Returns <tt>getMinOrderForSumOfPowers() <= k && k <= getMaxOrderForSumOfPowers()</tt>. */ protected synchronized boolean xisLegalOrder(int k) { return getMinOrderForSumOfPowers() <= k && k <= getMaxOrderForSumOfPowers(); } }
tobyclemson/msci-project
vendor/colt-1.2.0/src/hep/aida/bin/MightyStaticBin1D.java
Java
mit
15,232
package org.multibit.exchange; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import javax.swing.SwingUtilities; import org.multibit.controller.Controller; import org.multibit.model.exchange.ExchangeData; import org.multibit.model.exchange.ExchangeModel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.joda.money.CurrencyUnit; import org.joda.money.IllegalCurrencyException; import org.joda.money.Money; import org.joda.money.format.MoneyAmountStyle; import org.joda.money.format.MoneyFormatter; import org.joda.money.format.MoneyFormatterBuilder; public enum CurrencyConverter { INSTANCE; private static final Logger log = LoggerFactory.getLogger(CurrencyConverter.class); private Controller controller; private Collection<CurrencyConverterListener> listeners; public static final BigInteger NUMBER_OF_SATOSHI_IN_ONE_BITCOIN = BigInteger.valueOf(100000000); // 8 zeros public static final int NUMBER_OF_DECIMAL_POINTS_IN_A_BITCOIN = 8; // Extra digits used in calculation. public static final int ADDITIONAL_CALCULATION_DIGITS = 16; // This is the Bitcoin currency unit, denominated in satoshi with 0 decimal places. public CurrencyUnit BITCOIN_CURRENCY_UNIT; /** * The currency unit for the currency being converted. */ private CurrencyUnit currencyUnit; /** * MoneyFormatter without currency code */ MoneyFormatter moneyFormatter; /** * MoneyFormatter with currency code */ MoneyFormatter moneyFormatterWithCurrencyCode; /** * The exchange rate i.e the value of 1 BTC in the currency. */ private BigDecimal rate; /** * The rate rate in terms of satoshi i.e. value of 1 satoshi in the currency */ private BigDecimal rateDividedByNumberOfSatoshiInOneBitcoin; private String groupingSeparator; /** * Map of currency code to currency info. */ private Map<String, CurrencyInfo> currencyCodeToInfoMap; /** * Map of currency code to currency description (from OpenExchangeRates) */ private Map<String, String> currencyCodeToDescriptionMap; public void initialise(Controller controller) { // Initialise conversion currency. String currencyCode = controller.getModel().getUserPreference(ExchangeModel.TICKER_FIRST_ROW_CURRENCY); String exchange = controller.getModel().getUserPreference(ExchangeModel.TICKER_FIRST_ROW_EXCHANGE); String newCurrencyCode = currencyCode; if (ExchangeData.BITCOIN_CHARTS_EXCHANGE_NAME.equals(exchange)) { // Use only the last three characters - the currency code. if (currencyCode.length() >= 3) { newCurrencyCode = currencyCode.substring(currencyCode.length() - 3); } } initialise(controller, newCurrencyCode); } public void initialise(Controller controller, String currencyCode) { this.controller = controller; try { BITCOIN_CURRENCY_UNIT = CurrencyUnit.of("BTC"); if (currencyCode != null && !"".equals(currencyCode)) { currencyUnit = CurrencyUnit.of(currencyCode); } else { currencyUnit = CurrencyUnit.of("USD"); } } catch (IllegalCurrencyException ice) { ice.printStackTrace(); // Default to USD. currencyUnit = CurrencyUnit.of("USD"); } // Exchange rate is unknown. rate = null; rateDividedByNumberOfSatoshiInOneBitcoin = null; // Setup listeners listeners = new ArrayList<CurrencyConverterListener>(); // Initialise currency info map. currencyCodeToInfoMap = new HashMap<String, CurrencyInfo>(); currencyCodeToInfoMap.put("USD", new CurrencyInfo("USD", "$", true)); currencyCodeToInfoMap.put("AUD", new CurrencyInfo("AUD", "AU$", true)); currencyCodeToInfoMap.put("CAD", new CurrencyInfo("CAD", "CA$", true)); currencyCodeToInfoMap.put("NZD", new CurrencyInfo("NZD", "NZ$", true)); currencyCodeToInfoMap.put("SGD", new CurrencyInfo("SGD", "SG$", true)); currencyCodeToInfoMap.put("HKD", new CurrencyInfo("HKD", "HK$", true)); currencyCodeToInfoMap.put("GBP", new CurrencyInfo("GBP", "\u00A3", true)); currencyCodeToInfoMap.put("EUR", new CurrencyInfo("EUR", "\u20AC", true)); currencyCodeToInfoMap.put("CHF", new CurrencyInfo("CHF", "Fr.", true)); currencyCodeToInfoMap.put("JPY", new CurrencyInfo("JPY", "\u00A5", true)); currencyCodeToInfoMap.put("CNY", new CurrencyInfo("CNY", "\u5143", false)); currencyCodeToInfoMap.put("RUB", new CurrencyInfo("RUB", "\u0440\u0443\u0431", false)); currencyCodeToInfoMap.put("SEK", new CurrencyInfo("SEK", "\u006B\u0072", true)); currencyCodeToInfoMap.put("DKK", new CurrencyInfo("DKK", "\u006B\u0072.", true)); currencyCodeToInfoMap.put("THB", new CurrencyInfo("THB", "\u0E3F", true)); currencyCodeToInfoMap.put("PLN", new CurrencyInfo("PLN", "\u007A\u0142", false)); updateFormatters(); // Initialise currency description map. currencyCodeToDescriptionMap = new HashMap<String, String>(); currencyCodeToDescriptionMap.put("AED", "United Arab Emirates Dirham"); currencyCodeToDescriptionMap.put("AFN", "Afghan Afghani"); currencyCodeToDescriptionMap.put("ALL", "Albanian Lek"); currencyCodeToDescriptionMap.put("AMD", "Armenian Dram"); currencyCodeToDescriptionMap.put("ANG", "Netherlands Antillean Guilder"); currencyCodeToDescriptionMap.put("AOA", "Angolan Kwanza"); currencyCodeToDescriptionMap.put("ARS", "Argentine Peso"); currencyCodeToDescriptionMap.put("AUD", "Australian Dollar"); currencyCodeToDescriptionMap.put("AWG", "Aruban Florin"); currencyCodeToDescriptionMap.put("AZN", "Azerbaijani Manat"); currencyCodeToDescriptionMap.put("BAM", "Bosnia-Herzegovina Convertible Mark"); currencyCodeToDescriptionMap.put("BBD", "Barbadian Dollar"); currencyCodeToDescriptionMap.put("BDT", "Bangladeshi Taka"); currencyCodeToDescriptionMap.put("BGN", "Bulgarian Lev"); currencyCodeToDescriptionMap.put("BHD", "Bahraini Dinar"); currencyCodeToDescriptionMap.put("BIF", "Burundian Franc"); currencyCodeToDescriptionMap.put("BMD", "Bermudan Dollar"); currencyCodeToDescriptionMap.put("BND", "Brunei Dollar"); currencyCodeToDescriptionMap.put("BOB", "Bolivian Boliviano"); currencyCodeToDescriptionMap.put("BRL", "Brazilian Real"); currencyCodeToDescriptionMap.put("BSD", "Bahamian Dollar"); currencyCodeToDescriptionMap.put("BTC", "Bitcoin"); currencyCodeToDescriptionMap.put("BTN", "Bhutanese Ngultrum"); currencyCodeToDescriptionMap.put("BWP", "Botswanan Pula"); currencyCodeToDescriptionMap.put("BYR", "Belarusian Ruble"); currencyCodeToDescriptionMap.put("BZD", "Belize Dollar"); currencyCodeToDescriptionMap.put("CAD", "Canadian Dollar"); currencyCodeToDescriptionMap.put("CDF", "Congolese Franc"); currencyCodeToDescriptionMap.put("CHF", "Swiss Franc"); currencyCodeToDescriptionMap.put("CLP", "Chilean Peso"); currencyCodeToDescriptionMap.put("CNY", "Chinese Yuan"); currencyCodeToDescriptionMap.put("COP", "Colombian Peso"); currencyCodeToDescriptionMap.put("CRC", "Costa Rican Col\u00F3n"); currencyCodeToDescriptionMap.put("CUP", "Cuban Peso"); currencyCodeToDescriptionMap.put("CVE", "Cape Verdean Escudo"); currencyCodeToDescriptionMap.put("CZK", "Czech Republic Koruna"); currencyCodeToDescriptionMap.put("DJF", "Djiboutian Franc"); currencyCodeToDescriptionMap.put("DKK", "Danish Krone"); currencyCodeToDescriptionMap.put("DOP", "Dominican Peso"); currencyCodeToDescriptionMap.put("DZD", "Algerian Dinar"); currencyCodeToDescriptionMap.put("EGP", "Egyptian Pound"); currencyCodeToDescriptionMap.put("ETB", "Ethiopian Birr"); currencyCodeToDescriptionMap.put("EUR", "Euro"); currencyCodeToDescriptionMap.put("FJD", "Fijian Dollar"); currencyCodeToDescriptionMap.put("FKP", "Falkland Islands Pound"); currencyCodeToDescriptionMap.put("GBP", "British Pound Sterling"); currencyCodeToDescriptionMap.put("GEL", "Georgian Lari"); currencyCodeToDescriptionMap.put("GHS", "Ghanaian Cedi"); currencyCodeToDescriptionMap.put("GIP", "Gibraltar Pound"); currencyCodeToDescriptionMap.put("GMD", "Gambian Dalasi"); currencyCodeToDescriptionMap.put("GNF", "Guinean Franc"); currencyCodeToDescriptionMap.put("GTQ", "Guatemalan Quetzal"); currencyCodeToDescriptionMap.put("GYD", "Guyanaese Dollar"); currencyCodeToDescriptionMap.put("HKD", "Hong Kong Dollar"); currencyCodeToDescriptionMap.put("HNL", "Honduran Lempira"); currencyCodeToDescriptionMap.put("HRK", "Croatian Kuna"); currencyCodeToDescriptionMap.put("HTG", "Haitian Gourde"); currencyCodeToDescriptionMap.put("HUF", "Hungarian Forint"); currencyCodeToDescriptionMap.put("IDR", "Indonesian Rupiah"); currencyCodeToDescriptionMap.put("ILS", "Israeli New Sheqel"); currencyCodeToDescriptionMap.put("INR", "Indian Rupee"); currencyCodeToDescriptionMap.put("IQD", "Iraqi Dinar"); currencyCodeToDescriptionMap.put("IRR", "Iranian Rial"); currencyCodeToDescriptionMap.put("ISK", "Icelandic Kr\u00F3na"); currencyCodeToDescriptionMap.put("JMD", "Jamaican Dollar"); currencyCodeToDescriptionMap.put("JOD", "Jordanian Dinar"); currencyCodeToDescriptionMap.put("JPY", "Japanese Yen"); currencyCodeToDescriptionMap.put("KES", "Kenyan Shilling"); currencyCodeToDescriptionMap.put("KGS", "Kyrgystani Som"); currencyCodeToDescriptionMap.put("KHR", "Cambodian Riel"); currencyCodeToDescriptionMap.put("KMF", "Comorian Franc"); currencyCodeToDescriptionMap.put("KPW", "North Korean Won"); currencyCodeToDescriptionMap.put("KRW", "South Korean Won"); currencyCodeToDescriptionMap.put("KWD", "Kuwaiti Dinar"); currencyCodeToDescriptionMap.put("KYD", "Cayman Islands Dollar"); currencyCodeToDescriptionMap.put("KZT", "Kazakhstani Tenge"); currencyCodeToDescriptionMap.put("LAK", "Laotian Kip"); currencyCodeToDescriptionMap.put("LBP", "Lebanese Pound"); currencyCodeToDescriptionMap.put("LKR", "Sri Lankan Rupee"); currencyCodeToDescriptionMap.put("LRD", "Liberian Dollar"); currencyCodeToDescriptionMap.put("LSL", "Lesotho Loti"); currencyCodeToDescriptionMap.put("LTL", "Lithuanian Litas"); currencyCodeToDescriptionMap.put("LVL", "Latvian Lats"); currencyCodeToDescriptionMap.put("LYD", "Libyan Dinar"); currencyCodeToDescriptionMap.put("MAD", "Moroccan Dirham"); currencyCodeToDescriptionMap.put("MDL", "Moldovan Leu"); currencyCodeToDescriptionMap.put("MGA", "Malagasy Ariary"); currencyCodeToDescriptionMap.put("MKD", "Macedonian Denar"); currencyCodeToDescriptionMap.put("MMK", "Myanma Kyat"); currencyCodeToDescriptionMap.put("MNT", "Mongolian Tugrik"); currencyCodeToDescriptionMap.put("MOP", "Macanese Pataca"); currencyCodeToDescriptionMap.put("MRO", "Mauritanian Ouguiya"); currencyCodeToDescriptionMap.put("MUR", "Mauritian Rupee"); currencyCodeToDescriptionMap.put("MVR", "Maldivian Rufiyaa"); currencyCodeToDescriptionMap.put("MWK", "Malawian Kwacha"); currencyCodeToDescriptionMap.put("MXN", "Mexican Peso"); currencyCodeToDescriptionMap.put("MYR", "Malaysian Ringgit"); currencyCodeToDescriptionMap.put("MZN", "Mozambican Metical"); currencyCodeToDescriptionMap.put("NAD", "Namibian Dollar"); currencyCodeToDescriptionMap.put("NGN", "Nigerian Naira"); currencyCodeToDescriptionMap.put("NIO", "Nicaraguan C\u00F3rdoba"); currencyCodeToDescriptionMap.put("NOK", "Norwegian Krone"); currencyCodeToDescriptionMap.put("NPR", "Nepalese Rupee"); currencyCodeToDescriptionMap.put("NZD", "New Zealand Dollar"); currencyCodeToDescriptionMap.put("OMR", "Omani Rial"); currencyCodeToDescriptionMap.put("PAB", "Panamanian Balboa"); currencyCodeToDescriptionMap.put("PEN", "Peruvian Nuevo Sol"); currencyCodeToDescriptionMap.put("PGK", "Papua New Guinean Kina"); currencyCodeToDescriptionMap.put("PHP", "Philippine Peso"); currencyCodeToDescriptionMap.put("PKR", "Pakistani Rupee"); currencyCodeToDescriptionMap.put("PLN", "Polish Zloty"); currencyCodeToDescriptionMap.put("PYG", "Paraguayan Guarani"); currencyCodeToDescriptionMap.put("QAR", "Qatari Rial"); currencyCodeToDescriptionMap.put("RON", "Romanian Leu"); currencyCodeToDescriptionMap.put("RSD", "Serbian Dinar"); currencyCodeToDescriptionMap.put("RUB", "Russian Ruble"); currencyCodeToDescriptionMap.put("RWF", "Rwandan Franc"); currencyCodeToDescriptionMap.put("SAR", "Saudi Riyal"); currencyCodeToDescriptionMap.put("SBD", "Solomon Islands Dollar"); currencyCodeToDescriptionMap.put("SCR", "Seychellois Rupee"); currencyCodeToDescriptionMap.put("SDG", "Sudanese Pound"); currencyCodeToDescriptionMap.put("SEK", "Swedish Krona"); currencyCodeToDescriptionMap.put("SGD", "Singapore Dollar"); currencyCodeToDescriptionMap.put("SHP", "Saint Helena Pound"); currencyCodeToDescriptionMap.put("SLL", "Sierra Leonean Leone"); currencyCodeToDescriptionMap.put("SOS", "Somali Shilling"); currencyCodeToDescriptionMap.put("SRD", "Surinamese Dollar"); currencyCodeToDescriptionMap.put("STD", "S\u0101o Tom\u00E9 and Principe Dobra"); currencyCodeToDescriptionMap.put("SYP", "Syrian Pound"); currencyCodeToDescriptionMap.put("SZL", "Swazi Lilangeni"); currencyCodeToDescriptionMap.put("THB", "Thai Baht"); currencyCodeToDescriptionMap.put("TJS", "Tajikistani Somoni"); currencyCodeToDescriptionMap.put("TMT", "Turkmenistani Manat"); currencyCodeToDescriptionMap.put("TND", "Tunisian Dinar"); currencyCodeToDescriptionMap.put("TOP", "Tongan Pa'anga"); currencyCodeToDescriptionMap.put("TRY", "Turkish Lira"); currencyCodeToDescriptionMap.put("TTD", "Trinidad and Tobago Dollar"); currencyCodeToDescriptionMap.put("TWD", "New Taiwan Dollar"); currencyCodeToDescriptionMap.put("TZS", "Tanzanian Shilling"); currencyCodeToDescriptionMap.put("UAH", "Ukrainian Hryvnia"); currencyCodeToDescriptionMap.put("UGX", "Ugandan Shilling"); currencyCodeToDescriptionMap.put("USD", "United States Dollar"); currencyCodeToDescriptionMap.put("UYU", "Uruguayan Peso"); currencyCodeToDescriptionMap.put("UZS", "Uzbekistan Som"); currencyCodeToDescriptionMap.put("VEF", "Venezuelan Bol\u00EDvar"); currencyCodeToDescriptionMap.put("VND", "Vietnamese Dong"); currencyCodeToDescriptionMap.put("VUV", "Vanuatu Vatu"); currencyCodeToDescriptionMap.put("WST", "Samoan Tala"); currencyCodeToDescriptionMap.put("XAF", "CFA Franc BEAC"); currencyCodeToDescriptionMap.put("XCD", "East Caribbean Dollar"); currencyCodeToDescriptionMap.put("XDR", "Special Drawing Rights"); currencyCodeToDescriptionMap.put("XOF", "CFA Franc BCEAO"); currencyCodeToDescriptionMap.put("XPF", "CFP Franc"); currencyCodeToDescriptionMap.put("YER", "Yemeni Rial"); currencyCodeToDescriptionMap.put("ZAR", "South African Rand"); currencyCodeToDescriptionMap.put("ZMK", "Zambian Kwacha"); currencyCodeToDescriptionMap.put("ZWL", "Zimbabwean Dollar"); } public void updateFormatters() { moneyFormatter = getMoneyFormatter(false); moneyFormatterWithCurrencyCode = getMoneyFormatter(true); DecimalFormat fiatFormatter = (DecimalFormat) DecimalFormat.getInstance(controller.getLocaliser().getLocale()); groupingSeparator = String.valueOf(fiatFormatter.getDecimalFormatSymbols().getGroupingSeparator()); } /** * Convert a number of satoshis to fiat * @param bitcoinAmount in satoshis * @return equivalent fiat amount */ public Money convertFromBTCToFiat(BigInteger bitcoinAmountInSatoshi) { if (rate == null) { return null; } else { Money bitcoin = Money.of(BITCOIN_CURRENCY_UNIT, new BigDecimal(bitcoinAmountInSatoshi)); Money fiatAmount = null; if (rateDividedByNumberOfSatoshiInOneBitcoin != null) { fiatAmount = bitcoin.convertedTo(currencyUnit, rateDividedByNumberOfSatoshiInOneBitcoin, RoundingMode.HALF_EVEN); } return fiatAmount; } } public CurrencyConverterResult convertFromFiatToBTC(String fiat) { if (rate == null || rate.equals(BigDecimal.ZERO)) { return new CurrencyConverterResult(); } else { if (fiat == null || fiat.trim().equals("")) { return new CurrencyConverterResult(); } Money btcAmount = null; DecimalFormat formatter = (DecimalFormat) DecimalFormat.getInstance(controller.getLocaliser().getLocale()); formatter.setParseBigDecimal(true); // Convert spaces to non breakable space. fiat = fiat.replaceAll(" ", "\u00A0"); try { BigDecimal parsedFiat = (BigDecimal)formatter.parse(fiat); Money fiatMoney = Money.of(currencyUnit, parsedFiat); btcAmount = fiatMoney.convertedTo(BITCOIN_CURRENCY_UNIT, new BigDecimal(NUMBER_OF_SATOSHI_IN_ONE_BITCOIN).divide(rate, BITCOIN_CURRENCY_UNIT.getDecimalPlaces() + ADDITIONAL_CALCULATION_DIGITS, RoundingMode.HALF_EVEN), RoundingMode.HALF_EVEN); CurrencyConverterResult result = new CurrencyConverterResult(); result.setBtcMoneyValid(true); result.setBtcMoney(btcAmount); result.setFiatMoneyValid(true); result.setFiatMoney(fiatMoney); return result; } catch (ParseException pe) { log.debug("convertFromFiatToBTC: " + pe.getClass().getName() + " " + pe.getMessage()); CurrencyConverterResult result = new CurrencyConverterResult(); result.setBtcMoneyValid(false); result.setFiatMoneyValid(false); result.setFiatMessage(controller.getLocaliser().getString("currencyConverter.couldNotUnderstandAmount", new Object[]{fiat})); return result; } catch (ArithmeticException ae) { log.debug("convertFromFiatToBTC: " + ae.getClass().getName() + " " + ae.getMessage()); String currencyString = currencyUnit.getCurrencyCode(); if (currencyCodeToInfoMap.get(currencyString) != null) { currencyString = currencyCodeToInfoMap.get(currencyString).getCurrencySymbol(); } CurrencyConverterResult result = new CurrencyConverterResult(); result.setBtcMoneyValid(false); result.setFiatMoneyValid(false); result.setFiatMessage(controller.getLocaliser().getString("currencyConverter.fiatCanOnlyHaveSetDecimalPlaces", new Object[]{currencyString, currencyUnit.getDecimalPlaces()})); return result; } } } private MoneyFormatter getMoneyFormatter(boolean addCurrencySymbol) { MoneyFormatter moneyFormatter; // Suffix currency codes. String currencyCode = currencyUnit.getCurrencyCode(); CurrencyInfo currencyInfo = currencyCodeToInfoMap.get(currencyCode); if (currencyInfo == null) { // Create a default currency info with the raw currency code as a suffix, including a separator space currencyInfo = new CurrencyInfo(currencyCode, currencyCode, false); currencyInfo.setHasSeparatingSpace(true); } DecimalFormat formatter = (DecimalFormat) DecimalFormat.getInstance(controller.getLocaliser().getLocale()); char decimalSeparator = formatter.getDecimalFormatSymbols().getDecimalSeparator(); char groupingSeparator = formatter.getDecimalFormatSymbols().getGroupingSeparator(); MoneyAmountStyle moneyAmountStyle; if ('.' == decimalSeparator) { if (',' == groupingSeparator) { moneyAmountStyle = MoneyAmountStyle.ASCII_DECIMAL_POINT_GROUP3_COMMA; } else if (' ' == groupingSeparator || '\u00A0' == groupingSeparator) { moneyAmountStyle = MoneyAmountStyle.ASCII_DECIMAL_POINT_GROUP3_SPACE; } else { moneyAmountStyle = MoneyAmountStyle.ASCII_DECIMAL_POINT_NO_GROUPING; } } else { if (',' == decimalSeparator) { if ('.' == groupingSeparator) { moneyAmountStyle = MoneyAmountStyle.ASCII_DECIMAL_COMMA_GROUP3_DOT; } else if (' ' == groupingSeparator || '\u00A0' == groupingSeparator) { moneyAmountStyle = MoneyAmountStyle.ASCII_DECIMAL_COMMA_GROUP3_SPACE; } else { moneyAmountStyle = MoneyAmountStyle.ASCII_DECIMAL_COMMA_NO_GROUPING; } } else { // Do not really know - keep it simple. moneyAmountStyle = MoneyAmountStyle.ASCII_DECIMAL_POINT_NO_GROUPING; } } String separator; if (currencyInfo.hasSeparatingSpace) { separator = " "; } else { separator = ""; } if (currencyInfo.isPrefix()) { // Prefix currency code. if (addCurrencySymbol) { moneyFormatter = new MoneyFormatterBuilder().appendLiteral(currencyInfo.getCurrencySymbol()).appendLiteral(separator).appendAmount(moneyAmountStyle).toFormatter(controller.getLocaliser().getLocale()); } else { moneyFormatter = new MoneyFormatterBuilder().appendAmount(moneyAmountStyle).toFormatter(controller.getLocaliser().getLocale()); } } else { // Postfix currency code. if (addCurrencySymbol) { moneyFormatter = new MoneyFormatterBuilder().appendAmount(moneyAmountStyle).appendLiteral(separator).appendLiteral(currencyInfo.getCurrencySymbol()).toFormatter(controller.getLocaliser().getLocale()); } else { moneyFormatter = new MoneyFormatterBuilder().appendAmount(moneyAmountStyle).toFormatter(controller.getLocaliser().getLocale()); } } return moneyFormatter; } public String getFiatAsLocalisedString(Money money) { return getFiatAsLocalisedString(money, true, false); } public String getFiatAsLocalisedString(Money money, boolean addCurrencySymbol, boolean addParenthesis) { if (money == null) { return ""; } MoneyFormatter moneyFormatterToUse; if (addCurrencySymbol) { if (moneyFormatterWithCurrencyCode == null) { moneyFormatterWithCurrencyCode = getMoneyFormatter(true); } moneyFormatterToUse = moneyFormatterWithCurrencyCode; } else { if (moneyFormatter == null) { moneyFormatter = getMoneyFormatter(false); } moneyFormatterToUse = moneyFormatter; } if (groupingSeparator == null) { DecimalFormat fiatFormatter = (DecimalFormat) DecimalFormat.getInstance(controller.getLocaliser().getLocale()); groupingSeparator = String.valueOf(fiatFormatter.getDecimalFormatSymbols().getGroupingSeparator()); } String toReturn = moneyFormatterToUse.print(money); // Get rid of negative sign followed by thousand separator if (".".equals(groupingSeparator)) { // Escape regex. groupingSeparator = "\\."; } toReturn = toReturn.replaceAll("-" + groupingSeparator, "-"); if (addParenthesis) { toReturn = " (" + toReturn + ")"; } return toReturn; } public String getBTCAsLocalisedString(Money btcMoney) { DecimalFormat formatter = (DecimalFormat) DecimalFormat.getInstance(controller.getLocaliser().getLocale()); formatter.setMaximumFractionDigits(NUMBER_OF_DECIMAL_POINTS_IN_A_BITCOIN); String btcString = formatter.format(btcMoney.getAmount().divide(new BigDecimal(NUMBER_OF_SATOSHI_IN_ONE_BITCOIN))); return btcString; } public CurrencyConverterResult parseToFiat(String fiat) { DecimalFormat formatter = (DecimalFormat) DecimalFormat.getInstance(controller.getLocaliser().getLocale()); formatter.setParseBigDecimal(true); // Convert spaces to non breakable space. fiat = fiat.replaceAll(" ", "\u00A0"); try { BigDecimal parsedFiat = (BigDecimal) formatter.parse(fiat); Money fiatMoney = Money.of(currencyUnit, parsedFiat); CurrencyConverterResult result = new CurrencyConverterResult(); result.setFiatMoneyValid(true); result.setFiatMoney(fiatMoney); return result; } catch (ParseException pe) { log.debug("convertToMoney: " + pe.getClass().getName() + " " + pe.getMessage()); CurrencyConverterResult result = new CurrencyConverterResult(); result.setFiatMoneyValid(false); result.setFiatMessage(controller.getLocaliser().getString("currencyConverter.couldNotUnderstandAmount", new Object[]{fiat})); return result; } catch (ArithmeticException ae) { log.debug("convertToMoney: " + ae.getClass().getName() + " " + ae.getMessage()); String currencyString = currencyUnit.getCurrencyCode(); if (currencyCodeToInfoMap.get(currencyString) != null) { currencyString = currencyCodeToInfoMap.get(currencyString).getCurrencySymbol(); } CurrencyConverterResult result = new CurrencyConverterResult(); result.setFiatMoneyValid(false); result.setFiatMessage(controller.getLocaliser().getString("currencyConverter.fiatCanOnlyHaveSetDecimalPlaces", new Object[]{currencyString, currencyUnit.getDecimalPlaces()})); return result; } } /** * Parse a localised string and returns a Money denominated in Satoshi * @param btcString * @return */ public CurrencyConverterResult parseToBTC(String btcString) { return parseToBTC(btcString, controller.getLocaliser().getLocale()); } /** * Parse a non localised string and returns a Money denominated in Satoshi * @param btcString * @return */ public CurrencyConverterResult parseToBTCNotLocalised(String btcString) { return parseToBTC(btcString, Locale.ENGLISH); } private CurrencyConverterResult parseToBTC(String btcString, Locale locale) { if (btcString == null || btcString.equals("")) { return new CurrencyConverterResult(); } // Convert spaces to non breakable space. btcString = btcString.replaceAll(" ", "\u00A0"); Money btcAmount = null; DecimalFormat formatter = (DecimalFormat) DecimalFormat.getInstance(locale); formatter.setParseBigDecimal(true); try { BigDecimal parsedBTC = ((BigDecimal)formatter.parse(btcString)).movePointRight(NUMBER_OF_DECIMAL_POINTS_IN_A_BITCOIN); //log.debug("For locale " + controller.getLocaliser().getLocale().toString() + ", '" + btcString + "' parses to " + parsedBTC.toPlainString()); btcAmount = Money.of(BITCOIN_CURRENCY_UNIT, parsedBTC); CurrencyConverterResult result = new CurrencyConverterResult(); result.setBtcMoneyValid(true); result.setBtcMoney(btcAmount); return result; } catch (ParseException pe) { log.debug("parseToBTC: " + pe.getClass().getName() + " " + pe.getMessage()); CurrencyConverterResult result = new CurrencyConverterResult(); result.setBtcMoneyValid(false); result.setBtcMessage(controller.getLocaliser().getString("currencyConverter.couldNotUnderstandAmount", new Object[]{btcString})); return result; } catch (ArithmeticException ae) { log.debug("parseToBTC: " + ae.getClass().getName() + " " + ae.getMessage()); CurrencyConverterResult result = new CurrencyConverterResult(); result.setBtcMoneyValid(false); result.setBtcMessage(controller.getLocaliser().getString("currencyConverter.btcCanOnlyHaveEightDecimalPlaces")); return result; } } /** * Convert an unlocalised BTC amount e.g. 0.1234 to a localised BTC value with fiat * e.g. 0,1234 ($10,23) * @param btcAsString * @return pretty string with format <btc localised> (<fiat localised>) */ public String prettyPrint(String btcAsString) { String prettyPrint = ""; CurrencyConverterResult converterResult = parseToBTCNotLocalised(btcAsString); if (converterResult.isBtcMoneyValid()) { prettyPrint = getBTCAsLocalisedString(converterResult.getBtcMoney()); } else { // BTC did not parse - just use the original text prettyPrint = btcAsString; } prettyPrint = prettyPrint + " " + controller.getLocaliser().getString("sendBitcoinPanel.amountUnitLabel"); if (btcAsString != null && !"".equals(btcAsString)) { if (getRate() != null && isShowingFiat()) { if (converterResult.isBtcMoneyValid()) { Money fiat = convertFromBTCToFiat(converterResult.getBtcMoney().getAmount() .toBigInteger()); prettyPrint = prettyPrint + getFiatAsLocalisedString(fiat, true, true); } } } return prettyPrint; } public boolean isShowingFiat() { return !Boolean.FALSE.toString().equals(controller.getModel().getUserPreference(ExchangeModel.SHOW_BITCOIN_CONVERTED_TO_FIAT)); } public CurrencyUnit getCurrencyUnit() { return currencyUnit; } public void setCurrencyUnit(CurrencyUnit currencyUnit) { // If this is a new currency, blank the rate. // Thus you should set the currency unit first. if (this.currencyUnit != null && !this.currencyUnit.equals(currencyUnit)) { rate = null; rateDividedByNumberOfSatoshiInOneBitcoin = null; } this.currencyUnit = currencyUnit; // Reinitialise currency formatters. moneyFormatter = getMoneyFormatter(false); moneyFormatterWithCurrencyCode = getMoneyFormatter(true); } public BigDecimal getRate() { return rate; } public void setRate(BigDecimal rate) { boolean fireFoundInsteadOfUpdated = (rate== null); this.rate = rate; rateDividedByNumberOfSatoshiInOneBitcoin = rate.divide(new BigDecimal(CurrencyConverter.NUMBER_OF_SATOSHI_IN_ONE_BITCOIN)); if (fireFoundInsteadOfUpdated) { notifyFoundExchangeRate(); } else { notifyUpdatedExchangeRate(); } } public void addCurrencyConverterListener(CurrencyConverterListener listener) { if (listeners == null) { throw new IllegalStateException("You need to initialise the CurrencyConverter first"); } listeners.add(listener); } public void removeCurrencyConverterListener(CurrencyConverterListener listener) { if (listeners == null) { throw new IllegalStateException("You need to initialise the CurrencyConverter first"); } listeners.remove(listener); } private void notifyFoundExchangeRate() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (listeners != null) { for (CurrencyConverterListener listener : listeners) { listener.foundExchangeRate(new ExchangeRate(currencyUnit, rate, new Date())); } } } }); } private void notifyUpdatedExchangeRate() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (listeners != null) { for (CurrencyConverterListener listener : listeners) { listener.updatedExchangeRate(new ExchangeRate(currencyUnit, rate, new Date())); } } } }); } public Map<String, CurrencyInfo> getCurrencyCodeToInfoMap() { return currencyCodeToInfoMap; } public Map<String, String> getCurrencyCodeToDescriptionMap() { return currencyCodeToDescriptionMap; } }
da2ce7/multibit
src/main/java/org/multibit/exchange/CurrencyConverter.java
Java
mit
34,225
package com.desmond.parallaxviewpager; import android.support.v4.util.SparseArrayCompat; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.View; /** * Created by desmond on 1/6/15. */ public class ParallaxViewPagerChangeListener implements ViewPager.OnPageChangeListener { public static final String TAG = ParallaxViewPagerChangeListener.class.getSimpleName(); protected ViewPager mViewPager; protected ParallaxFragmentPagerAdapter mAdapter; protected View mHeader; protected int mNumFragments; public ParallaxViewPagerChangeListener(ViewPager viewPager, ParallaxFragmentPagerAdapter adapter, View headerView) { mViewPager = viewPager; mAdapter = adapter; mNumFragments = mAdapter.getCount(); mHeader = headerView; } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { int currentItem = mViewPager.getCurrentItem(); if (positionOffsetPixels > 0) { SparseArrayCompat<ScrollTabHolder> scrollTabHolders = mAdapter.getScrollTabHolders(); ScrollTabHolder fragmentContent; if (position < currentItem) { // Revealed the previous page fragmentContent = scrollTabHolders.valueAt(position); } else { // Revealed the next page fragmentContent = scrollTabHolders.valueAt(position + 1); } fragmentContent.adjustScroll((int) (mHeader.getHeight() + mHeader.getTranslationY()), mHeader.getHeight()); } } @Override public void onPageSelected(int position) { SparseArrayCompat<ScrollTabHolder> scrollTabHolders = mAdapter.getScrollTabHolders(); if (scrollTabHolders == null || scrollTabHolders.size() != mNumFragments) { return; } ScrollTabHolder currentHolder = scrollTabHolders.valueAt(position); currentHolder.adjustScroll( (int) (mHeader.getHeight() + mHeader.getTranslationY()), mHeader.getHeight()); } @Override public void onPageScrollStateChanged(int state) {} }
qingsong-xu/ParallaxHeaderViewPager
parallaxviewpager/src/main/java/com/desmond/parallaxviewpager/ParallaxViewPagerChangeListener.java
Java
mit
2,211
// Copyright 2013 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.media; import android.media.MediaCrypto; import android.media.MediaDrm; import android.os.AsyncTask; import android.os.Handler; import android.util.Log; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.HttpClient; import org.apache.http.client.ClientProtocolException; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.chromium.base.CalledByNative; import org.chromium.base.JNINamespace; import java.io.IOException; import java.util.HashMap; import java.util.UUID; /** * A wrapper of the android MediaDrm class. Each MediaDrmBridge manages multiple * sessions for a single MediaSourcePlayer. */ @JNINamespace("media") class MediaDrmBridge { private static final String TAG = "MediaDrmBridge"; private MediaDrm mMediaDrm; private UUID mSchemeUUID; private int mNativeMediaDrmBridge; // TODO(qinmin): we currently only support one session per DRM bridge. // Change this to a HashMap if we start to support multiple sessions. private String mSessionId; private MediaCrypto mMediaCrypto; private String mMimeType; private Handler mHandler; private byte[] mPendingInitData; private static UUID getUUIDFromBytes(byte[] data) { if (data.length != 16) { return null; } long mostSigBits = 0; long leastSigBits = 0; for (int i = 0; i < 8; i++) { mostSigBits = (mostSigBits << 8) | (data[i] & 0xff); } for (int i = 8; i < 16; i++) { leastSigBits = (leastSigBits << 8) | (data[i] & 0xff); } return new UUID(mostSigBits, leastSigBits); } private MediaDrmBridge(UUID schemeUUID, int nativeMediaDrmBridge) { try { mSchemeUUID = schemeUUID; mMediaDrm = new MediaDrm(schemeUUID); mNativeMediaDrmBridge = nativeMediaDrmBridge; mMediaDrm.setPropertyString("privacyMode", "enable"); mMediaDrm.setOnEventListener(new MediaDrmListener()); mHandler = new Handler(); } catch (android.media.UnsupportedSchemeException e) { Log.e(TAG, "Unsupported DRM scheme " + e.toString()); } } /** * Open a new session and return the sessionId. * * @return ID of the session. */ private String openSession() { String session = null; try { final byte[] sessionId = mMediaDrm.openSession(); session = new String(sessionId, "UTF-8"); } catch (android.media.NotProvisionedException e) { Log.e(TAG, "Cannot open a new session " + e.toString()); } catch (java.io.UnsupportedEncodingException e) { Log.e(TAG, "Cannot open a new session " + e.toString()); } return session; } /** * Create a new MediaDrmBridge from the crypto scheme UUID. * * @param schemeUUID Crypto scheme UUID. * @param nativeMediaDrmBridge Native object of this class. */ @CalledByNative private static MediaDrmBridge create(byte[] schemeUUID, int nativeMediaDrmBridge) { UUID cryptoScheme = getUUIDFromBytes(schemeUUID); if (cryptoScheme != null && MediaDrm.isCryptoSchemeSupported(cryptoScheme)) { return new MediaDrmBridge(cryptoScheme, nativeMediaDrmBridge); } return null; } /** * Create a new MediaCrypto object from the session Id. * * @param sessionId Crypto session Id. */ @CalledByNative private MediaCrypto getMediaCrypto() { if (mMediaCrypto != null) { return mMediaCrypto; } try { final byte[] session = mSessionId.getBytes("UTF-8"); if (MediaCrypto.isCryptoSchemeSupported(mSchemeUUID)) { mMediaCrypto = new MediaCrypto(mSchemeUUID, session); } } catch (android.media.MediaCryptoException e) { Log.e(TAG, "Cannot create MediaCrypto " + e.toString()); } catch (java.io.UnsupportedEncodingException e) { Log.e(TAG, "Cannot create MediaCrypto " + e.toString()); } return mMediaCrypto; } /** * Release the MediaDrmBridge object. */ @CalledByNative private void release() { if (mMediaCrypto != null) { mMediaCrypto.release(); } if (mSessionId != null) { try { final byte[] session = mSessionId.getBytes("UTF-8"); mMediaDrm.closeSession(session); } catch (java.io.UnsupportedEncodingException e) { Log.e(TAG, "Failed to close session " + e.toString()); } } mMediaDrm.release(); } /** * Generate a key request and post an asynchronous task to the native side * with the response message. * * @param initData Data needed to generate the key request. * @param mime Mime type. */ @CalledByNative private void generateKeyRequest(byte[] initData, String mime) { Log.d(TAG, "generateKeyRequest()."); if (mMimeType == null) { mMimeType = mime; } else if (!mMimeType.equals(mime)) { onKeyError(); return; } if (mSessionId == null) { mSessionId = openSession(); if (mSessionId == null) { if (mPendingInitData != null) { Log.e(TAG, "generateKeyRequest is called when another call is pending."); onKeyError(); return; } // We assume some event will be fired if openSession() failed. // generateKeyRequest() will be resumed after provisioning is finished. // TODO(xhwang): Double check if this assumption is true. Otherwise we need // to handle the exception in openSession more carefully. mPendingInitData = initData; return; } } try { final byte[] session = mSessionId.getBytes("UTF-8"); HashMap<String, String> optionalParameters = new HashMap<String, String>(); final MediaDrm.KeyRequest request = mMediaDrm.getKeyRequest( session, initData, mime, MediaDrm.KEY_TYPE_STREAMING, optionalParameters); mHandler.post(new Runnable(){ public void run() { nativeOnKeyMessage(mNativeMediaDrmBridge, mSessionId, request.getData(), request.getDefaultUrl()); } }); return; } catch (android.media.NotProvisionedException e) { // MediaDrm.EVENT_PROVISION_REQUIRED is also fired in this case. // Provisioning is handled in the handler of that event. Log.e(TAG, "Cannot get key request " + e.toString()); return; } catch (java.io.UnsupportedEncodingException e) { Log.e(TAG, "Cannot get key request " + e.toString()); } onKeyError(); } /** * Cancel a key request for a session Id. * * @param sessionId Crypto session Id. */ @CalledByNative private void cancelKeyRequest(String sessionId) { if (mSessionId == null || !mSessionId.equals(sessionId)) { return; } try { final byte[] session = sessionId.getBytes("UTF-8"); mMediaDrm.removeKeys(session); } catch (java.io.UnsupportedEncodingException e) { Log.e(TAG, "Cannot cancel key request " + e.toString()); } } /** * Add a key for a session Id. * * @param sessionId Crypto session Id. * @param key Response data from the server. */ @CalledByNative private void addKey(String sessionId, byte[] key) { if (mSessionId == null || !mSessionId.equals(sessionId)) { return; } try { final byte[] session = sessionId.getBytes("UTF-8"); try { mMediaDrm.provideKeyResponse(session, key); } catch (java.lang.IllegalStateException e) { // This is not really an exception. Some error code are incorrectly // reported as an exception. // TODO(qinmin): remove this exception catch when b/10495563 is fixed. Log.e(TAG, "Exception intentionally caught when calling provideKeyResponse() " + e.toString()); } mHandler.post(new Runnable() { public void run() { nativeOnKeyAdded(mNativeMediaDrmBridge, mSessionId); } }); return; } catch (android.media.NotProvisionedException e) { Log.e(TAG, "failed to provide key response " + e.toString()); } catch (android.media.DeniedByServerException e) { Log.e(TAG, "failed to provide key response " + e.toString()); } catch (java.io.UnsupportedEncodingException e) { Log.e(TAG, "failed to provide key response " + e.toString()); } onKeyError(); } /** * Return the security level of this DRM object. */ @CalledByNative private String getSecurityLevel() { return mMediaDrm.getPropertyString("securityLevel"); } /** * Called when the provision response is received. * * @param response Response data from the provision server. */ private void onProvisionResponse(byte[] response) { Log.d(TAG, "provide key response."); if (response == null || response.length == 0) { Log.e(TAG, "Invalid provision response."); onKeyError(); return; } try { mMediaDrm.provideProvisionResponse(response); } catch (android.media.DeniedByServerException e) { Log.e(TAG, "failed to provide provision response " + e.toString()); onKeyError(); return; } if (mPendingInitData != null) { byte[] initData = mPendingInitData; mPendingInitData = null; generateKeyRequest(initData, mMimeType); } } private void onKeyError() { // TODO(qinmin): pass the error code to native. mHandler.post(new Runnable() { public void run() { nativeOnKeyError(mNativeMediaDrmBridge, mSessionId); } }); } private class MediaDrmListener implements MediaDrm.OnEventListener { @Override public void onEvent(MediaDrm mediaDrm, byte[] sessionId, int event, int extra, byte[] data) { switch(event) { case MediaDrm.EVENT_PROVISION_REQUIRED: Log.d(TAG, "MediaDrm.EVENT_PROVISION_REQUIRED."); MediaDrm.ProvisionRequest request = mMediaDrm.getProvisionRequest(); PostRequestTask postTask = new PostRequestTask(request.getData()); postTask.execute(request.getDefaultUrl()); break; case MediaDrm.EVENT_KEY_REQUIRED: generateKeyRequest(data, mMimeType); break; case MediaDrm.EVENT_KEY_EXPIRED: onKeyError(); break; case MediaDrm.EVENT_VENDOR_DEFINED: assert(false); break; default: Log.e(TAG, "Invalid DRM event " + (int)event); return; } } } private class PostRequestTask extends AsyncTask<String, Void, Void> { private static final String TAG = "PostRequestTask"; private byte[] mDrmRequest; private byte[] mResponseBody; public PostRequestTask(byte[] drmRequest) { mDrmRequest = drmRequest; } @Override protected Void doInBackground(String... urls) { mResponseBody = postRequest(urls[0], mDrmRequest); if (mResponseBody != null) { Log.d(TAG, "response length=" + mResponseBody.length); } return null; } private byte[] postRequest(String url, byte[] drmRequest) { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url + "&signedRequest=" + new String(drmRequest)); Log.d(TAG, "PostRequest:" + httpPost.getRequestLine()); try { // Add data httpPost.setHeader("Accept", "*/*"); httpPost.setHeader("User-Agent", "Widevine CDM v1.0"); httpPost.setHeader("Content-Type", "application/json"); // Execute HTTP Post Request HttpResponse response = httpClient.execute(httpPost); byte[] responseBody; int responseCode = response.getStatusLine().getStatusCode(); if (responseCode == 200) { responseBody = EntityUtils.toByteArray(response.getEntity()); } else { Log.d(TAG, "Server returned HTTP error code " + responseCode); return null; } return responseBody; } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void v) { onProvisionResponse(mResponseBody); } } private native void nativeOnKeyMessage(int nativeMediaDrmBridge, String sessionId, byte[] message, String destinationUrl); private native void nativeOnKeyAdded(int nativeMediaDrmBridge, String sessionId); private native void nativeOnKeyError(int nativeMediaDrmBridge, String sessionId); }
gendeld/android-chromium-view
media/src/org/chromium/media/MediaDrmBridge.java
Java
mit
14,286
package kilim.test.ex; public interface TaskStatusCB { void beforeYield(); void afterYield(); void done(); }
killme2008/kilim
test/kilim/test/ex/TaskStatusCB.java
Java
mit
122
/******************************************************************************* * Copyright (c) 2012-2017 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.ide.actions; import com.google.inject.Inject; import com.google.inject.Singleton; import org.eclipse.che.ide.CoreLocalizationConstant; import org.eclipse.che.ide.Resources; import org.eclipse.che.ide.api.action.AbstractPerspectiveAction; import org.eclipse.che.ide.api.action.ActionEvent; import org.eclipse.che.ide.api.app.AppContext; import org.eclipse.che.ide.api.resources.Container; import org.eclipse.che.ide.api.resources.Resource; import org.eclipse.che.ide.upload.file.UploadFilePresenter; import javax.validation.constraints.NotNull; import static com.google.common.base.Preconditions.checkState; import static java.util.Collections.singletonList; import static org.eclipse.che.ide.workspace.perspectives.project.ProjectPerspective.PROJECT_PERSPECTIVE_ID; /** * Upload file Action * * @author Roman Nikitenko * @author Dmitry Shnurenko * @author Vlad Zhukovskyi */ @Singleton public class UploadFileAction extends AbstractPerspectiveAction { private final UploadFilePresenter presenter; private final AppContext appContext; @Inject public UploadFileAction(UploadFilePresenter presenter, CoreLocalizationConstant locale, Resources resources, AppContext appContext) { super(singletonList(PROJECT_PERSPECTIVE_ID), locale.uploadFileName(), locale.uploadFileDescription(), null, resources.uploadFile()); this.presenter = presenter; this.appContext = appContext; } /** {@inheritDoc} */ @Override public void actionPerformed(ActionEvent e) { final Resource[] resources = appContext.getResources(); checkState(resources != null && resources.length == 1 && resources[0] instanceof Container); presenter.showDialog((Container)resources[0]); } /** {@inheritDoc} */ @Override public void updateInPerspective(@NotNull ActionEvent e) { final Resource[] resources = appContext.getResources(); e.getPresentation().setVisible(true); e.getPresentation().setEnabled(resources != null && resources.length == 1 && resources[0] instanceof Container); } }
gazarenkov/che-sketch
ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/actions/UploadFileAction.java
Java
epl-1.0
2,726
/******************************************************************************* /******************************************************************************* * Copyright (c) 2015 Bosch Software Innovations GmbH and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v1.0 which accompany this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Bosch Software Innovations GmbH - Please refer to git log *******************************************************************************/ package org.eclipse.vorto.wizard.datatype; public enum Datatype { Entity, Enum }
erlemantos/eclipse-vorto
bundles/org.eclipse.vorto.wizard/src/org/eclipse/vorto/wizard/datatype/Datatype.java
Java
epl-1.0
907
/* * ProGuard -- shrinking, optimization, obfuscation, and preverification * of Java bytecode. * * Copyright (c) 2002-2009 Eric Lafortune (eric@graphics.cornell.edu) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package proguard.optimize.peephole; import proguard.classfile.*; import proguard.classfile.attribute.*; import proguard.classfile.attribute.visitor.*; import proguard.classfile.instruction.*; import proguard.classfile.util.SimplifiedVisitor; import proguard.optimize.info.ExceptionInstructionChecker; /** * This AttributeVisitor removes exception handlers that are unreachable in the * code attributes that it visits. * * @author Eric Lafortune */ public class UnreachableExceptionRemover extends SimplifiedVisitor implements AttributeVisitor, ExceptionInfoVisitor { private final ExceptionInfoVisitor extraExceptionInfoVisitor; private final ExceptionInstructionChecker exceptionInstructionChecker = new ExceptionInstructionChecker(); /** * Creates a new UnreachableExceptionRemover. */ public UnreachableExceptionRemover() { this(null); } /** * Creates a new UnreachableExceptionRemover. * @param extraExceptionInfoVisitor an optional extra visitor for all * removed exceptions. */ public UnreachableExceptionRemover(ExceptionInfoVisitor extraExceptionInfoVisitor) { this.extraExceptionInfoVisitor = extraExceptionInfoVisitor; } // Implementations for AttributeVisitor. public void visitAnyAttribute(Clazz clazz, Attribute attribute) {} public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute) { // Go over the exception table. codeAttribute.exceptionsAccept(clazz, method, this); // Remove exceptions with empty code blocks. codeAttribute.u2exceptionTableLength = removeEmptyExceptions(codeAttribute.exceptionTable, codeAttribute.u2exceptionTableLength); } // Implementations for ExceptionInfoVisitor. public void visitExceptionInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, ExceptionInfo exceptionInfo) { if (!mayThrowExceptions(clazz, method, codeAttribute, exceptionInfo.u2startPC, exceptionInfo.u2endPC)) { // Make the code block empty. exceptionInfo.u2endPC = exceptionInfo.u2startPC; if (extraExceptionInfoVisitor != null) { extraExceptionInfoVisitor.visitExceptionInfo(clazz, method, codeAttribute, exceptionInfo); } } } // Small utility methods. /** * Returns whether the specified block of code may throw exceptions. */ private boolean mayThrowExceptions(Clazz clazz, Method method, CodeAttribute codeAttribute, int startOffset, int endOffset) { byte[] code = codeAttribute.code; // Go over all instructions. int offset = startOffset; while (offset < endOffset) { // Get the current instruction. Instruction instruction = InstructionFactory.create(code, offset); // Check if it may be throwing exceptions. if (exceptionInstructionChecker.mayThrowExceptions(clazz, method, codeAttribute, offset, instruction)) { return true; } // Go to the next instruction. offset += instruction.length(offset); } return false; } /** * Returns the given list of exceptions, without the ones that have empty * code blocks. */ private int removeEmptyExceptions(ExceptionInfo[] exceptionInfos, int exceptionInfoCount) { // Overwrite all empty exceptions. int newIndex = 0; for (int index = 0; index < exceptionInfoCount; index++) { ExceptionInfo exceptionInfo = exceptionInfos[index]; if (exceptionInfo.u2startPC < exceptionInfo.u2endPC) { exceptionInfos[newIndex++] = exceptionInfo; } } return newIndex; } }
rex-xxx/mt6572_x201
external/proguard/src/proguard/optimize/peephole/UnreachableExceptionRemover.java
Java
gpl-2.0
5,494
/* * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @key stress * * @summary converted from VM Testbase nsk/monitoring/stress/classload/load008. * VM Testbase keywords: [stress, monitoring, nonconcurrent] * VM Testbase readme: * DESCRIPTION * The test checks up getAllClasses(), getLoadedClassCount(), * getTotalLoadedClassCount(), getUnloadedClassCount() methods when 100 * classes are loaded by 100 loaders, which are the instances of two * custom ClassLoader classes. * Access to the management metrics is accomplished through the MBeanServer. * The load008 test is performed for the ClassLoadingMBean interface under * DEFAULT implementation of MBean server. * COMMENTS * Fixed the bug * 4976274 Regression: "OutOfMemoryError: Java heap space" when -XX:+UseParallelGC * * @library /vmTestbase * /test/lib * @run driver jdk.test.lib.FileInstaller . . * @comment generate and compile LoadableClassXXX classes * @run driver nsk.monitoring.stress.classload.GenClassesBuilder * @run main/othervm * -XX:-UseGCOverheadLimit * nsk.monitoring.stress.classload.load001 * classes * -testMode=server * -loadableClassCount=100 * -loadersCount=100 */
md-5/jdk10
test/hotspot/jtreg/vmTestbase/nsk/monitoring/stress/classload/load008/TestDescription.java
Java
gpl-2.0
2,268
/* * Copyright (c) 2000, 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 sun.security.provider.certpath; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.security.PublicKey; import java.security.cert.CertificateException; import java.security.cert.CertPathValidatorException; import java.security.cert.PKIXReason; import java.security.cert.CertStore; import java.security.cert.CertStoreException; import java.security.cert.PKIXBuilderParameters; import java.security.cert.PKIXCertPathChecker; import java.security.cert.TrustAnchor; import java.security.cert.X509Certificate; import java.security.cert.X509CertSelector; import java.util.*; import javax.security.auth.x500.X500Principal; import sun.security.provider.certpath.PKIX.BuilderParams; import sun.security.util.Debug; import sun.security.x509.AccessDescription; import sun.security.x509.AuthorityInfoAccessExtension; import static sun.security.x509.PKIXExtensions.*; import sun.security.x509.X500Name; import sun.security.x509.AuthorityKeyIdentifierExtension; /** * This class represents a forward builder, which is able to retrieve * matching certificates from CertStores and verify a particular certificate * against a ForwardState. * * @since 1.4 * @author Yassir Elley * @author Sean Mullan */ class ForwardBuilder extends Builder { private static final Debug debug = Debug.getInstance("certpath"); private final Set<X509Certificate> trustedCerts; private final Set<X500Principal> trustedSubjectDNs; private final Set<TrustAnchor> trustAnchors; private X509CertSelector eeSelector; private AdaptableX509CertSelector caSelector; private X509CertSelector caTargetSelector; TrustAnchor trustAnchor; private Comparator<X509Certificate> comparator; private boolean searchAllCertStores = true; /** * Initialize the builder with the input parameters. * * @param params the parameter set used to build a certification path */ ForwardBuilder(BuilderParams buildParams, boolean searchAllCertStores) { super(buildParams); // populate sets of trusted certificates and subject DNs trustAnchors = buildParams.trustAnchors(); trustedCerts = new HashSet<X509Certificate>(trustAnchors.size()); trustedSubjectDNs = new HashSet<X500Principal>(trustAnchors.size()); for (TrustAnchor anchor : trustAnchors) { X509Certificate trustedCert = anchor.getTrustedCert(); if (trustedCert != null) { trustedCerts.add(trustedCert); trustedSubjectDNs.add(trustedCert.getSubjectX500Principal()); } else { trustedSubjectDNs.add(anchor.getCA()); } } comparator = new PKIXCertComparator(trustedSubjectDNs); this.searchAllCertStores = searchAllCertStores; } /** * Retrieves all certs from the specified CertStores that satisfy the * requirements specified in the parameters and the current * PKIX state (name constraints, policy constraints, etc). * * @param currentState the current state. * Must be an instance of <code>ForwardState</code> * @param certStores list of CertStores */ @Override Collection<X509Certificate> getMatchingCerts(State currentState, List<CertStore> certStores) throws CertStoreException, CertificateException, IOException { if (debug != null) { debug.println("ForwardBuilder.getMatchingCerts()..."); } ForwardState currState = (ForwardState) currentState; /* * We store certs in a Set because we don't want duplicates. * As each cert is added, it is sorted based on the PKIXCertComparator * algorithm. */ Set<X509Certificate> certs = new TreeSet<>(comparator); /* * Only look for EE certs if search has just started. */ if (currState.isInitial()) { getMatchingEECerts(currState, certStores, certs); } getMatchingCACerts(currState, certStores, certs); return certs; } /* * Retrieves all end-entity certificates which satisfy constraints * and requirements specified in the parameters and PKIX state. */ private void getMatchingEECerts(ForwardState currentState, List<CertStore> certStores, Collection<X509Certificate> eeCerts) throws IOException { if (debug != null) { debug.println("ForwardBuilder.getMatchingEECerts()..."); } /* * Compose a certificate matching rule to filter out * certs which don't satisfy constraints * * First, retrieve clone of current target cert constraints, * and then add more selection criteria based on current validation * state. Since selector never changes, cache local copy & reuse. */ if (eeSelector == null) { eeSelector = (X509CertSelector) targetCertConstraints.clone(); /* * Match on certificate validity date */ eeSelector.setCertificateValid(buildParams.date()); /* * Policy processing optimizations */ if (buildParams.explicitPolicyRequired()) { eeSelector.setPolicy(getMatchingPolicies()); } /* * Require EE certs */ eeSelector.setBasicConstraints(-2); } /* Retrieve matching EE certs from CertStores */ addMatchingCerts(eeSelector, certStores, eeCerts, searchAllCertStores); } /** * Retrieves all CA certificates which satisfy constraints * and requirements specified in the parameters and PKIX state. */ private void getMatchingCACerts(ForwardState currentState, List<CertStore> certStores, Collection<X509Certificate> caCerts) throws IOException { if (debug != null) { debug.println("ForwardBuilder.getMatchingCACerts()..."); } int initialSize = caCerts.size(); /* * Compose a CertSelector to filter out * certs which do not satisfy requirements. */ X509CertSelector sel = null; if (currentState.isInitial()) { if (targetCertConstraints.getBasicConstraints() == -2) { // no need to continue: this means we never can match a CA cert return; } /* This means a CA is the target, so match on same stuff as * getMatchingEECerts */ if (debug != null) { debug.println("ForwardBuilder.getMatchingCACerts(): ca is target"); } if (caTargetSelector == null) { caTargetSelector = (X509CertSelector) targetCertConstraints.clone(); /* * Since we don't check the validity period of trusted * certificates, please don't set the certificate valid * criterion unless the trusted certificate matching is * completed. */ /* * Policy processing optimizations */ if (buildParams.explicitPolicyRequired()) caTargetSelector.setPolicy(getMatchingPolicies()); } sel = caTargetSelector; } else { if (caSelector == null) { caSelector = new AdaptableX509CertSelector(); /* * Since we don't check the validity period of trusted * certificates, please don't set the certificate valid * criterion unless the trusted certificate matching is * completed. */ /* * Policy processing optimizations */ if (buildParams.explicitPolicyRequired()) caSelector.setPolicy(getMatchingPolicies()); } /* * Match on subject (issuer of previous cert) */ caSelector.setSubject(currentState.issuerDN); /* * Match on subjectNamesTraversed (both DNs and AltNames) * (checks that current cert's name constraints permit it * to certify all the DNs and AltNames that have been traversed) */ CertPathHelper.setPathToNames (caSelector, currentState.subjectNamesTraversed); /* * Facilitate certification path construction with authority * key identifier and subject key identifier. */ AuthorityKeyIdentifierExtension akidext = currentState.cert.getAuthorityKeyIdentifierExtension(); caSelector.parseAuthorityKeyIdentifierExtension(akidext); /* * check the validity period */ caSelector.setValidityPeriod(currentState.cert.getNotBefore(), currentState.cert.getNotAfter()); sel = caSelector; } /* * For compatibility, conservatively, we don't check the path * length constraint of trusted anchors. Please don't set the * basic constraints criterion unless the trusted certificate * matching is completed. */ sel.setBasicConstraints(-1); for (X509Certificate trustedCert : trustedCerts) { if (sel.match(trustedCert)) { if (debug != null) { debug.println("ForwardBuilder.getMatchingCACerts: " + "found matching trust anchor"); } if (caCerts.add(trustedCert) && !searchAllCertStores) { return; } } } /* * The trusted certificate matching is completed. We need to match * on certificate validity date. */ sel.setCertificateValid(buildParams.date()); /* * Require CA certs with a pathLenConstraint that allows * at least as many CA certs that have already been traversed */ sel.setBasicConstraints(currentState.traversedCACerts); /* * If we have already traversed as many CA certs as the maxPathLength * will allow us to, then we don't bother looking through these * certificate pairs. If maxPathLength has a value of -1, this * means it is unconstrained, so we always look through the * certificate pairs. */ if (currentState.isInitial() || (buildParams.maxPathLength() == -1) || (buildParams.maxPathLength() > currentState.traversedCACerts)) { if (addMatchingCerts(sel, certStores, caCerts, searchAllCertStores) && !searchAllCertStores) { return; } } if (!currentState.isInitial() && Builder.USE_AIA) { // check for AuthorityInformationAccess extension AuthorityInfoAccessExtension aiaExt = currentState.cert.getAuthorityInfoAccessExtension(); if (aiaExt != null) { getCerts(aiaExt, caCerts); } } if (debug != null) { int numCerts = caCerts.size() - initialSize; debug.println("ForwardBuilder.getMatchingCACerts: found " + numCerts + " CA certs"); } } /** * Download Certificates from the given AIA and add them to the * specified Collection. */ // cs.getCertificates(caSelector) returns a collection of X509Certificate's // because of the selector, so the cast is safe @SuppressWarnings("unchecked") private boolean getCerts(AuthorityInfoAccessExtension aiaExt, Collection<X509Certificate> certs) { if (Builder.USE_AIA == false) { return false; } List<AccessDescription> adList = aiaExt.getAccessDescriptions(); if (adList == null || adList.isEmpty()) { return false; } boolean add = false; for (AccessDescription ad : adList) { CertStore cs = URICertStore.getInstance(ad); if (cs != null) { try { if (certs.addAll((Collection<X509Certificate>) cs.getCertificates(caSelector))) { add = true; if (!searchAllCertStores) { return true; } } } catch (CertStoreException cse) { if (debug != null) { debug.println("exception getting certs from CertStore:"); cse.printStackTrace(); } } } } return add; } /** * This inner class compares 2 PKIX certificates according to which * should be tried first when building a path from the target. * The preference order is as follows: * * Given trusted certificate(s): * Subject:ou=D,ou=C,o=B,c=A * * Preference order for current cert: * * 1) Issuer matches a trusted subject * Issuer: ou=D,ou=C,o=B,c=A * * 2) Issuer is a descendant of a trusted subject (in order of * number of links to the trusted subject) * a) Issuer: ou=E,ou=D,ou=C,o=B,c=A [links=1] * b) Issuer: ou=F,ou=E,ou=D,ou=C,ou=B,c=A [links=2] * * 3) Issuer is an ancestor of a trusted subject (in order of number of * links to the trusted subject) * a) Issuer: ou=C,o=B,c=A [links=1] * b) Issuer: o=B,c=A [links=2] * * 4) Issuer is in the same namespace as a trusted subject (in order of * number of links to the trusted subject) * a) Issuer: ou=G,ou=C,o=B,c=A [links=2] * b) Issuer: ou=H,o=B,c=A [links=3] * * 5) Issuer is an ancestor of certificate subject (in order of number * of links to the certificate subject) * a) Issuer: ou=K,o=J,c=A * Subject: ou=L,ou=K,o=J,c=A * b) Issuer: o=J,c=A * Subject: ou=L,ou=K,0=J,c=A * * 6) Any other certificates */ static class PKIXCertComparator implements Comparator<X509Certificate> { final static String METHOD_NME = "PKIXCertComparator.compare()"; private final Set<X500Principal> trustedSubjectDNs; PKIXCertComparator(Set<X500Principal> trustedSubjectDNs) { this.trustedSubjectDNs = trustedSubjectDNs; } /** * @param oCert1 First X509Certificate to be compared * @param oCert2 Second X509Certificate to be compared * @return -1 if oCert1 is preferable to oCert2, or * if oCert1 and oCert2 are equally preferable (in this * case it doesn't matter which is preferable, but we don't * return 0 because the comparator would behave strangely * when used in a SortedSet). * 1 if oCert2 is preferable to oCert1 * 0 if oCert1.equals(oCert2). We only return 0 if the * certs are equal so that this comparator behaves * correctly when used in a SortedSet. * @throws ClassCastException if either argument is not of type * X509Certificate */ @Override public int compare(X509Certificate oCert1, X509Certificate oCert2) { // if certs are the same, return 0 if (oCert1.equals(oCert2)) return 0; X500Principal cIssuer1 = oCert1.getIssuerX500Principal(); X500Principal cIssuer2 = oCert2.getIssuerX500Principal(); X500Name cIssuer1Name = X500Name.asX500Name(cIssuer1); X500Name cIssuer2Name = X500Name.asX500Name(cIssuer2); if (debug != null) { debug.println(METHOD_NME + " o1 Issuer: " + cIssuer1); debug.println(METHOD_NME + " o2 Issuer: " + cIssuer2); } /* If one cert's issuer matches a trusted subject, then it is * preferable. */ if (debug != null) { debug.println(METHOD_NME + " MATCH TRUSTED SUBJECT TEST..."); } boolean m1 = trustedSubjectDNs.contains(cIssuer1); boolean m2 = trustedSubjectDNs.contains(cIssuer2); if (debug != null) { debug.println(METHOD_NME + " m1: " + m1); debug.println(METHOD_NME + " m2: " + m2); } if (m1 && m2) { return -1; } else if (m1) { return -1; } else if (m2) { return 1; } /* If one cert's issuer is a naming descendant of a trusted subject, * then it is preferable, in order of increasing naming distance. */ if (debug != null) { debug.println(METHOD_NME + " NAMING DESCENDANT TEST..."); } for (X500Principal tSubject : trustedSubjectDNs) { X500Name tSubjectName = X500Name.asX500Name(tSubject); int distanceTto1 = Builder.distance(tSubjectName, cIssuer1Name, -1); int distanceTto2 = Builder.distance(tSubjectName, cIssuer2Name, -1); if (debug != null) { debug.println(METHOD_NME +" distanceTto1: " + distanceTto1); debug.println(METHOD_NME +" distanceTto2: " + distanceTto2); } if (distanceTto1 > 0 || distanceTto2 > 0) { if (distanceTto1 == distanceTto2) { return -1; } else if (distanceTto1 > 0 && distanceTto2 <= 0) { return -1; } else if (distanceTto1 <= 0 && distanceTto2 > 0) { return 1; } else if (distanceTto1 < distanceTto2) { return -1; } else { // distanceTto1 > distanceTto2 return 1; } } } /* If one cert's issuer is a naming ancestor of a trusted subject, * then it is preferable, in order of increasing naming distance. */ if (debug != null) { debug.println(METHOD_NME + " NAMING ANCESTOR TEST..."); } for (X500Principal tSubject : trustedSubjectDNs) { X500Name tSubjectName = X500Name.asX500Name(tSubject); int distanceTto1 = Builder.distance (tSubjectName, cIssuer1Name, Integer.MAX_VALUE); int distanceTto2 = Builder.distance (tSubjectName, cIssuer2Name, Integer.MAX_VALUE); if (debug != null) { debug.println(METHOD_NME +" distanceTto1: " + distanceTto1); debug.println(METHOD_NME +" distanceTto2: " + distanceTto2); } if (distanceTto1 < 0 || distanceTto2 < 0) { if (distanceTto1 == distanceTto2) { return -1; } else if (distanceTto1 < 0 && distanceTto2 >= 0) { return -1; } else if (distanceTto1 >= 0 && distanceTto2 < 0) { return 1; } else if (distanceTto1 > distanceTto2) { return -1; } else { return 1; } } } /* If one cert's issuer is in the same namespace as a trusted * subject, then it is preferable, in order of increasing naming * distance. */ if (debug != null) { debug.println(METHOD_NME +" SAME NAMESPACE AS TRUSTED TEST..."); } for (X500Principal tSubject : trustedSubjectDNs) { X500Name tSubjectName = X500Name.asX500Name(tSubject); X500Name tAo1 = tSubjectName.commonAncestor(cIssuer1Name); X500Name tAo2 = tSubjectName.commonAncestor(cIssuer2Name); if (debug != null) { debug.println(METHOD_NME +" tAo1: " + String.valueOf(tAo1)); debug.println(METHOD_NME +" tAo2: " + String.valueOf(tAo2)); } if (tAo1 != null || tAo2 != null) { if (tAo1 != null && tAo2 != null) { int hopsTto1 = Builder.hops (tSubjectName, cIssuer1Name, Integer.MAX_VALUE); int hopsTto2 = Builder.hops (tSubjectName, cIssuer2Name, Integer.MAX_VALUE); if (debug != null) { debug.println(METHOD_NME +" hopsTto1: " + hopsTto1); debug.println(METHOD_NME +" hopsTto2: " + hopsTto2); } if (hopsTto1 == hopsTto2) { } else if (hopsTto1 > hopsTto2) { return 1; } else { // hopsTto1 < hopsTto2 return -1; } } else if (tAo1 == null) { return 1; } else { return -1; } } } /* If one cert's issuer is an ancestor of that cert's subject, * then it is preferable, in order of increasing naming distance. */ if (debug != null) { debug.println(METHOD_NME+" CERT ISSUER/SUBJECT COMPARISON TEST..."); } X500Principal cSubject1 = oCert1.getSubjectX500Principal(); X500Principal cSubject2 = oCert2.getSubjectX500Principal(); X500Name cSubject1Name = X500Name.asX500Name(cSubject1); X500Name cSubject2Name = X500Name.asX500Name(cSubject2); if (debug != null) { debug.println(METHOD_NME + " o1 Subject: " + cSubject1); debug.println(METHOD_NME + " o2 Subject: " + cSubject2); } int distanceStoI1 = Builder.distance (cSubject1Name, cIssuer1Name, Integer.MAX_VALUE); int distanceStoI2 = Builder.distance (cSubject2Name, cIssuer2Name, Integer.MAX_VALUE); if (debug != null) { debug.println(METHOD_NME + " distanceStoI1: " + distanceStoI1); debug.println(METHOD_NME + " distanceStoI2: " + distanceStoI2); } if (distanceStoI2 > distanceStoI1) { return -1; } else if (distanceStoI2 < distanceStoI1) { return 1; } /* Otherwise, certs are equally preferable. */ if (debug != null) { debug.println(METHOD_NME + " no tests matched; RETURN 0"); } return -1; } } /** * Verifies a matching certificate. * * This method executes the validation steps in the PKIX path * validation algorithm <draft-ietf-pkix-new-part1-08.txt> which were * not satisfied by the selection criteria used by getCertificates() * to find the certs and only the steps that can be executed in a * forward direction (target to trust anchor). Those steps that can * only be executed in a reverse direction are deferred until the * complete path has been built. * * Trust anchor certs are not validated, but are used to verify the * signature and revocation status of the previous cert. * * If the last certificate is being verified (the one whose subject * matches the target subject, then steps in 6.1.4 of the PKIX * Certification Path Validation algorithm are NOT executed, * regardless of whether or not the last cert is an end-entity * cert or not. This allows callers to certify CA certs as * well as EE certs. * * @param cert the certificate to be verified * @param currentState the current state against which the cert is verified * @param certPathList the certPathList generated thus far */ @Override void verifyCert(X509Certificate cert, State currentState, List<X509Certificate> certPathList) throws GeneralSecurityException { if (debug != null) { debug.println("ForwardBuilder.verifyCert(SN: " + Debug.toHexString(cert.getSerialNumber()) + "\n Issuer: " + cert.getIssuerX500Principal() + ")" + "\n Subject: " + cert.getSubjectX500Principal() + ")"); } ForwardState currState = (ForwardState)currentState; // Don't bother to verify untrusted certificate more. currState.untrustedChecker.check(cert, Collections.<String>emptySet()); /* * check for looping - abort a loop if we encounter the same * certificate twice */ if (certPathList != null) { for (X509Certificate cpListCert : certPathList) { if (cert.equals(cpListCert)) { if (debug != null) { debug.println("loop detected!!"); } throw new CertPathValidatorException("loop detected"); } } } /* check if trusted cert */ boolean isTrustedCert = trustedCerts.contains(cert); /* we don't perform any validation of the trusted cert */ if (!isTrustedCert) { /* * Check CRITICAL private extensions for user checkers that * support forward checking (forwardCheckers) and remove * ones we know how to check. */ Set<String> unresCritExts = cert.getCriticalExtensionOIDs(); if (unresCritExts == null) { unresCritExts = Collections.<String>emptySet(); } for (PKIXCertPathChecker checker : currState.forwardCheckers) { checker.check(cert, unresCritExts); } /* * Remove extensions from user checkers that don't support * forward checking. After this step, we will have removed * all extensions that all user checkers are capable of * processing. */ for (PKIXCertPathChecker checker : buildParams.certPathCheckers()) { if (!checker.isForwardCheckingSupported()) { Set<String> supportedExts = checker.getSupportedExtensions(); if (supportedExts != null) { unresCritExts.removeAll(supportedExts); } } } /* * Look at the remaining extensions and remove any ones we know how * to check. If there are any left, throw an exception! */ if (!unresCritExts.isEmpty()) { unresCritExts.remove(BasicConstraints_Id.toString()); unresCritExts.remove(NameConstraints_Id.toString()); unresCritExts.remove(CertificatePolicies_Id.toString()); unresCritExts.remove(PolicyMappings_Id.toString()); unresCritExts.remove(PolicyConstraints_Id.toString()); unresCritExts.remove(InhibitAnyPolicy_Id.toString()); unresCritExts.remove(SubjectAlternativeName_Id.toString()); unresCritExts.remove(KeyUsage_Id.toString()); unresCritExts.remove(ExtendedKeyUsage_Id.toString()); if (!unresCritExts.isEmpty()) throw new CertPathValidatorException ("Unrecognized critical extension(s)", null, null, -1, PKIXReason.UNRECOGNIZED_CRIT_EXT); } } /* * if this is the target certificate (init=true), then we are * not able to do any more verification, so just return */ if (currState.isInitial()) { return; } /* we don't perform any validation of the trusted cert */ if (!isTrustedCert) { /* Make sure this is a CA cert */ if (cert.getBasicConstraints() == -1) { throw new CertificateException("cert is NOT a CA cert"); } /* * Check keyUsage extension */ KeyChecker.verifyCAKeyUsage(cert); } /* * the following checks are performed even when the cert * is a trusted cert, since we are only extracting the * subjectDN, and publicKey from the cert * in order to verify a previous cert */ /* * Check signature only if no key requiring key parameters has been * encountered. */ if (!currState.keyParamsNeeded()) { if (buildParams.sigProvider() != null) { (currState.cert).verify(cert.getPublicKey(), buildParams.sigProvider()); } else { (currState.cert).verify(cert.getPublicKey()); } } } /** * Verifies whether the input certificate completes the path. * Checks the cert against each trust anchor that was specified, in order, * and returns true as soon as it finds a valid anchor. * Returns true if the cert matches a trust anchor specified as a * certificate or if the cert verifies with a trust anchor that * was specified as a trusted {pubkey, caname} pair. Returns false if none * of the trust anchors are valid for this cert. * * @param cert the certificate to test * @return a boolean value indicating whether the cert completes the path. */ @Override boolean isPathCompleted(X509Certificate cert) { for (TrustAnchor anchor : trustAnchors) { if (anchor.getTrustedCert() != null) { if (cert.equals(anchor.getTrustedCert())) { this.trustAnchor = anchor; return true; } else { continue; } } X500Principal principal = anchor.getCA(); PublicKey publicKey = anchor.getCAPublicKey(); if (principal != null && publicKey != null && principal.equals(cert.getSubjectX500Principal())) { if (publicKey.equals(cert.getPublicKey())) { // the cert itself is a trust anchor this.trustAnchor = anchor; return true; } // else, it is a self-issued certificate of the anchor } // Check subject/issuer name chaining if (principal == null || !principal.equals(cert.getIssuerX500Principal())) { continue; } // skip anchor if it contains a DSA key with no DSA params if (PKIX.isDSAPublicKeyWithoutParams(publicKey)) { continue; } /* * Check signature */ try { if (buildParams.sigProvider() != null) { cert.verify(publicKey, buildParams.sigProvider()); } else { cert.verify(publicKey); } } catch (InvalidKeyException ike) { if (debug != null) { debug.println("ForwardBuilder.isPathCompleted() invalid " + "DSA key found"); } continue; } catch (GeneralSecurityException e){ if (debug != null) { debug.println("ForwardBuilder.isPathCompleted() " + "unexpected exception"); e.printStackTrace(); } continue; } this.trustAnchor = anchor; return true; } return false; } /** Adds the certificate to the certPathList * * @param cert the certificate to be added * @param certPathList the certification path list */ @Override void addCertToPath(X509Certificate cert, LinkedList<X509Certificate> certPathList) { certPathList.addFirst(cert); } /** Removes final certificate from the certPathList * * @param certPathList the certification path list */ @Override void removeFinalCertFromPath(LinkedList<X509Certificate> certPathList) { certPathList.removeFirst(); } }
debian-pkg-android-tools/android-platform-libcore
ojluni/src/main/java/sun/security/provider/certpath/ForwardBuilder.java
Java
gpl-2.0
34,751
/* * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @summary Test of diagnostic command VM.classloader_stats * @library /testlibrary * @modules java.base/sun.misc * java.compiler * java.management * jdk.jvmstat/sun.jvmstat.monitor * @build jdk.test.lib.* * @build jdk.test.lib.dcmd.* * @run testng ClassLoaderStatsTest */ import org.testng.annotations.Test; import org.testng.Assert; import jdk.test.lib.OutputAnalyzer; import jdk.test.lib.dcmd.CommandExecutor; import jdk.test.lib.dcmd.JMXExecutor; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.Iterator; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ClassLoaderStatsTest { // ClassLoader Parent CLD* Classes ChunkSz BlockSz Type // 0x00000007c0215928 0x0000000000000000 0x0000000000000000 0 0 0 org.eclipse.osgi.baseadaptor.BaseAdaptor$1 // 0x00000007c0009868 0x0000000000000000 0x00007fc52aebcc80 1 6144 3768 sun.reflect.DelegatingClassLoader // 0x00000007c0009868 0x0000000000000000 0x00007fc52b8916d0 1 6144 3688 sun.reflect.DelegatingClassLoader // 0x00000007c0009868 0x00000007c0038ba8 0x00007fc52afb8760 1 6144 3688 sun.reflect.DelegatingClassLoader // 0x00000007c0009868 0x0000000000000000 0x00007fc52afbb1a0 1 6144 3688 sun.reflect.DelegatingClassLoader // 0x0000000000000000 0x0000000000000000 0x00007fc523416070 5019 30060544 29956216 <boot classloader> // 455 1210368 672848 + unsafe anonymous classes // 0x00000007c016b5c8 0x00000007c0038ba8 0x00007fc52a995000 5 8192 5864 org.netbeans.StandardModule$OneModuleClassLoader // 0x00000007c0009868 0x00000007c016b5c8 0x00007fc52ac13640 1 6144 3896 sun.reflect.DelegatingClassLoader // ... static Pattern clLine = Pattern.compile("0x\\p{XDigit}*\\s*0x\\p{XDigit}*\\s*0x\\p{XDigit}*\\s*(\\d*)\\s*(\\d*)\\s*(\\d*)\\s*(.*)"); static Pattern anonLine = Pattern.compile("\\s*(\\d*)\\s*(\\d*)\\s*(\\d*)\\s*.*"); public static DummyClassLoader dummyloader; public void run(CommandExecutor executor) throws ClassNotFoundException { // create a classloader and load our special class dummyloader = new DummyClassLoader(); Class<?> c = Class.forName("TestClass", true, dummyloader); if (c.getClassLoader() != dummyloader) { Assert.fail("TestClass defined by wrong classloader: " + c.getClassLoader()); } OutputAnalyzer output = executor.execute("VM.classloader_stats"); Iterator<String> lines = output.asLines().iterator(); while (lines.hasNext()) { String line = lines.next(); Matcher m = clLine.matcher(line); if (m.matches()) { // verify that DummyClassLoader has loaded 1 class and 1 anonymous class if (m.group(4).equals("ClassLoaderStatsTest$DummyClassLoader")) { System.out.println("line: " + line); if (!m.group(1).equals("1")) { Assert.fail("Should have loaded 1 class: " + line); } checkPositiveInt(m.group(2)); checkPositiveInt(m.group(3)); String next = lines.next(); System.out.println("next: " + next); Matcher m1 = anonLine.matcher(next); m1.matches(); if (!m1.group(1).equals("1")) { Assert.fail("Should have loaded 1 anonymous class, but found : " + m1.group(1)); } checkPositiveInt(m1.group(2)); checkPositiveInt(m1.group(3)); } } } } private static void checkPositiveInt(String s) { if (Integer.parseInt(s) <= 0) { Assert.fail("Value should have been > 0: " + s); } } public static class DummyClassLoader extends ClassLoader { public static final String CLASS_NAME = "TestClass"; static ByteBuffer readClassFile(String name) { File f = new File(System.getProperty("test.classes", "."), name); try (FileInputStream fin = new FileInputStream(f); FileChannel fc = fin.getChannel()) { return fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); } catch (IOException e) { Assert.fail("Can't open file: " + name, e); } /* Will not reach here as Assert.fail() throws exception */ return null; } protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { Class<?> c; if (!"TestClass".equals(name)) { c = super.loadClass(name, resolve); } else { // should not delegate to the system class loader c = findClass(name); if (resolve) { resolveClass(c); } } return c; } protected Class<?> findClass(String name) throws ClassNotFoundException { if (!"TestClass".equals(name)) { throw new ClassNotFoundException("Unexpected class: " + name); } return defineClass(name, readClassFile(name + ".class"), null); } } /* DummyClassLoader */ @Test public void jmx() throws ClassNotFoundException { run(new JMXExecutor()); } } class TestClass { static { // force creation of anonymous class (for the lambdaform) Runnable r = () -> System.out.println("Hello"); r.run(); } }
benbenolson/hotspot_9_mc
test/serviceability/dcmd/vm/ClassLoaderStatsTest.java
Java
gpl-2.0
7,109
/** * Copyright (C) 2012-2015 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * If the program is linked with libraries which are licensed under one of * the following licenses, the combination of the program with the linked * library is not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed * under the aforementioned licenses, is permitted by the copyright holders * if the distribution is compliant with both the GNU General Public * License version 2 and the aforementioned licenses. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * Public License for more details. */ package org.n52.sos.ds.hibernate.util; import static org.junit.Assert.assertTrue; import java.util.List; import org.junit.Test; import com.google.common.collect.Lists; public class HibernateHelperTest { @Test public void shouldReturnListsOfLists() { assertTrue( HibernateHelper.getValidSizedLists(getList()).size() == 11); } @Test public void shouldListSizeLessThanLimitExpressionDepth() { for (List<Long> validSizedList : HibernateHelper.getValidSizedLists(getList())) { assertTrue(validSizedList.size() <= HibernateConstants.LIMIT_EXPRESSION_DEPTH); } } private List<Long> getList() { List<Long> list = Lists.newArrayList(); for (long i = 0; i < 9999; i++) { list.add(i); } return list; } }
nuest/SOS
hibernate/common/src/test/java/org/n52/sos/ds/hibernate/util/HibernateHelperTest.java
Java
gpl-2.0
2,132
package org.ovirt.engine.ui.common.widget.parser; import java.text.ParseException; import org.ovirt.engine.core.compat.StringHelper; import com.google.gwt.regexp.shared.MatchResult; import com.google.gwt.regexp.shared.RegExp; import com.google.gwt.text.shared.Parser; public class MemorySizeParser implements Parser<Integer> { @Override public Integer parse(CharSequence text) throws ParseException { MatchResult match = RegExp.compile("^(\\d*)\\s*(\\w*)$").exec(text.toString()); //$NON-NLS-1$ if (match == null) { return 0; } String prefix = match.getGroup(1); String suffix = match.getGroup(2); Integer size = null; try { size = Integer.parseInt(prefix); } catch (NumberFormatException e) { return 0; } if (suffix.equalsIgnoreCase("TB") || suffix.equalsIgnoreCase("T")) { //$NON-NLS-1$ $NON-NLS-2$ return size * 1024 * 1024; } else if (suffix.equalsIgnoreCase("GB") || suffix.equalsIgnoreCase("G")) { //$NON-NLS-1$ $NON-NLS-2$ return size * 1024; } else if (suffix.equalsIgnoreCase("MB") || suffix.equalsIgnoreCase("M")) { //$NON-NLS-1$ $NON-NLS-2$ return size; } else if (StringHelper.isNullOrEmpty(suffix)) { return size; } else { return 0; // disallow garbled suffixes } } }
jtux270/translate
ovirt/3.6_source/frontend/webadmin/modules/gwt-common/src/main/java/org/ovirt/engine/ui/common/widget/parser/MemorySizeParser.java
Java
gpl-3.0
1,417
/** * Aptana Studio * Copyright (c) 2005-2011 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the GNU Public License (GPL) v3 (with exceptions). * Please see the license.html included with this distribution for details. * Any modifications to this file must keep this entire header intact. */ package com.aptana.portal.ui.dispatch.browserNotifications; import java.util.HashMap; import java.util.Map; import com.aptana.jetty.util.epl.ajax.JSON; import com.aptana.core.logging.IdeLog; import com.aptana.core.projects.templates.IProjectTemplate; import com.aptana.portal.ui.IDebugScopes; import com.aptana.portal.ui.dispatch.IBrowserNotificationConstants; import com.aptana.portal.ui.dispatch.actionControllers.TemplateActionController.TEMPLATE_INFO; import com.aptana.projects.ProjectsPlugin; import com.aptana.projects.templates.IProjectTemplateListener; /** * A class that notify the portal browser when a new template is loaded. * * @author Shalom Gibly <sgibly@appcelerator.com> */ public class TemplatesNotification extends AbstractBrowserNotification { private IProjectTemplateListener listener; /* * (non-Javadoc) * @see com.aptana.portal.ui.dispatch.browserNotifications.AbstractBrowserNotification#start() */ @Override public synchronized void start() { isListening = true; ProjectsPlugin.getDefault().getTemplatesManager().addListener(getListener()); IdeLog.logInfo(ProjectsPlugin.getDefault(), "Template Portal notifier started", IDebugScopes.START_PAGE); //$NON-NLS-1$ } /* * (non-Javadoc) * @see com.aptana.portal.ui.dispatch.browserNotifications.AbstractBrowserNotification#stop() */ @Override public synchronized void stop() { isListening = false; ProjectsPlugin.getDefault().getTemplatesManager().removeListener(getListener()); listener = null; IdeLog.logInfo(ProjectsPlugin.getDefault(), "Template Portal notifier stopped", IDebugScopes.START_PAGE); //$NON-NLS-1$ } /** * Notify a template addition * * @param template */ protected void notifyAdd(IProjectTemplate template) { IdeLog.logInfo(ProjectsPlugin.getDefault(), "Template added. Notifying portal...", IDebugScopes.START_PAGE); //$NON-NLS-1$ notifyTargets(IBrowserNotificationConstants.EVENT_ID_TEMPLATES, IBrowserNotificationConstants.EVENT_TYPE_ADDED, createTemplateInfo(template), true); } /** * Notify a template removal * * @param template */ protected void notifyRemoved(IProjectTemplate template) { IdeLog.logInfo(ProjectsPlugin.getDefault(), "Template removed. Notifying portal...", IDebugScopes.START_PAGE); //$NON-NLS-1$ notifyTargets(IBrowserNotificationConstants.EVENT_ID_TEMPLATES, IBrowserNotificationConstants.EVENT_TYPE_DELETED, createTemplateInfo(template), true); } /** * Create a JSON template info that will be send as the browser notification data. * * @param template * @return A JSON representation of the template that was added or removed. */ protected String createTemplateInfo(IProjectTemplate template) { Map<String, String> templateInfo = new HashMap<String, String>(); templateInfo.put(TEMPLATE_INFO.ID.toString(), template.getId()); templateInfo.put(TEMPLATE_INFO.NAME.toString(), template.getDisplayName()); templateInfo.put(TEMPLATE_INFO.DESCRIPTION.toString(), template.getDescription()); templateInfo.put(TEMPLATE_INFO.TEMPLATE_TYPE.toString(), template.getType().name()); return JSON.toString(templateInfo); } /** * @return an {@link IProjectTemplateListener} */ protected synchronized IProjectTemplateListener getListener() { if (listener == null) { listener = new IProjectTemplateListener() { public void templateAdded(IProjectTemplate template) { if (isListening) { notifyAdd(template); } } public void templateRemoved(IProjectTemplate template) { if (isListening) { notifyRemoved(template); } } }; } return listener; } }
HossainKhademian/Studio3
plugins/com.aptana.portal.ui/src/com/aptana/portal/ui/dispatch/browserNotifications/TemplatesNotification.java
Java
gpl-3.0
3,979
package org.ovirt.engine.core.common.validation.annotation; import static java.lang.annotation.ElementType.TYPE; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; import org.ovirt.engine.core.common.validation.TimeZoneValidator; @Target({TYPE}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = TimeZoneValidator.class) public @interface ValidTimeZone { String message() default "ACTION_TYPE_FAILED_INVALID_TIMEZONE"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
jtux270/translate
ovirt/3.6_source/backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/validation/annotation/ValidTimeZone.java
Java
gpl-3.0
672
package com.salesmanager.core.business.utils.ajax; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.collections4.CollectionUtils; import org.json.simple.JSONAware; import org.json.simple.JSONObject; public class AjaxResponse implements JSONAware { public final static int RESPONSE_STATUS_SUCCESS=0; public final static int RESPONSE_STATUS_FAIURE=-1; public final static int RESPONSE_STATUS_VALIDATION_FAILED=-2; public final static int RESPONSE_OPERATION_COMPLETED=9999; public final static int CODE_ALREADY_EXIST=9998; private int status; private List<Map<String,String>> data = new ArrayList<Map<String,String>>(); private Map<String,String> dataMap = new HashMap<String,String>(); private Map<String,String> validationMessages = new HashMap<String,String>(); public Map<String, String> getValidationMessages() { return validationMessages; } public void setValidationMessages(Map<String, String> validationMessages) { this.validationMessages = validationMessages; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } protected List<Map<String,String>> getData() { return data; } public void addDataEntry(Map<String,String> dataEntry) { this.data.add(dataEntry); } public void addEntry(String key, String value) { dataMap.put(key, value); } public void setErrorMessage(Throwable t) { this.setStatusMessage(t.getMessage()); } public void setErrorString(String t) { this.setStatusMessage(t); } public void addValidationMessage(String fieldName, String message) { this.validationMessages.put(fieldName, message); } private String statusMessage = null; public String getStatusMessage() { return statusMessage; } public void setStatusMessage(String statusMessage) { this.statusMessage = statusMessage; } protected String getJsonInfo() { StringBuilder returnString = new StringBuilder(); returnString.append("{"); returnString.append("\"response\"").append(":"); returnString.append("{"); returnString.append("\"status\"").append(":").append(this.getStatus()); if(this.getStatusMessage()!=null && this.getStatus()!=0) { returnString.append(",").append("\"statusMessage\"").append(":\"").append(JSONObject.escape(this.getStatusMessage())).append("\""); } return returnString.toString(); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public String toJSONString() { StringBuilder returnString = new StringBuilder(); returnString.append(getJsonInfo()); if(this.getData().size()>0) { StringBuilder dataEntries = null; int count = 0; for(Map keyValue : this.getData()) { if(dataEntries == null) { dataEntries = new StringBuilder(); } JSONObject data = new JSONObject(); Set<String> keys = keyValue.keySet(); for(String key : keys) { data.put(key, keyValue.get(key)); } String dataField = data.toJSONString(); dataEntries.append(dataField); if(count<this.data.size()-1) { dataEntries.append(","); } count ++; } returnString.append(",").append("\"data\"").append(":["); if(dataEntries!=null) { returnString.append(dataEntries.toString()); } returnString.append("]"); } if(this.getDataMap().size()>0) { StringBuilder dataEntries = null; int count = 0; for(String key : this.getDataMap().keySet()) { if(dataEntries == null) { dataEntries = new StringBuilder(); } dataEntries.append("\"").append(key).append("\""); dataEntries.append(":"); dataEntries.append("\"").append(this.getDataMap().get(key)).append("\""); if(count<this.getDataMap().size()-1) { dataEntries.append(","); } count ++; } if(dataEntries!=null) { returnString.append(",").append(dataEntries.toString()); } } if(CollectionUtils.isNotEmpty(this.getValidationMessages().values())) { StringBuilder dataEntries = null; int count = 0; for(String key : this.getValidationMessages().keySet()) { if(dataEntries == null) { dataEntries = new StringBuilder(); } dataEntries.append("{"); dataEntries.append("\"field\":\"").append(key).append("\""); dataEntries.append(","); dataEntries.append("\"message\":\"").append(this.getValidationMessages().get(key)).append("\""); dataEntries.append("}"); if(count<this.getValidationMessages().size()-1) { dataEntries.append(","); } count ++; } returnString.append(",").append("\"validations\"").append(":["); if(dataEntries!=null) { returnString.append(dataEntries.toString()); } returnString.append("]"); } returnString.append("}}"); return returnString.toString(); } public Map<String,String> getDataMap() { return dataMap; } public void setDataMap(Map<String,String> dataMap) { this.dataMap = dataMap; } }
abedeen/shopizer
sm-core/src/main/java/com/salesmanager/core/business/utils/ajax/AjaxResponse.java
Java
lgpl-2.1
4,969
import jcifs.smb.*; public class GetSecurity { public static void main( String[] argv ) throws Exception { SmbFile file = new SmbFile( argv[0] ); ACE[] security = file.getSecurity(true); for (int ai = 0; ai < security.length; ai++) { System.out.println(security[ai].toString()); } } }
IdentityAutomation/jcifs-idautopatch
examples/GetSecurity.java
Java
lgpl-2.1
341
/* * Copyright 2016-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.android; import com.facebook.buck.android.AndroidLibraryDescription.JvmLanguage; /** * Factory providing implementations of {@link AndroidLibraryCompiler} * for the specified {@code language}. * {@link AndroidLibraryDescription} uses this factory to handle multiple JVM languages. * Implementations should provide a compiler implementation for every {@link JvmLanguage}. * See {@link DefaultAndroidLibraryCompiler} */ public interface AndroidLibraryCompilerFactory { AndroidLibraryCompilerFactory JAVA_ONLY_COMPILER_FACTORY = language -> new JavaAndroidLibraryCompiler(); AndroidLibraryCompiler getCompiler(JvmLanguage language); }
daedric/buck
src/com/facebook/buck/android/AndroidLibraryCompilerFactory.java
Java
apache-2.0
1,286
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache license, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the license for the specific language governing permissions and * limitations under the license. */ package org.apache.logging.log4j.core.jmx; import java.util.Objects; import javax.management.ObjectName; import com.lmax.disruptor.RingBuffer; /** * Instruments an LMAX Disruptor ring buffer. */ public class RingBufferAdmin implements RingBufferAdminMBean { private final RingBuffer<?> ringBuffer; private final ObjectName objectName; public static RingBufferAdmin forAsyncLogger(final RingBuffer<?> ringBuffer, final String contextName) { final String ctxName = Server.escape(contextName); final String name = String.format(PATTERN_ASYNC_LOGGER, ctxName); return new RingBufferAdmin(ringBuffer, name); } public static RingBufferAdmin forAsyncLoggerConfig(final RingBuffer<?> ringBuffer, final String contextName, final String configName) { final String ctxName = Server.escape(contextName); final String cfgName = Server.escape(configName); final String name = String.format(PATTERN_ASYNC_LOGGER_CONFIG, ctxName, cfgName); return new RingBufferAdmin(ringBuffer, name); } protected RingBufferAdmin(final RingBuffer<?> ringBuffer, final String mbeanName) { this.ringBuffer = Objects.requireNonNull(ringBuffer, "ringbuffer"); try { objectName = new ObjectName(mbeanName); } catch (final Exception e) { throw new IllegalStateException(e); } } @Override public long getBufferSize() { return ringBuffer.getBufferSize(); } @Override public long getRemainingCapacity() { return ringBuffer.remainingCapacity(); } /** * Returns the {@code ObjectName} of this mbean. * * @return the {@code ObjectName} * @see RingBufferAdminMBean#PATTERN_ASYNC_LOGGER * @see RingBufferAdminMBean#PATTERN_ASYNC_LOGGER_CONFIG */ public ObjectName getObjectName() { return objectName; } }
pisfly/logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/RingBufferAdmin.java
Java
apache-2.0
2,741
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.cloud.vm; import java.util.Formatter; /** * VM Name. */ public class VirtualMachineName { public static final String SEPARATOR = "-"; public static boolean isValidCloudStackVmName(String name, String instance) { String[] parts = name.split(SEPARATOR); if (parts.length <= 1) { return false; } if (!parts[parts.length - 1].equals(instance)) { return false; } return true; } public static String getVnetName(long vnetId) { StringBuilder vnet = new StringBuilder(); Formatter formatter = new Formatter(vnet); formatter.format("%04x", vnetId); return vnet.toString(); } public static boolean isValidVmName(String vmName) { return isValidVmName(vmName, null); } public static boolean isValidVmName(String vmName, String instance) { String[] tokens = vmName.split(SEPARATOR); if (tokens.length <= 1) { return false; } if (!tokens[0].equals("i")) { return false; } return true; } public static String getVmName(long vmId, long userId, String instance) { StringBuilder vmName = new StringBuilder("i"); vmName.append(SEPARATOR).append(userId).append(SEPARATOR).append(vmId); vmName.append(SEPARATOR).append(instance); return vmName.toString(); } public static long getVmId(String vmName) { int begin = vmName.indexOf(SEPARATOR); begin = vmName.indexOf(SEPARATOR, begin + SEPARATOR.length()); int end = vmName.indexOf(SEPARATOR, begin + SEPARATOR.length()); return Long.parseLong(vmName.substring(begin + 1, end)); } public static long getRouterId(String routerName) { int begin = routerName.indexOf(SEPARATOR); int end = routerName.indexOf(SEPARATOR, begin + SEPARATOR.length()); return Long.parseLong(routerName.substring(begin + 1, end)); } public static long getConsoleProxyId(String vmName) { int begin = vmName.indexOf(SEPARATOR); int end = vmName.indexOf(SEPARATOR, begin + SEPARATOR.length()); return Long.parseLong(vmName.substring(begin + 1, end)); } public static long getSystemVmId(String vmName) { int begin = vmName.indexOf(SEPARATOR); int end = vmName.indexOf(SEPARATOR, begin + SEPARATOR.length()); return Long.parseLong(vmName.substring(begin + 1, end)); } public static String getRouterName(long routerId, String instance) { StringBuilder builder = new StringBuilder("r"); builder.append(SEPARATOR).append(routerId).append(SEPARATOR).append(instance); return builder.toString(); } public static String getConsoleProxyName(long vmId, String instance) { StringBuilder builder = new StringBuilder("v"); builder.append(SEPARATOR).append(vmId).append(SEPARATOR).append(instance); return builder.toString(); } public static String getSystemVmName(long vmId, String instance, String prefix) { StringBuilder builder = new StringBuilder(prefix); builder.append(SEPARATOR).append(vmId).append(SEPARATOR).append(instance); return builder.toString(); } public static String attachVnet(String name, String vnet) { return name + SEPARATOR + vnet; } public static boolean isValidRouterName(String name) { return isValidRouterName(name, null); } public static boolean isValidRouterName(String name, String instance) { String[] tokens = name.split(SEPARATOR); if (tokens.length != 3 && tokens.length != 4) { return false; } if (!tokens[0].equals("r")) { return false; } try { Long.parseLong(tokens[1]); } catch (NumberFormatException ex) { return false; } return instance == null || tokens[2].equals(instance); } public static boolean isValidConsoleProxyName(String name) { return isValidConsoleProxyName(name, null); } public static boolean isValidConsoleProxyName(String name, String instance) { String[] tokens = name.split(SEPARATOR); if (tokens.length != 3) { return false; } if (!tokens[0].equals("v")) { return false; } try { Long.parseLong(tokens[1]); } catch (NumberFormatException ex) { return false; } return instance == null || tokens[2].equals(instance); } public static boolean isValidSecStorageVmName(String name, String instance) { return isValidSystemVmName(name, instance, "s"); } public static boolean isValidSystemVmName(String name, String instance, String prefix) { String[] tokens = name.split(SEPARATOR); if (tokens.length != 3) { return false; } if (!tokens[0].equals(prefix)) { return false; } try { Long.parseLong(tokens[1]); } catch (NumberFormatException ex) { return false; } return instance == null || tokens[2].equals(instance); } }
GabrielBrascher/cloudstack
api/src/main/java/com/cloud/vm/VirtualMachineName.java
Java
apache-2.0
6,046
/** * Copyright 2013 Cloudera 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.kitesdk.data.spi.filesystem; import org.kitesdk.data.Signalable; import com.google.common.collect.Lists; import org.kitesdk.data.Dataset; import org.kitesdk.data.DatasetDescriptor; import org.kitesdk.data.DatasetException; import org.kitesdk.data.DatasetReader; import org.kitesdk.data.Format; import org.kitesdk.data.Formats; import org.kitesdk.data.MiniDFSTest; import org.kitesdk.data.URIBuilder; import org.kitesdk.data.ValidationException; import org.kitesdk.data.impl.Accessor; import org.kitesdk.data.spi.PartitionKey; import org.kitesdk.data.PartitionStrategy; import com.google.common.collect.Sets; import com.google.common.io.Files; import java.io.IOException; import java.net.URI; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Set; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.GenericData.Record; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.kitesdk.data.CompressionType; import org.kitesdk.data.TestHelpers; import org.kitesdk.data.spi.PartitionedDataset; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.kitesdk.data.spi.filesystem.DatasetTestUtilities.*; import org.kitesdk.data.spi.FieldPartitioner; @RunWith(Parameterized.class) public class TestFileSystemDataset extends MiniDFSTest { private static final Logger LOG = LoggerFactory .getLogger(TestFileSystemDataset.class); @Parameterized.Parameters public static Collection<Object[]> data() throws IOException { MiniDFSTest.setupFS(); Object[][] data = new Object[][] { { Formats.AVRO, getDFS(), CompressionType.Uncompressed }, { Formats.AVRO, getDFS(), CompressionType.Snappy }, { Formats.AVRO, getDFS(), CompressionType.Deflate}, { Formats.AVRO, getDFS(), CompressionType.Bzip2}, { Formats.AVRO, getFS(), CompressionType.Uncompressed}, { Formats.AVRO, getFS(), CompressionType.Snappy}, { Formats.AVRO, getFS(), CompressionType.Deflate}, { Formats.AVRO, getFS(), CompressionType.Bzip2}, { Formats.PARQUET, getDFS(), CompressionType.Uncompressed }, { Formats.PARQUET, getDFS(), CompressionType.Snappy }, { Formats.PARQUET, getDFS(), CompressionType.Deflate }, { Formats.PARQUET, getFS(), CompressionType.Uncompressed }, { Formats.PARQUET, getFS(), CompressionType.Snappy }, { Formats.PARQUET, getFS(), CompressionType.Deflate } }; return Arrays.asList(data); } private final Format format; private final FileSystem fileSystem; private final CompressionType compressionType; private Path testDirectory; public TestFileSystemDataset(Format format, FileSystem fs, CompressionType compressionType) { this.format = format; this.fileSystem = fs; this.compressionType = compressionType; } @Before public void setUp() throws IOException { testDirectory = fileSystem.makeQualified( new Path(Files.createTempDir().getAbsolutePath() + "/test%2F-0")); } @After public void tearDown() throws IOException { fileSystem.delete(testDirectory, true); } @Test public void testWriteAndRead() throws IOException { FileSystemDataset<Record> ds = new FileSystemDataset.Builder<Record>() .namespace("ns") .name("test") .configuration(getConfiguration()) .descriptor(new DatasetDescriptor.Builder() .schemaUri(USER_SCHEMA_URL) .format(format) .compressionType(compressionType) .location(testDirectory) .build()) .type(Record.class) .build(); Assert.assertFalse("Dataset is not partitioned", ds.getDescriptor() .isPartitioned()); writeTestUsers(ds, 10); checkTestUsers(ds, 10); } @Test @SuppressWarnings("deprecation") public void testPartitionedWriterSingle() throws IOException { PartitionStrategy partitionStrategy = new PartitionStrategy.Builder().hash( "username", 2).build(); FileSystemDataset<Record> ds = new FileSystemDataset.Builder<Record>() .namespace("ns") .name("partitioned-users") .configuration(getConfiguration()) .descriptor(new DatasetDescriptor.Builder() .schema(USER_SCHEMA) .format(format) .compressionType(compressionType) .location(testDirectory) .partitionStrategy(partitionStrategy) .build()) .type(Record.class) .build(); Assert.assertTrue("Dataset is partitioned", ds.getDescriptor() .isPartitioned()); Assert.assertEquals(partitionStrategy, ds.getDescriptor() .getPartitionStrategy()); writeTestUsers(ds, 10); Assert.assertTrue("Partitioned directory 0 exists", fileSystem.exists(new Path(testDirectory, "username_hash=0"))); Assert.assertTrue("Partitioned directory 1 exists", fileSystem.exists(new Path(testDirectory, "username_hash=1"))); checkTestUsers(ds, 10); PartitionKey key0 = new PartitionKey(0); PartitionKey key1 = new PartitionKey(1); int total = readTestUsersInPartition(ds, key0, null) + readTestUsersInPartition(ds, key1, null); Assert.assertEquals(10, total); testPartitionKeysAreEqual(ds, key0, key1); Set<Record> records = Sets.newHashSet(); for (Dataset dataset : ds.getPartitions()) { Assert.assertFalse("Partitions should not have further partitions", dataset.getDescriptor().isPartitioned()); records.addAll(materialize(ds)); } checkTestUsers(records, 10); } @Test @SuppressWarnings("deprecation") public void testPartitionedWriterSingleNullableField() throws IOException { PartitionStrategy partitionStrategy = new PartitionStrategy.Builder().hash( "username", 2).build(); FileSystemDataset<Record> ds = new FileSystemDataset.Builder<Record>() .namespace("ns") .name("partitioned-users") .configuration(getConfiguration()) .descriptor(new DatasetDescriptor.Builder() .schema(USER_NULLABLE_SCHEMA) .format(format) .compressionType(compressionType) .location(testDirectory) .partitionStrategy(partitionStrategy) .build()) .type(Record.class) .build(); Assert.assertTrue("Dataset is partitioned", ds.getDescriptor() .isPartitioned()); Assert.assertEquals(partitionStrategy, ds.getDescriptor() .getPartitionStrategy()); writeTestUsers(ds, 10); Assert.assertTrue("Partitioned directory 0 exists", fileSystem.exists(new Path(testDirectory, "username_hash=0"))); Assert.assertTrue("Partitioned directory 1 exists", fileSystem.exists(new Path(testDirectory, "username_hash=1"))); checkTestUsers(ds, 10); PartitionKey key0 = new PartitionKey(0); PartitionKey key1 = new PartitionKey(1); int total = readTestUsersInPartition(ds, key0, null) + readTestUsersInPartition(ds, key1, null); Assert.assertEquals(10, total); testPartitionKeysAreEqual(ds, key0, key1); Set<Record> records = Sets.newHashSet(); for (Dataset dataset : ds.getPartitions()) { Assert.assertFalse("Partitions should not have further partitions", dataset.getDescriptor().isPartitioned()); records.addAll(materialize(ds)); } checkTestUsers(records, 10); } @Test @SuppressWarnings("deprecation") public void testPartitionedWriterDouble() throws IOException { PartitionStrategy partitionStrategy = new PartitionStrategy.Builder() .hash("username", 2).hash("email", 3).build(); FileSystemDataset<Record> ds = new FileSystemDataset.Builder<Record>() .namespace("ns") .name("partitioned-users") .configuration(getConfiguration()) .descriptor(new DatasetDescriptor.Builder() .schema(USER_SCHEMA) .format(format) .compressionType(compressionType) .location(testDirectory) .partitionStrategy(partitionStrategy) .build()) .type(Record.class) .build(); Assert.assertTrue("Dataset is partitioned", ds.getDescriptor() .isPartitioned()); Assert.assertEquals(partitionStrategy, ds.getDescriptor() .getPartitionStrategy()); writeTestUsers(ds, 10); checkTestUsers(ds, 10); PartitionKey key0 = new PartitionKey(0); PartitionKey key1 = new PartitionKey(1); int total = readTestUsersInPartition(ds, key0, "email_hash") + readTestUsersInPartition(ds, key0, "email_hash"); Assert.assertEquals(10, total); total = 0; for (int i1 = 0; i1 < 2; i1++) { for (int i2 = 0; i2 < 3; i2++) { String part = "username_hash=" + i1 + "/email_hash=" + i2; Assert.assertTrue("Partitioned directory " + part + " exists", fileSystem.exists(new Path(testDirectory, part))); total += readTestUsersInPartition(ds, new PartitionKey(i1, i2), null); } } Assert.assertEquals(10, total); testPartitionKeysAreEqual(ds, key0, key1); Set<Record> records = Sets.newHashSet(); for (Dataset<Record> dataset : ds.getPartitions()) { Assert.assertTrue("Partitions should have further partitions", dataset .getDescriptor().isPartitioned()); records.addAll(materialize(ds)); } checkTestUsers(records, 10); } @Test @SuppressWarnings("deprecation") public void testGetPartitionReturnsNullIfNoAutoCreate() throws IOException { PartitionStrategy partitionStrategy = new PartitionStrategy.Builder().hash( "username", 2).build(); FileSystemDataset<Record> ds = new FileSystemDataset.Builder<Record>() .namespace("ns") .name("partitioned-users") .configuration(getConfiguration()) .descriptor(new DatasetDescriptor.Builder() .schema(USER_SCHEMA) .format(format) .location(testDirectory) .partitionStrategy(partitionStrategy) .build()) .type(Record.class) .build(); Assert .assertNull(ds.getPartition(new PartitionKey(1), false)); } @Test @SuppressWarnings("deprecation") public void testWriteToSubpartition() throws IOException { PartitionStrategy partitionStrategy = new PartitionStrategy.Builder() .hash("username", "username_part", 2).hash("email", 3).build(); FileSystemDataset<Record> ds = new FileSystemDataset.Builder<Record>() .namespace("ns") .name("partitioned-users") .configuration(getConfiguration()) .descriptor(new DatasetDescriptor.Builder() .schema(USER_SCHEMA) .format(format) .compressionType(compressionType) .location(testDirectory) .partitionStrategy(partitionStrategy) .build()) .type(Record.class) .build(); PartitionKey key = new PartitionKey(1); FileSystemDataset<Record> userPartition = (FileSystemDataset<Record>) ds.getPartition(key, true); Assert.assertEquals(key, userPartition.getPartitionKey()); writeTestUsers(userPartition, 1); Assert.assertTrue("Partitioned directory exists", fileSystem.exists(new Path(testDirectory, "username_part=1/email_hash=2"))); Assert.assertEquals(1, readTestUsersInPartition(ds, key, "email_hash")); } @Test @SuppressWarnings("deprecation") public void testDropPartition() throws IOException { PartitionStrategy partitionStrategy = new PartitionStrategy.Builder() .hash("username", 2).build(); FileSystemDataset<Record> ds = new FileSystemDataset.Builder<Record>() .namespace("ns") .name("partitioned-users") .configuration(getConfiguration()) .descriptor(new DatasetDescriptor.Builder() .schema(USER_SCHEMA) .format(format) .compressionType(compressionType) .location(testDirectory) .partitionStrategy(partitionStrategy) .build()) .type(Record.class) .build(); writeTestUsers(ds, 10); Assert.assertTrue( fileSystem.isDirectory(new Path(testDirectory, "username_hash=0"))); Assert.assertTrue( fileSystem.isDirectory(new Path(testDirectory, "username_hash=1"))); ds.dropPartition(new PartitionKey(0)); Assert.assertFalse( fileSystem.isDirectory(new Path(testDirectory, "username_hash=0"))); ds.dropPartition(new PartitionKey(1)); Assert.assertFalse( fileSystem.isDirectory(new Path(testDirectory, "username_hash=1"))); DatasetException caught = null; try { ds.dropPartition(new PartitionKey(0)); } catch (DatasetException e) { caught = e; } Assert.assertNotNull(caught); } @Test public void testMerge() throws IOException { PartitionStrategy partitionStrategy = new PartitionStrategy.Builder().hash( "username", 2).build(); FileSystemDataset<Record> ds = new FileSystemDataset.Builder<Record>() .namespace("ns") .name("partitioned-users") .configuration(getConfiguration()) .descriptor(new DatasetDescriptor.Builder() .schema(USER_SCHEMA) .format(format) .compressionType(compressionType) .location(testDirectory) .partitionStrategy(partitionStrategy) .build()) .type(Record.class) .build(); writeTestUsers(ds, 10); checkTestUsers(ds, 10); Path newTestDirectory = fileSystem.makeQualified( new Path(Files.createTempDir().getAbsolutePath())); FileSystemDataset<Record> dsUpdate = new FileSystemDataset.Builder<Record>() .namespace("ns") .name("partitioned-users") .configuration(getConfiguration()) .descriptor(new DatasetDescriptor.Builder() .schema(USER_SCHEMA) .format(format) .compressionType(compressionType) .location(newTestDirectory) .partitionStrategy(partitionStrategy) .build()) .type(Record.class) .build(); writeTestUsers(dsUpdate, 5, 10); checkTestUsers(dsUpdate, 5, 10); ds.merge(dsUpdate); checkTestUsers(dsUpdate, 0); checkTestUsers(ds, 15); } @Test(expected = ValidationException.class) public void testCannotMergeDatasetsWithDifferentFormats() throws IOException { FileSystemDataset<Record> ds = new FileSystemDataset.Builder<Record>() .namespace("ns") .name("users") .configuration(getConfiguration()) .descriptor(new DatasetDescriptor.Builder() .schema(USER_SCHEMA) .format(Formats.AVRO) .location(testDirectory) .build()) .type(Record.class) .build(); FileSystemDataset<Record> dsUpdate = new FileSystemDataset.Builder<Record>() .namespace("ns") .name("users") .configuration(getConfiguration()) .descriptor(new DatasetDescriptor.Builder() .schema(USER_SCHEMA) .format(Formats.PARQUET) .location(testDirectory) .build()) .type(Record.class) .build(); ds.merge(dsUpdate); } @Test(expected = ValidationException.class) public void testCannotMergeDatasetsWithDifferentPartitionStrategies() throws IOException { FileSystemDataset<Record> ds = new FileSystemDataset.Builder<Record>() .namespace("ns") .name("users") .configuration(getConfiguration()) .descriptor(new DatasetDescriptor.Builder() .schema(USER_SCHEMA) .location(testDirectory) .partitionStrategy(new PartitionStrategy.Builder() .hash("username", 2).build()) .build()) .type(Record.class) .build(); FileSystemDataset<Record> dsUpdate = new FileSystemDataset.Builder<Record>() .namespace("ns") .name("users") .configuration(getConfiguration()) .descriptor(new DatasetDescriptor.Builder() .schema(USER_SCHEMA) .location(testDirectory) .partitionStrategy(new PartitionStrategy.Builder() .hash("username", 2).hash("email", 3).build()) .build()) .type(Record.class) .build(); ds.merge(dsUpdate); } @Test(expected = ValidationException.class) public void testCannotMergeDatasetsWithDifferentSchemas() throws IOException { FileSystemDataset<Record> ds = new FileSystemDataset.Builder<Record>() .namespace("ns") .name("users") .configuration(getConfiguration()) .descriptor(new DatasetDescriptor.Builder() .schema(STRING_SCHEMA) .location(testDirectory) .build()) .type(Record.class) .build(); FileSystemDataset<Record> dsUpdate = new FileSystemDataset.Builder<Record>() .namespace("ns") .name("users") .configuration(getConfiguration()) .descriptor(new DatasetDescriptor.Builder() .schema(USER_SCHEMA) .location(testDirectory) .build()) .type(Record.class) .build(); ds.merge(dsUpdate); } @Test public void testPathIterator_Directory() { FileSystemDataset<Record> ds = new FileSystemDataset.Builder<Record>() .namespace("ns") .name("users") .configuration(getConfiguration()) .descriptor(new DatasetDescriptor.Builder() .schema(USER_SCHEMA) .format(format) .compressionType(compressionType) .location(testDirectory) .build()) .type(Record.class) .build(); List<Path> dirPaths = Lists.newArrayList(ds.dirIterator()); Assert.assertEquals("dirIterator for non-partitioned dataset should yield a single path.", 1, dirPaths.size()); Assert.assertEquals("dirIterator should yield absolute paths.", testDirectory, dirPaths.get(0)); } @Test @SuppressWarnings("deprecation") public void testPathIterator_Partition_Directory() { PartitionStrategy partitionStrategy = new PartitionStrategy.Builder() .hash("username", 2).hash("email", 3).build(); final FileSystemDataset<Record> ds = new FileSystemDataset.Builder<Record>() .namespace("ns") .name("partitioned-users") .configuration(getConfiguration()) .descriptor(new DatasetDescriptor.Builder() .schema(USER_SCHEMA) .format(format) .compressionType(compressionType) .location(testDirectory) .partitionStrategy(partitionStrategy) .build()) .type(Record.class) .build(); Assert.assertTrue("Dataset is partitioned", ds.getDescriptor() .isPartitioned()); Assert.assertEquals(partitionStrategy, ds.getDescriptor() .getPartitionStrategy()); writeTestUsers(ds, 10); checkTestUsers(ds, 10); List<Path> dirPaths = Lists.newArrayList(ds.dirIterator()); // 2 user directories * 3 email directories Assert.assertEquals(6, dirPaths.size()); Assert.assertTrue("dirIterator should yield absolute paths.", dirPaths.get(0).isAbsolute()); FileSystemDataset<Record> partition = (FileSystemDataset<Record>) ds.getPartition(new PartitionKey(1, 2), false); List<Path> leafPaths = Lists.newArrayList(partition.dirIterator()); Assert.assertEquals(1, leafPaths.size()); final Path leafPath = leafPaths.get(0); Assert.assertTrue("dirIterator should yield absolute paths.", leafPath.isAbsolute()); Assert.assertEquals(new PartitionKey(1, 2), ds.keyFromDirectory(leafPath)); Assert.assertEquals(new PartitionKey(1), ds.keyFromDirectory(leafPath.getParent())); Assert.assertEquals(new PartitionKey(), ds.keyFromDirectory(leafPath.getParent().getParent())); TestHelpers.assertThrows("Path with too many components", IllegalStateException.class, new Runnable() { @Override public void run() { ds.keyFromDirectory(new Path(leafPath, "extra_dir")); } }); TestHelpers.assertThrows("Non-relative path", IllegalStateException.class, new Runnable() { @Override public void run() { ds.keyFromDirectory(new Path("hdfs://different_host/")); } }); } @Test public void testDeleteAllWithoutPartitions() { final FileSystemDataset<Record> ds = new FileSystemDataset.Builder<Record>() .namespace("ns") .name("users") .configuration(getConfiguration()) .descriptor( new DatasetDescriptor.Builder().schema(USER_SCHEMA).format(format) .location(testDirectory).build()) .type(Record.class) .build(); writeTestUsers(ds, 10); Assert.assertTrue(ds.deleteAll()); checkReaderBehavior(ds.newReader(), 0, (RecordValidator<Record>) null); } @Test public void signalReadyOnUnboundedDataset() { final FileSystemDataset<Record> ds = new FileSystemDataset.Builder<Record>() .namespace("ns") .name("users") .configuration(getConfiguration()) .descriptor( new DatasetDescriptor.Builder().schema(USER_SCHEMA).format(format) .location(testDirectory).build()) .type(Record.class) .uri(URIBuilder.build(URI.create("repo:" + testDirectory.toUri()), "ns", "name")) .build(); Assert.assertFalse("Unbounded dataset has not been signaled", ds.isReady()); ds.signalReady(); Assert.assertTrue("Unbounded dataset has been signaled and should be ready", ds.isReady()); } @Test public void testReadySignalUpdatesModifiedTime() { final FileSystemDataset<Record> ds = new FileSystemDataset.Builder<Record>() .namespace("ns") .name("users") .configuration(getConfiguration()) .descriptor( new DatasetDescriptor.Builder().schema(USER_SCHEMA).format(format) .location(testDirectory).build()) .type(Record.class) .uri(URIBuilder.build(URI.create("repo:" + testDirectory.toUri()), "ns", "name")) .build(); Assert.assertFalse("Dataset should not be ready before being signaled", ds.isReady()); // the modified time depends on the filesystem, and may only be granular to the second // signal and check until the modified time is after the current time, or until // enough time has past that the signal should have been distinguishable long signaledTime = 0; long currentTime = System.currentTimeMillis(); while(currentTime >= signaledTime && (System.currentTimeMillis() - currentTime) <= 2000) { ds.signalReady(); signaledTime = ds.getLastModified(); } Assert.assertTrue("Dataset should have been signaled as ready", ds.isReady()); Assert.assertTrue("Signal should update the modified time", signaledTime > currentTime); Assert.assertFalse("Only the dataset should have been signaled", ((Signalable)ds.with("username", "bob")).isReady()); } @SuppressWarnings("deprecation") private int readTestUsersInPartition(FileSystemDataset<Record> ds, PartitionKey key, String subpartitionName) { int readCount = 0; DatasetReader<Record> reader = null; try { PartitionedDataset<Record> partition = ds.getPartition(key, false); if (subpartitionName != null) { List<FieldPartitioner> fieldPartitioners = Accessor.getDefault().getFieldPartitioners(partition.getDescriptor() .getPartitionStrategy()); Assert.assertEquals(1, fieldPartitioners.size()); Assert.assertEquals(subpartitionName, fieldPartitioners.get(0) .getName()); } reader = partition.newReader(); for (GenericData.Record actualRecord : reader) { Assert.assertEquals(actualRecord.toString(), key.get(0), (actualRecord .get("username").hashCode() & Integer.MAX_VALUE) % 2); if (key.getLength() > 1) { Assert.assertEquals(key.get(1), (actualRecord.get("email").hashCode() & Integer.MAX_VALUE) % 3); } readCount++; } } finally { if (reader != null) { reader.close(); } } return readCount; } }
gabrielreid/kite
kite-data/kite-data-core/src/test/java/org/kitesdk/data/spi/filesystem/TestFileSystemDataset.java
Java
apache-2.0
25,117
/* * Copyright (C) 2013 salesforce.com, 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.auraframework.impl.java.type; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import org.auraframework.builder.DefBuilder; import org.auraframework.def.DefDescriptor; import org.auraframework.def.TypeDef; import org.auraframework.impl.java.BaseJavaDefFactory; import org.auraframework.system.SourceLoader; import org.auraframework.util.AuraTextUtil; /** * Loads Java types for Aura components. */ public class JavaTypeDefFactory extends BaseJavaDefFactory<TypeDef> { public JavaTypeDefFactory() { this(null); } public JavaTypeDefFactory(List<SourceLoader> sourceLoaders) { super(sourceLoaders); } @Override protected DefBuilder<?, ? extends TypeDef> getBuilder(DefDescriptor<TypeDef> descriptor) { JavaTypeDef.Builder builder; Class<?> clazz = getClazz(descriptor); if (clazz == null) { return null; } builder = new JavaTypeDef.Builder(); builder.setDescriptor(descriptor); builder.setLocation(clazz.getCanonicalName(), 0); builder.setTypeClass(clazz); return builder; } /** * Return base of class name, truncating Generic qualifier, if included. * Can't instantiate a class with parameters using Class.forName(). * * @param className - the class name, with or without a < > clause * @return - the base class name minus generic parameters */ private String getRawClassName(String className) { int genPos = className.indexOf('<'); String name = genPos == -1 ? className : className.substring(0, genPos); return name; } @Override protected Class<?> getClazz(DefDescriptor<TypeDef> descriptor) { Class<?> clazz = null; String className = descriptor.getName(); if (descriptor.getNamespace() == null) { if (className.equals("List") || className.startsWith("List<") || className.endsWith("[]")) { clazz = ArrayList.class; } else if (className.equals("Map") || className.startsWith("Map<")) { clazz = HashMap.class; } else if (className.equals("Set") || className.startsWith("Set<")) { clazz = HashSet.class; } else if (className.equals("Decimal")) { clazz = BigDecimal.class; } else if (className.equals("Date")) { clazz = Date.class; } else if (className.equals("DateTime")) { clazz = Calendar.class; } else if (className.equals("int")) { clazz = Integer.class; } else if (className.equals("char")) { clazz = Character.class; } else { try { clazz = Class.forName("java.lang." + AuraTextUtil.initCap(className)); } catch (ClassNotFoundException e) { // ignore } } } else { className = String.format("%s.%s", descriptor.getNamespace(), getRawClassName(className)); } if (clazz == null) { try { clazz = Class.forName(className); } catch (ClassNotFoundException e) { // ignore } } return clazz; } }
TribeMedia/aura
aura-impl/src/main/java/org/auraframework/impl/java/type/JavaTypeDefFactory.java
Java
apache-2.0
4,048
/** * 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.fs.s3a; import com.amazonaws.auth.InstanceProfileCredentialsProvider; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; /** * A subclass of {@link InstanceProfileCredentialsProvider} that enforces * instantiation of only a single instance. * This credential provider calls the EC2 instance metadata service to obtain * credentials. For highly multi-threaded applications, it's possible that * multiple instances call the service simultaneously and overwhelm it with * load. The service handles this by throttling the client with an HTTP 429 * response or forcibly terminating the connection. Forcing use of a single * instance reduces load on the metadata service by allowing all threads to * share the credentials. The base class is thread-safe, and there is nothing * that varies in the credentials across different instances of * {@link S3AFileSystem} connecting to different buckets, so sharing a singleton * instance is safe. * * As of AWS SDK 1.11.39, the SDK code internally enforces a singleton. After * Hadoop upgrades to that version or higher, it's likely that we can remove * this class. */ @InterfaceAudience.Private @InterfaceStability.Stable public final class SharedInstanceProfileCredentialsProvider extends InstanceProfileCredentialsProvider { private static final SharedInstanceProfileCredentialsProvider INSTANCE = new SharedInstanceProfileCredentialsProvider(); /** * Returns the singleton instance. * * @return singleton instance */ public static SharedInstanceProfileCredentialsProvider getInstance() { return INSTANCE; } /** * Default constructor, defined explicitly as private to enforce singleton. */ private SharedInstanceProfileCredentialsProvider() { super(); } }
grahamar/hadoop-aws
src/main/java/org/apache/hadoop/fs/s3a/SharedInstanceProfileCredentialsProvider.java
Java
apache-2.0
2,674
/** * Copyright (C) 2008 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.inject.internal; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.google.inject.Binder; import com.google.inject.Key; import com.google.inject.Module; import com.google.inject.Provider; import com.google.inject.Provides; import com.google.inject.TypeLiteral; import com.google.inject.spi.Dependency; import com.google.inject.spi.Message; import com.google.inject.util.Modules; import java.lang.annotation.Annotation; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.List; import java.util.logging.Logger; /** * Creates bindings to methods annotated with {@literal @}{@link Provides}. Use the scope and * binding annotations on the provider method to configure the binding. * * @author crazybob@google.com (Bob Lee) * @author jessewilson@google.com (Jesse Wilson) */ public final class ProviderMethodsModule implements Module { private final Object delegate; private final TypeLiteral<?> typeLiteral; private ProviderMethodsModule(Object delegate) { this.delegate = checkNotNull(delegate, "delegate"); this.typeLiteral = TypeLiteral.get(this.delegate.getClass()); } /** * Returns a module which creates bindings for provider methods from the given module. */ public static Module forModule(Module module) { return forObject(module); } /** * Returns a module which creates bindings for provider methods from the given object. * This is useful notably for <a href="http://code.google.com/p/google-gin/">GIN</a> */ public static Module forObject(Object object) { // avoid infinite recursion, since installing a module always installs itself if (object instanceof ProviderMethodsModule) { return Modules.EMPTY_MODULE; } return new ProviderMethodsModule(object); } public synchronized void configure(Binder binder) { for (ProviderMethod<?> providerMethod : getProviderMethods(binder)) { providerMethod.configure(binder); } } public List<ProviderMethod<?>> getProviderMethods(Binder binder) { List<ProviderMethod<?>> result = Lists.newArrayList(); Multimap<Signature, Method> methodsBySignature = HashMultimap.create(); for (Class<?> c = delegate.getClass(); c != Object.class; c = c.getSuperclass()) { for (Method method : c.getDeclaredMethods()) { // private/static methods cannot override or be overridden by other methods, so there is no // point in indexing them. // Skip synthetic methods and bridge methods since java will automatically generate // synthetic overrides in some cases where we don't want to generate an error (e.g. // increasing visibility of a subclass). if (((method.getModifiers() & (Modifier.PRIVATE | Modifier.STATIC)) == 0) && !method.isBridge() && !method.isSynthetic()) { methodsBySignature.put(new Signature(method), method); } if (isProvider(method)) { result.add(createProviderMethod(binder, method)); } } } // we have found all the providers and now need to identify if any were overridden // In the worst case this will have O(n^2) in the number of @Provides methods, but that is only // assuming that every method is an override, in general it should be very quick. for (ProviderMethod<?> provider : result) { Method method = provider.getMethod(); for (Method matchingSignature : methodsBySignature.get(new Signature(method))) { // matching signature is in the same class or a super class, therefore method cannot be // overridding it. if (matchingSignature.getDeclaringClass().isAssignableFrom(method.getDeclaringClass())) { continue; } // now we know matching signature is in a subtype of method.getDeclaringClass() if (overrides(matchingSignature, method)) { binder.addError( "Overriding @Provides methods is not allowed." + "\n\t@Provides method: %s\n\toverridden by: %s", method, matchingSignature); break; } } } return result; } /** * Returns true if the method is a provider. * * Synthetic bridge methods are excluded. Starting with JDK 8, javac copies annotations onto * bridge methods (which always have erased signatures). */ private static boolean isProvider(Method method) { return !method.isBridge() && !method.isSynthetic() && method.isAnnotationPresent(Provides.class); } private final class Signature { final Class<?>[] parameters; final String name; final int hashCode; Signature(Method method) { this.name = method.getName(); // We need to 'resolve' the parameters against the actual class type in case this method uses // type parameters. This is so we can detect overrides of generic superclass methods where // the subclass specifies the type parameter. javac implements these kinds of overrides via // bridge methods, but we don't want to give errors on bridge methods (but rather the target // of the bridge). List<TypeLiteral<?>> resolvedParameterTypes = typeLiteral.getParameterTypes(method); this.parameters = new Class<?>[resolvedParameterTypes.size()]; int i = 0; for (TypeLiteral<?> type : resolvedParameterTypes) { parameters[i] = type.getRawType(); } this.hashCode = name.hashCode() + 31 * Arrays.hashCode(parameters); } @Override public boolean equals(Object obj) { if (obj instanceof Signature) { Signature other = (Signature) obj; return other.name.equals(name) && Arrays.equals(parameters, other.parameters); } return false; } @Override public int hashCode() { return hashCode; } } /** Returns true if a overrides b, assumes that the signatures match */ private static boolean overrides(Method a, Method b) { // See JLS section 8.4.8.1 int modifiers = b.getModifiers(); if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers)) { return true; } if (Modifier.isPrivate(modifiers)) { return false; } // b must be package-private return a.getDeclaringClass().getPackage().equals(b.getDeclaringClass().getPackage()); } private <T> ProviderMethod<T> createProviderMethod(Binder binder, Method method) { binder = binder.withSource(method); Errors errors = new Errors(method); // prepare the parameter providers List<Dependency<?>> dependencies = Lists.newArrayList(); List<Provider<?>> parameterProviders = Lists.newArrayList(); List<TypeLiteral<?>> parameterTypes = typeLiteral.getParameterTypes(method); Annotation[][] parameterAnnotations = method.getParameterAnnotations(); for (int i = 0; i < parameterTypes.size(); i++) { Key<?> key = getKey(errors, parameterTypes.get(i), method, parameterAnnotations[i]); if(key.equals(Key.get(Logger.class))) { // If it was a Logger, change the key to be unique & bind it to a // provider that provides a logger with a proper name. // This solves issue 482 (returning a new anonymous logger on every call exhausts memory) Key<Logger> loggerKey = Key.get(Logger.class, UniqueAnnotations.create()); binder.bind(loggerKey).toProvider(new LogProvider(method)); key = loggerKey; } dependencies.add(Dependency.get(key)); parameterProviders.add(binder.getProvider(key)); } @SuppressWarnings("unchecked") // Define T as the method's return type. TypeLiteral<T> returnType = (TypeLiteral<T>) typeLiteral.getReturnType(method); Key<T> key = getKey(errors, returnType, method, method.getAnnotations()); Class<? extends Annotation> scopeAnnotation = Annotations.findScopeAnnotation(errors, method.getAnnotations()); for (Message message : errors.getMessages()) { binder.addError(message); } return ProviderMethod.create(key, method, delegate, ImmutableSet.copyOf(dependencies), parameterProviders, scopeAnnotation); } <T> Key<T> getKey(Errors errors, TypeLiteral<T> type, Member member, Annotation[] annotations) { Annotation bindingAnnotation = Annotations.findBindingAnnotation(errors, member, annotations); return bindingAnnotation == null ? Key.get(type) : Key.get(type, bindingAnnotation); } @Override public boolean equals(Object o) { return o instanceof ProviderMethodsModule && ((ProviderMethodsModule) o).delegate == delegate; } @Override public int hashCode() { return delegate.hashCode(); } /** A provider that returns a logger based on the method name. */ private static final class LogProvider implements Provider<Logger> { private final String name; public LogProvider(Method method) { this.name = method.getDeclaringClass().getName() + "." + method.getName(); } public Logger get() { return Logger.getLogger(name); } } }
bineanzhou/google-guice
core/src/com/google/inject/internal/ProviderMethodsModule.java
Java
apache-2.0
9,907
/* * Copyright (c) 2013-2015 Cinchapi 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.cinchapi.concourse.importer.cli; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.text.MessageFormat; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.cinchapi.concourse.cli.CommandLineInterface; import org.cinchapi.concourse.cli.Options; import org.cinchapi.concourse.importer.CsvImporter; import org.cinchapi.concourse.importer.Importer; import org.cinchapi.concourse.util.FileOps; import com.beust.jcommander.Parameter; import com.google.common.base.Stopwatch; import com.google.common.base.Throwables; import com.google.common.collect.Lists; import com.google.common.collect.Sets; /** * A CLI that uses the import framework to import data into Concourse. * * @author Jeff Nelson */ public class ImportCli extends CommandLineInterface { /* * TODO * 1) add flag to specify importer (default will be CSV..or maybe auto * detect??) * 2) add flags to whitelist or blacklist files in a directory * 3) add option to configure verbosity */ /** * The importer. */ private final Importer importer; /** * Construct a new instance. * * @param args */ public ImportCli(String[] args) { super(new ImportOptions(), args); this.importer = new CsvImporter(this.concourse, log); } @Override protected void doTask() { System.out.println("Starting import..."); final ImportOptions opts = (ImportOptions) options; ExecutorService executor = Executors .newFixedThreadPool(((ImportOptions) options).numThreads); String data = opts.data; List<String> files = scan(Paths.get(FileOps.expandPath(data, getLaunchDirectory()))); Stopwatch watch = Stopwatch.createStarted(); final Set<Long> records = Sets.newConcurrentHashSet(); for (final String file : files) { executor.execute(new Runnable() { @Override public void run() { records.addAll(importer.importFile(file)); } }); } executor.shutdown(); while (!executor.isTerminated()) { continue; // block until all tasks are completed } watch.stop(); long elapsed = watch.elapsed(TimeUnit.MILLISECONDS); double seconds = elapsed / 1000.0; if(options.verbose) { System.out.println(records); } System.out.println(MessageFormat.format("Imported data " + "into {0} records in {1} seconds", records.size(), seconds)); } /** * Recursively scan and collect all the files in the directory defined by * {@code path}. * * @param path * @return the list of files in the directory */ protected List<String> scan(Path path) { try { List<String> files = Lists.newArrayList(); if(java.nio.file.Files.isDirectory(path)) { Iterator<Path> it = java.nio.file.Files .newDirectoryStream(path).iterator(); while (it.hasNext()) { files.addAll(scan(it.next())); } } else { files.add(path.toString()); } return files; } catch (IOException e) { throw Throwables.propagate(e); } } /** * Import specific {@link Options}. * * @author jnelson */ protected static class ImportOptions extends Options { @Parameter(names = { "-d", "--data" }, description = "The path to the file or directory to import", required = true) public String data; @Parameter(names = "--numThreads", description = "The number of worker threads to use for a multithreaded import") public int numThreads = 1; @Parameter(names = { "-r", "--resolveKey" }, description = "The key to use when resolving data into existing records") public String resolveKey = null; } }
bigtreeljc/concourse
concourse-import/src/main/java/org/cinchapi/concourse/importer/cli/ImportCli.java
Java
apache-2.0
4,839
/* * Copyright 2014 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.apiman.manager.api.rest.contract.exceptions; /** * Thrown when trying to create an Client that already exists. * * @author eric.wittmann@redhat.com */ public class ClientAlreadyExistsException extends AbstractAlreadyExistsException { private static final long serialVersionUID = 3643381549889270663L; /** * Constructor. */ public ClientAlreadyExistsException() { } /** * Constructor. * @param message the message */ public ClientAlreadyExistsException(String message) { super(message); } /** * @see io.apiman.manager.api.rest.contract.exceptions.AbstractRestException#getErrorCode() */ @Override public int getErrorCode() { return ErrorCodes.CLIENT_ALREADY_EXISTS; } /** * @see io.apiman.manager.api.rest.contract.exceptions.AbstractRestException#getMoreInfoUrl() */ @Override public String getMoreInfoUrl() { return ErrorCodes.CLIENT_ALREADY_EXISTS_INFO; } }
jasonchaffee/apiman
manager/api/rest/src/main/java/io/apiman/manager/api/rest/contract/exceptions/ClientAlreadyExistsException.java
Java
apache-2.0
1,619
/** * 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.master; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.Date; import java.util.concurrent.atomic.AtomicLong; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos; /** * State of a Region while undergoing transitions. * Region state cannot be modified except the stamp field. * So it is almost immutable. */ @InterfaceAudience.Private public class RegionState implements org.apache.hadoop.io.Writable { @InterfaceAudience.Public @InterfaceStability.Evolving public enum State { OFFLINE, // region is in an offline state PENDING_OPEN, // sent rpc to server to open but has not begun OPENING, // server has begun to open but not yet done OPEN, // server opened region and updated meta PENDING_CLOSE, // sent rpc to server to close but has not begun CLOSING, // server has begun to close but not yet done CLOSED, // server closed region and updated meta SPLITTING, // server started split of a region SPLIT, // server completed split of a region FAILED_OPEN, // failed to open, and won't retry any more FAILED_CLOSE, // failed to close, and won't retry any more MERGING, // server started merge a region MERGED, // server completed merge a region SPLITTING_NEW, // new region to be created when RS splits a parent // region but hasn't be created yet, or master doesn't // know it's already created MERGING_NEW // new region to be created when RS merges two // daughter regions but hasn't be created yet, or // master doesn't know it's already created } // Many threads can update the state at the stamp at the same time private final AtomicLong stamp; private HRegionInfo hri; private volatile ServerName serverName; private volatile State state; public RegionState() { this.stamp = new AtomicLong(System.currentTimeMillis()); } public RegionState(HRegionInfo region, State state) { this(region, state, System.currentTimeMillis(), null); } public RegionState(HRegionInfo region, State state, long stamp, ServerName serverName) { this.hri = region; this.state = state; this.stamp = new AtomicLong(stamp); this.serverName = serverName; } public void updateTimestampToNow() { setTimestamp(System.currentTimeMillis()); } public State getState() { return state; } public long getStamp() { return stamp.get(); } public HRegionInfo getRegion() { return hri; } public ServerName getServerName() { return serverName; } public boolean isClosing() { return state == State.CLOSING; } public boolean isClosed() { return state == State.CLOSED; } public boolean isPendingClose() { return state == State.PENDING_CLOSE; } public boolean isOpening() { return state == State.OPENING; } public boolean isOpened() { return state == State.OPEN; } public boolean isPendingOpen() { return state == State.PENDING_OPEN; } public boolean isOffline() { return state == State.OFFLINE; } public boolean isSplitting() { return state == State.SPLITTING; } public boolean isSplit() { return state == State.SPLIT; } public boolean isSplittingNew() { return state == State.SPLITTING_NEW; } public boolean isFailedOpen() { return state == State.FAILED_OPEN; } public boolean isFailedClose() { return state == State.FAILED_CLOSE; } public boolean isMerging() { return state == State.MERGING; } public boolean isMerged() { return state == State.MERGED; } public boolean isMergingNew() { return state == State.MERGING_NEW; } public boolean isOpenOrMergingOnServer(final ServerName sn) { return isOnServer(sn) && (isOpened() || isMerging()); } public boolean isOpenOrMergingNewOnServer(final ServerName sn) { return isOnServer(sn) && (isOpened() || isMergingNew()); } public boolean isOpenOrSplittingOnServer(final ServerName sn) { return isOnServer(sn) && (isOpened() || isSplitting()); } public boolean isOpenOrSplittingNewOnServer(final ServerName sn) { return isOnServer(sn) && (isOpened() || isSplittingNew()); } public boolean isPendingOpenOrOpeningOnServer(final ServerName sn) { return isOnServer(sn) && isPendingOpenOrOpening(); } // Failed open is also kind of pending open public boolean isPendingOpenOrOpening() { return isPendingOpen() || isOpening() || isFailedOpen(); } public boolean isPendingCloseOrClosingOnServer(final ServerName sn) { return isOnServer(sn) && isPendingCloseOrClosing(); } // Failed close is also kind of pending close public boolean isPendingCloseOrClosing() { return isPendingClose() || isClosing() || isFailedClose(); } public boolean isOnServer(final ServerName sn) { return serverName != null && serverName.equals(sn); } /** * Check if a region state can transition to offline */ public boolean isReadyToOffline() { return isMerged() || isSplit() || isOffline() || isSplittingNew() || isMergingNew(); } /** * Check if a region state can transition to online */ public boolean isReadyToOnline() { return isOpened() || isSplittingNew() || isMergingNew(); } /** * Check if a region state is one of offline states that * can't transition to pending_close/closing (unassign/offline) */ public boolean isUnassignable() { return isUnassignable(state); } /** * Check if a region state is one of offline states that * can't transition to pending_close/closing (unassign/offline) */ public static boolean isUnassignable(State state) { return state == State.MERGED || state == State.SPLIT || state == State.OFFLINE || state == State.SPLITTING_NEW || state == State.MERGING_NEW; } @Override public String toString() { return "{" + hri.getShortNameToLog() + " state=" + state + ", ts=" + stamp + ", server=" + serverName + "}"; } /** * A slower (but more easy-to-read) stringification */ public String toDescriptiveString() { long lstamp = stamp.get(); long relTime = System.currentTimeMillis() - lstamp; return hri.getRegionNameAsString() + " state=" + state + ", ts=" + new Date(lstamp) + " (" + (relTime/1000) + "s ago)" + ", server=" + serverName; } /** * Convert a RegionState to an HBaseProtos.RegionState * * @return the converted HBaseProtos.RegionState */ public ClusterStatusProtos.RegionState convert() { ClusterStatusProtos.RegionState.Builder regionState = ClusterStatusProtos.RegionState.newBuilder(); ClusterStatusProtos.RegionState.State rs; switch (regionState.getState()) { case OFFLINE: rs = ClusterStatusProtos.RegionState.State.OFFLINE; break; case PENDING_OPEN: rs = ClusterStatusProtos.RegionState.State.PENDING_OPEN; break; case OPENING: rs = ClusterStatusProtos.RegionState.State.OPENING; break; case OPEN: rs = ClusterStatusProtos.RegionState.State.OPEN; break; case PENDING_CLOSE: rs = ClusterStatusProtos.RegionState.State.PENDING_CLOSE; break; case CLOSING: rs = ClusterStatusProtos.RegionState.State.CLOSING; break; case CLOSED: rs = ClusterStatusProtos.RegionState.State.CLOSED; break; case SPLITTING: rs = ClusterStatusProtos.RegionState.State.SPLITTING; break; case SPLIT: rs = ClusterStatusProtos.RegionState.State.SPLIT; break; case FAILED_OPEN: rs = ClusterStatusProtos.RegionState.State.FAILED_OPEN; break; case FAILED_CLOSE: rs = ClusterStatusProtos.RegionState.State.FAILED_CLOSE; break; case MERGING: rs = ClusterStatusProtos.RegionState.State.MERGING; break; case MERGED: rs = ClusterStatusProtos.RegionState.State.MERGED; break; case SPLITTING_NEW: rs = ClusterStatusProtos.RegionState.State.SPLITTING_NEW; break; case MERGING_NEW: rs = ClusterStatusProtos.RegionState.State.MERGING_NEW; break; default: throw new IllegalStateException(""); } regionState.setRegionInfo(HRegionInfo.convert(hri)); regionState.setState(rs); regionState.setStamp(getStamp()); return regionState.build(); } /** * Convert a protobuf HBaseProtos.RegionState to a RegionState * * @return the RegionState */ public static RegionState convert(ClusterStatusProtos.RegionState proto) { RegionState.State state; switch (proto.getState()) { case OFFLINE: state = State.OFFLINE; break; case PENDING_OPEN: state = State.PENDING_OPEN; break; case OPENING: state = State.OPENING; break; case OPEN: state = State.OPEN; break; case PENDING_CLOSE: state = State.PENDING_CLOSE; break; case CLOSING: state = State.CLOSING; break; case CLOSED: state = State.CLOSED; break; case SPLITTING: state = State.SPLITTING; break; case SPLIT: state = State.SPLIT; break; case FAILED_OPEN: state = State.FAILED_OPEN; break; case FAILED_CLOSE: state = State.FAILED_CLOSE; break; case MERGING: state = State.MERGING; break; case MERGED: state = State.MERGED; break; case SPLITTING_NEW: state = State.SPLITTING_NEW; break; case MERGING_NEW: state = State.MERGING_NEW; break; default: throw new IllegalStateException(""); } return new RegionState(HRegionInfo.convert(proto.getRegionInfo()),state,proto.getStamp(),null); } protected void setTimestamp(final long timestamp) { stamp.set(timestamp); } /** * @deprecated Writables are going away */ @Deprecated @Override public void readFields(DataInput in) throws IOException { hri = new HRegionInfo(); hri.readFields(in); state = State.valueOf(in.readUTF()); stamp.set(in.readLong()); } /** * @deprecated Writables are going away */ @Deprecated @Override public void write(DataOutput out) throws IOException { hri.write(out); out.writeUTF(state.name()); out.writeLong(stamp.get()); } }
throughsky/lywebank
hbase-client/src/main/java/org/apache/hadoop/hbase/master/RegionState.java
Java
apache-2.0
11,496
/** * Copyright 2009 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 org.waveprotocol.wave.model.document.operation; /** * A <code>DocOpCursor</code> that can return a value at the end of a sequence * of operation components. * * @param <T> the type of the value returned by an instance of this interface */ public interface EvaluatingDocInitializationCursor<T> extends DocInitializationCursor { /** * Signals the completion of the sequence of mutation events and returns a * value. * * @return a value returned after all the mutation events have been applied. */ T finish(); }
processone/google-wave-api
wave-model/src/main/java/org/waveprotocol/wave/model/document/operation/EvaluatingDocInitializationCursor.java
Java
apache-2.0
1,143
// // Copyright (c) 2015 VK.com // // 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 com.vk.sdk.payments; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.support.annotation.NonNull; import java.util.HashSet; class VKPaymentsDatabase extends SQLiteOpenHelper { private static int VERSION = 1; public static final String DATABASE_NAME = "vk_sdk_db"; public static final String TABLE_PURCHASE_INFO = "vk_sdk_table_purchase_info"; public static final String TABLE_PURCHASE_INFO_PURCHASE = "purchase"; public static final String TABLE_PURCHASE_INFO_CREATE_SQL = "CREATE TABLE IF NOT EXISTS " + TABLE_PURCHASE_INFO + " (" + TABLE_PURCHASE_INFO_PURCHASE + " TEXT);"; private static VKPaymentsDatabase sInstance; // ---------- PURCHASE INFO ---------- public void insertPurchase(String purchase) { SQLiteDatabase db = getWritableDatabase(); ContentValues values = new ContentValues(); values.put(TABLE_PURCHASE_INFO_PURCHASE, purchase); db.insert(TABLE_PURCHASE_INFO, TABLE_PURCHASE_INFO_PURCHASE, values); } public void deletePurchase(String purchase) { SQLiteDatabase db = getWritableDatabase(); db.delete(TABLE_PURCHASE_INFO, TABLE_PURCHASE_INFO_PURCHASE + "=?", new String[]{purchase}); } public HashSet<String> getPurchases() { SQLiteDatabase db = getReadableDatabase(); Cursor cursor = db.query(TABLE_PURCHASE_INFO, new String[]{TABLE_PURCHASE_INFO_PURCHASE}, null, null, null, null, null); HashSet<String> set = new HashSet<>(); if (cursor.moveToFirst()) { do { set.add(cursor.getString(0)); } while (cursor.moveToNext()); } cursor.close(); return set; } // ---------- SQLITE OPEN HELPER PART ---------- public static VKPaymentsDatabase getInstance(@NonNull Context context) { if (sInstance == null) { synchronized (VKPaymentsDatabase.class) { if (sInstance == null) { sInstance = new VKPaymentsDatabase(context); } } } return sInstance; } private VKPaymentsDatabase(@NonNull Context context) { super(context.getApplicationContext(), DATABASE_NAME, null, VERSION); } @Override public void onCreate(SQLiteDatabase arg0) { arg0.execSQL(TABLE_PURCHASE_INFO_CREATE_SQL); } @Override public void onUpgrade(SQLiteDatabase arg0, int oldVersion, int newVersion) { } }
programmerr47/vk-mobile-challenge
vksdk_library/src/main/java/com/vk/sdk/payments/VKPaymentsDatabase.java
Java
apache-2.0
3,752
/* * 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 to test JOrphanUtils methods */ package org.apache.jorphan.exec; import java.io.IOException; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; public class TestKeyToolUtils extends TestCase { public TestKeyToolUtils() { super(); } public TestKeyToolUtils(String arg0) { super(arg0); } /* * Check the assumption that a missing executable will generate * either an IOException or status which is neither 0 nor 1 * */ public void testCheckKeytool() throws Exception { SystemCommand sc = new SystemCommand(null, null); List<String> arguments = new ArrayList<>(); arguments.add("xyzqwas"); // should not exist try { int status = sc.run(arguments); if (status == 0 || status ==1) { fail("Unexpected status " + status); } // System.out.println("testCheckKeytool:status="+status); } catch (IOException expected) { // System.out.println("testCheckKeytool:Exception="+e); } } }
hemikak/jmeter
test/src/org/apache/jorphan/exec/TestKeyToolUtils.java
Java
apache-2.0
1,923
/*========================================================================= * Copyright (c) 2010-2014 Pivotal Software, Inc. All Rights Reserved. * This product is protected by U.S. and international copyright * and intellectual property laws. Pivotal products are covered by * one or more patents listed at http://www.pivotal.io/patents. *========================================================================= */ /** * */ package com.gemstone.gemfire.internal.cache; import com.gemstone.gemfire.cache.RegionShortcut; import com.gemstone.gemfire.cache.Region; import com.gemstone.gemfire.cache30.CacheTestCase; import java.util.Iterator; import dunit.Host; import dunit.SerializableCallable; import dunit.VM; /** * Test that keys iterator do not returned keys with removed token as its values * @author sbawaska * */ public class IteratorDUnitTest extends CacheTestCase { /** * @param name */ public IteratorDUnitTest(String name) { super(name); } public void testKeysIteratorOnLR() throws Exception { final String regionName = getUniqueName(); Region r = getGemfireCache().createRegionFactory(RegionShortcut.REPLICATE).create(regionName); r.put("key", "value"); r.put("key2", "value2"); r.put("key3", "value3"); LocalRegion lr = (LocalRegion)r; // simulate a removed key // lr.getRegionMap().getEntry("key")._setValue(Token.REMOVED_PHASE1); lr.getRegionMap().getEntry("key").setValue(lr,Token.REMOVED_PHASE1); Iterator it = r.keySet().iterator(); int numKeys = 0; while (it.hasNext()) { it.next(); numKeys++; } assertEquals(2, numKeys); } public void testKeysIteratorOnPR() { Host host = Host.getHost(0); VM accessor = host.getVM(0); VM datastore = host.getVM(1); final String regionName = getUniqueName(); accessor.invoke(new SerializableCallable() { public Object call() throws Exception { getGemfireCache().createRegionFactory(RegionShortcut.PARTITION_PROXY).create(regionName); return null; } }); datastore.invoke(new SerializableCallable() { public Object call() throws Exception { Region r = getGemfireCache().createRegionFactory(RegionShortcut.PARTITION).create(regionName); r.put("key", "value"); r.put("key2", "value2"); r.put("key3", "value3"); PartitionedRegion pr = (PartitionedRegion)r; BucketRegion br = pr.getBucketRegion("key"); assertNotNull(br); // simulate a removed key br.getRegionMap().getEntry("key").setValue(pr,Token.REMOVED_PHASE1); return null; } }); accessor.invoke(new SerializableCallable() { public Object call() throws Exception { Region r = getGemfireCache().getRegion(regionName); Iterator it = r.keySet().iterator(); int numKeys = 0; while (it.hasNext()) { it.next(); numKeys++; } assertEquals(2, numKeys); return null; } }); } }
fengshao0907/incubator-geode
gemfire-core/src/test/java/com/gemstone/gemfire/internal/cache/IteratorDUnitTest.java
Java
apache-2.0
3,035
/** * <copyright> * </copyright> * * $Id$ */ package org.wso2.developerstudio.eclipse.gmf.esb.provider; import java.util.Collection; import java.util.List; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.edit.provider.IEditingDomainItemProvider; import org.eclipse.emf.edit.provider.IItemLabelProvider; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor; import org.eclipse.emf.edit.provider.IItemPropertySource; import org.eclipse.emf.edit.provider.IStructuredItemContentProvider; import org.eclipse.emf.edit.provider.ITreeItemContentProvider; /** * This is the item provider adapter for a {@link org.wso2.developerstudio.eclipse.gmf.esb.ConditionalRouterMediatorInputConnector} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class ConditionalRouterMediatorInputConnectorItemProvider extends InputConnectorItemProvider implements IEditingDomainItemProvider, IStructuredItemContentProvider, ITreeItemContentProvider, IItemLabelProvider, IItemPropertySource { /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ConditionalRouterMediatorInputConnectorItemProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { if (itemPropertyDescriptors == null) { super.getPropertyDescriptors(object); } return itemPropertyDescriptors; } /** * This returns ConditionalRouterMediatorInputConnector.gif. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/ConditionalRouterMediatorInputConnector")); } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getText(Object object) { return getString("_UI_ConditionalRouterMediatorInputConnector_type"); } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void notifyChanged(Notification notification) { updateChildren(notification); super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); } }
thiliniish/developer-studio
esb/org.wso2.developerstudio.eclipse.gmf.esb.edit/src/org/wso2/developerstudio/eclipse/gmf/esb/provider/ConditionalRouterMediatorInputConnectorItemProvider.java
Java
apache-2.0
3,113
// 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.sh; import com.intellij.ui.IconManager; import org.jetbrains.annotations.NotNull; import javax.swing.*; /** * NOTE THIS FILE IS AUTO-GENERATED * DO NOT EDIT IT BY HAND, run "Generate icon classes" configuration instead */ public final class SHIcons { private static @NotNull Icon load(@NotNull String path, long cacheKey, int flags) { return IconManager.getInstance().loadRasterizedIcon(path, SHIcons.class.getClassLoader(), cacheKey, flags); } /** 16x16 */ public static final @NotNull Icon ShFile = load("icons/shFile.svg", 5123689148493670156L, 0); }
GunoH/intellij-community
plugins/sh/gen/com/intellij/sh/SHIcons.java
Java
apache-2.0
732
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.index.fielddata.plain; import org.apache.lucene.index.DocValues; import org.apache.lucene.index.DocValuesType; import org.apache.lucene.index.LeafReader; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.NumericDocValues; import org.apache.lucene.index.SortedNumericDocValues; import org.apache.lucene.sandbox.document.HalfFloatPoint; import org.apache.lucene.util.Accountable; import org.apache.lucene.util.NumericUtils; import org.elasticsearch.index.fielddata.FieldData; import org.elasticsearch.index.fielddata.IndexFieldData; import org.elasticsearch.index.fielddata.IndexFieldDataCache; import org.elasticsearch.index.fielddata.IndexNumericFieldData; import org.elasticsearch.index.fielddata.LeafNumericFieldData; import org.elasticsearch.index.fielddata.NumericDoubleValues; import org.elasticsearch.index.fielddata.SortedNumericDoubleValues; import org.elasticsearch.indices.breaker.CircuitBreakerService; import org.elasticsearch.script.field.DocValuesField; import org.elasticsearch.script.field.ToScriptField; import org.elasticsearch.search.aggregations.support.ValuesSourceType; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.Objects; /** * FieldData for floating point types * backed by {@link LeafReader#getSortedNumericDocValues(String)} * @see DocValuesType#SORTED_NUMERIC */ public class SortedDoublesIndexFieldData extends IndexNumericFieldData { public static class Builder implements IndexFieldData.Builder { private final String name; private final NumericType numericType; protected final ToScriptField<SortedNumericDoubleValues> toScriptField; public Builder(String name, NumericType numericType, ToScriptField<SortedNumericDoubleValues> toScriptField) { this.name = name; this.numericType = numericType; this.toScriptField = toScriptField; } @Override public SortedDoublesIndexFieldData build(IndexFieldDataCache cache, CircuitBreakerService breakerService) { return new SortedDoublesIndexFieldData(name, numericType, toScriptField); } } private final NumericType numericType; protected final String fieldName; protected final ValuesSourceType valuesSourceType; protected final ToScriptField<SortedNumericDoubleValues> toScriptField; public SortedDoublesIndexFieldData(String fieldName, NumericType numericType, ToScriptField<SortedNumericDoubleValues> toScriptField) { this.fieldName = fieldName; this.numericType = Objects.requireNonNull(numericType); assert this.numericType.isFloatingPoint(); this.valuesSourceType = numericType.getValuesSourceType(); this.toScriptField = toScriptField; } @Override public final String getFieldName() { return fieldName; } @Override public ValuesSourceType getValuesSourceType() { return valuesSourceType; } @Override protected boolean sortRequiresCustomComparator() { return numericType == NumericType.HALF_FLOAT; } @Override public NumericType getNumericType() { return numericType; } @Override public LeafNumericFieldData loadDirect(LeafReaderContext context) throws Exception { return load(context); } @Override public LeafNumericFieldData load(LeafReaderContext context) { final LeafReader reader = context.reader(); final String field = fieldName; switch (numericType) { case HALF_FLOAT: return new SortedNumericHalfFloatFieldData(reader, field, toScriptField); case FLOAT: return new SortedNumericFloatFieldData(reader, field, toScriptField); default: return new SortedNumericDoubleFieldData(reader, field, toScriptField); } } /** * FieldData implementation for 16-bit float values. * <p> * Order of values within a document is consistent with * {@link Float#compareTo(Float)}, hence the following reversible * transformation is applied at both index and search: * {@code bits ^ (bits >> 15) & 0x7fff} * <p> * Although the API is multi-valued, most codecs in Lucene specialize * for the case where documents have at most one value. In this case * {@link FieldData#unwrapSingleton(SortedNumericDoubleValues)} will return * the underlying single-valued NumericDoubleValues representation. */ static final class SortedNumericHalfFloatFieldData extends LeafDoubleFieldData { final LeafReader reader; final String field; protected final ToScriptField<SortedNumericDoubleValues> toScriptField; SortedNumericHalfFloatFieldData(LeafReader reader, String field, ToScriptField<SortedNumericDoubleValues> toScriptField) { super(0L); this.reader = reader; this.field = field; this.toScriptField = toScriptField; } @Override public SortedNumericDoubleValues getDoubleValues() { try { SortedNumericDocValues raw = DocValues.getSortedNumeric(reader, field); NumericDocValues single = DocValues.unwrapSingleton(raw); if (single != null) { return FieldData.singleton(new SingleHalfFloatValues(single)); } else { return new MultiHalfFloatValues(raw); } } catch (IOException e) { throw new IllegalStateException("Cannot load doc values", e); } } @Override public Collection<Accountable> getChildResources() { return Collections.emptyList(); } @Override public DocValuesField<?> getScriptField(String name) { return toScriptField.getScriptField(getDoubleValues(), name); } } /** * Wraps a NumericDocValues and exposes a single 16-bit float per document. */ static final class SingleHalfFloatValues extends NumericDoubleValues { final NumericDocValues in; SingleHalfFloatValues(NumericDocValues in) { this.in = in; } @Override public double doubleValue() throws IOException { return HalfFloatPoint.sortableShortToHalfFloat((short) in.longValue()); } @Override public boolean advanceExact(int doc) throws IOException { return in.advanceExact(doc); } } /** * Wraps a SortedNumericDocValues and exposes multiple 16-bit floats per document. */ static final class MultiHalfFloatValues extends SortedNumericDoubleValues { final SortedNumericDocValues in; MultiHalfFloatValues(SortedNumericDocValues in) { this.in = in; } @Override public boolean advanceExact(int target) throws IOException { return in.advanceExact(target); } @Override public double nextValue() throws IOException { return HalfFloatPoint.sortableShortToHalfFloat((short) in.nextValue()); } @Override public int docValueCount() { return in.docValueCount(); } } /** * FieldData implementation for 32-bit float values. * <p> * Order of values within a document is consistent with * {@link Float#compareTo(Float)}, hence the following reversible * transformation is applied at both index and search: * {@code bits ^ (bits >> 31) & 0x7fffffff} * <p> * Although the API is multi-valued, most codecs in Lucene specialize * for the case where documents have at most one value. In this case * {@link FieldData#unwrapSingleton(SortedNumericDoubleValues)} will return * the underlying single-valued NumericDoubleValues representation. */ static final class SortedNumericFloatFieldData extends LeafDoubleFieldData { final LeafReader reader; final String field; protected final ToScriptField<SortedNumericDoubleValues> toScriptField; SortedNumericFloatFieldData(LeafReader reader, String field, ToScriptField<SortedNumericDoubleValues> toScriptField) { super(0L); this.reader = reader; this.field = field; this.toScriptField = toScriptField; } @Override public SortedNumericDoubleValues getDoubleValues() { try { SortedNumericDocValues raw = DocValues.getSortedNumeric(reader, field); NumericDocValues single = DocValues.unwrapSingleton(raw); if (single != null) { return FieldData.singleton(new SingleFloatValues(single)); } else { return new MultiFloatValues(raw); } } catch (IOException e) { throw new IllegalStateException("Cannot load doc values", e); } } @Override public Collection<Accountable> getChildResources() { return Collections.emptyList(); } @Override public DocValuesField<?> getScriptField(String name) { return toScriptField.getScriptField(getDoubleValues(), name); } } /** * Wraps a NumericDocValues and exposes a single 32-bit float per document. */ static final class SingleFloatValues extends NumericDoubleValues { final NumericDocValues in; SingleFloatValues(NumericDocValues in) { this.in = in; } @Override public double doubleValue() throws IOException { return NumericUtils.sortableIntToFloat((int) in.longValue()); } @Override public boolean advanceExact(int doc) throws IOException { return in.advanceExact(doc); } } /** * Wraps a SortedNumericDocValues and exposes multiple 32-bit floats per document. */ static final class MultiFloatValues extends SortedNumericDoubleValues { final SortedNumericDocValues in; MultiFloatValues(SortedNumericDocValues in) { this.in = in; } @Override public boolean advanceExact(int target) throws IOException { return in.advanceExact(target); } @Override public double nextValue() throws IOException { return NumericUtils.sortableIntToFloat((int) in.nextValue()); } @Override public int docValueCount() { return in.docValueCount(); } } /** * FieldData implementation for 64-bit double values. * <p> * Order of values within a document is consistent with * {@link Double#compareTo(Double)}, hence the following reversible * transformation is applied at both index and search: * {@code bits ^ (bits >> 63) & 0x7fffffffffffffffL} * <p> * Although the API is multi-valued, most codecs in Lucene specialize * for the case where documents have at most one value. In this case * {@link FieldData#unwrapSingleton(SortedNumericDoubleValues)} will return * the underlying single-valued NumericDoubleValues representation. */ static final class SortedNumericDoubleFieldData extends LeafDoubleFieldData { final LeafReader reader; final String field; protected final ToScriptField<SortedNumericDoubleValues> toScriptField; SortedNumericDoubleFieldData(LeafReader reader, String field, ToScriptField<SortedNumericDoubleValues> toScriptField) { super(0L); this.reader = reader; this.field = field; this.toScriptField = toScriptField; } @Override public SortedNumericDoubleValues getDoubleValues() { try { SortedNumericDocValues raw = DocValues.getSortedNumeric(reader, field); return FieldData.sortableLongBitsToDoubles(raw); } catch (IOException e) { throw new IllegalStateException("Cannot load doc values", e); } } @Override public Collection<Accountable> getChildResources() { return Collections.emptyList(); } @Override public DocValuesField<?> getScriptField(String name) { return toScriptField.getScriptField(getDoubleValues(), name); } } }
GlenRSmith/elasticsearch
server/src/main/java/org/elasticsearch/index/fielddata/plain/SortedDoublesIndexFieldData.java
Java
apache-2.0
12,914
/* * Copyright 2010-2013 Ning, Inc. * * Ning 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.killbill.billing.catalog; import org.killbill.billing.catalog.api.PriceListSet; public class MockPriceList extends DefaultPriceList { public MockPriceList() { setName(PriceListSet.DEFAULT_PRICELIST_NAME); setPlans(MockPlan.createAll()); } }
24671335/killbill
catalog/src/test/java/org/killbill/billing/catalog/MockPriceList.java
Java
apache-2.0
904
/* * Copyright 2000-2009 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.groovydoc.psi.impl; import org.jetbrains.plugins.groovy.lang.groovydoc.psi.api.GrDocReferenceElement; import org.jetbrains.plugins.groovy.lang.groovydoc.psi.api.GrDocTagValueToken; import org.jetbrains.annotations.NotNull; import com.intellij.lang.ASTNode; /** * @author ilyas */ public class GrDocTagValueTokenImpl extends GroovyDocPsiElementImpl implements GrDocTagValueToken { public GrDocTagValueTokenImpl(@NotNull ASTNode node) { super(node); } public String toString() { return "GrDocTagValueToken"; } }
android-ia/platform_tools_idea
plugins/groovy/src/org/jetbrains/plugins/groovy/lang/groovydoc/psi/impl/GrDocTagValueTokenImpl.java
Java
apache-2.0
1,176
/* * Copyright 2009 Red Hat, Inc. * * Red Hat 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.jboss.netty.example.proxy; import static org.jboss.netty.channel.Channels.*; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.socket.ClientSocketChannelFactory; /** * @author <a href="http://www.jboss.org/netty/">The Netty Project</a> * @author <a href="http://gleamynode.net/">Trustin Lee</a> * @version $Rev: 2080 $, $Date: 2010-01-26 18:04:19 +0900 (Tue, 26 Jan 2010) $ */ public class HexDumpProxyPipelineFactory implements ChannelPipelineFactory { private final ClientSocketChannelFactory cf; private final String remoteHost; private final int remotePort; public HexDumpProxyPipelineFactory( ClientSocketChannelFactory cf, String remoteHost, int remotePort) { this.cf = cf; this.remoteHost = remoteHost; this.remotePort = remotePort; } public ChannelPipeline getPipeline() throws Exception { ChannelPipeline p = pipeline(); // Note the static import. p.addLast("handler", new HexDumpProxyInboundHandler(cf, remoteHost, remotePort)); return p; } }
whg333/netty-3.2.5.Final
src/main/java/org/jboss/netty/example/proxy/HexDumpProxyPipelineFactory.java
Java
apache-2.0
1,771
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.psi.impl.source.html.dtd; import com.intellij.html.RelaxedHtmlNSDescriptor; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.util.SimpleFieldCache; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.xml.XmlDocument; import com.intellij.psi.xml.XmlFile; import com.intellij.psi.xml.XmlTag; import com.intellij.util.ArrayUtilRt; import com.intellij.xml.XmlAttributeDescriptor; import com.intellij.xml.XmlElementDescriptor; import com.intellij.xml.XmlNSDescriptor; import com.intellij.xml.impl.schema.TypeDescriptor; import com.intellij.xml.impl.schema.XmlNSTypeDescriptorProvider; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.Map; /** * @author Maxim.Mossienko */ public class HtmlNSDescriptorImpl implements XmlNSDescriptor, DumbAware, XmlNSTypeDescriptorProvider { private final XmlNSDescriptor myDelegate; private final boolean myRelaxed; private final boolean myCaseSensitive; private static final SimpleFieldCache<Map<String, HtmlElementDescriptorImpl>, HtmlNSDescriptorImpl> myCachedDeclsCache = new SimpleFieldCache<>() { @Override protected Map<String, HtmlElementDescriptorImpl> compute(final HtmlNSDescriptorImpl htmlNSDescriptor) { return htmlNSDescriptor.doBuildCachedMap(); } @Override protected Map<String, HtmlElementDescriptorImpl> getValue(final HtmlNSDescriptorImpl htmlNSDescriptor) { return htmlNSDescriptor.myCachedDecls; } @Override protected void putValue(final Map<String, HtmlElementDescriptorImpl> map, final HtmlNSDescriptorImpl htmlNSDescriptor) { htmlNSDescriptor.myCachedDecls = map; } }; private volatile Map<String, HtmlElementDescriptorImpl> myCachedDecls; public HtmlNSDescriptorImpl(XmlNSDescriptor _delegate) { this(_delegate, _delegate instanceof RelaxedHtmlNSDescriptor, false); } public HtmlNSDescriptorImpl(XmlNSDescriptor _delegate, boolean relaxed, boolean caseSensitive) { myDelegate = _delegate; myRelaxed = relaxed; myCaseSensitive = caseSensitive; } @Nullable public static XmlAttributeDescriptor getCommonAttributeDescriptor(@NotNull final String attributeName, @Nullable final XmlTag context) { final XmlElementDescriptor descriptor = guessTagForCommonAttributes(context); if (descriptor != null) { return descriptor.getAttributeDescriptor(attributeName, context); } return null; } public static XmlAttributeDescriptor @NotNull [] getCommonAttributeDescriptors(XmlTag context) { final XmlElementDescriptor descriptor = guessTagForCommonAttributes(context); if (descriptor != null) { return descriptor.getAttributesDescriptors(context); } return XmlAttributeDescriptor.EMPTY; } @Nullable public static XmlElementDescriptor guessTagForCommonAttributes(@Nullable final XmlTag context) { if (context == null) return null; final XmlNSDescriptor nsDescriptor = context.getNSDescriptor(context.getNamespace(), false); if (nsDescriptor instanceof HtmlNSDescriptorImpl) { XmlElementDescriptor descriptor = ((HtmlNSDescriptorImpl)nsDescriptor).getElementDescriptorByName("div"); descriptor = descriptor == null ? ((HtmlNSDescriptorImpl)nsDescriptor).getElementDescriptorByName("span") : descriptor; return descriptor; } return null; } private Map<String,HtmlElementDescriptorImpl> buildDeclarationMap() { return myCachedDeclsCache.get(this); } // Read-only calculation private HashMap<String, HtmlElementDescriptorImpl> doBuildCachedMap() { HashMap<String, HtmlElementDescriptorImpl> decls = new HashMap<>(); XmlElementDescriptor[] elements = myDelegate == null ? XmlElementDescriptor.EMPTY_ARRAY : myDelegate.getRootElementsDescriptors(null); for (XmlElementDescriptor element : elements) { decls.put( element.getName(), new HtmlElementDescriptorImpl(element, myRelaxed, myCaseSensitive) ); } return decls; } @Override public XmlElementDescriptor getElementDescriptor(@NotNull XmlTag tag) { XmlElementDescriptor xmlElementDescriptor = getElementDescriptorByName(tag.getLocalName()); if (xmlElementDescriptor == null && myRelaxed) { xmlElementDescriptor = myDelegate.getElementDescriptor(tag); } return xmlElementDescriptor; } private XmlElementDescriptor getElementDescriptorByName(String name) { if (!myCaseSensitive) name = StringUtil.toLowerCase(name); return buildDeclarationMap().get(name); } @Override public XmlElementDescriptor @NotNull [] getRootElementsDescriptors(@Nullable final XmlDocument document) { if (myDelegate == null) return XmlElementDescriptor.EMPTY_ARRAY; if (document != null) return myDelegate.getRootElementsDescriptors(document); return buildDeclarationMap() .values() .stream() .map(HtmlElementDescriptorImpl::getDelegate) .toArray(XmlElementDescriptor[]::new); } @Override @Nullable public XmlFile getDescriptorFile() { return myDelegate == null ? null : myDelegate.getDescriptorFile(); } @Override public PsiElement getDeclaration() { return myDelegate == null ? null : myDelegate.getDeclaration(); } @Override public String getName(PsiElement context) { return myDelegate == null ? "" : myDelegate.getName(context); } @Override public String getName() { return myDelegate == null ? "" : myDelegate.getName(); } @Override public void init(PsiElement element) { myDelegate.init(element); } @Override public Object @NotNull [] getDependencies() { return myDelegate == null ? ArrayUtilRt.EMPTY_OBJECT_ARRAY : myDelegate.getDependencies(); } @Override public TypeDescriptor getTypeDescriptor(@NotNull String name, XmlTag context) { return myDelegate instanceof XmlNSTypeDescriptorProvider ? ((XmlNSTypeDescriptorProvider)myDelegate).getTypeDescriptor(name, context) : null; } @Override public TypeDescriptor getTypeDescriptor(XmlTag descriptorTag) { return myDelegate instanceof XmlNSTypeDescriptorProvider ? ((XmlNSTypeDescriptorProvider)myDelegate).getTypeDescriptor(descriptorTag) : null; } }
siosio/intellij-community
xml/xml-psi-impl/src/com/intellij/psi/impl/source/html/dtd/HtmlNSDescriptorImpl.java
Java
apache-2.0
6,486
package aima.test.core.unit.environment.vacuum; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import aima.core.environment.vacuum.VacuumEnvironmentViewActionTracker; import aima.core.environment.vacuum.SimpleReflexVacuumAgent; import aima.core.environment.vacuum.VacuumEnvironment; /** * @author Ciaran O'Reilly * */ public class SimpleReflexVacuumAgentTest { private SimpleReflexVacuumAgent agent; private StringBuilder envChanges; @Before public void setUp() { agent = new SimpleReflexVacuumAgent(); envChanges = new StringBuilder(); } @Test public void testCleanClean() { VacuumEnvironment tve = new VacuumEnvironment( VacuumEnvironment.LocationState.Clean, VacuumEnvironment.LocationState.Clean); tve.addAgent(agent, VacuumEnvironment.LOCATION_A); tve.addEnvironmentView(new VacuumEnvironmentViewActionTracker(envChanges)); tve.step(8); Assert.assertEquals( "Action[name==Right]Action[name==Left]Action[name==Right]Action[name==Left]Action[name==Right]Action[name==Left]Action[name==Right]Action[name==Left]", envChanges.toString()); } @Test public void testCleanDirty() { VacuumEnvironment tve = new VacuumEnvironment( VacuumEnvironment.LocationState.Clean, VacuumEnvironment.LocationState.Dirty); tve.addAgent(agent, VacuumEnvironment.LOCATION_A); tve.addEnvironmentView(new VacuumEnvironmentViewActionTracker(envChanges)); tve.step(8); Assert.assertEquals( "Action[name==Right]Action[name==Suck]Action[name==Left]Action[name==Right]Action[name==Left]Action[name==Right]Action[name==Left]Action[name==Right]", envChanges.toString()); } @Test public void testDirtyClean() { VacuumEnvironment tve = new VacuumEnvironment( VacuumEnvironment.LocationState.Dirty, VacuumEnvironment.LocationState.Clean); tve.addAgent(agent, VacuumEnvironment.LOCATION_A); tve.addEnvironmentView(new VacuumEnvironmentViewActionTracker(envChanges)); tve.step(8); Assert.assertEquals( "Action[name==Suck]Action[name==Right]Action[name==Left]Action[name==Right]Action[name==Left]Action[name==Right]Action[name==Left]Action[name==Right]", envChanges.toString()); } @Test public void testDirtyDirty() { VacuumEnvironment tve = new VacuumEnvironment( VacuumEnvironment.LocationState.Dirty, VacuumEnvironment.LocationState.Dirty); tve.addAgent(agent, VacuumEnvironment.LOCATION_A); tve.addEnvironmentView(new VacuumEnvironmentViewActionTracker(envChanges)); tve.step(8); Assert.assertEquals( "Action[name==Suck]Action[name==Right]Action[name==Suck]Action[name==Left]Action[name==Right]Action[name==Left]Action[name==Right]Action[name==Left]", envChanges.toString()); } }
futuristixa/aima-java
aima-core/src/test/java/aima/test/core/unit/environment/vacuum/SimpleReflexVacuumAgentTest.java
Java
mit
2,813
package org.spongycastle.cert.jcajce; import java.math.BigInteger; import java.security.PublicKey; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; import java.util.Date; import javax.security.auth.x500.X500Principal; import org.spongycastle.asn1.ASN1ObjectIdentifier; import org.spongycastle.asn1.x500.X500Name; import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; import org.spongycastle.asn1.x509.Time; import org.spongycastle.cert.X509v3CertificateBuilder; /** * JCA helper class to allow JCA objects to be used in the construction of a Version 3 certificate. */ public class JcaX509v3CertificateBuilder extends X509v3CertificateBuilder { /** * Initialise the builder using a PublicKey. * * @param issuer X500Name representing the issuer of this certificate. * @param serial the serial number for the certificate. * @param notBefore date before which the certificate is not valid. * @param notAfter date after which the certificate is not valid. * @param subject X500Name representing the subject of this certificate. * @param publicKey the public key to be associated with the certificate. */ public JcaX509v3CertificateBuilder(X500Name issuer, BigInteger serial, Date notBefore, Date notAfter, X500Name subject, PublicKey publicKey) { super(issuer, serial, notBefore, notAfter, subject, SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())); } /** * Initialise the builder using a PublicKey. * * @param issuer X500Name representing the issuer of this certificate. * @param serial the serial number for the certificate. * @param notBefore Time before which the certificate is not valid. * @param notAfter Time after which the certificate is not valid. * @param subject X500Name representing the subject of this certificate. * @param publicKey the public key to be associated with the certificate. */ public JcaX509v3CertificateBuilder(X500Name issuer, BigInteger serial, Time notBefore, Time notAfter, X500Name subject, PublicKey publicKey) { super(issuer, serial, notBefore, notAfter, subject, SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())); } /** * Initialise the builder using X500Principal objects and a PublicKey. * * @param issuer principal representing the issuer of this certificate. * @param serial the serial number for the certificate. * @param notBefore date before which the certificate is not valid. * @param notAfter date after which the certificate is not valid. * @param subject principal representing the subject of this certificate. * @param publicKey the public key to be associated with the certificate. */ public JcaX509v3CertificateBuilder(X500Principal issuer, BigInteger serial, Date notBefore, Date notAfter, X500Principal subject, PublicKey publicKey) { super(X500Name.getInstance(issuer.getEncoded()), serial, notBefore, notAfter, X500Name.getInstance(subject.getEncoded()), SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())); } /** * Initialise the builder using the subject from the passed in issuerCert as the issuer, as well as * passing through and converting the other objects provided. * * @param issuerCert certificate who's subject is the issuer of the certificate we are building. * @param serial the serial number for the certificate. * @param notBefore date before which the certificate is not valid. * @param notAfter date after which the certificate is not valid. * @param subject principal representing the subject of this certificate. * @param publicKey the public key to be associated with the certificate. */ public JcaX509v3CertificateBuilder(X509Certificate issuerCert, BigInteger serial, Date notBefore, Date notAfter, X500Principal subject, PublicKey publicKey) { this(issuerCert.getSubjectX500Principal(), serial, notBefore, notAfter, subject, publicKey); } /** * Initialise the builder using the subject from the passed in issuerCert as the issuer, as well as * passing through and converting the other objects provided. * * @param issuerCert certificate who's subject is the issuer of the certificate we are building. * @param serial the serial number for the certificate. * @param notBefore date before which the certificate is not valid. * @param notAfter date after which the certificate is not valid. * @param subject principal representing the subject of this certificate. * @param publicKey the public key to be associated with the certificate. */ public JcaX509v3CertificateBuilder(X509Certificate issuerCert, BigInteger serial, Date notBefore, Date notAfter, X500Name subject, PublicKey publicKey) { this(X500Name.getInstance(issuerCert.getSubjectX500Principal().getEncoded()), serial, notBefore, notAfter, subject, publicKey); } /** * Add a given extension field for the standard extensions tag (tag 3) * copying the extension value from another certificate. * * @param oid the type of the extension to be copied. * @param critical true if the extension is to be marked critical, false otherwise. * @param certificate the source of the extension to be copied. * @return the builder instance. */ public JcaX509v3CertificateBuilder copyAndAddExtension( ASN1ObjectIdentifier oid, boolean critical, X509Certificate certificate) throws CertificateEncodingException { this.copyAndAddExtension(oid, critical, new JcaX509CertificateHolder(certificate)); return this; } }
Skywalker-11/spongycastle
pkix/src/main/java/org/spongycastle/cert/jcajce/JcaX509v3CertificateBuilder.java
Java
mit
5,780
/******************************************************************************* * Copyright (c) 2013, 2015 Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat Inc. - initial API and implementation and/or initial documentation *******************************************************************************/ package org.eclipse.thym.core.engine.internal.cordova; public class DownloadableCordovaEngine { private String platformId; private String downloadURL; private String version; public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getPlatformId() { return platformId; } public void setPlatformId(String platformId) { this.platformId = platformId; } public String getDownloadURL() { return downloadURL; } public void setDownloadURL(String downloadURI) { this.downloadURL = downloadURI; } }
massimiliano76/thym
plugins/org.eclipse.thym.core/src/org/eclipse/thym/core/engine/internal/cordova/DownloadableCordovaEngine.java
Java
epl-1.0
1,149
/* * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * 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 testpackage; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class Main { private static final int MAIN_VERSION = 9; public static void main(String[] args) { System.out.println("Main version: " + getMainVersion()); System.out.println("Helpers version: " + getHelperVersion()); System.out.println("Resource version: " + getResourceVersion()); } public static int getMainVersion() { return MAIN_VERSION; } public static int getHelperVersion() { return testpackage.Helper.getHelperVersion(); } public static int getResourceVersion() { ClassLoader cl = Main.class.getClassLoader(); InputStream ris = cl.getResourceAsStream("versionResource"); if (ris == null) { throw new Error("Test issue: resource versionResource" + " cannot be loaded!"); } try (BufferedReader br = new BufferedReader(new InputStreamReader(ris))) { return Integer.parseInt(br.readLine()); } catch (IOException ioe) { throw new Error("Unexpected issue", ioe); } } }
YouDiSN/OpenJDK-Research
jdk9/jdk/test/tools/jar/multiRelease/data/runtimetest/v9/testpackage/Main.java
Java
gpl-2.0
2,266
/* * Copyright 2007-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.internal.artifacts.publish; import org.gradle.api.artifacts.PublishArtifact; import org.gradle.api.internal.tasks.DefaultTaskDependency; import org.gradle.api.tasks.TaskDependency; public abstract class AbstractPublishArtifact implements PublishArtifact { private final DefaultTaskDependency taskDependency; public AbstractPublishArtifact(Object... tasks) { taskDependency = new DefaultTaskDependency(); taskDependency.add(tasks); } public TaskDependency getBuildDependencies() { return taskDependency; } public AbstractPublishArtifact builtBy(Object... tasks) { taskDependency.add(tasks); return this; } @Override public String toString() { return String.format("%s %s:%s:%s:%s", getClass().getSimpleName(), getName(), getType(), getExtension(), getClassifier()); } }
cams7/gradle-samples
plugin/core/src/main/groovy/org/gradle/api/internal/artifacts/publish/AbstractPublishArtifact.java
Java
gpl-2.0
1,507
package org.checkerframework.qualframework.base.format; import org.checkerframework.dataflow.qual.SideEffectFree; import org.checkerframework.framework.type.AnnotatedTypeFormatter; import org.checkerframework.framework.type.DefaultAnnotatedTypeFormatter; import org.checkerframework.framework.util.AnnotationFormatter; import org.checkerframework.framework.util.DefaultAnnotationFormatter; import org.checkerframework.javacutil.AnnotationUtils; import org.checkerframework.javacutil.ErrorReporter; import org.checkerframework.qualframework.base.QualifiedTypeMirror; import org.checkerframework.qualframework.base.TypeMirrorConverter; import org.checkerframework.qualframework.poly.QualParams; import org.checkerframework.qualframework.poly.format.PrettyQualParamsFormatter; import javax.lang.model.element.AnnotationMirror; import java.util.Collection; /** * DefaultQualifiedTypeFormatter formats QualifiedTypeMirrors into Strings. * * This implementation used a component AnnotatedTypeFormatter to drive the formatting * and an AnnotationFormatter that converts @Key annotations to the qualifier, which * is then formatted by a QualFormatter. */ public class DefaultQualifiedTypeFormatter<Q, QUAL_FORMATTER extends QualFormatter<Q>> implements QualifiedTypeFormatter<Q> { protected final TypeMirrorConverter<Q> converter; protected final QUAL_FORMATTER qualFormatter; protected final boolean defaultPrintInvisibleQualifiers; protected final AnnotatedTypeFormatter adapter; protected final AnnotationFormatter annoAdapter; protected final boolean useOldFormat; public DefaultQualifiedTypeFormatter( QUAL_FORMATTER qualFormatter, TypeMirrorConverter<Q> converter, boolean useOldFormat, boolean defaultPrintInvisibleQualifiers) { this.converter = converter; this.useOldFormat = useOldFormat; this.defaultPrintInvisibleQualifiers = defaultPrintInvisibleQualifiers; this.qualFormatter = qualFormatter; this.annoAdapter = createAnnotationFormatter(); this.adapter = createAnnotatedTypeFormatter(annoAdapter); } /** * Create the AnnotatedTypeFormatter to be used as the underling formatter. This formatter * should use formatter as its AnnotationFormatter. * * @param annotationFormatter an AnnotationFormatter that is configured to printout qualifiers using * qualFormatter. * @return the AnnotatedTypeFormatter */ protected AnnotatedTypeFormatter createAnnotatedTypeFormatter(AnnotationFormatter annotationFormatter) { return new DefaultAnnotatedTypeFormatter(annotationFormatter, useOldFormat, defaultPrintInvisibleQualifiers); } @Override public String format(QualifiedTypeMirror<Q> qtm) { return adapter.format(converter.getAnnotatedType(qtm)); } @Override public String format(QualifiedTypeMirror<Q> qtm, boolean printInvisibles) { return adapter.format(converter.getAnnotatedType(qtm), printInvisibles); } @Override public QUAL_FORMATTER getQualFormatter() { return qualFormatter; } protected AnnotationFormatter createAnnotationFormatter() { return new AnnoToQualFormatter(); } /** * Formats an @Key annotation by looking up the corresponding {@link QualParams} and * formatting it using a {@link PrettyQualParamsFormatter}. */ protected class AnnoToQualFormatter extends DefaultAnnotationFormatter { @SideEffectFree public String formatAnnotationString(Collection<? extends AnnotationMirror> annos, boolean printInvisible) { StringBuilder sb = new StringBuilder(); for (AnnotationMirror obj : annos) { if (obj == null) { ErrorReporter.errorAbort("Found unexpected null AnnotationMirror " + "when formatting annotation mirror: " + annos); } if (!AnnotationUtils.areSameByClass(obj, TypeMirrorConverter.Key.class)) { ErrorReporter.errorAbort("Tried to format something other than an @Key annotation: " + obj); } else { Q qual = converter.getQualifier(obj); String result = qualFormatter.format(qual, printInvisible); if (result != null) { sb.append(result); sb.append(" "); } } } return sb.toString(); } @Override protected void formatAnnotationMirror(AnnotationMirror am, StringBuilder sb) { if (!AnnotationUtils.areSameByClass(am, TypeMirrorConverter.Key.class)) { ErrorReporter.errorAbort("Tried to format something other than an @Key annotation: " + am); } else { Q qual = converter.getQualifier(am); String result = qualFormatter.format(qual); if (result != null) { sb.append(result); } } } } }
renatoathaydes/checker-framework
framework/src/org/checkerframework/qualframework/base/format/DefaultQualifiedTypeFormatter.java
Java
gpl-2.0
5,152
/* * org.openmicroscopy.shoola.util.ui.tdialog.BorderListener * *------------------------------------------------------------------------------ * Copyright (C) 2006 University of Dundee. All rights reserved. * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * *------------------------------------------------------------------------------ */ package org.openmicroscopy.shoola.util.ui.tdialog; //Java imports import java.awt.Dimension; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import javax.swing.SwingUtilities; //Third-party libraries //Application-internal dependencies /** * We no longer use the usual decoration of a <code>JDialog</code> so we need to * provide our own border listener. * * @author Jean-Marie Burel &nbsp;&nbsp;&nbsp;&nbsp; * <a href="mailto:j.burel@dundee.ac.uk">j.burel@dundee.ac.uk</a> * @author <br>Andrea Falconi &nbsp;&nbsp;&nbsp;&nbsp; * <a href="mailto:a.falconi@dundee.ac.uk"> * a.falconi@dundee.ac.uk</a> * @version 2.2 * <small> * (<b>Internal version:</b> $Revision: 4698 $ $Date: 2006-12-18 11:46:06 +0000 (Mon, 18 Dec 2006) $) * </small> * @since OME2.2 */ class BorderListener implements MouseMotionListener { /** The default border thickness. */ private static int THICKNESS = 10; /** Reference to the model. */ private TinyDialog model; /** * Sets the bounds of the model. * * @param bounds The bounds to set. */ private void setModelBounds(Rectangle bounds) { model.setBounds(bounds); model.setRestoreSize(new Dimension(bounds.width, bounds.height)); model.validate(); } /** * Creates a new instance. * * @param model Reference to the Model. Mustn't be <code>null</code>. */ BorderListener(TinyDialog model) { if (model == null) throw new IllegalArgumentException("No model."); this.model = model; } /** * Handles mouseDragged events. * @see MouseMotionListener#mouseDragged(MouseEvent) */ public void mouseDragged(MouseEvent e) { Rectangle bounds = model.getBounds(); Point p = e.getPoint(); Dimension min = model.getMinimumSize(); Dimension max = model.getMaximumSize(); if (p.x < THICKNESS) { model.invalidate(); SwingUtilities.convertPointToScreen(p, model.getContentPane()); int diff = bounds.x-p.x; bounds.x = p.x; bounds.width += diff; if (bounds.width > min.width && bounds.width < max.width) setModelBounds(bounds); } else if (e.getX() > (model.getWidth()-THICKNESS)) { model.invalidate(); bounds.width = p.x; if (bounds.width > min.width && bounds.width < max.width) setModelBounds(bounds); } else if (e.getY() < THICKNESS) { model.invalidate(); SwingUtilities.convertPointToScreen(p, model.getContentPane()); int diff = bounds.y-p.y; bounds.y = p.y; bounds.height += diff; if (bounds.height < max.height && bounds.height > min.height) setModelBounds(bounds); } else if (e.getY() > (model.getHeight()-THICKNESS)) { model.invalidate(); bounds.height = p.y; if (bounds.height < max.height && bounds.height > min.height) setModelBounds(bounds); } } /** * Required by {@link MouseMotionListener} I/F but not actually needed in * our case, no op implementation. * @see MouseMotionListener#mouseMoved(MouseEvent) */ public void mouseMoved(MouseEvent e) {} }
ximenesuk/openmicroscopy
components/insight/SRC/org/openmicroscopy/shoola/util/ui/tdialog/BorderListener.java
Java
gpl-2.0
4,498
package outputModules.neo4j.importers; import neo4j.batchInserter.Neo4JBatchInserter; import org.neo4j.graphdb.DynamicRelationshipType; import org.neo4j.graphdb.RelationshipType; import ast.ASTNode; import ast.declarations.ClassDefStatement; import databaseNodes.ClassDefDatabaseNode; import databaseNodes.EdgeTypes; import databaseNodes.FileDatabaseNode; public class ClassDefImporter extends ASTNodeImporter { public void addToDatabaseSafe(ASTNode node) { try { ClassDefDatabaseNode classDefNode = new ClassDefDatabaseNode(); classDefNode.initialize(node); addClassDefToDatabase(classDefNode); linkClassDefToFileNode(classDefNode, curFile); } catch (RuntimeException ex) { ex.printStackTrace(); System.err.println("Error adding class to database: " + ((ClassDefStatement) node).name.getEscapedCodeStr()); return; } } private void linkClassDefToFileNode(ClassDefDatabaseNode classDefNode, FileDatabaseNode fileNode) { RelationshipType rel = DynamicRelationshipType .withName(EdgeTypes.IS_FILE_OF); long fileId = fileNode.getId(); long functionId = nodeStore.getIdForObject(classDefNode); Neo4JBatchInserter.addRelationship(fileId, functionId, rel, null); } private void addClassDefToDatabase(ClassDefDatabaseNode classDefNode) { addMainNode(classDefNode); } }
a0x77n/joern
src/outputModules/neo4j/importers/ClassDefImporter.java
Java
gpl-3.0
1,338
/** * 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.alibaba.rocketmq.common.protocol; /** * @author shijia.wxr */ public class MQProtosHelperTest { }
y123456yz/reading-and-annotate-rocketmq-3.4.6
rocketmq-src/RocketMQ-3.4.6/rocketmq-common/src/test/java/com/alibaba/rocketmq/common/protocol/MQProtosHelperTest.java
Java
gpl-3.0
923
/******************************************************************************* * 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.features.topology.app.internal.operations; import org.opennms.features.topology.api.LayoutAlgorithm; import org.opennms.features.topology.app.internal.jung.TopoFRLayoutAlgorithm; public class TopoFRLayoutOperation extends LayoutOperation { public TopoFRLayoutOperation() { super(new LayoutFactory() { private final TopoFRLayoutAlgorithm m_layoutAlgorithm = new TopoFRLayoutAlgorithm(); @Override public LayoutAlgorithm getLayoutAlgorithm() { return m_layoutAlgorithm; } }); } @Override public String getId() { return getClass().getSimpleName(); } }
roskens/opennms-pre-github
features/topology-map/org.opennms.features.topology.app/src/main/java/org/opennms/features/topology/app/internal/operations/TopoFRLayoutOperation.java
Java
agpl-3.0
1,862
package dr.math; /** * @author Marc Suchard */ public class LogTricks { public static final double maxFloat = Double.MAX_VALUE; //3.40282347E+38; public static final double logLimit = -maxFloat / 100; public static final double logZero = -maxFloat; public static final double NATS = 400; //40; public static double logSumNoCheck(double x, double y) { double temp = y - x; if (Math.abs(temp) > NATS) return (x > y) ? x : y; else return x + StrictMath.log1p(StrictMath.exp(temp)); } public static double logSum(double[] x) { double sum = x[0]; final int len = x.length; for(int i=1; i<len; i++) sum = logSumNoCheck(sum,x[i]); return sum; } public static double logSum(double x, double y) { final double temp = y - x; if (temp > NATS || x < logLimit) return y; if (temp < -NATS || y < logLimit) return x; if (temp < 0) return x + StrictMath.log1p(StrictMath.exp(temp)); return y + StrictMath.log1p(StrictMath.exp(-temp)); } public static void logInc(Double x, double y) { double temp = y - x; if (temp > NATS || x < logLimit) x = y; else if (temp < -NATS || y < logLimit) ; else x += StrictMath.log1p(StrictMath.exp(temp)); } public static double logDiff(double x, double y) { assert x > y; double temp = y - x; if (temp < -NATS || y < logLimit) return x; return x + StrictMath.log1p(-Math.exp(temp)); } }
armanbilge/BEAST_sandbox
src/dr/math/LogTricks.java
Java
lgpl-2.1
1,650
/* * JBoss, Home of Professional Open Source * Copyright 2007, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. * See the copyright.txt in the distribution for a * full listing of individual contributors. * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * 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, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * (C) 2005-2006, * @author JBoss Inc. */ // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 // // Arjuna Technologies Ltd., // Newcastle upon Tyne, // Tyne and Wear, // UK // package org.jboss.jbossts.qa.RawResources02Servers; /* * Copyright (C) 1999-2001 by HP Bluestone Software, Inc. All rights Reserved. * * HP Arjuna Labs, * Newcastle upon Tyne, * Tyne and Wear, * UK. * * $Id: Server02.java,v 1.2 2003/06/26 11:44:59 rbegg Exp $ */ /* * Try to get around the differences between Ansi CPP and * K&R cpp with concatenation. */ /* * Copyright (C) 1999-2001 by HP Bluestone Software, Inc. All rights Reserved. * * HP Arjuna Labs, * Newcastle upon Tyne, * Tyne and Wear, * UK. * * $Id: Server02.java,v 1.2 2003/06/26 11:44:59 rbegg Exp $ */ import org.jboss.jbossts.qa.RawResources02.*; import org.jboss.jbossts.qa.RawResources02Impls.ServiceImpl01; import org.jboss.jbossts.qa.Utils.OAInterface; import org.jboss.jbossts.qa.Utils.ORBInterface; import org.jboss.jbossts.qa.Utils.ServerIORStore; public class Server02 { public static void main(String args[]) { try { ORBInterface.initORB(args, null); OAInterface.initOA(); ServiceImpl01 serviceImpl1 = new ServiceImpl01(0); ServiceImpl01 serviceImpl2 = new ServiceImpl01(1); ServicePOATie servant1 = new ServicePOATie(serviceImpl1); ServicePOATie servant2 = new ServicePOATie(serviceImpl2); OAInterface.objectIsReady(servant1); OAInterface.objectIsReady(servant2); Service service1 = ServiceHelper.narrow(OAInterface.corbaReference(servant1)); Service service2 = ServiceHelper.narrow(OAInterface.corbaReference(servant2)); ServerIORStore.storeIOR(args[args.length - 2], ORBInterface.orb().object_to_string(service1)); ServerIORStore.storeIOR(args[args.length - 1], ORBInterface.orb().object_to_string(service2)); System.out.println("Ready"); ORBInterface.run(); } catch (Exception exception) { System.err.println("Server02.main: " + exception); exception.printStackTrace(System.err); } } }
gytis/narayana
qa/tests/src/org/jboss/jbossts/qa/RawResources02Servers/Server02.java
Java
lgpl-2.1
2,980
/* * JBoss, Home of Professional Open Source * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * 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.jboss.arquillian.testenricher.cdi.client; import java.util.Map; import org.jboss.arquillian.container.spi.client.deployment.Validate; import org.jboss.arquillian.container.test.spi.TestDeployment; import org.jboss.arquillian.container.test.spi.client.deployment.ProtocolArchiveProcessor; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ArchivePath; import org.jboss.shrinkwrap.api.Filters; import org.jboss.shrinkwrap.api.GenericArchive; import org.jboss.shrinkwrap.api.Node; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; /** * A {@link ProtocolArchiveProcessor} that will add beans.xml to the protocol unit if one is defined in the test deployment. * * @author <a href="mailto:aslak@redhat.com">Aslak Knutsen</a> * @version $Revision: $ */ public class BeansXMLProtocolProcessor implements ProtocolArchiveProcessor { /* (non-Javadoc) * @see org.jboss.arquillian.spi.client.deployment.ProtocolArchiveProcessor#process(org.jboss.arquillian.spi.TestDeployment, org.jboss.shrinkwrap.api.Archive) */ @Override public void process(TestDeployment testDeployment, Archive<?> protocolArchive) { if(testDeployment.getApplicationArchive().equals(protocolArchive)) { return; // if the protocol is merged in the user Archive, the user is in control. } if(containsBeansXML(testDeployment.getApplicationArchive())) { if(Validate.isArchiveOfType(WebArchive.class, protocolArchive)) { if(!protocolArchive.contains("WEB-INF/beans.xml")) { protocolArchive.as(WebArchive.class).addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); } } else if(Validate.isArchiveOfType(JavaArchive.class, protocolArchive)) { if(!protocolArchive.contains("META-INF/beans.xml")) { protocolArchive.as(JavaArchive.class).addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); } } } } private boolean containsBeansXML(Archive<?> archive) { Map<ArchivePath, Node> content = archive.getContent(Filters.include(".*/beans\\.xml")); if(!content.isEmpty()) { return true; } Map<ArchivePath, Node> nested = archive.getContent(Filters.include("/.*\\.(jar|war)")); if(!nested.isEmpty()) { for(ArchivePath path : nested.keySet()) { try { if(containsBeansXML(archive.getAsType(GenericArchive.class, path))) { return true; } } catch (IllegalArgumentException e) { // no-op, Nested archive is not a ShrinkWrap archive. } } } return false; } }
andreiserea/arquillian-core
testenrichers/cdi/src/main/java/org/jboss/arquillian/testenricher/cdi/client/BeansXMLProtocolProcessor.java
Java
apache-2.0
3,756
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.json; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.IdeActions; import com.intellij.openapi.fileTypes.LanguageFileType; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import com.intellij.spellchecker.inspections.SpellCheckingInspection; import com.intellij.testFramework.ServiceContainerUtil; import com.intellij.util.containers.Predicate; import com.jetbrains.jsonSchema.JsonSchemaTestProvider; import com.jetbrains.jsonSchema.JsonSchemaTestServiceImpl; import com.jetbrains.jsonSchema.ide.JsonSchemaService; /** * @author Mikhail Golubev */ public class JsonSpellcheckerTest extends JsonTestCase { private void doTest() { myFixture.enableInspections(SpellCheckingInspection.class); myFixture.configureByFile(getTestName(false) + ".json"); myFixture.checkHighlighting(true, false, true); } public void testEscapeAwareness() { doTest(); } public void testSimple() { doTest(); } protected Predicate<VirtualFile> getAvailabilityPredicate() { return file -> file.getFileType() instanceof LanguageFileType && ((LanguageFileType)file.getFileType()).getLanguage().isKindOf( JsonLanguage.INSTANCE); } public void testWithSchema() { PsiFile[] files = myFixture.configureByFiles(getTestName(false) + ".json", "Schema.json"); JsonSchemaTestServiceImpl.setProvider(new JsonSchemaTestProvider(files[1].getVirtualFile(), getAvailabilityPredicate())); ServiceContainerUtil.replaceService(getProject(), JsonSchemaService.class, new JsonSchemaTestServiceImpl(getProject()), getTestRootDisposable()); Disposer.register(getTestRootDisposable(), new Disposable() { @Override public void dispose() { JsonSchemaTestServiceImpl.setProvider(null); } }); myFixture.enableInspections(SpellCheckingInspection.class); myFixture.checkHighlighting(true, false, true); } // WEB-31894 EA-117068 public void testAfterModificationOfStringLiteralWithEscaping() { myFixture.configureByFile(getTestName(false) + ".json"); myFixture.enableInspections(SpellCheckingInspection.class); myFixture.checkHighlighting(); myFixture.performEditorAction(IdeActions.ACTION_EDITOR_BACKSPACE); myFixture.performEditorAction(IdeActions.ACTION_EDITOR_BACKSPACE); myFixture.doHighlighting(); } @Override protected String getTestDataPath() { return super.getTestDataPath() + "/spellchecker"; } }
siosio/intellij-community
json/tests/test/com/intellij/json/JsonSpellcheckerTest.java
Java
apache-2.0
2,668
package fr.free.nrw.commons.auth; import android.os.Bundle; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; import fr.free.nrw.commons.BuildConfig; import fr.free.nrw.commons.R; import fr.free.nrw.commons.theme.BaseActivity; import timber.log.Timber; public class SignupActivity extends BaseActivity { private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Timber.d("Signup Activity started"); webView = new WebView(this); setContentView(webView); webView.setWebViewClient(new MyWebViewClient()); WebSettings webSettings = webView.getSettings(); /*Needed to refresh Captcha. Might introduce XSS vulnerabilities, but we can trust Wikimedia's site... right?*/ webSettings.setJavaScriptEnabled(true); webView.loadUrl(BuildConfig.SIGNUP_LANDING_URL); } private class MyWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.equals(BuildConfig.SIGNUP_SUCCESS_REDIRECTION_URL)) { //Signup success, so clear cookies, notify user, and load LoginActivity again Timber.d("Overriding URL %s", url); Toast toast = Toast.makeText(SignupActivity.this, R.string.account_created, Toast.LENGTH_LONG); toast.show(); // terminate on task completion. finish(); return true; } else { //If user clicks any other links in the webview Timber.d("Not overriding URL, URL is: %s", url); return false; } } } @Override public void onBackPressed() { if (webView.canGoBack()) { webView.goBack(); } else { super.onBackPressed(); } } }
commons-app/apps-android-commons
app/src/main/java/fr/free/nrw/commons/auth/SignupActivity.java
Java
apache-2.0
2,045
/* * Copyright 2000-2014 Vaadin Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.vaadin.client.ui.nativeselect; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.BlurHandler; import com.google.gwt.event.dom.client.FocusEvent; import com.google.gwt.event.dom.client.FocusHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.vaadin.client.EventHelper; import com.vaadin.client.annotations.OnStateChange; import com.vaadin.client.ui.VNativeSelect; import com.vaadin.client.ui.optiongroup.OptionGroupBaseConnector; import com.vaadin.shared.communication.FieldRpc.FocusAndBlurServerRpc; import com.vaadin.shared.ui.Connect; import com.vaadin.ui.NativeSelect; @Connect(NativeSelect.class) public class NativeSelectConnector extends OptionGroupBaseConnector implements BlurHandler, FocusHandler { private HandlerRegistration focusHandlerRegistration = null; private HandlerRegistration blurHandlerRegistration = null; public NativeSelectConnector() { super(); } @OnStateChange("registeredEventListeners") private void onServerEventListenerChanged() { focusHandlerRegistration = EventHelper.updateFocusHandler(this, focusHandlerRegistration, getWidget().getSelect()); blurHandlerRegistration = EventHelper.updateBlurHandler(this, blurHandlerRegistration, getWidget().getSelect()); } @Override public VNativeSelect getWidget() { return (VNativeSelect) super.getWidget(); } @Override public void onFocus(FocusEvent event) { // EventHelper.updateFocusHandler ensures that this is called only when // there is a listener on server side getRpcProxy(FocusAndBlurServerRpc.class).focus(); } @Override public void onBlur(BlurEvent event) { // EventHelper.updateFocusHandler ensures that this is called only when // there is a listener on server side getRpcProxy(FocusAndBlurServerRpc.class).blur(); } }
fireflyc/vaadin
client/src/com/vaadin/client/ui/nativeselect/NativeSelectConnector.java
Java
apache-2.0
2,573