repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
toobs/Toobs
trunk/PresFramework/src/main/java/org/toobsframework/pres/app/controller/URLResolverImpl.java
3668
/* * This file is licensed to the Toobs Framework Group under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The Toobs Framework Group 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.toobsframework.pres.app.controller; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.toobsframework.pres.app.AppReader; public class URLResolverImpl implements URLResolver { private static Log log = LogFactory.getLog(URLResolverImpl.class); public AppRequest resolve(AppReader appReader, String url, String method) { log.info(url); return null; } protected AppRequest getBaseAppView(AppReader appReader, String urlPath) { String[] splitUrl = urlPath.split("/"); if (log.isDebugEnabled()) { for (int i = 0; i < splitUrl.length; i++) { log.debug("Url part " + i + ": " + splitUrl[i]); } } BaseAppRequest view = null; if (splitUrl.length <= 1) { return new BaseAppRequest("/", DEFAULT_VIEW); } if (appReader.containsApp("/" + splitUrl[1])) { String appName = splitUrl[1]; if (splitUrl.length == 2) { return new BaseAppRequest(appName, DEFAULT_VIEW); } else { } } /* if (splitUrl[1].equals(compPrefix)) { if (splitUrl.length >= 5) { return new BaseAppView("/", true, splitUrl[2], splitUrl[3], splitUrl[4]); } else if (splitUrl.length == 4) { return new BaseAppView("/", true, splitUrl[2], splitUrl[3], splitUrl[2]); } else { return new BaseAppView("/", true, null, null, splitUrl[2]); } } if (appManager.containsApp("/" + splitUrl[1])) { if (splitUrl[1].equals(compPrefix)) { if (splitUrl.length >= 6) { return new BaseAppView("/" + splitUrl[1], true, splitUrl[3], splitUrl[4], splitUrl[5]); } else if (splitUrl.length == 4) { return new BaseAppView("/" + splitUrl[1], true, splitUrl[3], splitUrl[4], splitUrl[3]); } else { return new BaseAppView("/" + splitUrl[1], true, null, null, splitUrl[3]); } } else { if (splitUrl.length >= 5) { return new BaseAppView("/" + splitUrl[1], false, splitUrl[2], splitUrl[3], splitUrl[4]); } else if (splitUrl.length == 4) { return new BaseAppView("/" + splitUrl[1], false, splitUrl[2], splitUrl[3], splitUrl[2]); } else if (splitUrl.length == 3) { return new BaseAppView("/" + splitUrl[1], false, null, null, splitUrl[2]); } else { return new BaseAppView("/" + splitUrl[1], false, null, null, DEFAULT_VIEW); } } } else { if (splitUrl.length >= 4) { return new BaseAppView("/", true, splitUrl[1], splitUrl[2], splitUrl[3]); } else if (splitUrl.length == 3) { return new BaseAppView("/", true, splitUrl[1], splitUrl[2], splitUrl[1]); } else { return new BaseAppView("/", true, null, null, splitUrl[1]); } } */ return view; } }
apache-2.0
bcleenders/hops-metadata-dal
src/main/java/io/hops/transaction/handler/TransactionalRequestHandler.java
9752
/* * Copyright (C) 2015 hops.io. * * 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.hops.transaction.handler; import io.hops.exception.StorageException; import io.hops.exception.TransactionContextException; import io.hops.exception.TransientStorageException; import io.hops.exception.TupleAlreadyExistedException; import io.hops.log.NDCWrapper; import io.hops.metadata.hdfs.entity.MetadataLogEntry; import io.hops.transaction.EntityManager; import io.hops.transaction.TransactionInfo; import io.hops.transaction.context.TransactionsStats; import io.hops.transaction.lock.TransactionLockAcquirer; import io.hops.transaction.lock.TransactionLocks; import java.io.IOException; import java.util.Collection; import java.util.Collections; public abstract class TransactionalRequestHandler extends RequestHandler { private Collection<MetadataLogEntry> previousLogEntries = Collections.emptyList(); public TransactionalRequestHandler(OperationType opType) { super(opType); } @Override protected Object execute(Object info) throws IOException { boolean rollback; boolean committed; int tryCount = 0; IOException ignoredException; TransactionLocks locks = null; Object txRetValue = null; while (tryCount <= RETRY_COUNT) { long expWaitTime = exponentialBackoff(); long txStartTime = System.currentTimeMillis(); long oldTime = System.currentTimeMillis(); long setupTime = -1; long beginTxTime = -1; long acquireLockTime = -1; long inMemoryProcessingTime = -1; long commitTime = -1; long totalTime = -1; rollback = false; tryCount++; ignoredException = null; committed = false; EntityManager.preventStorageCall(false); try { setNDC(info); log.debug("Pretransaction phase started"); preTransactionSetup(); //sometimes in setup we call light weight request handler that messes up with the NDC removeNDC(); setNDC(info); setupTime = (System.currentTimeMillis() - oldTime); oldTime = System.currentTimeMillis(); log.debug("Pretransaction phase finished. Time " + setupTime + " ms"); setRandomPartitioningKey(); EntityManager.begin(); log.debug("TX Started"); beginTxTime = (System.currentTimeMillis() - oldTime); oldTime = System.currentTimeMillis(); TransactionLockAcquirer locksAcquirer = newLockAcquirer(); acquireLock(locksAcquirer.getLocks()); locksAcquirer.acquire(); log.debug("Update timestamp phase started"); updatedTimestamp(); acquireLockTime = (System.currentTimeMillis() - oldTime); oldTime = System.currentTimeMillis(); log.debug("All Locks Acquired. Time " + acquireLockTime + " ms"); //sometimes in setup we call light weight request handler that messes up with the NDC removeNDC(); setNDC(info); EntityManager.preventStorageCall(true); try { txRetValue = performTask(); } catch (IOException e) { if (shouldAbort(e)) { throw e; } else { ignoredException = e; } } inMemoryProcessingTime = (System.currentTimeMillis() - oldTime); oldTime = System.currentTimeMillis(); log.debug( "In Memory Processing Finished. Time " + inMemoryProcessingTime + " ms"); TransactionsStats.TransactionStat stat = TransactionsStats.getInstance() .collectStats(opType, ignoredException); EntityManager.commit(locksAcquirer.getLocks()); committed = true; commitTime = (System.currentTimeMillis() - oldTime); if(stat != null){ stat.setTimes(acquireLockTime, inMemoryProcessingTime, commitTime); } log.debug("TX committed. Time " + commitTime + " ms"); totalTime = (System.currentTimeMillis() - txStartTime); log.debug("TX Finished. TX Stats: Try Count: " + tryCount + " Wait Before Next Retry:" + expWaitTime + " Stepup: " + setupTime + " ms, Begin Tx:" + beginTxTime + " ms, Acquire Locks: " + acquireLockTime + "ms, In Memory Processing: " + inMemoryProcessingTime + "ms, Commit Time: " + commitTime + "ms, Total Time: " + totalTime + "ms"); //post TX phase //any error in this phase will not re-start the tx //TODO: XXX handle failures in post tx phase if (info != null && info instanceof TransactionInfo) { ((TransactionInfo) info).performPostTransactionAction(); } return txRetValue; } catch (TransientStorageException e) { rollback = true; if (tryCount <= RETRY_COUNT) { log.error("Tx Failed. total tx time " + (System.currentTimeMillis() - txStartTime) + " msec. TotalRetryCount(" + RETRY_COUNT + ") RemainingRetries(" + (RETRY_COUNT - tryCount) + ") TX Stats: Setup: " + setupTime + "ms Acquire Locks: " + acquireLockTime + "ms, In Memory Processing: " + inMemoryProcessingTime + "ms, Commit Time: " + commitTime + "ms, Total Time: " + totalTime + "ms", e); } else { log.debug("Transaction failed after " + RETRY_COUNT + " retries.", e); throw e; } } catch (TupleAlreadyExistedException e) { rollback = true; if (tryCount <= RETRY_COUNT) { previousLogEntries = EntityManager.findList( MetadataLogEntry.Finder.ALL_CACHED); if (previousLogEntries.isEmpty()) { log.error("Transaction failed", e); throw e; } else { log.error("Tx Failed. total tx time " + (System.currentTimeMillis() - txStartTime) + " msec. TotalRetryCount(" + RETRY_COUNT + ") RemainingRetries(" + (RETRY_COUNT - tryCount) + ") TX Stats: Setup: " + setupTime + "ms Acquire Locks: " + acquireLockTime + "ms, In Memory Processing: " + inMemoryProcessingTime + "ms, Commit Time: " + commitTime + "ms, Total Time: " + totalTime + "ms", e); resetWaitTime(); // Not an overloading error } } else { log.debug("Transaction failed after " + RETRY_COUNT + " retries.", e); throw e; } } catch (IOException e) { rollback = true; if (committed) { log.error("Exception in Post Tx Stage.", e); } else { log.error("Transaction failed", e); } throw e; } catch (RuntimeException e) { rollback = true; log.error("Transaction handler received a runtime exception", e); throw e; } catch (Error e) { rollback = true; log.error("Transaction handler received an error", e); throw e; } finally { removeNDC(); if (rollback) { try { log.error("Rollback the TX"); EntityManager.rollback(locks); } catch (Exception e) { log.warn("Could not rollback transaction", e); } } // If the code is about to return but the exception was caught if (ignoredException != null) { throw ignoredException; } } } throw new RuntimeException("TransactionalRequestHandler did not execute"); } private void updatedTimestamp() throws TransactionContextException, StorageException { if (!previousLogEntries.isEmpty()) { EntityManager.findList(MetadataLogEntry.Finder.FETCH_EXISTING, previousLogEntries); } } protected abstract void preTransactionSetup() throws IOException; public abstract void acquireLock(TransactionLocks locks) throws IOException; protected abstract TransactionLockAcquirer newLockAcquirer(); @Override public TransactionalRequestHandler setParams(Object... params) { this.params = params; return this; } private void setNDC(Object info) { // Defines a context for every operation to track them in the logs easily. if (info != null && info instanceof TransactionInfo) { NDCWrapper.push(((TransactionInfo) info).getContextName(opType)); } else { NDCWrapper.push(opType.toString()); } } private void removeNDC() { NDCWrapper.clear(); NDCWrapper.remove(); } private void setRandomPartitioningKey() throws StorageException, StorageException { // Random rand =new Random(System.currentTimeMillis()); // Integer partKey = new Integer(rand.nextInt()); // //set partitioning key // Object[] pk = new Object[2]; // pk[0] = partKey; // pk[1] = Integer.toString(partKey); // // EntityManager.setPartitionKey(INodeDataAccess.class, pk); // //// EntityManager.readCommited(); //// EntityManager.find(INode.Finder.ByPK_NameAndParentId, "", partKey); } protected abstract boolean shouldAbort(Exception e); }
apache-2.0
EvilMcJerkface/atlasdb
atlasdb-tests-shared/src/test/java/com/palantir/atlasdb/schema/stream/generated/StreamTestStreamHashAidxTable.java
32035
package com.palantir.atlasdb.schema.stream.generated; import java.util.Arrays; import java.util.Collection; import java.util.EnumSet; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.SortedMap; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.function.BiFunction; import java.util.function.Supplier; import java.util.stream.Stream; import javax.annotation.Generated; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.MoreObjects; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Collections2; import com.google.common.collect.ComparisonChain; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import com.google.common.collect.Sets; import com.google.common.hash.Hashing; import com.google.common.primitives.Bytes; import com.google.common.primitives.UnsignedBytes; import com.google.protobuf.InvalidProtocolBufferException; import com.palantir.atlasdb.compress.CompressionUtils; import com.palantir.atlasdb.encoding.PtBytes; import com.palantir.atlasdb.keyvalue.api.BatchColumnRangeSelection; import com.palantir.atlasdb.keyvalue.api.Cell; import com.palantir.atlasdb.keyvalue.api.ColumnRangeSelection; import com.palantir.atlasdb.keyvalue.api.ColumnRangeSelections; import com.palantir.atlasdb.keyvalue.api.ColumnSelection; import com.palantir.atlasdb.keyvalue.api.Namespace; import com.palantir.atlasdb.keyvalue.api.Prefix; import com.palantir.atlasdb.keyvalue.api.RangeRequest; import com.palantir.atlasdb.keyvalue.api.RowResult; import com.palantir.atlasdb.keyvalue.api.TableReference; import com.palantir.atlasdb.keyvalue.impl.Cells; import com.palantir.atlasdb.ptobject.EncodingUtils; import com.palantir.atlasdb.table.api.AtlasDbDynamicMutablePersistentTable; import com.palantir.atlasdb.table.api.AtlasDbMutablePersistentTable; import com.palantir.atlasdb.table.api.AtlasDbNamedMutableTable; import com.palantir.atlasdb.table.api.AtlasDbNamedPersistentSet; import com.palantir.atlasdb.table.api.ColumnValue; import com.palantir.atlasdb.table.api.TypedRowResult; import com.palantir.atlasdb.table.description.ColumnValueDescription.Compression; import com.palantir.atlasdb.table.description.ValueType; import com.palantir.atlasdb.table.generation.ColumnValues; import com.palantir.atlasdb.table.generation.Descending; import com.palantir.atlasdb.table.generation.NamedColumnValue; import com.palantir.atlasdb.transaction.api.AtlasDbConstraintCheckingMode; import com.palantir.atlasdb.transaction.api.ConstraintCheckingTransaction; import com.palantir.atlasdb.transaction.api.ImmutableGetRangesQuery; import com.palantir.atlasdb.transaction.api.Transaction; import com.palantir.common.base.AbortingVisitor; import com.palantir.common.base.AbortingVisitors; import com.palantir.common.base.BatchingVisitable; import com.palantir.common.base.BatchingVisitableView; import com.palantir.common.base.BatchingVisitables; import com.palantir.common.base.Throwables; import com.palantir.common.collect.IterableView; import com.palantir.common.persist.Persistable; import com.palantir.common.persist.Persistable.Hydrator; import com.palantir.common.persist.Persistables; import com.palantir.util.AssertUtils; import com.palantir.util.crypto.Sha256Hash; @Generated("com.palantir.atlasdb.table.description.render.TableRenderer") @SuppressWarnings("all") public final class StreamTestStreamHashAidxTable implements AtlasDbDynamicMutablePersistentTable<StreamTestStreamHashAidxTable.StreamTestStreamHashAidxRow, StreamTestStreamHashAidxTable.StreamTestStreamHashAidxColumn, StreamTestStreamHashAidxTable.StreamTestStreamHashAidxColumnValue, StreamTestStreamHashAidxTable.StreamTestStreamHashAidxRowResult> { private final Transaction t; private final List<StreamTestStreamHashAidxTrigger> triggers; private final static String rawTableName = "stream_test_stream_hash_aidx"; private final TableReference tableRef; private final static ColumnSelection allColumns = ColumnSelection.all(); static StreamTestStreamHashAidxTable of(Transaction t, Namespace namespace) { return new StreamTestStreamHashAidxTable(t, namespace, ImmutableList.<StreamTestStreamHashAidxTrigger>of()); } static StreamTestStreamHashAidxTable of(Transaction t, Namespace namespace, StreamTestStreamHashAidxTrigger trigger, StreamTestStreamHashAidxTrigger... triggers) { return new StreamTestStreamHashAidxTable(t, namespace, ImmutableList.<StreamTestStreamHashAidxTrigger>builder().add(trigger).add(triggers).build()); } static StreamTestStreamHashAidxTable of(Transaction t, Namespace namespace, List<StreamTestStreamHashAidxTrigger> triggers) { return new StreamTestStreamHashAidxTable(t, namespace, triggers); } private StreamTestStreamHashAidxTable(Transaction t, Namespace namespace, List<StreamTestStreamHashAidxTrigger> triggers) { this.t = t; this.tableRef = TableReference.create(namespace, rawTableName); this.triggers = triggers; } public static String getRawTableName() { return rawTableName; } public TableReference getTableRef() { return tableRef; } public String getTableName() { return tableRef.getQualifiedName(); } public Namespace getNamespace() { return tableRef.getNamespace(); } /** * <pre> * StreamTestStreamHashAidxRow { * {@literal Sha256Hash hash}; * } * </pre> */ public static final class StreamTestStreamHashAidxRow implements Persistable, Comparable<StreamTestStreamHashAidxRow> { private final Sha256Hash hash; public static StreamTestStreamHashAidxRow of(Sha256Hash hash) { return new StreamTestStreamHashAidxRow(hash); } private StreamTestStreamHashAidxRow(Sha256Hash hash) { this.hash = hash; } public Sha256Hash getHash() { return hash; } public static Function<StreamTestStreamHashAidxRow, Sha256Hash> getHashFun() { return new Function<StreamTestStreamHashAidxRow, Sha256Hash>() { @Override public Sha256Hash apply(StreamTestStreamHashAidxRow row) { return row.hash; } }; } public static Function<Sha256Hash, StreamTestStreamHashAidxRow> fromHashFun() { return new Function<Sha256Hash, StreamTestStreamHashAidxRow>() { @Override public StreamTestStreamHashAidxRow apply(Sha256Hash row) { return StreamTestStreamHashAidxRow.of(row); } }; } @Override public byte[] persistToBytes() { byte[] hashBytes = hash.getBytes(); return EncodingUtils.add(hashBytes); } public static final Hydrator<StreamTestStreamHashAidxRow> BYTES_HYDRATOR = new Hydrator<StreamTestStreamHashAidxRow>() { @Override public StreamTestStreamHashAidxRow hydrateFromBytes(byte[] __input) { int __index = 0; Sha256Hash hash = new Sha256Hash(EncodingUtils.get32Bytes(__input, __index)); __index += 32; return new StreamTestStreamHashAidxRow(hash); } }; @Override public String toString() { return MoreObjects.toStringHelper(getClass().getSimpleName()) .add("hash", hash) .toString(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } StreamTestStreamHashAidxRow other = (StreamTestStreamHashAidxRow) obj; return Objects.equals(hash, other.hash); } @SuppressWarnings("ArrayHashCode") @Override public int hashCode() { return Objects.hashCode(hash); } @Override public int compareTo(StreamTestStreamHashAidxRow o) { return ComparisonChain.start() .compare(this.hash, o.hash) .result(); } } /** * <pre> * StreamTestStreamHashAidxColumn { * {@literal Long streamId}; * } * </pre> */ public static final class StreamTestStreamHashAidxColumn implements Persistable, Comparable<StreamTestStreamHashAidxColumn> { private final long streamId; public static StreamTestStreamHashAidxColumn of(long streamId) { return new StreamTestStreamHashAidxColumn(streamId); } private StreamTestStreamHashAidxColumn(long streamId) { this.streamId = streamId; } public long getStreamId() { return streamId; } public static Function<StreamTestStreamHashAidxColumn, Long> getStreamIdFun() { return new Function<StreamTestStreamHashAidxColumn, Long>() { @Override public Long apply(StreamTestStreamHashAidxColumn row) { return row.streamId; } }; } public static Function<Long, StreamTestStreamHashAidxColumn> fromStreamIdFun() { return new Function<Long, StreamTestStreamHashAidxColumn>() { @Override public StreamTestStreamHashAidxColumn apply(Long row) { return StreamTestStreamHashAidxColumn.of(row); } }; } @Override public byte[] persistToBytes() { byte[] streamIdBytes = EncodingUtils.encodeUnsignedVarLong(streamId); return EncodingUtils.add(streamIdBytes); } public static final Hydrator<StreamTestStreamHashAidxColumn> BYTES_HYDRATOR = new Hydrator<StreamTestStreamHashAidxColumn>() { @Override public StreamTestStreamHashAidxColumn hydrateFromBytes(byte[] __input) { int __index = 0; Long streamId = EncodingUtils.decodeUnsignedVarLong(__input, __index); __index += EncodingUtils.sizeOfUnsignedVarLong(streamId); return new StreamTestStreamHashAidxColumn(streamId); } }; @Override public String toString() { return MoreObjects.toStringHelper(getClass().getSimpleName()) .add("streamId", streamId) .toString(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } StreamTestStreamHashAidxColumn other = (StreamTestStreamHashAidxColumn) obj; return Objects.equals(streamId, other.streamId); } @SuppressWarnings("ArrayHashCode") @Override public int hashCode() { return Objects.hashCode(streamId); } @Override public int compareTo(StreamTestStreamHashAidxColumn o) { return ComparisonChain.start() .compare(this.streamId, o.streamId) .result(); } } public interface StreamTestStreamHashAidxTrigger { public void putStreamTestStreamHashAidx(Multimap<StreamTestStreamHashAidxRow, ? extends StreamTestStreamHashAidxColumnValue> newRows); } /** * <pre> * Column name description { * {@literal Long streamId}; * } * Column value description { * type: Long; * } * </pre> */ public static final class StreamTestStreamHashAidxColumnValue implements ColumnValue<Long> { private final StreamTestStreamHashAidxColumn columnName; private final Long value; public static StreamTestStreamHashAidxColumnValue of(StreamTestStreamHashAidxColumn columnName, Long value) { return new StreamTestStreamHashAidxColumnValue(columnName, value); } private StreamTestStreamHashAidxColumnValue(StreamTestStreamHashAidxColumn columnName, Long value) { this.columnName = columnName; this.value = value; } public StreamTestStreamHashAidxColumn getColumnName() { return columnName; } @Override public Long getValue() { return value; } @Override public byte[] persistColumnName() { return columnName.persistToBytes(); } @Override public byte[] persistValue() { byte[] bytes = EncodingUtils.encodeUnsignedVarLong(value); return CompressionUtils.compress(bytes, Compression.NONE); } public static Long hydrateValue(byte[] bytes) { bytes = CompressionUtils.decompress(bytes, Compression.NONE); return EncodingUtils.decodeUnsignedVarLong(bytes, 0); } public static Function<StreamTestStreamHashAidxColumnValue, StreamTestStreamHashAidxColumn> getColumnNameFun() { return new Function<StreamTestStreamHashAidxColumnValue, StreamTestStreamHashAidxColumn>() { @Override public StreamTestStreamHashAidxColumn apply(StreamTestStreamHashAidxColumnValue columnValue) { return columnValue.getColumnName(); } }; } public static Function<StreamTestStreamHashAidxColumnValue, Long> getValueFun() { return new Function<StreamTestStreamHashAidxColumnValue, Long>() { @Override public Long apply(StreamTestStreamHashAidxColumnValue columnValue) { return columnValue.getValue(); } }; } @Override public String toString() { return MoreObjects.toStringHelper(getClass().getSimpleName()) .add("ColumnName", this.columnName) .add("Value", this.value) .toString(); } } public static final class StreamTestStreamHashAidxRowResult implements TypedRowResult { private final StreamTestStreamHashAidxRow rowName; private final ImmutableSet<StreamTestStreamHashAidxColumnValue> columnValues; public static StreamTestStreamHashAidxRowResult of(RowResult<byte[]> rowResult) { StreamTestStreamHashAidxRow rowName = StreamTestStreamHashAidxRow.BYTES_HYDRATOR.hydrateFromBytes(rowResult.getRowName()); Set<StreamTestStreamHashAidxColumnValue> columnValues = Sets.newHashSetWithExpectedSize(rowResult.getColumns().size()); for (Entry<byte[], byte[]> e : rowResult.getColumns().entrySet()) { StreamTestStreamHashAidxColumn col = StreamTestStreamHashAidxColumn.BYTES_HYDRATOR.hydrateFromBytes(e.getKey()); Long value = StreamTestStreamHashAidxColumnValue.hydrateValue(e.getValue()); columnValues.add(StreamTestStreamHashAidxColumnValue.of(col, value)); } return new StreamTestStreamHashAidxRowResult(rowName, ImmutableSet.copyOf(columnValues)); } private StreamTestStreamHashAidxRowResult(StreamTestStreamHashAidxRow rowName, ImmutableSet<StreamTestStreamHashAidxColumnValue> columnValues) { this.rowName = rowName; this.columnValues = columnValues; } @Override public StreamTestStreamHashAidxRow getRowName() { return rowName; } public Set<StreamTestStreamHashAidxColumnValue> getColumnValues() { return columnValues; } public static Function<StreamTestStreamHashAidxRowResult, StreamTestStreamHashAidxRow> getRowNameFun() { return new Function<StreamTestStreamHashAidxRowResult, StreamTestStreamHashAidxRow>() { @Override public StreamTestStreamHashAidxRow apply(StreamTestStreamHashAidxRowResult rowResult) { return rowResult.rowName; } }; } public static Function<StreamTestStreamHashAidxRowResult, ImmutableSet<StreamTestStreamHashAidxColumnValue>> getColumnValuesFun() { return new Function<StreamTestStreamHashAidxRowResult, ImmutableSet<StreamTestStreamHashAidxColumnValue>>() { @Override public ImmutableSet<StreamTestStreamHashAidxColumnValue> apply(StreamTestStreamHashAidxRowResult rowResult) { return rowResult.columnValues; } }; } @Override public String toString() { return MoreObjects.toStringHelper(getClass().getSimpleName()) .add("RowName", getRowName()) .add("ColumnValues", getColumnValues()) .toString(); } } @Override public void delete(StreamTestStreamHashAidxRow row, StreamTestStreamHashAidxColumn column) { delete(ImmutableMultimap.of(row, column)); } @Override public void delete(Iterable<StreamTestStreamHashAidxRow> rows) { Multimap<StreamTestStreamHashAidxRow, StreamTestStreamHashAidxColumn> toRemove = HashMultimap.create(); Multimap<StreamTestStreamHashAidxRow, StreamTestStreamHashAidxColumnValue> result = getRowsMultimap(rows); for (Entry<StreamTestStreamHashAidxRow, StreamTestStreamHashAidxColumnValue> e : result.entries()) { toRemove.put(e.getKey(), e.getValue().getColumnName()); } delete(toRemove); } @Override public void delete(Multimap<StreamTestStreamHashAidxRow, StreamTestStreamHashAidxColumn> values) { t.delete(tableRef, ColumnValues.toCells(values)); } @Override public void put(StreamTestStreamHashAidxRow rowName, Iterable<StreamTestStreamHashAidxColumnValue> values) { put(ImmutableMultimap.<StreamTestStreamHashAidxRow, StreamTestStreamHashAidxColumnValue>builder().putAll(rowName, values).build()); } @Override public void put(StreamTestStreamHashAidxRow rowName, StreamTestStreamHashAidxColumnValue... values) { put(ImmutableMultimap.<StreamTestStreamHashAidxRow, StreamTestStreamHashAidxColumnValue>builder().putAll(rowName, values).build()); } @Override public void put(Multimap<StreamTestStreamHashAidxRow, ? extends StreamTestStreamHashAidxColumnValue> values) { t.useTable(tableRef, this); t.put(tableRef, ColumnValues.toCellValues(values)); for (StreamTestStreamHashAidxTrigger trigger : triggers) { trigger.putStreamTestStreamHashAidx(values); } } @Override public void touch(Multimap<StreamTestStreamHashAidxRow, StreamTestStreamHashAidxColumn> values) { Multimap<StreamTestStreamHashAidxRow, StreamTestStreamHashAidxColumnValue> currentValues = get(values); put(currentValues); Multimap<StreamTestStreamHashAidxRow, StreamTestStreamHashAidxColumn> toDelete = HashMultimap.create(values); for (Map.Entry<StreamTestStreamHashAidxRow, StreamTestStreamHashAidxColumnValue> e : currentValues.entries()) { toDelete.remove(e.getKey(), e.getValue().getColumnName()); } delete(toDelete); } public static ColumnSelection getColumnSelection(Collection<StreamTestStreamHashAidxColumn> cols) { return ColumnSelection.create(Collections2.transform(cols, Persistables.persistToBytesFunction())); } public static ColumnSelection getColumnSelection(StreamTestStreamHashAidxColumn... cols) { return getColumnSelection(Arrays.asList(cols)); } @Override public Multimap<StreamTestStreamHashAidxRow, StreamTestStreamHashAidxColumnValue> get(Multimap<StreamTestStreamHashAidxRow, StreamTestStreamHashAidxColumn> cells) { Set<Cell> rawCells = ColumnValues.toCells(cells); Map<Cell, byte[]> rawResults = t.get(tableRef, rawCells); Multimap<StreamTestStreamHashAidxRow, StreamTestStreamHashAidxColumnValue> rowMap = HashMultimap.create(); for (Entry<Cell, byte[]> e : rawResults.entrySet()) { if (e.getValue().length > 0) { StreamTestStreamHashAidxRow row = StreamTestStreamHashAidxRow.BYTES_HYDRATOR.hydrateFromBytes(e.getKey().getRowName()); StreamTestStreamHashAidxColumn col = StreamTestStreamHashAidxColumn.BYTES_HYDRATOR.hydrateFromBytes(e.getKey().getColumnName()); Long val = StreamTestStreamHashAidxColumnValue.hydrateValue(e.getValue()); rowMap.put(row, StreamTestStreamHashAidxColumnValue.of(col, val)); } } return rowMap; } @Override public List<StreamTestStreamHashAidxColumnValue> getRowColumns(StreamTestStreamHashAidxRow row) { return getRowColumns(row, allColumns); } @Override public List<StreamTestStreamHashAidxColumnValue> getRowColumns(StreamTestStreamHashAidxRow row, ColumnSelection columns) { byte[] bytes = row.persistToBytes(); RowResult<byte[]> rowResult = t.getRows(tableRef, ImmutableSet.of(bytes), columns).get(bytes); if (rowResult == null) { return ImmutableList.of(); } else { List<StreamTestStreamHashAidxColumnValue> ret = Lists.newArrayListWithCapacity(rowResult.getColumns().size()); for (Entry<byte[], byte[]> e : rowResult.getColumns().entrySet()) { StreamTestStreamHashAidxColumn col = StreamTestStreamHashAidxColumn.BYTES_HYDRATOR.hydrateFromBytes(e.getKey()); Long val = StreamTestStreamHashAidxColumnValue.hydrateValue(e.getValue()); ret.add(StreamTestStreamHashAidxColumnValue.of(col, val)); } return ret; } } @Override public Multimap<StreamTestStreamHashAidxRow, StreamTestStreamHashAidxColumnValue> getRowsMultimap(Iterable<StreamTestStreamHashAidxRow> rows) { return getRowsMultimapInternal(rows, allColumns); } @Override public Multimap<StreamTestStreamHashAidxRow, StreamTestStreamHashAidxColumnValue> getRowsMultimap(Iterable<StreamTestStreamHashAidxRow> rows, ColumnSelection columns) { return getRowsMultimapInternal(rows, columns); } private Multimap<StreamTestStreamHashAidxRow, StreamTestStreamHashAidxColumnValue> getRowsMultimapInternal(Iterable<StreamTestStreamHashAidxRow> rows, ColumnSelection columns) { SortedMap<byte[], RowResult<byte[]>> results = t.getRows(tableRef, Persistables.persistAll(rows), columns); return getRowMapFromRowResults(results.values()); } private static Multimap<StreamTestStreamHashAidxRow, StreamTestStreamHashAidxColumnValue> getRowMapFromRowResults(Collection<RowResult<byte[]>> rowResults) { Multimap<StreamTestStreamHashAidxRow, StreamTestStreamHashAidxColumnValue> rowMap = HashMultimap.create(); for (RowResult<byte[]> result : rowResults) { StreamTestStreamHashAidxRow row = StreamTestStreamHashAidxRow.BYTES_HYDRATOR.hydrateFromBytes(result.getRowName()); for (Entry<byte[], byte[]> e : result.getColumns().entrySet()) { StreamTestStreamHashAidxColumn col = StreamTestStreamHashAidxColumn.BYTES_HYDRATOR.hydrateFromBytes(e.getKey()); Long val = StreamTestStreamHashAidxColumnValue.hydrateValue(e.getValue()); rowMap.put(row, StreamTestStreamHashAidxColumnValue.of(col, val)); } } return rowMap; } @Override public Map<StreamTestStreamHashAidxRow, BatchingVisitable<StreamTestStreamHashAidxColumnValue>> getRowsColumnRange(Iterable<StreamTestStreamHashAidxRow> rows, BatchColumnRangeSelection columnRangeSelection) { Map<byte[], BatchingVisitable<Map.Entry<Cell, byte[]>>> results = t.getRowsColumnRange(tableRef, Persistables.persistAll(rows), columnRangeSelection); Map<StreamTestStreamHashAidxRow, BatchingVisitable<StreamTestStreamHashAidxColumnValue>> transformed = Maps.newHashMapWithExpectedSize(results.size()); for (Entry<byte[], BatchingVisitable<Map.Entry<Cell, byte[]>>> e : results.entrySet()) { StreamTestStreamHashAidxRow row = StreamTestStreamHashAidxRow.BYTES_HYDRATOR.hydrateFromBytes(e.getKey()); BatchingVisitable<StreamTestStreamHashAidxColumnValue> bv = BatchingVisitables.transform(e.getValue(), result -> { StreamTestStreamHashAidxColumn col = StreamTestStreamHashAidxColumn.BYTES_HYDRATOR.hydrateFromBytes(result.getKey().getColumnName()); Long val = StreamTestStreamHashAidxColumnValue.hydrateValue(result.getValue()); return StreamTestStreamHashAidxColumnValue.of(col, val); }); transformed.put(row, bv); } return transformed; } @Override public Iterator<Map.Entry<StreamTestStreamHashAidxRow, StreamTestStreamHashAidxColumnValue>> getRowsColumnRange(Iterable<StreamTestStreamHashAidxRow> rows, ColumnRangeSelection columnRangeSelection, int batchHint) { Iterator<Map.Entry<Cell, byte[]>> results = t.getRowsColumnRange(getTableRef(), Persistables.persistAll(rows), columnRangeSelection, batchHint); return Iterators.transform(results, e -> { StreamTestStreamHashAidxRow row = StreamTestStreamHashAidxRow.BYTES_HYDRATOR.hydrateFromBytes(e.getKey().getRowName()); StreamTestStreamHashAidxColumn col = StreamTestStreamHashAidxColumn.BYTES_HYDRATOR.hydrateFromBytes(e.getKey().getColumnName()); Long val = StreamTestStreamHashAidxColumnValue.hydrateValue(e.getValue()); StreamTestStreamHashAidxColumnValue colValue = StreamTestStreamHashAidxColumnValue.of(col, val); return Maps.immutableEntry(row, colValue); }); } @Override public Map<StreamTestStreamHashAidxRow, Iterator<StreamTestStreamHashAidxColumnValue>> getRowsColumnRangeIterator(Iterable<StreamTestStreamHashAidxRow> rows, BatchColumnRangeSelection columnRangeSelection) { Map<byte[], Iterator<Map.Entry<Cell, byte[]>>> results = t.getRowsColumnRangeIterator(tableRef, Persistables.persistAll(rows), columnRangeSelection); Map<StreamTestStreamHashAidxRow, Iterator<StreamTestStreamHashAidxColumnValue>> transformed = Maps.newHashMapWithExpectedSize(results.size()); for (Entry<byte[], Iterator<Map.Entry<Cell, byte[]>>> e : results.entrySet()) { StreamTestStreamHashAidxRow row = StreamTestStreamHashAidxRow.BYTES_HYDRATOR.hydrateFromBytes(e.getKey()); Iterator<StreamTestStreamHashAidxColumnValue> bv = Iterators.transform(e.getValue(), result -> { StreamTestStreamHashAidxColumn col = StreamTestStreamHashAidxColumn.BYTES_HYDRATOR.hydrateFromBytes(result.getKey().getColumnName()); Long val = StreamTestStreamHashAidxColumnValue.hydrateValue(result.getValue()); return StreamTestStreamHashAidxColumnValue.of(col, val); }); transformed.put(row, bv); } return transformed; } private ColumnSelection optimizeColumnSelection(ColumnSelection columns) { if (columns.allColumnsSelected()) { return allColumns; } return columns; } public BatchingVisitableView<StreamTestStreamHashAidxRowResult> getAllRowsUnordered() { return getAllRowsUnordered(allColumns); } public BatchingVisitableView<StreamTestStreamHashAidxRowResult> getAllRowsUnordered(ColumnSelection columns) { return BatchingVisitables.transform(t.getRange(tableRef, RangeRequest.builder() .retainColumns(optimizeColumnSelection(columns)).build()), new Function<RowResult<byte[]>, StreamTestStreamHashAidxRowResult>() { @Override public StreamTestStreamHashAidxRowResult apply(RowResult<byte[]> input) { return StreamTestStreamHashAidxRowResult.of(input); } }); } @Override public List<String> findConstraintFailures(Map<Cell, byte[]> writes, ConstraintCheckingTransaction transaction, AtlasDbConstraintCheckingMode constraintCheckingMode) { return ImmutableList.of(); } @Override public List<String> findConstraintFailuresNoRead(Map<Cell, byte[]> writes, AtlasDbConstraintCheckingMode constraintCheckingMode) { return ImmutableList.of(); } /** * This exists to avoid unused import warnings * {@link AbortingVisitor} * {@link AbortingVisitors} * {@link ArrayListMultimap} * {@link Arrays} * {@link AssertUtils} * {@link AtlasDbConstraintCheckingMode} * {@link AtlasDbDynamicMutablePersistentTable} * {@link AtlasDbMutablePersistentTable} * {@link AtlasDbNamedMutableTable} * {@link AtlasDbNamedPersistentSet} * {@link BatchColumnRangeSelection} * {@link BatchingVisitable} * {@link BatchingVisitableView} * {@link BatchingVisitables} * {@link BiFunction} * {@link Bytes} * {@link Callable} * {@link Cell} * {@link Cells} * {@link Collection} * {@link Collections2} * {@link ColumnRangeSelection} * {@link ColumnRangeSelections} * {@link ColumnSelection} * {@link ColumnValue} * {@link ColumnValues} * {@link ComparisonChain} * {@link Compression} * {@link CompressionUtils} * {@link ConstraintCheckingTransaction} * {@link Descending} * {@link EncodingUtils} * {@link Entry} * {@link EnumSet} * {@link Function} * {@link Generated} * {@link HashMultimap} * {@link HashSet} * {@link Hashing} * {@link Hydrator} * {@link ImmutableGetRangesQuery} * {@link ImmutableList} * {@link ImmutableMap} * {@link ImmutableMultimap} * {@link ImmutableSet} * {@link InvalidProtocolBufferException} * {@link IterableView} * {@link Iterables} * {@link Iterator} * {@link Iterators} * {@link Joiner} * {@link List} * {@link Lists} * {@link Map} * {@link Maps} * {@link MoreObjects} * {@link Multimap} * {@link Multimaps} * {@link NamedColumnValue} * {@link Namespace} * {@link Objects} * {@link Optional} * {@link Persistable} * {@link Persistables} * {@link Prefix} * {@link PtBytes} * {@link RangeRequest} * {@link RowResult} * {@link Set} * {@link Sets} * {@link Sha256Hash} * {@link SortedMap} * {@link Stream} * {@link Supplier} * {@link TableReference} * {@link Throwables} * {@link TimeUnit} * {@link Transaction} * {@link TypedRowResult} * {@link UUID} * {@link UnsignedBytes} * {@link ValueType} */ static String __CLASS_HASH = "n1Ji+IXKejaNz+wUbmp0+g=="; }
apache-2.0
LuxCore/dkitrish
1.Trainee/002.OOP/src/test/java/ru/job4j/coffeemachine/CoffeeMachineTest.java
1125
package ru.job4j.coffeemachine; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertThat; import static org.hamcrest.core.Is.is; /** * Tests giving of change from bying the coffee. */ public class CoffeeMachineTest { /** * Coffee machine. */ private CoffeeMachine automat; /** * Inits data for every test. */ @Before public void init() { this.automat = new CoffeeMachine(); } /** * Tetst giving of change for coffee. */ @Test public void testGiveChange() { this.automat.acceptPayment(30); this.automat.selectCoffee(Coffee.AMERICANO); int[] result = this.automat.giveChange(); int[] expected = new int[] {2, 2}; assertThat(result, is(expected)); this.automat.acceptPayment(56); this.automat.selectCoffee(Coffee.ESPRESSO); result = this.automat.giveChange(); expected = new int[] {10, 10, 1}; assertThat(result, is(expected)); this.automat.acceptPayment(96); this.automat.selectCoffee(Coffee.IRISH_WHISKУY); result = this.automat.giveChange(); expected = new int[] {10, 10, 10, 10, 5, 2, 2}; assertThat(result, is(expected)); } }
apache-2.0
runnerfish/SSH2
src/com/jialin/entity/User.java
1060
package com.jialin.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "p_user") public class User { private int id; private String name; private String password; private int age; @Column(name="name", length=30, nullable=false, unique=true) public String getName() { return name; } public void setName(String name) { this.name = name; } @Column(name="password", length=20, nullable=false, unique=true) public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Column(name="age", length=10) public int getAge() { return age; } public void setAge(Integer age) { this.age = 0; if (age != null) { this.age = age; } } @Id //²ÉÓÃÊý¾Ý¿â×ÔÔö·½Ê½Éú³ÉÖ÷¼ü //@GeneratedValue(strategy=GenerationType.AUTO) @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } }
apache-2.0
LXGaming/ClearLag
src/main/java/io/github/lxgaming/clearlag/mixin/core/world/WorldMixin.java
1948
/* * Copyright 2019 Alex Thomson * * 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.github.lxgaming.clearlag.mixin.core.world; import io.github.lxgaming.clearlag.ClearLag; import io.github.lxgaming.clearlag.bridge.entity.EntityBridge; import net.minecraft.entity.Entity; import net.minecraft.world.World; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.common.SpongeImpl; @Mixin(value = World.class, priority = 137) public abstract class WorldMixin { @Inject(method = "updateEntityWithOptionalForce", at = @At(value = "HEAD"), cancellable = true) private void onUpdateEntityWithOptionalForce(Entity entity, boolean forceUpdate, CallbackInfo callbackInfo) { EntityBridge entityBridge = (EntityBridge) entity; if (entityBridge.bridge$getLastTick() == SpongeImpl.getServer().getTickCounter()) { ClearLag.getInstance().debug("{} already ticked", entityBridge.getType().getId()); return; } entityBridge.bridge$setLastTick(SpongeImpl.getServer().getTickCounter()); entityBridge.bridge$removeEntity(); // Don't perform update logic on a dead entity if (entityBridge.isRemoved()) { callbackInfo.cancel(); } } }
apache-2.0
shaolinwu/uimaster
modules/workflow/src/main/java/org/shaolin/bmdp/workflow/internal/WorkFlowEventProcessor.java
5468
/* * Copyright 2015 The UIMaster Project * * The UIMaster Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * 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.shaolin.bmdp.workflow.internal; import java.util.Collection; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import org.shaolin.bmdp.runtime.AppContext; import org.shaolin.bmdp.runtime.be.ITaskEntity; import org.shaolin.bmdp.runtime.spi.Event; import org.shaolin.bmdp.runtime.spi.EventProcessor; import org.shaolin.bmdp.runtime.spi.IServiceProvider; import org.shaolin.bmdp.workflow.be.ITask; import org.shaolin.bmdp.workflow.coordinator.ICoordinatorService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Unified event processor which registered to one event producer. * * THe event processor will pass event to real app, an event producer * can be handled by multiple APPs. Each app will be one event consumer * instance. */ public final class WorkFlowEventProcessor implements EventProcessor, IServiceProvider { private static final Logger logger = LoggerFactory.getLogger(WorkFlowEventProcessor.class); // private final ExecutorService pool; private final Map<String, EventConsumer> allConsumers; private static final ThreadLocal<StringBuilder> idBuilder = new ThreadLocal<StringBuilder>() { @Override public StringBuilder initialValue() { return new StringBuilder(); } }; private final AtomicLong seq = new AtomicLong(0); public WorkFlowEventProcessor(Map<String, EventConsumer> allConsumers) { this.allConsumers = allConsumers; } Map<String, EventConsumer> getConsumers() { return allConsumers; } /** * for update. * @param tempProcessors */ void addConsumers(Map<String, EventConsumer> tempProcessors) { allConsumers.putAll(tempProcessors); } @Override public void process(final Event event) { // Generate a unique id for the event. if (event.getId() == null) { StringBuilder sb = idBuilder.get(); sb.setLength(0); event.setId(sb.append(event.getEventConsumer()) .append('[').append(seq.getAndIncrement()) .append(']').toString()); } boolean hasTaskEntity = false; event.setAttribute(BuiltInAttributeConstant.KEY_ORIGINAL_EVENT, event); Collection<String> keys = event.getAttributeKeys(); for (String key: keys) { Object var = event.getAttribute(key); // get the previous flow context from the first task entity with task id. if (var instanceof ITaskEntity) { hasTaskEntity = true; ITaskEntity taskObject = (ITaskEntity)var; if (taskObject.getTaskId() > 0 || (taskObject.getSessionId() != null && taskObject.getSessionId().length() > 0)) { try { FlowRuntimeContext flowContext = null; ICoordinatorService coordinator = AppContext.get().getService(ICoordinatorService.class); ITask task = null; if (taskObject.getSessionId() != null && taskObject.getSessionId().length() > 0) { // find the previous context from the last executed task. task = coordinator.getLastTaskBySessionId(taskObject.getSessionId()); if (task == null) { throw new IllegalStateException("No any task is existing! session ID: " + taskObject.getSessionId()); } } else if (taskObject.getTaskId() > 0) { task = coordinator.getTask(taskObject.getTaskId()); if (task == null) { throw new IllegalStateException("Task id is not existed! task ID: " + taskObject.getTaskId()); } } flowContext = FlowRuntimeContext.unmarshall(task.getFlowState()); flowContext.changeEvent(event); flowContext.getFlowContextInfo().setWaitingNode(flowContext.getCurrentNode()); flowContext.getEvent().setFlowContext(flowContext.getFlowContextInfo()); event.setFlowContext(flowContext.getFlowContextInfo()); break; } catch (Exception e) { throw new RuntimeException("Unable to process Workflow due to fail recovering the previous flow state!", e); } } } } if (!hasTaskEntity) { logger.warn("No any TaskEntity specified from {}", event.getId()); } if (logger.isTraceEnabled()) { logger.trace("Assign Id {} to event {}", event.getId(), event); logger.trace("Receive a event {}", event); } EventConsumer consumer = allConsumers.get(event.getEventConsumer()); if (logger.isTraceEnabled()) { logger.trace("Trigger event {} on {}", event.getId(), consumer); } if (!consumer.accept(event, null)) { logger.warn("No matched node for event {} from {}", event.getId(), event.getEventConsumer()); } } @Override public Class getServiceInterface() { return WorkFlowEventProcessor.class; } }
apache-2.0
jajakobyly/rustidea
tests/org/rustidea/psi/util/UnquoteTest.java
1603
/* * Copyright 2015 Marek Kaput * * 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.rustidea.psi.util; import com.intellij.util.containers.ContainerUtil; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.Collection; @RunWith(Parameterized.class) public class UnquoteTest { private final String input; private final String expected; public UnquoteTest(String input, String expected) { this.input = input; this.expected = expected; } @Parameters(name = "{index}: {0} -> {1}") public static Collection<Object[]> data() { return ContainerUtil.immutableList(new Object[][]{ {"'aaa'", "aaa"}, {"'bbb", "bbb"}, {"ccc'", "ccc"}, {"ddd", "ddd"}, {"''", ""}, {"'", ""}, {"", ""} }); } @Test public void test() { Assert.assertEquals(expected, RsStringUtil.unquote(input, '\'')); } }
apache-2.0
OpenNTF/XPagesToolkit
org.openntf.xpt.objectlist/src/org/openntf/xpt/objectlist/utils/SortOrder.java
144
package org.openntf.xpt.objectlist.utils; public enum SortOrder { NONE,ASC,DESC; public boolean isAscending() { return this == ASC; } }
apache-2.0
lalithsuresh/cassandra-c3
src/java/org/apache/cassandra/db/marshal/CompositeType.java
17096
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.db.marshal; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.google.common.collect.ImmutableList; import org.apache.cassandra.db.filter.ColumnSlice; import org.apache.cassandra.db.filter.SliceQueryFilter; import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.cassandra.exceptions.SyntaxException; import org.apache.cassandra.cql3.ColumnNameBuilder; import org.apache.cassandra.cql3.Relation; import org.apache.cassandra.io.util.DataOutputBuffer; import org.apache.cassandra.serializers.MarshalException; import org.apache.cassandra.utils.ByteBufferUtil; /* * The encoding of a CompositeType column name should be: * <component><component><component> ... * where <component> is: * <length of value><value><'end-of-component' byte> * where <length of value> is a 2 bytes unsigned short (but 0xFFFF is invalid, see * below) and the 'end-of-component' byte should always be 0 for actual column name. * However, it can set to 1 for query bounds. This allows to query for the * equivalent of 'give me the full super-column'. That is, if during a slice * query uses: * start = <3><"foo".getBytes()><0> * end = <3><"foo".getBytes()><1> * then he will be sure to get *all* the columns whose first component is "foo". * If for a component, the 'end-of-component' is != 0, there should not be any * following component. The end-of-component can also be -1 to allow * non-inclusive query. For instance: * start = <3><"foo".getBytes()><-1> * allows to query everything that is greater than <3><"foo".getBytes()>, but * not <3><"foo".getBytes()> itself. * * On top of that, CQL3 uses a specific prefix (0xFFFF) to encode "static columns" * (CASSANDRA-6561). This does mean the maximum size of the first component of a * composite is 65534, not 65535 (or we wouldn't be able to detect if the first 2 * bytes is the static prefix or not). */ public class CompositeType extends AbstractCompositeType { public static final int STATIC_MARKER = 0xFFFF; public final List<AbstractType<?>> types; // interning instances private static final Map<List<AbstractType<?>>, CompositeType> instances = new HashMap<List<AbstractType<?>>, CompositeType>(); public static CompositeType getInstance(TypeParser parser) throws ConfigurationException, SyntaxException { return getInstance(parser.getTypeParameters()); } public static CompositeType getInstance(AbstractType... types) { return getInstance(Arrays.<AbstractType<?>>asList(types)); } protected boolean readIsStatic(ByteBuffer bb) { return readStatic(bb); } private static boolean readStatic(ByteBuffer bb) { if (bb.remaining() < 2) return false; int header = ByteBufferUtil.getShortLength(bb, bb.position()); if ((header & 0xFFFF) != STATIC_MARKER) return false; ByteBufferUtil.readShortLength(bb); // Skip header return true; } public static synchronized CompositeType getInstance(List<AbstractType<?>> types) { assert types != null && !types.isEmpty(); CompositeType ct = instances.get(types); if (ct == null) { ct = new CompositeType(types); instances.put(types, ct); } return ct; } private CompositeType(List<AbstractType<?>> types) { this.types = ImmutableList.copyOf(types); } protected AbstractType<?> getComparator(int i, ByteBuffer bb) { try { return types.get(i); } catch (IndexOutOfBoundsException e) { // We shouldn't get there in general because 1) we shouldn't construct broken composites // from CQL and 2) broken composites coming from thrift should be rejected by validate. // There is a few cases however where, if the schema has changed since we created/validated // the composite, this will be thrown (see #6262). Those cases are a user error but // throwing a more meaningful error message to make understanding such error easier. . throw new RuntimeException("Cannot get comparator " + i + " in " + this + ". " + "This might due to a mismatch between the schema and the data read", e); } } protected AbstractType<?> getComparator(int i, ByteBuffer bb1, ByteBuffer bb2) { return getComparator(i, bb1); } protected AbstractType<?> getAndAppendComparator(int i, ByteBuffer bb, StringBuilder sb) { return types.get(i); } protected ParsedComparator parseComparator(int i, String part) { return new StaticParsedComparator(types.get(i), part); } protected AbstractType<?> validateComparator(int i, ByteBuffer bb) throws MarshalException { if (i >= types.size()) throw new MarshalException("Too many bytes for comparator"); return types.get(i); } public ByteBuffer decompose(Object... objects) { assert objects.length == types.size(); ByteBuffer[] serialized = new ByteBuffer[objects.length]; for (int i = 0; i < objects.length; i++) { ByteBuffer buffer = ((AbstractType) types.get(i)).decompose(objects[i]); serialized[i] = buffer; } return build(serialized); } // Extract component idx from bb. Return null if there is not enough component. public static ByteBuffer extractComponent(ByteBuffer bb, int idx) { bb = bb.duplicate(); readStatic(bb); int i = 0; while (bb.remaining() > 0) { ByteBuffer c = ByteBufferUtil.readBytesWithShortLength(bb); if (i == idx) return c; bb.get(); // skip end-of-component ++i; } return null; } // Extract CQL3 column name from the full column name. public ByteBuffer extractLastComponent(ByteBuffer bb) { int idx = types.get(types.size() - 1) instanceof ColumnToCollectionType ? types.size() - 2 : types.size() - 1; return extractComponent(bb, idx); } public static boolean isStaticName(ByteBuffer bb) { return bb.remaining() >= 2 && (ByteBufferUtil.getShortLength(bb, bb.position()) & 0xFFFF) == STATIC_MARKER; } @Override public int componentsCount() { return types.size(); } @Override public List<AbstractType<?>> getComponents() { return types; } @Override public boolean isCompatibleWith(AbstractType<?> previous) { if (this == previous) return true; if (!(previous instanceof CompositeType)) return false; // Extending with new components is fine CompositeType cp = (CompositeType)previous; if (types.size() < cp.types.size()) return false; for (int i = 0; i < cp.types.size(); i++) { AbstractType tprev = cp.types.get(i); AbstractType tnew = types.get(i); if (!tnew.isCompatibleWith(tprev)) return false; } return true; } @Override public boolean isValueCompatibleWithInternal(AbstractType<?> otherType) { if (this == otherType) return true; if (!(otherType instanceof CompositeType)) return false; // Extending with new components is fine CompositeType cp = (CompositeType) otherType; if (types.size() < cp.types.size()) return false; for (int i = 0; i < cp.types.size(); i++) { AbstractType tprev = cp.types.get(i); AbstractType tnew = types.get(i); if (!tnew.isValueCompatibleWith(tprev)) return false; } return true; } @Override public boolean intersects(List<ByteBuffer> minColumnNames, List<ByteBuffer> maxColumnNames, SliceQueryFilter filter) { assert minColumnNames.size() == maxColumnNames.size(); // If any of the slices in the filter intersect, return true outer: for (ColumnSlice slice : filter.slices) { ByteBuffer[] start = split(filter.isReversed() ? slice.finish : slice.start); ByteBuffer[] finish = split(filter.isReversed() ? slice.start : slice.finish); if (compare(start, maxColumnNames, true) > 0 || compare(finish, minColumnNames, false) < 0) continue; // slice does not intersect // We could safely return true here, but there's a minor optimization: if the first component is restricted // to a single value, we can check that the second component falls within the min/max for that component // (and repeat for all components). for (int i = 0; i < minColumnNames.size(); i++) { AbstractType<?> t = types.get(i); ByteBuffer s = i < start.length ? start[i] : ByteBufferUtil.EMPTY_BYTE_BUFFER; ByteBuffer f = i < finish.length ? finish[i] : ByteBufferUtil.EMPTY_BYTE_BUFFER; // we already know the first component falls within its min/max range (otherwise we wouldn't get here) if (i > 0 && !t.intersects(minColumnNames.get(i), maxColumnNames.get(i), s, f)) continue outer; // if this component isn't equal in the start and finish, we don't need to check any more if (i >= start.length || i >= finish.length || t.compare(s, f) != 0) break; } return true; } // none of the slices intersected return false; } /** Helper method for intersects() */ private int compare(ByteBuffer[] sliceBounds, List<ByteBuffer> sstableBounds, boolean isSliceStart) { for (int i = 0; i < sstableBounds.size(); i++) { if (i >= sliceBounds.length) return isSliceStart ? -1 : 1; int comparison = types.get(i).compare(sliceBounds[i], sstableBounds.get(i)); if (comparison != 0) return comparison; } return 0; } private static class StaticParsedComparator implements ParsedComparator { final AbstractType<?> type; final String part; StaticParsedComparator(AbstractType<?> type, String part) { this.type = type; this.part = part; } public AbstractType<?> getAbstractType() { return type; } public String getRemainingPart() { return part; } public int getComparatorSerializedSize() { return 0; } public void serializeComparator(ByteBuffer bb) {} } @Override public String toString() { return getClass().getName() + TypeParser.stringifyTypeParameters(types); } public Builder builder() { return new Builder(this); } public static ByteBuffer build(ByteBuffer... buffers) { int totalLength = 0; for (ByteBuffer bb : buffers) totalLength += 2 + bb.remaining() + 1; ByteBuffer out = ByteBuffer.allocate(totalLength); for (ByteBuffer bb : buffers) { ByteBufferUtil.writeShortLength(out, bb.remaining()); out.put(bb.duplicate()); out.put((byte) 0); } out.flip(); return out; } public static class Builder implements ColumnNameBuilder { private final CompositeType composite; private final List<ByteBuffer> components; private final byte[] endOfComponents; private int serializedSize; private final boolean isStatic; public Builder(CompositeType composite) { this(composite, new ArrayList<ByteBuffer>(composite.types.size()), new byte[composite.types.size()], false); } public static Builder staticBuilder(CompositeType composite) { return new Builder(composite, new ArrayList<ByteBuffer>(composite.types.size()), new byte[composite.types.size()], true); } private Builder(CompositeType composite, List<ByteBuffer> components, byte[] endOfComponents, boolean isStatic) { assert endOfComponents.length == composite.types.size(); this.composite = composite; this.components = components; this.endOfComponents = endOfComponents; this.isStatic = isStatic; if (isStatic) serializedSize = 2; } private Builder(Builder b) { this(b.composite, new ArrayList<ByteBuffer>(b.components), Arrays.copyOf(b.endOfComponents, b.endOfComponents.length), b.isStatic); this.serializedSize = b.serializedSize; } public Builder add(ByteBuffer bb) { if (components.size() >= composite.types.size()) throw new IllegalStateException("Composite column is already fully constructed"); components.add(bb); serializedSize += 3 + bb.remaining(); // 2 bytes lenght + 1 byte eoc return this; } public int componentCount() { return components.size(); } public int remainingCount() { return composite.types.size() - components.size(); } public ByteBuffer get(int i) { return components.get(i); } public ByteBuffer build() { try { DataOutputBuffer out = new DataOutputBuffer(serializedSize); if (isStatic) out.writeShort(STATIC_MARKER); for (int i = 0; i < components.size(); i++) { ByteBufferUtil.writeWithShortLength(components.get(i), out); out.write(endOfComponents[i]); } return ByteBuffer.wrap(out.getData(), 0, out.getLength()); } catch (IOException e) { throw new RuntimeException(e); } } public ByteBuffer buildAsEndOfRange() { if (components.isEmpty()) return ByteBufferUtil.EMPTY_BYTE_BUFFER; ByteBuffer bb = build(); bb.put(bb.remaining() - 1, (byte)1); return bb; } public ByteBuffer buildForRelation(Relation.Type op) { /* * Given the rules for eoc (end-of-component, see AbstractCompositeType.compare()), * We can select: * - = 'a' by using <'a'><0> * - < 'a' by using <'a'><-1> * - <= 'a' by using <'a'><1> * - > 'a' by using <'a'><1> * - >= 'a' by using <'a'><0> */ int current = components.size() - 1; switch (op) { case LT: endOfComponents[current] = (byte) -1; break; case GT: case LTE: endOfComponents[current] = (byte) 1; break; default: endOfComponents[current] = (byte) 0; break; } return build(); } public Builder copy() { return new Builder(this); } public ByteBuffer getComponent(int i) { if (i >= components.size()) throw new IllegalArgumentException(); return components.get(i); } public int getLength() { int length = 0; for (ByteBuffer component : components) length += component.remaining() + 3; // length + 2 bytes for length + EOC return length; } } }
apache-2.0
castrors/reddit
app/src/prod/java/com/castrodev/reddit/repository/Repository.java
864
package com.castrodev.reddit.repository; import com.castrodev.reddit.repository.Implementation.CommentRepositoryImpl; import com.castrodev.reddit.repository.Implementation.PostRepositoryImpl; import com.castrodev.reddit.repository.Interface.CommentRepository; import com.castrodev.reddit.repository.Interface.PostRespository; public class Repository { private static PostRespository postRespository; private static CommentRepository commentRepository; public static PostRespository providesPostRepository() { if (postRespository == null) postRespository = new PostRepositoryImpl(); return postRespository; } public static CommentRepository providesCommentRepository() { if (commentRepository == null) commentRepository = new CommentRepositoryImpl(); return commentRepository; } }
apache-2.0
liulongbiao/fastdfs-client
src/main/java/cn/strong/fastdfs/ex/FastdfsTimeoutException.java
329
/** * */ package cn.strong.fastdfs.ex; /** * Fastdfs 超时异常 * * @author liulongbiao * */ public class FastdfsTimeoutException extends FastdfsException { /** * */ private static final long serialVersionUID = -5384713284430243210L; public FastdfsTimeoutException(String message) { super(message); } }
apache-2.0
vespa-engine/vespa
container-core/src/main/java/com/yahoo/container/jdisc/EmptyResponse.java
536
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.container.jdisc; import java.io.IOException; import java.io.OutputStream; /** * Placeholder response when no content, only headers and status is to be returned. * * @author Steinar Knutsen */ public class EmptyResponse extends HttpResponse { public EmptyResponse(int status) { super(status); } public void render(OutputStream outputStream) throws IOException { // NOP } }
apache-2.0
manzoli2122/Vip
src/vip/core/domain/Task_.java
637
package vip.core.domain; import javax.annotation.Generated; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; import vip.kernel.domain.PersistentObjectRegister_; @Generated(value="Dali", date="2016-07-25T22:29:02.990-0300") @StaticMetamodel(Task.class) public class Task_ extends PersistentObjectRegister_ { public static volatile SingularAttribute<Task, String> name; public static volatile SingularAttribute<Task, Double> valor; public static volatile SingularAttribute<Task, Double> porcentagemFuncionario; public static volatile SingularAttribute<Task, Boolean> ativo; }
apache-2.0
dimaslv/heroic
heroic-core/src/main/java/com/spotify/heroic/cluster/CoreClusterNodeGroup.java
8616
/* * Copyright (c) 2015 Spotify AB. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.spotify.heroic.cluster; import com.spotify.heroic.QueryOptions; import com.spotify.heroic.aggregation.AggregationInstance; import com.spotify.heroic.cluster.ClusterNode.Group; import com.spotify.heroic.common.DateRange; import com.spotify.heroic.common.RangeFilter; import com.spotify.heroic.common.Series; import com.spotify.heroic.filter.Filter; import com.spotify.heroic.metadata.CountSeries; import com.spotify.heroic.metadata.DeleteSeries; import com.spotify.heroic.metadata.FindKeys; import com.spotify.heroic.metadata.FindSeries; import com.spotify.heroic.metadata.FindTags; import com.spotify.heroic.metric.MetricType; import com.spotify.heroic.metric.QueryTrace; import com.spotify.heroic.metric.ResultGroups; import com.spotify.heroic.metric.WriteMetric; import com.spotify.heroic.metric.WriteResult; import com.spotify.heroic.suggest.KeySuggest; import com.spotify.heroic.suggest.MatchOptions; import com.spotify.heroic.suggest.TagKeyCount; import com.spotify.heroic.suggest.TagSuggest; import com.spotify.heroic.suggest.TagValueSuggest; import com.spotify.heroic.suggest.TagValuesSuggest; import eu.toolchain.async.AsyncFramework; import eu.toolchain.async.AsyncFuture; import lombok.RequiredArgsConstructor; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Optional; @RequiredArgsConstructor public class CoreClusterNodeGroup implements ClusterNodeGroup { public static final QueryTrace.Identifier QUERY_NODE = QueryTrace.identifier(CoreClusterNodeGroup.class, "query_node"); public static final QueryTrace.Identifier QUERY = QueryTrace.identifier(CoreClusterNodeGroup.class, "query"); private final AsyncFramework async; private final Collection<ClusterNode.Group> entries; @Override public Iterator<Group> iterator() { return entries.iterator(); } @Override public ClusterNode node() { throw new IllegalStateException("No node associated with ClusterNodeGroups"); } @Override public AsyncFuture<ResultGroups> query( MetricType source, Filter filter, DateRange range, AggregationInstance aggregation, QueryOptions options ) { final List<AsyncFuture<ResultGroups>> futures = new ArrayList<>(entries.size()); for (final ClusterNode.Group g : entries) { futures.add(g .query(source, filter, range, aggregation, options) .catchFailed(ResultGroups.nodeError(QUERY_NODE, g))); } return async.collect(futures, ResultGroups.collect(QUERY)); } @Override public AsyncFuture<FindTags> findTags(RangeFilter filter) { final List<AsyncFuture<FindTags>> futures = new ArrayList<>(entries.size()); for (final ClusterNode.Group g : entries) { futures.add(g.findTags(filter).catchFailed(FindTags.nodeError(g))); } return async.collect(futures, FindTags.reduce()); } @Override public AsyncFuture<FindKeys> findKeys(RangeFilter filter) { final List<AsyncFuture<FindKeys>> futures = new ArrayList<>(entries.size()); for (final ClusterNode.Group g : entries) { futures.add(g.findKeys(filter).catchFailed(FindKeys.nodeError(g))); } return async.collect(futures, FindKeys.reduce()); } @Override public AsyncFuture<FindSeries> findSeries(RangeFilter filter) { final List<AsyncFuture<FindSeries>> futures = new ArrayList<>(entries.size()); for (final ClusterNode.Group g : entries) { futures.add(g.findSeries(filter).catchFailed(FindSeries.nodeError(g))); } return async.collect(futures, FindSeries.reduce(filter.getLimit())); } @Override public AsyncFuture<DeleteSeries> deleteSeries(RangeFilter filter) { final List<AsyncFuture<DeleteSeries>> futures = new ArrayList<>(entries.size()); for (final ClusterNode.Group g : entries) { futures.add(g.deleteSeries(filter).catchFailed(DeleteSeries.nodeError(g))); } return async.collect(futures, DeleteSeries.reduce()); } @Override public AsyncFuture<CountSeries> countSeries(RangeFilter filter) { final List<AsyncFuture<CountSeries>> futures = new ArrayList<>(entries.size()); for (final ClusterNode.Group g : entries) { futures.add(g.countSeries(filter).catchFailed(CountSeries.nodeError(g))); } return async.collect(futures, CountSeries.reduce()); } @Override public AsyncFuture<TagKeyCount> tagKeyCount(RangeFilter filter) { final List<AsyncFuture<TagKeyCount>> futures = new ArrayList<>(entries.size()); for (final ClusterNode.Group g : entries) { futures.add(g.tagKeyCount(filter).catchFailed(TagKeyCount.nodeError(g))); } return async.collect(futures, TagKeyCount.reduce(filter.getLimit())); } @Override public AsyncFuture<TagSuggest> tagSuggest( RangeFilter filter, MatchOptions options, Optional<String> key, Optional<String> value ) { final List<AsyncFuture<TagSuggest>> futures = new ArrayList<>(entries.size()); for (final ClusterNode.Group g : entries) { futures.add( g.tagSuggest(filter, options, key, value).catchFailed(TagSuggest.nodeError(g))); } return async.collect(futures, TagSuggest.reduce(filter.getLimit())); } @Override public AsyncFuture<KeySuggest> keySuggest( RangeFilter filter, MatchOptions options, Optional<String> key ) { final List<AsyncFuture<KeySuggest>> futures = new ArrayList<>(entries.size()); for (final ClusterNode.Group g : entries) { futures.add(g.keySuggest(filter, options, key).catchFailed(KeySuggest.nodeError(g))); } return async.collect(futures, KeySuggest.reduce(filter.getLimit())); } @Override public AsyncFuture<TagValuesSuggest> tagValuesSuggest( RangeFilter filter, List<String> exclude, int groupLimit ) { final List<AsyncFuture<TagValuesSuggest>> futures = new ArrayList<>(entries.size()); for (final ClusterNode.Group g : entries) { futures.add(g .tagValuesSuggest(filter, exclude, groupLimit) .catchFailed(TagValuesSuggest.nodeError(g))); } return async.collect(futures, TagValuesSuggest.reduce(filter.getLimit(), groupLimit)); } @Override public AsyncFuture<TagValueSuggest> tagValueSuggest(RangeFilter filter, Optional<String> key) { final List<AsyncFuture<TagValueSuggest>> futures = new ArrayList<>(entries.size()); for (final ClusterNode.Group g : entries) { futures.add(g.tagValueSuggest(filter, key).catchFailed(TagValueSuggest.nodeError(g))); } return async.collect(futures, TagValueSuggest.reduce(filter.getLimit())); } @Override public AsyncFuture<WriteResult> writeSeries(DateRange range, Series series) { final List<AsyncFuture<WriteResult>> futures = new ArrayList<>(entries.size()); for (final ClusterNode.Group g : entries) { futures.add(g.writeSeries(range, series).catchFailed(WriteResult.nodeError(g))); } return async.collect(futures, WriteResult.merger()); } @Override public AsyncFuture<WriteResult> writeMetric(WriteMetric write) { final List<AsyncFuture<WriteResult>> futures = new ArrayList<>(entries.size()); for (final ClusterNode.Group g : entries) { futures.add(g.writeMetric(write).catchFailed(WriteResult.nodeError(g))); } return async.collect(futures, WriteResult.merger()); } }
apache-2.0
liuzyw/study-hello
spring-boot-shiro/src/main/java/com/study/spring/entity/SysPermission.java
2396
package com.study.spring.entity; import java.io.Serializable; /** * Created on 2018-01-06 * <p>权限实体类</p> * * @author liuzhaoyuan */ public class SysPermission implements Serializable { private static final long serialVersionUID = 9116034510405843082L; private Integer id; // 名称. private String name; // 资源类型,[menu|button] private String resourceType; // 资源路径. private String url; // 权限字符串,menu例子:role:*,button例子:role:create,role:update,role:delete,role:view private String permission; // 父编号 private Long parentId; // 父编号列表 private String parentIds; private Integer available = 1; public SysPermission() { } @Override public String toString() { return "SysPermission{" + "id=" + id + ", name='" + name + '\'' + ", resourceType='" + resourceType + '\'' + ", url='" + url + '\'' + ", permission='" + permission + '\'' + ", parentId=" + parentId + ", parentIds='" + parentIds + '\'' + ", available=" + available + '}'; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getResourceType() { return resourceType; } public void setResourceType(String resourceType) { this.resourceType = resourceType; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getPermission() { return permission; } public void setPermission(String permission) { this.permission = permission; } public Long getParentId() { return parentId; } public void setParentId(Long parentId) { this.parentId = parentId; } public String getParentIds() { return parentIds; } public void setParentIds(String parentIds) { this.parentIds = parentIds; } public Integer getAvailable() { return available; } public void setAvailable(Integer available) { this.available = available; } }
apache-2.0
ppamorim/ExoPlayer
library/src/main/java/com/google/android/exoplayer/MediaCodecVideoTrackRenderer.java
24133
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer; import com.google.android.exoplayer.MediaCodecUtil.DecoderQueryException; import com.google.android.exoplayer.drm.DrmSessionManager; import com.google.android.exoplayer.util.MimeTypes; import com.google.android.exoplayer.util.TraceUtil; import com.google.android.exoplayer.util.Util; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.media.MediaCodec; import android.media.MediaCrypto; import android.os.Handler; import android.os.SystemClock; import android.view.Surface; import android.view.TextureView; import java.nio.ByteBuffer; /** * Decodes and renders video using {@link MediaCodec}. */ @TargetApi(16) public class MediaCodecVideoTrackRenderer extends MediaCodecTrackRenderer { /** * Interface definition for a callback to be notified of {@link MediaCodecVideoTrackRenderer} * events. */ public interface EventListener extends MediaCodecTrackRenderer.EventListener { /** * Invoked to report the number of frames dropped by the renderer. Dropped frames are reported * whenever the renderer is stopped having dropped frames, and optionally, whenever the count * reaches a specified threshold whilst the renderer is started. * * @param count The number of dropped frames. * @param elapsed The duration in milliseconds over which the frames were dropped. This * duration is timed from when the renderer was started or from when dropped frames were * last reported (whichever was more recent), and not from when the first of the reported * drops occurred. */ void onDroppedFrames(int count, long elapsed); /** * Invoked each time there's a change in the size of the video being rendered. * * @param width The video width in pixels. * @param height The video height in pixels. * @param unappliedRotationDegrees For videos that require a rotation, this is the clockwise * rotation in degrees that the application should apply for the video for it to be rendered * in the correct orientation. This value will always be zero on API levels 21 and above, * since the renderer will apply all necessary rotations internally. On earlier API levels * this is not possible. Applications that use {@link TextureView} can apply the rotation by * calling {@link TextureView#setTransform}. Applications that do not expect to encounter * rotated videos can safely ignore this parameter. * @param pixelWidthHeightRatio The width to height ratio of each pixel. For the normal case * of square pixels this will be equal to 1.0. Different values are indicative of anamorphic * content. */ void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio); /** * Invoked when a frame is rendered to a surface for the first time following that surface * having been set as the target for the renderer. * * @param surface The surface to which a first frame has been rendered. */ void onDrawnToSurface(Surface surface); } // TODO: Use MediaFormat constants if these get exposed through the API. See [Internal: b/14127601]. private static final String KEY_CROP_LEFT = "crop-left"; private static final String KEY_CROP_RIGHT = "crop-right"; private static final String KEY_CROP_BOTTOM = "crop-bottom"; private static final String KEY_CROP_TOP = "crop-top"; /** * The type of a message that can be passed to an instance of this class via * {@link ExoPlayer#sendMessage} or {@link ExoPlayer#blockingSendMessage}. The message object * should be the target {@link Surface}, or null. */ public static final int MSG_SET_SURFACE = 1; private final VideoFrameReleaseTimeHelper frameReleaseTimeHelper; private final EventListener eventListener; private final long allowedJoiningTimeUs; private final int videoScalingMode; private final int maxDroppedFrameCountToNotify; private Surface surface; private boolean reportedDrawnToSurface; private boolean renderedFirstFrame; private long joiningDeadlineUs; private long droppedFrameAccumulationStartTimeMs; private int droppedFrameCount; private int consecutiveDroppedFrameCount; private int pendingRotationDegrees; private float pendingPixelWidthHeightRatio; private int currentWidth; private int currentHeight; private int currentUnappliedRotationDegrees; private float currentPixelWidthHeightRatio; private int lastReportedWidth; private int lastReportedHeight; private int lastReportedUnappliedRotationDegrees; private float lastReportedPixelWidthHeightRatio; /** * @param context A context. * @param source The upstream source from which the renderer obtains samples. * @param videoScalingMode The scaling mode to pass to * {@link MediaCodec#setVideoScalingMode(int)}. */ public MediaCodecVideoTrackRenderer(Context context, SampleSource source, int videoScalingMode) { this(context, source, videoScalingMode, 0); } /** * @param context A context. * @param source The upstream source from which the renderer obtains samples. * @param videoScalingMode The scaling mode to pass to * {@link MediaCodec#setVideoScalingMode(int)}. * @param allowedJoiningTimeMs The maximum duration in milliseconds for which this video renderer * can attempt to seamlessly join an ongoing playback. */ public MediaCodecVideoTrackRenderer(Context context, SampleSource source, int videoScalingMode, long allowedJoiningTimeMs) { this(context, source, videoScalingMode, allowedJoiningTimeMs, null, null, -1); } /** * @param context A context. * @param source The upstream source from which the renderer obtains samples. * @param videoScalingMode The scaling mode to pass to * {@link MediaCodec#setVideoScalingMode(int)}. * @param allowedJoiningTimeMs The maximum duration in milliseconds for which this video renderer * can attempt to seamlessly join an ongoing playback. * @param eventHandler A handler to use when delivering events to {@code eventListener}. May be * null if delivery of events is not required. * @param eventListener A listener of events. May be null if delivery of events is not required. * @param maxDroppedFrameCountToNotify The maximum number of frames that can be dropped between * invocations of {@link EventListener#onDroppedFrames(int, long)}. */ public MediaCodecVideoTrackRenderer(Context context, SampleSource source, int videoScalingMode, long allowedJoiningTimeMs, Handler eventHandler, EventListener eventListener, int maxDroppedFrameCountToNotify) { this(context, source, videoScalingMode, allowedJoiningTimeMs, null, false, eventHandler, eventListener, maxDroppedFrameCountToNotify); } /** * @param context A context. * @param source The upstream source from which the renderer obtains samples. * @param videoScalingMode The scaling mode to pass to * {@link MediaCodec#setVideoScalingMode(int)}. * @param allowedJoiningTimeMs The maximum duration in milliseconds for which this video renderer * can attempt to seamlessly join an ongoing playback. * @param drmSessionManager For use with encrypted content. May be null if support for encrypted * content is not required. * @param playClearSamplesWithoutKeys Encrypted media may contain clear (un-encrypted) regions. * For example a media file may start with a short clear region so as to allow playback to * begin in parallel with key acquisision. This parameter specifies whether the renderer is * permitted to play clear regions of encrypted media files before {@code drmSessionManager} * has obtained the keys necessary to decrypt encrypted regions of the media. * @param eventHandler A handler to use when delivering events to {@code eventListener}. May be * null if delivery of events is not required. * @param eventListener A listener of events. May be null if delivery of events is not required. * @param maxDroppedFrameCountToNotify The maximum number of frames that can be dropped between * invocations of {@link EventListener#onDroppedFrames(int, long)}. */ public MediaCodecVideoTrackRenderer(Context context, SampleSource source, int videoScalingMode, long allowedJoiningTimeMs, DrmSessionManager drmSessionManager, boolean playClearSamplesWithoutKeys, Handler eventHandler, EventListener eventListener, int maxDroppedFrameCountToNotify) { super(source, drmSessionManager, playClearSamplesWithoutKeys, eventHandler, eventListener); this.frameReleaseTimeHelper = new VideoFrameReleaseTimeHelper(context); this.videoScalingMode = videoScalingMode; this.allowedJoiningTimeUs = allowedJoiningTimeMs * 1000; this.eventListener = eventListener; this.maxDroppedFrameCountToNotify = maxDroppedFrameCountToNotify; joiningDeadlineUs = -1; currentWidth = -1; currentHeight = -1; currentPixelWidthHeightRatio = -1; pendingPixelWidthHeightRatio = -1; lastReportedWidth = -1; lastReportedHeight = -1; lastReportedPixelWidthHeightRatio = -1; } @Override protected boolean handlesTrack(MediaFormat mediaFormat) throws DecoderQueryException { // TODO: Use MediaCodecList.findDecoderForFormat on API 23. String mimeType = mediaFormat.mimeType; return MimeTypes.isVideo(mimeType) && (MimeTypes.VIDEO_UNKNOWN.equals(mimeType) || MediaCodecUtil.getDecoderInfo(mimeType, false) != null); } @Override protected void onEnabled(int track, long positionUs, boolean joining) throws ExoPlaybackException { super.onEnabled(track, positionUs, joining); renderedFirstFrame = false; consecutiveDroppedFrameCount = 0; if (joining && allowedJoiningTimeUs > 0) { joiningDeadlineUs = SystemClock.elapsedRealtime() * 1000L + allowedJoiningTimeUs; } frameReleaseTimeHelper.enable(); } @Override protected void seekTo(long positionUs) throws ExoPlaybackException { super.seekTo(positionUs); renderedFirstFrame = false; consecutiveDroppedFrameCount = 0; joiningDeadlineUs = -1; } @Override protected boolean isReady() { if (super.isReady() && (renderedFirstFrame || !codecInitialized() || getSourceState() == SOURCE_STATE_READY_READ_MAY_FAIL)) { // Ready. If we were joining then we've now joined, so clear the joining deadline. joiningDeadlineUs = -1; return true; } else if (joiningDeadlineUs == -1) { // Not joining. return false; } else if (SystemClock.elapsedRealtime() * 1000 < joiningDeadlineUs) { // Joining and still within the joining deadline. return true; } else { // The joining deadline has been exceeded. Give up and clear the deadline. joiningDeadlineUs = -1; return false; } } @Override protected void onStarted() { super.onStarted(); droppedFrameCount = 0; droppedFrameAccumulationStartTimeMs = SystemClock.elapsedRealtime(); } @Override protected void onStopped() { joiningDeadlineUs = -1; maybeNotifyDroppedFrameCount(); super.onStopped(); } @Override protected void onDisabled() throws ExoPlaybackException { currentWidth = -1; currentHeight = -1; currentPixelWidthHeightRatio = -1; pendingPixelWidthHeightRatio = -1; lastReportedWidth = -1; lastReportedHeight = -1; lastReportedPixelWidthHeightRatio = -1; frameReleaseTimeHelper.disable(); super.onDisabled(); } @Override public void handleMessage(int messageType, Object message) throws ExoPlaybackException { if (messageType == MSG_SET_SURFACE) { setSurface((Surface) message); } else { super.handleMessage(messageType, message); } } /** * @param surface The surface to set. * @throws ExoPlaybackException */ private void setSurface(Surface surface) throws ExoPlaybackException { if (this.surface == surface) { return; } this.surface = surface; this.reportedDrawnToSurface = false; int state = getState(); if (state == TrackRenderer.STATE_ENABLED || state == TrackRenderer.STATE_STARTED) { releaseCodec(); maybeInitCodec(); } } @Override protected boolean shouldInitCodec() { return super.shouldInitCodec() && surface != null && surface.isValid(); } // Override configureCodec to provide the surface. @Override protected void configureCodec(MediaCodec codec, String codecName, boolean codecIsAdaptive, android.media.MediaFormat format, MediaCrypto crypto) { maybeSetMaxInputSize(format, codecIsAdaptive); codec.configure(format, surface, crypto, 0); codec.setVideoScalingMode(videoScalingMode); } @Override protected void onInputFormatChanged(MediaFormatHolder holder) throws ExoPlaybackException { super.onInputFormatChanged(holder); pendingPixelWidthHeightRatio = holder.format.pixelWidthHeightRatio == MediaFormat.NO_VALUE ? 1 : holder.format.pixelWidthHeightRatio; pendingRotationDegrees = holder.format.rotationDegrees == MediaFormat.NO_VALUE ? 0 : holder.format.rotationDegrees; } /** * @return True if the first frame has been rendered (playback has not necessarily begun). */ protected final boolean haveRenderedFirstFrame() { return renderedFirstFrame; } @Override protected void onOutputFormatChanged(android.media.MediaFormat outputFormat) { boolean hasCrop = outputFormat.containsKey(KEY_CROP_RIGHT) && outputFormat.containsKey(KEY_CROP_LEFT) && outputFormat.containsKey(KEY_CROP_BOTTOM) && outputFormat.containsKey(KEY_CROP_TOP); currentWidth = hasCrop ? outputFormat.getInteger(KEY_CROP_RIGHT) - outputFormat.getInteger(KEY_CROP_LEFT) + 1 : outputFormat.getInteger(android.media.MediaFormat.KEY_WIDTH); currentHeight = hasCrop ? outputFormat.getInteger(KEY_CROP_BOTTOM) - outputFormat.getInteger(KEY_CROP_TOP) + 1 : outputFormat.getInteger(android.media.MediaFormat.KEY_HEIGHT); currentPixelWidthHeightRatio = pendingPixelWidthHeightRatio; if (Util.SDK_INT >= 21) { // On API level 21 and above the decoder applies the rotation when rendering to the surface. // Hence currentUnappliedRotation should always be 0. For 90 and 270 degree rotations, we need // to flip the width, height and pixel aspect ratio to reflect the rotation that was applied. if (pendingRotationDegrees == 90 || pendingRotationDegrees == 270) { int rotatedHeight = currentWidth; currentWidth = currentHeight; currentHeight = rotatedHeight; currentPixelWidthHeightRatio = 1 / currentPixelWidthHeightRatio; } } else { // On API level 20 and below the decoder does not apply the rotation. currentUnappliedRotationDegrees = pendingRotationDegrees; } } @Override protected boolean canReconfigureCodec(MediaCodec codec, boolean codecIsAdaptive, MediaFormat oldFormat, MediaFormat newFormat) { return newFormat.mimeType.equals(oldFormat.mimeType) && (codecIsAdaptive || (oldFormat.width == newFormat.width && oldFormat.height == newFormat.height)); } @Override protected boolean processOutputBuffer(long positionUs, long elapsedRealtimeUs, MediaCodec codec, ByteBuffer buffer, MediaCodec.BufferInfo bufferInfo, int bufferIndex, boolean shouldSkip) { if (shouldSkip) { skipOutputBuffer(codec, bufferIndex); consecutiveDroppedFrameCount = 0; return true; } if (!renderedFirstFrame) { if (Util.SDK_INT >= 21) { renderOutputBufferV21(codec, bufferIndex, System.nanoTime()); } else { renderOutputBuffer(codec, bufferIndex); } consecutiveDroppedFrameCount = 0; return true; } if (getState() != TrackRenderer.STATE_STARTED) { return false; } // Compute how many microseconds it is until the buffer's presentation time. long elapsedSinceStartOfLoopUs = (SystemClock.elapsedRealtime() * 1000) - elapsedRealtimeUs; long earlyUs = bufferInfo.presentationTimeUs - positionUs - elapsedSinceStartOfLoopUs; // Compute the buffer's desired release time in nanoseconds. long systemTimeNs = System.nanoTime(); long unadjustedFrameReleaseTimeNs = systemTimeNs + (earlyUs * 1000); // Apply a timestamp adjustment, if there is one. long adjustedReleaseTimeNs = frameReleaseTimeHelper.adjustReleaseTime( bufferInfo.presentationTimeUs, unadjustedFrameReleaseTimeNs); earlyUs = (adjustedReleaseTimeNs - systemTimeNs) / 1000; if (earlyUs < -30000) { // We're more than 30ms late rendering the frame. dropOutputBuffer(codec, bufferIndex); return true; } if (Util.SDK_INT >= 21) { // Let the underlying framework time the release. if (earlyUs < 50000) { renderOutputBufferV21(codec, bufferIndex, adjustedReleaseTimeNs); consecutiveDroppedFrameCount = 0; return true; } } else { // We need to time the release ourselves. if (earlyUs < 30000) { if (earlyUs > 11000) { // We're a little too early to render the frame. Sleep until the frame can be rendered. // Note: The 11ms threshold was chosen fairly arbitrarily. try { // Subtracting 10000 rather than 11000 ensures the sleep time will be at least 1ms. Thread.sleep((earlyUs - 10000) / 1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } renderOutputBuffer(codec, bufferIndex); consecutiveDroppedFrameCount = 0; return true; } } // We're either not playing, or it's not time to render the frame yet. return false; } protected void skipOutputBuffer(MediaCodec codec, int bufferIndex) { TraceUtil.beginSection("skipVideoBuffer"); codec.releaseOutputBuffer(bufferIndex, false); TraceUtil.endSection(); codecCounters.skippedOutputBufferCount++; } protected void dropOutputBuffer(MediaCodec codec, int bufferIndex) { TraceUtil.beginSection("dropVideoBuffer"); codec.releaseOutputBuffer(bufferIndex, false); TraceUtil.endSection(); codecCounters.droppedOutputBufferCount++; droppedFrameCount++; consecutiveDroppedFrameCount++; codecCounters.maxConsecutiveDroppedOutputBufferCount = Math.max(consecutiveDroppedFrameCount, codecCounters.maxConsecutiveDroppedOutputBufferCount); if (droppedFrameCount == maxDroppedFrameCountToNotify) { maybeNotifyDroppedFrameCount(); } } protected void renderOutputBuffer(MediaCodec codec, int bufferIndex) { maybeNotifyVideoSizeChanged(); TraceUtil.beginSection("releaseOutputBuffer"); codec.releaseOutputBuffer(bufferIndex, true); TraceUtil.endSection(); codecCounters.renderedOutputBufferCount++; renderedFirstFrame = true; maybeNotifyDrawnToSurface(); } @TargetApi(21) protected void renderOutputBufferV21(MediaCodec codec, int bufferIndex, long releaseTimeNs) { maybeNotifyVideoSizeChanged(); TraceUtil.beginSection("releaseOutputBuffer"); codec.releaseOutputBuffer(bufferIndex, releaseTimeNs); TraceUtil.endSection(); codecCounters.renderedOutputBufferCount++; renderedFirstFrame = true; maybeNotifyDrawnToSurface(); } @SuppressLint("InlinedApi") private void maybeSetMaxInputSize(android.media.MediaFormat format, boolean codecIsAdaptive) { if (!MimeTypes.VIDEO_H264.equals(format.getString(android.media.MediaFormat.KEY_MIME))) { // Only set a max input size for H264 for now. return; } if (format.containsKey(android.media.MediaFormat.KEY_MAX_INPUT_SIZE)) { // Already set. The source of the format may know better, so do nothing. return; } if ("BRAVIA 4K 2015".equals(Util.MODEL)) { // The Sony BRAVIA 4k TV has input buffers that are too small for the calculated 4k video // maximum input size, so use the default value. return; } int maxHeight = format.getInteger(android.media.MediaFormat.KEY_HEIGHT); if (codecIsAdaptive && format.containsKey(android.media.MediaFormat.KEY_MAX_HEIGHT)) { maxHeight = Math.max(maxHeight, format.getInteger(android.media.MediaFormat.KEY_MAX_HEIGHT)); } int maxWidth = format.getInteger(android.media.MediaFormat.KEY_WIDTH); if (codecIsAdaptive && format.containsKey(android.media.MediaFormat.KEY_MAX_WIDTH)) { maxWidth = Math.max(maxHeight, format.getInteger(android.media.MediaFormat.KEY_MAX_WIDTH)); } // H264 requires compression ratio of at least 2, and uses macroblocks. int maxInputSize = ((maxWidth + 15) / 16) * ((maxHeight + 15) / 16) * 192; format.setInteger(android.media.MediaFormat.KEY_MAX_INPUT_SIZE, maxInputSize); } private void maybeNotifyVideoSizeChanged() { if (eventHandler == null || eventListener == null || (lastReportedWidth == currentWidth && lastReportedHeight == currentHeight && lastReportedUnappliedRotationDegrees == currentUnappliedRotationDegrees && lastReportedPixelWidthHeightRatio == currentPixelWidthHeightRatio)) { return; } // Make final copies to ensure the runnable reports the correct values. final int currentWidth = this.currentWidth; final int currentHeight = this.currentHeight; final int currentUnappliedRotationDegrees = this.currentUnappliedRotationDegrees; final float currentPixelWidthHeightRatio = this.currentPixelWidthHeightRatio; eventHandler.post(new Runnable() { @Override public void run() { eventListener.onVideoSizeChanged(currentWidth, currentHeight, currentUnappliedRotationDegrees, currentPixelWidthHeightRatio); } }); // Update the last reported values. lastReportedWidth = currentWidth; lastReportedHeight = currentHeight; lastReportedUnappliedRotationDegrees = currentUnappliedRotationDegrees; lastReportedPixelWidthHeightRatio = currentPixelWidthHeightRatio; } private void maybeNotifyDrawnToSurface() { if (eventHandler == null || eventListener == null || reportedDrawnToSurface) { return; } // Make a final copy to ensure the runnable reports the correct surface. final Surface surface = this.surface; eventHandler.post(new Runnable() { @Override public void run() { eventListener.onDrawnToSurface(surface); } }); // Record that we have reported that the surface has been drawn to. reportedDrawnToSurface = true; } private void maybeNotifyDroppedFrameCount() { if (eventHandler == null || eventListener == null || droppedFrameCount == 0) { return; } long now = SystemClock.elapsedRealtime(); // Make final copies to ensure the runnable reports the correct values. final int countToNotify = droppedFrameCount; final long elapsedToNotify = now - droppedFrameAccumulationStartTimeMs; eventHandler.post(new Runnable() { @Override public void run() { eventListener.onDroppedFrames(countToNotify, elapsedToNotify); } }); // Reset the dropped frame tracking. droppedFrameCount = 0; droppedFrameAccumulationStartTimeMs = now; } }
apache-2.0
YoungDigitalPlanet/empiria.player
src/main/java/eu/ydp/empiria/player/client/gin/providers/VariableProcessingAdapterPageScopedProvider.java
1399
/* * Copyright 2017 Young Digital Planet S.A. * * 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 eu.ydp.empiria.player.client.gin.providers; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import eu.ydp.empiria.player.client.controller.variables.processor.VariableProcessingAdapter; import eu.ydp.empiria.player.client.gin.scopes.page.CurrentPageScopeProvider; import eu.ydp.empiria.player.client.gin.scopes.page.PageScopedProvider; @Singleton public class VariableProcessingAdapterPageScopedProvider extends PageScopedProvider<VariableProcessingAdapter> { @Inject public VariableProcessingAdapterPageScopedProvider(Provider<VariableProcessingAdapter> provider, CurrentPageScopeProvider currentScopeProvider) { super(provider, currentScopeProvider); } }
apache-2.0
SRmonologue/coolweather
app/src/main/java/com/cooleweather/android/MainActivity.java
847
package com.cooleweather.android; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.cooleweather.android.ui.activity.WeatherActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initData(); } private void initData() { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); if (sp.getString("weather", null) != null) { Intent intent = new Intent(this, WeatherActivity.class); startActivity(intent); finish(); } } }
apache-2.0
tianyun6655/EducationSystemAndroid
EducationSystem/app/src/main/java/dao/BandParentDao.java
815
package dao; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; /** * Created by tianyunchen on 11/19/16. */ public class BandParentDao extends BaseDao { private String actionName ="student/bandParent"; private final String TAG="BandParentDao"; @Override public String getAcionName() { return actionName; } @Override public String getTAG() { return TAG; } public void setParamers(int stid,int pid,int cid){ HashMap<String,String> hashMap = new HashMap<String, String>(); hashMap.put("stid",stid+""); hashMap.put("pid",pid+""); hashMap.put("cid",cid+""); loadData(hashMap); } @Override protected void dealWithJson(JSONObject jsonObject) throws JSONException { } }
apache-2.0
kamalmarhubi/bazel
src/test/java/com/google/devtools/build/lib/actions/ResourceSetTest.java
2154
// Copyright 2015 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.actions; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import com.google.devtools.build.lib.actions.ResourceSet.ResourceSetConverter; import com.google.devtools.common.options.OptionsParsingException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests for @{link ResourceSet}. */ @RunWith(JUnit4.class) public class ResourceSetTest { private ResourceSetConverter converter; @Before public void setUp() throws Exception { converter = new ResourceSetConverter(); } @Test public void testConverterParsesExpectedFormat() throws Exception { ResourceSet resources = converter.convert("1,0.5,2"); assertEquals(1.0, resources.getMemoryMb(), 0.01); assertEquals(0.5, resources.getCpuUsage(), 0.01); assertEquals(2.0, resources.getIoUsage(), 0.01); assertEquals(Integer.MAX_VALUE, resources.getLocalTestCount()); } @Test(expected = OptionsParsingException.class) public void testConverterThrowsWhenGivenInsufficientInputs() throws Exception { converter.convert("0,0,"); fail(); } @Test(expected = OptionsParsingException.class) public void testConverterThrowsWhenGivenTooManyInputs() throws Exception { converter.convert("0,0,0,"); fail(); } @Test(expected = OptionsParsingException.class) public void testConverterThrowsWhenGivenNegativeInputs() throws Exception { converter.convert("-1,0,0"); fail(); } }
apache-2.0
StripesFramework/stripes-stuff
src/main/java/org/stripesstuff/plugin/waitpage/WaitPage.java
5732
package org.stripesstuff.plugin.waitpage; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import net.sourceforge.stripes.action.ActionBeanContext; /** * Used to send user to a wait page when event handling takes a long time to complete. * <p> * Event will be invoked by a background request and the user will be redirected to a wait page. * </p> * <p> * The wait page must refresh itself to allow the resolution returned by event to be executed. * To refresh wait page, it can contain a <code>&lt;meta http-equiv="refresh" content="0"/&gt;</code> tag or it can use an AJAX * updater to know when to refresh page. * </p> * <p> * The expected flow when using a simple wait page is: * </p> * <ol> * <li> * ActionBeanResolution, HandlerResolution, BindingAndValidation, CustomValidation are executed the same way as if event didn't * contain a WaitPage annotation. * </li> * <li> * A resolution is returned to wait for event to complete. * </li> * <li> * If event completes before delay, resolution returned by event is executed. Flow ends immediately. * </li> * <li> * If delay expired and event didn't complete, wait page is returned. * </li> * <li> * Wait page is refreshed until event completes. * </li> * <li> * Event resolution is executed. * </li> * </ol> * <p> * If an AJAX updater is used, your page must have a way to known when to refresh itself. It can * be done by putting an indicator in your action bean that will be flagged once event completes.<br> * Examples :<br> * <code> * public Resolution myEvent {<br> * Do stuff...<br> * completeIndicator = true;<br> * }<br> * </code> * Then your AJAX page must inform the AJAX updater to refresh wait page.<br> * The expected flow when using an AJAX updater is: * </p> * <ol> * <li> * ActionBeanResolution, HandlerResolution, BindingAndValidation, CustomValidation are executed the same as if event didn't * contain a WaitPage annotation. * </li> * <li> * A resolution is returned to wait for delay. * </li> * <li> * If event completes before delay, resolution returned by event is executed. Flow ends immediately. * </li> * <li> * If delay expired and event didn't complete, wait page is returned. * </li> * <li> * AJAX updater in wait page will now make requests to the same URL as wait page would do for refresh, but a non-empty parameter * named "ajax" must be added to request. * </li> * <li> * Once indicator is flagged, AJAX updater must refresh wait page. * </li> * <li> * Event resolution is executed. * </li> * </ol> * <p> * How validation errors are handled: * </p> * <ul> * <li> * If a validation error occurs during any stages preceding event EventHandling, WaitPage annotation will have no effects. * </li> * <li> * If a validation error occurs during EventHandling, event resolution is execute and errors are available in * {@link ActionBeanContext#getValidationErrors()} and Stripes's errors tag can be used normally. * Event can return {@link ActionBeanContext#getSourcePageResolution()}. * </li> * </ul> * <p> * In case the event throws an exception, you can specify an error page that the user will be forwarded to. If no error page is * specified, the exception will be handled by stripes (or any exception handler registered by stripes).<br> * Note that if event throws an exception and no error page is specified, the exception will be handled twice by stripes: * once for the event invocation in background and once again when wait page refreshes. * </p> * <p> * It is recommended to use session instead of request to store attributes when using WaitPage.<br> * The request present in action bean during event execution is <strong>NOT</strong> the same request as the one in preceding lifecycle stages. * So all headers and parameters set before event handling will <strong>NOT</strong> be available in event.<br> * <strong> * Request attributes set before EventHandling stage will not be available in event.<br> * </strong> * <strong> * Request headers and parameters will not be available in resolution.<br> * </strong> * <strong> * Request attributes set before resolution stage will not be available in resolution.<br> * </strong> * <strong> * Form tags values must be coming from action bean since no request parameter will be available. * </strong> * </p> * * @author Aaron Porter * @author Christian Poitras */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) @Documented public @interface WaitPage { /** * Wait page location. * * @return wait page location */ String path(); /** * Delay in milliseconds allowed for event to complete before sending user to wait page.<br> * If event completes before delay is expired, the resolution returned by event will be executed directly and wait page * will never be shown. * * @return delay in milliseconds allowed for event to complete before sending user to wait page */ int delay() default 0; /** * Time between each wait page refresh in milliseconds. * * @return time between each wait page refresh in milliseconds */ int refresh() default 0; /** * Forward user to this page if event throws an exception. * * @return forward user to this page if event throws an exception */ String error() default ""; /** * Page location for AJAX updater (usually used to display progression). * * @return page location for AJAX updater */ String ajax() default ""; }
apache-2.0
ardito-jp/sastruts-extension
sastruts-extension/src/main/java/jp/ardito/seasar/struts/creator/package-info.java
715
/* * Copyright 2009-2014 Ardito Co.,Ltd. and the Others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the License. */ /** * @author Yohji Nihonyanagi */ package jp.ardito.seasar.struts.creator;
apache-2.0
AdaptiveMe/adaptive-arp-api
adaptive-arp-api-specs/src/main/java/me/adaptive/arp/api/IGlobalization.java
3006
/* * =| ADAPTIVE RUNTIME PLATFORM |======================================================================================= * * (C) Copyright 2013-2014 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. * * 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. * * Original author: * * * Carlos Lozano Diez * <http://github.com/carloslozano> * <http://twitter.com/adaptivecoder> * <mailto:carlos@adaptive.me> * * Contributors: * * * Ferran Vila Conesa * <http://github.com/fnva> * <http://twitter.com/ferran_vila> * <mailto:ferran.vila.conesa@gmail.com> * * * Aryslan * <http://github.com/Aryslan> * <http://twitter.com/Aryslan> * <mailto:ddbc@gft.com> * * * Francisco Javier Martin Bueno * <https://github.com/kechis> * <mailto:kechis@gmail.com> * * ===================================================================================================================== */ package me.adaptive.arp.api; /** * Interface for Managing the Globalization results * * @author Francisco Javier Martin Bueno * @since v2.0 */ public interface IGlobalization extends IBaseApplication { /** * Returns the default locale of the application defined in the configuration file * * @return Default Locale of the application * @since v2.0 */ Locale getDefaultLocale(); /** * List of supported locales for the application defined in the configuration file * * @return List of locales * @since v2.0 */ Locale[] getLocaleSupportedDescriptors(); /** * Gets the text/message corresponding to the given key and locale. * * @param key to match text * @param locale The locale object to get localized message, or the locale desciptor ("language" or "language-country" two-letters ISO codes. * @return Localized text. * @since v2.0 */ String getResourceLiteral(String key, Locale locale); /** * Gets the full application configured literals (key/message pairs) corresponding to the given locale. * * @param locale The locale object to get localized message, or the locale desciptor ("language" or "language-country" two-letters ISO codes. * @return Localized texts in the form of an object. * @since v2.0 */ KeyPair[] getResourceLiterals(Locale locale); }
apache-2.0
ctripcorp/dal
dal-client/src/test/java/com/ctrip/platform/dal/dao/unitbase/BaseTestStub.java
3851
package com.ctrip.platform.dal.dao.unitbase; import com.ctrip.platform.dal.common.enums.DatabaseCategory; import com.ctrip.platform.dal.dao.DalClient; import com.ctrip.platform.dal.dao.DalClientFactory; import com.ctrip.platform.dal.dao.DalTableDao; import com.ctrip.platform.dal.dao.unittests.DalTestHelper; import org.junit.Assert; import java.sql.SQLException; public class BaseTestStub { public static class DatabaseDifference { /** * This for very strange issue about difference of sql server and oracle * String callSql = diff.category == DatabaseCategory.SqlServer ? "{call " + SP_D_NAME + "(?,?)}": "call " + SP_D_NAME + "(?,?)"; */ public DatabaseCategory category; public boolean validateBatchUpdateCount; public boolean validateBatchInsertCount; public boolean validateReturnCount; public boolean supportGetGeneratedKeys; public boolean supportMixOfHardCodeValueAndPlaceholder; public boolean supportInsertValues; public boolean supportSpIntermediateResult; public boolean supportBatchSpWithOutParameter; } public final static String TABLE_NAME = "dal_client_test"; public final static String SP_WITHOUT_OUT_PARAM = "SP_WITHOUT_OUT_PARAM"; public final static String SP_WITH_OUT_PARAM = "SP_WITH_OUT_PARAM"; public final static String SP_WITH_IN_OUT_PARAM = "SP_WITH_IN_OUT_PARAM"; public final static String SP_WITH_INTERMEDIATE_RESULT = "SP_WITH_INTERMEDIATE_RESULT"; public String dbName; public DatabaseDifference diff; public DalClient client = null; public ClientTestDalRowMapper mapper = null; public DalTableDao<ClientTestModel> dao = null; public BaseTestStub( String dbName, DatabaseDifference diff) { this.dbName = dbName; this.diff = diff; try { client = DalClientFactory.getClient(dbName); mapper = new ClientTestDalRowMapper(); dao = new DalTableDao<ClientTestModel>(new ClientTestDalParser(dbName)); } catch (Exception e) { e.printStackTrace(); } } public void assertEquals(int expected, int res, int expAll) throws SQLException { if(diff.validateReturnCount) { Assert.assertEquals(expected, res); }else{ Assert.assertEquals(expAll, DalTestHelper.getCount(dao)); } } public void assertEquals(int expected, int res, int expAll, String countWhere) throws SQLException { if(diff.validateReturnCount) { Assert.assertEquals(expected, res); }else Assert.assertEquals(expAll, DalTestHelper.getCount(dao, countWhere)); } public void assertEquals(int[] expected, int[] res, int expAll) throws SQLException { if(diff.validateReturnCount) { Assert.assertArrayEquals(expected, res); }else Assert.assertEquals(expAll, DalTestHelper.getCount(dao)); } public void assertEquals(int[] expected, int[] res, int exp, String countWhere) throws SQLException { if(diff.validateReturnCount) Assert.assertArrayEquals(expected, res); else Assert.assertEquals(exp, DalTestHelper.getCount(dao, countWhere)); } public void assertEqualsBatch(int[] expected, int[] res, int expAll) throws SQLException { if(diff.validateBatchUpdateCount) { Assert.assertArrayEquals(expected, res); }else Assert.assertEquals(expAll, DalTestHelper.getCount(dao)); } public void assertEqualsBatch(int[] expected, int[] res, int expAll, String countWhere) throws SQLException { if(diff.validateBatchUpdateCount) { Assert.assertArrayEquals(expected, res); }else Assert.assertEquals(expAll, DalTestHelper.getCount(dao, countWhere)); } public void assertEqualsBatchInsert(int[] expected, int[] res, int expAll) throws SQLException { if(diff.validateBatchInsertCount) { Assert.assertArrayEquals(expected, res); }else Assert.assertEquals(expAll, DalTestHelper.getCount(dao)); } }
apache-2.0
mwjmurphy/Axel-Framework
axel-action/src/main/java/org/xmlactions/action/NestedActionException.java
1018
package org.xmlactions.action; @SuppressWarnings("serial") public class NestedActionException extends Exception { /** * Constructs a new exception with null as its detail message. */ public NestedActionException() { super(); } /** * Constructs a new exception with the specified detail message. * * @param message */ public NestedActionException(String message) { super(message); } /** * Constructs a new exception with the specified detail message and cause. * * @param message * @param cause */ public NestedActionException(String message, Throwable cause) { super(message, cause); } /** * Constructs a new exception with the specified cause and a detail message * of (cause==null ? null : cause.toString()) (which typically contains the * class and detail message of cause). * * @param cause */ public NestedActionException(Throwable cause) { super(cause); } }
apache-2.0
ChinaFir/BKLockGuard
app/src/main/java/com/zhoujianbin/bklockguard/bean/SelectedBean.java
613
package com.zhoujianbin.bklockguard.bean; /******************************************************************************* * Copyright © 2014-2017 zhoujianbin All Rights Reserved. * Project Name:BKLockGuard * File Creation Time:2017/07/12 02:35:54 * Class Description: 单选基类 * Comment: 单选基类 ******************************************************************************/ public class SelectedBean { private boolean isSelected; public boolean isSelected() { return isSelected; } public void setSelected(boolean selected) { isSelected = selected; } }
apache-2.0
dernasherbrezon/jradio
src/main/java/ru/r2cloud/jradio/smogp/PcuDep.java
1986
package ru.r2cloud.jradio.smogp; import java.io.IOException; import ru.r2cloud.jradio.util.LittleEndianDataInputStream; public class PcuDep { private long timestamp; private int deploymentSwitch; private boolean removeBeforeFlight; private boolean pcuDeployment; private boolean antennaDeployment; private int pcuBootCounter; private int pcuUptimeMinutes; public PcuDep() { // do nothing } public PcuDep(LittleEndianDataInputStream dis) throws IOException { timestamp = dis.readUnsignedInt(); int b = dis.readUnsignedByte(); deploymentSwitch = (b >> 6) & 0b11; removeBeforeFlight = ((b >> 5) & 0x1) > 0; pcuDeployment = ((b >> 3) & 0x1) > 0; antennaDeployment = ((b >> 2) & 0x1) > 0; pcuBootCounter = dis.readUnsignedShort(); pcuUptimeMinutes = dis.readUnsignedShort(); } public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } public int getDeploymentSwitch() { return deploymentSwitch; } public void setDeploymentSwitch(int deploymentSwitch) { this.deploymentSwitch = deploymentSwitch; } public boolean isRemoveBeforeFlight() { return removeBeforeFlight; } public void setRemoveBeforeFlight(boolean removeBeforeFlight) { this.removeBeforeFlight = removeBeforeFlight; } public boolean isPcuDeployment() { return pcuDeployment; } public void setPcuDeployment(boolean pcuDeployment) { this.pcuDeployment = pcuDeployment; } public boolean isAntennaDeployment() { return antennaDeployment; } public void setAntennaDeployment(boolean antennaDeployment) { this.antennaDeployment = antennaDeployment; } public int getPcuBootCounter() { return pcuBootCounter; } public void setPcuBootCounter(int pcuBootCounter) { this.pcuBootCounter = pcuBootCounter; } public int getPcuUptimeMinutes() { return pcuUptimeMinutes; } public void setPcuUptimeMinutes(int pcuUptimeMinutes) { this.pcuUptimeMinutes = pcuUptimeMinutes; } }
apache-2.0
tufangorel/hazelcast
hazelcast/src/test/java/com/hazelcast/internal/util/comparators/AbstractValueComparatorTest.java
4459
/* * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.internal.util.comparators; import com.hazelcast.core.PartitioningStrategy; import com.hazelcast.internal.serialization.InternalSerializationService; import com.hazelcast.internal.serialization.impl.DefaultSerializationServiceBuilder; import com.hazelcast.internal.serialization.impl.HeapData; import com.hazelcast.map.impl.record.Person; import com.hazelcast.nio.serialization.Data; import com.hazelcast.partition.strategy.DefaultPartitioningStrategy; import com.hazelcast.spi.serialization.SerializationService; import com.hazelcast.test.HazelcastTestSupport; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @SuppressWarnings("WeakerAccess") public abstract class AbstractValueComparatorTest extends HazelcastTestSupport { SerializationService serializationService; PartitioningStrategy partitioningStrategy; ValueComparator comparator; Person object1; Person object2; Data data1; Data data2; Data nullData; @Before public final void init() { serializationService = createSerializationService(); partitioningStrategy = new DefaultPartitioningStrategy(); object1 = new Person("Alice"); object2 = new Person("Bob"); data1 = serializationService.toData(object1); data2 = serializationService.toData(object2); nullData = new HeapData(new byte[0]); } @Test public void testIsEqual() { newRecordComparator(); assertTrue(comparator.isEqual(null, null, serializationService)); assertTrue(comparator.isEqual(object1, object1, serializationService)); assertTrue(comparator.isEqual(object1, data1, serializationService)); assertTrue(comparator.isEqual(data1, data1, serializationService)); assertTrue(comparator.isEqual(data1, object1, serializationService)); assertTrue(comparator.isEqual(nullData, nullData, serializationService)); assertFalse(comparator.isEqual(null, object1, serializationService)); assertFalse(comparator.isEqual(null, data1, serializationService)); assertFalse(comparator.isEqual(null, nullData, serializationService)); assertFalse(comparator.isEqual(object1, null, serializationService)); assertFalse(comparator.isEqual(object1, nullData, serializationService)); assertFalse(comparator.isEqual(object1, object2, serializationService)); assertFalse(comparator.isEqual(object1, data2, serializationService)); assertFalse(comparator.isEqual(data1, null, serializationService)); assertFalse(comparator.isEqual(data1, nullData, serializationService)); assertFalse(comparator.isEqual(data1, object2, serializationService)); assertFalse(comparator.isEqual(data1, data2, serializationService)); assertFalse(comparator.isEqual(nullData, null, serializationService)); assertFalse(comparator.isEqual(nullData, object1, serializationService)); assertFalse(comparator.isEqual(nullData, data1, serializationService)); } @Test public void testIsEqual_withCustomPartitioningStrategy() { partitioningStrategy = new PersonPartitioningStrategy(); data1 = serializationService.toData(object1, partitioningStrategy); data2 = serializationService.toData(object2, partitioningStrategy); testIsEqual(); } abstract void newRecordComparator(); InternalSerializationService createSerializationService() { return new DefaultSerializationServiceBuilder().build(); } static class PersonPartitioningStrategy implements PartitioningStrategy<Person> { @Override public Object getPartitionKey(Person key) { return key.getName(); } } }
apache-2.0
TomaszMolenda/mediciline-android
app/src/main/java/local/tomo/medi/activity/drug/DrugActivity.java
3814
package local.tomo.medi.activity.drug; import android.content.Intent; import android.os.Bundle; import android.widget.Button; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import org.joda.time.LocalDate; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import local.tomo.medi.R; import local.tomo.medi.activity.DatabaseAccessActivity; import local.tomo.medi.activity.drug.add.SearchDrugActivity; import local.tomo.medi.activity.drug.list.ArchiveUserDrugActivity; import local.tomo.medi.activity.drug.list.OverdueUserDrugActivity; import local.tomo.medi.activity.drug.list.UserDrugActivity; import local.tomo.medi.activity.drug.scan.ScanActivity; import local.tomo.medi.ormlite.DatabaseDataCreator; public class DrugActivity extends DatabaseAccessActivity { @BindView(R.id.buttonScan) Button buttonScan; @BindView(R.id.buttonAdd) Button buttonAdd; @BindView(R.id.buttonActive) Button buttonActive; @BindView(R.id.buttonArchive) Button buttonArchive; @BindView(R.id.buttonAll) Button buttonAll; @BindView(R.id.buttonOverdue) Button buttonOverdue; @BindView(R.id.textActive) TextView textViewActive; @BindView(R.id.textArchive) TextView textViewArchive; @BindView(R.id.textOverdue) TextView textViewOverdue; @BindView(R.id.relativeLayoutOverdue) RelativeLayout relativeLayoutOverdue; OverdueAnimation overdueAnimation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_drugs); ButterKnife.bind(this); DatabaseDataCreator databaseDataCreator = new DatabaseDataCreator(getResources(), getApplicationContext()); databaseDataCreator.execute(); overdueAnimation = new OverdueAnimation(DrugActivity.this, relativeLayoutOverdue); if (getHelper().getUserDrugQuery().isAnyDrugOverdue(LocalDate.now())) { overdueAnimation.start(); } } @OnClick(R.id.buttonAdd) void add() { buttonAdd.setEnabled(false); Intent intent = new Intent(this, SearchDrugActivity.class); this.startActivity(intent); } @OnClick(R.id.buttonScan) void scan() { buttonScan.setEnabled(false); Intent intent = new Intent(this, ScanActivity.class); this.startActivity(intent); } @OnClick(R.id.buttonActive) void listActive() { buttonActive.setEnabled(false); Intent intent = new Intent(this, UserDrugActivity.class); this.startActivity(intent); } @OnClick(R.id.buttonArchive) void listArchive() { buttonArchive.setEnabled(false); Intent intent = new Intent(this, ArchiveUserDrugActivity.class); this.startActivity(intent); } @OnClick(R.id.buttonOverdue) void listOverdue() { buttonArchive.setEnabled(false); Intent intent = new Intent(this, OverdueUserDrugActivity.class); this.startActivity(intent); } @OnClick(R.id.buttonAll) void listAll() { buttonAll.setEnabled(false); runOnUiThread(() -> Toast.makeText(DrugActivity.this, getString(R.string.available_soon), Toast.LENGTH_SHORT).show()); } @Override public void onResume() { super.onResume(); buttonScan.setEnabled(true); buttonAdd.setEnabled(true); buttonActive.setEnabled(true); buttonAll.setEnabled(true); buttonArchive.setEnabled(true); buttonOverdue.setEnabled(true); if (getHelper().getUserDrugQuery().isAnyDrugOverdue(LocalDate.now())) { overdueAnimation.start(); } else { overdueAnimation.stop(); } } }
apache-2.0
5agado/unitn
android_projects/MyBooksAndMovies/src/edu/unitn/pbam/androidproject/model/Category.java
620
package edu.unitn.pbam.androidproject.model; import java.io.Serializable; public class Category extends Model implements Serializable { private String name; private String description; private Type type; public static enum Type { BOOK, MOVIE, BOTH } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Type getType() { return type; } public void setType(Type type) { this.type = type; }; }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-kafka/src/main/java/com/amazonaws/services/kafka/model/transform/ClusterOperationStepInfoJsonUnmarshaller.java
2844
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.kafka.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.kafka.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * ClusterOperationStepInfo JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ClusterOperationStepInfoJsonUnmarshaller implements Unmarshaller<ClusterOperationStepInfo, JsonUnmarshallerContext> { public ClusterOperationStepInfo unmarshall(JsonUnmarshallerContext context) throws Exception { ClusterOperationStepInfo clusterOperationStepInfo = new ClusterOperationStepInfo(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("stepStatus", targetDepth)) { context.nextToken(); clusterOperationStepInfo.setStepStatus(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return clusterOperationStepInfo; } private static ClusterOperationStepInfoJsonUnmarshaller instance; public static ClusterOperationStepInfoJsonUnmarshaller getInstance() { if (instance == null) instance = new ClusterOperationStepInfoJsonUnmarshaller(); return instance; } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-devicefarm/src/main/java/com/amazonaws/services/devicefarm/AWSDeviceFarm.java
71638
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.devicefarm; import javax.annotation.Generated; import com.amazonaws.*; import com.amazonaws.regions.*; import com.amazonaws.services.devicefarm.model.*; /** * Interface for accessing AWS Device Farm. * <p> * <b>Note:</b> Do not directly implement this interface, new methods are added to it regularly. Extend from * {@link com.amazonaws.services.devicefarm.AbstractAWSDeviceFarm} instead. * </p> * <p> * <p> * AWS Device Farm is a service that enables mobile app developers to test Android, iOS, and Fire OS apps on physical * phones, tablets, and other devices in the cloud. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public interface AWSDeviceFarm { /** * The region metadata service name for computing region endpoints. You can use this value to retrieve metadata * (such as supported regions) of the service. * * @see RegionUtils#getRegionsForService(String) */ String ENDPOINT_PREFIX = "devicefarm"; /** * Overrides the default endpoint for this client ("https://devicefarm.us-west-2.amazonaws.com"). Callers can use * this method to control which AWS region they want to work with. * <p> * Callers can pass in just the endpoint (ex: "devicefarm.us-west-2.amazonaws.com") or a full URL, including the * protocol (ex: "https://devicefarm.us-west-2.amazonaws.com"). If the protocol is not specified here, the default * protocol from this client's {@link ClientConfiguration} will be used, which by default is HTTPS. * <p> * For more information on using AWS regions with the AWS SDK for Java, and a complete list of all available * endpoints for all AWS services, see: <a href= * "https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/java-dg-region-selection.html#region-selection-choose-endpoint" * > https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/java-dg-region-selection.html#region-selection- * choose-endpoint</a> * <p> * <b>This method is not threadsafe. An endpoint should be configured when the client is created and before any * service requests are made. Changing it afterwards creates inevitable race conditions for any service requests in * transit or retrying.</b> * * @param endpoint * The endpoint (ex: "devicefarm.us-west-2.amazonaws.com") or a full URL, including the protocol (ex: * "https://devicefarm.us-west-2.amazonaws.com") of the region specific AWS endpoint this client will * communicate with. * @deprecated use {@link AwsClientBuilder#setEndpointConfiguration(AwsClientBuilder.EndpointConfiguration)} for * example: * {@code builder.setEndpointConfiguration(new EndpointConfiguration(endpoint, signingRegion));} */ @Deprecated void setEndpoint(String endpoint); /** * An alternative to {@link AWSDeviceFarm#setEndpoint(String)}, sets the regional endpoint for this client's service * calls. Callers can use this method to control which AWS region they want to work with. * <p> * By default, all service endpoints in all regions use the https protocol. To use http instead, specify it in the * {@link ClientConfiguration} supplied at construction. * <p> * <b>This method is not threadsafe. A region should be configured when the client is created and before any service * requests are made. Changing it afterwards creates inevitable race conditions for any service requests in transit * or retrying.</b> * * @param region * The region this client will communicate with. See {@link Region#getRegion(com.amazonaws.regions.Regions)} * for accessing a given region. Must not be null and must be a region where the service is available. * * @see Region#getRegion(com.amazonaws.regions.Regions) * @see Region#createClient(Class, com.amazonaws.auth.AWSCredentialsProvider, ClientConfiguration) * @see Region#isServiceSupported(String) * @deprecated use {@link AwsClientBuilder#setRegion(String)} */ @Deprecated void setRegion(Region region); /** * <p> * Creates a device pool. * </p> * * @param createDevicePoolRequest * Represents a request to the create device pool operation. * @return Result of the CreateDevicePool operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.CreateDevicePool * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateDevicePool" target="_top">AWS * API Documentation</a> */ CreateDevicePoolResult createDevicePool(CreateDevicePoolRequest createDevicePoolRequest); /** * <p> * Creates a profile that can be applied to one or more private fleet device instances. * </p> * * @param createInstanceProfileRequest * @return Result of the CreateInstanceProfile operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.CreateInstanceProfile * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateInstanceProfile" * target="_top">AWS API Documentation</a> */ CreateInstanceProfileResult createInstanceProfile(CreateInstanceProfileRequest createInstanceProfileRequest); /** * <p> * Creates a network profile. * </p> * * @param createNetworkProfileRequest * @return Result of the CreateNetworkProfile operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.CreateNetworkProfile * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateNetworkProfile" * target="_top">AWS API Documentation</a> */ CreateNetworkProfileResult createNetworkProfile(CreateNetworkProfileRequest createNetworkProfileRequest); /** * <p> * Creates a new project. * </p> * * @param createProjectRequest * Represents a request to the create project operation. * @return Result of the CreateProject operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @throws TagOperationException * The operation was not successful. Try again. * @sample AWSDeviceFarm.CreateProject * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateProject" target="_top">AWS API * Documentation</a> */ CreateProjectResult createProject(CreateProjectRequest createProjectRequest); /** * <p> * Specifies and starts a remote access session. * </p> * * @param createRemoteAccessSessionRequest * Creates and submits a request to start a remote access session. * @return Result of the CreateRemoteAccessSession operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.CreateRemoteAccessSession * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateRemoteAccessSession" * target="_top">AWS API Documentation</a> */ CreateRemoteAccessSessionResult createRemoteAccessSession(CreateRemoteAccessSessionRequest createRemoteAccessSessionRequest); /** * <p> * Uploads an app or test scripts. * </p> * * @param createUploadRequest * Represents a request to the create upload operation. * @return Result of the CreateUpload operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.CreateUpload * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateUpload" target="_top">AWS API * Documentation</a> */ CreateUploadResult createUpload(CreateUploadRequest createUploadRequest); /** * <p> * Creates a configuration record in Device Farm for your Amazon Virtual Private Cloud (VPC) endpoint. * </p> * * @param createVPCEConfigurationRequest * @return Result of the CreateVPCEConfiguration operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.CreateVPCEConfiguration * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateVPCEConfiguration" * target="_top">AWS API Documentation</a> */ CreateVPCEConfigurationResult createVPCEConfiguration(CreateVPCEConfigurationRequest createVPCEConfigurationRequest); /** * <p> * Deletes a device pool given the pool ARN. Does not allow deletion of curated pools owned by the system. * </p> * * @param deleteDevicePoolRequest * Represents a request to the delete device pool operation. * @return Result of the DeleteDevicePool operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.DeleteDevicePool * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteDevicePool" target="_top">AWS * API Documentation</a> */ DeleteDevicePoolResult deleteDevicePool(DeleteDevicePoolRequest deleteDevicePoolRequest); /** * <p> * Deletes a profile that can be applied to one or more private device instances. * </p> * * @param deleteInstanceProfileRequest * @return Result of the DeleteInstanceProfile operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.DeleteInstanceProfile * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteInstanceProfile" * target="_top">AWS API Documentation</a> */ DeleteInstanceProfileResult deleteInstanceProfile(DeleteInstanceProfileRequest deleteInstanceProfileRequest); /** * <p> * Deletes a network profile. * </p> * * @param deleteNetworkProfileRequest * @return Result of the DeleteNetworkProfile operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.DeleteNetworkProfile * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteNetworkProfile" * target="_top">AWS API Documentation</a> */ DeleteNetworkProfileResult deleteNetworkProfile(DeleteNetworkProfileRequest deleteNetworkProfileRequest); /** * <p> * Deletes an AWS Device Farm project, given the project ARN. * </p> * <p> * <b>Note</b> Deleting this resource does not stop an in-progress run. * </p> * * @param deleteProjectRequest * Represents a request to the delete project operation. * @return Result of the DeleteProject operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.DeleteProject * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteProject" target="_top">AWS API * Documentation</a> */ DeleteProjectResult deleteProject(DeleteProjectRequest deleteProjectRequest); /** * <p> * Deletes a completed remote access session and its results. * </p> * * @param deleteRemoteAccessSessionRequest * Represents the request to delete the specified remote access session. * @return Result of the DeleteRemoteAccessSession operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.DeleteRemoteAccessSession * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteRemoteAccessSession" * target="_top">AWS API Documentation</a> */ DeleteRemoteAccessSessionResult deleteRemoteAccessSession(DeleteRemoteAccessSessionRequest deleteRemoteAccessSessionRequest); /** * <p> * Deletes the run, given the run ARN. * </p> * <p> * <b>Note</b> Deleting this resource does not stop an in-progress run. * </p> * * @param deleteRunRequest * Represents a request to the delete run operation. * @return Result of the DeleteRun operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.DeleteRun * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteRun" target="_top">AWS API * Documentation</a> */ DeleteRunResult deleteRun(DeleteRunRequest deleteRunRequest); /** * <p> * Deletes an upload given the upload ARN. * </p> * * @param deleteUploadRequest * Represents a request to the delete upload operation. * @return Result of the DeleteUpload operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.DeleteUpload * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteUpload" target="_top">AWS API * Documentation</a> */ DeleteUploadResult deleteUpload(DeleteUploadRequest deleteUploadRequest); /** * <p> * Deletes a configuration for your Amazon Virtual Private Cloud (VPC) endpoint. * </p> * * @param deleteVPCEConfigurationRequest * @return Result of the DeleteVPCEConfiguration operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws ServiceAccountException * There was a problem with the service account. * @throws InvalidOperationException * There was an error with the update request, or you do not have sufficient permissions to update this VPC * endpoint configuration. * @sample AWSDeviceFarm.DeleteVPCEConfiguration * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteVPCEConfiguration" * target="_top">AWS API Documentation</a> */ DeleteVPCEConfigurationResult deleteVPCEConfiguration(DeleteVPCEConfigurationRequest deleteVPCEConfigurationRequest); /** * <p> * Returns the number of unmetered iOS and/or unmetered Android devices that have been purchased by the account. * </p> * * @param getAccountSettingsRequest * Represents the request sent to retrieve the account settings. * @return Result of the GetAccountSettings operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.GetAccountSettings * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetAccountSettings" target="_top">AWS * API Documentation</a> */ GetAccountSettingsResult getAccountSettings(GetAccountSettingsRequest getAccountSettingsRequest); /** * <p> * Gets information about a unique device type. * </p> * * @param getDeviceRequest * Represents a request to the get device request. * @return Result of the GetDevice operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.GetDevice * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetDevice" target="_top">AWS API * Documentation</a> */ GetDeviceResult getDevice(GetDeviceRequest getDeviceRequest); /** * <p> * Returns information about a device instance belonging to a private device fleet. * </p> * * @param getDeviceInstanceRequest * @return Result of the GetDeviceInstance operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.GetDeviceInstance * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetDeviceInstance" target="_top">AWS * API Documentation</a> */ GetDeviceInstanceResult getDeviceInstance(GetDeviceInstanceRequest getDeviceInstanceRequest); /** * <p> * Gets information about a device pool. * </p> * * @param getDevicePoolRequest * Represents a request to the get device pool operation. * @return Result of the GetDevicePool operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.GetDevicePool * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetDevicePool" target="_top">AWS API * Documentation</a> */ GetDevicePoolResult getDevicePool(GetDevicePoolRequest getDevicePoolRequest); /** * <p> * Gets information about compatibility with a device pool. * </p> * * @param getDevicePoolCompatibilityRequest * Represents a request to the get device pool compatibility operation. * @return Result of the GetDevicePoolCompatibility operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.GetDevicePoolCompatibility * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetDevicePoolCompatibility" * target="_top">AWS API Documentation</a> */ GetDevicePoolCompatibilityResult getDevicePoolCompatibility(GetDevicePoolCompatibilityRequest getDevicePoolCompatibilityRequest); /** * <p> * Returns information about the specified instance profile. * </p> * * @param getInstanceProfileRequest * @return Result of the GetInstanceProfile operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.GetInstanceProfile * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetInstanceProfile" target="_top">AWS * API Documentation</a> */ GetInstanceProfileResult getInstanceProfile(GetInstanceProfileRequest getInstanceProfileRequest); /** * <p> * Gets information about a job. * </p> * * @param getJobRequest * Represents a request to the get job operation. * @return Result of the GetJob operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.GetJob * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetJob" target="_top">AWS API * Documentation</a> */ GetJobResult getJob(GetJobRequest getJobRequest); /** * <p> * Returns information about a network profile. * </p> * * @param getNetworkProfileRequest * @return Result of the GetNetworkProfile operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.GetNetworkProfile * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetNetworkProfile" target="_top">AWS * API Documentation</a> */ GetNetworkProfileResult getNetworkProfile(GetNetworkProfileRequest getNetworkProfileRequest); /** * <p> * Gets the current status and future status of all offerings purchased by an AWS account. The response indicates * how many offerings are currently available and the offerings that will be available in the next period. The API * returns a <code>NotEligible</code> error if the user is not permitted to invoke the operation. Please contact <a * href="mailto:aws-devicefarm-support@amazon.com">aws-devicefarm-support@amazon.com</a> if you believe that you * should be able to invoke this operation. * </p> * * @param getOfferingStatusRequest * Represents the request to retrieve the offering status for the specified customer or account. * @return Result of the GetOfferingStatus operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws NotEligibleException * Exception gets thrown when a user is not eligible to perform the specified transaction. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.GetOfferingStatus * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetOfferingStatus" target="_top">AWS * API Documentation</a> */ GetOfferingStatusResult getOfferingStatus(GetOfferingStatusRequest getOfferingStatusRequest); /** * <p> * Gets information about a project. * </p> * * @param getProjectRequest * Represents a request to the get project operation. * @return Result of the GetProject operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.GetProject * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetProject" target="_top">AWS API * Documentation</a> */ GetProjectResult getProject(GetProjectRequest getProjectRequest); /** * <p> * Returns a link to a currently running remote access session. * </p> * * @param getRemoteAccessSessionRequest * Represents the request to get information about the specified remote access session. * @return Result of the GetRemoteAccessSession operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.GetRemoteAccessSession * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetRemoteAccessSession" * target="_top">AWS API Documentation</a> */ GetRemoteAccessSessionResult getRemoteAccessSession(GetRemoteAccessSessionRequest getRemoteAccessSessionRequest); /** * <p> * Gets information about a run. * </p> * * @param getRunRequest * Represents a request to the get run operation. * @return Result of the GetRun operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.GetRun * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetRun" target="_top">AWS API * Documentation</a> */ GetRunResult getRun(GetRunRequest getRunRequest); /** * <p> * Gets information about a suite. * </p> * * @param getSuiteRequest * Represents a request to the get suite operation. * @return Result of the GetSuite operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.GetSuite * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetSuite" target="_top">AWS API * Documentation</a> */ GetSuiteResult getSuite(GetSuiteRequest getSuiteRequest); /** * <p> * Gets information about a test. * </p> * * @param getTestRequest * Represents a request to the get test operation. * @return Result of the GetTest operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.GetTest * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetTest" target="_top">AWS API * Documentation</a> */ GetTestResult getTest(GetTestRequest getTestRequest); /** * <p> * Gets information about an upload. * </p> * * @param getUploadRequest * Represents a request to the get upload operation. * @return Result of the GetUpload operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.GetUpload * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetUpload" target="_top">AWS API * Documentation</a> */ GetUploadResult getUpload(GetUploadRequest getUploadRequest); /** * <p> * Returns information about the configuration settings for your Amazon Virtual Private Cloud (VPC) endpoint. * </p> * * @param getVPCEConfigurationRequest * @return Result of the GetVPCEConfiguration operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.GetVPCEConfiguration * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetVPCEConfiguration" * target="_top">AWS API Documentation</a> */ GetVPCEConfigurationResult getVPCEConfiguration(GetVPCEConfigurationRequest getVPCEConfigurationRequest); /** * <p> * Installs an application to the device in a remote access session. For Android applications, the file must be in * .apk format. For iOS applications, the file must be in .ipa format. * </p> * * @param installToRemoteAccessSessionRequest * Represents the request to install an Android application (in .apk format) or an iOS application (in .ipa * format) as part of a remote access session. * @return Result of the InstallToRemoteAccessSession operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.InstallToRemoteAccessSession * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/InstallToRemoteAccessSession" * target="_top">AWS API Documentation</a> */ InstallToRemoteAccessSessionResult installToRemoteAccessSession(InstallToRemoteAccessSessionRequest installToRemoteAccessSessionRequest); /** * <p> * Gets information about artifacts. * </p> * * @param listArtifactsRequest * Represents a request to the list artifacts operation. * @return Result of the ListArtifacts operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.ListArtifacts * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListArtifacts" target="_top">AWS API * Documentation</a> */ ListArtifactsResult listArtifacts(ListArtifactsRequest listArtifactsRequest); /** * <p> * Returns information about the private device instances associated with one or more AWS accounts. * </p> * * @param listDeviceInstancesRequest * @return Result of the ListDeviceInstances operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.ListDeviceInstances * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListDeviceInstances" target="_top">AWS * API Documentation</a> */ ListDeviceInstancesResult listDeviceInstances(ListDeviceInstancesRequest listDeviceInstancesRequest); /** * <p> * Gets information about device pools. * </p> * * @param listDevicePoolsRequest * Represents the result of a list device pools request. * @return Result of the ListDevicePools operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.ListDevicePools * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListDevicePools" target="_top">AWS API * Documentation</a> */ ListDevicePoolsResult listDevicePools(ListDevicePoolsRequest listDevicePoolsRequest); /** * <p> * Gets information about unique device types. * </p> * * @param listDevicesRequest * Represents the result of a list devices request. * @return Result of the ListDevices operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.ListDevices * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListDevices" target="_top">AWS API * Documentation</a> */ ListDevicesResult listDevices(ListDevicesRequest listDevicesRequest); /** * <p> * Returns information about all the instance profiles in an AWS account. * </p> * * @param listInstanceProfilesRequest * @return Result of the ListInstanceProfiles operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.ListInstanceProfiles * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListInstanceProfiles" * target="_top">AWS API Documentation</a> */ ListInstanceProfilesResult listInstanceProfiles(ListInstanceProfilesRequest listInstanceProfilesRequest); /** * <p> * Gets information about jobs for a given test run. * </p> * * @param listJobsRequest * Represents a request to the list jobs operation. * @return Result of the ListJobs operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.ListJobs * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListJobs" target="_top">AWS API * Documentation</a> */ ListJobsResult listJobs(ListJobsRequest listJobsRequest); /** * <p> * Returns the list of available network profiles. * </p> * * @param listNetworkProfilesRequest * @return Result of the ListNetworkProfiles operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.ListNetworkProfiles * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListNetworkProfiles" target="_top">AWS * API Documentation</a> */ ListNetworkProfilesResult listNetworkProfiles(ListNetworkProfilesRequest listNetworkProfilesRequest); /** * <p> * Returns a list of offering promotions. Each offering promotion record contains the ID and description of the * promotion. The API returns a <code>NotEligible</code> error if the caller is not permitted to invoke the * operation. Contact <a href="mailto:aws-devicefarm-support@amazon.com">aws-devicefarm-support@amazon.com</a> if * you believe that you should be able to invoke this operation. * </p> * * @param listOfferingPromotionsRequest * @return Result of the ListOfferingPromotions operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws NotEligibleException * Exception gets thrown when a user is not eligible to perform the specified transaction. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.ListOfferingPromotions * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListOfferingPromotions" * target="_top">AWS API Documentation</a> */ ListOfferingPromotionsResult listOfferingPromotions(ListOfferingPromotionsRequest listOfferingPromotionsRequest); /** * <p> * Returns a list of all historical purchases, renewals, and system renewal transactions for an AWS account. The * list is paginated and ordered by a descending timestamp (most recent transactions are first). The API returns a * <code>NotEligible</code> error if the user is not permitted to invoke the operation. Please contact <a * href="mailto:aws-devicefarm-support@amazon.com">aws-devicefarm-support@amazon.com</a> if you believe that you * should be able to invoke this operation. * </p> * * @param listOfferingTransactionsRequest * Represents the request to list the offering transaction history. * @return Result of the ListOfferingTransactions operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws NotEligibleException * Exception gets thrown when a user is not eligible to perform the specified transaction. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.ListOfferingTransactions * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListOfferingTransactions" * target="_top">AWS API Documentation</a> */ ListOfferingTransactionsResult listOfferingTransactions(ListOfferingTransactionsRequest listOfferingTransactionsRequest); /** * <p> * Returns a list of products or offerings that the user can manage through the API. Each offering record indicates * the recurring price per unit and the frequency for that offering. The API returns a <code>NotEligible</code> * error if the user is not permitted to invoke the operation. Please contact <a * href="mailto:aws-devicefarm-support@amazon.com">aws-devicefarm-support@amazon.com</a> if you believe that you * should be able to invoke this operation. * </p> * * @param listOfferingsRequest * Represents the request to list all offerings. * @return Result of the ListOfferings operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws NotEligibleException * Exception gets thrown when a user is not eligible to perform the specified transaction. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.ListOfferings * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListOfferings" target="_top">AWS API * Documentation</a> */ ListOfferingsResult listOfferings(ListOfferingsRequest listOfferingsRequest); /** * <p> * Gets information about projects. * </p> * * @param listProjectsRequest * Represents a request to the list projects operation. * @return Result of the ListProjects operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.ListProjects * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListProjects" target="_top">AWS API * Documentation</a> */ ListProjectsResult listProjects(ListProjectsRequest listProjectsRequest); /** * <p> * Returns a list of all currently running remote access sessions. * </p> * * @param listRemoteAccessSessionsRequest * Represents the request to return information about the remote access session. * @return Result of the ListRemoteAccessSessions operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.ListRemoteAccessSessions * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListRemoteAccessSessions" * target="_top">AWS API Documentation</a> */ ListRemoteAccessSessionsResult listRemoteAccessSessions(ListRemoteAccessSessionsRequest listRemoteAccessSessionsRequest); /** * <p> * Gets information about runs, given an AWS Device Farm project ARN. * </p> * * @param listRunsRequest * Represents a request to the list runs operation. * @return Result of the ListRuns operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.ListRuns * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListRuns" target="_top">AWS API * Documentation</a> */ ListRunsResult listRuns(ListRunsRequest listRunsRequest); /** * <p> * Gets information about samples, given an AWS Device Farm job ARN. * </p> * * @param listSamplesRequest * Represents a request to the list samples operation. * @return Result of the ListSamples operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.ListSamples * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListSamples" target="_top">AWS API * Documentation</a> */ ListSamplesResult listSamples(ListSamplesRequest listSamplesRequest); /** * <p> * Gets information about test suites for a given job. * </p> * * @param listSuitesRequest * Represents a request to the list suites operation. * @return Result of the ListSuites operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.ListSuites * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListSuites" target="_top">AWS API * Documentation</a> */ ListSuitesResult listSuites(ListSuitesRequest listSuitesRequest); /** * <p> * List the tags for an AWS Device Farm resource. * </p> * * @param listTagsForResourceRequest * @return Result of the ListTagsForResource operation returned by the service. * @throws NotFoundException * The specified entity was not found. * @throws TagOperationException * The operation was not successful. Try again. * @sample AWSDeviceFarm.ListTagsForResource * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListTagsForResource" target="_top">AWS * API Documentation</a> */ ListTagsForResourceResult listTagsForResource(ListTagsForResourceRequest listTagsForResourceRequest); /** * <p> * Gets information about tests in a given test suite. * </p> * * @param listTestsRequest * Represents a request to the list tests operation. * @return Result of the ListTests operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.ListTests * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListTests" target="_top">AWS API * Documentation</a> */ ListTestsResult listTests(ListTestsRequest listTestsRequest); /** * <p> * Gets information about unique problems. * </p> * * @param listUniqueProblemsRequest * Represents a request to the list unique problems operation. * @return Result of the ListUniqueProblems operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.ListUniqueProblems * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListUniqueProblems" target="_top">AWS * API Documentation</a> */ ListUniqueProblemsResult listUniqueProblems(ListUniqueProblemsRequest listUniqueProblemsRequest); /** * <p> * Gets information about uploads, given an AWS Device Farm project ARN. * </p> * * @param listUploadsRequest * Represents a request to the list uploads operation. * @return Result of the ListUploads operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.ListUploads * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListUploads" target="_top">AWS API * Documentation</a> */ ListUploadsResult listUploads(ListUploadsRequest listUploadsRequest); /** * <p> * Returns information about all Amazon Virtual Private Cloud (VPC) endpoint configurations in the AWS account. * </p> * * @param listVPCEConfigurationsRequest * @return Result of the ListVPCEConfigurations operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.ListVPCEConfigurations * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListVPCEConfigurations" * target="_top">AWS API Documentation</a> */ ListVPCEConfigurationsResult listVPCEConfigurations(ListVPCEConfigurationsRequest listVPCEConfigurationsRequest); /** * <p> * Immediately purchases offerings for an AWS account. Offerings renew with the latest total purchased quantity for * an offering, unless the renewal was overridden. The API returns a <code>NotEligible</code> error if the user is * not permitted to invoke the operation. Please contact <a * href="mailto:aws-devicefarm-support@amazon.com">aws-devicefarm-support@amazon.com</a> if you believe that you * should be able to invoke this operation. * </p> * * @param purchaseOfferingRequest * Represents a request for a purchase offering. * @return Result of the PurchaseOffering operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws NotEligibleException * Exception gets thrown when a user is not eligible to perform the specified transaction. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.PurchaseOffering * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/PurchaseOffering" target="_top">AWS * API Documentation</a> */ PurchaseOfferingResult purchaseOffering(PurchaseOfferingRequest purchaseOfferingRequest); /** * <p> * Explicitly sets the quantity of devices to renew for an offering, starting from the <code>effectiveDate</code> of * the next period. The API returns a <code>NotEligible</code> error if the user is not permitted to invoke the * operation. Please contact <a * href="mailto:aws-devicefarm-support@amazon.com">aws-devicefarm-support@amazon.com</a> if you believe that you * should be able to invoke this operation. * </p> * * @param renewOfferingRequest * A request representing an offering renewal. * @return Result of the RenewOffering operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws NotEligibleException * Exception gets thrown when a user is not eligible to perform the specified transaction. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.RenewOffering * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/RenewOffering" target="_top">AWS API * Documentation</a> */ RenewOfferingResult renewOffering(RenewOfferingRequest renewOfferingRequest); /** * <p> * Schedules a run. * </p> * * @param scheduleRunRequest * Represents a request to the schedule run operation. * @return Result of the ScheduleRun operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws IdempotencyException * An entity with the same name already exists. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.ScheduleRun * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ScheduleRun" target="_top">AWS API * Documentation</a> */ ScheduleRunResult scheduleRun(ScheduleRunRequest scheduleRunRequest); /** * <p> * Initiates a stop request for the current job. AWS Device Farm will immediately stop the job on the device where * tests have not started executing, and you will not be billed for this device. On the device where tests have * started executing, Setup Suite and Teardown Suite tests will run to completion before stopping execution on the * device. You will be billed for Setup, Teardown, and any tests that were in progress or already completed. * </p> * * @param stopJobRequest * @return Result of the StopJob operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.StopJob * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/StopJob" target="_top">AWS API * Documentation</a> */ StopJobResult stopJob(StopJobRequest stopJobRequest); /** * <p> * Ends a specified remote access session. * </p> * * @param stopRemoteAccessSessionRequest * Represents the request to stop the remote access session. * @return Result of the StopRemoteAccessSession operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.StopRemoteAccessSession * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/StopRemoteAccessSession" * target="_top">AWS API Documentation</a> */ StopRemoteAccessSessionResult stopRemoteAccessSession(StopRemoteAccessSessionRequest stopRemoteAccessSessionRequest); /** * <p> * Initiates a stop request for the current test run. AWS Device Farm will immediately stop the run on devices where * tests have not started executing, and you will not be billed for these devices. On devices where tests have * started executing, Setup Suite and Teardown Suite tests will run to completion before stopping execution on those * devices. You will be billed for Setup, Teardown, and any tests that were in progress or already completed. * </p> * * @param stopRunRequest * Represents the request to stop a specific run. * @return Result of the StopRun operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.StopRun * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/StopRun" target="_top">AWS API * Documentation</a> */ StopRunResult stopRun(StopRunRequest stopRunRequest); /** * <p> * Associates the specified tags to a resource with the specified <code>resourceArn</code>. If existing tags on a * resource are not specified in the request parameters, they are not changed. When a resource is deleted, the tags * associated with that resource are deleted as well. * </p> * * @param tagResourceRequest * @return Result of the TagResource operation returned by the service. * @throws NotFoundException * The specified entity was not found. * @throws TagOperationException * The operation was not successful. Try again. * @throws TooManyTagsException * The list of tags on the repository is over the limit. The maximum number of tags that can be applied to a * repository is 50. * @throws TagPolicyException * The request doesn't comply with the AWS Identity and Access Management (IAM) tag policy. Correct your * request and then retry it. * @sample AWSDeviceFarm.TagResource * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/TagResource" target="_top">AWS API * Documentation</a> */ TagResourceResult tagResource(TagResourceRequest tagResourceRequest); /** * <p> * Deletes the specified tags from a resource. * </p> * * @param untagResourceRequest * @return Result of the UntagResource operation returned by the service. * @throws NotFoundException * The specified entity was not found. * @throws TagOperationException * The operation was not successful. Try again. * @sample AWSDeviceFarm.UntagResource * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/UntagResource" target="_top">AWS API * Documentation</a> */ UntagResourceResult untagResource(UntagResourceRequest untagResourceRequest); /** * <p> * Updates information about an existing private device instance. * </p> * * @param updateDeviceInstanceRequest * @return Result of the UpdateDeviceInstance operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.UpdateDeviceInstance * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/UpdateDeviceInstance" * target="_top">AWS API Documentation</a> */ UpdateDeviceInstanceResult updateDeviceInstance(UpdateDeviceInstanceRequest updateDeviceInstanceRequest); /** * <p> * Modifies the name, description, and rules in a device pool given the attributes and the pool ARN. Rule updates * are all-or-nothing, meaning they can only be updated as a whole (or not at all). * </p> * * @param updateDevicePoolRequest * Represents a request to the update device pool operation. * @return Result of the UpdateDevicePool operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.UpdateDevicePool * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/UpdateDevicePool" target="_top">AWS * API Documentation</a> */ UpdateDevicePoolResult updateDevicePool(UpdateDevicePoolRequest updateDevicePoolRequest); /** * <p> * Updates information about an existing private device instance profile. * </p> * * @param updateInstanceProfileRequest * @return Result of the UpdateInstanceProfile operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.UpdateInstanceProfile * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/UpdateInstanceProfile" * target="_top">AWS API Documentation</a> */ UpdateInstanceProfileResult updateInstanceProfile(UpdateInstanceProfileRequest updateInstanceProfileRequest); /** * <p> * Updates the network profile with specific settings. * </p> * * @param updateNetworkProfileRequest * @return Result of the UpdateNetworkProfile operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.UpdateNetworkProfile * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/UpdateNetworkProfile" * target="_top">AWS API Documentation</a> */ UpdateNetworkProfileResult updateNetworkProfile(UpdateNetworkProfileRequest updateNetworkProfileRequest); /** * <p> * Modifies the specified project name, given the project ARN and a new name. * </p> * * @param updateProjectRequest * Represents a request to the update project operation. * @return Result of the UpdateProject operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.UpdateProject * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/UpdateProject" target="_top">AWS API * Documentation</a> */ UpdateProjectResult updateProject(UpdateProjectRequest updateProjectRequest); /** * <p> * Update an uploaded test specification (test spec). * </p> * * @param updateUploadRequest * @return Result of the UpdateUpload operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws LimitExceededException * A limit was exceeded. * @throws ServiceAccountException * There was a problem with the service account. * @sample AWSDeviceFarm.UpdateUpload * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/UpdateUpload" target="_top">AWS API * Documentation</a> */ UpdateUploadResult updateUpload(UpdateUploadRequest updateUploadRequest); /** * <p> * Updates information about an existing Amazon Virtual Private Cloud (VPC) endpoint configuration. * </p> * * @param updateVPCEConfigurationRequest * @return Result of the UpdateVPCEConfiguration operation returned by the service. * @throws ArgumentException * An invalid argument was specified. * @throws NotFoundException * The specified entity was not found. * @throws ServiceAccountException * There was a problem with the service account. * @throws InvalidOperationException * There was an error with the update request, or you do not have sufficient permissions to update this VPC * endpoint configuration. * @sample AWSDeviceFarm.UpdateVPCEConfiguration * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/UpdateVPCEConfiguration" * target="_top">AWS API Documentation</a> */ UpdateVPCEConfigurationResult updateVPCEConfiguration(UpdateVPCEConfigurationRequest updateVPCEConfigurationRequest); /** * Shuts down this client object, releasing any resources that might be held open. This is an optional method, and * callers are not expected to call it, but can if they want to explicitly release any open resources. Once a client * has been shutdown, it should not be used to make any more requests. */ void shutdown(); /** * Returns additional metadata for a previously executed successful request, typically used for debugging issues * where a service isn't acting as expected. This data isn't considered part of the result data returned by an * operation, so it's available through this separate, diagnostic interface. * <p> * Response metadata is only cached for a limited period of time, so if you need to access this extra diagnostic * information for an executed request, you should use this method to retrieve it as soon as possible after * executing a request. * * @param request * The originally executed request. * * @return The response metadata for the specified request, or null if none is available. */ ResponseMetadata getCachedResponseMetadata(AmazonWebServiceRequest request); }
apache-2.0
santhosh-tekuri/jlibs
wadl/src/main/java/jlibs/wadl/model/Resource.java
9494
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.02.03 at 05:17:30 PM GMT+05:30 // package jlibs.wadl.model; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyAttribute; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElements; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import javax.xml.namespace.QName; import org.w3c.dom.Element; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://wadl.dev.java.net/2009/02}doc" maxOccurs="unbounded" minOccurs="0"/> * &lt;element ref="{http://wadl.dev.java.net/2009/02}param" maxOccurs="unbounded" minOccurs="0"/> * &lt;choice maxOccurs="unbounded" minOccurs="0"> * &lt;element ref="{http://wadl.dev.java.net/2009/02}method"/> * &lt;element ref="{http://wadl.dev.java.net/2009/02}resource"/> * &lt;/choice> * &lt;any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="id" type="{http://www.w3.org/2001/XMLSchema}ID" /> * &lt;attribute name="type" type="{http://wadl.dev.java.net/2009/02}resource_type_list" /> * &lt;attribute name="queryType" type="{http://www.w3.org/2001/XMLSchema}string" default="application/x-www-form-urlencoded" /> * &lt;attribute name="path" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;anyAttribute processContents='lax' namespace='##other'/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "doc", "param", "methodOrResource", "any" }) @XmlRootElement(name = "resource") public class Resource { protected List<Doc> doc; protected List<Param> param; @XmlElements({ @XmlElement(name = "method", type = Method.class), @XmlElement(name = "resource", type = Resource.class) }) protected List<Object> methodOrResource; @XmlAnyElement(lax = true) protected List<Object> any; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected String id; @XmlAttribute protected List<String> type; @XmlAttribute protected String queryType; @XmlAttribute protected String path; @XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>(); /** * Gets the value of the doc property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the doc property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDoc().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Doc } * * */ public List<Doc> getDoc() { if (doc == null) { doc = new ArrayList<Doc>(); } return this.doc; } /** * Gets the value of the param property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the param property. * * <p> * For example, to add a new item, do as follows: * <pre> * getParam().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Param } * * */ public List<Param> getParam() { if (param == null) { param = new ArrayList<Param>(); } return this.param; } /** * Gets the value of the methodOrResource property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the methodOrResource property. * * <p> * For example, to add a new item, do as follows: * <pre> * getMethodOrResource().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Method } * {@link Resource } * * */ public List<Object> getMethodOrResource() { if (methodOrResource == null) { methodOrResource = new ArrayList<Object>(); } return this.methodOrResource; } /** * Gets the value of the any property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the any property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAny().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Element } * {@link Object } * * */ public List<Object> getAny() { if (any == null) { any = new ArrayList<Object>(); } return this.any; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the type property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the type property. * * <p> * For example, to add a new item, do as follows: * <pre> * getType().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getType() { if (type == null) { type = new ArrayList<String>(); } return this.type; } /** * Gets the value of the queryType property. * * @return * possible object is * {@link String } * */ public String getQueryType() { if (queryType == null) { return "application/x-www-form-urlencoded"; } else { return queryType; } } /** * Sets the value of the queryType property. * * @param value * allowed object is * {@link String } * */ public void setQueryType(String value) { this.queryType = value; } /** * Gets the value of the path property. * * @return * possible object is * {@link String } * */ public String getPath() { return path; } /** * Sets the value of the path property. * * @param value * allowed object is * {@link String } * */ public void setPath(String value) { this.path = value; } /** * Gets a map that contains attributes that aren't bound to any typed property on this class. * * <p> * the map is keyed by the name of the attribute and * the value is the string value of the attribute. * * the map returned by this method is live, and you can add new attribute * by updating the map directly. Because of this design, there's no setter. * * * @return * always non-null */ public Map<QName, String> getOtherAttributes() { return otherAttributes; } }
apache-2.0
0359xiaodong/auto-parcel
auto-parcel-processor/src/main/java/auto/parcel/processor/TypeSimplifier.java
10116
package auto.parcel.processor; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.lang.model.element.Element; import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; import javax.lang.model.type.ArrayType; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; import javax.lang.model.type.TypeVariable; import javax.lang.model.type.TypeVisitor; import javax.lang.model.type.WildcardType; import javax.lang.model.util.SimpleTypeVisitor6; import javax.lang.model.util.Types; /** * Takes a set of types and a package and determines which of those types can be imported, and how * to spell any of the types in the set given those imports. * * @author emcmanus@google.com (Éamonn McManus) */ final class TypeSimplifier { /** * The spelling that should be used to refer to a given class, and an indication of whether it * should be imported. */ private static class Spelling { final String spelling; final boolean importIt; Spelling(String spelling, boolean importIt) { this.spelling = spelling; this.importIt = importIt; } } private final Types typeUtil; private final Map<String, Spelling> imports; TypeSimplifier(Types typeUtil, String packageName, Set<TypeMirror> types) { this.typeUtil = typeUtil; Set<TypeMirror> referenced = referencedClassTypes(typeUtil, types); this.imports = findImports(typeUtil, packageName, referenced); } /** * Returns the set of types to import. We import every type that is neither in java.lang nor in * the package containing the AutoParcel class, provided that the result refers to the type * unambiguously. For example, if there is a property of type java.util.Map.Entry then we will * import java.util.Map.Entry and refer to the property as Entry. We could also import just * java.util.Map in this case and refer to Map.Entry, but currently we never do that. */ SortedSet<String> typesToImport() { SortedSet<String> typesToImport = new TreeSet<String>(); for (Map.Entry<String, Spelling> entry : imports.entrySet()) { if (entry.getValue().importIt) { typesToImport.add(entry.getKey()); } } return typesToImport; } /** * Returns a string that can be used to refer to the given type given the imports defined by * {@link #typesToImport}. */ String simplify(TypeMirror type) { return type.accept(new ToStringTypeVisitor(), new StringBuilder()).toString(); } /** * Visitor that produces a string representation of a type for use in generated code. * The visitor takes into account the imports defined by {@link #typesToImport} and will use * the short names of those types. * * <p>A simpler alternative would be just to use TypeMirror.toString() and regular expressions to * pick apart the type references and replace fully-qualified types where possible. That depends * on unspecified behaviour of TypeMirror.toString(), though, and is vulnerable to formatting * quirks such as the way it omits the comma in * {@code java.util.Map<java.lang.String, java.lang.String>}. */ private class ToStringTypeVisitor extends SimpleTypeVisitor6<StringBuilder, StringBuilder> { @Override protected StringBuilder defaultAction(TypeMirror type, StringBuilder sb) { return sb.append(type); } @Override public StringBuilder visitArray(ArrayType type, StringBuilder sb) { return visit(type.getComponentType(), sb).append("[]"); } @Override public StringBuilder visitDeclared(DeclaredType type, StringBuilder sb) { TypeElement typeElement = (TypeElement) typeUtil.asElement(type); String typeString = typeElement.getQualifiedName().toString(); if (imports.containsKey(typeString)) { sb.append(imports.get(typeString).spelling); } else { sb.append(typeString); } List<? extends TypeMirror> arguments = type.getTypeArguments(); if (!arguments.isEmpty()) { sb.append("<"); String sep = ""; for (TypeMirror argument : arguments) { sb.append(sep); sep = ", "; visit(argument, sb); } sb.append(">"); } return sb; } @Override public StringBuilder visitWildcard(WildcardType type, StringBuilder sb) { sb.append("?"); TypeMirror extendsBound = type.getExtendsBound(); TypeMirror superBound = type.getSuperBound(); if (superBound != null) { sb.append(" super "); visit(superBound, sb); } else if (extendsBound != null) { sb.append(" extends "); visit(extendsBound, sb); } return sb; } } /** * Returns the name of the package that the given type is in. If the type is in the default * (unnamed) package then the name is the empty string. */ static String packageNameOf(TypeElement type) { while (true) { Element enclosing = type.getEnclosingElement(); if (enclosing instanceof PackageElement) { return ((PackageElement) enclosing).getQualifiedName().toString(); } type = (TypeElement) enclosing; } } /** * Given a set of referenced types, works out which of them should be imported and what the * resulting spelling of each one is. * * <p>This method operates on a {@code Set<TypeMirror>} rather than just a {@code Set<String>} * because it is not strictly possible to determine what part of a fully-qualified type name is * the package and what part is the top-level class. For example, {@code java.util.Map.Entry} is * a class called {@code Map.Entry} in a package called {@code java.util} assuming Java * conventions are being followed, but it could theoretically also be a class called {@code Entry} * in a package called {@code java.util.Map}. Since we are operating as part of the compiler, our * goal should be complete correctness, and the only way to achieve that is to operate on the real * representations of types. * * @param packageName The name of the package where the class containing these references is * defined. Other classes within the same package do not need to be imported. * @param referenced The complete set of declared types (classes and interfaces) that will be * referenced in the generated code. * @return a map where the keys are fully-qualified types and the corresponding values indicate * whether the type should be imported, and how the type should be spelled in the source code. */ private static Map<String, Spelling> findImports( Types typeUtil, String packageName, Set<TypeMirror> referenced) { Map<String, Spelling> imports = new HashMap<String, Spelling>(); Set<String> ambiguous = ambiguousNames(typeUtil, referenced); for (TypeMirror type : referenced) { TypeElement typeElement = (TypeElement) typeUtil.asElement(type); String fullName = typeElement.getQualifiedName().toString(); String simpleName = typeElement.getSimpleName().toString(); String pkg = packageNameOf(typeElement); boolean importIt; String spelling; if (ambiguous.contains(simpleName)) { importIt = false; spelling = fullName; } else if (pkg.equals(packageName) || pkg.equals("java.lang")) { importIt = false; spelling = fullName.substring(pkg.isEmpty() ? 0 : pkg.length() + 1); } else { importIt = true; spelling = simpleName; } imports.put(fullName, new Spelling(spelling, importIt)); } return imports; } /** * Finds all declared types (classes and interfaces) that are referenced in the given * {@code Set<TypeMirror>}. This includes classes and interfaces that appear directly in the set, * but also ones that appear in type parameters and the like. For example, if the set contains * {@code java.util.List<? extends java.lang.Number>} then both {@code java.util.List} and * {@code java.lang.Number} will be in the resulting set. */ private static Set<TypeMirror> referencedClassTypes(Types typeUtil, Set<TypeMirror> types) { Set<TypeMirror> referenced = new HashSet<TypeMirror>(); TypeVisitor<Void, Void> typeVisitor = new ReferencedClassTypeVisitor(typeUtil, referenced); for (TypeMirror type : types) { type.accept(typeVisitor, null); } return referenced; } private static class ReferencedClassTypeVisitor extends SimpleTypeVisitor6<Void, Void> { private final Types typeUtil; private final Set<TypeMirror> referenced; ReferencedClassTypeVisitor(Types typeUtil, Set<TypeMirror> referenced) { this.typeUtil = typeUtil; this.referenced = referenced; } @Override public Void visitArray(ArrayType t, Void p) { return visit(t.getComponentType(), p); } @Override public Void visitDeclared(DeclaredType t, Void p) { boolean added = referenced.add(typeUtil.erasure(t)); if (added) { for (TypeMirror param : t.getTypeArguments()) { visit(param, p); } } return null; } @Override public Void visitTypeVariable(TypeVariable t, Void p) { visit(t.getLowerBound(), p); return visit(t.getUpperBound(), p); } @Override public Void visitWildcard(WildcardType t, Void p) { for (TypeMirror bound : new TypeMirror[] {t.getSuperBound(), t.getExtendsBound()}) { if (bound != null) { visit(bound, p); } } return null; } } private static Set<String> ambiguousNames(Types typeUtil, Set<TypeMirror> types) { Set<String> ambiguous = new HashSet<String>(); Set<String> simpleNames = new HashSet<String>(); for (TypeMirror type : types) { String simpleName = typeUtil.asElement(type).getSimpleName().toString(); if (!simpleNames.add(simpleName)) { ambiguous.add(simpleName); } } return ambiguous; } }
apache-2.0
dbahat/conventions
Conventions/app/src/main/java/amai/org/conventions/map/MapFloorFragment.java
33303
package amai.org.conventions.map; import android.animation.Animator; import android.animation.ObjectAnimator; import android.animation.TimeInterpolator; import android.animation.ValueAnimator; import android.app.Activity; import android.app.ActivityOptions; import android.content.Context; import android.content.Intent; import android.graphics.Picture; import android.graphics.drawable.Drawable; import android.graphics.drawable.PictureDrawable; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.animation.AccelerateInterpolator; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.animation.DecelerateInterpolator; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.core.view.MotionEventCompat; import androidx.fragment.app.Fragment; import com.caverock.androidsvg.SVG; import com.caverock.androidsvg.SVGImageView; import com.google.firebase.analytics.FirebaseAnalytics; import com.manuelpeinado.imagelayout.ImageLayout; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.LinkedList; import java.util.List; import amai.org.conventions.ImageHandler; import amai.org.conventions.R; import amai.org.conventions.customviews.AspectRatioSVGImageView; import amai.org.conventions.customviews.InterceptorLinearLayout; import amai.org.conventions.events.EventView; import amai.org.conventions.events.activities.HallActivity; import amai.org.conventions.events.activities.StandsAreaFragment; import amai.org.conventions.model.ConventionEvent; import amai.org.conventions.model.ConventionEventComparator; import amai.org.conventions.model.ConventionMap; import amai.org.conventions.model.Floor; import amai.org.conventions.model.FloorLocation; import amai.org.conventions.model.Hall; import amai.org.conventions.model.MapLocation; import amai.org.conventions.model.Place; import amai.org.conventions.model.Stand; import amai.org.conventions.model.StandsArea; import amai.org.conventions.model.conventions.Convention; import amai.org.conventions.utils.BundleBuilder; import amai.org.conventions.utils.Dates; import amai.org.conventions.utils.Views; import pl.polidea.view.ZoomView; /** * A fragment showing a single map floor */ public class MapFloorFragment extends Fragment implements Marker.MarkerListener { private static final String ARGS_FLOOR_NUMBER = "FloorNumber"; private static final String ARGS_SHOW_ANIMATION = "ShowAnimation"; private static final String STATE_SELECTED_LOCATIONS = "StateSelectedLocation"; private static final String STATE_LOCATION_DETAILS_OPEN = "StateLocationDetailsOpen"; private static final String STATE_MAP_FLOOR_ZOOM_FACTOR = "StateMapFloorZoomFactor"; private static final String STATE_MAP_FLOOR_ZOOM_X = "StateMapFloorZoomX"; private static final String STATE_MAP_FLOOR_ZOOM_Y = "StateMapFloorZoomY"; private static final float MAX_ZOOM = 2.5f; private static final int LOCATION_DETAILS_OPEN_CLOSE_DURATION = 300; private Floor floor; private View progressBar; private ZoomView mapZoomView; private ImageLayout mapFloorImage; private View upArrow; private TextView upArrowText; private View downArrow; private TextView downArrowText; private InterceptorLinearLayout locationDetails; private TextView locationTitle; private ImageView locationDetailsCloseImage; private EventView locationCurrentEvent; private View locationEventsDivider; private EventView locationNextEvent; private Button gotoStandsListButton; private Button gotoFloorButton; private OnMapFloorEventListener mapFloorEventsListener; private List<Marker> floorMarkers = new LinkedList<>(); private List<MapLocation> locationsToSelect; private Context appContext; private MapLocation currentLocationDetails; private boolean preventFragmentScroll; public MapFloorFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { setHasOptionsMenu(true); // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_map_floor, container, false); resolveUIElements(view); initializeLocationDetails(); initializeEventsListener(); setMapClickListeners(); configureMapFloorAndRestoreState(savedInstanceState); return view; } public Floor getFloor() { return floor; } public void toggleMapZoom() { changeMapZoom(!isMapZoomedIn()); } private void changeMapZoom(boolean zoomIn) { if (zoomIn) { // Find a selected marker and center it ImageView view = null; for (Marker marker : floorMarkers) { if (marker.isSelected()) { view = marker.getImageView(); break; } } if (view == null) { mapZoomView.smoothZoomTo(MAX_ZOOM, mapZoomView.getWidth() / 2, mapZoomView.getHeight() / 2); } else { mapZoomView.smoothZoomTo(MAX_ZOOM, view.getX(), view.getY()); } } else { mapZoomView.smoothZoomTo(1.0f, mapZoomView.getWidth() / 2, mapZoomView.getHeight() / 2); } } public boolean canSwipeToChangeFloor() { // Allow to swipe between floors when map is not zoomed in and location details is not open return !isMapZoomedIn() && !preventFragmentScroll; } public boolean isMapZoomedIn() { // If the fragment is still being initialized the view zoom will be null. // This could happen while the map activity is loading and its onCreateOptionsMenu is called // before this fragment's onCreateView. return mapZoomView != null && mapZoomView.getZoom() > 1.0f; } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof OnMapFloorEventListener)) { throw new AssertionError("This fragment must be invoked form an activity implementing " + mapFloorEventsListener.getClass().getSimpleName()); } mapFloorEventsListener = (OnMapFloorEventListener) activity; // The activity might be detached during the lifecycle while we still need a context. // The application context is always valid. appContext = activity.getApplicationContext(); } @Override public void onDetach() { super.onDetach(); mapFloorEventsListener = null; } @Override public void onSaveInstanceState(Bundle outState) { ArrayList<Integer> selectedLocationIDs = new ArrayList<>(); for (Marker marker : floorMarkers) { if (marker.isSelected()) { selectedLocationIDs.add(marker.getLocation().getId()); } } outState.putIntegerArrayList(STATE_SELECTED_LOCATIONS, selectedLocationIDs); outState.putBoolean(STATE_LOCATION_DETAILS_OPEN, locationDetails.getVisibility() == View.VISIBLE); outState.putFloat(STATE_MAP_FLOOR_ZOOM_FACTOR, mapZoomView.getZoom()); outState.putFloat(STATE_MAP_FLOOR_ZOOM_X, mapZoomView.getZoomFocusX() / mapZoomView.getWidth()); outState.putFloat(STATE_MAP_FLOOR_ZOOM_Y, mapZoomView.getZoomFocusY() / mapZoomView.getHeight()); super.onSaveInstanceState(outState); } public static MapFloorFragment newInstance(int floor, boolean showAnimation) { MapFloorFragment fragment = new MapFloorFragment(); Bundle args = new Bundle(); args.putInt(ARGS_FLOOR_NUMBER, floor); args.putBoolean(ARGS_SHOW_ANIMATION, showAnimation); fragment.setArguments(args); return fragment; } private void initializeEventsListener() { upArrow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mapFloorEventsListener != null) { mapFloorEventsListener.onUpArrowClicked(); } } }); downArrow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mapFloorEventsListener != null) { mapFloorEventsListener.onDownArrowClicked(); } } }); mapZoomView.setZoomListener(new ZoomView.ZoomViewListener() { @Override public void onZoomStarted(float zoom, float zoomx, float zoomy) { } @Override public void onZooming(float zoom, float zoomx, float zoomy) { } @Override public void onZoomEnded(float zoom, float zoomx, float zoomy) { if (mapFloorEventsListener != null) { mapFloorEventsListener.onZoomChanged(); } } }); } private void resolveUIElements(View view) { progressBar = view.findViewById(R.id.floor_loading_progress_bar); mapZoomView = (ZoomView) view.findViewById(R.id.map_zoom_view); mapFloorImage = (ImageLayout) view.findViewById(R.id.map_floor_image); upArrow = view.findViewById(R.id.map_floor_up); upArrowText = view.findViewById(R.id.map_floor_up_text); downArrow = view.findViewById(R.id.map_floor_down); downArrowText = view.findViewById(R.id.map_floor_down_text); // Current selected location details locationDetails = (InterceptorLinearLayout) view.findViewById(R.id.location_details); locationTitle = (TextView) view.findViewById(R.id.location_title); locationDetailsCloseImage = (ImageView) view.findViewById(R.id.location_details_close_image); locationCurrentEvent = (EventView) view.findViewById(R.id.location_current_event); locationEventsDivider = view.findViewById(R.id.location_events_divider); locationNextEvent = (EventView) view.findViewById(R.id.location_next_event); gotoStandsListButton = (Button) view.findViewById(R.id.goto_stands_list_button); gotoFloorButton = view.findViewById(R.id.goto_floor_button); } private void initializeLocationDetails() { locationDetailsCloseImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { hideLocationDetails(); } }); InterceptorLinearLayout.AllTouchEventsListener touchListener = new InterceptorLinearLayout.AllTouchEventsListener() { public final int TOUCH_SLOP = ViewConfiguration.get(appContext).getScaledTouchSlop(); float startPointY; boolean isDragging = false; boolean performedDragUpAction = false; @Override public boolean onInterceptTouchEvent(MotionEvent event) { switch (MotionEventCompat.getActionMasked(event)) { case MotionEvent.ACTION_DOWN: // If the user started a scroll on the event details, don't let the view pager // we're in scroll to the floor below/above handleTouchEventsStarted(event); resetMotionEventParameters(event); break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: // Touch events finished, let the view pager and children intercept events again. handleTouchEventsFinished(event); break; case MotionEvent.ACTION_MOVE: if (isDragging || movePassesThreshold(event)) { // The view is being dragged, so it should handle the event (and not its children) isDragging = true; return true; } break; } // Don't intercept any touch event except dragging return false; } @Override public boolean onTouch(View v, MotionEvent event) { switch (MotionEventCompat.getActionMasked(event)) { case MotionEvent.ACTION_DOWN: handleTouchEventsStarted(event); resetMotionEventParameters(event); break; case MotionEvent.ACTION_CANCEL: // It's cancel so don't perform a click handleTouchEventsFinished(event); break; case MotionEvent.ACTION_UP: handleTouchEventsFinished(event); // Handle click event for locationDetails (it isn't called because we consume // all motion events) handleClick(event); break; case MotionEvent.ACTION_MOVE: // Handle drag event handleMove(event); break; } // Always consume the events that arrive here return true; } private void handleMove(MotionEvent event) { if (movePassesThreshold(event)) { // Check if we moved down or up if (startPointY - event.getY() > 0) { // This could be called more than once because it takes a while to // navigate to the hall while the user moves their finger if (!performedDragUpAction) { performedDragUpAction = true; locationDetails.callOnClick(); } } else { hideLocationDetails(); } } } private void handleClick(MotionEvent event) { if (!movePassesThreshold(event)) { locationDetails.callOnClick(); } } private boolean movePassesThreshold(MotionEvent event) { return Math.abs(startPointY - event.getY()) > TOUCH_SLOP; } private void resetMotionEventParameters(MotionEvent event) { if (event.getPointerCount() == 1) { isDragging = false; performedDragUpAction = false; startPointY = event.getY(); } } private void handleTouchEventsFinished(MotionEvent event) { // Touch events finished, let the view pager intercept events again if (event.getPointerCount() == 1) { preventFragmentScroll = false; isDragging = false; } } private void handleTouchEventsStarted(MotionEvent event) { // If the user started a scroll on the event details, don't let the view pager // we're in scroll to the floor below/above preventFragmentScroll = true; } }; // Intercept and handle touch events on locationDetails so we can handle drag as well // as click on the view and its children locationDetails.setOnInterceptTouchEventListener(touchListener); locationDetails.setOnTouchListener(touchListener); } private void configureMapFloorAndRestoreState(final Bundle savedInstanceState) { int mapFloor = getArguments().getInt(ARGS_FLOOR_NUMBER); final boolean showAnimation = getArguments().getBoolean(ARGS_SHOW_ANIMATION); getArguments().remove(ARGS_SHOW_ANIMATION); // Only show the animation once final ConventionMap map = Convention.getInstance().getMap(); floor = map.findFloorByNumber(mapFloor); // Add up and down arrows boolean isTopFloor = floor.getNumber() == map.getTopFloor().getNumber(); if (isTopFloor) { upArrow.setVisibility(View.GONE); } else { upArrow.setVisibility(View.VISIBLE); upArrowText.setText(getString(R.string.goto_floor, map.getFloors().get(map.floorNumberToFloorIndex(floor.getNumber()) + 1).getName())); } boolean isBottomFloor = floor.getNumber() == map.getBottomFloor().getNumber(); if (isBottomFloor) { downArrow.setVisibility(View.GONE); } else { downArrow.setVisibility(View.VISIBLE); downArrowText.setText(getString(R.string.goto_floor, map.getFloors().get(map.floorNumberToFloorIndex(floor.getNumber()) - 1).getName())); } // We have to measure for the animations to work downArrow.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); mapZoomView.setMaxZoom(MAX_ZOOM); // Load images in background new AsyncTask<Void, Void, Boolean>() { SVG svg = null; List<MapLocation> locations = null; @Override protected Boolean doInBackground(Void... params) { if (floor.isImageSVG()) { svg = ImageHandler.loadSVG(appContext, floor.getImageResource()); } // Find location markers and load their svg images (the views are created in the UI thread) locations = map.findLocationsByFloor(floor); for (final MapLocation location : locations) { // We don't save the result because it's saved in a cache for quicker access in the UI thread if (location.isMarkerResourceSVG()) { ImageHandler.loadSVG(appContext, location.getMarkerResource()); } } return true; } @Override protected void onPostExecute(Boolean successful) { // Check the background method finished successfully if (!successful) { return; } mapFloorImage.setLayerType(View.LAYER_TYPE_SOFTWARE, null); if (floor.isImageSVG()) { Picture picture = svg.renderToPicture(); mapFloorImage.setImageResourceFromDrawable(new PictureDrawable(picture), floor.getImageWidth(), floor.getImageHeight()); } else { mapFloorImage.setImageResource(floor.getImageResource(), floor.getImageWidth(), floor.getImageHeight()); } Animation animation = null; if (showAnimation) { animation = AnimationUtils.loadAnimation(appContext, R.anim.drop_and_fade_in_from_top); animation.setStartOffset(100); } // Add markers for (final MapLocation location : locations) { // Add the marker for this location View markerImageView = createMarkerView(location); mapFloorImage.addView(markerImageView); if (animation != null) { markerImageView.startAnimation(animation); } } // Set initially selected location now after we created all the markers if (locationsToSelect != null) { selectLocations(locationsToSelect); locationsToSelect = null; } restoreState(savedInstanceState); progressBar.setVisibility(View.GONE); mapZoomView.setVisibility(View.VISIBLE); } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } private void restoreState(Bundle savedInstanceState) { if (savedInstanceState != null) { ArrayList<Integer> selectedLocations = savedInstanceState.getIntegerArrayList(STATE_SELECTED_LOCATIONS); MapLocation selectedLocation = null; if (selectedLocations != null) { for (int locationId : selectedLocations) { for (Marker marker : floorMarkers) { if (marker.getLocation().getId() == locationId) { selectedLocation = marker.getLocation(); marker.select(false); break; } } } } boolean locationDetailsOpen = savedInstanceState.getBoolean(STATE_LOCATION_DETAILS_OPEN); if (locationDetailsOpen && selectedLocation != null) { // If the details are open there should only be one location selected so we take the last one // Don't show animation when restoring showLocationDetails(selectedLocation, false); } float zoomFactor = savedInstanceState.getFloat(STATE_MAP_FLOOR_ZOOM_FACTOR, 1.0f); if (zoomFactor > 1.0f) { float zoomX = savedInstanceState.getFloat(STATE_MAP_FLOOR_ZOOM_X) * mapZoomView.getWidth(); float zoomY = savedInstanceState.getFloat(STATE_MAP_FLOOR_ZOOM_Y) * mapZoomView.getHeight(); mapZoomView.zoomTo(zoomFactor, zoomX / zoomFactor, zoomY / zoomFactor); } } } private View createMarkerView(final MapLocation location) { // We send the appContext here and not the activity due to reasons stated in onAttach, // this means any activity-specific information (like theme, layout direction etc) is not // passed to this image view. It doesn't make any difference in this case since we don't use // such information. final SVGImageView markerImageView = new AspectRatioSVGImageView(appContext); // Set marker image if (location.isMarkerResourceSVG()) { SVG markerSvg = ImageHandler.loadSVG(appContext, location.getMarkerResource()); markerImageView.setSVG(markerSvg); } else { markerImageView.setImageDrawable(ContextCompat.getDrawable(appContext, location.getMarkerResource())); } // Setting layer type to none to avoid caching the marker views bitmap when in zoomed-out state. // The caching causes the marker image looks pixelized in zoomed-in state. // This has to be done after calling setSVG. markerImageView.setLayerType(View.LAYER_TYPE_NONE, null); // Set marker layout parameters and scaling ImageLayout.LayoutParams layoutParams = new ImageLayout.LayoutParams(); // Marker size layoutParams.width = ViewGroup.LayoutParams.WRAP_CONTENT; layoutParams.height = location.getMarkerHeight(); // Marker location layoutParams.centerX = location.getX(); if (location.doesMarkerPointUp()) { layoutParams.top = floor.getImageHeight() - location.getY(); } else { layoutParams.bottom = floor.getImageHeight() - location.getY(); } markerImageView.setLayoutParams(layoutParams); markerImageView.setScaleType(ImageView.ScaleType.FIT_CENTER); // On click handler Marker marker = new Marker(location, markerImageView, markerImageView.getDrawable(), new Marker.DrawableProvider() { Drawable drawable = null; @Override public Drawable getDrawable() { if (drawable == null) { if (location.isSelectedMarkerResourceSVG()) { SVG markerSelectedSvg = ImageHandler.loadSVG(appContext, location.getSelectedMarkerResource()); drawable = new PictureDrawable(markerSelectedSvg.renderToPicture()); } else { drawable = ContextCompat.getDrawable(appContext, location.getSelectedMarkerResource()); } } return drawable; } }); floorMarkers.add(marker); marker.setOnClickListener(this); return markerImageView; } public void selectLocations(List<MapLocation> locations) { // If this fragment is already initialized, select the marker if (!floorMarkers.isEmpty()) { for (MapLocation location : locations) { for (Marker marker : floorMarkers) { if (marker.getLocation().getId() == location.getId()) { marker.select(true); break; } } } // If exactly 1 location is selected, show its details if (locations.size() == 1) { showLocationDetails(locations.get(0), true); } } else { // Save it for later use locationsToSelect = locations; } } public void resetState() { for (Marker marker : floorMarkers) { marker.deselect(); } hideLocationDetails(); changeMapZoom(false); } public void selectMarkersWithNameAndFloor(List<MapLocation> locations) { if (locations == null || locations.isEmpty()) { for (Marker marker : floorMarkers) { marker.deselect(); } return; } MapLocation locationToDisplay = null; // Select sent locations and deselect everything else. // Don't deselect then reselect the same marker. int numOfSelectedMarkers = 0; MapLocationSearchEquality comparator = new MapLocationSearchEquality(); for (Marker marker : floorMarkers) { boolean selected = false; for (MapLocation location : locations) { if (comparator.equals(location, marker.getLocation())) { marker.select(); selected = true; ++numOfSelectedMarkers; locationToDisplay = location; break; } } if (!selected) { marker.deselect(); } } // Show the selected location (in case there's only 1 - it can be more than 1 if there are // several places with the same name in this floor) if (numOfSelectedMarkers == 1) { showLocationDetails(locationToDisplay, true); } } public void selectStandByLocation(final MapLocation location, final Stand stand) { int delayOpenStandsLocation = 200; int numOfSelectedMarkers = 0; for (Marker marker : floorMarkers) { boolean selected = false; if (location != null && marker.getLocation().getId() == location.getId()) { marker.select(); selected = true; ++numOfSelectedMarkers; } if (!selected) { marker.deselect(); } } if (numOfSelectedMarkers == 1) { showLocationDetails(location, true); delayOpenStandsLocation += LOCATION_DETAILS_OPEN_CLOSE_DURATION; } new Handler().postDelayed(new Runnable() { @Override public void run() { showStandsArea(location, stand); } }, delayOpenStandsLocation); } public interface OnMapFloorEventListener { void onUpArrowClicked(); void onDownArrowClicked(); void onZoomChanged(); /** * Location details top changed ("top" meaning distance from bottom). * This method is called during animation. */ void onLocationDetailsTopChanged(int top, MapFloorFragment floor); void onShowFloorClicked(Floor floor); } @Override public void onClick(Marker marker) { FirebaseAnalytics .getInstance(getContext()) .logEvent("map_marker_clicked", new BundleBuilder() .putString("location", marker.getLocation().getName()) .build() ); // Deselect all markers except the clicked marker for (Marker currMarker : floorMarkers) { if (currMarker != marker) { currMarker.deselect(); } } // Ensure clicked marker is selected marker.select(); showLocationDetails(marker.getLocation(), true); } private void setMapClickListeners() { mapFloorImage.setOnTouchListener(Views.createOnSingleTapConfirmedListener(appContext, new Runnable() { @Override public void run() { for (Marker marker : floorMarkers) { marker.deselect(); } hideLocationDetails(); } })); } private void hideLocationDetails() { if (currentLocationDetails == null) { return; } currentLocationDetails = null; if (locationDetails.getVisibility() != View.GONE) { Animator animator = animateLocationDetailsTranslationY(0, 1, new AccelerateInterpolator()); animator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { locationDetails.setVisibility(View.GONE); locationDetails.setTranslationY(0); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); animator.start(); } } public int getMapHiddenPortionHeight() { return (downArrow == null) ? 0 : (downArrow.getVisibility() == View.VISIBLE ? downArrow.getMeasuredHeight() : 0) + (locationDetails.getVisibility() == View.VISIBLE ? locationDetails.getMeasuredHeight() : 0); } @NonNull private ObjectAnimator animateLocationDetailsTranslationY(float fromFraction, float toFraction, TimeInterpolator interpolator) { // Using ObjectAnimator and not xml animation so we can listen to the animation update and notify the listener // (which updates the location of the floating action button( final int detailsHeight = locationDetails.getMeasuredHeight(); ObjectAnimator animator = ObjectAnimator.ofFloat(locationDetails, "translationY", fromFraction * detailsHeight, toFraction * detailsHeight); animator.setInterpolator(interpolator); final int baseline = (downArrow.getVisibility() == View.VISIBLE ? downArrow.getMeasuredHeight() : 0); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float value = (float) animation.getAnimatedValue(); if (mapFloorEventsListener != null) { mapFloorEventsListener.onLocationDetailsTopChanged(detailsHeight - (int) value + baseline, MapFloorFragment.this); } } }); animator.setDuration(LOCATION_DETAILS_OPEN_CLOSE_DURATION); return animator; } private void showLocationDetails(final MapLocation location, boolean animate) { // Don't change location details if it's already the displayed location // because we don't want the animation to be displayed in this case if (location == currentLocationDetails || location == null) { return; } currentLocationDetails = location; boolean isVisible = locationDetails.getVisibility() == View.VISIBLE; if (isVisible && animate) { // Hide the location details with animation before opening it Animator hideAnimator = animateLocationDetailsTranslationY(0, 1, new DecelerateInterpolator()); hideAnimator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { setLocationDetails(location); createShowLocationDetailsAnimator().start(); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); hideAnimator.start(); } else { setLocationDetails(location); if (animate) { createShowLocationDetailsAnimator().start(); } else { locationDetails.post(new Runnable() { @Override public void run() { if (mapFloorEventsListener != null) { mapFloorEventsListener.onLocationDetailsTopChanged(getMapHiddenPortionHeight(), MapFloorFragment.this); } } }); } } } private Animator createShowLocationDetailsAnimator() { final Animator showAnimator = animateLocationDetailsTranslationY(1, 0, new AccelerateInterpolator()); showAnimator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { locationDetails.setTranslationY(0); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); return showAnimator; } private void setLocationDetails(final MapLocation location) { locationDetails.setVisibility(View.VISIBLE); locationTitle.setText(location.getName()); locationDetails.setOnClickListener(null); // Get current and next events in this location setupHallLocation(location); // Check if it's a stands area setupStandsLocation(location); // Check if it's a floor location setupFloorLocation(location); // We have to measure for the animations to work (we can't define percentage in ObjectAnimator) locationDetails.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); } private void setupStandsLocation(final MapLocation location) { // Only show button if there is more than 1 stand if (location.hasSinglePlace() && location.getPlaces().get(0) instanceof StandsArea && ((StandsArea) location.getPlaces().get(0)).getStands().size() > 1) { gotoStandsListButton.setVisibility(View.VISIBLE); gotoStandsListButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showStandsArea(location, null); } }); } else { gotoStandsListButton.setVisibility(View.GONE); } } private void setupFloorLocation(final MapLocation location) { // Only show button if there is a floor set if (location.hasSinglePlace() && location.getPlaces().get(0) instanceof FloorLocation && ((FloorLocation) location.getPlaces().get(0)).getFloor() != null) { Floor floor = ((FloorLocation) location.getPlaces().get(0)).getFloor(); gotoFloorButton.setVisibility(View.VISIBLE); gotoFloorButton.setText(getString(R.string.goto_floor, floor.getName())); gotoFloorButton.setOnClickListener(v -> { if (mapFloorEventsListener != null) { mapFloorEventsListener.onShowFloorClicked(floor); } }); } else { gotoFloorButton.setVisibility(View.GONE); } } private void showStandsArea(MapLocation location, Stand stand) { // Show the list of stands in a dialog Place place = location.getPlaces().get(0); StandsAreaFragment standsFragment = new StandsAreaFragment(); Bundle args = new Bundle(); args.putInt(StandsAreaFragment.ARGUMENT_STANDS_AREA_ID, ((StandsArea) place).getId()); if (stand != null) { // Select the stand inside the area args.putString(StandsAreaFragment.ARGUMENT_STAND_NAME, stand.getName()); } standsFragment.setArguments(args); standsFragment.show(getFragmentManager(), null); } private void setupHallLocation(final MapLocation location) { ConventionEvent currEvent = null; ConventionEvent nextEvent = null; boolean isSingleHall = location.hasSinglePlace() && location.getPlaces().get(0) instanceof Hall; if (isSingleHall) { ArrayList<ConventionEvent> events = Convention.getInstance().findEventsByHall(location.getPlaces().get(0).getName()); if (events.size() == 0) { isSingleHall = false; } else { Collections.sort(events, new ConventionEventComparator()); for (ConventionEvent event : events) { Date now = Dates.now(); if (currEvent == null && event.getStartTime().before(now) && event.getEndTime().after(now)) { currEvent = event; } if (nextEvent == null && event.getStartTime().after(now)) { nextEvent = event; } if (currEvent != null && nextEvent != null) { break; } } } } if (currEvent == null) { locationCurrentEvent.setVisibility(View.GONE); } else { locationCurrentEvent.setVisibility(View.VISIBLE); locationCurrentEvent.setEvent(currEvent); } if (nextEvent == null) { locationNextEvent.setVisibility(View.GONE); } else { locationNextEvent.setVisibility(View.VISIBLE); locationNextEvent.setEvent(nextEvent); } if (currEvent != null && nextEvent != null) { locationEventsDivider.setVisibility(View.VISIBLE); } else { locationEventsDivider.setVisibility(View.GONE); } if (isSingleHall) { locationDetails.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Navigate to the hall associated with this location (only if it's a hall) Place place = location.getPlaces().get(0); Bundle animationBundle = ActivityOptions.makeCustomAnimation(appContext, R.anim.slide_in_bottom, 0).toBundle(); Bundle bundle = new Bundle(); bundle.putString(HallActivity.EXTRA_HALL_NAME, place.getName()); bundle.putBoolean(HallActivity.EXTRA_USE_SLIDE_OUT_ANIMATION_ON_BACK, true); Intent intent = new Intent(getActivity(), HallActivity.class); intent.putExtras(bundle); getActivity().startActivity(intent, animationBundle); } }); } } }
apache-2.0
ecologylab/BigSemanticsWrapperRepository
BigSemanticsGeneratedClassesJava/src/ecologylab/bigsemantics/generated/library/person/author/NewmuseumArtist.java
1884
package ecologylab.bigsemantics.generated.library.person.author; /** * Automatically generated by MetaMetadataJavaTranslator * * DO NOT modify this code manually: All your changes may get lost! * * Copyright (2017) Interface Ecology Lab. */ import ecologylab.bigsemantics.generated.library.creativeWork.exhibition.NewmuseumExhibition; import ecologylab.bigsemantics.generated.library.person.author.Artist; import ecologylab.bigsemantics.metadata.builtins.MetadataBuiltinsTypesScope; import ecologylab.bigsemantics.metadata.mm_name; import ecologylab.bigsemantics.metametadata.MetaMetadataCompositeField; import ecologylab.bigsemantics.namesandnums.SemanticsNames; import ecologylab.serialization.annotations.simpl_collection; import ecologylab.serialization.annotations.simpl_inherit; import java.util.ArrayList; import java.util.List; import java.util.Map; @simpl_inherit public class NewmuseumArtist extends Artist { @simpl_collection("newmuseum_exhibition") @mm_name("related_exhibitions") private List<NewmuseumExhibition> relatedExhibitions; public NewmuseumArtist() { super(); } public NewmuseumArtist(MetaMetadataCompositeField mmd) { super(mmd); } public List<NewmuseumExhibition> getRelatedExhibitions() { return relatedExhibitions; } // lazy evaluation: public List<NewmuseumExhibition> relatedExhibitions() { if (relatedExhibitions == null) relatedExhibitions = new ArrayList<NewmuseumExhibition>(); return relatedExhibitions; } // addTo: public void addToRelatedExhibitions(NewmuseumExhibition element) { relatedExhibitions().add(element); } // size: public int relatedExhibitionsSize() { return relatedExhibitions == null ? 0 : relatedExhibitions.size(); } public void setRelatedExhibitions(List<NewmuseumExhibition> relatedExhibitions) { this.relatedExhibitions = relatedExhibitions; } }
apache-2.0
rajadileepkolli/POC
poc-spring-boot-rest/poc-spring-boot-rest-webmvc/src/main/java/com/example/poc/webmvc/dto/PostDTO.java
919
package com.example.poc.webmvc.dto; import io.swagger.v3.oas.annotations.media.Schema; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import org.springframework.hateoas.RepresentationModel; @Getter @Setter @Builder @ToString @NoArgsConstructor @AllArgsConstructor @Schema(description = "All details related to posts.") public class PostDTO extends RepresentationModel<PostDTO> { @Schema(description = "Title is mandatory", required = true) private String title; private String content; private String createdBy; private LocalDateTime createdOn; @Builder.Default private List<PostCommentsDTO> comments = new ArrayList<>(); @Builder.Default private List<TagDTO> tags = new ArrayList<>(); }
apache-2.0
DrMoriarty/cordova-social-ok
src/android/odnoklassniki-android-sdk/src/ru/ok/android/sdk/util/StatsBuilder.java
1817
package ru.ok.android.sdk.util; import java.util.Collection; import java.util.Collections; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class StatsBuilder { public enum Type { /** * simple counter, fe: "10" */ COUNTER, /** * funnel identification, fe: "payment.card" */ SELECT, /** * duration time in ms, fe: "30000" */ INTERVAL, /** * progress, fe: "1" as level number, and id being "start" or "complete" */ STATUS, // ; } private String version = "1.0.0"; private long time = System.currentTimeMillis(); private final JSONArray stats = new JSONArray(); public StatsBuilder() { } public StatsBuilder withVersion(String version) { this.version = version; return this; } public StatsBuilder withTime(long time) { this.time = time; return this; } public StatsBuilder addCounter(Type type, String id, long stamp, Collection<String> values) throws JSONException { JSONObject obj = new JSONObject(); obj.put("type", type.name().toLowerCase()); obj.put("id", id); obj.put("time", stamp); obj.put("data", new JSONArray(values)); stats.put(obj); return this; } public StatsBuilder addCounter(Type type, String id, long stamp, String value) throws JSONException { return addCounter(type, id, stamp, Collections.singleton(value)); } public JSONObject build() throws JSONException { JSONObject obj = new JSONObject(); obj.put("version", version); obj.put("time", time); obj.put("stats", stats); return obj; } }
apache-2.0
realityforge/arez
downstream-test/src/main/java/arez/downstream/CollectFluxChallengeBuildStats.java
4181
package arez.downstream; import gir.Gir; import gir.io.FileUtil; import gir.ruby.Buildr; import gir.ruby.Ruby; import java.nio.file.Path; import java.util.Collections; import javax.annotation.Nonnull; public final class CollectFluxChallengeBuildStats { public static void main( final String[] args ) { try { run(); } catch ( final Exception e ) { System.err.println( "Failed command." ); e.printStackTrace( System.err ); System.exit( 42 ); } } private static void run() throws Exception { Gir.go( () -> { WorkspaceUtil.forEachBranch( "react4j-flux-challenge", "https://github.com/react4j/react4j-flux-challenge.git", Collections.singletonList( "master" ), context -> buildBranch( context, WorkspaceUtil.getVersion() ) ); WorkspaceUtil.collectStatistics( Collections.singletonList( "sithtracker" ), branch -> true, false ); } ); } private static void buildBranch( @Nonnull final WorkspaceUtil.BuildContext context, @Nonnull final String version ) { final boolean initialBuildSuccess = WorkspaceUtil.runBeforeBuild( context, () -> { final Path archiveDir = WorkspaceUtil.getArchiveDir( context.workingDirectory, "sithtracker.before" ); buildAndRecordStatistics( context.appDirectory, archiveDir ); } ); WorkspaceUtil.runAfterBuild( context, initialBuildSuccess, () -> { Buildr.patchBuildYmlDependency( context.appDirectory, "org.realityforge.arez", version ); final Path archiveDir = WorkspaceUtil.getArchiveDir( context.workingDirectory, "sithtracker.after" ); buildAndRecordStatistics( context.appDirectory, archiveDir ); }, () -> { final Path dir = WorkspaceUtil.getArchiveDir( context.workingDirectory, "sithtracker.after" ); FileUtil.deleteDirIfExists( dir ); } ); } private static void buildAndRecordStatistics( @Nonnull final Path appDirectory, @Nonnull final Path archiveDir ) { WorkspaceUtil.customizeBuildr( appDirectory ); if ( !archiveDir.toFile().mkdirs() ) { final String message = "Error creating archive directory: " + archiveDir; Gir.messenger().error( message ); } // Perform the build Ruby.buildr( "clean", "package", "EXCLUDE_GWT_DEV_MODULE=true", "GWT=react4j-sithtracker" ); archiveBuildrOutput( archiveDir ); archiveStatistics( archiveDir ); } private static void archiveStatistics( @Nonnull final Path archiveDir ) { final OrderedProperties properties = new OrderedProperties(); properties.setProperty( "sithtracker.size", String.valueOf( getJsSize( archiveDir ) ) ); properties.setProperty( "sithtracker.gz.size", String.valueOf( getJsGzSize( archiveDir ) ) ); final Path statisticsFile = archiveDir.resolve( "statistics.properties" ); Gir.messenger().info( "Archiving statistics to " + statisticsFile + "." ); WorkspaceUtil.writeProperties( statisticsFile, properties ); } private static void archiveBuildrOutput( @Nonnull final Path archiveDir ) { final Path currentDirectory = FileUtil.getCurrentDirectory(); WorkspaceUtil.archiveDirectory( currentDirectory.resolve( "target/assets" ), archiveDir.resolve( "assets" ) ); WorkspaceUtil.archiveDirectory( currentDirectory .resolve( "target/gwt_compile_reports/react4j.sithtracker.SithTrackerProd" ), archiveDir.resolve( "compileReports" ) ); } private static long getJsSize( @Nonnull final Path archiveDir ) { return WorkspaceUtil.getFileSize( archiveDir.resolve( "assets" ) .resolve( "sithtracker" ) .resolve( "sithtracker.nocache.js" ) ); } private static long getJsGzSize( @Nonnull final Path archiveDir ) { return WorkspaceUtil.getFileSize( archiveDir.resolve( "assets" ) .resolve( "sithtracker" ) .resolve( "sithtracker.nocache.js.gz" ) ); } }
apache-2.0
asual/summer
modules/core/src/main/java/com/asual/summer/core/util/ClassUtils.java
3869
/* * 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.asual.summer.core.util; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import javax.inject.Named; import org.springframework.util.ReflectionUtils; /** * * @author Rostislav Hristov * */ @Named public class ClassUtils { public static Class<?> getClass(String clazz) throws ClassNotFoundException { return Class.forName(clazz); } public static Object cast(Object obj, String clazz) throws ClassNotFoundException { return Class.forName(clazz).cast(obj); } public static boolean isInstance(Object obj, String clazz) { try { return Class.forName(clazz).isInstance(obj); } catch (ClassNotFoundException e) { return false; } } public static Object newInstance(String clazz, Object... parameters) throws SecurityException, ClassNotFoundException { Class<?>[] classParameters = new Class[parameters == null ? 0 : parameters.length]; for (int i = 0; i < classParameters.length; i++) { classParameters[i] = parameters[i].getClass(); } Object instance = null; try { instance = Class.forName(clazz).getConstructor(classParameters).newInstance(parameters == null ? new Object[] {} : parameters.length); } catch (Exception e) { Constructor<?>[] constructors = Class.forName(clazz).getConstructors(); for (Constructor<?> constructor : constructors) { Class<?>[] types = constructor.getParameterTypes(); if (types.length == parameters.length) { Object[] params = new Object[parameters.length]; for (int i = 0; i < parameters.length; i++) { if (types[i] == boolean.class || types[i] == Boolean.class) { params[i] = Boolean.valueOf(parameters[i].toString()); } else if (types[i] == int.class || types[i] == Integer.class) { params[i] = Integer.valueOf(parameters[i].toString()); } else { params[i] = types[i].cast(parameters[i]); } } try { instance = constructor.newInstance(params); break; } catch (Exception ex) { continue; } } } } return instance; } public static Object invokeMethod(Object target, final String methodName, final Object[] parameters) { if (target != null) { final List<Method> matches = new ArrayList<Method>(); ReflectionUtils.doWithMethods(target.getClass(), new ReflectionUtils.MethodCallback() { public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { matches.add(method); } }, new ReflectionUtils.MethodFilter() { public boolean matches(Method method) { if (method.getName().equals(methodName)) { Class<?>[] types = method.getParameterTypes(); if (parameters == null && types.length == 0) { return true; } if (types.length != parameters.length) { return false; } for (int i = 0; i < types.length; i++) { if (!types[i].isInstance(parameters[i])) { return false; } } return true; } return false; } }); if (matches.size() > 0) { if (parameters == null) { return ReflectionUtils.invokeMethod(matches.get(0), target); } else { return ReflectionUtils.invokeMethod(matches.get(0), target, parameters); } } } return null; } }
apache-2.0
dump247/aws-sdk-java
aws-java-sdk-directory/src/main/java/com/amazonaws/services/directory/model/transform/DescribeTrustsRequestMarshaller.java
4276
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights * Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.directory.model.transform; import static com.amazonaws.util.StringUtils.UTF8; import static com.amazonaws.util.StringUtils.COMMA_SEPARATOR; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.Writer; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.List; import java.util.regex.Pattern; import com.amazonaws.AmazonClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.directory.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.BinaryUtils; import com.amazonaws.util.StringUtils; import com.amazonaws.util.IdempotentUtils; import com.amazonaws.util.StringInputStream; import com.amazonaws.util.json.*; /** * DescribeTrustsRequest Marshaller */ public class DescribeTrustsRequestMarshaller implements Marshaller<Request<DescribeTrustsRequest>, DescribeTrustsRequest> { public Request<DescribeTrustsRequest> marshall( DescribeTrustsRequest describeTrustsRequest) { if (describeTrustsRequest == null) { throw new AmazonClientException( "Invalid argument passed to marshall(...)"); } Request<DescribeTrustsRequest> request = new DefaultRequest<DescribeTrustsRequest>( describeTrustsRequest, "AWSDirectoryService"); request.addHeader("X-Amz-Target", "DirectoryService_20150416.DescribeTrusts"); request.setHttpMethod(HttpMethodName.POST); request.setResourcePath(""); try { final SdkJsonGenerator jsonGenerator = new SdkJsonGenerator(); jsonGenerator.writeStartObject(); if (describeTrustsRequest.getDirectoryId() != null) { jsonGenerator.writeFieldName("DirectoryId").writeValue( describeTrustsRequest.getDirectoryId()); } com.amazonaws.internal.SdkInternalList<String> trustIdsList = (com.amazonaws.internal.SdkInternalList<String>) describeTrustsRequest .getTrustIds(); if (!trustIdsList.isEmpty() || !trustIdsList.isAutoConstruct()) { jsonGenerator.writeFieldName("TrustIds"); jsonGenerator.writeStartArray(); for (String trustIdsListValue : trustIdsList) { if (trustIdsListValue != null) { jsonGenerator.writeValue(trustIdsListValue); } } jsonGenerator.writeEndArray(); } if (describeTrustsRequest.getNextToken() != null) { jsonGenerator.writeFieldName("NextToken").writeValue( describeTrustsRequest.getNextToken()); } if (describeTrustsRequest.getLimit() != null) { jsonGenerator.writeFieldName("Limit").writeValue( describeTrustsRequest.getLimit()); } jsonGenerator.writeEndObject(); byte[] content = jsonGenerator.getBytes(); request.setContent(new ByteArrayInputStream(content)); request.addHeader("Content-Length", Integer.toString(content.length)); request.addHeader("Content-Type", "application/x-amz-json-1.1"); } catch (Throwable t) { throw new AmazonClientException( "Unable to marshall request to JSON: " + t.getMessage(), t); } return request; } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-sagemaker/src/main/java/com/amazonaws/services/sagemaker/model/transform/ListStudioLifecycleConfigsRequestProtocolMarshaller.java
2858
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.sagemaker.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.sagemaker.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * ListStudioLifecycleConfigsRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class ListStudioLifecycleConfigsRequestProtocolMarshaller implements Marshaller<Request<ListStudioLifecycleConfigsRequest>, ListStudioLifecycleConfigsRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/") .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true) .operationIdentifier("SageMaker.ListStudioLifecycleConfigs").serviceName("AmazonSageMaker").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public ListStudioLifecycleConfigsRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<ListStudioLifecycleConfigsRequest> marshall(ListStudioLifecycleConfigsRequest listStudioLifecycleConfigsRequest) { if (listStudioLifecycleConfigsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<ListStudioLifecycleConfigsRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller( SDK_OPERATION_BINDING, listStudioLifecycleConfigsRequest); protocolMarshaller.startMarshalling(); ListStudioLifecycleConfigsRequestMarshaller.getInstance().marshall(listStudioLifecycleConfigsRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
xubaifuCode/TerrificWeather
app/src/main/java/com/example/andro/terrificweather/model/County.java
802
package com.example.andro.terrificweather.model; /** * Created by andro on 2016/1/20. */ public class County { private int id; private String countyName; private String countyCode; private int cityId; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCountyName() { return countyName; } public void setCountyName(String countyName) { this.countyName = countyName; } public String getCountyCode() { return countyCode; } public void setCountyCode(String countyCode) { this.countyCode = countyCode; } public int getCityId() { return cityId; } public void setCityId(int cityId) { this.cityId = cityId; } }
apache-2.0
intercom/intercom-java
intercom-java/src/main/java/io/intercom/api/HttpClient.java
10512
package io.intercom.api; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.io.CharStreams; import com.google.common.primitives.Ints; import com.google.common.primitives.Longs; import org.apache.commons.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ThreadLocalRandom; class HttpClient { private static final Logger logger = LoggerFactory.getLogger("intercom-java"); private static final String CLIENT_AGENT_DETAILS = clientAgentDetails(); private static final String USER_AGENT = Intercom.USER_AGENT; private static final String UTF_8 = "UTF-8"; private static final String APPLICATION_JSON = "application/json"; public static final String RATE_LIMIT_HEADER = "X-RateLimit-Limit"; public static final String RATE_LIMIT_REMAINING_HEADER = "X-RateLimit-Remaining"; public static final String RATE_LIMIT_RESET_HEADER = "X-RateLimit-Reset"; private static String clientAgentDetails() { final HashMap<String, String> map = Maps.newHashMap(); final ArrayList<String> propKeys = Lists.newArrayList( "os.arch", "os.name", "os.version", "user.language", "user.timezone", "java.class.version", "java.runtime.version", "java.version", "java.vm.name", "java.vm.vendor", "java.vm.version"); for (String propKey : propKeys) { map.put(propKey, System.getProperty(propKey)); } final ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { MapperSupport.objectMapper().disable(SerializationFeature.INDENT_OUTPUT).writeValue(baos, map); } catch (IOException e) { logger.warn(String.format("could not serialize client agent details [%s]", e.getMessage()), e); } return baos.toString(); } private final ObjectMapper objectMapper; private final URI uri; private final Map<String, String> headers; private final HttpConnectorSupplier connection = Intercom.getHttpConnectorSupplier(); public HttpClient(URI uri) { this(uri, Maps.<String, String>newHashMap()); } private HttpClient(URI uri, Map<String, String> headers) { this.uri = uri; this.headers = headers; this.objectMapper = MapperSupport.objectMapper(); } public <T> T get(Class<T> reqres) throws IntercomException { return get(getJavaType(reqres)); } <T> T get(JavaType responseType) throws IntercomException { return executeHttpMethod("GET", null, responseType); } public <T> T delete(Class<T> reqres) { return executeHttpMethod("DELETE", null, getJavaType(reqres)); } public <T, E> T put(Class<T> reqres, E entity) { headers.put("Content-Type", APPLICATION_JSON); return executeHttpMethod("PUT", (E) entity, getJavaType(reqres)); } public <T, E> T post(Class<T> reqres, E entity) { headers.put("Content-Type", APPLICATION_JSON); return executeHttpMethod("POST", entity, getJavaType(reqres)); } private <T, E> T executeHttpMethod(String method, E entity, JavaType responseType) { HttpURLConnection conn = null; try { conn = initializeConnection(uri, method); if(entity != null) { prepareRequestEntity(entity, conn); } return runRequest(uri, responseType, conn); } catch (IOException e) { return throwLocalException(e); } finally { IOUtils.disconnectQuietly(conn); } } private <T> JavaType getJavaType(Class<T> reqres) { return objectMapper.getTypeFactory().constructType(reqres); } // trick java with a dummy return private <T> T throwLocalException(IOException e) { throw new IntercomException(String.format("Local exception calling [%s]. Check connectivity and settings. [%s]", uri.toASCIIString(), e.getMessage()), e); } private void prepareRequestEntity(Object entity, HttpURLConnection conn) throws IOException { conn.setDoOutput(true); OutputStream stream = null; try { stream = conn.getOutputStream(); if (logger.isDebugEnabled()) { logger.info(String.format("api server request --\n%s\n-- ", objectMapper.writeValueAsString(entity))); } objectMapper.writeValue(stream, entity); } finally { IOUtils.closeQuietly(stream); } } private HttpURLConnection initializeConnection(URI uri, String method) throws IOException { HttpURLConnection conn = connection.connect(uri); conn.setRequestMethod(method); conn = prepareConnection(conn); conn = applyHeaders(conn); return conn; } private <T> T runRequest(URI uri, JavaType javaType, HttpURLConnection conn) throws IOException { conn.connect(); final int responseCode = conn.getResponseCode(); if (responseCode >= 200 && responseCode < 300) { return handleSuccess(javaType, conn, responseCode); } else { return handleError(uri, conn, responseCode); } } private <T> T handleError(URI uri, HttpURLConnection conn, int responseCode) throws IOException { ErrorCollection errors; try { errors = objectMapper.readValue(conn.getErrorStream(), ErrorCollection.class); } catch (IOException e) { errors = createUnprocessableErrorResponse(e); } if (logger.isDebugEnabled()) { logger.debug("error json follows --\n{}\n-- ", objectMapper.writeValueAsString(errors)); } return throwException(responseCode, errors, conn); } private <T> T handleSuccess(JavaType javaType, HttpURLConnection conn, int responseCode) throws IOException { if (shouldSkipResponseEntity(javaType, conn, responseCode)) { return null; } else { return readEntity(conn, responseCode, javaType); } } private boolean shouldSkipResponseEntity(JavaType javaType, HttpURLConnection conn, int responseCode) { return responseCode == 204 || Void.class.equals(javaType.getRawClass()); } private <T> T readEntity(HttpURLConnection conn, int responseCode, JavaType javaType) throws IOException { final InputStream entityStream = conn.getInputStream(); try { final String text = CharStreams.toString(new InputStreamReader(entityStream)); if (logger.isDebugEnabled()) { logger.debug("api server response status[{}] --\n{}\n-- ", responseCode, text); } if (text.isEmpty()) return null; return objectMapper.readValue(text, javaType); } finally { IOUtils.closeQuietly(entityStream); } } private <T> T throwException(int responseCode, ErrorCollection errors, HttpURLConnection conn) { // bind some well known response codes to exceptions if (responseCode == 403 || responseCode == 401) { throw new AuthorizationException(errors); } else if (responseCode == 429) { throw new RateLimitException(errors, Ints.tryParse(conn.getHeaderField(RATE_LIMIT_HEADER)), Ints.tryParse(conn.getHeaderField(RATE_LIMIT_REMAINING_HEADER)), Longs.tryParse(conn.getHeaderField(RATE_LIMIT_RESET_HEADER))); } else if (responseCode == 404) { throw new NotFoundException(errors); } else if (responseCode == 422) { throw new InvalidException(errors); } else if (responseCode == 400 || responseCode == 405 || responseCode == 406) { throw new ClientException(errors); } else if (responseCode == 500 || responseCode == 503) { throw new ServerException(errors); } else { throw new IntercomException(errors); } } private HttpURLConnection applyHeaders(HttpURLConnection conn) { for (Map.Entry<String, String> entry : createHeaders().entrySet()) { conn.setRequestProperty(entry.getKey(), entry.getValue()); } for (Map.Entry<String, String> entry : createAuthorizationHeaders().entrySet()) { conn.setRequestProperty(entry.getKey(), entry.getValue()); } return conn; } // todo: expose this config private HttpURLConnection prepareConnection(HttpURLConnection conn) { conn.setConnectTimeout(Intercom.getConnectionTimeout()); conn.setReadTimeout(Intercom.getRequestTimeout()); conn.setUseCaches(Intercom.isRequestUsingCaches()); return conn; } private Map<String, String> createAuthorizationHeaders() { headers.put("Authorization", "Basic " + generateAuthString(Intercom.getToken(),"")); return headers; } private String generateAuthString(String username, String password) { return Base64.encodeBase64String((username + ":" + password).getBytes()); } private Map<String, String> createHeaders() { headers.put("User-Agent", USER_AGENT); headers.put("X-Client-Platform-Details", CLIENT_AGENT_DETAILS); headers.put("Accept-Charset", UTF_8); headers.put("Accept", APPLICATION_JSON); return headers; } private ErrorCollection createUnprocessableErrorResponse(IOException e) { ErrorCollection errors; final long grepCode = getGrepCode(); final String msg = String.format("could not parse error response: [%s]", e.getLocalizedMessage()); logger.error(String.format("[%016x] %s", grepCode, msg), e); Error err = new Error("unprocessable_entity", String.format("%s logged with code [%016x]", msg, grepCode)); errors = new ErrorCollection(Lists.newArrayList(err)); return errors; } private long getGrepCode() { return ThreadLocalRandom.current().nextLong(); } }
apache-2.0
manuel-palacio/keycloak
testsuite/integration/src/test/java/org/keycloak/testsuite/federation/storage/ldap/LDAPGroupMapperSyncTest.java
18407
/* * 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.testsuite.federation.storage.ldap; import org.junit.Assert; import org.junit.Before; import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.rules.RuleChain; import org.junit.rules.TestRule; import org.junit.runners.MethodSorters; import org.keycloak.admin.client.Keycloak; import org.keycloak.common.util.MultivaluedHashMap; import org.keycloak.component.ComponentModel; import org.keycloak.models.Constants; import org.keycloak.representations.idm.SynchronizationResultRepresentation; import org.keycloak.storage.UserStorageProvider; import org.keycloak.storage.UserStorageProviderModel; import org.keycloak.storage.ldap.LDAPStorageProvider; import org.keycloak.storage.ldap.LDAPStorageProviderFactory; import org.keycloak.storage.ldap.LDAPUtils; import org.keycloak.storage.ldap.idm.model.LDAPObject; import org.keycloak.storage.ldap.mappers.membership.LDAPGroupMapperMode; import org.keycloak.storage.ldap.mappers.membership.MembershipType; import org.keycloak.storage.ldap.mappers.membership.group.GroupLDAPStorageMapper; import org.keycloak.storage.ldap.mappers.membership.group.GroupLDAPStorageMapperFactory; import org.keycloak.storage.ldap.mappers.membership.group.GroupMapperConfig; import org.keycloak.models.GroupModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.LDAPConstants; import org.keycloak.models.ModelException; import org.keycloak.models.RealmModel; import org.keycloak.models.UserModel; import org.keycloak.models.utils.KeycloakModelUtils; import org.keycloak.services.managers.RealmManager; import org.keycloak.storage.user.SynchronizationResult; import org.keycloak.testsuite.rule.KeycloakRule; import org.keycloak.testsuite.rule.LDAPRule; import javax.ws.rs.BadRequestException; import java.util.List; import java.util.Set; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MASTER; import static org.keycloak.models.AdminRoles.ADMIN; import static org.keycloak.testsuite.Constants.AUTH_SERVER_ROOT; /** * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a> */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class LDAPGroupMapperSyncTest { private static LDAPRule ldapRule = new LDAPRule(); private static ComponentModel ldapModel = null; private static String descriptionAttrName = null; private static KeycloakRule keycloakRule = new KeycloakRule(new KeycloakRule.KeycloakSetup() { @Override public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) { MultivaluedHashMap<String,String> ldapConfig = LDAPTestUtils.getLdapRuleConfig(ldapRule); ldapConfig.putSingle(LDAPConstants.SYNC_REGISTRATIONS, "true"); ldapConfig.putSingle(LDAPConstants.EDIT_MODE, UserStorageProvider.EditMode.WRITABLE.toString()); UserStorageProviderModel model = new UserStorageProviderModel(); model.setLastSync(0); model.setChangedSyncPeriod(-1); model.setFullSyncPeriod(-1); model.setName("test-ldap"); model.setPriority(0); model.setProviderId(LDAPStorageProviderFactory.PROVIDER_NAME); model.setConfig(ldapConfig); ldapModel = appRealm.addComponentModel(model); LDAPStorageProvider ldapFedProvider = LDAPTestUtils.getLdapProvider(session, ldapModel); descriptionAttrName = ldapFedProvider.getLdapIdentityStore().getConfig().isActiveDirectory() ? "displayName" : "description"; // Add group mapper LDAPTestUtils.addOrUpdateGroupMapper(appRealm, ldapModel, LDAPGroupMapperMode.LDAP_ONLY, descriptionAttrName); // Remove all LDAP groups LDAPTestUtils.removeAllLDAPGroups(session, appRealm, ldapModel, "groupsMapper"); // Add some groups for testing LDAPObject group1 = LDAPTestUtils.createLDAPGroup(manager.getSession(), appRealm, ldapModel, "group1", descriptionAttrName, "group1 - description"); LDAPObject group11 = LDAPTestUtils.createLDAPGroup(manager.getSession(), appRealm, ldapModel, "group11"); LDAPObject group12 = LDAPTestUtils.createLDAPGroup(manager.getSession(), appRealm, ldapModel, "group12", descriptionAttrName, "group12 - description"); LDAPUtils.addMember(ldapFedProvider, MembershipType.DN, LDAPConstants.MEMBER, group1, group11, false); LDAPUtils.addMember(ldapFedProvider, MembershipType.DN, LDAPConstants.MEMBER, group1, group12, true); } }); @ClassRule public static TestRule chain = RuleChain .outerRule(ldapRule) .around(keycloakRule); protected Keycloak adminClient; @Before public void before() { adminClient = Keycloak.getInstance(AUTH_SERVER_ROOT, MASTER, ADMIN, ADMIN, Constants.ADMIN_CLI_CLIENT_ID); KeycloakSession session = keycloakRule.startSession(); try { RealmModel realm = session.realms().getRealmByName("test"); List<GroupModel> kcGroups = realm.getTopLevelGroups(); for (GroupModel kcGroup : kcGroups) { realm.removeGroup(kcGroup); } } finally { keycloakRule.stopSession(session, true); } } @Test public void test01_syncNoPreserveGroupInheritance() throws Exception { KeycloakSession session = keycloakRule.startSession(); try { RealmModel realm = session.realms().getRealmByName("test"); ComponentModel mapperModel = LDAPTestUtils.getSubcomponentByName(realm,ldapModel, "groupsMapper"); LDAPStorageProvider ldapProvider = LDAPTestUtils.getLdapProvider(session, ldapModel); GroupLDAPStorageMapper groupMapper = LDAPTestUtils.getGroupMapper(mapperModel, ldapProvider, realm); // Add recursive group mapping to LDAP. Check that sync with preserve group inheritance will fail LDAPObject group1 = groupMapper.loadLDAPGroupByName("group1"); LDAPObject group12 = groupMapper.loadLDAPGroupByName("group12"); LDAPUtils.addMember(ldapProvider, MembershipType.DN, LDAPConstants.MEMBER, group12, group1, true); try { new GroupLDAPStorageMapperFactory().create(session, mapperModel).syncDataFromFederationProviderToKeycloak(mapperModel, ldapProvider, session, realm); Assert.fail("Not expected group sync to pass"); } catch (ModelException expected) { Assert.assertTrue(expected.getMessage().contains("Recursion detected")); } // Update group mapper to skip preserve inheritance and check it will pass now LDAPTestUtils.updateGroupMapperConfigOptions(mapperModel, GroupMapperConfig.PRESERVE_GROUP_INHERITANCE, "false"); realm.updateComponent(mapperModel); new GroupLDAPStorageMapperFactory().create(session, mapperModel).syncDataFromFederationProviderToKeycloak(mapperModel, ldapProvider, session, realm); // Assert groups are imported to keycloak. All are at top level GroupModel kcGroup1 = KeycloakModelUtils.findGroupByPath(realm, "/group1"); GroupModel kcGroup11 = KeycloakModelUtils.findGroupByPath(realm, "/group11"); GroupModel kcGroup12 = KeycloakModelUtils.findGroupByPath(realm, "/group12"); Assert.assertEquals(0, kcGroup1.getSubGroups().size()); Assert.assertEquals("group1 - description", kcGroup1.getFirstAttribute(descriptionAttrName)); Assert.assertNull(kcGroup11.getFirstAttribute(descriptionAttrName)); Assert.assertEquals("group12 - description", kcGroup12.getFirstAttribute(descriptionAttrName)); // Cleanup - remove recursive mapping in LDAP LDAPUtils.deleteMember(ldapProvider, MembershipType.DN, LDAPConstants.MEMBER, group12, group1, true); } finally { keycloakRule.stopSession(session, false); } } @Test public void testSyncRestAPI() { KeycloakSession session = keycloakRule.startSession(); try { RealmModel realm = session.realms().getRealmByName("test"); ComponentModel mapperModel = LDAPTestUtils.getSubcomponentByName(realm,ldapModel, "groupsMapper"); try { // testing KEYCLOAK-3980 which threw an NPE because I was looking up the factory wrong. SynchronizationResultRepresentation syncResultRep = adminClient.realm("test").userStorage().syncMapperData(ldapModel.getId(), mapperModel.getId(), "error"); Assert.fail("Should throw 400"); } catch (BadRequestException e) { } } finally { keycloakRule.stopSession(session, false); } } @Test public void test02_syncWithGroupInheritance() throws Exception { KeycloakSession session = keycloakRule.startSession(); try { RealmModel realm = session.realms().getRealmByName("test"); ComponentModel mapperModel = LDAPTestUtils.getSubcomponentByName(realm,ldapModel, "groupsMapper"); LDAPStorageProvider ldapProvider = LDAPTestUtils.getLdapProvider(session, ldapModel); GroupLDAPStorageMapper groupMapper = LDAPTestUtils.getGroupMapper(mapperModel, ldapProvider, realm); // Sync groups with inheritance SynchronizationResult syncResult = new GroupLDAPStorageMapperFactory().create(session, mapperModel).syncDataFromFederationProviderToKeycloak(mapperModel, ldapProvider, session, realm); LDAPTestUtils.assertSyncEquals(syncResult, 3, 0, 0, 0); // Assert groups are imported to keycloak including their inheritance from LDAP GroupModel kcGroup1 = KeycloakModelUtils.findGroupByPath(realm, "/group1"); Assert.assertNull(KeycloakModelUtils.findGroupByPath(realm, "/group11")); Assert.assertNull(KeycloakModelUtils.findGroupByPath(realm, "/group12")); GroupModel kcGroup11 = KeycloakModelUtils.findGroupByPath(realm, "/group1/group11"); GroupModel kcGroup12 = KeycloakModelUtils.findGroupByPath(realm, "/group1/group12"); Assert.assertEquals(2, kcGroup1.getSubGroups().size()); Assert.assertEquals("group1 - description", kcGroup1.getFirstAttribute(descriptionAttrName)); Assert.assertNull(kcGroup11.getFirstAttribute(descriptionAttrName)); Assert.assertEquals("group12 - description", kcGroup12.getFirstAttribute(descriptionAttrName)); // Update description attributes in LDAP LDAPObject group1 = groupMapper.loadLDAPGroupByName("group1"); group1.setSingleAttribute(descriptionAttrName, "group1 - changed description"); ldapProvider.getLdapIdentityStore().update(group1); LDAPObject group12 = groupMapper.loadLDAPGroupByName("group12"); group12.setAttribute(descriptionAttrName, null); ldapProvider.getLdapIdentityStore().update(group12); // Sync and assert groups updated syncResult = new GroupLDAPStorageMapperFactory().create(session, mapperModel).syncDataFromFederationProviderToKeycloak(mapperModel, ldapProvider, session, realm); LDAPTestUtils.assertSyncEquals(syncResult, 0, 3, 0, 0); // Assert attributes changed in keycloak kcGroup1 = KeycloakModelUtils.findGroupByPath(realm, "/group1"); kcGroup12 = KeycloakModelUtils.findGroupByPath(realm, "/group1/group12"); Assert.assertEquals("group1 - changed description", kcGroup1.getFirstAttribute(descriptionAttrName)); Assert.assertNull(kcGroup12.getFirstAttribute(descriptionAttrName)); } finally { keycloakRule.stopSession(session, false); } } @Test public void test03_syncWithDropNonExistingGroups() throws Exception { KeycloakSession session = keycloakRule.startSession(); try { RealmModel realm = session.realms().getRealmByName("test"); ComponentModel mapperModel = LDAPTestUtils.getSubcomponentByName(realm,ldapModel, "groupsMapper"); LDAPStorageProvider ldapProvider = LDAPTestUtils.getLdapProvider(session, ldapModel); // Sync groups with inheritance SynchronizationResult syncResult = new GroupLDAPStorageMapperFactory().create(session, mapperModel).syncDataFromFederationProviderToKeycloak(mapperModel, ldapProvider, session, realm); LDAPTestUtils.assertSyncEquals(syncResult, 3, 0, 0, 0); // Assert groups are imported to keycloak including their inheritance from LDAP GroupModel kcGroup1 = KeycloakModelUtils.findGroupByPath(realm, "/group1"); Assert.assertNotNull(KeycloakModelUtils.findGroupByPath(realm, "/group1/group11")); Assert.assertNotNull(KeycloakModelUtils.findGroupByPath(realm, "/group1/group12")); Assert.assertEquals(2, kcGroup1.getSubGroups().size()); // Create some new groups in keycloak GroupModel model1 = realm.createGroup("model1"); realm.moveGroup(model1, null); GroupModel model2 = realm.createGroup("model2"); realm.moveGroup(model2, kcGroup1); // Sync groups again from LDAP. Nothing deleted syncResult = new GroupLDAPStorageMapperFactory().create(session, mapperModel).syncDataFromFederationProviderToKeycloak(mapperModel, ldapProvider, session, realm); LDAPTestUtils.assertSyncEquals(syncResult, 0, 3, 0, 0); Assert.assertNotNull(KeycloakModelUtils.findGroupByPath(realm, "/group1/group11")); Assert.assertNotNull(KeycloakModelUtils.findGroupByPath(realm, "/group1/group12")); Assert.assertNotNull(KeycloakModelUtils.findGroupByPath(realm, "/model1")); Assert.assertNotNull(KeycloakModelUtils.findGroupByPath(realm, "/group1/model2")); // Update group mapper to drop non-existing groups during sync LDAPTestUtils.updateGroupMapperConfigOptions(mapperModel, GroupMapperConfig.DROP_NON_EXISTING_GROUPS_DURING_SYNC, "true"); realm.updateComponent(mapperModel); // Sync groups again from LDAP. Assert LDAP non-existing groups deleted syncResult = new GroupLDAPStorageMapperFactory().create(session, mapperModel).syncDataFromFederationProviderToKeycloak(mapperModel, ldapProvider, session, realm); Assert.assertEquals(3, syncResult.getUpdated()); Assert.assertTrue(syncResult.getRemoved() == 2); // Sync and assert groups updated Assert.assertNotNull(KeycloakModelUtils.findGroupByPath(realm, "/group1/group11")); Assert.assertNotNull(KeycloakModelUtils.findGroupByPath(realm, "/group1/group12")); Assert.assertNull(KeycloakModelUtils.findGroupByPath(realm, "/model1")); Assert.assertNull(KeycloakModelUtils.findGroupByPath(realm, "/group1/model2")); } finally { keycloakRule.stopSession(session, false); } } @Test public void test04_syncNoPreserveGroupInheritanceWithLazySync() throws Exception { KeycloakSession session = keycloakRule.startSession(); try { RealmModel realm = session.realms().getRealmByName("test"); ComponentModel mapperModel = LDAPTestUtils.getSubcomponentByName(realm,ldapModel, "groupsMapper"); LDAPStorageProvider ldapProvider = LDAPTestUtils.getLdapProvider(session, ldapModel); GroupLDAPStorageMapper groupMapper = LDAPTestUtils.getGroupMapper(mapperModel, ldapProvider, realm); // Update group mapper to skip preserve inheritance LDAPTestUtils.updateGroupMapperConfigOptions(mapperModel, GroupMapperConfig.PRESERVE_GROUP_INHERITANCE, "false"); realm.updateComponent(mapperModel); // Add user to LDAP and put him as member of group11 LDAPTestUtils.removeAllLDAPUsers(ldapProvider, realm); LDAPObject johnLdap = LDAPTestUtils.addLDAPUser(ldapProvider, realm, "johnkeycloak", "John", "Doe", "john@email.org", null, "1234"); LDAPTestUtils.updateLDAPPassword(ldapProvider, johnLdap, "Password1"); groupMapper.addGroupMappingInLDAP("group11", johnLdap); // Assert groups not yet imported to Keycloak DB Assert.assertNull(KeycloakModelUtils.findGroupByPath(realm, "/group1")); Assert.assertNull(KeycloakModelUtils.findGroupByPath(realm, "/group11")); Assert.assertNull(KeycloakModelUtils.findGroupByPath(realm, "/group12")); // Load user from LDAP to Keycloak DB UserModel john = session.users().getUserByUsername("johnkeycloak", realm); Set<GroupModel> johnGroups = john.getGroups(); // Assert just those groups, which john was memberOf exists because they were lazily created GroupModel group1 = KeycloakModelUtils.findGroupByPath(realm, "/group1"); GroupModel group11 = KeycloakModelUtils.findGroupByPath(realm, "/group11"); GroupModel group12 = KeycloakModelUtils.findGroupByPath(realm, "/group12"); Assert.assertNull(group1); Assert.assertNotNull(group11); Assert.assertNull(group12); Assert.assertEquals(1, johnGroups.size()); Assert.assertTrue(johnGroups.contains(group11)); // Delete group mapping john.leaveGroup(group11); } finally { keycloakRule.stopSession(session, false); } } }
apache-2.0
raphaelning/resteasy-client-android
jaxrs/eagledns/src/main/java/se/unlogic/standardutils/arrays/ArrayUtils.java
855
/******************************************************************************* * Copyright (c) 2010 Robert "Unlogic" Olofsson (unlogic@unlogic.se). * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-3.0-standalone.html ******************************************************************************/ package se.unlogic.standardutils.arrays; public class ArrayUtils { public static <T> T[] toArray(T... values) { return values; } public static boolean isEmpty(Object[] array) { if(array == null || array.length == 0){ return true; } for(Object value : array){ if(value != null){ return false; } } return true; } }
apache-2.0
codesoftware/NSIGEMCO
src/main/java/co/com/codesoftware/server/nsigemco/ObtieneProductosCategoria.java
2555
package co.com.codesoftware.server.nsigemco; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Clase Java para obtieneProductosCategoria complex type. * * <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase. * * <pre> * &lt;complexType name="obtieneProductosCategoria"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="arg0" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="arg1" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="arg2" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "obtieneProductosCategoria", propOrder = { "arg0", "arg1", "arg2" }) public class ObtieneProductosCategoria { protected Integer arg0; protected String arg1; protected String arg2; /** * Obtiene el valor de la propiedad arg0. * * @return * possible object is * {@link Integer } * */ public Integer getArg0() { return arg0; } /** * Define el valor de la propiedad arg0. * * @param value * allowed object is * {@link Integer } * */ public void setArg0(Integer value) { this.arg0 = value; } /** * Obtiene el valor de la propiedad arg1. * * @return * possible object is * {@link String } * */ public String getArg1() { return arg1; } /** * Define el valor de la propiedad arg1. * * @param value * allowed object is * {@link String } * */ public void setArg1(String value) { this.arg1 = value; } /** * Obtiene el valor de la propiedad arg2. * * @return * possible object is * {@link String } * */ public String getArg2() { return arg2; } /** * Define el valor de la propiedad arg2. * * @param value * allowed object is * {@link String } * */ public void setArg2(String value) { this.arg2 = value; } }
apache-2.0
jaxio/celerio
celerio-engine/src/main/java/com/jaxio/celerio/model/relation/CompositeRelation.java
2458
/* * Copyright 2015 JAXIO http://www.jaxio.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.jaxio.celerio.model.relation; import com.jaxio.celerio.model.Attribute; import com.jaxio.celerio.model.Entity; import com.jaxio.celerio.model.Relation; import com.jaxio.celerio.support.Namer; import lombok.Getter; import java.util.List; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Lists.newArrayList; import static java.util.Collections.unmodifiableList; @Getter public abstract class CompositeRelation extends AbstractRelation { private List<Attribute> fromAttributes; private Entity fromEntity; private Entity toEntity; private List<Attribute> toAttributes; private Namer from; private Namer to; private List<Relation> relations; public CompositeRelation(Namer fromNamer, Namer toNamer, List<Attribute> fromAttributes, Entity fromEntity, Entity toEntity, List<Attribute> toAttributes) { this.from = checkNotNull(fromNamer); this.to = checkNotNull(toNamer); this.fromAttributes = checkNotNull(fromAttributes); this.fromEntity = checkNotNull(fromEntity); this.toEntity = checkNotNull(toEntity); this.toAttributes = checkNotNull(toAttributes); this.relations = unmodifiableList(newArrayList((Relation) this)); } @Override final public boolean isSimple() { return false; } @Override final public boolean isComposite() { return true; } @Override public Attribute getFromAttribute() { return getFromAttributes().get(0); // we tolerate calling it as it is needed for cascade stuff } @Override public Attribute getToAttribute() { throw new IllegalStateException("do not call it please"); } @Override public String toString() { return "// relation involving composite FK"; } }
apache-2.0
x-meta/xworker
xworker_draw2d/src/main/java/xworker/eclipse/zest/model/Node.java
3002
package xworker.eclipse.zest.model; import org.eclipse.draw2d.Label; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.Image; import org.eclipse.zest.core.widgets.GraphNode; import org.eclipse.zest.core.widgets.IContainer; import org.xmeta.ActionContext; import org.xmeta.Thing; import xworker.util.UtilData; public class Node { public static Object create(ActionContext actionContext){ Thing self = (Thing) actionContext.get("self"); IContainer parent = (IContainer) actionContext.get("parent"); int style = Constants.getNodeStyle(self.getString("style")); GraphNode node = new GraphNode(parent, style); init(self, node, actionContext); actionContext.getScope(0).put(self.getMetadata().getName(), node); return node; } public static void init(Thing self, GraphNode node, ActionContext actionContext){ node.setData("thing", self); node.setData("actionContext", actionContext); node.setText(self.getMetadata().getLabel()); Color backgroundColor = UtilData.getObject(self.getString("backgroundColor"), actionContext, Color.class); if(backgroundColor != null){ node.setBackgroundColor(backgroundColor); } Color borderColor = UtilData.getObject(self.getString("borderColor"), actionContext, Color.class); if(borderColor != null){ node.setBorderColor(borderColor); } Color borderHighlightColor = UtilData.getObject(self.getString("borderHighlightColor"), actionContext, Color.class); if(borderHighlightColor != null){ node.setBorderHighlightColor(borderHighlightColor); } Color foregroundColor = UtilData.getObject(self.getString("foregroundColor"), actionContext, Color.class); if(foregroundColor != null){ node.setForegroundColor(foregroundColor); } Color highlightColor = UtilData.getObject(self.getString("highlightColor"), actionContext, Color.class); if(highlightColor != null){ node.setHighlightColor(highlightColor); } if(self.getStringBlankAsNull("borderWidth") != null){ node.setBorderWidth(self.getInt("borderWidth")); } if(self.getStringBlankAsNull("cacheLabel") != null){ node.setCacheLabel(self.getBoolean("cacheLabel")); } Font font = UtilData.getObject(self.getString("font"), actionContext, Font.class); if(font != null){ node.setFont(font); } Image image = UtilData.getObject(self.getString("image"), actionContext, Image.class); if(image != null){ node.setImage(image); } if(self.getStringBlankAsNull("x") != null && self.getStringBlankAsNull("y") != null){ node.setLocation(self.getDouble("x"), self.getDouble("y")); } if(self.getStringBlankAsNull("width") != null && self.getStringBlankAsNull("height") != null){ node.setSize(self.getDouble("width"), self.getDouble("height")); } if(self.getStringBlankAsNull("tooltip") != null){ node.setTooltip(new Label(self.getString("tooltip"))); } node.setVisible(self.getBoolean("visible")); } }
apache-2.0
ctripcorp/x-pipe
redis/redis-proxy/src/main/java/com/ctrip/xpipe/redis/proxy/model/TunnelIdentity.java
1289
package com.ctrip.xpipe.redis.proxy.model; import com.ctrip.xpipe.utils.ChannelUtil; import io.netty.channel.Channel; /** * @author chen.zhu * <p> * Jul 25, 2018 */ public class TunnelIdentity { private Channel frontend; private Channel backend; private String destination; private String source; public TunnelIdentity(Channel frontend, String destination, String source) { this.frontend = frontend; this.destination = destination; this.source = source; } public Channel getFrontend() { return frontend; } public TunnelIdentity setFrontend(Channel frontend) { this.frontend = frontend; return this; } public Channel getBackend() { return backend; } public TunnelIdentity setBackend(Channel backend) { this.backend = backend; return this; } public String getDestination() { return destination; } public TunnelIdentity setDestination(String destination) { this.destination = destination; return this; } @Override public String toString() { return String.format("%s-%s-%s-%s", source, ChannelUtil.getRemoteAddr(frontend), ChannelUtil.getDesc(backend), destination); } }
apache-2.0
codemonkeykings/study
spring/src/main/java/spring/aop/aopinterface/BaseAroundAdvice.java
1239
package spring.aop.aopinterface; import java.lang.reflect.Method; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; /** * Ò»¾ä»°¹¦ÄܼòÊö. * * @author Zhang.Ge * @version v1.0 2017Äê4ÔÂ12ÈÕ ÉÏÎç11:25:43 */ public class BaseAroundAdvice implements MethodInterceptor { @Override public Object invoke(MethodInvocation invocation) throws Throwable { System.out.println("ÕýÔÚ½øÈëaround advice"); // µ÷ÓÃÄ¿±ê·½·¨Ö®Ç°Ö´Ðе͝×÷ System.out.println("µ÷Ó÷½·¨Ö®Ç°: Ö´ÐУ¡\n"); // µ÷Ó÷½·¨µÄ²ÎÊý Object[] args = invocation.getArguments(); // µ÷Óõķ½·¨ Method method = invocation.getMethod(); // »ñȡĿ±ê¶ÔÏó Object target = invocation.getThis(); // Ö´ÐÐÍê·½·¨µÄ·µ»ØÖµ£ºµ÷ÓÃproceed()·½·¨£¬¾Í»á´¥·¢ÇÐÈëµã·½·¨Ö´ÐÐ Object returnValue = invocation.proceed(); System.out.println("===========½áÊø½øÈëaround»·ÈÆ·½·¨£¡=========== \n"); System.out.println("Êä³ö£º" + args[0] + ";" + method + ";" + target + ";" + returnValue + "\n"); System.out.println("µ÷Ó÷½·¨½áÊø£ºÖ®ºóÖ´ÐУ¡\n"); return returnValue; } }
apache-2.0
cqse/test-analyzer
test-analyzer-extensions/src/test/resources/de/tum/in/niedermr/ta/extensions/testing/frameworks/testng/detector/IgnoredTestNgTestClass2.java
202
package de.tum.in.niedermr.ta.extensions.testing.frameworks.testng.detector; public class IgnoredTestNgTestClass2 { @org.testng.annotations.Test(enabled = false) public void testX() { // NOP } }
apache-2.0
alvindaiyan/cassava
src/test/java/com/cassava/core/dao/objecteample/ObjectExample.java
1249
package com.cassava.core.dao.objecteample; import com.cassava.annotations.Column; import com.cassava.annotations.ColumnFamily; import com.cassava.annotations.Key; import com.cassava.core.model.IDataTransferObject; import com.google.gson.annotations.Expose; import java.util.UUID; /** * Created by yan.dai on 12/11/2015. */ @ColumnFamily public class ObjectExample implements IDataTransferObject { @Key @Column @Expose private UUID id; @Column @Expose private String state; @Column @Expose private String description; @Column @Expose private HelperExample example; @Override public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public HelperExample getExample() { return example; } public void setExample(HelperExample example) { this.example = example; } }
apache-2.0
alibaba/tamper
src/main/java/com/alibaba/tamper/process/convertor/CommonAndCommonConvertor.java
8903
package com.alibaba.tamper.process.convertor; import java.math.BigDecimal; import java.math.BigInteger; import com.alibaba.tamper.core.BeanMappingException; /** * common <-> common对象之间的转化 * * <pre> * common对象范围:8种Primitive和对应的Java类型,BigDecimal, BigInteger * * </pre> * * @author jianghang 2011-6-14 下午10:09:09 */ public class CommonAndCommonConvertor { /** * common <-> common对象的转化 */ public static class CommonToCommon extends AbastactConvertor { private static final Integer ZERO = new Integer(0); private static final Integer ONE = new Integer(1); // Number数据处理 private Object toCommon(Class srcClass, Class targetClass, Number value) { // 相同类型,直接返回 if (targetClass.equals(value.getClass())) { return value; } // Integer if (targetClass == Integer.class || targetClass == int.class) { long longValue = value.longValue(); if (longValue > Integer.MAX_VALUE) { throw new BeanMappingException(srcClass.getName() + " value '" + value + "' is too large for " + targetClass.getName()); } if (longValue < Integer.MIN_VALUE) { throw new BeanMappingException(srcClass.getName() + " value '" + value + "' is too small " + targetClass.getName()); } return Integer.valueOf(value.intValue()); } // Long if (targetClass == Long.class || targetClass == long.class) { return Long.valueOf(value.longValue()); } // Boolean if (targetClass == Boolean.class || targetClass == boolean.class) { long longValue = value.longValue(); return Boolean.valueOf(longValue > 0 ? true : false); } // Byte if (targetClass == Byte.class || targetClass == byte.class) { long longValue = value.longValue(); if (longValue > Byte.MAX_VALUE) { throw new BeanMappingException(srcClass.getName() + " value '" + value + "' is too large for " + targetClass.getName()); } if (longValue < Byte.MIN_VALUE) { throw new BeanMappingException(srcClass.getName() + " value '" + value + "' is too small " + targetClass.getName()); } return Byte.valueOf(value.byteValue()); } // Double if (targetClass == Double.class || targetClass == double.class) { return Double.valueOf(value.doubleValue()); } // BigDecimal if (targetClass == BigDecimal.class) { if (value instanceof Float || value instanceof Double) { return new BigDecimal(value.toString()); } else if (value instanceof BigInteger) { return new BigDecimal((BigInteger) value); } else { return BigDecimal.valueOf(value.longValue()); } } // BigInteger if (targetClass == BigInteger.class) { if (value instanceof BigDecimal) { return ((BigDecimal) value).toBigInteger(); } else { return BigInteger.valueOf(value.longValue()); } } // Short if (targetClass == Short.class || targetClass == short.class) { long longValue = value.longValue(); if (longValue > Short.MAX_VALUE) { throw new BeanMappingException(srcClass.getName() + " value '" + value + "' is too large for " + targetClass.getName()); } if (longValue < Short.MIN_VALUE) { throw new BeanMappingException(srcClass.getName() + " value '" + value + "' is too small " + targetClass.getName()); } return Short.valueOf(value.shortValue()); } // Float if (targetClass == Float.class || targetClass == float.class) { double doubleValue = value.doubleValue(); if (doubleValue > Float.MAX_VALUE) { throw new BeanMappingException(srcClass.getName() + " value '" + value + "' is too large for " + targetClass.getName()); } if (doubleValue < Float.MIN_VALUE) { throw new BeanMappingException(srcClass.getName() + " value '" + value + "' is too small for " + targetClass.getName()); } return Float.valueOf(value.floatValue()); } // Character if (targetClass == Character.class || targetClass == char.class) { long longValue = value.longValue(); // Character没有很明显的值上下边界,直接依赖于jvm的转型 return Character.valueOf((char) longValue); } throw new BeanMappingException("Unsupported convert: [" + srcClass.getName() + "," + targetClass.getName() + "]"); } // BigDecimal数据处理 private Object toCommon(Class srcClass, Class targetClass, BigDecimal value) { if (targetClass == srcClass) { return value; } if (targetClass == BigInteger.class) { return value.toBigInteger(); } // 其他类型的处理,先转化为String,再转到对应的目标对象 StringAndCommonConvertor.StringToCommon strConvertor = new StringAndCommonConvertor.StringToCommon(); return strConvertor.convert(value.toPlainString(), targetClass); } // BigInteger数据处理 private Object toCommon(Class srcClass, Class targetClass, BigInteger value) { if (targetClass == srcClass) { return value; } if (targetClass == BigDecimal.class) { return new BigDecimal((BigInteger) value); } // 其他类型的处理,先转化为String,再转到对应的目标对象 StringAndCommonConvertor.StringToCommon strConvertor = new StringAndCommonConvertor.StringToCommon(); return strConvertor.convert(value.toString(), targetClass); } @Override public Object convert(Object src, Class targetClass) { Class srcClass = src.getClass(); if (srcClass == Integer.class || srcClass == int.class) { return toCommon(srcClass, targetClass, (Integer) src); } if (srcClass == Long.class || srcClass == long.class) { return toCommon(srcClass, targetClass, (Long) src); } if (srcClass == Boolean.class || srcClass == boolean.class) { Boolean boolValue = (Boolean) src; return toCommon(srcClass, targetClass, boolValue.booleanValue() ? ONE : ZERO); } if (srcClass == Byte.class || srcClass == byte.class) { return toCommon(Double.class, targetClass, (Byte) src); } if (srcClass == Double.class || srcClass == double.class) { return toCommon(srcClass, targetClass, (Double) src); } if (srcClass == BigDecimal.class) { return toCommon(srcClass, targetClass, (BigDecimal) src); } if (srcClass == BigInteger.class) { return toCommon(srcClass, targetClass, (BigInteger) src); } if (srcClass == Float.class || srcClass == float.class) { return toCommon(srcClass, targetClass, (Float) src); } if (srcClass == Short.class || srcClass == short.class) { return toCommon(srcClass, targetClass, (Short) src); } if (srcClass == Character.class || srcClass == char.class) { Character charvalue = (Character) src; return toCommon(srcClass, targetClass, Integer.valueOf((int) charvalue)); } throw new BeanMappingException("Unsupported convert: [" + src + "," + targetClass.getName() + "]"); } } }
apache-2.0
sbower/kuali-rice-1
ldap/src/main/java/org/kuali/rice/kim/ldap/EntityTypeContactInfoDefaultMapper.java
4033
/* * Copyright 2010 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.kim.ldap; import org.springframework.ldap.core.ContextMapper; import org.springframework.ldap.core.DirContextOperations; import org.springframework.ldap.core.support.AbstractContextMapper; import org.kuali.rice.kim.api.identity.address.EntityAddress; import org.kuali.rice.kim.api.identity.email.EntityEmail; import org.kuali.rice.kim.api.identity.type.EntityTypeContactInfo; import org.kuali.rice.kim.api.identity.type.EntityTypeContactInfoDefault; import org.kuali.rice.kim.util.Constants; /** * * @author Kuali Rice Team (rice.collab@kuali.org) */ public class EntityTypeContactInfoDefaultMapper extends AbstractContextMapper { private Constants constants; private EntityAddressMapper addressMapper; private EntityPhoneMapper phoneMapper; private EntityEmailMapper emailMapper; public EntityTypeContactInfoDefault.Builder mapFromContext(DirContextOperations context) { return (EntityTypeContactInfoDefault.Builder) doMapFromContext(context); } public Object doMapFromContext(DirContextOperations context) { final EntityTypeContactInfoDefault.Builder retval = EntityTypeContactInfoDefault.Builder.create(); retval.setDefaultAddress(getAddressMapper().mapFromContext(context)); retval.setDefaultPhoneNumber(getPhoneMapper().mapFromContext(context)); retval.setDefaultEmailAddress(getEmailMapper().mapFromContext(context)); retval.setEntityTypeCode(getConstants().getPersonEntityTypeCode()); // debug("Created Entity Type with code ", retval.getEntityTypeCode()); return retval; } /** * Gets the value of constants * * @return the value of constants */ public final Constants getConstants() { return this.constants; } /** * Sets the value of constants * * @param argConstants Value to assign to this.constants */ public final void setConstants(final Constants argConstants) { this.constants = argConstants; } /** * Gets the value of addressMapper * * @return the value of addressMapper */ public final EntityAddressMapper getAddressMapper() { return this.addressMapper; } /** * Sets the value of addressMapper * * @param argAddressMapper Value to assign to this.addressMapper */ public final void setAddressMapper(final EntityAddressMapper argAddressMapper) { this.addressMapper = argAddressMapper; } /** * Gets the value of phoneMapper * * @return the value of phoneMapper */ public final EntityPhoneMapper getPhoneMapper() { return this.phoneMapper; } /** * Sets the value of phoneMapper * * @param argPhoneMapper Value to assign to this.phoneMapper */ public final void setPhoneMapper(final EntityPhoneMapper argPhoneMapper) { this.phoneMapper = argPhoneMapper; } /** * Gets the value of emailMapper * * @return the value of emailMapper */ public final EntityEmailMapper getEmailMapper() { return this.emailMapper; } /** * Sets the value of emailMapper * * @param argEmailMapper Value to assign to this.emailMapper */ public final void setEmailMapper(final EntityEmailMapper argEmailMapper) { this.emailMapper = argEmailMapper; } }
apache-2.0
eFaps/eFaps-WebApp
src/main/java/org/efaps/ui/wicket/models/field/IHidden.java
1298
/* * Copyright 2003 - 2016 The eFaps Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.efaps.ui.wicket.models.field; import org.apache.wicket.Component; import org.efaps.util.EFapsException; /** * TODO comment! * * @author The eFaps Team */ public interface IHidden { /** * Sets the added. * * @param _true the true * @return the i hidden */ IHidden setAdded(boolean _true); /** * Checks if is added. * * @return true, if is added */ boolean isAdded(); /** * Gets the component. * * @param _wicketId the wicket id * @return the component * @throws EFapsException on error */ Component getComponent(final String _wicketId) throws EFapsException; }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-lightsail/src/main/java/com/amazonaws/services/lightsail/model/transform/TagMarshaller.java
2108
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.lightsail.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.lightsail.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * TagMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class TagMarshaller { private static final MarshallingInfo<String> KEY_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("key").build(); private static final MarshallingInfo<String> VALUE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("value").build(); private static final TagMarshaller instance = new TagMarshaller(); public static TagMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(Tag tag, ProtocolMarshaller protocolMarshaller) { if (tag == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(tag.getKey(), KEY_BINDING); protocolMarshaller.marshall(tag.getValue(), VALUE_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
adamrduffy/trinidad-1.0.x
trinidad-api/src/main/java-templates/org/apache/myfaces/trinidad/component/UIXPollTemplate.java
2145
/* * 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.myfaces.trinidad.component; import javax.faces.el.MethodBinding; import javax.faces.event.AbortProcessingException; import javax.faces.event.FacesEvent; import javax.faces.event.PhaseId; import org.apache.myfaces.trinidad.event.PollEvent; /** * Base class for Poll component. * @version $Name: $ ($Revision: 518820 $) $Date: 2007-03-16 01:02:36 +0000 (Fri, 16 Mar 2007) $ */ abstract public class UIXPollTemplate extends UIXComponentBase { /**/ // Abstract methods implemented by code gen /**/ abstract public boolean isImmediate(); /**/ abstract public MethodBinding getPollListener(); // // Abstract methods implemented by subclass. @Override public void broadcast(FacesEvent event) throws AbortProcessingException { // Perform standard superclass processing super.broadcast(event); // Notify the specified Poll listener method (if any) if (event instanceof PollEvent) { broadcastToMethodBinding(event, getPollListener()); } } @Override public void queueEvent(FacesEvent e) { if ((e instanceof PollEvent) && (e.getSource() == this)) { if (isImmediate()) { e.setPhaseId(PhaseId.ANY_PHASE); } else { e.setPhaseId(PhaseId.INVOKE_APPLICATION); } } super.queueEvent(e); } }
apache-2.0
massx1/syncope
core/persistence-jpa/src/main/java/org/apache/syncope/core/persistence/jpa/dao/JPAExternalResourceDAO.java
9821
/* * 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.syncope.core.persistence.jpa.dao; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.persistence.NoResultException; import javax.persistence.TypedQuery; import org.apache.syncope.common.lib.types.IntMappingType; import org.apache.syncope.common.lib.types.PolicyType; import org.apache.syncope.common.lib.types.TaskType; import org.apache.syncope.core.persistence.api.dao.ExternalResourceDAO; import org.apache.syncope.core.persistence.api.dao.NotFoundException; import org.apache.syncope.core.persistence.api.dao.PolicyDAO; import org.apache.syncope.core.persistence.api.dao.RoleDAO; import org.apache.syncope.core.persistence.api.dao.TaskDAO; import org.apache.syncope.core.persistence.api.dao.UserDAO; import org.apache.syncope.core.persistence.api.entity.AccountPolicy; import org.apache.syncope.core.persistence.api.entity.ExternalResource; import org.apache.syncope.core.persistence.api.entity.Mapping; import org.apache.syncope.core.persistence.api.entity.MappingItem; import org.apache.syncope.core.persistence.api.entity.Policy; import org.apache.syncope.core.persistence.api.entity.role.Role; import org.apache.syncope.core.persistence.api.entity.task.PropagationTask; import org.apache.syncope.core.persistence.api.entity.task.PushTask; import org.apache.syncope.core.persistence.api.entity.task.SyncTask; import org.apache.syncope.core.persistence.api.entity.user.UMappingItem; import org.apache.syncope.core.persistence.api.entity.user.User; import org.apache.syncope.core.persistence.jpa.entity.AbstractMappingItem; import org.apache.syncope.core.persistence.jpa.entity.JPAExternalResource; import org.apache.syncope.core.persistence.jpa.entity.role.JPARMappingItem; import org.apache.syncope.core.persistence.jpa.entity.user.JPAUMappingItem; import org.apache.syncope.core.provisioning.api.ConnectorRegistry; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; @Repository public class JPAExternalResourceDAO extends AbstractDAO<ExternalResource, String> implements ExternalResourceDAO { @Autowired private TaskDAO taskDAO; @Autowired private UserDAO userDAO; @Autowired private RoleDAO roleDAO; @Autowired private PolicyDAO policyDAO; @Autowired private ConnectorRegistry connRegistry; @Override public ExternalResource find(final String name) { TypedQuery<ExternalResource> query = entityManager.createQuery("SELECT e FROM " + JPAExternalResource.class.getSimpleName() + " e WHERE e.name = :name", ExternalResource.class); query.setParameter("name", name); ExternalResource result = null; try { result = query.getSingleResult(); } catch (NoResultException e) { LOG.debug("No resource found with name {}", name, e); } return result; } private StringBuilder getByPolicyQuery(final PolicyType type) { StringBuilder query = new StringBuilder("SELECT e FROM "). append(JPAExternalResource.class.getSimpleName()). append(" e WHERE e."); switch (type) { case ACCOUNT: case GLOBAL_ACCOUNT: query.append("accountPolicy"); break; case PASSWORD: case GLOBAL_PASSWORD: query.append("passwordPolicy"); break; case SYNC: case GLOBAL_SYNC: query.append("syncPolicy"); break; default: break; } return query; } @Override public List<ExternalResource> findByPolicy(final Policy policy) { TypedQuery<ExternalResource> query = entityManager.createQuery( getByPolicyQuery(policy.getType()).append(" = :policy").toString(), ExternalResource.class); query.setParameter("policy", policy); return query.getResultList(); } @Override public List<ExternalResource> findWithoutPolicy(final PolicyType type) { TypedQuery<ExternalResource> query = entityManager.createQuery( getByPolicyQuery(type).append(" IS NULL").toString(), ExternalResource.class); return query.getResultList(); } @Override public List<ExternalResource> findAll() { TypedQuery<ExternalResource> query = entityManager.createQuery( "SELECT e FROM " + JPAExternalResource.class.getSimpleName() + " e", ExternalResource.class); return query.getResultList(); } @Override public List<ExternalResource> findAllByPriority() { TypedQuery<ExternalResource> query = entityManager.createQuery( "SELECT e FROM " + JPAExternalResource.class.getSimpleName() + " e ORDER BY e.propagationPriority", ExternalResource.class); return query.getResultList(); } /** * This method has an explicit Transactional annotation because it is called by SyncJob. * * @see org.apache.syncope.core.sync.impl.SyncJob * * @param resource entity to be merged * @return the same entity, updated */ @Override @Transactional(rollbackFor = { Throwable.class }) public ExternalResource save(final ExternalResource resource) { ExternalResource merged = entityManager.merge(resource); try { connRegistry.registerConnector(merged); } catch (NotFoundException e) { LOG.error("While registering connector for resource", e); } return merged; } @Override @SuppressWarnings("unchecked") public <T extends MappingItem> void deleteMapping( final String intAttrName, final IntMappingType intMappingType, final Class<T> reference) { if (IntMappingType.getEmbedded().contains(intMappingType)) { return; } Class<? extends AbstractMappingItem> jpaRef = reference.equals(UMappingItem.class) ? JPAUMappingItem.class : JPARMappingItem.class; TypedQuery<T> query = entityManager.createQuery("SELECT m FROM " + jpaRef.getSimpleName() + " m WHERE m.intAttrName=:intAttrName AND m.intMappingType=:intMappingType", reference); query.setParameter("intAttrName", intAttrName); query.setParameter("intMappingType", intMappingType); Set<Long> itemIds = new HashSet<>(); for (T item : query.getResultList()) { itemIds.add(item.getKey()); } Class<?> mappingRef = null; for (Long itemId : itemIds) { T item = (T) entityManager.find(jpaRef, itemId); if (item != null) { mappingRef = item.getMapping().getClass(); ((Mapping<T>) item.getMapping()).removeItem(item); item.setMapping(null); entityManager.remove(item); } } // Make empty query cache for *MappingItem and related *Mapping entityManager.getEntityManagerFactory().getCache().evict(jpaRef); if (mappingRef != null) { entityManager.getEntityManagerFactory().getCache().evict(mappingRef); } } @Override public void delete(final String name) { ExternalResource resource = find(name); if (resource == null) { return; } taskDAO.deleteAll(resource, TaskType.PROPAGATION); taskDAO.deleteAll(resource, TaskType.SYNCHRONIZATION); taskDAO.deleteAll(resource, TaskType.PUSH); for (User user : userDAO.findByResource(resource)) { user.removeResource(resource); } for (Role role : roleDAO.findByResource(resource)) { role.removeResource(resource); } for (AccountPolicy policy : policyDAO.findByResource(resource)) { policy.removeResource(resource); } if (resource.getConnector() != null && resource.getConnector().getResources() != null && !resource.getConnector().getResources().isEmpty()) { resource.getConnector().getResources().remove(resource); } resource.setConnector(null); if (resource.getUmapping() != null) { for (MappingItem item : resource.getUmapping().getItems()) { item.setMapping(null); } resource.getUmapping().getItems().clear(); resource.getUmapping().setResource(null); resource.setUmapping(null); } if (resource.getRmapping() != null) { for (MappingItem item : resource.getRmapping().getItems()) { item.setMapping(null); } resource.getRmapping().getItems().clear(); resource.getRmapping().setResource(null); resource.setRmapping(null); } entityManager.remove(resource); } }
apache-2.0
sharaquss/android-google-course
app/src/main/java/com/example/android/miniweather/app/impl/ForecastCursorAdapter.java
4941
package com.example.android.miniweather.app.impl; import android.content.Context; import android.database.Cursor; import android.support.v4.widget.CursorAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.example.android.miniweather.app.MainForecastFragment; import com.example.android.miniweather.app.R; import com.example.android.miniweather.app.data.WeatherContract; import com.example.android.miniweather.app.front.ViewCache; import com.example.android.miniweather.app.utilities.Utility; /** * Created by Ciemek on 24/02/16. */ public class ForecastCursorAdapter extends CursorAdapter { private View inflatedLayout; private ViewCache inflatedLayoutCache; private TextView dateTextView, temperatureHighTextView, temperatureLowTextView, friendlyForecastTextView; private ImageView iconImageView; private final int VIEW_TODAY_TYPE = 0; private final int VIEW_FUTURE_TYPE = 1; private final int VIEW_LOCATION_TYPE = 2; private int actualViewType = VIEW_FUTURE_TYPE; public ForecastCursorAdapter(Context context, Cursor c, int flags) { super(context, c, flags); } private String formatHighLows(double high, double low) { boolean isMetric = Utility.isMetric(mContext); String highLowStr = Utility.formatTemperature(high, isMetric) + "/" + Utility.formatTemperature(low, isMetric); return highLowStr; } private String convertCursorRowToUXFormat(Cursor cursor) { String highAndLow = formatHighLows( cursor.getDouble(WeatherContract.getColWeatherMaxTemp()), cursor.getDouble(WeatherContract.getColWeatherMinTemp())); return Utility.formatDate(cursor.getLong(WeatherContract.getColWeatherDate())) + " - " + cursor.getString(WeatherContract.getColWeatherDesc()) + " - " + highAndLow; } /* Remember that these views are reused as needed. */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { int inflateLayoutId; if (getItemViewType(cursor.getPosition()) == VIEW_TODAY_TYPE) { inflateLayoutId = R.layout.list_item_today; actualViewType = VIEW_TODAY_TYPE; } else { inflateLayoutId = R.layout.list_item_future; actualViewType = VIEW_FUTURE_TYPE; } inflatedLayout = LayoutInflater.from(context).inflate(inflateLayoutId, parent, false); inflatedLayoutCache = new ViewCache((LinearLayout)inflatedLayout); return inflatedLayout; } /* This is where we fill-in the views with the contents of the cursor. */ @Override public void bindView(View view, Context context, Cursor cursor) { int weatherId = cursor.getInt(WeatherContract.COL_WEATHER_ID); dateTextView = inflatedLayoutCache.dateTextView; long dateMilliseconds = cursor.getLong(WeatherContract.COL_WEATHER_DATE); dateTextView.setText(Utility.formatDate(dateMilliseconds)); temperatureHighTextView = inflatedLayoutCache.temperatureHighTextView; int temperatureHigh = cursor.getInt(WeatherContract.COL_WEATHER_MAX_TEMP); temperatureHighTextView.setText(String.valueOf(temperatureHigh)); temperatureLowTextView = inflatedLayoutCache.temperatureLowTextView; int temperatureLow = cursor.getInt(WeatherContract.COL_WEATHER_MIN_TEMP); temperatureLowTextView.setText(String.valueOf(temperatureLow)); friendlyForecastTextView = inflatedLayoutCache.descriptionTextView; friendlyForecastTextView.setText(cursor.getString(WeatherContract.COL_WEATHER_DESC) + " / " + Integer.toString(weatherId)); iconImageView = inflatedLayoutCache.iconImageView; if (actualViewType == VIEW_TODAY_TYPE) // iconImageView.setImageResource(Utility.weatherIdToDrawableColour(cursor.getInt(WeatherContract.COL_WEATHER_ID))); iconImageView.setImageResource(Utility.weatherDescToDrawableColour(cursor.getString(WeatherContract.COL_WEATHER_DESC))); else { // iconImageView.setImageResource(Utility.weatherIdToDrawableGrey(cursor.getInt(WeatherContract.COL_WEATHER_ID))); // iconImageView.setImageResource(R.drawable.art_clear); iconImageView.setImageResource(Utility.weatherDescToDrawableGrey(cursor.getString(WeatherContract.COL_WEATHER_DESC))); } // iconImageView.setImageResource(R.drawable.ic_launcher); } //'int position' here is position on a list @Override public int getItemViewType(int position) { if (position == 0) return VIEW_TODAY_TYPE; return VIEW_FUTURE_TYPE; } @Override public int getViewTypeCount() { return 3; } }
apache-2.0
secdec/zap-extensions
addOns/ascanrules/src/test/java/org/zaproxy/zap/extension/ascanrules/CodeInjectionScanRuleUnitTest.java
6329
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2016 The ZAP Development Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.zaproxy.zap.extension.ascanrules; import static fi.iki.elonen.NanoHTTPD.newFixedLengthResponse; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import fi.iki.elonen.NanoHTTPD; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.jupiter.api.Test; import org.parosproxy.paros.core.scanner.Plugin.AttackStrength; import org.parosproxy.paros.network.HttpMessage; import org.zaproxy.zap.model.Tech; import org.zaproxy.zap.model.TechSet; import org.zaproxy.zap.testutils.NanoServerHandler; /** Unit test for {@link CodeInjectionScanRule}. */ class CodeInjectionScanRuleUnitTest extends ActiveScannerTest<CodeInjectionScanRule> { @Override protected int getRecommendMaxNumberMessagesPerParam(AttackStrength strength) { int recommendMax = super.getRecommendMaxNumberMessagesPerParam(strength); switch (strength) { case LOW: return recommendMax + 2; case MEDIUM: default: return recommendMax; case HIGH: return recommendMax; case INSANE: return recommendMax; } } @Override protected CodeInjectionScanRule createScanner() { return new CodeInjectionScanRule(); } @Test void shouldTargetAspTech() { // Given TechSet techSet = techSet(Tech.ASP); // When boolean targets = rule.targets(techSet); // Then assertThat(targets, is(equalTo(true))); } @Test void shouldTargetPhpTech() { // Given TechSet techSet = techSet(Tech.PHP); // When boolean targets = rule.targets(techSet); // Then assertThat(targets, is(equalTo(true))); } @Test void shouldNotTargetNonAspPhpTechs() { // Given TechSet techSet = techSetWithout(Tech.ASP, Tech.PHP); // When boolean targets = rule.targets(techSet); // Then assertThat(targets, is(equalTo(false))); } @Test void shouldFindPhpInjection() throws Exception { // Given String test = "/shouldFindPhpInjection.php"; String PHP_ENCODED_TOKEN = "chr(122).chr(97).chr(112).chr(95).chr(116).chr(111).chr(107).chr(101).chr(110)"; String PHP_PAYLOAD = "print(" + PHP_ENCODED_TOKEN + ")"; String PHP_CONTROL_TOKEN = "zap_token"; this.nano.addHandler( new NanoServerHandler(test) { @Override protected NanoHTTPD.Response serve(NanoHTTPD.IHTTPSession session) { String years = getFirstParamValue(session, "years"); if (years.contains(PHP_PAYLOAD)) { return newFixedLengthResponse( "<html><body>" + PHP_CONTROL_TOKEN + "</body></html>"); } return newFixedLengthResponse("<html><body></body></html>"); } }); // When HttpMessage msg = this.getHttpMessage(test + "?years=1"); this.rule.init(msg, this.parent); this.rule.scan(); // Then assertThat(alertsRaised.size(), equalTo(1)); assertThat(alertsRaised.get(0).getParam(), equalTo("years")); assertThat(alertsRaised.get(0).getEvidence(), equalTo(PHP_CONTROL_TOKEN)); } @Test void shouldFindAspInjection() throws Exception { // Given String test = "/shouldFindAspInjection"; List<String> evaluationResults = new ArrayList<>(); this.nano.addHandler( new NanoServerHandler(test) { @Override protected NanoHTTPD.Response serve(NanoHTTPD.IHTTPSession session) { String years = getFirstParamValue(session, "years"); String responseWriteRgx = "response\\.write\\(([0-9]{1,3}(?:,[0-9]{3})?)\\*([0-9]{1,3}(?:,[0-9]{3})?)\\)"; Pattern pattern = Pattern.compile(responseWriteRgx); Matcher matcher = pattern.matcher(years); if (matcher.find()) { int num1 = Integer.parseInt(matcher.group(1).replace(",", "")); int num2 = Integer.parseInt(matcher.group(2).replace(",", "")); String resultEval = String.valueOf((long) num1 * num2); evaluationResults.add(resultEval); return newFixedLengthResponse( "<html><body>" + resultEval + "</body></html>"); } return newFixedLengthResponse("<html><body>years</body></html>"); } }); // When HttpMessage msg = this.getHttpMessage(test + "?years=1"); this.rule.init(msg, this.parent); this.rule.scan(); // Then assertThat(alertsRaised.size(), equalTo(1)); assertThat(alertsRaised.get(0).getParam(), equalTo("years")); boolean evidenceOnEvaluationResults = false; for (String result : evaluationResults) { if (alertsRaised.get(0).getEvidence().contains(result)) evidenceOnEvaluationResults = true; } assert (evidenceOnEvaluationResults); } }
apache-2.0
tmurakami/dexopener
dexopener/src/test/java/test/MyClass.java
642
/* * Copyright 2016 Tsuyoshi Murakami * * 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 test; public class MyClass { }
apache-2.0
Legioth/vaadin
client/src/main/java/com/vaadin/client/ui/textfield/ValueChangeHandler.java
4060
/* * Copyright 2000-2016 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.textfield; import com.google.gwt.core.client.Scheduler; import com.google.gwt.user.client.Timer; import com.vaadin.client.ComponentConnector; import com.vaadin.shared.ui.ValueChangeMode; /** * Helper for dealing with scheduling value change events based on a given mode * and possibly timeout. */ public class ValueChangeHandler { /** * Must be implemented by any user of a ValueChangeHandler. */ public interface Owner extends ComponentConnector { /** * Sends the current value to the server, if it has changed. */ void sendValueChange(); } private Owner owner; private boolean scheduled; private Timer valueChangeTrigger = new Timer() { @Override public void run() { Scheduler.get().scheduleDeferred(() -> { owner.sendValueChange(); scheduled = false; }); } }; private int valueChangeTimeout = -1; private ValueChangeMode valueChangeMode; /** * Creates a value change handler for the given owner. * * @param owner * the owner connector */ public ValueChangeHandler(Owner owner) { this.owner = owner; } /** * Called whenever a change in the value has been detected. Schedules a * value change to be sent to the server, depending on the current value * change mode. * <p> * Note that this method does not consider the {@link ValueChangeMode#BLUR} * mode but assumes that {@link #sendValueChange()} is called directly for * this mode. */ public void scheduleValueChange() { switch (valueChangeMode) { case LAZY: lazyTextChange(); break; case TIMEOUT: timeoutTextChange(); break; case EAGER: eagerTextChange(); break; case BLUR: // Nothing to schedule for this mode break; default: throw new IllegalStateException("Unknown mode: " + valueChangeMode); } } private void lazyTextChange() { scheduled = true; valueChangeTrigger.schedule(valueChangeTimeout); } private void timeoutTextChange() { if (valueChangeTrigger.isRunning()) { return; } scheduled = true; valueChangeTrigger.schedule(valueChangeTimeout); } private void eagerTextChange() { scheduled = true; valueChangeTrigger.run(); } /** * Sets the value change mode to use. * * @see ValueChangeMode * * @param valueChangeMode * the value change mode to use */ public void setValueChangeMode(ValueChangeMode valueChangeMode) { this.valueChangeMode = valueChangeMode; } /** * Sets the value change timeout to use. * * @see ValueChangeMode * * @param valueChangeTimeout * the value change timeout */ public void setValueChangeTimeout(int valueChangeTimeout) { this.valueChangeTimeout = valueChangeTimeout; } /** * Checks whether the value change is scheduled for sending. * * @since 8.0.0 * * @return {@code true} if value change is scheduled for sending, * {@code false} otherwise */ public boolean isScheduled() { return scheduled; } }
apache-2.0
consulo/consulo-java
java-analysis-impl/src/main/java/com/intellij/codeInspection/bytecodeAnalysis/DataValue.java
4209
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInspection.bytecodeAnalysis; import com.intellij.codeInspection.dataFlow.ContractReturnValue; import java.util.stream.Stream; // data for data analysis abstract class DataValue implements consulo.internal.org.objectweb.asm.tree.analysis.Value { public static final DataValue[] EMPTY = new DataValue[0]; private final int myHash; DataValue(int hash) { myHash = hash; } @Override public final int hashCode() { return myHash; } Stream<EKey> dependencies() { return Stream.empty(); } public ContractReturnValue asContractReturnValue() { return ContractReturnValue.returnAny(); } static final DataValue ThisDataValue = new DataValue(-1) { @Override public int getSize() { return 1; } @Override public ContractReturnValue asContractReturnValue() { return ContractReturnValue.returnThis(); } @Override public String toString() { return "DataValue: this"; } }; static final DataValue LocalDataValue = new DataValue(-2) { @Override public int getSize() { return 1; } @Override public ContractReturnValue asContractReturnValue() { return ContractReturnValue.returnNew(); } @Override public String toString() { return "DataValue: local"; } }; static class ParameterDataValue extends DataValue { static final ParameterDataValue PARAM0 = new ParameterDataValue(0); static final ParameterDataValue PARAM1 = new ParameterDataValue(1); static final ParameterDataValue PARAM2 = new ParameterDataValue(2); final int n; private ParameterDataValue(int n) { super(n); this.n = n; } @Override public ContractReturnValue asContractReturnValue() { return ContractReturnValue.returnParameter(n); } static ParameterDataValue create(int n) { switch(n) { case 0: return PARAM0; case 1: return PARAM1; case 2: return PARAM2; default: return new ParameterDataValue(n); } } @Override public int getSize() { return 1; } @Override public boolean equals(Object o) { if(this == o) { return true; } if(o == null || getClass() != o.getClass()) { return false; } ParameterDataValue that = (ParameterDataValue) o; return n == that.n; } @Override public String toString() { return "DataValue: arg#" + n; } } static class ReturnDataValue extends DataValue { final EKey key; ReturnDataValue(EKey key) { super(key.hashCode()); this.key = key; } @Override public int getSize() { return 1; } @Override public boolean equals(Object o) { if(this == o) { return true; } if(o == null || getClass() != o.getClass()) { return false; } ReturnDataValue that = (ReturnDataValue) o; return key.equals(that.key); } @Override Stream<EKey> dependencies() { return Stream.of(key); } @Override public String toString() { return "Return of: " + key; } } static final DataValue OwnedDataValue = new DataValue(-3) { @Override public int getSize() { return 1; } @Override public String toString() { return "DataValue: owned"; } }; static final DataValue UnknownDataValue1 = new DataValue(-4) { @Override public int getSize() { return 1; } @Override public String toString() { return "DataValue: unknown (1-slot)"; } }; static final DataValue UnknownDataValue2 = new DataValue(-5) { @Override public int getSize() { return 2; } @Override public String toString() { return "DataValue: unknown (2-slot)"; } }; }
apache-2.0
RihnKornak/TestTasks
src/test/java/browser/BrowserSingleton.java
435
package browser; import org.openqa.selenium.firefox.FirefoxDriver; /** * Created by Rihn Kornak on 24.06.2017. */ public class BrowserSingleton { private static FirefoxDriver driver; public static FirefoxDriver getInstance(){ if (driver == null){ System.setProperty("webdriver.gecko.driver", "drv/geckodriver.exe"); driver = new FirefoxDriver(); } return driver; } }
apache-2.0
orioncode/orionplatform
orion_web/orion_web_services/src/main/java/com/orionplatform/web/services/WebService.java
156
package com.orionplatform.web.services; import com.orionplatform.core.abstraction.OrionService; public abstract class WebService extends OrionService { }
apache-2.0
peterhoeltschi/AzureStorage
microsoft-azure-storage-test/src/com/microsoft/azure/storage/analytics/CloudAnalyticsClientTests.java
22229
/** * Copyright Microsoft Corporation * * 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.microsoft.azure.storage.analytics; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.UUID; import junit.framework.TestCase; import com.microsoft.azure.storage.Constants; import com.microsoft.azure.storage.StorageException; import com.microsoft.azure.storage.StorageLocation; import com.microsoft.azure.storage.blob.CloudBlobContainer; import com.microsoft.azure.storage.blob.CloudBlockBlob; import com.microsoft.azure.storage.blob.ListBlobItem; import com.microsoft.azure.storage.table.CloudTable; /** * Analytics Client Tests */ public class CloudAnalyticsClientTests extends TestCase { protected CloudAnalyticsClient client; protected CloudBlobContainer container; @Override public void setUp() throws URISyntaxException, StorageException { this.container = AnalyticsTestHelper.getRandomContainerReference(); this.client = AnalyticsTestHelper.createCloudAnalyticsClient(); } public void tearDown() throws StorageException { this.container.deleteIfExists(); } /** * Test table getters. * * @throws StorageException * @throws URISyntaxException */ public void testCloudAnalyticsClientGetTables() throws URISyntaxException, StorageException { CloudTable blobHourPrimary = this.client.getHourMetricsTable(StorageService.BLOB); CloudTable blobHourSecondary = this.client.getHourMetricsTable(StorageService.BLOB, StorageLocation.SECONDARY); CloudTable queueHourPrimary = this.client.getHourMetricsTable(StorageService.QUEUE, StorageLocation.PRIMARY); CloudTable queueHourSecondary = this.client .getHourMetricsTable(StorageService.QUEUE, StorageLocation.SECONDARY); CloudTable tableHourPrimary = this.client.getHourMetricsTable(StorageService.TABLE, StorageLocation.PRIMARY); CloudTable tableHourSecondary = this.client .getHourMetricsTable(StorageService.TABLE, StorageLocation.SECONDARY); CloudTable blobMinutePrimary = this.client.getMinuteMetricsTable(StorageService.BLOB); CloudTable blobMinuteSecondary = this.client.getMinuteMetricsTable(StorageService.BLOB, StorageLocation.SECONDARY); CloudTable queueMinutePrimary = this.client .getMinuteMetricsTable(StorageService.QUEUE, StorageLocation.PRIMARY); CloudTable queueMinuteSecondary = this.client.getMinuteMetricsTable(StorageService.QUEUE, StorageLocation.SECONDARY); CloudTable tableMinutePrimary = this.client .getMinuteMetricsTable(StorageService.TABLE, StorageLocation.PRIMARY); CloudTable tableMinuteSecondary = this.client.getMinuteMetricsTable(StorageService.TABLE, StorageLocation.SECONDARY); CloudTable capacity = this.client.getCapacityTable(); assertEquals(Constants.AnalyticsConstants.METRICS_HOUR_PRIMARY_TRANSACTIONS_BLOB, blobHourPrimary.getName()); assertEquals(Constants.AnalyticsConstants.METRICS_HOUR_SECONDARY_TRANSACTIONS_BLOB, blobHourSecondary.getName()); assertEquals(Constants.AnalyticsConstants.METRICS_HOUR_PRIMARY_TRANSACTIONS_QUEUE, queueHourPrimary.getName()); assertEquals(Constants.AnalyticsConstants.METRICS_HOUR_SECONDARY_TRANSACTIONS_QUEUE, queueHourSecondary.getName()); assertEquals(Constants.AnalyticsConstants.METRICS_HOUR_PRIMARY_TRANSACTIONS_TABLE, tableHourPrimary.getName()); assertEquals(Constants.AnalyticsConstants.METRICS_HOUR_SECONDARY_TRANSACTIONS_TABLE, tableHourSecondary.getName()); assertEquals(Constants.AnalyticsConstants.METRICS_MINUTE_PRIMARY_TRANSACTIONS_BLOB, blobMinutePrimary.getName()); assertEquals(Constants.AnalyticsConstants.METRICS_MINUTE_SECONDARY_TRANSACTIONS_BLOB, blobMinuteSecondary.getName()); assertEquals(Constants.AnalyticsConstants.METRICS_MINUTE_PRIMARY_TRANSACTIONS_QUEUE, queueMinutePrimary.getName()); assertEquals(Constants.AnalyticsConstants.METRICS_MINUTE_SECONDARY_TRANSACTIONS_QUEUE, queueMinuteSecondary.getName()); assertEquals(Constants.AnalyticsConstants.METRICS_MINUTE_PRIMARY_TRANSACTIONS_TABLE, tableMinutePrimary.getName()); assertEquals(Constants.AnalyticsConstants.METRICS_MINUTE_SECONDARY_TRANSACTIONS_TABLE, tableMinuteSecondary.getName()); assertEquals(Constants.AnalyticsConstants.METRICS_CAPACITY_BLOB, capacity.getName()); } /** * List all logs * * @throws URISyntaxException * @throws StorageException * @throws IOException * @throws InterruptedException */ public void testCloudAnalyticsClientListLogs() throws URISyntaxException, StorageException, IOException { this.container.create(); this.client.LogContainer = this.container.getName(); int numBlobs = 13; Calendar now = new GregorianCalendar(); now.add(GregorianCalendar.MONTH, -13); List<String> blobNames = AnalyticsTestHelper.CreateLogs(this.container, StorageService.BLOB, 13, now, Granularity.MONTH); assertEquals(numBlobs, blobNames.size()); for (ListBlobItem blob : this.client.listLogBlobs(StorageService.BLOB)) { assertEquals(CloudBlockBlob.class, blob.getClass()); assertTrue(blobNames.remove(((CloudBlockBlob) blob).getName())); } assertTrue(blobNames.size() == 0); } /** * List Logs with open ended time range * * @throws URISyntaxException * @throws StorageException * @throws IOException * @throws InterruptedException */ public void testCloudAnalyticsClientListLogsStartTime() throws URISyntaxException, StorageException, IOException { this.container.create(); this.client.LogContainer = this.container.getName(); int numBlobs = 48; Calendar now = new GregorianCalendar(); now.add(GregorianCalendar.DAY_OF_MONTH, -2); List<String> blobNames = AnalyticsTestHelper.CreateLogs(this.container, StorageService.BLOB, 48, now, Granularity.HOUR); assertEquals(numBlobs, blobNames.size()); Calendar start = new GregorianCalendar(); start.add(GregorianCalendar.DAY_OF_MONTH, -1); for (ListBlobItem blob : this.client.listLogBlobs(StorageService.BLOB, start.getTime(), null, null, null, null, null)) { assertEquals(CloudBlockBlob.class, blob.getClass()); assertTrue(blobNames.remove(((CloudBlockBlob) blob).getName())); } assertTrue(blobNames.size() == 24); } /** * List Logs with well defined time range * * @throws URISyntaxException * @throws StorageException * @throws IOException * @throws InterruptedException */ public void testCloudAnalyticsClientListLogsStartEndTime() throws URISyntaxException, StorageException, IOException { this.container.create(); this.client.LogContainer = this.container.getName(); int numBlobs = 72; Calendar now = new GregorianCalendar(); now.add(GregorianCalendar.DAY_OF_MONTH, -3); List<String> blobNames = AnalyticsTestHelper.CreateLogs(this.container, StorageService.BLOB, 72, now, Granularity.HOUR); assertEquals(numBlobs, blobNames.size()); Calendar start = new GregorianCalendar(); start.add(GregorianCalendar.DAY_OF_MONTH, -2); Calendar end = new GregorianCalendar(); end.add(GregorianCalendar.DAY_OF_MONTH, -1); for (ListBlobItem blob : this.client.listLogBlobs(StorageService.BLOB, start.getTime(), end.getTime(), null, null, null, null)) { assertEquals(CloudBlockBlob.class, blob.getClass()); assertTrue(blobNames.remove(((CloudBlockBlob) blob).getName())); } assertTrue(blobNames.size() == 48); } /** * Validate Log Parser * * @throws ParseException * @throws URISyntaxException * @throws StorageException * @throws IOException * @throws InterruptedException */ public void testCloudAnalyticsClientParseExLogs() throws ParseException, URISyntaxException, StorageException, IOException { String logText = "1.0;2011-08-09T18:52:40.9241789Z;GetBlob;AnonymousSuccess;200;18;10;anonymous;;myaccount;blob;\"https://myaccount.blob.core.windows.net/thumb&amp;nails/lake.jpg?timeout=30000\";\"/myaccount/thumbnails/lake.jpg\";a84aa705-8a85-48c5-b064-b43bd22979c3;0;123.100.2.10;2009-09-19;252;0;265;100;0;;;\"0x8CE1B6EA95033D5\";Tuesday, 09-Aug-11 18:52:40 GMT;;;;\"8/9/2011 6:52:40 PM ba98eb12-700b-4d53-9230-33a3330571fc\"" + '\n' + "1.0;2011-08-09T18:02:40.6271789Z;PutBlob;Success;201;28;21;authenticated;myaccount;myaccount;blob;\"https://myaccount.blob.core.windows.net/thumbnails/lake.jpg?timeout=30000\";\"/myaccount/thumbnails/lake.jpg\";fb658ee6-6123-41f5-81e2-4bfdc178fea3;0;201.9.10.20;2009-09-19;438;100;223;0;100;;\"66CbMXKirxDeTr82SXBKbg==\";\"0x8CE1B67AD25AA05\";Tuesday, 09-Aug-11 18:02:40 GMT;;;;\"8/9/2011 6:02:40 PM ab970a57-4a49-45c4-baa9-20b687941e32\"" + '\n'; this.container.createIfNotExists(); CloudBlockBlob blob = this.container.getBlockBlobReference("blob1"); blob.uploadText(logText); Iterator<LogRecord> iterator = CloudAnalyticsClient.parseLogBlob(blob).iterator(); assertTrue(iterator.hasNext()); LogRecord actualItemOne = iterator.next(); assertTrue(iterator.hasNext()); LogRecord actualItemTwo = iterator.next(); LogRecord expectedItemOne = new LogRecord(); expectedItemOne.setVersionNumber("1.0"); expectedItemOne.setRequestStartTime(LogRecord.REQUEST_START_TIME_FORMAT.parse("2011-08-09T18:52:40.9241789Z")); expectedItemOne.setOperationType("GetBlob"); expectedItemOne.setRequestStatus("AnonymousSuccess"); expectedItemOne.setHttpStatusCode("200"); expectedItemOne.setEndToEndLatencyInMS(18); expectedItemOne.setServerLatencyInMS(10); expectedItemOne.setAuthenticationType("anonymous"); expectedItemOne.setRequesterAccountName(null); expectedItemOne.setOwnerAccountName("myaccount"); expectedItemOne.setServiceType("blob"); expectedItemOne.setRequestUrl(new URI( "https://myaccount.blob.core.windows.net/thumb&nails/lake.jpg?timeout=30000")); expectedItemOne.setRequestedObjectKey("/myaccount/thumbnails/lake.jpg"); expectedItemOne.setRequestIdHeader(UUID.fromString("a84aa705-8a85-48c5-b064-b43bd22979c3")); expectedItemOne.setOperationCount(0); expectedItemOne.setRequesterIPAddress("123.100.2.10"); expectedItemOne.setRequestVersionHeader("2009-09-19"); expectedItemOne.setRequestHeaderSize(252L); expectedItemOne.setRequestPacketSize(0L); expectedItemOne.setResponseHeaderSize(265L); expectedItemOne.setResponsePacketSize(100L); expectedItemOne.setRequestContentLength(0L); expectedItemOne.setRequestMD5(null); expectedItemOne.setServerMD5(null); expectedItemOne.setETagIdentifier("0x8CE1B6EA95033D5"); expectedItemOne.setLastModifiedTime(LogRecord.LAST_MODIFIED_TIME_FORMAT .parse("Tuesday, 09-Aug-11 18:52:40 GMT")); expectedItemOne.setConditionsUsed(null); expectedItemOne.setUserAgentHeader(null); expectedItemOne.setReferrerHeader(null); expectedItemOne.setClientRequestId("8/9/2011 6:52:40 PM ba98eb12-700b-4d53-9230-33a3330571fc"); LogRecord expectedItemTwo = new LogRecord(); expectedItemTwo.setVersionNumber("1.0"); expectedItemTwo.setRequestStartTime(LogRecord.REQUEST_START_TIME_FORMAT.parse("2011-08-09T18:02:40.6271789Z")); expectedItemTwo.setOperationType("PutBlob"); expectedItemTwo.setRequestStatus("Success"); expectedItemTwo.setHttpStatusCode("201"); expectedItemTwo.setEndToEndLatencyInMS(28); expectedItemTwo.setServerLatencyInMS(21); expectedItemTwo.setAuthenticationType("authenticated"); expectedItemTwo.setRequesterAccountName("myaccount"); expectedItemTwo.setOwnerAccountName("myaccount"); expectedItemTwo.setServiceType("blob"); expectedItemTwo.setRequestUrl(new URI( "https://myaccount.blob.core.windows.net/thumbnails/lake.jpg?timeout=30000")); expectedItemTwo.setRequestedObjectKey("/myaccount/thumbnails/lake.jpg"); expectedItemTwo.setRequestIdHeader(UUID.fromString("fb658ee6-6123-41f5-81e2-4bfdc178fea3")); expectedItemTwo.setOperationCount(0); expectedItemTwo.setRequesterIPAddress("201.9.10.20"); expectedItemTwo.setRequestVersionHeader("2009-09-19"); expectedItemTwo.setRequestHeaderSize(438L); expectedItemTwo.setRequestPacketSize(100L); expectedItemTwo.setResponseHeaderSize(223L); expectedItemTwo.setResponsePacketSize(0L); expectedItemTwo.setRequestContentLength(100L); expectedItemTwo.setRequestMD5(null); expectedItemTwo.setServerMD5("66CbMXKirxDeTr82SXBKbg=="); expectedItemTwo.setETagIdentifier("0x8CE1B67AD25AA05"); expectedItemTwo.setLastModifiedTime(LogRecord.LAST_MODIFIED_TIME_FORMAT .parse("Tuesday, 09-Aug-11 18:02:40 GMT")); expectedItemTwo.setConditionsUsed(null); expectedItemTwo.setUserAgentHeader(null); expectedItemTwo.setReferrerHeader(null); expectedItemTwo.setClientRequestId("8/9/2011 6:02:40 PM ab970a57-4a49-45c4-baa9-20b687941e32"); CloudAnalyticsClientTests.assertLogItemsEqual(expectedItemOne, actualItemOne); CloudAnalyticsClientTests.assertLogItemsEqual(expectedItemTwo, actualItemTwo); } /** * Validate Log Parser with prod data * * @throws ParseException * @throws URISyntaxException * @throws StorageException * @throws IOException * @throws InterruptedException */ public void testCloudAnalyticsClientParseProdLogs() throws ParseException, URISyntaxException, StorageException, IOException { Calendar startTime = new GregorianCalendar(); startTime.add(GregorianCalendar.HOUR_OF_DAY, -2); Iterator<LogRecord> logRecordsIterator = (this.client.listLogRecords(StorageService.BLOB, startTime.getTime(), null, null, null)).iterator(); while (logRecordsIterator.hasNext()) { // Makes sure there's no exceptions thrown and that no records are null. // Primarily a sanity check. LogRecord rec = logRecordsIterator.next(); System.out.println(rec.getRequestUrl()); assertNotNull(rec); } } /** * Log parser error cases. * * @throws ParseException * @throws URISyntaxException * @throws StorageException * @throws IOException * @throws InterruptedException */ public void testCloudAnalyticsClientParseLogErrors() throws ParseException, URISyntaxException, StorageException, IOException { this.container.createIfNotExists(); String v2Entry = "2.0;2011-08-09T18:02:40.6271789Z;PutBlob;Success;201;28;21;authenticated;myaccount;myaccount;blob;\"https://myaccount.blob.core.windows.net/thumbnails/lake.jpg?timeout=30000\";\"/myaccount/thumbnails/lake.jpg\";fb658ee6-6123-41f5-81e2-4bfdc178fea3;0;201.9.10.20;2009-09-19;438;100;223;0;100;;\"66CbMXKirxDeTr82SXBKbg==\";\"0x8CE1B67AD25AA05\";Tuesday, 09-Aug-11 18:02:40 GMT;;;;\"8/9/2011 6:02:40 PM ab970a57-4a49-45c4-baa9-20b687941e32\"" + '\n'; CloudBlockBlob v2Blob = this.container.getBlockBlobReference("v2Blob"); v2Blob.uploadText(v2Entry); Iterator<LogRecord> v2Iterator = CloudAnalyticsClient.parseLogBlob(v2Blob).iterator(); try { v2Iterator.next(); fail(); } catch (IllegalArgumentException e) { assertEquals(e.getMessage(), "A storage log version of 2.0 is unsupported."); } // Note that if this non log data ('%s') contains a semicolon, we'll get an unfortunate failure // saying that a log version of %s is not supported. Otherwise, we'll see the behavior below. String nonLogData = "THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG 1234567890"; CloudBlockBlob nonLogDataBlob = this.container.getBlockBlobReference("nonLogBlob"); nonLogDataBlob.uploadText(nonLogData); Iterator<LogRecord> nonLogDataIterator = CloudAnalyticsClient.parseLogBlob(nonLogDataBlob).iterator(); try { nonLogDataIterator.next(); fail(); } catch (NoSuchElementException e) { assertEquals(e.getMessage(), "An error occurred while enumerating the result, check the original exception for details."); assertEquals(e.getCause().getMessage(), "Error parsing log record: unexpected end of stream."); } CloudBlockBlob nullBlob1 = this.container.getBlockBlobReference("nullBlob1"); CloudBlockBlob nullBlob2 = this.container.getBlockBlobReference("nullBlob2"); CloudBlockBlob nullBlob3 = this.container.getBlockBlobReference("nullBlob3"); ArrayList<ListBlobItem> nullBlobIterator = new ArrayList<ListBlobItem>(); nullBlobIterator.add(nullBlob1); nullBlobIterator.add(nullBlob2); nullBlobIterator.add(nullBlob3); Iterator<LogRecord> nullLogIterator = CloudAnalyticsClient.parseLogBlobs(nullBlobIterator).iterator(); try { nullLogIterator.next(); fail(); } catch (NoSuchElementException e) { assertEquals(e.getMessage(), "An error occurred while enumerating the result, check the original exception for details."); assertEquals(e.getCause().getMessage(), "The specified blob does not exist."); } try { Iterator<LogRecord> emptyIterator = CloudAnalyticsClient.parseLogBlobs(new ArrayList<ListBlobItem>()).iterator(); assertFalse(emptyIterator.hasNext()); emptyIterator.next(); } catch (NoSuchElementException e) { assertEquals(e.getMessage(), "There are no more elements in this enumeration."); } try { CloudAnalyticsClient.parseLogBlobs(null); } catch (IllegalArgumentException e) { assertEquals(e.getMessage(), "The argument must not be null or an empty string. Argument name: logBlobs."); } } public static void assertLogItemsEqual(LogRecord expected, LogRecord actual) { assertEquals(expected.getVersionNumber(), actual.getVersionNumber()); assertEquals(expected.getRequestStartTime(), actual.getRequestStartTime()); assertEquals(expected.getOperationType(), actual.getOperationType()); assertEquals(expected.getRequestStatus(), actual.getRequestStatus()); assertEquals(expected.getHttpStatusCode(), actual.getHttpStatusCode()); assertEquals(expected.getEndToEndLatencyInMS(), actual.getEndToEndLatencyInMS()); assertEquals(expected.getServerLatencyInMS(), actual.getServerLatencyInMS()); assertEquals(expected.getAuthenticationType(), actual.getAuthenticationType()); assertEquals(expected.getRequesterAccountName(), actual.getRequesterAccountName()); assertEquals(expected.getOwnerAccountName(), actual.getOwnerAccountName()); assertEquals(expected.getServiceType(), actual.getServiceType()); assertEquals(expected.getRequestUrl(), actual.getRequestUrl()); assertEquals(expected.getRequestedObjectKey(), actual.getRequestedObjectKey()); assertEquals(expected.getRequestIdHeader(), actual.getRequestIdHeader()); assertEquals(expected.getOperationCount(), actual.getOperationCount()); assertEquals(expected.getRequesterIPAddress(), actual.getRequesterIPAddress()); assertEquals(expected.getRequestVersionHeader(), actual.getRequestVersionHeader()); assertEquals(expected.getRequestHeaderSize(), actual.getRequestHeaderSize()); assertEquals(expected.getRequestPacketSize(), actual.getRequestPacketSize()); assertEquals(expected.getResponseHeaderSize(), actual.getResponseHeaderSize()); assertEquals(expected.getResponsePacketSize(), actual.getResponsePacketSize()); assertEquals(expected.getRequestContentLength(), actual.getRequestContentLength()); assertEquals(expected.getRequestMD5(), actual.getRequestMD5()); assertEquals(expected.getServerMD5(), actual.getServerMD5()); assertEquals(expected.getETagIdentifier(), actual.getETagIdentifier()); assertEquals(expected.getLastModifiedTime(), actual.getLastModifiedTime()); assertEquals(expected.getConditionsUsed(), actual.getConditionsUsed()); assertEquals(expected.getUserAgentHeader(), actual.getUserAgentHeader()); assertEquals(expected.getReferrerHeader(), actual.getReferrerHeader()); assertEquals(expected.getClientRequestId(), actual.getClientRequestId()); } }
apache-2.0
liyzhou/iscoder.rpc
scf-server/src/main/java/com/github/leeyazhou/scf/server/deploy/bytecode/ProxyFactoryCreater.java
3417
package com.github.leeyazhou.scf.server.deploy.bytecode; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.leeyazhou.scf.core.loader.DynamicClassLoader; import com.github.leeyazhou.scf.server.contract.context.Global; import javassist.ClassPool; import javassist.CtClass; import javassist.CtConstructor; import javassist.CtField; import javassist.CtMethod; /** * * */ public class ProxyFactoryCreater { private static Logger logger = LoggerFactory.getLogger(ProxyFactoryCreater.class); @SuppressWarnings("rawtypes") public ClassFile createProxy(DynamicClassLoader classLoader, ContractInfo serviceContract, long time) { try { String pfClsName = "ProxyFactory" + time; logger.info("begin create ProxyFactory:" + pfClsName); ClassPool pool = ClassPool.getDefault(); Set<String> jarList = classLoader.getJarList(); for (String jar : jarList) { pool.appendClassPath(jar); } CtClass ctProxyClass = pool.makeClass(pfClsName, null); CtClass proxyFactory = pool.getCtClass(Constant.IPROXYFACTORY_CLASS_NAME); ctProxyClass.addInterface(proxyFactory); // createProxy StringBuilder sbBody = new StringBuilder(); sbBody.append("public " + Constant.IPROXYSTUB_CLASS_NAME + " getProxy(String lookup) {"); StringBuilder sbConstructor = new StringBuilder(); sbConstructor.append("{"); int proxyCount = 0; for (ContractInfo.SessionBean sessionBean : serviceContract.getSessionBeanList()) { Iterator it = sessionBean.getInstanceMap().entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); String lookup = entry.getKey().toString(); sbBody.append("if(lookup.equalsIgnoreCase(\"" + lookup + "\")){"); sbBody.append("return proxy"); sbBody.append(lookup); sbBody.append(Global.getSingleton().getServiceConfig().getServiceName()); sbBody.append(";}"); sbConstructor.append("proxy"); sbConstructor.append(lookup); sbConstructor.append(Global.getSingleton().getServiceConfig().getServiceName()); sbConstructor.append("=("); sbConstructor.append(Constant.IPROXYSTUB_CLASS_NAME); sbConstructor.append(")$1.get("); sbConstructor.append(proxyCount); sbConstructor.append(");"); CtField proxyField = CtField.make("private " + Constant.IPROXYSTUB_CLASS_NAME + " proxy" + lookup + Global.getSingleton().getServiceConfig().getServiceName() + " = null;", ctProxyClass); ctProxyClass.addField(proxyField); proxyCount++; } } sbBody.append("return null;}}"); sbConstructor.append("}"); CtMethod methodItem = CtMethod.make(sbBody.toString(), ctProxyClass); ctProxyClass.addMethod(methodItem); CtConstructor cc = new CtConstructor(new CtClass[] {pool.get("java.util.List")}, ctProxyClass); cc.setBody(sbConstructor.toString()); ctProxyClass.addConstructor(cc); logger.debug("ProxyFactory source code:" + sbBody.toString()); logger.info("create ProxyFactory success!!!"); return new ClassFile(pfClsName, ctProxyClass.toBytecode()); } catch (Exception e) { throw new RuntimeException(e); } } }
apache-2.0
consulo/consulo
modules/base/diff-impl/src/main/java/com/intellij/diff/util/DiffGutterRenderer.java
2065
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diff.util; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.editor.markup.GutterIconRenderer; import com.intellij.openapi.project.DumbAwareAction; import consulo.ui.image.Image; import javax.annotation.Nonnull; import javax.annotation.Nullable; public abstract class DiffGutterRenderer extends GutterIconRenderer { @Nonnull private final Image myIcon; @Nullable private final String myTooltip; public DiffGutterRenderer(@Nonnull Image icon, @Nullable String tooltip) { myIcon = icon; myTooltip = tooltip; } @Nonnull @Override public Image getIcon() { return myIcon; } @Nullable @Override public String getTooltipText() { return myTooltip; } @Override public boolean isNavigateAction() { return true; } @Override public boolean isDumbAware() { return true; } @Nonnull @Override public Alignment getAlignment() { return Alignment.LEFT; } @Nullable @Override public AnAction getClickAction() { return new DumbAwareAction() { @Override public void actionPerformed(AnActionEvent e) { performAction(e); } }; } @Override public boolean equals(Object obj) { return obj == this; } @Override public int hashCode() { return System.identityHashCode(this); } protected abstract void performAction(AnActionEvent e); }
apache-2.0
mk-5/gdx-fireapp
gdx-fireapp-android/src/main/java/pl/mk5/gdx/fireapp/android/database/DataSnapshotResolver.java
1718
/* * Copyright 2019 mk * * 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 pl.mk5.gdx.fireapp.android.database; import com.badlogic.gdx.utils.reflect.ClassReflection; import com.google.firebase.database.DataSnapshot; import java.util.Collections; import java.util.List; import pl.mk5.gdx.fireapp.promises.ConverterPromise; class DataSnapshotResolver { private final Class dataType; private final ConverterPromise promise; DataSnapshotResolver(Class dataType, ConverterPromise promise) { this.dataType = dataType; this.promise = promise; } void resolve(DataSnapshot dataSnapshot) { if (ClassReflection.isAssignableFrom(List.class, dataType) && dataSnapshot.getValue() == null) { promise.doComplete(Collections.emptyList()); } else if (ClassReflection.isAssignableFrom(List.class, dataType) && ResolverDataSnapshotList.shouldResolveOrderBy(dataType, dataSnapshot)) { promise.doComplete(ResolverDataSnapshotList.resolve(dataSnapshot)); } else { promise.doComplete(dataSnapshot.getValue()); } } public ConverterPromise getPromise() { return promise; } }
apache-2.0
hm-yap/service-mesc
src/main/java/com/mesc/service/entity/PhoneProblem.java
783
package com.mesc.service.entity; import java.math.BigDecimal; import javax.persistence.AttributeOverride; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name = "phone_problem") @AttributeOverride(name = "guid", column = @Column(name = "pp_id") ) public class PhoneProblem extends BaseEntity { private static final long serialVersionUID = 1472030457662135436L; private String detail; private BigDecimal partsAmt; public PhoneProblem() { super(); } public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } public BigDecimal getPartsAmt() { return partsAmt; } public void setPartsAmt(BigDecimal partsAmt) { this.partsAmt = partsAmt; } }
apache-2.0
BeamFoundry/spring-osgi
spring-dm/core/src/main/java/org/springframework/osgi/util/OsgiPlatformDetector.java
3743
/* * Copyright 2006-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.springframework.osgi.util; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.springframework.util.Assert; /** * Utility class that detects the running platform. Useful when certain quirks * or tweaks have to made for a specific implementations. * * Currently we can detect Equinox, Knopflerfish and Felix platforms. * * @author Adrian Colyer * @author Costin Leau */ public abstract class OsgiPlatformDetector { private static final String[] EQUINOX_LABELS = new String[] { "Eclipse", "eclipse", "Equinox", "equinox", }; private static final String[] KF_LABELS = new String[] { "Knopflerfish", "knopflerfish" }; private static final String[] FELIX_LABELS = new String[] { "Apache Software Foundation", "Felix", "felix" }; /** * Returns true if the given bundle context belongs to the Equinox platform. * * @param bundleContext OSGi bundle context * @return true if the context indicates Equinox platform, false otherwise */ public static boolean isEquinox(BundleContext bundleContext) { return determinePlatform(bundleContext, EQUINOX_LABELS); } /** * Returns true if the given bundle context belongs to the Knopflerfish * platform. * * @param bundleContext OSGi bundle context * @return true if the context indicates Knopflerfish platform, false * otherwise */ public static boolean isKnopflerfish(BundleContext bundleContext) { return determinePlatform(bundleContext, KF_LABELS); } /** * Returns true if the given bundle context belongs to the Felix platform. * * @param bundleContext OSGi bundle context * @return true if the context indicates Felix platform, false otherwise */ public static boolean isFelix(BundleContext bundleContext) { return determinePlatform(bundleContext, FELIX_LABELS); } private static boolean determinePlatform(BundleContext context, String[] labels) { Assert.notNull(context); Assert.notNull(labels); String vendorProperty = context.getProperty(Constants.FRAMEWORK_VENDOR); if (vendorProperty == null) { return false; // might be running outside of container } else { // code defensively here to allow for variation in vendor name over // time if (containsAnyOf(vendorProperty, labels)) { return true; } } return false; } private static boolean containsAnyOf(String source, String[] searchTerms) { for (int i = 0; i < searchTerms.length; i++) { if (source.indexOf(searchTerms[i]) != -1) { return true; } } return false; } /** * Returns the OSGi platform version (using the manifest entries from the * system bundle). The version can be empty. * * @param bundleContext bundle context to inspect * @return not-null system bundle version */ public static String getVersion(BundleContext bundleContext) { if (bundleContext == null) return ""; // get system bundle Bundle sysBundle = bundleContext.getBundle(0); // force string conversion instead of casting just to be safe return "" + sysBundle.getHeaders().get(Constants.BUNDLE_VERSION); } }
apache-2.0
adligo/fabricate.adligo.org
src/org/adligo/fabricate/common/I_FabStage.java
829
package org.adligo.fabricate.common; /** * I_FabTask is a interface to allow plug-able * tasks to be called from fabricate. It is generally * assumed that I_FabTask's are NOT concurrent * and only one at a time will run on the fabricate * environment. * The run method should be thread safe since * it will be called by multiple threads, any memory * should also use the concurrent collections. * * @author scott * */ public interface I_FabStage extends Runnable { public void setStageName(String stageName); public void setup(I_RunContext ctx); public boolean isConcurrent(); /** * The thread that calls this method * will be blocked until it is notified * that it is ok to continue */ public void waitUntilFinished(); public boolean hadException(); public Exception getException(); }
apache-2.0
Mrsunsunshine/ForElder
FallDetector/src/org/heartwings/care/falldetect/HighPassFilter.java
296
package org.heartwings.care.falldetect; /** * @author Wave */ public class HighPassFilter { LowPassFilter lpf; public HighPassFilter(double tau, double dt) { lpf = new LowPassFilter(tau, dt); } public double nextValue(double current) { return current - lpf.nextValue(current); } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-waf/src/main/java/com/amazonaws/services/waf/model/waf_regional/transform/PutLoggingConfigurationRequestMarshaller.java
2152
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.waf.model.waf_regional.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.waf.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * PutLoggingConfigurationRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class PutLoggingConfigurationRequestMarshaller { private static final MarshallingInfo<StructuredPojo> LOGGINGCONFIGURATION_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("LoggingConfiguration").build(); private static final PutLoggingConfigurationRequestMarshaller instance = new PutLoggingConfigurationRequestMarshaller(); public static PutLoggingConfigurationRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(PutLoggingConfigurationRequest putLoggingConfigurationRequest, ProtocolMarshaller protocolMarshaller) { if (putLoggingConfigurationRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(putLoggingConfigurationRequest.getLoggingConfiguration(), LOGGINGCONFIGURATION_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
aehlig/bazel
src/main/java/com/google/devtools/build/lib/remote/http/AbstractHttpHandler.java
6378
// Copyright 2018 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.remote.http; import com.google.auth.Credentials; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableList; import com.google.common.io.BaseEncoding; import com.google.devtools.build.lib.analysis.BlazeVersionInfo; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelOutboundHandler; import io.netty.channel.ChannelPromise; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.HttpRequest; import java.io.IOException; import java.net.SocketAddress; import java.net.URI; import java.nio.channels.ClosedChannelException; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** Common functionality shared by concrete classes. */ abstract class AbstractHttpHandler<T extends HttpObject> extends SimpleChannelInboundHandler<T> implements ChannelOutboundHandler { private static final String USER_AGENT_VALUE = "bazel/" + BlazeVersionInfo.instance().getVersion(); private final Credentials credentials; private final ImmutableList<Entry<String, String>> extraHttpHeaders; public AbstractHttpHandler( Credentials credentials, ImmutableList<Entry<String, String>> extraHttpHeaders) { this.credentials = credentials; this.extraHttpHeaders = extraHttpHeaders; } protected ChannelPromise userPromise; @SuppressWarnings("FutureReturnValueIgnored") protected void failAndResetUserPromise(Throwable t) { if (userPromise != null && !userPromise.isDone()) { userPromise.setFailure(t); } userPromise = null; } @SuppressWarnings("FutureReturnValueIgnored") protected void succeedAndResetUserPromise() { userPromise.setSuccess(); userPromise = null; } protected void addCredentialHeaders(HttpRequest request, URI uri) throws IOException { String userInfo = uri.getUserInfo(); if (userInfo != null) { String value = BaseEncoding.base64Url().encode(userInfo.getBytes(Charsets.UTF_8)); request.headers().set(HttpHeaderNames.AUTHORIZATION, "Basic " + value); return; } if (credentials == null || !credentials.hasRequestMetadata()) { return; } Map<String, List<String>> authHeaders = credentials.getRequestMetadata(uri); if (authHeaders == null || authHeaders.isEmpty()) { return; } for (Map.Entry<String, List<String>> entry : authHeaders.entrySet()) { String name = entry.getKey(); for (String value : entry.getValue()) { request.headers().add(name, value); } } } protected void addExtraRemoteHeaders(HttpRequest request) { for (Map.Entry<String, String> header : extraHttpHeaders) { request.headers().add(header.getKey(), header.getValue()); } } protected void addUserAgentHeader(HttpRequest request) { request.headers().set(HttpHeaderNames.USER_AGENT, USER_AGENT_VALUE); } protected String constructPath(URI uri, String hash, boolean isCas) { StringBuilder builder = new StringBuilder(); builder.append(uri.getPath()); if (!uri.getPath().endsWith("/")) { builder.append("/"); } builder.append(isCas ? HttpBlobStore.CAS_PREFIX : HttpBlobStore.AC_PREFIX); builder.append(hash); return builder.toString(); } protected String constructHost(URI uri) { boolean includePort = (uri.getPort() > 0) && ((uri.getScheme().equals("http") && uri.getPort() != 80) || (uri.getScheme().equals("https") && uri.getPort() != 443)); return uri.getHost() + (includePort ? ":" + uri.getPort() : ""); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable t) { failAndResetUserPromise(t); ctx.fireExceptionCaught(t); } @SuppressWarnings("FutureReturnValueIgnored") @Override public void bind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) { ctx.bind(localAddress, promise); } @SuppressWarnings("FutureReturnValueIgnored") @Override public void connect( ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) { ctx.connect(remoteAddress, localAddress, promise); } @SuppressWarnings("FutureReturnValueIgnored") @Override public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) { failAndResetUserPromise(new ClosedChannelException()); ctx.disconnect(promise); } @SuppressWarnings("FutureReturnValueIgnored") @Override public void close(ChannelHandlerContext ctx, ChannelPromise promise) { failAndResetUserPromise(new ClosedChannelException()); ctx.close(promise); } @SuppressWarnings("FutureReturnValueIgnored") @Override public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) { failAndResetUserPromise(new ClosedChannelException()); ctx.deregister(promise); } @SuppressWarnings("FutureReturnValueIgnored") @Override public void read(ChannelHandlerContext ctx) { ctx.read(); } @SuppressWarnings("FutureReturnValueIgnored") @Override public void flush(ChannelHandlerContext ctx) { ctx.flush(); } @Override public void channelInactive(ChannelHandlerContext ctx) { failAndResetUserPromise(new ClosedChannelException()); ctx.fireChannelInactive(); } @Override public void handlerRemoved(ChannelHandlerContext ctx) { failAndResetUserPromise(new IOException("handler removed")); } @Override public void channelUnregistered(ChannelHandlerContext ctx) { failAndResetUserPromise(new ClosedChannelException()); ctx.fireChannelUnregistered(); } }
apache-2.0
RoelandSalij/EmailModuleWithTemplates
src/EmailModuleWithTemplates/javasource/encryption/actions/DecryptString.java
2364
// This file was generated by Mendix Modeler. // // WARNING: Only the following code will be retained when actions are regenerated: // - the import list // - the code between BEGIN USER CODE and END USER CODE // - the code between BEGIN EXTRA CODE and END EXTRA CODE // Other code you write will be lost the next time you deploy the project. // Special characters, e.g., é, ö, à, etc. are supported in comments. package encryption.actions; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; import com.mendix.systemwideinterfaces.MendixRuntimeException; import com.mendix.systemwideinterfaces.core.IContext; import com.mendix.webui.CustomJavaAction; public class DecryptString extends CustomJavaAction<java.lang.String> { private java.lang.String value; private java.lang.String key; private java.lang.String prefix; public DecryptString(IContext context, java.lang.String value, java.lang.String key, java.lang.String prefix) { super(context); this.value = value; this.key = key; this.prefix = prefix; } @Override public java.lang.String executeAction() throws Exception { // BEGIN USER CODE if (value == null || !value.startsWith(prefix)) return null; if (prefix == null || prefix.isEmpty()) throw new MendixRuntimeException("Prefix should not be empty"); if (key == null || key.isEmpty()) throw new MendixRuntimeException("Key should not be empty"); if (key.length() != 16) throw new MendixRuntimeException("Key length should be 16"); Cipher c = Cipher.getInstance("AES/CBC/PKCS5PADDING"); SecretKeySpec k = new SecretKeySpec(key.getBytes(), "AES"); String[] s = value.substring(prefix.length()).split(";"); if (s.length < 2) //Not an encrypted string, just return the original value. return value; byte[] iv = Base64.decodeBase64(s[0].getBytes()); byte[] encryptedData = Base64.decodeBase64(s[1].getBytes()); c.init(Cipher.DECRYPT_MODE, k, new IvParameterSpec(iv)); return new String(c.doFinal(encryptedData)); // END USER CODE } /** * Returns a string representation of this action */ @Override public java.lang.String toString() { return "DecryptString"; } // BEGIN EXTRA CODE // END EXTRA CODE }
apache-2.0
daxslab/daxSmail
src/com/daxslab/mail/mail/store/imap/ImapUtility.java
4342
/* * Copyright (C) 2012 The K-9 Dog Walkers * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.daxslab.mail.mail.store.imap; import android.util.Log; import com.daxslab.mail.K9; import java.util.ArrayList; import java.util.List; /** * Utility methods for use with IMAP. */ public class ImapUtility { /** * Gets all of the values in a sequence set per RFC 3501. * * <p> * Any ranges are expanded into a list of individual numbers. * </p> * * <pre> * sequence-number = nz-number / "*" * sequence-range = sequence-number ":" sequence-number * sequence-set = (sequence-number / sequence-range) *("," sequence-set) * </pre> * * @param set * The sequence set string as received by the server. * * @return The list of IDs as strings in this sequence set. If the set is invalid, an empty * list is returned. */ public static List<String> getImapSequenceValues(String set) { ArrayList<String> list = new ArrayList<String>(); if (set != null) { String[] setItems = set.split(","); for (String item : setItems) { if (item.indexOf(':') == -1) { // simple item if (isNumberValid(item)) { list.add(item); } } else { // range list.addAll(getImapRangeValues(item)); } } } return list; } /** * Expand the given number range into a list of individual numbers. * * <pre> * sequence-number = nz-number / "*" * sequence-range = sequence-number ":" sequence-number * sequence-set = (sequence-number / sequence-range) *("," sequence-set) * </pre> * * @param range * The range string as received by the server. * * @return The list of IDs as strings in this range. If the range is not valid, an empty list * is returned. */ public static List<String> getImapRangeValues(String range) { ArrayList<String> list = new ArrayList<String>(); try { if (range != null) { int colonPos = range.indexOf(':'); if (colonPos > 0) { long first = Long.parseLong(range.substring(0, colonPos)); long second = Long.parseLong(range.substring(colonPos + 1)); if (is32bitValue(first) && is32bitValue(second)) { if (first < second) { for (long i = first; i <= second; i++) { list.add(Long.toString(i)); } } else { for (long i = first; i >= second; i--) { list.add(Long.toString(i)); } } } else { Log.d(K9.LOG_TAG, "Invalid range: " + range); } } } } catch (NumberFormatException e) { Log.d(K9.LOG_TAG, "Invalid range value: " + range, e); } return list; } private static boolean isNumberValid(String number) { try { long value = Long.parseLong(number); if (is32bitValue(value)) { return true; } } catch (NumberFormatException e) { // do nothing } Log.d(K9.LOG_TAG, "Invalid UID value: " + number); return false; } private static boolean is32bitValue(long value) { return ((value & ~0xFFFFFFFFL) == 0L); } }
apache-2.0
mohanaraosv/commons-beanutils
src/test/java/org/apache/commons/beanutils/converters/FloatConverterTestCase.java
5007
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import junit.framework.TestSuite; import org.apache.commons.beanutils.Converter; /** * Test Case for the FloatConverter class. * * @version $Id$ */ public class FloatConverterTestCase extends NumberConverterTestBase { private Converter converter = null; // ------------------------------------------------------------------------ public FloatConverterTestCase(final String name) { super(name); } // ------------------------------------------------------------------------ @Override public void setUp() throws Exception { converter = makeConverter(); numbers[0] = new Float("-12"); numbers[1] = new Float("13"); numbers[2] = new Float("-22"); numbers[3] = new Float("23"); } public static TestSuite suite() { return new TestSuite(FloatConverterTestCase.class); } @Override public void tearDown() throws Exception { converter = null; } // ------------------------------------------------------------------------ @Override protected NumberConverter makeConverter() { return new FloatConverter(); } @Override protected NumberConverter makeConverter(final Object defaultValue) { return new FloatConverter(defaultValue); } @Override protected Class<?> getExpectedType() { return Float.class; } // ------------------------------------------------------------------------ public void testSimpleConversion() throws Exception { final String[] message= { "from String", "from String", "from String", "from String", "from String", "from String", "from String", "from Byte", "from Short", "from Integer", "from Long", "from Float", "from Double" }; final Object[] input = { String.valueOf(Float.MIN_VALUE), "-17.2", "-1.1", "0.0", "1.1", "17.2", String.valueOf(Float.MAX_VALUE), new Byte((byte)7), new Short((short)8), new Integer(9), new Long(10), new Float(11.1), new Double(12.2), }; final Float[] expected = { new Float(Float.MIN_VALUE), new Float(-17.2), new Float(-1.1), new Float(0.0), new Float(1.1), new Float(17.2), new Float(Float.MAX_VALUE), new Float(7), new Float(8), new Float(9), new Float(10), new Float(11.1), new Float(12.2) }; for(int i=0;i<expected.length;i++) { assertEquals( message[i] + " to Float", expected[i].floatValue(), (converter.convert(Float.class,input[i])).floatValue(), 0.00001); assertEquals( message[i] + " to float", expected[i].floatValue(), (converter.convert(Float.TYPE,input[i])).floatValue(), 0.00001); assertEquals( message[i] + " to null type", expected[i].floatValue(), ((Float)(converter.convert(null,input[i]))).floatValue(), 0.00001); } } /** * Test Invalid Amounts (too big/small) */ public void testInvalidAmount() { final Converter converter = makeConverter(); final Class<?> clazz = Float.class; final Double max = new Double(Float.MAX_VALUE); final Double tooBig = new Double(Double.MAX_VALUE); // Maximum assertEquals("Maximum", new Float(Float.MAX_VALUE), converter.convert(clazz, max)); // Too Large try { assertEquals("Too Big", null, converter.convert(clazz, tooBig)); fail("More than maximum, expected ConversionException"); } catch (final Exception e) { // expected result } } }
apache-2.0
javild/opencga
opencga-storage/opencga-storage-hadoop/src/main/java/org/opencb/opencga/storage/hadoop/alignment/HadoopAlignmentDBAdaptor.java
1825
/* * Copyright 2015-2016 OpenCB * * 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.opencb.opencga.storage.hadoop.alignment; import org.opencb.biodata.models.core.Region; import org.opencb.commons.datastore.core.QueryOptions; import org.opencb.commons.datastore.core.QueryResult; import org.opencb.opencga.storage.core.alignment.adaptors.AlignmentDBAdaptor; import java.util.List; /** * Created by imedina on 16/06/15. */ public class HadoopAlignmentDBAdaptor implements AlignmentDBAdaptor { @Override public QueryResult getAllAlignmentsByRegion(List<Region> regions, QueryOptions options) { return null; } @Override public QueryResult getAllAlignmentsByGene(String gene, QueryOptions options) { return null; } @Override public QueryResult getCoverageByRegion(Region region, QueryOptions options) { return null; } @Override public QueryResult getAlignmentsHistogramByRegion(Region region, boolean histogramLogarithm, int histogramMax) { return null; } @Override public QueryResult getAllIntervalFrequencies(Region region, QueryOptions options) { return null; } @Override public QueryResult getAlignmentRegionInfo(Region region, QueryOptions options) { return null; } }
apache-2.0
sstafford/gerrit-rest-java-client
src/test/java/com/urswolfer/gerrit/client/rest/http/changes/ReviewerInfoParserTest.java
1840
/* * Copyright 2013-2015 Urs Wolfer * * 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.urswolfer.gerrit.client.rest.http.changes; import com.google.common.truth.Truth; import com.google.gerrit.extensions.common.ReviewerInfo; import com.google.gson.JsonElement; import com.urswolfer.gerrit.client.rest.http.common.AbstractParserTest; import org.testng.annotations.Test; import java.util.List; public class ReviewerInfoParserTest extends AbstractParserTest { private final ReviewerInfoParser reviewerInfoParser = new ReviewerInfoParser(getGson()); @Test public void testParseReviewerInfo() throws Exception { JsonElement jsonElement = getJsonElement("reviewer.json"); List<ReviewerInfo> reviewerInfos = reviewerInfoParser.parseReviewerInfos(jsonElement); Truth.assertThat(reviewerInfos).hasSize(1); Truth.assertThat(reviewerInfos.get(0).approvals.get("Code-Review").equals("+2")); } @Test public void testParseReviewersInfo() throws Exception { JsonElement jsonElement = getJsonElement("reviewers.json"); List<ReviewerInfo> reviewerInfos = reviewerInfoParser.parseReviewerInfos(jsonElement); Truth.assertThat(reviewerInfos).hasSize(2); Truth.assertThat(reviewerInfos.get(1).approvals.get("My-Own-Label").equals("-2")); } }
apache-2.0
dritter-hd/camel-dropbox
dev/camel-dropbox/src/test/java/org/apache/camel/dropbox/utils/DropboxConfigurationTest.java
2073
package org.apache.camel.dropbox.utils; import org.apache.camel.dropbox.component.TestUtil; import org.apache.camel.dropbox.utils.DropboxConfiguration; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class DropboxConfigurationTest { private DropboxConfiguration config; @Before public void setup() throws Exception { this.config = DropboxConfiguration.create(TestUtil.TEST_DATA_FOLDER, DropboxConfiguration.DEFAULT_RESOURCES); assertNotNull(this.config); } @Test(expected = IllegalArgumentException.class) public void testGetByKey_keyNull() throws Exception { this.config.getByKey(null); } @Test(expected = IllegalArgumentException.class) public void testGetKey_keyEmpty() throws Exception { this.config.getByKey(""); } @Test public void testGetKey_notNull() throws Exception { assertNotNull("Property file dropbox.properties has no " + DropboxConfiguration.APP_KEY + ".", this.config.getByKey(DropboxConfiguration.APP_KEY)); assertNotNull("Property file dropbox.properties has no " + DropboxConfiguration.APP_SECRET + ".", this.config.getByKey(DropboxConfiguration.APP_SECRET)); assertNotNull("Property file dropbox.properties has no " + DropboxConfiguration.TOKEN + ".", this.config.getByKey(DropboxConfiguration.TOKEN)); } @Test(expected = IllegalArgumentException.class) public void testStore_null() throws Exception { this.config.store(null, null); } @Test(expected = IllegalArgumentException.class) public void testStore_empty() throws Exception { this.config.store("", null); } @Test public void testStoreAndRemove_notNull() throws Exception { final String key = "dummy"; final String value = "myToken"; this.config.store(key, value); assertEquals(value, this.config.getByKey(key)); this.config.remove(key); assertNull(null, this.config.getByKey(key)); } }
apache-2.0
colliona/DontClickTheWhiteTile
src/main/java/bm/game/tile/view/GameView.java
1959
package bm.game.tile.view; import javafx.scene.Group; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.input.MouseEvent; import javafx.scene.paint.Color; import bm.game.tile.controller.GameController; import bm.game.tile.model.GameWindow; import bm.game.tile.model.Row; import bm.game.tile.model.Tile; /** * Class of the game view. * @author collion * */ public class GameView extends Group { /** * Delegate of the game controller. */ private GameViewDelegate delegate; /** * Canvas to draw on. */ private Canvas canvas; /** * Graphic context. */ private GraphicsContext graphicsContext; /** * Class constructor. * * @param game - the controller of the next game */ public GameView(GameController game) { this.delegate = game; setUp(); } /** * * @return - this view's reprezentative of the game controller */ public GameViewDelegate getDelegate() { return delegate; } /** * * @param delegate - this view's reprezentative of the game controller */ public void setDelegate(GameViewDelegate delegate) { this.delegate = delegate; } /** * Initializes the game view. */ private void setUp() { canvas = new Canvas(600, 600); graphicsContext = canvas.getGraphicsContext2D(); canvas.addEventHandler(MouseEvent.MOUSE_CLICKED, delegate.getClickHandler()); getChildren().add(canvas); } /** * Draws on the game window. * @param gameWindow - main window of the game */ public void draw(GameWindow gameWindow) { for (Row row : gameWindow.getRows()) { for (Tile tile : row.getTiles()) { if (tile.isBlack()) { graphicsContext.setFill(Color.BLACK); graphicsContext.fillRect(tile.getX(), row.getY(), tile.getTileWidth(), row.getRowHeight()); } else { graphicsContext.setFill(Color.WHITE); graphicsContext.fillRect(tile.getX(), row.getY(), tile.getTileWidth(), row.getRowHeight()); } } } } }
apache-2.0
joewalnes/idea-community
platform/lang-impl/src/com/intellij/openapi/module/impl/ModulePointerManagerImpl.java
3730
/* * 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.openapi.module.impl; import com.intellij.ProjectTopics; import com.intellij.openapi.Disposable; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModulePointer; import com.intellij.openapi.module.ModulePointerManager; import com.intellij.openapi.project.ModuleAdapter; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import org.jetbrains.annotations.NotNull; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author nik */ public class ModulePointerManagerImpl extends ModulePointerManager { private final Map<String, ModulePointerImpl> myUnresolved = new HashMap<String, ModulePointerImpl>(); private final Map<Module, ModulePointerImpl> myPointers = new HashMap<Module, ModulePointerImpl>(); private final Project myProject; public ModulePointerManagerImpl(Project project) { myProject = project; project.getMessageBus().connect().subscribe(ProjectTopics.MODULES, new ModuleAdapter() { @Override public void beforeModuleRemoved(Project project, Module module) { unregisterPointer(module); } @Override public void moduleAdded(Project project, Module module) { moduleAppears(module); } @Override public void modulesRenamed(Project project, List<Module> modules) { for (Module module : modules) { moduleAppears(module); } } }); } private void moduleAppears(Module module) { ModulePointerImpl pointer = myUnresolved.remove(module.getName()); if (pointer != null && pointer.getModule() == null) { pointer.moduleAdded(module); registerPointer(module, pointer); } } private void registerPointer(final Module module, final ModulePointerImpl pointer) { myPointers.put(module, pointer); Disposer.register(module, new Disposable() { public void dispose() { unregisterPointer(module); } }); } private void unregisterPointer(Module module) { final ModulePointerImpl pointer = myPointers.remove(module); if (pointer != null) { pointer.moduleRemoved(module); myUnresolved.put(pointer.getModuleName(), pointer); } } @NotNull @Override public ModulePointer create(@NotNull Module module) { ModulePointerImpl pointer = myPointers.get(module); if (pointer == null) { pointer = myUnresolved.get(module.getName()); if (pointer == null) { pointer = new ModulePointerImpl(module); } else { pointer.moduleAdded(module); } registerPointer(module, pointer); } return pointer; } @NotNull @Override public ModulePointer create(@NotNull String moduleName) { final Module module = ModuleManagerImpl.getInstance(myProject).findModuleByName(moduleName); if (module != null) { return create(module); } ModulePointerImpl pointer = myUnresolved.get(moduleName); if (pointer == null) { pointer = new ModulePointerImpl(moduleName); myUnresolved.put(moduleName, pointer); } return pointer; } }
apache-2.0
davide-maestroni/robo-fashion
library/src/main/java/com/github/dm/rf/android/entry/SparseBooleanArrayEntry.java
1960
/** * 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.dm.rf.android.entry; /** * This interface defines a {@link SparseEntry} associated with a * {@link android.util.SparseBooleanArray} collection. * <p/> * Created by davide-maestroni on 3/10/14. */ public interface SparseBooleanArrayEntry extends IntSparseBooleanEntry { /** * Returns the index inside the backing sparse collection. * * @return the entry index. */ public int getIndex(); /** * Removes this entry from the backing sparse collection. * <p/> * It has the same effect as calling {@link java.util.Iterator#remove()}. */ public void remove(); /** * Modifies the value inside the sparse collection associated with this entry key. * * @param value the new value. */ public void setValue(boolean value); /** * Returns an immutable copy of this entry. The object will just store this entry key and value * without allowing any modification of the backing sparse collection. * * @return the immutable entry. */ public IntSparseBooleanEntry toImmutable(); /** * Returns a parcelable copy of this entry. The object will just store this entry key and value * without allowing any modification of the backing sparse collection. * * @return the parcelable entry. */ public ParcelableIntSparseBooleanEntry toParcelable(); }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-memorydb/src/main/java/com/amazonaws/services/memorydb/model/transform/SecurityGroupMembershipJsonUnmarshaller.java
3090
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.memorydb.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.memorydb.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * SecurityGroupMembership JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class SecurityGroupMembershipJsonUnmarshaller implements Unmarshaller<SecurityGroupMembership, JsonUnmarshallerContext> { public SecurityGroupMembership unmarshall(JsonUnmarshallerContext context) throws Exception { SecurityGroupMembership securityGroupMembership = new SecurityGroupMembership(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("SecurityGroupId", targetDepth)) { context.nextToken(); securityGroupMembership.setSecurityGroupId(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("Status", targetDepth)) { context.nextToken(); securityGroupMembership.setStatus(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return securityGroupMembership; } private static SecurityGroupMembershipJsonUnmarshaller instance; public static SecurityGroupMembershipJsonUnmarshaller getInstance() { if (instance == null) instance = new SecurityGroupMembershipJsonUnmarshaller(); return instance; } }
apache-2.0
fivesmallq/web-data-extractor
src/test/java/im/nll/data/extractor/impl/HtmlCleanerExtractorTest.java
2269
package im.nll.data.extractor.impl; import com.google.common.base.Charsets; import com.google.common.io.Resources; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.List; /** * @author <a href="mailto:fivesmallq@gmail.com">fivesmallq</a> * @version Revision: 1.0 * @date 16/1/6 上午12:32 */ public class HtmlCleanerExtractorTest { HtmlCleanerExtractor xPathExtractor; private String baseHtml; @Before public void setUp() throws Exception { baseHtml = Resources.toString(Resources.getResource("demo1.html"), Charsets.UTF_8); } @Test public void testExtract() throws Exception { //attribute xPathExtractor = new HtmlCleanerExtractor("//div/a/@href"); String s = xPathExtractor.extract(baseHtml); Assert.assertEquals("/fivesmallq", s); //element xPathExtractor = new HtmlCleanerExtractor("//div/a[1]"); s = xPathExtractor.extract(baseHtml); Assert.assertEquals("<a href=\"/fivesmallq\" class=\"title\">fivesmallq</a>", s); //text xPathExtractor = new HtmlCleanerExtractor("//div/a[1]/text()"); s = xPathExtractor.extract(baseHtml); Assert.assertEquals("fivesmallq", s); } @Test public void testExtractList() throws Exception { //attribute xPathExtractor = new HtmlCleanerExtractor("//div/a/@href"); List<String> s = xPathExtractor.extractList(baseHtml); Assert.assertNotNull(s); Assert.assertEquals(2, s.size()); String second = s.get(1); Assert.assertEquals("/fivesmallq/followers", second); //element xPathExtractor = new HtmlCleanerExtractor("//div/a"); s = xPathExtractor.extractList(baseHtml); Assert.assertNotNull(s); Assert.assertEquals(2, s.size()); second = s.get(1); Assert.assertEquals("<a href=\"/fivesmallq/followers\">29671 Followers</a>", second); //text xPathExtractor = new HtmlCleanerExtractor("//div/a/text()"); s = xPathExtractor.extractList(baseHtml); Assert.assertNotNull(s); Assert.assertEquals(2, s.size()); second = s.get(1); Assert.assertEquals("29671 Followers", second); } }
apache-2.0
quding0308/sxrk
Sxrk/src/com/dianyitech/madaptor/activitys/templates/TeSetActivity.java
6015
package com.dianyitech.madaptor.activitys.templates; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.RelativeLayout; import android.widget.Toast; import com.dianyitech.madaptor.common.Contants; import com.dianyitech.madaptor.common.FileCacheManager; import com.dianyitech.madaptor.common.MAdaptorProgressDialog; import com.dianyitech.madaptor.common.MAlertDialog; import com.dianyitech.madaptor.httpcommunication.ActionResponse; import com.dianyitech.madaptor.httpcommunication.ServerAdaptor; import com.dianyitech.madaptor.httpcommunication.ServiceSyncListener; import java.io.File; import java.util.Map; public class TeSetActivity extends Activity { RelativeLayout clean_rel; RelativeLayout setting_rel; RelativeLayout updata_rel; public static void checkLoginUpdate(Context paramContext) { ServerAdaptor.getInstance(paramContext).checkUpdateAsync(Contants.APP_VERSION_SXRK, new ServiceSyncListener() { public void onError(ActionResponse paramAnonymousActionResponse) { Toast.makeText(TeSetActivity.this, 2131427511, 0).show(); } public void onSuccess(ActionResponse paramAnonymousActionResponse) { if (paramAnonymousActionResponse.getData() == null) Toast.makeText(TeSetActivity.this, 2131427511, 0).show(); while (true) { return; Map localMap = (Map)paramAnonymousActionResponse.getData(); if (!"0".equals((String)localMap.get("update"))) { Toast.makeText(TeSetActivity.this, 2131427512, 0).show(); } else { String str1 = (String)localMap.get("version"); String str2 = (String)localMap.get("url"); if (Long.parseLong(str1) > Long.parseLong(Contants.APP_VERSION_SXRK)) TeSetActivity.updateLoginRemind(TeSetActivity.this, str2, str1); else Toast.makeText(TeSetActivity.this, 2131427512, 1).show(); } } } }); } public static void downloadApkLogin(Context paramContext, String paramString1, String paramString2) { ServerAdaptor.getInstance(paramContext).downloadApk(paramString1, new ServiceSyncListener() { public void onError(ActionResponse paramAnonymousActionResponse) { MAdaptorProgressDialog.dismiss(); Toast.makeText(TeSetActivity.this, "更新失败!", 1).show(); } public void onSuccess(ActionResponse paramAnonymousActionResponse) { File localFile = new File(TeSetActivity.this.getFilesDir().toString()); if (localFile.exists()) { FileCacheManager.deleteAllFiles(localFile); FileCacheManager.deleteAllFiles(TeSetActivity.this.getFilesDir()); } String str = Environment.getExternalStorageDirectory() + "/MAdaptor_V2.apk"; Intent localIntent = new Intent("android.intent.action.VIEW"); localIntent.setDataAndType(Uri.fromFile(new File(str)), "application/vnd.android.package-archive"); TeSetActivity.this.startActivity(localIntent); MAdaptorProgressDialog.dismiss(); Toast.makeText(TeSetActivity.this, "更新成功,正在安装!", 1).show(); } }); } public static void updateLoginRemind(Context paramContext, final String paramString1, final String paramString2) { MAlertDialog localMAlertDialog = new MAlertDialog(paramContext); localMAlertDialog.setTitle(2131427513); localMAlertDialog.setMessage("已有更新,是否需要下载"); localMAlertDialog.setPositiveButton(2131427356, new View.OnClickListener() { public void onClick(View paramAnonymousView) { MAdaptorProgressDialog.show(TeSetActivity.this, "数据获取中", "数据读取中,请稍等...", true, null); TeSetActivity.downloadApkLogin(TeSetActivity.this, paramString1, paramString2); } }); localMAlertDialog.setNegativeButton(2131427361, new View.OnClickListener() { public void onClick(View paramAnonymousView) { TeSetActivity.this.dismiss(); } }); localMAlertDialog.show(); } protected void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); setContentView(2130903060); this.setting_rel = ((RelativeLayout)findViewById(2131361913)); this.setting_rel.setOnClickListener(new View.OnClickListener() { public void onClick(View paramAnonymousView) { Intent localIntent = new Intent(); localIntent.setClass(TeSetActivity.this, TeSettingActivity.class); TeSetActivity.this.startActivity(localIntent); } }); this.clean_rel = ((RelativeLayout)findViewById(2131361914)); this.clean_rel.setOnClickListener(new View.OnClickListener() { public void onClick(View paramAnonymousView) { File localFile = new File(TeSetActivity.this.getFilesDir().toString()); if (localFile.exists()) { FileCacheManager.deleteAllFiles(localFile); FileCacheManager.deleteAllFiles(TeSetActivity.this.getFilesDir()); } } }); this.updata_rel = ((RelativeLayout)findViewById(2131361915)); this.updata_rel.setOnClickListener(new View.OnClickListener() { public void onClick(View paramAnonymousView) { TeSetActivity.checkLoginUpdate(TeSetActivity.this); } }); ((Button)findViewById(2131361917)).setOnClickListener(new View.OnClickListener() { public void onClick(View paramAnonymousView) { TeSetActivity.this.finish(); } }); } } /* Location: /Users/zqq/Downloads/联通软件 2/classes.jar * Qualified Name: com.dianyitech.madaptor.activitys.templates.TeSetActivity * JD-Core Version: 0.6.2 */
apache-2.0
xyfreemind/trader
src/main/java/trader/services/TradingService.java
647
package trader.services; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import trader.models.Quote; //import trader.repositories.MarketRepository; import trader.repositories.QuoteRepository; @Service public class TradingService { // @Autowired // private MarketRepository markets; @Autowired private QuoteRepository quotes; @Transactional(readOnly=true) public List<Quote> getQuotes() { return quotes.findByEnabled(true); } }
apache-2.0
goodwinnk/intellij-community
platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/RemoteExternalSystemTaskManager.java
4185
/* * Copyright 2000-2013 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.openapi.externalSystem.service.remote; import com.intellij.openapi.externalSystem.model.ExternalSystemException; import com.intellij.openapi.externalSystem.model.settings.ExternalSystemExecutionSettings; import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId; import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListener; import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType; import com.intellij.openapi.externalSystem.service.RemoteExternalSystemService; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.rmi.RemoteException; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; /** * @author Denis Zhdanov * @since 4/9/13 7:02 PM */ public interface RemoteExternalSystemTaskManager<S extends ExternalSystemExecutionSettings> extends RemoteExternalSystemService<S> { /** <a href="http://en.wikipedia.org/wiki/Null_Object_pattern">Null object</a> for {@link RemoteExternalSystemProjectResolverImpl}. */ RemoteExternalSystemTaskManager<ExternalSystemExecutionSettings> NULL_OBJECT = new RemoteExternalSystemTaskManager<ExternalSystemExecutionSettings>() { @Override public void executeTasks(@NotNull ExternalSystemTaskId id, @NotNull List<String> taskNames, @NotNull String projectPath, @Nullable ExternalSystemExecutionSettings settings, @Nullable String jvmAgentSetup) throws ExternalSystemException { } @Override public boolean cancelTask(@NotNull ExternalSystemTaskId id) throws ExternalSystemException { return false; } @Override public void setSettings(@NotNull ExternalSystemExecutionSettings settings) { } @Override public void setNotificationListener(@NotNull ExternalSystemTaskNotificationListener notificationListener) { } @Override public boolean isTaskInProgress(@NotNull ExternalSystemTaskId id) { return false; } @NotNull @Override public Map<ExternalSystemTaskType, Set<ExternalSystemTaskId>> getTasksInProgress() { return Collections.emptyMap(); } }; /** * @deprecated use {@link RemoteExternalSystemTaskManager#executeTasks(ExternalSystemTaskId, List, String, ExternalSystemExecutionSettings, String)} */ @Deprecated default void executeTasks(@NotNull ExternalSystemTaskId id, @NotNull List<String> taskNames, @NotNull String projectPath, @Nullable S settings, @NotNull List<String> vmOptions, @NotNull List<String> scriptParameters, @Nullable String jvmAgentSetup) throws RemoteException, ExternalSystemException { } default void executeTasks(@NotNull ExternalSystemTaskId id, @NotNull List<String> taskNames, @NotNull String projectPath, @Nullable S settings, @Nullable String jvmAgentSetup) throws RemoteException, ExternalSystemException { executeTasks(id, taskNames, projectPath, settings, Collections.emptyList(), Collections.emptyList(), jvmAgentSetup); } @Override boolean cancelTask(@NotNull ExternalSystemTaskId id) throws RemoteException, ExternalSystemException; }
apache-2.0
blakeaholics/Festical
app/src/main/java/com/cinemattson/festical/fragment/NavigationDrawerFragment.java
9778
package com.cinemattson.festical.fragment; import android.app.Activity; import android.content.SharedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.content.res.TypedArray; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import com.cinemattson.festical.R; import com.cinemattson.festical.adapter.DrawerMenuAdapter; import com.cinemattson.festical.fragment.api.BaseFragment; import com.cinemattson.festical.model.DrawerMenuBean; import java.util.ArrayList; /** * Fragment utilizado para o gerenciamento de interações para e apresentação do menu drawer. */ public class NavigationDrawerFragment extends BaseFragment { private static final String TAG = NavigationDrawerFragment.class.getSimpleName(); /** * Lembra a posição do item selecionado. */ private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position"; /** * Por as diretrizes de design, você deve mostrar o menu drawer até que o usuário expande ele manualmente. */ private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned"; /** * A pointer to the current callbacks instance (the Activity). */ private NavigationDrawerCallbacks mCallbacks; /** * Componente */ private ActionBarDrawerToggle mDrawerToggle; private DrawerLayout mDrawerLayout; private ListView mDrawerListView; private View mFragmentContainerView; private int mCurrentSelectedPosition = 0; private boolean mFromSavedInstanceState; private boolean mUserLearnedDrawer; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Read in the flag indicating whether or not the user has // s demonstrated awareness of the // drawer. See PREF_USER_LEARNED_DRAWER for details. SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity()); mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false); if (savedInstanceState != null) { mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION); mFromSavedInstanceState = true; } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mDrawerListView = (ListView) inflater.inflate(R.layout.fragment_drawer_menu, container, false); loadListeners(); loadInfoView(); return mDrawerListView; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setHasOptionsMenu(true); } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mCallbacks = (NavigationDrawerCallbacks) activity; } catch (ClassCastException e) { throw new ClassCastException("Activity must implement NavigationDrawerCallbacks."); } } @Override public void onDetach() { super.onDetach(); mCallbacks = null; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Forward the new configuration the drawer toggle component. mDrawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { if (mDrawerLayout != null) { if (isDrawerOpen()) { mDrawerLayout.closeDrawer(mFragmentContainerView); } else { mDrawerLayout.openDrawer(mFragmentContainerView); } } else { getActivity().finish(); } } return super.onOptionsItemSelected(item); } private void loadListeners() { mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectItem(position); } }); } private void loadInfoView() { ArrayList<DrawerMenuBean> menuDrawerListItens = loadMenuDrawerItens(); if (menuDrawerListItens != null) { DrawerMenuAdapter drawerMenuAdapter = new DrawerMenuAdapter(mContext, menuDrawerListItens); mDrawerListView.setAdapter(drawerMenuAdapter); mDrawerListView.setItemChecked(mCurrentSelectedPosition, true); } } private ArrayList<DrawerMenuBean> loadMenuDrawerItens() { String[] menuDrawerTitleArray; ArrayList<DrawerMenuBean> menuDrawerListItens = null; try { menuDrawerTitleArray = getActivity().getResources().getStringArray(R.array.fragment_drawerMenu_title); TypedArray imgs = getActivity().getResources().obtainTypedArray(R.array.fragment_drawerMenu_icon); int i = 0; menuDrawerListItens = new ArrayList<>(); for (String aMenuDrawerTitleArray : menuDrawerTitleArray) { menuDrawerListItens.add(new DrawerMenuBean(aMenuDrawerTitleArray, imgs.getResourceId(i, -1))); i++; } return menuDrawerListItens; } catch (Resources.NotFoundException notFoundExcepetion) { Log.e(TAG, "Error Getting The Array", notFoundExcepetion); } return menuDrawerListItens; } public boolean isDrawerOpen() { return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView); } public void setUp(int fragmentId, DrawerLayout drawerLayout) { mFragmentContainerView = getActivity().findViewById(fragmentId); mDrawerLayout = drawerLayout; // set a custom shadow that overlays the main content when the drawer opens mDrawerLayout.setDrawerShadow(R.drawable.ic_drawer_menu_shadow, GravityCompat.START); // set up the drawer's list view with items and click listener // ActionBarDrawerToggle ties together the the proper interactions // between the navigation drawer and the action bar app icon. mDrawerToggle = new ActionBarDrawerToggle( getActivity(), /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.string.app_name, /* "open drawer" description for accessibility */ R.string.app_name /* "close drawer" description for accessibility */ ) { @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); if (!isAdded()) { return; } getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu() } @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); if (!isAdded()) { return; } if (!mUserLearnedDrawer) { // The user manually opened the drawer; store this flag to prevent auto-showing // the navigation drawer automatically in the future. mUserLearnedDrawer = true; SharedPreferences sp = PreferenceManager .getDefaultSharedPreferences(getActivity()); sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply(); } getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu() } }; // If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer, // per the navigation drawer design guidelines. if (!mUserLearnedDrawer && !mFromSavedInstanceState) { mDrawerLayout.openDrawer(mFragmentContainerView); } mDrawerToggle.setDrawerIndicatorEnabled(true); // Defer code dependent on restoration of previous instance state. mDrawerLayout.post(new Runnable() { @Override public void run() { mDrawerToggle.syncState(); } }); mDrawerLayout.setDrawerListener(mDrawerToggle); } private void selectItem(int position) { mCurrentSelectedPosition = position; if (mDrawerListView != null) { mDrawerListView.setItemChecked(position, true); } if (mDrawerLayout != null) { mDrawerLayout.closeDrawer(mFragmentContainerView); } if (mCallbacks != null) { mCallbacks.onNavigationDrawerItemSelected(position); } } public static interface NavigationDrawerCallbacks { /** * Called when an item in the navigation drawer is selected. */ void onNavigationDrawerItemSelected(int position); } }
apache-2.0
pantsbuild/ivy
src/java/org/apache/ivy/tools/analyser/JarJarDependencyAnalyser.java
4118
/* * 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.ivy.tools.analyser; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.apache.ivy.core.module.descriptor.DefaultDependencyDescriptor; import org.apache.ivy.core.module.descriptor.DefaultModuleDescriptor; import org.apache.ivy.core.module.descriptor.ModuleDescriptor; import org.apache.ivy.util.Message; public class JarJarDependencyAnalyser implements DependencyAnalyser { private File jarjarjarLocation; public JarJarDependencyAnalyser(File jarjarjarLocation) { this.jarjarjarLocation = jarjarjarLocation; } public ModuleDescriptor[] analyze(JarModule[] modules) { StringBuffer jarjarCmd = new StringBuffer("java -jar \"").append( jarjarjarLocation.getAbsolutePath()).append("\" --find --level=jar "); Map jarModulesMap = new HashMap(); Map mds = new HashMap(); for (int i = 0; i < modules.length; i++) { jarModulesMap.put(modules[i].getJar().getAbsolutePath(), modules[i]); DefaultModuleDescriptor md = DefaultModuleDescriptor.newBasicInstance(modules[i] .getMrid(), new Date(modules[i].getJar().lastModified())); mds.put(modules[i].getMrid(), md); jarjarCmd.append("\"").append(modules[i].getJar().getAbsolutePath()).append("\""); if (i + 1 < modules.length) { jarjarCmd.append(File.pathSeparator); } } Message.verbose("jarjar command: " + jarjarCmd); try { Process p = Runtime.getRuntime().exec(jarjarCmd.toString()); BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; while ((line = r.readLine()) != null) { String[] deps = line.split(" -> "); JarModule module = (JarModule) jarModulesMap.get(deps[0]); JarModule dependency = (JarModule) jarModulesMap.get(deps[1]); if (module.getMrid().getModuleId().equals(dependency.getMrid().getModuleId())) { continue; } Message.verbose(module.getMrid() + " depends on " + dependency.getMrid()); DefaultModuleDescriptor md = (DefaultModuleDescriptor) mds.get(module.getMrid()); DefaultDependencyDescriptor dd = new DefaultDependencyDescriptor(md, dependency .getMrid(), false, false, true); dd.addDependencyConfiguration(ModuleDescriptor.DEFAULT_CONFIGURATION, ModuleDescriptor.DEFAULT_CONFIGURATION); md.addDependency(dd); } } catch (IOException e) { Message.debug(e); } return (ModuleDescriptor[]) mds.values().toArray(new ModuleDescriptor[mds.values().size()]); } public static void main(String[] args) { JarJarDependencyAnalyser a = new JarJarDependencyAnalyser(new File( "D:/temp/test2/jarjar-0.7.jar")); a.analyze(new JarModuleFinder( "D:/temp/test2/ivyrep/[organisation]/[module]/[revision]/[artifact].[ext]") .findJarModules()); } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-robomaker/src/main/java/com/amazonaws/services/robomaker/model/transform/ComputeResponseJsonUnmarshaller.java
3254
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.robomaker.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.robomaker.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * ComputeResponse JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ComputeResponseJsonUnmarshaller implements Unmarshaller<ComputeResponse, JsonUnmarshallerContext> { public ComputeResponse unmarshall(JsonUnmarshallerContext context) throws Exception { ComputeResponse computeResponse = new ComputeResponse(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("simulationUnitLimit", targetDepth)) { context.nextToken(); computeResponse.setSimulationUnitLimit(context.getUnmarshaller(Integer.class).unmarshall(context)); } if (context.testExpression("computeType", targetDepth)) { context.nextToken(); computeResponse.setComputeType(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("gpuUnitLimit", targetDepth)) { context.nextToken(); computeResponse.setGpuUnitLimit(context.getUnmarshaller(Integer.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return computeResponse; } private static ComputeResponseJsonUnmarshaller instance; public static ComputeResponseJsonUnmarshaller getInstance() { if (instance == null) instance = new ComputeResponseJsonUnmarshaller(); return instance; } }
apache-2.0
lyf19993/mycoolweather
app/src/main/java/com/lyf/mycoolweather/bean/AQI.java
218
package com.lyf.mycoolweather.bean; /** * Created by 刘亚飞 on 2017/3/28. */ public class AQI { public AQICity city; public class AQICity{ public String aqi; public String pm25; } }
apache-2.0
gosu-lang/old-gosu-repo
idea-gosu-plugin/src/main/java/gw/plugin/ij/lang/psi/custom/CustomGosuClassPresentation.java
1179
/* * Copyright 2013 Guidewire Software, Inc. */ package gw.plugin.ij.lang.psi.custom; import com.intellij.navigation.ColoredItemPresentation; import com.intellij.openapi.editor.colors.CodeInsightColors; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.util.Iconable; import com.intellij.psi.presentation.java.ClassPresentationUtil; import javax.swing.*; public class CustomGosuClassPresentation implements ColoredItemPresentation { private final CustomGosuClass psiClass; public CustomGosuClassPresentation(CustomGosuClass psiClass) { this.psiClass = psiClass; } @Override public String getPresentableText() { return ClassPresentationUtil.getNameForClass(psiClass, false); } @Override public String getLocationString() { return "(" + psiClass.getNamespace() + ")"; } @Override public TextAttributesKey getTextAttributesKey() { if (psiClass.isDeprecated()) { return CodeInsightColors.DEPRECATED_ATTRIBUTES; } return null; } @Override public Icon getIcon(boolean open) { return psiClass.getIcon(Iconable.ICON_FLAG_VISIBILITY | Iconable.ICON_FLAG_READ_STATUS); } }
apache-2.0
isg245/MaterialDateRangePicker
library/src/main/java/com/isg245/materialdaterangepicker/date/SimpleMonthView.java
2381
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.isg245.materialdaterangepicker.date; import android.content.Context; import android.graphics.Canvas; import android.graphics.Typeface; import android.util.AttributeSet; public class SimpleMonthView extends com.isg245.materialdaterangepicker.date.MonthView { public SimpleMonthView(Context context, AttributeSet attr, DatePickerController controller) { super(context, attr, controller); } @Override public void drawMonthDay(Canvas canvas, int year, int month, int day, int x, int y, int startX, int stopX, int startY, int stopY) { if (mSelectedDay == day) { canvas.drawCircle(x , y - (MINI_DAY_NUMBER_TEXT_SIZE / 3), DAY_SELECTED_CIRCLE_SIZE, mSelectedCirclePaint); } if(isHighlighted(year, month, day)) { mMonthNumPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD)); } else { mMonthNumPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.NORMAL)); } // If we have a mindate or maxdate, gray out the day number if it's outside the range. if (isOutOfRange(year, month, day)) { mMonthNumPaint.setColor(mDisabledDayTextColor); } else if (mSelectedDay == day) { mMonthNumPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD)); mMonthNumPaint.setColor(mSelectedDayTextColor); } else if (mHasToday && mToday == day) { mMonthNumPaint.setColor(mTodayNumberColor); } else { mMonthNumPaint.setColor(isHighlighted(year, month, day) ? mHighlightedDayTextColor : mDayTextColor); } canvas.drawText(String.format("%d", day), x, y, mMonthNumPaint); } }
apache-2.0
TheTemportalist/MIP-Data-Generator
MIPDataGenerator/src/Main/MIPDataGenerator.java
2250
package Main; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import javax.swing.JFrame; import javax.swing.JPanel; import Main.MIP.MIPData; import com.google.gson.Gson; public class MIPDataGenerator { public static MIPDataGenerator instance; public final int width, height; public JPanel panel; public MIPDataGenerator() { this.width = 800; this.height = 600; JFrame frame = new JFrame("M.I.P. Data Generator"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.panel = new Gui(this.width, this.height); frame.add(this.panel); frame.setSize(this.width, this.height); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setVisible(true); } private final Gson gson = new Gson(); private MIPData data; public String currentDataPluginID; public void setData(MIPData data) { this.data = data; } public MIPData getData() { return this.data; } public void openData(File file) { try { print("Reading data from JSON file"); print("~~~~~~~~~~~~~~~~~~~~~~~~~~~"); BufferedReader br = new BufferedReader(new FileReader(file.getAbsolutePath())); this.setData(this.gson.fromJson(br, MIPData.class)); this.currentDataPluginID = file.getName().substring(0, file.getName().lastIndexOf('.')); // print(this.currentDataPluginID + ":"); // this.getData().print(this.gson); print("~~~~~~~~~~~~~~~~~~~~~~~~~~~"); print("~~~~ Read sucessful ~~~~~~~"); } catch (IOException e) { e.printStackTrace(); } } public void saveData(File file) { String jsonDataString = this.gson.toJson(this.getData()); jsonDataString = JsonHelper.toReadableString(jsonDataString); FileWriter writer; try { file.createNewFile(); print("Writing data to JSON file"); print("~~~~~~~~~~~~~~~~~~~~~~~~~"); writer = new FileWriter(file.getAbsolutePath()); writer.write(jsonDataString); writer.close(); print("~~~~~~~~~~~~~~~~~~~~~~~~~"); print("~~~~ Write sucessful ~~~~"); } catch (IOException e) { e.printStackTrace(); } } public static void print(String str) { System.out.println(str); } }
apache-2.0
nikitin-da/sticky-dictionary
app/src/main/java/com/github/nikitin_da/sticky_dictionary/ui/fragment/AllGroupsWordListFragment.java
7929
package com.github.nikitin_da.sticky_dictionary.ui.fragment; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.widget.ListView; import com.github.nikitin_da.sticky_dictionary.R; import com.github.nikitin_da.sticky_dictionary.model.Group; import com.github.nikitin_da.sticky_dictionary.model.active.TaskListener; import com.github.nikitin_da.sticky_dictionary.ui.activity.BaseActivity; import com.github.nikitin_da.sticky_dictionary.ui.activity.GroupListForAddWordActivity; import com.github.nikitin_da.sticky_dictionary.ui.adapters.AllGroupsWordListAdapter; import com.github.nikitin_da.sticky_dictionary.ui.adapters.BaseWordListAdapter; import com.github.nikitin_da.sticky_dictionary.ui.anim.ResizeAnimation; import com.github.nikitin_da.sticky_dictionary.ui.view.floating_action_button.CustomFloatingActionButton; import com.github.nikitin_da.sticky_dictionary.util.ViewUtil; import com.nhaarman.listviewanimations.appearance.StickyListHeadersAdapterDecorator; import com.nhaarman.listviewanimations.appearance.simple.AlphaInAnimationAdapter; import com.nhaarman.listviewanimations.itemmanipulation.expandablelistitem.ExpandableListItemAdapter; import com.nhaarman.listviewanimations.util.StickyListHeadersListViewWrapper; import java.util.List; import butterknife.InjectView; import butterknife.OnClick; import se.emilsjolander.stickylistheaders.StickyListHeadersListView; /** * @author Dmitry Nikitin [nikitin.da.90@gmail.com] */ public class AllGroupsWordListFragment extends BaseWordListFragment<Group> { @InjectView(R.id.all_groups_word_list) StickyListHeadersListView listView; @InjectView(R.id.all_groups_word_list_add) CustomFloatingActionButton addButton; @InjectView(R.id.all_groups_word_list_error) View errorView; @InjectView(R.id.all_groups_word_list_empty) View emptyView; @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_all_groups_word_list, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); listView.setFitsSystemWindows(true); AlphaInAnimationAdapter animationAdapter = new AlphaInAnimationAdapter(adapter); StickyListHeadersAdapterDecorator stickyListHeadersAdapterDecorator = new StickyListHeadersAdapterDecorator(animationAdapter); stickyListHeadersAdapterDecorator.setListViewWrapper(new StickyListHeadersListViewWrapper(listView)); assert animationAdapter.getViewAnimator() != null; animationAdapter.getViewAnimator().setInitialDelayMillis(INITIAL_DELAY_MILLIS); assert stickyListHeadersAdapterDecorator.getViewAnimator() != null; stickyListHeadersAdapterDecorator.getViewAnimator().setInitialDelayMillis(INITIAL_DELAY_MILLIS); listView.setAdapter(stickyListHeadersAdapterDecorator); adapter.setExpandCollapseListener(mExpandCollapseListener); addButton.attachToListView(listView); } @Override protected void loadWords() { setUIStateShowContent(); groupActiveModel.asyncGetAllGroups(true, mGroupsListener); } private final TaskListener<List<Group>> mGroupsListener = new TaskListener<List<Group>>() { @Override public void onProblemOccurred(Throwable t) { setUIStateError(); } @Override public void onDataProcessed(List<Group> groups) { boolean empty = groups.isEmpty(); if (!empty) { boolean hasWords = false; for (Group group : groups) { if (!group.getWords().isEmpty()) { hasWords = true; break; } } if (!hasWords) { empty = true; } } if (empty) { setUIStateEmpty(); } else { setUIStateShowContent(); fillData(groups); } } }; protected void setDataToAdapter(@NonNull final List<Group> groups) { Activity activity = getActivity(); if (activity != null) { ((AllGroupsWordListAdapter) adapter).setData(groups); } } @Override protected BaseWordListAdapter createAdapter() { return new AllGroupsWordListAdapter(getActivity()); } @Override protected Animation getRemoveItemAnimation(@NonNull View viewToRemove) { return new ResizeAnimation( viewToRemove, ResizeAnimation.ResizeType.VERTICAL, false, getResources().getInteger(android.R.integer.config_mediumAnimTime)); } @Override protected void setUIStateShowContent() { ViewUtil.setVisibility(listView, true); ViewUtil.setVisibility(errorView, false); ViewUtil.setVisibility(emptyView, false); ViewUtil.setVisibility(addButton, true); } @Override protected void setUIStateError() { ViewUtil.setVisibility(listView, false); ViewUtil.setVisibility(errorView, true); ViewUtil.setVisibility(emptyView, false); ViewUtil.setVisibility(addButton, false); } @Override protected void setUIStateEmpty() { ViewUtil.setVisibility(listView, false); ViewUtil.setVisibility(errorView, false); ViewUtil.setVisibility(emptyView, true); ViewUtil.setVisibility(addButton, true); } @Override @Nullable protected ListView getListView() { return listView.getWrappedList(); } @OnClick(R.id.all_groups_word_list_add) void add() { final Activity activity = getActivity(); if (activity instanceof BaseActivity) { final Intent intent = new Intent(activity, GroupListForAddWordActivity.class); ((BaseActivity) activity).slideActivityForResult(intent, RQS_EDIT); } } @OnClick(R.id.all_groups_word_list_retry) void retry() { performLoadData(); } /** * Dirty hack that used to scroll listView bottom after expanding item * if it does not fit to screen. * Default implementation doesn't work * with {@link se.emilsjolander.stickylistheaders.StickyListHeadersListView}. */ private final ExpandableListItemAdapter.ExpandCollapseListener mExpandCollapseListener = new ExpandableListItemAdapter.ExpandCollapseListener() { @Override public void onItemExpanded(final int i) { listView.postDelayed(new Runnable() { @Override public void run() { final int listViewHeight = listView.getHeight(); final int listViewBottomPadding = listView.getPaddingBottom(); final View view = ViewUtil.getItemFromListViewByPosition(i, listView.getWrappedList()); int bottom = view.getBottom(); if (bottom > listViewHeight) { int top = view.getTop(); if (top > 0) { listView.smoothScrollBy(Math.min(bottom - listViewHeight + listViewBottomPadding, top), 300); } } } }, 400); } @Override public void onItemCollapsed(int i) { } }; }
apache-2.0
rfielding/iface
example.if.java
820
/* Typed send API*/ public interface ApiG extends Api { N doNotify(Z ZArg) throws PreconditionException; boolean Precondition_doNotify(Z ZArg); } /* Typed send API*/ public interface ApiA extends Api { void setZ(ApiB ApiBArg) throws PreconditionException; F doSomeF(X XArg) throws PreconditionException; G doSomeG(Y YArg) throws PreconditionException; void setB(ApiB ApiBArg) throws PreconditionException; boolean Precondition_setZ(ApiB ApiBArg); boolean Precondition_doSomeF(X XArg); boolean Precondition_doSomeG(Y YArg); boolean Precondition_setB(ApiB ApiBArg); } /* Typed send API*/ public interface ApiB extends Api { K doSomeK(X XArg) throws PreconditionException; boolean Precondition_doSomeK(X XArg); } /* Typed send API*/ public interface ApiC extends Api { }
apache-2.0