code
stringlengths 5
1.04M
| repo_name
stringlengths 7
108
| path
stringlengths 6
299
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 5
1.04M
|
---|---|---|---|---|---|
package com.identityforge.aad.adcl4j;
import com.identityforge.aad.adcl4j.io.ExcludeTransformer;
import flexjson.JSONDeserializer;
import flexjson.JSONSerializer;
import flexjson.transformer.DateTransformer;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.AbstractHttpMessage;
import javax.xml.ws.http.HTTPException;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
/**
* Created by nwoolls on 5/4/15.
*/
public class RestClientImpl implements RestClient {
private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";
private static final DateTransformer DATE_TRANSFORMER = new DateTransformer(DATE_FORMAT);
private static final String GRAPH_API_URI = "https://graph.windows.net";
private static final String APPLICATION_JSON = "application/json";
private static final String JS_CLASS_MASK = "*.class";
private static final String JS_VALUE_PATH = "value";
private static final String JS_VALUES_PATH = "values.values";
private final AuthClient authClient;
private final String tenantDomain;
public RestClientImpl(AuthClient authClient, String tenantDomain) {
this.authClient = authClient;
this.tenantDomain = tenantDomain;
}
@Override
public <T> T createEntry(Class<T> clazz, String path, Object entry)
throws IOException, URISyntaxException, AuthenticationException {
T result = null;
String payload = new JSONSerializer()
// exclude class info
.exclude(JS_CLASS_MASK)
// exclude properties with NULL values
.transform(new ExcludeTransformer(), void.class)
// set date format
.transform(DATE_TRANSFORMER, Date.class)
.deepSerialize(entry);
String response = postRestEntity(path, payload);
if (response != null) {
result = new JSONDeserializer<T>()
.use(null, clazz)
// set date format
.use(Date.class, DATE_TRANSFORMER)
.deserialize(response);
}
return result;
}
@Override
public void deleteEntry(String path, String oid)
throws IOException, URISyntaxException, AuthenticationException {
deleteRestEntity(path, oid);
}
@Override
public void updateEntry(String path, String oid, Object entry)
throws IOException, URISyntaxException, AuthenticationException {
String payload = new JSONSerializer()
// exclude class info
.exclude(JS_CLASS_MASK)
// exclude properties with NULL values
.transform(new ExcludeTransformer(), void.class)
// set date format
.transform(DATE_TRANSFORMER, Date.class)
.deepSerialize(entry);
patchRestEntity(path, oid, payload);
}
@Override
public <T> T getEntry(Class<T> clazz, String path, String oid)
throws IOException, URISyntaxException, AuthenticationException {
String response = getRestEntity(path, oid);
T result = new JSONDeserializer<T>()
.use(null, clazz)
// set date format
.use(Date.class, DATE_TRANSFORMER)
.deserialize(response);
return result;
}
@Override
public <T> Collection<T> getAllEntries(Class<T> clazz, String path)
throws IOException, URISyntaxException, AuthenticationException {
String response = getRestEntity(path, null);
Collection<T> results = new JSONDeserializer<Map<String, Collection<T>>>()
.use(JS_VALUES_PATH, clazz)
// set date format
.use(Date.class, DATE_TRANSFORMER)
.deserialize(response)
.get(JS_VALUE_PATH);
return results;
}
private String getRestEntity(String path, String oid)
throws IOException, URISyntaxException, AuthenticationException {
authClient.ensureAuthenticated();
String result;
try(CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpGet = new HttpGet(buildRestUri(path, oid));
setHeaders(httpGet);
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = new BasicResponseHandler().handleResponse(response);
} else {
throw new HTTPException(response.getStatusLine().getStatusCode());
}
}
}
return result;
}
private String deleteRestEntity(String path, String oid)
throws IOException, URISyntaxException, AuthenticationException {
authClient.ensureAuthenticated();
String result;
try(CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpDelete httpDelete = new HttpDelete(buildRestUri(path, oid));
setHeaders(httpDelete);
try (CloseableHttpResponse response = httpClient.execute(httpDelete)) {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NO_CONTENT) {
result = new BasicResponseHandler().handleResponse(response);
} else {
throw new HTTPException(response.getStatusLine().getStatusCode());
}
}
}
return result;
}
private String postRestEntity(String path, String payload)
throws IOException, URISyntaxException, AuthenticationException{
authClient.ensureAuthenticated();
String result;
try(CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(buildRestUri(path, null));
setHeaders(httpPost);
httpPost.setEntity(new StringEntity(payload));
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
if ((response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) ||
// using POST to add a member to a group returns 204
(response.getStatusLine().getStatusCode() == HttpStatus.SC_NO_CONTENT)) {
result = new BasicResponseHandler().handleResponse(response);
} else {
throw new HTTPException(response.getStatusLine().getStatusCode());
}
}
}
return result;
}
// TODO - trying to clear a value (e.g. specify "" for country) returns HTTP 400
// The JSON seems fine - {"country":""}
private void patchRestEntity(String path, String oid, String payload)
throws IOException, URISyntaxException, AuthenticationException {
authClient.ensureAuthenticated();
try(CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPatch httpPatch = new HttpPatch(buildRestUri(path, oid));
setHeaders(httpPatch);
httpPatch.setEntity(new StringEntity(payload));
try (CloseableHttpResponse response = httpClient.execute(httpPatch)) {
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) {
throw new HTTPException(response.getStatusLine().getStatusCode());
}
}
}
}
private URI buildRestUri(String path, String oid) throws URISyntaxException {
URIBuilder uriBuilder = new URIBuilder(GRAPH_API_URI);
uriBuilder.setPath(String.format("/%s/%s/%s",
this.tenantDomain,
// not lower-case, e.g. DirectoryRoles => directoryRoles
StringUtils.uncapitalize(path),
oid == null ? "" : oid));
// oldest API version that returns immutableId
uriBuilder.setParameter("api-version", "1.5");
return uriBuilder.build();
}
private void setHeaders(AbstractHttpMessage httpMessage) {
String bearerToken = authClient.getAuthenticationResult().getAccessToken();
httpMessage.setHeader("Authorization", String.format("Bearer %s", bearerToken));
httpMessage.setHeader("Content-type", APPLICATION_JSON);
}
}
| IDMWORKS/azure-activedirectory-client-for-java | src/main/java/com/identityforge/aad/adcl4j/RestClientImpl.java | Java | apache-2.0 | 8,821 |
/*******************************************************************************
* (c) Copyright 2014 Hewlett-Packard Development Company, L.P.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License v2.0 which accompany this distribution.
*
* The Apache License is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
*******************************************************************************/
package io.cloudslang.content.httpclient.build;
import io.cloudslang.content.httpclient.build.auth.AuthTypes;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthSchemeProvider;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Lookup;
import org.apache.http.impl.client.BasicAuthCache;
import java.net.URI;
/**
* Created with IntelliJ IDEA.
* User: davidmih
* Date: 10/7/14
*/
public class ContextBuilder {
private Lookup<AuthSchemeProvider> authSchemeLookup;
private URI uri;
private AuthTypes authTypes;
private CredentialsProvider credentialsProvider;
private String preemptiveAuth;
public ContextBuilder setAuthSchemeLookup(Lookup<AuthSchemeProvider> authSchemeLookup) {
this.authSchemeLookup = authSchemeLookup;
return this;
}
public ContextBuilder setUri(URI uri) {
this.uri = uri;
return this;
}
public ContextBuilder setAuthTypes(AuthTypes authTypes) {
this.authTypes = authTypes;
return this;
}
public ContextBuilder setCredentialsProvider(CredentialsProvider credentialsProvider) {
this.credentialsProvider = credentialsProvider;
return this;
}
public ContextBuilder setPreemptiveAuth(String preemptiveAuth) {
this.preemptiveAuth = preemptiveAuth;
return this;
}
public HttpClientContext build() {
if (StringUtils.isEmpty(preemptiveAuth)) {
preemptiveAuth = "true";
}
HttpClientContext context = HttpClientContext.create();
if (authTypes.size() == 1 && Boolean.parseBoolean(preemptiveAuth) && !authTypes.contains(AuthTypes.ANONYMOUS)) {
AuthCache authCache = new BasicAuthCache();
authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()),
authSchemeLookup.lookup(authTypes.iterator().next()).create(context));
context.setCredentialsProvider(credentialsProvider);
context.setAuthCache(authCache);
}
return context;
}
}
| gituser173/score-actions | score-http-client/src/main/java/io/cloudslang/content/httpclient/build/ContextBuilder.java | Java | apache-2.0 | 2,709 |
/*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH 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.graphhopper.routing;
import com.graphhopper.routing.util.*;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.hash.TIntObjectHashMap;
import java.util.PriorityQueue;
import com.graphhopper.routing.AStar.AStarEntry;
import com.graphhopper.storage.SPTEntry;
import com.graphhopper.storage.Graph;
import com.graphhopper.util.*;
/**
* This class implements a bidirectional A* algorithm. It is interesting to note that a
* bidirectional dijkstra is far more efficient than a single direction one. The same does not hold
* for a bidirectional A* as the heuristic can not be as tight.
* <p>
* See http://research.microsoft.com/apps/pubs/default.aspx?id=64511
* http://i11www.iti.uni-karlsruhe.de/_media/teaching/sommer2012/routenplanung/vorlesung4.pdf
* http://research.microsoft.com/pubs/64504/goldberg-sofsem07.pdf
* http://www.cs.princeton.edu/courses/archive/spr06/cos423/Handouts/EPP%20shortest%20path%20algorithms.pdf
* <p>
* and
* <p>
* 1. Ikeda, T., Hsu, M.-Y., Imai, H., Nishimura, S., Shimoura, H., Hashimoto, T., Tenmoku, K., and
* Mitoh, K. (1994). A fast algorithm for finding better routes by ai search techniques. In VNIS,
* pages 291–296.
* <p>
* 2. Whangbo, T. K. (2007). Efficient modified bidirectional a* algorithm for optimal route-
* finding. In IEA/AIE, volume 4570, pages 344–353. Springer.
* <p>
* or could we even use this three phase approach?
* www.lix.polytechnique.fr/~giacomon/papers/bidirtimedep.pdf
* <p>
* @author Peter Karich
* @author jansoe
*/
public class AStarBidirection extends AbstractBidirAlgo
{
private ConsistentWeightApproximator weightApprox;
private PriorityQueue<AStarEntry> prioQueueOpenSetFrom;
protected TIntObjectMap<AStarEntry> bestWeightMapFrom;
private PriorityQueue<AStarEntry> prioQueueOpenSetTo;
protected TIntObjectMap<AStarEntry> bestWeightMapTo;
private TIntObjectMap<AStarEntry> bestWeightMapOther;
protected AStarEntry currFrom;
protected AStarEntry currTo;
protected PathBidirRef bestPath;
public AStarBidirection( Graph graph, FlagEncoder encoder, Weighting weighting, TraversalMode tMode )
{
super(graph, encoder, weighting, tMode);
int size = Math.min(Math.max(200, graph.getNodes() / 10), 2000);
initCollections(size);
BeelineWeightApproximator defaultApprox = new BeelineWeightApproximator(nodeAccess, weighting);
defaultApprox.setDistanceCalc(new DistancePlaneProjection());
setApproximation(defaultApprox);
}
protected void initCollections( int size )
{
prioQueueOpenSetFrom = new PriorityQueue<AStarEntry>(size);
bestWeightMapFrom = new TIntObjectHashMap<AStarEntry>(size);
prioQueueOpenSetTo = new PriorityQueue<AStarEntry>(size);
bestWeightMapTo = new TIntObjectHashMap<AStarEntry>(size);
}
/**
* @param approx if true it enables approximative distance calculation from lat,lon values
*/
public AStarBidirection setApproximation( WeightApproximator approx )
{
weightApprox = new ConsistentWeightApproximator(approx);
return this;
}
@Override
protected SPTEntry createSPTEntry( int node, double weight )
{
throw new IllegalStateException("use AStarEdge constructor directly");
}
@Override
public void initFrom( int from, double weight )
{
currFrom = new AStarEntry(EdgeIterator.NO_EDGE, from, weight, weight);
weightApprox.setSourceNode(from);
prioQueueOpenSetFrom.add(currFrom);
if (currTo != null)
{
currFrom.weight += weightApprox.approximate(currFrom.adjNode, false);
currTo.weight += weightApprox.approximate(currTo.adjNode, true);
}
if (!traversalMode.isEdgeBased())
{
bestWeightMapFrom.put(from, currFrom);
if (currTo != null)
{
bestWeightMapOther = bestWeightMapTo;
updateBestPath(GHUtility.getEdge(graph, from, currTo.adjNode), currTo, from);
}
} else
{
if (currTo != null && currTo.adjNode == from)
{
// special case of identical start and end
bestPath.sptEntry = currFrom;
bestPath.edgeTo = currTo;
finishedFrom = true;
finishedTo = true;
}
}
}
@Override
public void initTo( int to, double weight )
{
currTo = new AStarEntry(EdgeIterator.NO_EDGE, to, weight, weight);
weightApprox.setGoalNode(to);
prioQueueOpenSetTo.add(currTo);
if (currFrom != null)
{
currFrom.weight += weightApprox.approximate(currFrom.adjNode, false);
currTo.weight += weightApprox.approximate(currTo.adjNode, true);
}
if (!traversalMode.isEdgeBased())
{
bestWeightMapTo.put(to, currTo);
if (currFrom != null)
{
bestWeightMapOther = bestWeightMapFrom;
updateBestPath(GHUtility.getEdge(graph, currFrom.adjNode, to), currFrom, to);
}
} else
{
if (currFrom != null && currFrom.adjNode == to)
{
// special case of identical start and end
bestPath.sptEntry = currFrom;
bestPath.edgeTo = currTo;
finishedFrom = true;
finishedTo = true;
}
}
}
@Override
protected Path createAndInitPath()
{
bestPath = new PathBidirRef(graph, flagEncoder);
return bestPath;
}
@Override
protected Path extractPath()
{
if (finished())
return bestPath.extract();
return bestPath;
}
@Override
protected double getCurrentFromWeight()
{
return currFrom.weight;
}
@Override
protected double getCurrentToWeight()
{
return currTo.weight;
}
@Override
protected boolean finished()
{
if (finishedFrom || finishedTo)
return true;
// using 'weight' is important and correct here e.g. approximation can get negative and smaller than 'weightOfVisitedPath'
return currFrom.weight + currTo.weight >= bestPath.getWeight();
}
@Override
boolean fillEdgesFrom()
{
if (prioQueueOpenSetFrom.isEmpty())
return false;
currFrom = prioQueueOpenSetFrom.poll();
bestWeightMapOther = bestWeightMapTo;
fillEdges(currFrom, prioQueueOpenSetFrom, bestWeightMapFrom, outEdgeExplorer, false);
visitedCountFrom++;
return true;
}
@Override
boolean fillEdgesTo()
{
if (prioQueueOpenSetTo.isEmpty())
return false;
currTo = prioQueueOpenSetTo.poll();
bestWeightMapOther = bestWeightMapFrom;
fillEdges(currTo, prioQueueOpenSetTo, bestWeightMapTo, inEdgeExplorer, true);
visitedCountTo++;
return true;
}
private void fillEdges( AStarEntry currEdge, PriorityQueue<AStarEntry> prioQueueOpenSet,
TIntObjectMap<AStarEntry> bestWeightMap, EdgeExplorer explorer, boolean reverse )
{
int currNode = currEdge.adjNode;
EdgeIterator iter = explorer.setBaseNode(currNode);
while (iter.next())
{
if (!accept(iter, currEdge.edge))
continue;
int neighborNode = iter.getAdjNode();
int traversalId = traversalMode.createTraversalId(iter, reverse);
// TODO performance: check if the node is already existent in the opposite direction
// then we could avoid the approximation as we already know the exact complete path!
double alreadyVisitedWeight = weighting.calcWeight(iter, reverse, currEdge.edge)
+ currEdge.getWeightOfVisitedPath();
if (Double.isInfinite(alreadyVisitedWeight))
continue;
AStarEntry ase = bestWeightMap.get(traversalId);
if (ase == null || ase.getWeightOfVisitedPath() > alreadyVisitedWeight)
{
double currWeightToGoal = weightApprox.approximate(neighborNode, reverse);
double estimationFullWeight = alreadyVisitedWeight + currWeightToGoal;
if (ase == null)
{
ase = new AStarEntry(iter.getEdge(), neighborNode, estimationFullWeight, alreadyVisitedWeight);
bestWeightMap.put(traversalId, ase);
} else
{
assert (ase.weight > 0.999999 * estimationFullWeight) : "Inconsistent distance estimate "
+ ase.weight + " vs " + estimationFullWeight + " (" + ase.weight / estimationFullWeight + "), and:"
+ ase.getWeightOfVisitedPath() + " vs " + alreadyVisitedWeight + " (" + ase.getWeightOfVisitedPath() / alreadyVisitedWeight + ")";
prioQueueOpenSet.remove(ase);
ase.edge = iter.getEdge();
ase.weight = estimationFullWeight;
ase.weightOfVisitedPath = alreadyVisitedWeight;
}
ase.parent = currEdge;
prioQueueOpenSet.add(ase);
updateBestPath(iter, ase, traversalId);
}
}
}
public void updateBestPath( EdgeIteratorState edgeState, AStarEntry entryCurrent, int currLoc )
{
AStarEntry entryOther = bestWeightMapOther.get(currLoc);
if (entryOther == null)
return;
boolean reverse = bestWeightMapFrom == bestWeightMapOther;
// update μ
double newWeight = entryCurrent.weightOfVisitedPath + entryOther.weightOfVisitedPath;
if (traversalMode.isEdgeBased())
{
if (entryOther.edge != entryCurrent.edge)
throw new IllegalStateException("cannot happen for edge based execution of " + getName());
// see DijkstraBidirectionRef
if (entryOther.adjNode != entryCurrent.adjNode)
{
entryCurrent = (AStar.AStarEntry) entryCurrent.parent;
newWeight -= weighting.calcWeight(edgeState, reverse, EdgeIterator.NO_EDGE);
} else
{
// we detected a u-turn at meeting point, skip if not supported
if (!traversalMode.hasUTurnSupport())
return;
}
}
if (newWeight < bestPath.getWeight())
{
bestPath.setSwitchToFrom(reverse);
bestPath.sptEntry = entryCurrent;
bestPath.edgeTo = entryOther;
bestPath.setWeight(newWeight);
}
}
@Override
public String getName()
{
return Parameters.Algorithms.ASTAR_BI;
}
}
| CEPFU/graphhopper | core/src/main/java/com/graphhopper/routing/AStarBidirection.java | Java | apache-2.0 | 11,710 |
package org.roaringbitmap;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
public class TestFastAggregation {
@Test
public void horizontal_or() {
RoaringBitmap rb1 = RoaringBitmap.bitmapOf(0, 1, 2);
RoaringBitmap rb2 = RoaringBitmap.bitmapOf(0, 5, 6);
RoaringBitmap rb3 = RoaringBitmap.bitmapOf(1<<16, 2<<16);
RoaringBitmap result = FastAggregation.horizontal_or(Arrays.asList(rb1, rb2, rb3));
RoaringBitmap expected = RoaringBitmap.bitmapOf(0, 1, 2, 5, 6, 1<<16, 2<<16);
assertEquals(expected, result);
}
@Test
public void or() {
RoaringBitmap rb1 = RoaringBitmap.bitmapOf(0, 1, 2);
RoaringBitmap rb2 = RoaringBitmap.bitmapOf(0, 5, 6);
RoaringBitmap rb3 = RoaringBitmap.bitmapOf(1<<16, 2<<16);
RoaringBitmap result = FastAggregation.or(rb1, rb2, rb3);
RoaringBitmap expected = RoaringBitmap.bitmapOf(0, 1, 2, 5, 6, 1<<16, 2<<16);
assertEquals(expected, result);
}
@Test
public void horizontal_or2() {
RoaringBitmap rb1 = RoaringBitmap.bitmapOf(0, 1, 2);
RoaringBitmap rb2 = RoaringBitmap.bitmapOf(0, 5, 6);
RoaringBitmap rb3 = RoaringBitmap.bitmapOf(1<<16, 2<<16);
RoaringBitmap result = FastAggregation.horizontal_or(rb1, rb2, rb3);
RoaringBitmap expected = RoaringBitmap.bitmapOf(0, 1, 2, 5, 6, 1<<16, 2<<16);
assertEquals(expected, result);
}
@Test
public void priorityqueue_or() {
RoaringBitmap rb1 = RoaringBitmap.bitmapOf(0, 1, 2);
RoaringBitmap rb2 = RoaringBitmap.bitmapOf(0, 5, 6);
RoaringBitmap rb3 = RoaringBitmap.bitmapOf(1<<16, 2<<16);
RoaringBitmap result = FastAggregation.priorityqueue_or(Arrays.asList(rb1, rb2, rb3).iterator());
RoaringBitmap expected = RoaringBitmap.bitmapOf(0, 1, 2, 5, 6, 1<<16, 2<<16);
assertEquals(expected, result);
}
@Test
public void priorityqueue_or2() {
RoaringBitmap rb1 = RoaringBitmap.bitmapOf(0, 1, 2);
RoaringBitmap rb2 = RoaringBitmap.bitmapOf(0, 5, 6);
RoaringBitmap rb3 = RoaringBitmap.bitmapOf(1<<16, 2<<16);
RoaringBitmap result = FastAggregation.priorityqueue_or(rb1, rb2, rb3);
RoaringBitmap expected = RoaringBitmap.bitmapOf(0, 1, 2, 5, 6, 1<<16, 2<<16);
assertEquals(expected, result);
}
private static class ExtendedRoaringBitmap extends RoaringBitmap {}
@Test
public void testAndWithIterator() {
final RoaringBitmap b1 = RoaringBitmap.bitmapOf(1, 2);
final RoaringBitmap b2 = RoaringBitmap.bitmapOf(2, 3);
final RoaringBitmap bResult = FastAggregation.and(Arrays.asList(b1, b2).iterator());
assertFalse(bResult.contains(1));
assertTrue(bResult.contains(2));
assertFalse(bResult.contains(3));
final ExtendedRoaringBitmap eb1 = new ExtendedRoaringBitmap();
eb1.add(1);
eb1.add(2);
final ExtendedRoaringBitmap eb2 = new ExtendedRoaringBitmap();
eb2.add(2);
eb2.add(3);
final RoaringBitmap ebResult = FastAggregation.and(Arrays.asList(b1, b2).iterator());
assertFalse(ebResult.contains(1));
assertTrue(ebResult.contains(2));
assertFalse(ebResult.contains(3));
}
@Test
public void testNaiveAndWithIterator() {
final RoaringBitmap b1 = RoaringBitmap.bitmapOf(1, 2);
final RoaringBitmap b2 = RoaringBitmap.bitmapOf(2, 3);
final RoaringBitmap bResult = FastAggregation.naive_and(Arrays.asList(b1, b2).iterator());
assertFalse(bResult.contains(1));
assertTrue(bResult.contains(2));
assertFalse(bResult.contains(3));
final ExtendedRoaringBitmap eb1 = new ExtendedRoaringBitmap();
eb1.add(1);
eb1.add(2);
final ExtendedRoaringBitmap eb2 = new ExtendedRoaringBitmap();
eb2.add(2);
eb2.add(3);
final RoaringBitmap ebResult = FastAggregation.naive_and(Arrays.asList(b1, b2).iterator());
assertFalse(ebResult.contains(1));
assertTrue(ebResult.contains(2));
assertFalse(ebResult.contains(3));
}
@Test
public void testOrWithIterator() {
final RoaringBitmap b1 = RoaringBitmap.bitmapOf(1, 2);
final RoaringBitmap b2 = RoaringBitmap.bitmapOf(2, 3);
final RoaringBitmap bItResult = FastAggregation.or(Arrays.asList(b1, b2).iterator());
assertTrue(bItResult.contains(1));
assertTrue(bItResult.contains(2));
assertTrue(bItResult.contains(3));
final ExtendedRoaringBitmap eb1 = new ExtendedRoaringBitmap();
eb1.add(1);
eb1.add(2);
final ExtendedRoaringBitmap eb2 = new ExtendedRoaringBitmap();
eb2.add(2);
eb2.add(3);
final RoaringBitmap ebItResult = FastAggregation.or(Arrays.asList(b1, b2).iterator());
assertTrue(ebItResult.contains(1));
assertTrue(ebItResult.contains(2));
assertTrue(ebItResult.contains(3));
}
@Test
public void testHorizontalOrWithIterator() {
final RoaringBitmap b1 = RoaringBitmap.bitmapOf(1, 2);
final RoaringBitmap b2 = RoaringBitmap.bitmapOf(2, 3);
final RoaringBitmap bItResult = FastAggregation.horizontal_or(Arrays.asList(b1, b2).iterator());
assertTrue(bItResult.contains(1));
assertTrue(bItResult.contains(2));
assertTrue(bItResult.contains(3));
final RoaringBitmap bListResult = FastAggregation.horizontal_or(Arrays.asList(b1, b2));
assertTrue(bListResult.contains(1));
assertTrue(bListResult.contains(2));
assertTrue(bListResult.contains(3));
final ExtendedRoaringBitmap eb1 = new ExtendedRoaringBitmap();
eb1.add(1);
eb1.add(2);
final ExtendedRoaringBitmap eb2 = new ExtendedRoaringBitmap();
eb2.add(2);
eb2.add(3);
final RoaringBitmap ebItResult = FastAggregation.horizontal_or(Arrays.asList(b1, b2).iterator());
assertTrue(ebItResult.contains(1));
assertTrue(ebItResult.contains(2));
assertTrue(ebItResult.contains(3));
final RoaringBitmap ebListResult = FastAggregation.horizontal_or(Arrays.asList(b1, b2));
assertTrue(ebListResult.contains(1));
assertTrue(ebListResult.contains(2));
assertTrue(ebListResult.contains(3));
}
@Test
public void testNaiveOrWithIterator() {
final RoaringBitmap b1 = RoaringBitmap.bitmapOf(1, 2);
final RoaringBitmap b2 = RoaringBitmap.bitmapOf(2, 3);
final RoaringBitmap bResult = FastAggregation.naive_or(Arrays.asList(b1, b2).iterator());
assertTrue(bResult.contains(1));
assertTrue(bResult.contains(2));
assertTrue(bResult.contains(3));
final ExtendedRoaringBitmap eb1 = new ExtendedRoaringBitmap();
eb1.add(1);
eb1.add(2);
final ExtendedRoaringBitmap eb2 = new ExtendedRoaringBitmap();
eb2.add(2);
eb2.add(3);
final RoaringBitmap ebResult = FastAggregation.naive_or(Arrays.asList(b1, b2).iterator());
assertTrue(ebResult.contains(1));
assertTrue(ebResult.contains(2));
assertTrue(ebResult.contains(3));
}
@Test
public void testNaiveXorWithIterator() {
final RoaringBitmap b1 = RoaringBitmap.bitmapOf(1, 2);
final RoaringBitmap b2 = RoaringBitmap.bitmapOf(2, 3);
final RoaringBitmap bResult = FastAggregation.naive_xor(Arrays.asList(b1, b2).iterator());
assertTrue(bResult.contains(1));
assertFalse(bResult.contains(2));
assertTrue(bResult.contains(3));
final ExtendedRoaringBitmap eb1 = new ExtendedRoaringBitmap();
eb1.add(1);
eb1.add(2);
final ExtendedRoaringBitmap eb2 = new ExtendedRoaringBitmap();
eb2.add(2);
eb2.add(3);
final RoaringBitmap ebResult = FastAggregation.naive_xor(Arrays.asList(b1, b2).iterator());
assertTrue(ebResult.contains(1));
assertFalse(ebResult.contains(2));
assertTrue(ebResult.contains(3));
}
}
| okrische/RoaringBitmap | src/test/java/org/roaringbitmap/TestFastAggregation.java | Java | apache-2.0 | 8,199 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.carbondata.scan.filter;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import org.apache.carbondata.common.logging.LogService;
import org.apache.carbondata.common.logging.LogServiceFactory;
import org.apache.carbondata.core.carbon.AbsoluteTableIdentifier;
import org.apache.carbondata.core.carbon.datastore.DataRefNode;
import org.apache.carbondata.core.carbon.datastore.DataRefNodeFinder;
import org.apache.carbondata.core.carbon.datastore.IndexKey;
import org.apache.carbondata.core.carbon.datastore.block.AbstractIndex;
import org.apache.carbondata.core.carbon.datastore.block.SegmentProperties;
import org.apache.carbondata.core.carbon.datastore.impl.btree.BTreeDataRefNodeFinder;
import org.apache.carbondata.core.carbon.metadata.datatype.DataType;
import org.apache.carbondata.core.carbon.metadata.encoder.Encoding;
import org.apache.carbondata.core.keygenerator.KeyGenException;
import org.apache.carbondata.scan.executor.exception.QueryExecutionException;
import org.apache.carbondata.scan.expression.BinaryExpression;
import org.apache.carbondata.scan.expression.Expression;
import org.apache.carbondata.scan.expression.conditional.BinaryConditionalExpression;
import org.apache.carbondata.scan.expression.conditional.ConditionalExpression;
import org.apache.carbondata.scan.expression.exception.FilterUnsupportedException;
import org.apache.carbondata.scan.filter.executer.FilterExecuter;
import org.apache.carbondata.scan.filter.intf.ExpressionType;
import org.apache.carbondata.scan.filter.resolver.ConditionalFilterResolverImpl;
import org.apache.carbondata.scan.filter.resolver.FilterResolverIntf;
import org.apache.carbondata.scan.filter.resolver.LogicalFilterResolverImpl;
import org.apache.carbondata.scan.filter.resolver.RowLevelFilterResolverImpl;
import org.apache.carbondata.scan.filter.resolver.RowLevelRangeFilterResolverImpl;
public class FilterExpressionProcessor implements FilterProcessor {
private static final LogService LOGGER =
LogServiceFactory.getLogService(FilterExpressionProcessor.class.getName());
/**
* Implementation will provide the resolved form of filters based on the
* filter expression tree which is been passed in Expression instance.
*
* @param expressionTree , filter expression tree
* @param tableIdentifier ,contains carbon store informations
* @return a filter resolver tree
* @throws QueryExecutionException
* @throws FilterUnsupportedException
*/
public FilterResolverIntf getFilterResolver(Expression expressionTree,
AbsoluteTableIdentifier tableIdentifier) throws FilterUnsupportedException {
if (null != expressionTree && null != tableIdentifier) {
return getFilterResolvertree(expressionTree, tableIdentifier);
}
return null;
}
/**
* This API will scan the Segment level all btrees and selects the required
* block reference nodes inorder to push the same to executer for applying filters
* on the respective data reference node.
* Following Algorithm is followed in below API
* Step:1 Get the start end key based on the filter tree resolver information
* Step:2 Prepare the IndexKeys inorder to scan the tree and get the start and end reference
* node(block)
* Step:3 Once data reference node ranges retrieved traverse the node within this range
* and select the node based on the block min and max value and the filter value.
* Step:4 The selected blocks will be send to executers for applying the filters with the help
* of Filter executers.
*
* @throws QueryExecutionException
*/
public List<DataRefNode> getFilterredBlocks(DataRefNode btreeNode,
FilterResolverIntf filterResolver, AbstractIndex tableSegment,
AbsoluteTableIdentifier tableIdentifier) throws QueryExecutionException {
// Need to get the current dimension tables
List<DataRefNode> listOfDataBlocksToScan = new ArrayList<DataRefNode>();
// getting the start and end index key based on filter for hitting the
// selected block reference nodes based on filter resolver tree.
LOGGER.debug("preparing the start and end key for finding"
+ "start and end block as per filter resolver");
List<IndexKey> listOfStartEndKeys = new ArrayList<IndexKey>(2);
FilterUtil.traverseResolverTreeAndGetStartAndEndKey(tableSegment.getSegmentProperties(),
tableIdentifier, filterResolver, listOfStartEndKeys);
// reading the first value from list which has start key
IndexKey searchStartKey = listOfStartEndKeys.get(0);
// reading the last value from list which has end key
IndexKey searchEndKey = listOfStartEndKeys.get(1);
if (null == searchStartKey && null == searchEndKey) {
try {
// TODO need to handle for no dictionary dimensions
searchStartKey =
FilterUtil.prepareDefaultStartIndexKey(tableSegment.getSegmentProperties());
// TODO need to handle for no dictionary dimensions
searchEndKey = FilterUtil.prepareDefaultEndIndexKey(tableSegment.getSegmentProperties());
} catch (KeyGenException e) {
return listOfDataBlocksToScan;
}
}
LOGGER.debug(
"Successfully retrieved the start and end key" + "Dictionary Start Key: " + searchStartKey
.getDictionaryKeys() + "No Dictionary Start Key " + searchStartKey.getNoDictionaryKeys()
+ "Dictionary End Key: " + searchEndKey.getDictionaryKeys() + "No Dictionary End Key "
+ searchEndKey.getNoDictionaryKeys());
long startTimeInMillis = System.currentTimeMillis();
DataRefNodeFinder blockFinder = new BTreeDataRefNodeFinder(
tableSegment.getSegmentProperties().getEachDimColumnValueSize());
DataRefNode startBlock = blockFinder.findFirstDataBlock(btreeNode, searchStartKey);
DataRefNode endBlock = blockFinder.findLastDataBlock(btreeNode, searchEndKey);
FilterExecuter filterExecuter =
FilterUtil.getFilterExecuterTree(filterResolver, tableSegment.getSegmentProperties(),null);
while (startBlock != endBlock) {
addBlockBasedOnMinMaxValue(filterExecuter, listOfDataBlocksToScan, startBlock,
tableSegment.getSegmentProperties());
startBlock = startBlock.getNextDataRefNode();
}
addBlockBasedOnMinMaxValue(filterExecuter, listOfDataBlocksToScan, endBlock,
tableSegment.getSegmentProperties());
LOGGER.info("Total Time in retrieving the data reference node" + "after scanning the btree " + (
System.currentTimeMillis() - startTimeInMillis)
+ " Total number of data reference node for executing filter(s) " + listOfDataBlocksToScan
.size());
return listOfDataBlocksToScan;
}
/**
* Selects the blocks based on col max and min value.
*
* @param filterResolver
* @param listOfDataBlocksToScan
* @param dataRefNode
* @param segmentProperties
*/
private void addBlockBasedOnMinMaxValue(FilterExecuter filterExecuter,
List<DataRefNode> listOfDataBlocksToScan, DataRefNode dataRefNode,
SegmentProperties segmentProperties) {
BitSet bitSet = filterExecuter
.isScanRequired(dataRefNode.getColumnsMaxValue(), dataRefNode.getColumnsMinValue());
if (!bitSet.isEmpty()) {
listOfDataBlocksToScan.add(dataRefNode);
}
}
/**
* API will return a filter resolver instance which will be used by
* executers to evaluate or execute the filters.
*
* @param expressionTree , resolver tree which will hold the resolver tree based on
* filter expression.
* @return FilterResolverIntf type.
* @throws QueryExecutionException
* @throws FilterUnsupportedException
*/
private FilterResolverIntf getFilterResolvertree(Expression expressionTree,
AbsoluteTableIdentifier tableIdentifier) throws FilterUnsupportedException {
FilterResolverIntf filterEvaluatorTree =
createFilterResolverTree(expressionTree, tableIdentifier, null);
traverseAndResolveTree(filterEvaluatorTree, tableIdentifier);
return filterEvaluatorTree;
}
/**
* constructing the filter resolver tree based on filter expression.
* this method will visit each node of the filter resolver and prepares
* the surrogates of the filter members which are involved filter
* expression.
*
* @param filterResolverTree
* @param tableIdentifier
* @throws FilterUnsupportedException
* @throws QueryExecutionException
*/
private void traverseAndResolveTree(FilterResolverIntf filterResolverTree,
AbsoluteTableIdentifier tableIdentifier) throws FilterUnsupportedException {
if (null == filterResolverTree) {
return;
}
traverseAndResolveTree(filterResolverTree.getLeft(), tableIdentifier);
filterResolverTree.resolve(tableIdentifier);
traverseAndResolveTree(filterResolverTree.getRight(), tableIdentifier);
}
/**
* Pattern used : Visitor Pattern
* Method will create filter resolver tree based on the filter expression tree,
* in this algorithm based on the expression instance the resolvers will created
*
* @param expressionTree
* @param tableIdentifier
* @return
*/
private FilterResolverIntf createFilterResolverTree(Expression expressionTree,
AbsoluteTableIdentifier tableIdentifier, Expression intermediateExpression) {
ExpressionType filterExpressionType = expressionTree.getFilterExpressionType();
BinaryExpression currentExpression = null;
switch (filterExpressionType) {
case OR:
currentExpression = (BinaryExpression) expressionTree;
return new LogicalFilterResolverImpl(
createFilterResolverTree(currentExpression.getLeft(), tableIdentifier,
currentExpression),
createFilterResolverTree(currentExpression.getRight(), tableIdentifier,
currentExpression),currentExpression);
case AND:
currentExpression = (BinaryExpression) expressionTree;
return new LogicalFilterResolverImpl(
createFilterResolverTree(currentExpression.getLeft(), tableIdentifier,
currentExpression),
createFilterResolverTree(currentExpression.getRight(), tableIdentifier,
currentExpression), currentExpression);
case EQUALS:
case IN:
return getFilterResolverBasedOnExpressionType(ExpressionType.EQUALS, false, expressionTree,
tableIdentifier, expressionTree);
case GREATERTHAN:
case GREATERTHAN_EQUALTO:
case LESSTHAN:
case LESSTHAN_EQUALTO:
return getFilterResolverBasedOnExpressionType(ExpressionType.EQUALS, true, expressionTree,
tableIdentifier, expressionTree);
case NOT_EQUALS:
case NOT_IN:
return getFilterResolverBasedOnExpressionType(ExpressionType.NOT_EQUALS, false,
expressionTree, tableIdentifier, expressionTree);
case FALSE:
return getFilterResolverBasedOnExpressionType(ExpressionType.FALSE, false,
expressionTree, tableIdentifier, expressionTree);
default:
return getFilterResolverBasedOnExpressionType(ExpressionType.UNKNOWN, false, expressionTree,
tableIdentifier, expressionTree);
}
}
/**
* Factory method which will return the resolver instance based on filter expression
* expressions.
*/
private FilterResolverIntf getFilterResolverBasedOnExpressionType(
ExpressionType filterExpressionType, boolean isExpressionResolve, Expression expression,
AbsoluteTableIdentifier tableIdentifier, Expression expressionTree) {
BinaryConditionalExpression currentCondExpression = null;
ConditionalExpression condExpression = null;
switch (filterExpressionType) {
case FALSE:
return new RowLevelFilterResolverImpl(expression, false, false, tableIdentifier);
case EQUALS:
currentCondExpression = (BinaryConditionalExpression) expression;
if (currentCondExpression.isSingleDimension()
&& currentCondExpression.getColumnList().get(0).getCarbonColumn().getDataType()
!= DataType.ARRAY
&& currentCondExpression.getColumnList().get(0).getCarbonColumn().getDataType()
!= DataType.STRUCT) {
// getting new dim index.
if (!currentCondExpression.getColumnList().get(0).getCarbonColumn()
.hasEncoding(Encoding.DICTIONARY) || currentCondExpression.getColumnList().get(0)
.getCarbonColumn().hasEncoding(Encoding.DIRECT_DICTIONARY)) {
if (FilterUtil.checkIfExpressionContainsColumn(currentCondExpression.getLeft())
&& FilterUtil.checkIfExpressionContainsColumn(currentCondExpression.getRight()) || (
FilterUtil.checkIfRightExpressionRequireEvaluation(currentCondExpression.getRight())
|| FilterUtil
.checkIfLeftExpressionRequireEvaluation(currentCondExpression.getLeft()))) {
return new RowLevelFilterResolverImpl(expression, isExpressionResolve, true,
tableIdentifier);
}
if (currentCondExpression.getFilterExpressionType() == ExpressionType.GREATERTHAN
|| currentCondExpression.getFilterExpressionType() == ExpressionType.LESSTHAN
|| currentCondExpression.getFilterExpressionType()
== ExpressionType.GREATERTHAN_EQUALTO
|| currentCondExpression.getFilterExpressionType()
== ExpressionType.LESSTHAN_EQUALTO) {
return new RowLevelRangeFilterResolverImpl(expression, isExpressionResolve, true,
tableIdentifier);
}
}
return new ConditionalFilterResolverImpl(expression, isExpressionResolve, true);
}
break;
case NOT_EQUALS:
currentCondExpression = (BinaryConditionalExpression) expression;
if (currentCondExpression.isSingleDimension()
&& currentCondExpression.getColumnList().get(0).getCarbonColumn().getDataType()
!= DataType.ARRAY
&& currentCondExpression.getColumnList().get(0).getCarbonColumn().getDataType()
!= DataType.STRUCT) {
if (!currentCondExpression.getColumnList().get(0).getCarbonColumn()
.hasEncoding(Encoding.DICTIONARY) || currentCondExpression.getColumnList().get(0)
.getCarbonColumn().hasEncoding(Encoding.DIRECT_DICTIONARY)) {
if (FilterUtil.checkIfExpressionContainsColumn(currentCondExpression.getLeft())
&& FilterUtil.checkIfExpressionContainsColumn(currentCondExpression.getRight()) || (
FilterUtil.checkIfRightExpressionRequireEvaluation(currentCondExpression.getRight())
|| FilterUtil
.checkIfLeftExpressionRequireEvaluation(currentCondExpression.getLeft()))) {
return new RowLevelFilterResolverImpl(expression, isExpressionResolve, false,
tableIdentifier);
}
if (expressionTree.getFilterExpressionType() == ExpressionType.GREATERTHAN
|| expressionTree.getFilterExpressionType() == ExpressionType.LESSTHAN
|| expressionTree.getFilterExpressionType() == ExpressionType.GREATERTHAN_EQUALTO
|| expressionTree.getFilterExpressionType() == ExpressionType.LESSTHAN_EQUALTO) {
return new RowLevelRangeFilterResolverImpl(expression, isExpressionResolve, false,
tableIdentifier);
}
return new ConditionalFilterResolverImpl(expression, isExpressionResolve, false);
}
return new ConditionalFilterResolverImpl(expression, isExpressionResolve, false);
}
break;
default:
if(expression instanceof ConditionalExpression) {
condExpression = (ConditionalExpression) expression;
if (condExpression.isSingleDimension()
&& condExpression.getColumnList().get(0).getCarbonColumn().getDataType()
!= DataType.ARRAY
&& condExpression.getColumnList().get(0).getCarbonColumn().getDataType()
!= DataType.STRUCT) {
condExpression = (ConditionalExpression) expression;
if (condExpression.getColumnList().get(0).getCarbonColumn()
.hasEncoding(Encoding.DICTIONARY) && !condExpression.getColumnList().get(0)
.getCarbonColumn().hasEncoding(Encoding.DIRECT_DICTIONARY)) {
return new ConditionalFilterResolverImpl(expression, true, true);
}
}
}
}
return new RowLevelFilterResolverImpl(expression, false, false, tableIdentifier);
}
}
| Zhangshunyu/incubator-carbondata | core/src/main/java/org/apache/carbondata/scan/filter/FilterExpressionProcessor.java | Java | apache-2.0 | 17,519 |
/*
* Copyright 2016 Lutz Fischer <[email protected]>.
*
* 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 rappsilber.ms.score;
import java.util.ArrayList;
import rappsilber.ms.spectra.match.MatchedXlinkedPeptide;
/**
*
* @author Lutz Fischer <[email protected]>
*/
public interface ScoreSpectraMatch extends Comparable<ScoreSpectraMatch> {
/**
* calculates a number of scores and returns one (hopefully most meaning full)
* score.
* The scores are saved under the list of names with in the match
* @param match
* @return one of the scores
*/
double score(MatchedXlinkedPeptide match);
/**
* returns a name for the score collection
* @return name for the score-group
*/
String name();
/**
* returns a list of names for all scores that are provided by this instance
* @return Array of Strings under which
*/
String[] scoreNames();
/**
* should provide the average of all scored scans for the given score
* @param name name of the score
* @return average of all up to now seen scores
*/
double getAverage(String name);
/**
* should provide the median (or as of now an estimate) of all scored scans for the given score
* @param name name of the score
* @return median of all up to now seen scores
*/
double getMedian(String name);
/**
* should provide the median absolute deviation (or as of now an estimate) of all scored scans for the given score
* @param name name of the score
* @return median absolute deviation
*/
double getMAD(String name);
/**
* should provide the standard deviation of all scored scans for the given score
* @param name name of the score
* @return average of all up to now seen scores
*/
double getStdDev(String name);
/**
* the smallest observed value for a given score
* @param name name of the score
* @return smallest score value
*/
double getMin(String name);
/**
* the largest observed value for a given score
* @param name name of the score
* @return largest score value
*/
double getMax(String name);
double getOrder();
}
| lutzfischer/XiSearch | src/main/java/rappsilber/ms/score/ScoreSpectraMatch.java | Java | apache-2.0 | 2,773 |
package org.hcjf.io.net.http;
import org.hcjf.encoding.MimeType;
import org.hcjf.errors.Errors;
import org.hcjf.log.Log;
import org.hcjf.properties.SystemProperties;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.util.*;
import java.util.jar.JarFile;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* This class publish some local folder in the web environment.
* @author javaito
*/
public class FolderContext extends Context {
private final Path baseFolder;
private final String name;
private String defaultFile;
private final String[] names;
private final MessageDigest messageDigest;
public FolderContext(String name, Path baseFolder, String defaultFile) {
super(START_CONTEXT + URI_FOLDER_SEPARATOR + name + END_CONTEXT);
if(baseFolder == null) {
throw new NullPointerException(Errors.getMessage(Errors.ORG_HCJF_IO_NET_HTTP_1));
}
if(!baseFolder.toFile().exists()) {
throw new IllegalArgumentException(Errors.getMessage(Errors.ORG_HCJF_IO_NET_HTTP_2));
}
if(verifyJatFormat(baseFolder)) {
try {
baseFolder = unzipJar(baseFolder);
} catch (IOException e) {
throw new IllegalArgumentException("Unable to unzip jar file", e);
}
} else if(verifyZipFormat(baseFolder)) {
try {
baseFolder = unzip(baseFolder);
} catch (IOException e) {
throw new IllegalArgumentException("Unable to unzip file", e);
}
}
if(defaultFile != null) {
File file = baseFolder.resolve(defaultFile).toFile();
if (file.exists()) {
if (file.isDirectory()) {
baseFolder = baseFolder.resolve(defaultFile);
} else {
this.defaultFile = defaultFile;
}
} else {
Log.w(SystemProperties.get(SystemProperties.Net.Http.Folder.LOG_TAG), "Default file doesn't exist %s", defaultFile);
}
}
this.name = name;
this.baseFolder = baseFolder;
this.names = name.split(URI_FOLDER_SEPARATOR);
try {
this.messageDigest = MessageDigest.getInstance(
SystemProperties.get(SystemProperties.Net.Http.DEFAULT_FILE_CHECKSUM_ALGORITHM));
} catch (Exception ex) {
throw new IllegalArgumentException(Errors.getMessage(Errors.ORG_HCJF_IO_NET_HTTP_9), ex);
}
}
public FolderContext(String name, Path baseFolder) {
this(name, baseFolder, null);
}
/**
* Verify if the specific path is a zip file or not.
* @param path Specific path.
* @return True if the path point to the zip file.
*/
private boolean verifyZipFormat(Path path) {
boolean result = false;
try {
new ZipFile(path.toFile()).getName();
result = true;
} catch (Exception ex){}
return result;
}
/**
* Verify if the specific path is a jar file or not.
* @param path Specific path.
* @return True if the path point to the jar file.
*/
private boolean verifyJatFormat(Path path) {
boolean result = false;
try {
new JarFile(path.toFile()).getName();
result = true;
} catch (Exception ex) {}
return result;
}
/**
* Unzip the specific file and create a temporal folder with all the content and returns
* the new base folder for the context.
* @param zipFilePath Specific file.
* @return New base folder.
*/
private Path unzip(Path zipFilePath) throws IOException {
ZipFile zipFile = new ZipFile(zipFilePath.toFile());
Path tempFolder = Files.createTempDirectory(
SystemProperties.getPath(SystemProperties.Net.Http.Folder.ZIP_CONTAINER),
SystemProperties.get(SystemProperties.Net.Http.Folder.ZIP_TEMP_PREFIX));
tempFolder.toFile().deleteOnExit();
int errors;
Set<String> processedNames = new TreeSet<>();
do {
errors = 0;
Enumeration<? extends ZipEntry> entryEnumeration = zipFile.entries();
while (entryEnumeration.hasMoreElements()) {
ZipEntry zipEntry = entryEnumeration.nextElement();
if(!processedNames.contains(zipEntry.getName())) {
try {
if (zipEntry.isDirectory()) {
Files.createDirectory(tempFolder.resolve(zipEntry.getName()));
} else {
Path file = Files.createFile(tempFolder.resolve(zipEntry.getName()));
try (InputStream inputStream = zipFile.getInputStream(zipEntry);
FileOutputStream fileOutputStream = new FileOutputStream(file.toFile())) {
byte[] buffer = new byte[2048];
int readSize = inputStream.read(buffer);
while (readSize >= 0) {
fileOutputStream.write(buffer, 0, readSize);
fileOutputStream.flush();
readSize = inputStream.read(buffer);
}
}
}
} catch (IOException ex) {
errors++;
}
processedNames.add(zipEntry.getName());
}
}
} while(errors > 0);
return tempFolder;
}
/**
* Unzip the specific file and create a temporal folder with all the content and returns
* the new base folder for the context.
* @param jarFilePath Specific file.
* @return New base folder.
*/
private Path unzipJar(Path jarFilePath) throws IOException {
JarFile jarFile = new JarFile(jarFilePath.toFile());
Path tempFolder = Files.createTempDirectory(
SystemProperties.getPath(SystemProperties.Net.Http.Folder.JAR_CONTAINER),
SystemProperties.get(SystemProperties.Net.Http.Folder.JAR_TEMP_PREFIX));
tempFolder.toFile().deleteOnExit();
int errors;
Set<String> processedNames = new TreeSet<>();
do {
errors = 0;
Enumeration<? extends ZipEntry> entryEnumeration = jarFile.entries();
while (entryEnumeration.hasMoreElements()) {
ZipEntry zipEntry = entryEnumeration.nextElement();
if(!processedNames.contains(zipEntry.getName())) {
try {
if (zipEntry.isDirectory()) {
Files.createDirectory(tempFolder.resolve(zipEntry.getName()));
} else {
Path file = Files.createFile(tempFolder.resolve(zipEntry.getName()));
try (InputStream inputStream = jarFile.getInputStream(zipEntry);
FileOutputStream fileOutputStream = new FileOutputStream(file.toFile())) {
byte[] buffer = new byte[2048];
int readSize = inputStream.read(buffer);
while (readSize >= 0) {
fileOutputStream.write(buffer, 0, readSize);
fileOutputStream.flush();
readSize = inputStream.read(buffer);
}
}
}
} catch (IOException ex) {
errors++;
}
processedNames.add(zipEntry.getName());
}
}
} while(errors > 0);
return tempFolder;
}
/**
* This method is called when there comes a http package addressed to this
* context.
*
* @param request All the request information.
* @return Return an object with all the response information.
*/
@Override
public final HttpResponse onContext(HttpRequest request) {
List<String> elements = request.getPathParts();
for(String forbidden : SystemProperties.getList(SystemProperties.Net.Http.Folder.FORBIDDEN_CHARACTERS)) {
for(String element : elements) {
if (element.contains(forbidden)) {
throw new IllegalArgumentException(Errors.getMessage(Errors.ORG_HCJF_IO_NET_HTTP_3, forbidden, request.getContext()));
}
}
}
//The first value is a empty value, and the second value is the base public context.
Path path = baseFolder.toAbsolutePath();
boolean emptyElement = true;
for(String element : elements) {
if(!element.isEmpty() && Arrays.binarySearch(names, element) < 0) {
path = path.resolve(element);
emptyElement = false;
}
}
if(emptyElement && defaultFile != null) {
path = path.resolve(defaultFile);
}
HttpResponse response = new HttpResponse();
File file = path.toFile();
//If the path that is finding doesn't exists then some particular
//implementation could implements onNonexistentFile method to decide
//retry the operation after take come action.
boolean retry = true;
while(retry) {
//By default never retry.
retry = false;
if (file.exists()) {
if (file.isDirectory()) {
StringBuilder list = new StringBuilder();
for (File subFile : file.listFiles()) {
list.append(String.format(SystemProperties.get(SystemProperties.Net.Http.Folder.DEFAULT_HTML_ROW),
path.relativize(baseFolder).resolve(request.getContext()).resolve(subFile.getName()).toString(),
subFile.getName()));
}
String htmlBody = String.format(SystemProperties.get(SystemProperties.Net.Http.Folder.DEFAULT_HTML_BODY), list.toString());
String document = String.format(SystemProperties.get(SystemProperties.Net.Http.Folder.DEFAULT_HTML_DOCUMENT), file.getName(), htmlBody);
byte[] body = document.getBytes();
response.addHeader(new HttpHeader(HttpHeader.CONTENT_LENGTH, Integer.toString(body.length)));
response.addHeader(new HttpHeader(HttpHeader.CONTENT_TYPE, MimeType.HTML));
response.setResponseCode(HttpResponseCode.OK);
response.setBody(body);
} else {
byte[] body;
String checksum;
try {
body = Files.readAllBytes(file.toPath());
synchronized (this) {
checksum = new String(Base64.getEncoder().encode(messageDigest.digest(body)));
messageDigest.reset();
}
} catch (IOException ex) {
throw new RuntimeException(Errors.getMessage(Errors.ORG_HCJF_IO_NET_HTTP_4, Paths.get(request.getContext(), file.getName())), ex);
}
Integer responseCode = HttpResponseCode.OK;
HttpHeader ifNonMatch = request.getHeader(HttpHeader.IF_NONE_MATCH);
if (ifNonMatch != null) {
if (checksum.equals(ifNonMatch.getHeaderValue())) {
responseCode = HttpResponseCode.NOT_MODIFIED;
}
}
String[] nameExtension = file.getName().split(SystemProperties.get(SystemProperties.Net.Http.Folder.FILE_EXTENSION_REGEX));
String extension = nameExtension.length == 2 ? nameExtension[1] : MimeType.BIN;
response.setResponseCode(responseCode);
MimeType mimeType = MimeType.fromSuffix(extension);
response.addHeader(new HttpHeader(HttpHeader.CONTENT_TYPE, mimeType == null ? MimeType.BIN : mimeType.toString()));
response.addHeader(new HttpHeader(HttpHeader.E_TAG, checksum));
response.addHeader(new HttpHeader(HttpHeader.LAST_MODIFIED,
SystemProperties.getDateFormat(SystemProperties.Net.Http.RESPONSE_DATE_HEADER_FORMAT_VALUE).
format(new Date(file.lastModified()))));
if (responseCode.equals(HttpResponseCode.OK)) {
HttpHeader acceptEncodingHeader = request.getHeader(HttpHeader.ACCEPT_ENCODING);
if (acceptEncodingHeader != null) {
boolean notAcceptable = true;
for (String group : acceptEncodingHeader.getGroups()) {
if (group.equalsIgnoreCase(HttpHeader.GZIP) || group.equalsIgnoreCase(HttpHeader.DEFLATE)) {
try (ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gzipOutputStream = new GZIPOutputStream(out)) {
gzipOutputStream.write(body);
gzipOutputStream.flush();
gzipOutputStream.finish();
body = out.toByteArray();
response.addHeader(new HttpHeader(HttpHeader.CONTENT_ENCODING, HttpHeader.GZIP));
notAcceptable = false;
break;
} catch (Exception ex) {
Log.w(SystemProperties.get(SystemProperties.Net.Http.Folder.LOG_TAG), "Zip file process fail", ex);
}
} else if (group.equalsIgnoreCase(HttpHeader.IDENTITY)) {
response.addHeader(new HttpHeader(HttpHeader.CONTENT_ENCODING, HttpHeader.IDENTITY));
notAcceptable = false;
break;
}
}
if (notAcceptable) {
response.setResponseCode(HttpResponseCode.NOT_ACCEPTABLE);
}
}
if (responseCode.equals(HttpResponseCode.OK)) {
response.addHeader(new HttpHeader(HttpHeader.CONTENT_LENGTH, Integer.toString(body.length)));
response.setBody(body);
}
}
}
} else {
retry = onNonExistentFile(request, file);
}
}
return response;
}
/**
* This method could be implemented in order to manage the non-existent file situation.
* By default this implementation throws an IllegalArgument exception if the file not exists.
* @param request Http request instance.
* @param file non-existent file pointer.
* @return Return true if the read file operation must by retried and false in the otherwise.
*/
public boolean onNonExistentFile(HttpRequest request, File file) {
throw new IllegalArgumentException(Errors.getMessage(Errors.ORG_HCJF_IO_NET_HTTP_5, request.getContext()));
}
}
| javaito/HolandaCatalinaFw | src/main/java/org/hcjf/io/net/http/FolderContext.java | Java | apache-2.0 | 15,945 |
package org.omg.dss.metadata.profile;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.omg.dss.common.EntityIdentifier;
/**
* This object groups service profiles of a given type.
*
* <p>Java class for ProfilesOfType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ProfilesOfType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="type" type="{http://www.omg.org/spec/CDSS/201105/dss}ProfileType"/>
* <element name="profileId" type="{http://www.omg.org/spec/CDSS/201105/dss}EntityIdentifier" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ProfilesOfType", propOrder = {
"type",
"profileId"
})
public class ProfilesOfType {
@XmlElement(required = true)
protected ProfileType type;
@XmlElement(required = true)
protected List<EntityIdentifier> profileId;
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link ProfileType }
*
*/
public ProfileType getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link ProfileType }
*
*/
public void setType(ProfileType value) {
this.type = value;
}
/**
* Gets the value of the profileId 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 profileId property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getProfileId().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link EntityIdentifier }
*
*
*/
public List<EntityIdentifier> getProfileId() {
if (profileId == null) {
profileId = new ArrayList<EntityIdentifier>();
}
return this.profileId;
}
}
| TonyWang-UMU/TFG-TWang | opencds-parent/dss-java-stub/src/main/java/org/omg/dss/metadata/profile/ProfilesOfType.java | Java | apache-2.0 | 2,647 |
package io.swagger.client;
import com.fasterxml.jackson.core.JsonGenerator.Feature;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.apache.http.*;
import org.apache.http.client.*;
import org.apache.http.client.methods.*;
import org.apache.http.conn.*;
import org.apache.http.conn.scheme.*;
import org.apache.http.conn.ssl.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.*;
import org.apache.http.impl.conn.*;
import org.apache.http.impl.conn.tsccm.*;
import org.apache.http.params.*;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.net.Socket;
import java.net.UnknownHostException;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class ApiInvoker {
private static ApiInvoker INSTANCE = new ApiInvoker();
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private HttpClient client = null;
private boolean ignoreSSLCertificates = false;
private ClientConnectionManager ignoreSSLConnectionManager;
/** Content type "text/plain" with UTF-8 encoding. */
public static final ContentType TEXT_PLAIN_UTF8 = ContentType.create("text/plain", Consts.UTF_8);
/**
* ISO 8601 date time format.
* @see https://en.wikipedia.org/wiki/ISO_8601
*/
public static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
/**
* ISO 8601 date format.
* @see https://en.wikipedia.org/wiki/ISO_8601
*/
public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
static {
// Use UTC as the default time zone.
DATE_TIME_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
// Set default User-Agent.
setUserAgent("Android-Java-Swagger");
}
public static void setUserAgent(String userAgent) {
INSTANCE.addDefaultHeader("User-Agent", userAgent);
}
public static Date parseDateTime(String str) {
try {
return DATE_TIME_FORMAT.parse(str);
} catch (java.text.ParseException e) {
throw new RuntimeException(e);
}
}
public static Date parseDate(String str) {
try {
return DATE_FORMAT.parse(str);
} catch (java.text.ParseException e) {
throw new RuntimeException(e);
}
}
public static String formatDateTime(Date datetime) {
return DATE_TIME_FORMAT.format(datetime);
}
public static String formatDate(Date date) {
return DATE_FORMAT.format(date);
}
public static String parameterToString(Object param) {
if (param == null) {
return "";
} else if (param instanceof Date) {
return formatDateTime((Date) param);
} else if (param instanceof Collection) {
StringBuilder b = new StringBuilder();
for(Object o : (Collection)param) {
if(b.length() > 0) {
b.append(",");
}
b.append(String.valueOf(o));
}
return b.toString();
} else {
return String.valueOf(param);
}
}
public ApiInvoker() {
initConnectionManager();
}
public static ApiInvoker getInstance() {
return INSTANCE;
}
public void ignoreSSLCertificates(boolean ignoreSSLCertificates) {
this.ignoreSSLCertificates = ignoreSSLCertificates;
}
public void addDefaultHeader(String key, String value) {
defaultHeaderMap.put(key, value);
}
public String escapeString(String str) {
return str;
}
public static Object deserialize(String json, String containerType, Class cls) throws ApiException {
try{
if("list".equalsIgnoreCase(containerType) || "array".equalsIgnoreCase(containerType)) {
JavaType typeInfo = JsonUtil.getJsonMapper().getTypeFactory().constructCollectionType(List.class, cls);
List response = (List<?>) JsonUtil.getJsonMapper().readValue(json, typeInfo);
return response;
}
else if(String.class.equals(cls)) {
if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1)
return json.substring(1, json.length() - 2);
else
return json;
}
else {
return JsonUtil.getJsonMapper().readValue(json, cls);
}
}
catch (IOException e) {
throw new ApiException(500, e.getMessage());
}
}
public static String serialize(Object obj) throws ApiException {
try {
if (obj != null)
return JsonUtil.getJsonMapper().writeValueAsString(obj);
else
return null;
}
catch (Exception e) {
throw new ApiException(500, e.getMessage());
}
}
public String invokeAPI(String host, String path, String method, Map<String, String> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType) throws ApiException {
HttpClient client = getClient(host);
StringBuilder b = new StringBuilder();
for(String key : queryParams.keySet()) {
String value = queryParams.get(key);
if (value != null){
if(b.toString().length() == 0)
b.append("?");
else
b.append("&");
b.append(escapeString(key)).append("=").append(escapeString(value));
}
}
String url = host + path + b.toString();
HashMap<String, String> headers = new HashMap<String, String>();
for(String key : headerParams.keySet()) {
headers.put(key, headerParams.get(key));
}
for(String key : defaultHeaderMap.keySet()) {
if(!headerParams.containsKey(key)) {
headers.put(key, defaultHeaderMap.get(key));
}
}
headers.put("Accept", "application/json");
// URL encoded string from form parameters
String formParamStr = null;
// for form data
if ("application/x-www-form-urlencoded".equals(contentType)) {
StringBuilder formParamBuilder = new StringBuilder();
// encode the form params
for (String key : formParams.keySet()) {
String value = formParams.get(key);
if (value != null && !"".equals(value.trim())) {
if (formParamBuilder.length() > 0) {
formParamBuilder.append("&");
}
try {
formParamBuilder.append(URLEncoder.encode(key, "utf8")).append("=").append(URLEncoder.encode(value, "utf8"));
}
catch (Exception e) {
// move on to next
}
}
}
formParamStr = formParamBuilder.toString();
}
HttpResponse response = null;
try {
if ("GET".equals(method)) {
HttpGet get = new HttpGet(url);
get.addHeader("Accept", "application/json");
for(String key : headers.keySet()) {
get.setHeader(key, headers.get(key));
}
response = client.execute(get);
}
else if ("POST".equals(method)) {
HttpPost post = new HttpPost(url);
if (formParamStr != null) {
post.setHeader("Content-Type", contentType);
post.setEntity(new StringEntity(formParamStr, "UTF-8"));
} else if (body != null) {
if (body instanceof HttpEntity) {
// this is for file uploading
post.setEntity((HttpEntity) body);
} else {
post.setHeader("Content-Type", contentType);
post.setEntity(new StringEntity(serialize(body), "UTF-8"));
}
}
for(String key : headers.keySet()) {
post.setHeader(key, headers.get(key));
}
response = client.execute(post);
}
else if ("PUT".equals(method)) {
HttpPut put = new HttpPut(url);
if (formParamStr != null) {
put.setHeader("Content-Type", contentType);
put.setEntity(new StringEntity(formParamStr, "UTF-8"));
} else if (body != null) {
put.setHeader("Content-Type", contentType);
put.setEntity(new StringEntity(serialize(body), "UTF-8"));
}
for(String key : headers.keySet()) {
put.setHeader(key, headers.get(key));
}
response = client.execute(put);
}
else if ("DELETE".equals(method)) {
HttpDelete delete = new HttpDelete(url);
for(String key : headers.keySet()) {
delete.setHeader(key, headers.get(key));
}
response = client.execute(delete);
}
else if ("PATCH".equals(method)) {
HttpPatch patch = new HttpPatch(url);
if (formParamStr != null) {
patch.setHeader("Content-Type", contentType);
patch.setEntity(new StringEntity(formParamStr, "UTF-8"));
} else if (body != null) {
patch.setHeader("Content-Type", contentType);
patch.setEntity(new StringEntity(serialize(body), "UTF-8"));
}
for(String key : headers.keySet()) {
patch.setHeader(key, headers.get(key));
}
response = client.execute(patch);
}
int code = response.getStatusLine().getStatusCode();
String responseString = null;
if(code == 204)
responseString = "";
else if(code >= 200 && code < 300) {
if(response.getEntity() != null) {
HttpEntity resEntity = response.getEntity();
responseString = EntityUtils.toString(resEntity);
}
return responseString;
}
else {
if(response.getEntity() != null) {
HttpEntity resEntity = response.getEntity();
responseString = EntityUtils.toString(resEntity);
}
else
responseString = "no data";
}
throw new ApiException(code, responseString);
}
catch(IOException e) {
throw new ApiException(500, e.getMessage());
}
}
private HttpClient getClient(String host) {
if (client == null) {
if (ignoreSSLCertificates && ignoreSSLConnectionManager != null) {
// Trust self signed certificates
client = new DefaultHttpClient(ignoreSSLConnectionManager, new BasicHttpParams());
} else {
client = new DefaultHttpClient();
}
}
return client;
}
private void initConnectionManager() {
try {
final SSLContext sslContext = SSLContext.getInstance("SSL");
// set up a TrustManager that trusts everything
TrustManager[] trustManagers = new TrustManager[] {
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {}
public void checkServerTrusted(X509Certificate[] certs, String authType) {}
}};
sslContext.init(null, trustManagers, new SecureRandom());
SSLSocketFactory sf = new SSLSocketFactory((KeyStore)null) {
private javax.net.ssl.SSLSocketFactory sslFactory = sslContext.getSocketFactory();
public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
throws IOException, UnknownHostException {
return sslFactory.createSocket(socket, host, port, autoClose);
}
public Socket createSocket() throws IOException {
return sslFactory.createSocket();
}
};
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Scheme httpsScheme = new Scheme("https", sf, 443);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(httpsScheme);
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
ignoreSSLConnectionManager = new ThreadSafeClientConnManager(new BasicHttpParams(), schemeRegistry);
} catch (NoSuchAlgorithmException e) {
// This will only be thrown if SSL isn't available for some reason.
} catch (KeyManagementException e) {
// This might be thrown when passing a key into init(), but no key is being passed.
} catch (GeneralSecurityException e) {
// This catches anything else that might go wrong.
// If anything goes wrong we default to the standard connection manager.
}
}
}
| jfiala/swagger-spring-demo | user-rest-service-1.0.2/generated-code/android/src/main/java/io/swagger/client/ApiInvoker.java | Java | apache-2.0 | 12,913 |
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/firestore/admin/v1/operation.proto
package com.google.firestore.admin.v1;
/**
*
*
* <pre>
* Describes the state of the operation.
* </pre>
*
* Protobuf enum {@code google.firestore.admin.v1.OperationState}
*/
public enum OperationState implements com.google.protobuf.ProtocolMessageEnum {
/**
*
*
* <pre>
* Unspecified.
* </pre>
*
* <code>OPERATION_STATE_UNSPECIFIED = 0;</code>
*/
OPERATION_STATE_UNSPECIFIED(0),
/**
*
*
* <pre>
* Request is being prepared for processing.
* </pre>
*
* <code>INITIALIZING = 1;</code>
*/
INITIALIZING(1),
/**
*
*
* <pre>
* Request is actively being processed.
* </pre>
*
* <code>PROCESSING = 2;</code>
*/
PROCESSING(2),
/**
*
*
* <pre>
* Request is in the process of being cancelled after user called
* google.longrunning.Operations.CancelOperation on the operation.
* </pre>
*
* <code>CANCELLING = 3;</code>
*/
CANCELLING(3),
/**
*
*
* <pre>
* Request has been processed and is in its finalization stage.
* </pre>
*
* <code>FINALIZING = 4;</code>
*/
FINALIZING(4),
/**
*
*
* <pre>
* Request has completed successfully.
* </pre>
*
* <code>SUCCESSFUL = 5;</code>
*/
SUCCESSFUL(5),
/**
*
*
* <pre>
* Request has finished being processed, but encountered an error.
* </pre>
*
* <code>FAILED = 6;</code>
*/
FAILED(6),
/**
*
*
* <pre>
* Request has finished being cancelled after user called
* google.longrunning.Operations.CancelOperation.
* </pre>
*
* <code>CANCELLED = 7;</code>
*/
CANCELLED(7),
UNRECOGNIZED(-1),
;
/**
*
*
* <pre>
* Unspecified.
* </pre>
*
* <code>OPERATION_STATE_UNSPECIFIED = 0;</code>
*/
public static final int OPERATION_STATE_UNSPECIFIED_VALUE = 0;
/**
*
*
* <pre>
* Request is being prepared for processing.
* </pre>
*
* <code>INITIALIZING = 1;</code>
*/
public static final int INITIALIZING_VALUE = 1;
/**
*
*
* <pre>
* Request is actively being processed.
* </pre>
*
* <code>PROCESSING = 2;</code>
*/
public static final int PROCESSING_VALUE = 2;
/**
*
*
* <pre>
* Request is in the process of being cancelled after user called
* google.longrunning.Operations.CancelOperation on the operation.
* </pre>
*
* <code>CANCELLING = 3;</code>
*/
public static final int CANCELLING_VALUE = 3;
/**
*
*
* <pre>
* Request has been processed and is in its finalization stage.
* </pre>
*
* <code>FINALIZING = 4;</code>
*/
public static final int FINALIZING_VALUE = 4;
/**
*
*
* <pre>
* Request has completed successfully.
* </pre>
*
* <code>SUCCESSFUL = 5;</code>
*/
public static final int SUCCESSFUL_VALUE = 5;
/**
*
*
* <pre>
* Request has finished being processed, but encountered an error.
* </pre>
*
* <code>FAILED = 6;</code>
*/
public static final int FAILED_VALUE = 6;
/**
*
*
* <pre>
* Request has finished being cancelled after user called
* google.longrunning.Operations.CancelOperation.
* </pre>
*
* <code>CANCELLED = 7;</code>
*/
public static final int CANCELLED_VALUE = 7;
public final int getNumber() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalArgumentException(
"Can't get the number of an unknown enum value.");
}
return value;
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static OperationState valueOf(int value) {
return forNumber(value);
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
*/
public static OperationState forNumber(int value) {
switch (value) {
case 0:
return OPERATION_STATE_UNSPECIFIED;
case 1:
return INITIALIZING;
case 2:
return PROCESSING;
case 3:
return CANCELLING;
case 4:
return FINALIZING;
case 5:
return SUCCESSFUL;
case 6:
return FAILED;
case 7:
return CANCELLED;
default:
return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<OperationState> internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<OperationState> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<OperationState>() {
public OperationState findValueByNumber(int number) {
return OperationState.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalStateException(
"Can't get the descriptor of an unrecognized enum value.");
}
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() {
return com.google.firestore.admin.v1.OperationProto.getDescriptor().getEnumTypes().get(0);
}
private static final OperationState[] VALUES = values();
public static OperationState valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type.");
}
if (desc.getIndex() == -1) {
return UNRECOGNIZED;
}
return VALUES[desc.getIndex()];
}
private final int value;
private OperationState(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:google.firestore.admin.v1.OperationState)
}
| googleapis/java-firestore | proto-google-cloud-firestore-admin-v1/src/main/java/com/google/firestore/admin/v1/OperationState.java | Java | apache-2.0 | 6,767 |
/**
* 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.pulsar.common.util;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format;
import com.fasterxml.jackson.databind.AnnotationIntrospector;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
import com.fasterxml.jackson.databind.util.EnumResolver;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
/**
* Generic value converter.
*
* <p><h3>Use examples</h3>
*
* <pre>
* String o1 = String.valueOf(1);
* ;
* Integer i = FieldParser.convert(o1, Integer.class);
* System.out.println(i); // 1
*
* </pre>
*
*/
public final class FieldParser {
private static final Map<String, Method> CONVERTERS = new HashMap<>();
private static final Map<Class<?>, Class<?>> WRAPPER_TYPES = new HashMap<>();
private static final AnnotationIntrospector ANNOTATION_INTROSPECTOR = new JacksonAnnotationIntrospector();
static {
// Preload converters and wrapperTypes.
initConverters();
initWrappers();
}
/**
* Convert the given object value to the given class.
*
* @param from
* The object value to be converted.
* @param to
* The type class which the given object should be converted to.
* @return The converted object value.
* @throws UnsupportedOperationException
* If no suitable converter can be found.
* @throws RuntimeException
* If conversion failed somehow. This can be caused by at least an ExceptionInInitializerError,
* IllegalAccessException or InvocationTargetException.
*/
@SuppressWarnings("unchecked")
public static <T> T convert(Object from, Class<T> to) {
checkNotNull(to);
if (from == null) {
return null;
}
to = (Class<T>) wrap(to);
// Can we cast? Then just do it.
if (to.isAssignableFrom(from.getClass())) {
return to.cast(from);
}
// Lookup the suitable converter.
String converterId = from.getClass().getName() + "_" + to.getName();
Method converter = CONVERTERS.get(converterId);
if (to.isEnum()) {
// Converting string to enum
EnumResolver r = EnumResolver.constructUsingToString((Class<Enum<?>>) to, ANNOTATION_INTROSPECTOR);
T value = (T) r.findEnum((String) from);
if (value == null) {
throw new RuntimeException("Invalid value '" + from + "' for enum " + to);
}
return value;
}
if (converter == null) {
throw new UnsupportedOperationException("Cannot convert from " + from.getClass().getName() + " to "
+ to.getName() + ". Requested converter does not exist.");
}
// Convert the value.
try {
Object val = converter.invoke(to, from);
return to.cast(val);
} catch (Exception e) {
throw new RuntimeException("Cannot convert from " + from.getClass().getName() + " to " + to.getName()
+ ". Conversion failed with " + e.getMessage(), e);
}
}
/**
* Update given Object attribute by reading it from provided map properties.
*
* @param properties
* which key-value pair of properties to assign those values to given object
* @param obj
* object which needs to be updated
* @throws IllegalArgumentException
* if the properties key-value contains incorrect value type
*/
public static <T> void update(Map<String, String> properties, T obj) throws IllegalArgumentException {
Field[] fields = obj.getClass().getDeclaredFields();
Arrays.stream(fields).forEach(f -> {
if (properties.containsKey(f.getName())) {
try {
f.setAccessible(true);
String v = properties.get(f.getName());
if (!StringUtils.isBlank(v)) {
f.set(obj, value(v, f));
} else {
setEmptyValue(v, f, obj);
}
} catch (Exception e) {
throw new IllegalArgumentException(format("failed to initialize %s field while setting value %s",
f.getName(), properties.get(f.getName())), e);
}
}
});
}
/**
* Converts value as per appropriate DataType of the field.
*
* @param strValue
* : string value of the object
* @param field
* : field of the attribute
* @return
*/
public static Object value(String strValue, Field field) {
checkNotNull(field);
// if field is not primitive type
Type fieldType = field.getGenericType();
if (fieldType instanceof ParameterizedType) {
Class<?> clazz = (Class<?>) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
if (field.getType().equals(List.class)) {
// convert to list
return stringToList(strValue, clazz);
} else if (field.getType().equals(Set.class)) {
// covert to set
return stringToSet(strValue, clazz);
} else if (field.getType().equals(Map.class)) {
Class<?> valueClass =
(Class<?>) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[1];
return stringToMap(strValue, clazz, valueClass);
} else if (field.getType().equals(Optional.class)) {
Type typeClazz = ((ParameterizedType) fieldType).getActualTypeArguments()[0];
if (typeClazz instanceof ParameterizedType) {
throw new IllegalArgumentException(format("unsupported non-primitive Optional<%s> for %s",
typeClazz.getClass(), field.getName()));
}
return Optional.ofNullable(convert(strValue, (Class) typeClazz));
} else {
throw new IllegalArgumentException(
format("unsupported field-type %s for %s", field.getType(), field.getName()));
}
} else {
return convert(strValue, field.getType());
}
}
/**
* Sets the empty/null value if field is allowed to be set empty.
*
* @param strValue
* @param field
* @param obj
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static <T> void setEmptyValue(String strValue, Field field, T obj)
throws IllegalArgumentException, IllegalAccessException {
checkNotNull(field);
// if field is not primitive type
Type fieldType = field.getGenericType();
if (fieldType instanceof ParameterizedType) {
if (field.getType().equals(List.class)) {
field.set(obj, Lists.newArrayList());
} else if (field.getType().equals(Set.class)) {
field.set(obj, Sets.newHashSet());
} else if (field.getType().equals(Optional.class)) {
field.set(obj, Optional.empty());
} else {
throw new IllegalArgumentException(
format("unsupported field-type %s for %s", field.getType(), field.getName()));
}
} else if (Number.class.isAssignableFrom(field.getType()) || fieldType.getClass().equals(String.class)) {
field.set(obj, null);
}
}
private static Class<?> wrap(Class<?> type) {
return WRAPPER_TYPES.containsKey(type) ? WRAPPER_TYPES.get(type) : type;
}
private static void initConverters() {
Method[] methods = FieldParser.class.getDeclaredMethods();
Arrays.stream(methods).forEach(method -> {
if (method.getParameterTypes().length == 1) {
// Converter should accept 1 argument. This skips the convert() method.
CONVERTERS.put(method.getParameterTypes()[0].getName() + "_" + method.getReturnType().getName(),
method);
}
});
}
private static void initWrappers() {
WRAPPER_TYPES.put(int.class, Integer.class);
WRAPPER_TYPES.put(float.class, Float.class);
WRAPPER_TYPES.put(double.class, Double.class);
WRAPPER_TYPES.put(long.class, Long.class);
WRAPPER_TYPES.put(boolean.class, Boolean.class);
}
/***** --- Converters --- ****/
/**
* Converts String to Integer.
*
* @param val
* The String to be converted.
* @return The converted Integer value.
*/
public static Integer stringToInteger(String val) {
String v = trim(val);
if (io.netty.util.internal.StringUtil.isNullOrEmpty(v)) {
return null;
} else {
return Integer.valueOf(v);
}
}
/**
* Converts String to Long.
*
* @param val
* The String to be converted.
* @return The converted Long value.
*/
public static Long stringToLong(String val) {
return Long.valueOf(trim(val));
}
/**
* Converts String to Double.
*
* @param val
* The String to be converted.
* @return The converted Double value.
*/
public static Double stringToDouble(String val) {
String v = trim(val);
if (io.netty.util.internal.StringUtil.isNullOrEmpty(v)) {
return null;
} else {
return Double.valueOf(v);
}
}
/**
* Converts String to float.
*
* @param val
* The String to be converted.
* @return The converted Double value.
*/
public static Float stringToFloat(String val) {
return Float.valueOf(trim(val));
}
/**
* Converts comma separated string to List.
*
* @param <T>
* type of list
* @param val
* comma separated values.
* @return The converted list with type {@code <T>}.
*/
public static <T> List<T> stringToList(String val, Class<T> type) {
String[] tokens = trim(val).split(",");
return Arrays.stream(tokens).map(t -> {
return convert(t, type);
}).collect(Collectors.toList());
}
/**
* Converts comma separated string to Set.
*
* @param <T>
* type of set
* @param val
* comma separated values.
* @return The converted set with type {@code <T>}.
*/
public static <T> Set<T> stringToSet(String val, Class<T> type) {
String[] tokens = trim(val).split(",");
return Arrays.stream(tokens).map(t -> {
return convert(t, type);
}).collect(Collectors.toSet());
}
private static <K, V> Map<K, V> stringToMap(String strValue, Class<K> keyType, Class<V> valueType) {
String[] tokens = trim(strValue).split(",");
Map<K, V> map = new HashMap<>();
for (String token : tokens) {
String[] keyValue = trim(token).split("=");
checkArgument(keyValue.length == 2,
strValue + " map-value is not in correct format key1=value,key2=value2");
map.put(convert(keyValue[0], keyType), convert(keyValue[1], valueType));
}
return map;
}
private static String trim(String val) {
checkNotNull(val);
return val.trim();
}
/**
* Converts Integer to String.
*
* @param value
* The Integer to be converted.
* @return The converted String value.
*/
public static String integerToString(Integer value) {
return value.toString();
}
/**
* Converts Boolean to String.
*
* @param value
* The Boolean to be converted.
* @return The converted String value.
*/
public static String booleanToString(Boolean value) {
return value.toString();
}
/**
* Converts String to Boolean.
*
* @param value
* The String to be converted.
* @return The converted Boolean value.
*/
public static Boolean stringToBoolean(String value) {
return Boolean.valueOf(value);
}
// implement more converter methods here.
} | yahoo/pulsar | pulsar-common/src/main/java/org/apache/pulsar/common/util/FieldParser.java | Java | apache-2.0 | 13,726 |
package com.alibaba.json.bvt.util;
import com.alibaba.fastjson.annotation.JSONType;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.alibaba.json.bvt.parser.deser.generic.GenericArrayTest;
import com.jsoniter.spi.GenericArrayTypeImpl;
import junit.framework.TestCase;
import java.lang.reflect.Constructor;
import java.lang.reflect.GenericArrayType;
public class TypeUtilsTest extends TestCase {
public void test_0() throws Exception {
assertEquals(0, TypeUtils.getSerializeFeatures(Object.class));
assertEquals(SerializerFeature.WriteMapNullValue.mask, TypeUtils.getSerializeFeatures(Model.class));
}
public void test_1() throws Exception {
TypeUtils.checkPrimitiveArray((GenericArrayType) A.class.getField("values").getGenericType());
}
public void test_3() throws Exception {
assertTrue(TypeUtils.isHibernateInitialized(new Object()));
}
public void test_2() throws Exception {
Constructor<?> constructor = GenericArrayTypeImpl.class.getDeclaredConstructors()[0];
constructor.setAccessible(true);
Class[] classes = new Class[] {
boolean[].class,
byte[].class,
short[].class,
int[].class,
long[].class,
float[].class,
double[].class,
char[].class,
};
for (Class clazz : classes) {
GenericArrayType type = (GenericArrayType) constructor.newInstance(clazz.getComponentType());
assertEquals(clazz, TypeUtils.checkPrimitiveArray(type));
}
}
@JSONType(serialzeFeatures = SerializerFeature.WriteMapNullValue)
public static class Model {
}
public static class A<T extends Number> {
public T[] values;
}
public static class VO extends GenericArrayTest.A {
}
}
| alibaba/fastjson | src/test/java/com/alibaba/json/bvt/util/TypeUtilsTest.java | Java | apache-2.0 | 1,899 |
package com.hozakan.spotifystreamer.ui.activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.hozakan.spotifystreamer.R;
import com.hozakan.spotifystreamer.ui.fragment.ListArtistTopTenTracksFragment;
import kaaes.spotify.webapi.android.models.Artist;
import kaaes.spotify.webapi.android.models.Track;
/**
* Created by gimbert on 15-06-28.
*/
public class ArtistActivity extends AppCompatActivity implements ListArtistTopTenTracksFragment.ListArtistTopTenTracksFragmentCallback {
private static final String ARTIST_ID_EXTRA_KEY = "ARTIST_ID_EXTRA_KEY";
private static final String ARTIST_NAME_EXTRA_KEY = "ARTIST_NAME_EXTRA_KEY";
public static Intent createIntent(Context context, Artist artist) {
Intent intent = new Intent(context, ArtistActivity.class);
intent.putExtra(ARTIST_ID_EXTRA_KEY, artist.id);
intent.putExtra(ARTIST_NAME_EXTRA_KEY, artist.name);
return intent;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_artist);
getSupportActionBar().setSubtitle(getIntent().getStringExtra(ARTIST_NAME_EXTRA_KEY));
if (savedInstanceState == null) {
getFragmentManager()
.beginTransaction()
.replace(R.id.container,
ListArtistTopTenTracksFragment.newInstance(getIntent().getStringExtra(ARTIST_ID_EXTRA_KEY)))
.commit();
}
}
@Override
public void onTrackClicked(Track track) {
startActivity(
TrackPreviewActivity.createIntent(
this, getIntent().getStringExtra(ARTIST_NAME_EXTRA_KEY), track));
}
}
| HozakaN/Spotify-Streamer | app/src/main/java/com/hozakan/spotifystreamer/ui/activity/ArtistActivity.java | Java | apache-2.0 | 1,858 |
package com.example.alexis.navitia_android;
import java.util.ArrayList;
/**
* @author Alexis Robin
* @version 0.6
* Licensed under the Apache2 license
*/
public class BusTrip extends WayPart {
private Route route;
private String busId;
private ArrayList<TimedStop> stops;
protected BusTrip(Address from, Address to, double co2Emission, String departureDateTime, String arrivalDateTime, int duration, GeoJSON geoJSON, Route route, String busId, ArrayList<TimedStop> stops) {
super("Bus Trip", from, to, co2Emission, departureDateTime, arrivalDateTime, duration, geoJSON);
this.route = route;
this.busId = busId;
this.stops = stops;
}
public Route getRoute() {
return route;
}
public String getBusId() {
return busId;
}
public ArrayList<TimedStop> getStops() {
return stops;
}
@Override
public String toString(){
return "Prendre la " + this.getRoute().toString() + " et descendre à " + this.getTo().toString();
}
}
| setARget/Navitia-Android | app/src/main/java/com/example/alexis/navitia_android/BusTrip.java | Java | apache-2.0 | 1,046 |
package com.waltz3d.museum;
import java.util.List;
import com.waltz3d.museum.FootListView.FootStatus;
import com.waltz3d.museum.FootListView.OnLoadMoreListenr;
import com.waltz3d.museum.HttpManager.OnLoadFinishListener;
import com.waltz3d.museum.detail.DetailActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
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.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.TextView;
public class CollectionListActivity extends Activity {
private GuideGallery mGuideGallery;
private int categoryids;
private FootListView mainlistView;
private CustomListAdapter mCustomListAdapter;
private TextView textView_listhead;
private static final int DEFINE_SIZE = 5;
private Handler mHandler = new Handler();
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collectionlist);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setDisplayShowHomeEnabled(false);
categoryids = getIntent().getIntExtra("categoryids", 5);
textView_listhead =(TextView) findViewById(R.id.textView_listhead);
textView_listhead.setText(categoryids == 5?"新石器时代":"青铜时代");
mGuideGallery = (GuideGallery) findViewById(R.id.listview_head);
mGuideGallery.setAdapter(new ImageAdapter());
// swipeLayout.setOnRefreshListener(new OnRefreshListener() {
//
// @Override
// public void onRefresh() {
// loadData(0,false);
// }
// });
// swipeLayout.setRefreshing(true);
mainlistView = (FootListView) findViewById(R.id.mainlistView);
mainlistView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(CollectionListActivity.this, DetailActivity.class);
Cultural item = mCustomListAdapter.getItem(position);
if(item != null){
String url = item.ProductPictures.get(Math.min(1, item.ProductPictures.size() - 1)).PictureUrl;
intent.putExtra("PictureUrl", url);
intent.putExtra("comFrom", 1);
startActivity(intent);
}
}
});
mainlistView.setOnLoadMoreListenr(new OnLoadMoreListenr() {
@Override
public void onLoadData() {
int pageIndex = mCustomListAdapter.getCount()/DEFINE_SIZE;
loadData(pageIndex,true);
}
});
mCustomListAdapter = new CustomListAdapter(CollectionListActivity.this);
mainlistView.setAdapter(mCustomListAdapter);
loadData(0,false);
}
private void loadData(int pageIndex,final boolean isAppend){
Log.d("loadData", "pageIndex="+pageIndex+",isAppend="+isAppend);
new HttpManager().loadDataWithNoCache(categoryids, pageIndex, DEFINE_SIZE, new OnLoadFinishListener<Cultural>() {
@Override
public void onLoad(final List<Cultural> mList) {
mHandler.post(new Runnable() {
@Override
public void run() {
if(mList != null && mList.size() > 0){
mCustomListAdapter.refreshData(mList, isAppend);
if(mList.size() < DEFINE_SIZE){
mainlistView.setFootStatus(FootStatus.Gone);
}else{
mainlistView.setFootStatus(FootStatus.Common);
}
}else{//拉取数据失败,则设置不可见
mainlistView.setFootStatus(FootStatus.Gone);
}
}
});
}
});
}
@Override
protected void onResume() {
super.onResume();
if(mGuideGallery!=null){
mGuideGallery.onResume();
}
}
@Override
protected void onStop() {
super.onStop();
if(mGuideGallery!=null){
mGuideGallery.onStop();
}
}
private class ImageAdapter extends RecyclingPagerAdapter {
private int[] menu_image_array_common = { R.drawable.collection_1, R.drawable.collection_2, R.drawable.collection_3, R.drawable.collection_4 };
LayoutInflater mInflater;
public ImageAdapter() {
mInflater = LayoutInflater.from(CollectionListActivity.this);
}
public int getCount() {
return Integer.MAX_VALUE;
}
public Integer getItem(int position) {
return menu_image_array_common[position % menu_image_array_common.length];
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder n = null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item_resource_suggest_head, null);
n = new ViewHolder();
n.gallery_image = (ImageView) convertView.findViewById(R.id.gallery_image);
convertView.setTag(n);
} else {
n = (ViewHolder) convertView.getTag();
}
final Integer mItem = getItem(position);
n.gallery_image.setImageResource(mItem);
n.gallery_image.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
return convertView;
}
class ViewHolder {
public ImageView gallery_image;
}
@Override
public int getRealCount() {
return menu_image_array_common.length;
}
}
}
| zhangzhige/Museum | src/com/waltz3d/museum/CollectionListActivity.java | Java | apache-2.0 | 5,894 |
/**
* JBoss, Home of Professional Open Source
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.warp.lifecycle;
import java.util.List;
import org.jboss.arquillian.container.test.test.AbstractContainerTestTestBase;
import org.jboss.arquillian.core.spi.Manager;
import org.jboss.arquillian.core.spi.context.Context;
import org.jboss.arquillian.warp.server.request.RequestContext;
import org.jboss.arquillian.warp.server.request.RequestContextImpl;
/**
* @author Lukas Fryc
*/
public class AbstractLifecycleTestBase extends AbstractContainerTestTestBase {
@Override
protected void addContexts(List<Class<? extends Context>> contexts) {
super.addContexts(contexts);
contexts.add(RequestContextImpl.class);
}
@Override
protected void startContexts(Manager manager) {
super.startContexts(manager);
manager.getContext(RequestContext.class).activate();
}
}
| aslakknutsen/arquillian-extension-warp | impl/src/test/java/org/jboss/arquillian/warp/lifecycle/AbstractLifecycleTestBase.java | Java | apache-2.0 | 1,631 |
/* Copyright 2014 Danish Maritime Authority.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.maritimecloud.identityregistry.domain;
/**
*
* @author Christoffer Børrild
*/
public enum Role {
ADMIN, USER
}
| MaritimeCloud/MaritimeCloudPortalTestbed | src/main/java/net/maritimecloud/identityregistry/domain/Role.java | Java | apache-2.0 | 750 |
package com.ityang.leetcode;
public class Subject11 {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public static int maxArea(int[] height) {
if(height.length<2)
return -1;
int start = 0,end = height.length-1,res=0,temp=0;
while(start<end){
if(height[start]>height[end]){
temp = height[end]*(end-start);
end--;
}else{
temp = height[start]*(end-start);
start++;
}
if(temp>res)
res = temp;
}
return res;
}
}
| itYangJie/leetcode | src/com/ityang/leetcode/Subject11.java | Java | apache-2.0 | 503 |
/*
Copyright 2017 IBM Corp.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.ibm.cloud.appid.android.internal.tokens;
import com.ibm.cloud.appid.android.api.tokens.AccessToken;
import org.jetbrains.annotations.NotNull;
public class AccessTokenImpl extends AbstractToken implements AccessToken {
private final static String SCOPE = "scope";
public AccessTokenImpl (@NotNull String raw) throws RuntimeException {
super(raw);
}
@Override
public String getScope () {
return (String) getValue(SCOPE);
}
}
| ibm-cloud-security/appid-clientsdk-android | lib/src/main/java/com/ibm/cloud/appid/android/internal/tokens/AccessTokenImpl.java | Java | apache-2.0 | 1,012 |
package sh.isaac.model.observable.override;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.Property;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import sh.isaac.api.observable.coordinate.PropertyWithOverride;
import sh.isaac.model.observable.equalitybased.SimpleEqualityBasedObjectProperty;
import java.util.ArrayList;
import java.util.HashSet;
public class ObjectPropertyWithOverride<T> extends SimpleEqualityBasedObjectProperty<T>
implements PropertyWithOverride<T> {
private HashSet<InvalidationListener> invalidationListeners;
private HashSet<ChangeListener<? super T>> changeListeners;
private final ObjectProperty<T> overriddenProperty;
private T oldValue;
private boolean overridden = false;
/**
* Note that if you don't declare a listener as final in this way, and just use method references, or
* a direct lambda expression, you will not be able to remove the listener, since each method reference will create
* a new object, and they won't compare equal using object identity.
* https://stackoverflow.com/questions/42146360/how-do-i-remove-lambda-expressions-method-handles-that-are-used-as-listeners
*/
private final ChangeListener<? super T> overriddenPropertyChangedListener = this::overriddenPropertyChanged;
/**
* Note that if you don't declare a listener as final in this way, and just use method references, or
* a direct lambda expression, you will not be able to remove the listener, since each method reference will create
* a new object, and they won't compare equal using object identity.
* https://stackoverflow.com/questions/42146360/how-do-i-remove-lambda-expressions-method-handles-that-are-used-as-listeners
*/
private final InvalidationListener overriddenPropertyInvalidationListener = this::overriddenPropertyInvalidated;
public ObjectPropertyWithOverride(ObjectProperty<T> overriddenProperty, Object bean) {
super(bean, overriddenProperty.getName());
this.overriddenProperty = overriddenProperty;
}
@Override
public boolean isOverridden() {
return overridden;
}
@Override
public void removeOverride() {
this.set(null);
}
@Override
public Property<T> overriddenProperty() {
return this.overriddenProperty;
}
@Override
public T get() {
if (this.overridden) {
return super.get();
}
return this.overriddenProperty.get();
}
@Override
public void set(T newValue) {
privateSet(newValue);
}
private void privateSet(T newValue) {
this.oldValue = get();
if (newValue == null) {
this.overridden = false;
if (this.oldValue != null) {
super.set(null);
if (this.oldValue != null &! this.oldValue.equals(this.overriddenProperty.get())) {
invalidated();
fireValueChangedEvent();
}
}
} else if (newValue.equals(this.overriddenProperty.get())) {
// values equal so not an override.
this.overridden = false;
super.set(null);
} else {
// values not equal
super.set(newValue);
this.overridden = true;
invalidated();
fireValueChangedEvent();
}
}
@Override
public void setValue(T v) {
privateSet(v);
}
@Override
public T getValue() {
if (this.overridden) {
return super.getValue();
}
return this.overriddenProperty.getValue();
}
@Override
public void addListener(InvalidationListener listener) {
if (this.invalidationListeners == null) {
this.invalidationListeners = new HashSet<>();
this.overriddenProperty.addListener(this.overriddenPropertyInvalidationListener);
}
this.invalidationListeners.add(listener);
}
@Override
public void removeListener(InvalidationListener listener) {
this.invalidationListeners.remove(listener);
if (this.invalidationListeners.isEmpty()) {
this.overriddenProperty.removeListener(this.overriddenPropertyInvalidationListener);
this.invalidationListeners = null;
}
}
@Override
public void addListener(ChangeListener<? super T> listener) {
if (this.changeListeners == null) {
this.changeListeners = new HashSet<>();
this.overriddenProperty.addListener(this.overriddenPropertyChangedListener);
}
this.changeListeners.add(listener);
}
@Override
public void removeListener(ChangeListener<? super T> listener) {
if (this.changeListeners != null) {
this.changeListeners.remove(listener);
if (this.changeListeners.isEmpty()) {
this.overriddenProperty.removeListener(this.overriddenPropertyChangedListener);
this.changeListeners = null;
}
}
}
private void overriddenPropertyChanged(ObservableValue<? extends T> observable, T oldValue, T newValue) {
if (!overridden) {
this.oldValue = oldValue;
fireValueChangedEvent();
}
}
@Override
protected void fireValueChangedEvent() {
T newValue = get();
if (this.oldValue != newValue) {
if (this.oldValue != null) {
if (!this.oldValue.equals(newValue)) {
notify(newValue);
}
} else {
notify(newValue);
}
}
}
private void notify(T newValue) {
if (this.changeListeners != null) {
ArrayList<ChangeListener<? super T>> listenerList = new ArrayList<>(this.changeListeners);
listenerList.forEach(changeListener -> changeListener.changed(this, this.oldValue, newValue));
}
}
private void overriddenPropertyInvalidated(Observable observable) {
if (!this.overridden) {
invalidated();
}
}
@Override
protected void invalidated() {
HashSet<InvalidationListener> listeners = this.invalidationListeners;
if (listeners != null) {
listeners.forEach(invalidationListener ->
invalidationListener.invalidated(this));
}
}
}
| OSEHRA/ISAAC | core/model/src/main/java/sh/isaac/model/observable/override/ObjectPropertyWithOverride.java | Java | apache-2.0 | 6,534 |
package org.ovirt.engine.core.common.action;
import org.ovirt.engine.core.common.businessentities.CopyVolumeType;
import org.ovirt.engine.core.common.businessentities.ImageOperation;
import org.ovirt.engine.core.common.businessentities.VolumeFormat;
import org.ovirt.engine.core.common.businessentities.VolumeType;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.NGuid;
public class MoveOrCopyImageGroupParameters extends ImagesContainterParametersBase {
private static final long serialVersionUID = -5874446297123213719L;
private ImageOperation operation = ImageOperation.Unassigned;
private boolean useCopyCollapse;
private VolumeFormat volumeFormat = VolumeFormat.UNUSED0;
private VolumeType volumeType = VolumeType.Unassigned;
private CopyVolumeType copyVolumeType = CopyVolumeType.SharedVol;
private boolean addImageDomainMapping;
private boolean forceOverride;
private NGuid sourceDomainId;
private Guid destImageGroupId;
public MoveOrCopyImageGroupParameters() {
}
public MoveOrCopyImageGroupParameters(Guid imageId,
NGuid sourceDomainId,
Guid destDomainId,
ImageOperation operation) {
super(imageId);
setSourceDomainId(sourceDomainId);
setStorageDomainId(destDomainId);
setOperation(operation);
}
public MoveOrCopyImageGroupParameters(Guid containerId, Guid imageGroupId, Guid leafSnapshotID,
Guid storageDomainId, ImageOperation operation) {
super(leafSnapshotID, containerId);
setStorageDomainId(storageDomainId);
setImageGroupID(imageGroupId);
setOperation(operation);
setUseCopyCollapse(false);
setVolumeFormat(VolumeFormat.Unassigned);
setVolumeType(VolumeType.Unassigned);
setForceOverride(false);
setDestinationImageId(leafSnapshotID);
setDestImageGroupId(imageGroupId);
}
public MoveOrCopyImageGroupParameters(Guid containerId,
Guid imageGroupId,
Guid imageId,
Guid destImageGroupId,
Guid destImageId,
Guid storageDomainId, ImageOperation operation) {
this(containerId, imageGroupId, imageId, storageDomainId, operation);
setDestImageGroupId(destImageGroupId);
setDestinationImageId(destImageId);
}
public Guid getDestImageGroupId() {
return destImageGroupId;
}
public void setDestImageGroupId(Guid destImageGroupId) {
this.destImageGroupId = destImageGroupId;
}
public ImageOperation getOperation() {
return operation;
}
private void setOperation(ImageOperation value) {
operation = value;
}
public boolean getUseCopyCollapse() {
return useCopyCollapse;
}
public void setUseCopyCollapse(boolean value) {
useCopyCollapse = value;
}
public VolumeFormat getVolumeFormat() {
return volumeFormat;
}
public void setVolumeFormat(VolumeFormat value) {
volumeFormat = value;
}
public VolumeType getVolumeType() {
return volumeType;
}
public void setVolumeType(VolumeType value) {
volumeType = value;
}
public CopyVolumeType getCopyVolumeType() {
return copyVolumeType;
}
public void setCopyVolumeType(CopyVolumeType value) {
copyVolumeType = value;
}
public boolean getAddImageDomainMapping() {
return addImageDomainMapping;
}
public void setAddImageDomainMapping(boolean value) {
addImageDomainMapping = value;
}
public boolean getForceOverride() {
return forceOverride;
}
public void setForceOverride(boolean value) {
forceOverride = value;
}
public NGuid getSourceDomainId() {
return sourceDomainId;
}
public void setSourceDomainId(NGuid value) {
sourceDomainId = value;
}
}
| jbeecham/ovirt-engine | backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/action/MoveOrCopyImageGroupParameters.java | Java | apache-2.0 | 3,974 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package de.hsbo.fbg.sm4c.common.dao;
/**
*
* @author Sebastian Drost
*/
public class DatabaseException extends Exception {
public DatabaseException(String message) {
super(message);
}
public DatabaseException(String message, Throwable cause) {
super(message, cause);
}
}
| SebaDro/SocialMedia4Crisis | sm4c-common/src/main/java/de/hsbo/fbg/sm4c/common/dao/DatabaseException.java | Java | apache-2.0 | 494 |
/*******************************************************************************
* Copyright (c) 2017 Intuit
*
* 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.intuit.ipp.serialization.custom;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.intuit.ipp.data.CustomerTypeEnum;
/**
* Custom JsonSerializer for reading CustomerTypeEnum values
*
*/
public class CustomerTypeEnumJsonSerializer extends JsonSerializer<CustomerTypeEnum> {
/**
* {@inheritDoc}
*/
@Override
public void serialize(CustomerTypeEnum value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
jgen.writeString(value.value());
}
}
| intuit/QuickBooks-V3-Java-SDK | ipp-v3-java-devkit/src/main/java/com/intuit/ipp/serialization/custom/CustomerTypeEnumJsonSerializer.java | Java | apache-2.0 | 1,388 |
// Copyright 2013 Konrad Twardowski
//
// 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.makagiga.commons;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;
/**
* @since 4.10
*/
public final class ElapsedTimer implements Serializable {
// private
private long nanoStart;
// public
public ElapsedTimer(final boolean start) {
if (start)
start();
}
public long elapsedMS() {
return elapsedNano() / 1000000L;
}
public long elapsedNano() {
return Math.abs(System.nanoTime() - nanoStart);
}
public long elapsedSeconds() {
return elapsedMS() / 1000L;
}
public static String formatNano(final long value) {
return String.format("%1.2f ms", value / 1000000f);
}
public boolean isExpired(final TimeUnit unit, final long value) {
return unit.convert(elapsedNano(), TimeUnit.NANOSECONDS) >= value;
}
public void start() {
nanoStart = System.nanoTime();
}
}
| stuffer2325/Makagiga | src/org/makagiga/commons/ElapsedTimer.java | Java | apache-2.0 | 1,432 |
package com.cowthan.algrithm.algs4;
/*************************************************************************
* Compilation: javac SET.java
* Execution: java SET
*
* Set implementation using Java's TreeSet library.
* Does not allow duplicates.
*
* % java SET
* 128.112.136.11
* 208.216.181.15
* null
*
* Remarks
* -------
* - The equals() method declares two empty sets to be equal
* even if they are parameterized by different generic types.
* This is consistent with the way equals() works with Java's
* Collections framework.
*
*************************************************************************/
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;
import com.cowthan.algrithm.std.In;
import com.cowthan.algrithm.std.StdIn;
import com.cowthan.algrithm.std.StdOut;
import com.cowthan.algrithm.std.StdRandom;
/**
* The <tt>SET</tt> class represents an ordered set. It assumes that
* the elements are <tt>Comparable</tt>.
* It supports the usual <em>add</em>, <em>contains</em>, and <em>delete</em>
* methods. It also provides ordered methods for finding the <em>minimum</em>,
* <em>maximum</em>, <em>floor</em>, and <em>ceiling</em>.
* <p>
* This implementation uses a balanced binary search tree.
* The <em>add</em>, <em>contains</em>, <em>delete</em>, <em>minimum</em>,
* <em>maximum</em>, <em>ceiling</em>, and <em>floor</em> methods take
* logarithmic time.
* <p>
* For additional documentation, see <a href="/algs4/45applications">Section 4.5</a> of
* <i>Algorithms in Java, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*/
public class SET<Key extends Comparable<Key>> implements Iterable<Key> {
private TreeSet<Key> set;
/**
* Create an empty set.
*/
public SET() {
set = new TreeSet<Key>();
}
/**
* Is this set empty?
*/
public boolean isEmpty() {
return set.isEmpty();
}
/**
* Add the key to this set.
*/
public void add(Key key) {
set.add(key);
}
/**
* Does this set contain the given key?
*/
public boolean contains(Key key) {
return set.contains(key);
}
/**
* Delete the given key from this set.
*/
public void delete(Key key) {
set.remove(key);
}
/**
* Return the number of keys in this set.
*/
public int size() {
return set.size();
}
/**
* Return an Iterator for this set.
*/
public Iterator<Key> iterator() {
return set.iterator();
}
/**
* Return the key in this set with the maximum value.
*/
public Key max() {
return set.last();
}
/**
* Return the key in this set with the minimum value.
*/
public Key min() {
return set.first();
}
/**
* Return the smallest key in this set >= k.
*/
public Key ceil(Key k) {
SortedSet<Key> tail = set.tailSet(k);
if (tail.isEmpty()) return null;
else return tail.first();
}
/**
* Return the largest key in this set <= k.
*/
public Key floor(Key k) {
if (set.contains(k)) return k;
// does not include key if present (!)
SortedSet<Key> head = set.headSet(k);
if (head.isEmpty()) return null;
else return head.last();
}
/**
* Return the union of this set with that set.
*/
public SET<Key> union(SET<Key> that) {
SET<Key> c = new SET<Key>();
for (Key x : this) { c.add(x); }
for (Key x : that) { c.add(x); }
return c;
}
/**
* Return the intersection of this set with that set.
*/
public SET<Key> intersects(SET<Key> that) {
SET<Key> c = new SET<Key>();
if (this.size() < that.size()) {
for (Key x : this) {
if (that.contains(x)) c.add(x);
}
}
else {
for (Key x : that) {
if (this.contains(x)) c.add(x);
}
}
return c;
}
/**
* Does this SET equal that set.
*/
public boolean equals(Object y) {
if (y == this) return true;
if (y == null) return false;
if (y.getClass() != this.getClass()) return false;
SET<Key> that = (SET<Key>) y;
if (this.size() != that.size()) return false;
try {
for (Key k : this)
if (!that.contains(k)) return false;
}
catch (ClassCastException exception) {
return false;
}
return true;
}
/***********************************************************************
* Test routine.
**********************************************************************/
public static void main(String[] args) {
SET<String> set = new SET<String>();
// insert some keys
set.add("www.cs.princeton.edu");
set.add("www.cs.princeton.edu"); // overwrite old value
set.add("www.princeton.edu");
set.add("www.math.princeton.edu");
set.add("www.yale.edu");
set.add("www.amazon.com");
set.add("www.simpsons.com");
set.add("www.stanford.edu");
set.add("www.google.com");
set.add("www.ibm.com");
set.add("www.apple.com");
set.add("www.slashdot.com");
set.add("www.whitehouse.gov");
set.add("www.espn.com");
set.add("www.snopes.com");
set.add("www.movies.com");
set.add("www.cnn.com");
set.add("www.iitb.ac.in");
StdOut.println(set.contains("www.cs.princeton.edu"));
StdOut.println(!set.contains("www.harvardsucks.com"));
StdOut.println(set.contains("www.simpsons.com"));
StdOut.println();
StdOut.println("ceil(www.simpsonr.com) = " + set.ceil("www.simpsonr.com"));
StdOut.println("ceil(www.simpsons.com) = " + set.ceil("www.simpsons.com"));
StdOut.println("ceil(www.simpsont.com) = " + set.ceil("www.simpsont.com"));
StdOut.println("floor(www.simpsonr.com) = " + set.floor("www.simpsonr.com"));
StdOut.println("floor(www.simpsons.com) = " + set.floor("www.simpsons.com"));
StdOut.println("floor(www.simpsont.com) = " + set.floor("www.simpsont.com"));
StdOut.println();
// print out all keys in the set in lexicographic order
for (String s : set) {
StdOut.println(s);
}
}
}
| cowthan/JavaAyo | src/com/cowthan/algrithm/algs4/SET.java | Java | apache-2.0 | 6,494 |
package com.alkaid.pearlharbor.net;
import java.util.HashMap;
import com.alkaid.pearlharbor.net.packethandler.HelloPacketHandler;
import com.alkaid.pearlharbor.net.packethandler.LoginPacketHandler;
import com.alkaid.pearlharbor.net.packethandler.PingPacketHandler;
import com.alkaid.pearlharbor.util.LifeCycle;
public class PacketHandlerManager implements LifeCycle{
private HashMap<Integer, IPacketHandler> mHandlerMap = null;
public PacketHandlerManager()
{
mHandlerMap = new HashMap<Integer, IPacketHandler>();
}
@Override
public boolean init() {
// TODO Auto-generated method stub
registerHandler(new HelloPacketHandler());
registerHandler(new LoginPacketHandler());
registerHandler(new PingPacketHandler());
return true;
}
@Override
public void tick() {
// TODO Auto-generated method stub
}
@Override
public void destroy() {
// TODO Auto-generated method stub
mHandlerMap.clear();
}
private void registerHandler(IPacketHandler handler)
{
mHandlerMap.put(handler.getType(), handler);
}
public boolean handle(Token token, int type, byte[] data)
{
IPacketHandler packetHandler = mHandlerMap.get(type);
boolean ret = false;
if (packetHandler != null)
{
ret = packetHandler.handle(token, data);
}
return ret;
}
}
| AlkaidFang/PearlHarbor | src/com/alkaid/pearlharbor/net/PacketHandlerManager.java | Java | apache-2.0 | 1,374 |
/* Copyright 2016 Esteve Fernandez <[email protected]>
* Copyright 2016-2017 Mickael Gaillard <[email protected]>
*
* 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.ros2.rcljava.exception;
/**
* Raised when an invalid RCLJAVAImplementation is requested.
*
*/
public class InvalidRCLJAVAImplementation extends RuntimeException {
/** Serial ID */
private static final long serialVersionUID = -7328914635553812875L;
/**
* Constructor.
*
* @param cause
*/
public InvalidRCLJAVAImplementation(Throwable cause) {
super("requested invalid rmw implementation", cause);
}
}
| Theosakamg/ros2_java | rcljava/src/main/java/org/ros2/rcljava/exception/InvalidRCLJAVAImplementation.java | Java | apache-2.0 | 1,150 |
package com.mine.junit;
import java.util.List;
import java.util.Map;
/**
* Created by Administrator on 2017/7/15.
*/
public class IBaseDao {
public void insert(String sql, Object[] objs) {
}
public List<Map<String,Object>> queryForList(String sql1, Object[] objs) {
return null;
}
}
| luoyedaren/show-me-the-code | showmecode/src/main/java/com/mine/junit/IBaseDao.java | Java | apache-2.0 | 312 |
/*
* Trident - A Multithreaded Server Alternative
* Copyright 2017 The TridentSDK 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 net.tridentsdk.server.packet.play;
import io.netty.buffer.ByteBuf;
import net.tridentsdk.server.net.NetClient;
import net.tridentsdk.server.net.NetData;
import net.tridentsdk.server.packet.PacketIn;
import net.tridentsdk.server.player.TridentPlayer;
/**
* @author TridentSDK
* @since 0.5-alpha
*/
public class PlayInEntityAction extends PacketIn {
public PlayInEntityAction() {
super(PlayInEntityAction.class);
}
@Override
public void read(ByteBuf buf, NetClient client) {
int entityId = NetData.rvint(buf);
int actionId = NetData.rvint(buf);
int jumpBoost = NetData.rvint(buf);
TridentPlayer player = client.getPlayer();
switch (actionId) {
case 0: // start crouching
player.setCrouching(true);
break;
case 1: // stop crouching
player.setCrouching(false);
break;
case 2: // leave bed
// TODO
break;
case 3: // start sprinting
player.setSprinting(true);
break;
case 4: // stop sprinting
player.setSprinting(false);
break;
case 5: // start jump w/ horse
// TODO
break;
case 6: // stop jump w/ horse
// TODO
break;
case 7: // open horse inventory
// TODO
break;
case 8: // start flying w/ elytra
// TODO
break;
default:
break;
}
player.updateMetadata();
}
}
| TridentSDK/Trident | src/main/java/net/tridentsdk/server/packet/play/PlayInEntityAction.java | Java | apache-2.0 | 2,332 |
package org._24601.kasper.parser;
public enum NodeType {
UNDEFINED, STATEMENT, ASSIGNMENT, LITERAL, LIST, STATEMENT_BLOCK
}
| JEBailey/kasper | kasper/core/src/main/java/org/_24601/kasper/parser/NodeType.java | Java | apache-2.0 | 131 |
/*
* Copyright (c) 2017-present, CV4J Contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cv4j.core.datamodel;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import javax.imageio.ImageIO;
import com.cv4j.exception.CV4JException;
public class CV4JImage implements ImageData, Serializable{
private static final long serialVersionUID = -8832812623741546452L;
private int width;
private int height;
private ImageProcessor processor;
private BufferedImage bitmap;
public CV4JImage(ImageProcessor processor) {
if(processor == null) {
throw new CV4JException("processor is null");
}
width = processor.getWidth();
height = processor.getHeight();
this.processor = processor;
if(processor instanceof ColorProcessor) {
((ColorProcessor)processor).setCallBack(this);
} else {
((ByteProcessor)processor).setCallBack(this);
}
}
public CV4JImage(BufferedImage bitmap) {
if (bitmap == null) {
throw new CV4JException("bitmap is null");
}
width = bitmap.getWidth();
height = bitmap.getHeight();
int[] input = new int[width * height];
getRGB(bitmap, 0, 0, width, height, input);
processor = new ColorProcessor(input,width, height);
((ColorProcessor)processor).setCallBack(this);
input = null;
}
public CV4JImage(byte[] bytes) {
if (bytes == null) {
throw new CV4JException("byte is null");
}
width = bitmap.getWidth();
height = bitmap.getHeight();
int[] input = new int[width * height];
getRGB(bitmap, 0, 0, width, height, input);
processor = new ColorProcessor(input,width, height);
((ColorProcessor)processor).setCallBack(this);
input = null;
}
public CV4JImage(int width,int height) {
this.width = width;
this.height = height;
processor = new ByteProcessor(new byte[width*height],width,height);
((ByteProcessor)processor).setCallBack(this);
}
public CV4JImage(int width, int height, int[] pixels) {
this.width = width;
this.height = height;
processor = new ColorProcessor(pixels,width, height);
((ColorProcessor)processor).setCallBack(this);
pixels = null;
}
@Override
public CV4JImage convert2Gray() {
if(processor instanceof ColorProcessor) {
byte[] gray = new byte[width * height];
int tr=0, tg=0, tb=0, c=0;
byte[] R = ((ColorProcessor) processor).getRed();
byte[] G = ((ColorProcessor) processor).getGreen();
byte[] B = ((ColorProcessor) processor).getBlue();
for (int i=0; i<gray.length; i++) {
tr = R[i] & 0xff;
tg = G[i] & 0xff;
tb = B[i] & 0xff;
c = (int) (0.299 * tr + 0.587 * tg + 0.114 * tb);
gray[i] = (byte) c;
}
processor = new ByteProcessor(gray, width, height);
((ByteProcessor)processor).setCallBack(this);
}
return this;
}
@Override
public BufferedImage toBitmap() {
int[] pixels = new int[width * height];
if(bitmap == null) { // suitable with JPG/PNG
bitmap = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
}
setRGB(width, height, pixels, processor.toByte(0), processor.toByte(1), processor.toByte(2));
setRGB(bitmap, 0, 0, width, height, pixels );
return bitmap;
}
@Override
public void setBitmap(BufferedImage bitmap) {
width = bitmap.getWidth();
height = bitmap.getHeight();
int[] input = new int[width * height];
getRGB(bitmap, 0, 0, width, height, input);
processor = new ColorProcessor(input,width, height);
((ColorProcessor)processor).setCallBack(this);
input = null;
}
public void resetBitmap() {
this.bitmap = null;
}
/**
* 保存图片到指定路径
* @param bitmap
* @param path
*/
public void savePic(BufferedImage bitmap, String path) {
File file = new File(path);
try {
FileOutputStream out = new FileOutputStream(file);
ImageIO.write(bitmap, "png", out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* A convenience method for getting ARGB pixels from an image. This tries to avoid the performance
* penalty of BufferedImage.getRGB unmanaging the image.
*/
public static int[] getRGB( BufferedImage image, int x, int y, int width, int height, int[] pixels ) {
int type = image.getType();
if ( type == BufferedImage.TYPE_INT_ARGB || type == BufferedImage.TYPE_INT_RGB )
return (int [])image.getRaster().getDataElements( x, y, width, height, pixels );
return image.getRGB( x, y, width, height, pixels, 0, width );
}
/**
* A convenience method for setting ARGB pixels in an image. This tries to avoid the performance
* penalty of BufferedImage.setRGB unmanaging the image.
*/
public static void setRGB( BufferedImage image, int x, int y, int width, int height, int[] pixels ) {
int type = image.getType();
if ( type == BufferedImage.TYPE_INT_ARGB || type == BufferedImage.TYPE_INT_RGB )
image.getRaster().setDataElements( x, y, width, height, pixels );
else
image.setRGB( x, y, width, height, pixels, 0, width );
}
public void setRGB(int width, int height, int[] pixels, byte[] R, byte[] G, byte[] B) {
for (int i=0; i < width*height; i++)
pixels[i] = 0xff000000 | ((R[i]&0xff)<<16) | ((G[i]&0xff)<<8) | B[i]&0xff;
}
/**
* 释放资源
*/
public void recycle() {
processor = null;
bitmap = null;
}
@Override
public ImageProcessor getProcessor() {
return this.processor;
}
}
| imageprocessor/cv4j-desktop | desktop/src/main/java/com/cv4j/core/datamodel/CV4JImage.java | Java | apache-2.0 | 6,674 |
/*
* Copyright 2015 Olivier Grégoire.
*
* 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 be.fror.password.vault.io;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
/**
*
* @author Olivier Grégoire
*/
public class IoModule extends AbstractModule {
@Override
protected void configure() {
}
@Provides
@Singleton
Serialization provideSerialization() {
return new GsonSerialization();
}
}
| ogregoire/password-tools | password-vault/src/main/java/be/fror/password/vault/io/IoModule.java | Java | apache-2.0 | 998 |
package com.lingju.assistant.activity.index.view;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.lingju.assistant.AppConfig;
import com.lingju.assistant.R;
import com.lingju.assistant.activity.MainActivity;
import com.lingju.assistant.activity.event.RecordUpdateEvent;
import com.lingju.assistant.activity.index.IGuide;
import com.lingju.assistant.player.audio.LingjuAudioPlayer;
import com.lingju.assistant.service.VoiceMediator;
import com.lingju.audio.engine.IflyRecognizer;
import com.lingju.model.PlayMusic;
import org.greenrobot.eventbus.EventBus;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by Ken on 2017/3/21.
*/
public class GuideFragment extends Fragment implements IGuide.IGuideView, View.OnClickListener {
public final static String SHOWED_RESP_GUIDE = "showed_resp_guide";
public final static String SHOWED_MUSIC_GUIDE = "showed_music_guide";
public final static String SHOWED_MENU_GUIDE = "showed_menu_guide";
public final static String SHOWED_SPEAK_TIPS_GUIDE = "showed_speak_tips_guide";
public final static String SHOW_TYPE = "show_type";
public final static String SHOW_TEXT = "show_text";
public final static int RESP_GUIDE = 0;
public final static int MUSIC_GUIDE = 1;
public final static int MENU_GUIDE = 2;
public final static int SPEAK_TIPS_GUIDE = 3;
@BindView(R.id.menu_guide_box)
RelativeLayout mMenuGuideBox;
@BindView(R.id.resp_guide)
LinearLayout mRespGuide;
@BindView(R.id.resp_guide_text)
TextView mRespGuideText;
@BindView(R.id.music_name)
TextView mMusicName;
@BindView(R.id.music_author)
TextView mMusicAuthor;
@BindView(R.id.music_guide_box)
LinearLayout mMusicGuideBox;
// @BindView(R.id.resp_text)
// TextView mRespText;
// @BindView(R.id.resp_guide_box)
// LinearLayout mRespGuideBox;
@BindView(R.id.tips_text)
TextView mTipsText;
@BindView(R.id.tips_guide_box)
LinearLayout mTipsGuideBox;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View contentView = inflater.inflate(R.layout.frag_guide, container, false);
ButterKnife.bind(this, contentView);
contentView.setOnClickListener(this);
setGuideView();
return contentView;
}
@Override
public void onHiddenChanged(boolean hidden) {
if (!hidden) { //fragment重新显示时触发
setGuideView();
}
super.onHiddenChanged(hidden);
}
@Override
public void onClick(View v) {
disppear();
}
@Override
public void setGuideView() {
Bundle arguments = getArguments();
if (arguments != null) {
String key = null;
int type = arguments.getInt(SHOW_TYPE, -1);
mMenuGuideBox.setVisibility(View.GONE);
// mRespGuideBox.setVisibility(View.GONE);
mMusicGuideBox.setVisibility(View.GONE);
mTipsGuideBox.setVisibility(View.GONE);
switch (type) {
// case RESP_GUIDE:
// mRespGuideBox.setVisibility(View.VISIBLE);
// mRespText.setText(arguments.getString(SHOW_TEXT));
// int guideTextMargin = ((MainActivity) getActivity()).getGuideTextMargin(RESP_GUIDE);
// ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) mRespGuideBox.getLayoutParams();
// layoutParams.topMargin = guideTextMargin;
// key = SHOWED_RESP_GUIDE;
// break;
case MUSIC_GUIDE:
//话筒波纹效果不展示
AppConfig.dPreferences.edit().putBoolean("wave_show",false).commit();
mMusicGuideBox.setVisibility(View.VISIBLE);
PlayMusic music = LingjuAudioPlayer.get().currentPlayMusic();
mMusicAuthor.setText(music.getSinger());
mMusicName.setText(music.getTitle());
key = SHOWED_MUSIC_GUIDE;
break;
case MENU_GUIDE:
mMenuGuideBox.setVisibility(View.VISIBLE);
mRespGuideText.setText(getResources().getString(R.string.first_welcome));
int textMargin = ((MainActivity) getActivity()).getGuideTextMargin(MENU_GUIDE);
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) mRespGuide.getLayoutParams();
params.topMargin = textMargin;
key = SHOWED_MENU_GUIDE;
break;
case SPEAK_TIPS_GUIDE:
//话筒波纹效果不展示
AppConfig.dPreferences.edit().putBoolean("wave_show",false).commit();
mTipsGuideBox.setVisibility(View.VISIBLE);
mTipsText.setText(arguments.getString(SHOW_TEXT));
ViewGroup.MarginLayoutParams tipsLayoutParams = (ViewGroup.MarginLayoutParams) mTipsGuideBox.getLayoutParams();
tipsLayoutParams.bottomMargin = ((MainActivity) getActivity()).getGuideTextMargin(SPEAK_TIPS_GUIDE);
key = SHOWED_SPEAK_TIPS_GUIDE;
break;
}
AppConfig.dPreferences.edit().putBoolean(key, true).commit();
}
}
@Override
public void disppear() {
getFragmentManager().beginTransaction().hide(this).commit();
//话筒波纹效果展示
AppConfig.dPreferences.edit().putBoolean("wave_show",true).commit();
//键盘输入界面切换为话筒界面如果正在识别时打开波纹效果
if(IflyRecognizer.getInstance().isRecognizing()){
EventBus.getDefault().post(new RecordUpdateEvent(RecordUpdateEvent.RECORDING));
}
}
}
| LingjuAI/AssistantBySDK | app/src/main/java/com/lingju/assistant/activity/index/view/GuideFragment.java | Java | apache-2.0 | 6,198 |
/*
* Copyright (C) 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.ftcresearch.tfod;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.google.ftcresearch.tfod.test", appContext.getPackageName());
}
}
| google/ftc-object-detection | TFObjectDetector/tfod/src/androidTest/java/com/google/ftcresearch/tfod/ExampleInstrumentedTest.java | Java | apache-2.0 | 1,307 |
package vkaretko;
import vkaretko.interfaces.Add;
import vkaretko.interfaces.Get;
import vkaretko.interfaces.MenuItems;
import vkaretko.menuitems.File;
import vkaretko.menuitems.FileOpen;
import vkaretko.menuitems.Project;
import vkaretko.menuitems.New;
import vkaretko.menuitems.Help;
import vkaretko.menuitems.HelpAbout;
import java.util.ArrayList;
import java.util.List;
/**
* Class ConsoleMenu for filling list of menu items and print them in console.
*
* @author Karetko Victor
* @version 1.00
* @since 07.12.2016
*/
public class ConsoleMenu implements Add, Get {
/**
* List of base menu items.
*/
private ArrayList<MenuItems> menu = new ArrayList<>();
/**
* Method fills list of menu with items.
*/
public void init() {
File file = new File();
New fileNew = new New();
Help help = new Help();
file.addMenuItem(fileNew);
file.addMenuItem(new FileOpen());
fileNew.addMenuItem(new Project());
help.addMenuItem(new HelpAbout());
menu.add(file);
menu.add(help);
printMenu(this.menu);
}
/**
* Method for printing menu to console.
* @param menu list of menu items to print.
*/
public void printMenu(List<MenuItems> menu) {
for (MenuItems item : menu) {
System.out.println(String.format("%s%s", printDashes(item.getLevel()), item.getInfo()));
if (item.getMenuItems() != null) {
printMenu(item.getMenuItems());
}
}
}
/**
* Method for printing double dashes before text.
* @param amountOfDashes amount of double dashes.
* @return string with dashes.
*/
private String printDashes(int amountOfDashes) {
StringBuilder sb = new StringBuilder();
for (int dashes = 0; dashes < amountOfDashes; dashes++) {
sb.append("--");
}
return sb.toString();
}
/**
* Method for adding menu items.
* @param item item to add.
*/
@Override
public void addMenuItem(MenuItems item) {
this.menu.add(item);
}
/**
* Getter-method for menu items.
* @return menu
*/
@Override
public List<MenuItems> getMenuItems() {
return this.menu;
}
}
| V1toss/JavaPA | part_4/consolemenu/src/main/java/vkaretko/ConsoleMenu.java | Java | apache-2.0 | 2,289 |
/*
* Copyright 2017 Urs Fässler
* SPDX-License-Identifier: Apache-2.0
*/
package world.bilo.stack.internal;
import java.util.List;
import world.bilo.stack.BlockId;
public interface BlockStateListener {
public void blocks(List<BlockId> blocks);
}
| bloctesian/blockstack | src/world/bilo/stack/internal/BlockStateListener.java | Java | apache-2.0 | 256 |
/*
* Copyright 2017 Daniel Nilsson
*
* 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.dannil.scbjavaclient.client.educationandresearch.communityinnovationsurvey.cooperation;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.github.dannil.scbjavaclient.test.extensions.Date;
import com.github.dannil.scbjavaclient.test.extensions.Remote;
import com.github.dannil.scbjavaclient.test.extensions.Suite;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@Suite
@Remote
public class EducationAndResearchCommunityInnovationSurveyCooperationClientIT {
private EducationAndResearchCommunityInnovationSurveyCooperationClient client;
@BeforeEach
public void setup() {
this.client = new EducationAndResearchCommunityInnovationSurveyCooperationClient();
}
@Test
@Date("2017-07-11")
public void getNumberOfInnovativeEnterprises() {
assertNotEquals(0, this.client.getNumberOfInnovativeEnterprises().size());
}
@Test
@Date("2017-07-11")
public void getNumberOfInnovativeEnterprisesWithParametersEmptyLists() {
assertNotEquals(0,
this.client.getNumberOfInnovativeEnterprises(Collections.<String>emptyList(),
Collections.<String>emptyList(), Collections.<String>emptyList(),
Collections.<String>emptyList()).size());
}
@Test
@Date("2017-07-11")
public void getNumberOfInnovativeEnterprisesWithParameters() {
List<String> industrialClassifications = Arrays.asList("64-66", "71+72");
List<String> sizeClasses = Arrays.asList("10-49", "50-249");
List<String> typesOfValues = Arrays.asList("PS", "KI");
List<String> periods = Arrays.asList("2010-2012", "2012-2014");
assertNotEquals(0, this.client.getNumberOfInnovativeEnterprises(industrialClassifications, sizeClasses,
typesOfValues, periods).size());
}
}
| dannil/scb-api | src/test/java/com/github/dannil/scbjavaclient/client/educationandresearch/communityinnovationsurvey/cooperation/EducationAndResearchCommunityInnovationSurveyCooperationClientIT.java | Java | apache-2.0 | 2,557 |
/* Generated By:JJTree&JavaCC: Do not edit this line. C2BSVParserConstants.java */
package lcr.c2bsv.parser;
/**
* Token literal values and constants.
* Generated by org.javacc.parser.OtherFilesGen#start()
*/
public interface C2BSVParserConstants {
/** End of File. */
int EOF = 0;
/** RegularExpression Id. */
int INTEGER_LITERAL = 12;
/** RegularExpression Id. */
int DECIMAL_LITERAL = 13;
/** RegularExpression Id. */
int HEX_LITERAL = 14;
/** RegularExpression Id. */
int OCTAL_LITERAL = 15;
/** RegularExpression Id. */
int FLOATING_POINT_LITERAL = 16;
/** RegularExpression Id. */
int EXPONENT = 17;
/** RegularExpression Id. */
int STRING_LITERAL = 18;
/** RegularExpression Id. */
int RETURN = 19;
/** RegularExpression Id. */
int STRUCT = 20;
/** RegularExpression Id. */
int WHILE = 21;
/** RegularExpression Id. */
int FLOAT = 22;
/** RegularExpression Id. */
int ELSE = 23;
/** RegularExpression Id. */
int VOID = 24;
/** RegularExpression Id. */
int INT = 25;
/** RegularExpression Id. */
int IF = 26;
/** RegularExpression Id. */
int IDENTIFIER = 27;
/** RegularExpression Id. */
int LETTER = 28;
/** RegularExpression Id. */
int DIGIT = 29;
/** RegularExpression Id. */
int SEMICOLON = 30;
/** Lexical state. */
int DEFAULT = 0;
/** Lexical state. */
int PREPROCESSOR_OUTPUT = 1;
/** Literal token values. */
String[] tokenImage = {
"<EOF>",
"\" \"",
"\"\\t\"",
"\"\\n\"",
"\"\\r\"",
"<token of kind 5>",
"<token of kind 6>",
"\"#\"",
"\"\\n\"",
"\"\\\\\\n\"",
"\"\\\\\\r\\n\"",
"<token of kind 11>",
"<INTEGER_LITERAL>",
"<DECIMAL_LITERAL>",
"<HEX_LITERAL>",
"<OCTAL_LITERAL>",
"<FLOATING_POINT_LITERAL>",
"<EXPONENT>",
"<STRING_LITERAL>",
"\"return\"",
"\"struct\"",
"\"while\"",
"\"float\"",
"\"else\"",
"\"void\"",
"\"int\"",
"\"if\"",
"<IDENTIFIER>",
"<LETTER>",
"<DIGIT>",
"\";\"",
"\"{\"",
"\"}\"",
"\",\"",
"\"=\"",
"\":\"",
"\"(\"",
"\")\"",
"\"[\"",
"\"]\"",
"\"...\"",
"\"*=\"",
"\"/=\"",
"\"%=\"",
"\"+=\"",
"\"-=\"",
"\"<<=\"",
"\">>=\"",
"\"&=\"",
"\"^=\"",
"\"|=\"",
"\"?\"",
"\"||\"",
"\"&&\"",
"\"|\"",
"\"^\"",
"\"&\"",
"\"==\"",
"\"!=\"",
"\"<\"",
"\">\"",
"\"<=\"",
"\">=\"",
"\"<<\"",
"\">>\"",
"\"+\"",
"\"-\"",
"\"*\"",
"\"/\"",
"\"%\"",
"\"++\"",
"\"--\"",
"\"~\"",
"\"!\"",
"\".\"",
};
}
| sergiodurand/Cparser | src/lcr/c2bsv/parser/C2BSVParserConstants.java | Java | apache-2.0 | 2,631 |
package com.bookmarking.bookmark.framework;
import java.util.*;
import com.bookmarking.bookmark.*;
import com.bookmarking.desktop.*;
import com.bookmarking.search.*;
import javafx.geometry.*;
import javafx.scene.control.*;
import javafx.scene.input.*;
import javafx.scene.layout.*;
/**
* The view the main bookmarks list will show
*/
public abstract class AbstractBookmarkListItemView extends VBox
{
private AbstractBookmark abstractBookmark;
private Map<String, Pane> enabledTags;
private Map<String, Pane> disabledTags;
private List<String> tagList;
private FlowPane tagsFlowPane;
public AbstractBookmarkListItemView()
{
super();
initUI();
initTagsPanel();
}
public AbstractBookmarkListItemView(AbstractBookmark abstractBookmark)
{
super();
Objects.requireNonNull(abstractBookmark);
this.abstractBookmark = abstractBookmark;
initUI();
initTagsPanel();
}
private void initTagsPanel()
{
this.setMinSize(100, 50);
this.setPrefHeight(100);
this.setStyle("-fx-border-color: blue");
this.tagList = new ArrayList<>();
enabledTags = new HashMap<>();
disabledTags = new HashMap<>();
tagsFlowPane = new FlowPane();
tagsFlowPane.setVgap(5);
tagsFlowPane.setHgap(10);
this.getChildren().add(tagsFlowPane);
refresh();
}
public AbstractBookmark getBookmark()
{
return abstractBookmark;
}
public void setBookmark(AbstractBookmark abstractBookmark)
{
this.abstractBookmark = abstractBookmark;
this.getChildren().clear();
this.enabledTags.clear();
this.disabledTags.clear();
initUI();
initTagsPanel();
}
public void refresh()
{
this.tagsFlowPane.getChildren().clear();
this.tagList.clear();
if (getBookmark() != null)
{
this.tagList.addAll(getBookmark().getTags());
Collections.sort(this.tagList);
for (String s : this.tagList)
{
if (SearchUIController.use().getSearchOptions().getTagsPresent().contains(s))
{
Pane pane = disabledTags.get(s);
if (pane == null)
{
pane = getTagPanel(s, true);
disabledTags.put(s, pane);
}
tagsFlowPane.getChildren().add(pane);
}
else
{
Pane pane = enabledTags.get(s);
if (pane == null)
{
pane = getTagPanel(s, false);
enabledTags.put(s, pane);
}
tagsFlowPane.getChildren().add(pane);
}
}
}
}
public Class getBookmarkClass()
{
return TextBookmark.class;
}
private void applyTagAction(String tag, Operation.TagOptions tagOption)
{
SearchOptions searchOptions = SearchUIController.use().getSearchOptions();
Operation lastOperation = searchOptions.lastOperation();
if (lastOperation == null || lastOperation.getOperation() != tagOption)
{
searchOptions.add(tagOption, tag);
}
else
{
Operation operation = lastOperation;
operation.getTags().add(tag);
}
MainUIController.use().refresh();
}
protected abstract void initUI();
private Pane getTagPanel(String text, boolean disabled)
{
HBox tmp = new HBox();
VBox.setVgrow(tmp, Priority.ALWAYS);
tmp.setAlignment(Pos.BOTTOM_LEFT);
HBox wrapper = null;
tmp.setSpacing(3);
if (disabled)
{
wrapper = new HBox();
tmp.setDisable(true);
wrapper.getChildren().add(tmp);
wrapper.addEventFilter(MouseEvent.MOUSE_CLICKED, event ->
{
SearchUIController.use().getSearchOptions().removeAll(text);
MainUIController.use().refresh();
event.consume();
});
}
tmp.setStyle("-fx-border-color:black;-fx-border-radius:3px;-fx-padding:3");
tmp.setOnMouseClicked(e ->
{
applyTagAction(text, Operation.TagOptions.ALL_TAGS);
e.consume();
});
HBox vb = new HBox();
Label label1 = new Label(text);
label1.setOnMouseClicked(e ->
{
applyTagAction(text, Operation.TagOptions.ALL_TAGS);
e.consume();
});
Separator separator = new Separator();
separator.setOrientation(Orientation.VERTICAL);
Button any = new Button("OR");
any.setStyle("-fx-font-size:7;-fx-border-radius:3px 0px 0px 3px;-fx-background-radius: 3px 0px 0px 3px;");
any.setOnAction(e ->
{
applyTagAction(text, Operation.TagOptions.ANY_TAG);
});
Button none = new Button("\uf05e");
none.setStyle("-fx-font-size:7;-fx-border-radius:0px 3px 3px 0px;-fx-background-radius: 0px 3px 3px 0px;");
none.setOnAction(e ->
{
applyTagAction(text, Operation.TagOptions.WITHOUT_TAGS);
});
vb.getChildren().addAll(any, none);
tmp.getChildren().addAll(vb, separator, label1);
if (tmp.isDisable())
{
return wrapper;
}
else
{
return tmp;
}
}
}
| flightx31/Bookmarkanator-Desktop | src/main/java/com/bookmarking/bookmark/framework/AbstractBookmarkListItemView.java | Java | apache-2.0 | 5,608 |
/*
* Copyright 2001-2009 Terracotta, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.quartz;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import org.junit.Test;
import org.quartz.DateBuilder.IntervalUnit;
import org.quartz.impl.calendar.BaseCalendar;
import org.quartz.impl.triggers.CalendarIntervalTriggerImpl;
/**
* Unit tests for DateIntervalTrigger.
*/
public class CalendarIntervalTriggerTest extends SerializationTestSupport {
private static final String[] VERSIONS = new String[] {"2.0"};
@Test
public void testQTZ331FireTimeAfterBoundary() {
Calendar start = Calendar.getInstance();
start.clear();
start.set(2013, Calendar.FEBRUARY, 15);
Date startTime = start.getTime();
start.add(Calendar.DAY_OF_MONTH, 1);
Date triggerTime = start.getTime();
CalendarIntervalTriggerImpl trigger = new CalendarIntervalTriggerImpl("test", startTime, null, IntervalUnit.DAY, 1);
assertThat(trigger.getFireTimeAfter(startTime), equalTo(triggerTime));
Date after = new Date(start.getTimeInMillis() - 500);
assertThat(trigger.getFireTimeAfter(after), equalTo(triggerTime));
}
public void testQTZ330DaylightSavingsCornerCase() {
TimeZone edt = TimeZone.getTimeZone("America/New_York");
Calendar start = Calendar.getInstance();
start.clear();
start.setTimeZone(edt);
start.set(2012, Calendar.MARCH, 16, 2, 30, 0);
Calendar after = Calendar.getInstance();
after.clear();
after.setTimeZone(edt);
after.set(2013, Calendar.APRIL, 19, 2, 30, 0);
BaseCalendar baseCalendar = new BaseCalendar(edt);
CalendarIntervalTriggerImpl intervalTrigger = new CalendarIntervalTriggerImpl("QTZ-330", start.getTime(), null, DateBuilder.IntervalUnit.DAY, 1);
intervalTrigger.setTimeZone(edt);
intervalTrigger.setPreserveHourOfDayAcrossDaylightSavings(true);
intervalTrigger.computeFirstFireTime(baseCalendar);
Date fireTime = intervalTrigger.getFireTimeAfter(after.getTime());
assertThat(fireTime.after(after.getTime()), is(true));
}
public void testYearlyIntervalGetFireTimeAfter() {
Calendar startCalendar = Calendar.getInstance();
startCalendar.set(2005, Calendar.JUNE, 1, 9, 30, 17);
startCalendar.clear(Calendar.MILLISECOND);
CalendarIntervalTriggerImpl yearlyTrigger = new CalendarIntervalTriggerImpl();
yearlyTrigger.setStartTime(startCalendar.getTime());
yearlyTrigger.setRepeatIntervalUnit(DateBuilder.IntervalUnit.YEAR);
yearlyTrigger.setRepeatInterval(2); // every two years;
Calendar targetCalendar = Calendar.getInstance();
targetCalendar.set(2009, Calendar.JUNE, 1, 9, 30, 17); // jump 4 years (2 intervals)
targetCalendar.clear(Calendar.MILLISECOND);
List<Date> fireTimes = TriggerUtils.computeFireTimes(yearlyTrigger, null, 4);
Date secondTime = fireTimes.get(2); // get the third fire time
assertEquals("Year increment result not as expected.", targetCalendar.getTime(), secondTime);
}
public void testMonthlyIntervalGetFireTimeAfter() {
Calendar startCalendar = Calendar.getInstance();
startCalendar.set(2005, Calendar.JUNE, 1, 9, 30, 17);
startCalendar.clear(Calendar.MILLISECOND);
CalendarIntervalTriggerImpl yearlyTrigger = new CalendarIntervalTriggerImpl();
yearlyTrigger.setStartTime(startCalendar.getTime());
yearlyTrigger.setRepeatIntervalUnit(DateBuilder.IntervalUnit.MONTH);
yearlyTrigger.setRepeatInterval(5); // every five months
Calendar targetCalendar = Calendar.getInstance();
targetCalendar.set(2005, Calendar.JUNE, 1, 9, 30, 17);
targetCalendar.setLenient(true);
targetCalendar.add(Calendar.MONTH, 25); // jump 25 five months (5 intervals)
targetCalendar.clear(Calendar.MILLISECOND);
List<Date> fireTimes = TriggerUtils.computeFireTimes(yearlyTrigger, null, 6);
Date fifthTime = fireTimes.get(5); // get the sixth fire time
assertEquals("Month increment result not as expected.", targetCalendar.getTime(), fifthTime);
}
public void testWeeklyIntervalGetFireTimeAfter() {
Calendar startCalendar = Calendar.getInstance();
startCalendar.set(2005, Calendar.JUNE, 1, 9, 30, 17);
startCalendar.clear(Calendar.MILLISECOND);
CalendarIntervalTriggerImpl yearlyTrigger = new CalendarIntervalTriggerImpl();
yearlyTrigger.setStartTime(startCalendar.getTime());
yearlyTrigger.setRepeatIntervalUnit(DateBuilder.IntervalUnit.WEEK);
yearlyTrigger.setRepeatInterval(6); // every six weeks
Calendar targetCalendar = Calendar.getInstance();
targetCalendar.set(2005, Calendar.JUNE, 1, 9, 30, 17);
targetCalendar.setLenient(true);
targetCalendar.add(Calendar.DAY_OF_YEAR, 7 * 6 * 4); // jump 24 weeks (4 intervals)
targetCalendar.clear(Calendar.MILLISECOND);
List<Date> fireTimes = TriggerUtils.computeFireTimes(yearlyTrigger, null, 7);
Date fifthTime = fireTimes.get(4); // get the fifth fire time
assertEquals("Week increment result not as expected.", targetCalendar.getTime(), fifthTime);
}
public void testDailyIntervalGetFireTimeAfter() {
Calendar startCalendar = Calendar.getInstance();
startCalendar.set(2005, Calendar.JUNE, 1, 9, 30, 17);
startCalendar.clear(Calendar.MILLISECOND);
CalendarIntervalTriggerImpl dailyTrigger = new CalendarIntervalTriggerImpl();
dailyTrigger.setStartTime(startCalendar.getTime());
dailyTrigger.setRepeatIntervalUnit(DateBuilder.IntervalUnit.DAY);
dailyTrigger.setRepeatInterval(90); // every ninety days
Calendar targetCalendar = Calendar.getInstance();
targetCalendar.set(2005, Calendar.JUNE, 1, 9, 30, 17);
targetCalendar.setLenient(true);
targetCalendar.add(Calendar.DAY_OF_YEAR, 360); // jump 360 days (4 intervals)
targetCalendar.clear(Calendar.MILLISECOND);
List<Date> fireTimes = TriggerUtils.computeFireTimes(dailyTrigger, null, 6);
Date fifthTime = fireTimes.get(4); // get the fifth fire time
assertEquals("Day increment result not as expected.", targetCalendar.getTime(), fifthTime);
}
public void testHourlyIntervalGetFireTimeAfter() {
Calendar startCalendar = Calendar.getInstance();
startCalendar.set(2005, Calendar.JUNE, 1, 9, 30, 17);
startCalendar.clear(Calendar.MILLISECOND);
CalendarIntervalTriggerImpl yearlyTrigger = new CalendarIntervalTriggerImpl();
yearlyTrigger.setStartTime(startCalendar.getTime());
yearlyTrigger.setRepeatIntervalUnit(DateBuilder.IntervalUnit.HOUR);
yearlyTrigger.setRepeatInterval(100); // every 100 hours
Calendar targetCalendar = Calendar.getInstance();
targetCalendar.set(2005, Calendar.JUNE, 1, 9, 30, 17);
targetCalendar.setLenient(true);
targetCalendar.add(Calendar.HOUR, 400); // jump 400 hours (4 intervals)
targetCalendar.clear(Calendar.MILLISECOND);
List<Date> fireTimes = TriggerUtils.computeFireTimes(yearlyTrigger, null, 6);
Date fifthTime = fireTimes.get(4); // get the fifth fire time
assertEquals("Hour increment result not as expected.", targetCalendar.getTime(), fifthTime);
}
public void testMinutelyIntervalGetFireTimeAfter() {
Calendar startCalendar = Calendar.getInstance();
startCalendar.set(2005, Calendar.JUNE, 1, 9, 30, 17);
startCalendar.clear(Calendar.MILLISECOND);
CalendarIntervalTriggerImpl yearlyTrigger = new CalendarIntervalTriggerImpl();
yearlyTrigger.setStartTime(startCalendar.getTime());
yearlyTrigger.setRepeatIntervalUnit(DateBuilder.IntervalUnit.MINUTE);
yearlyTrigger.setRepeatInterval(100); // every 100 minutes
Calendar targetCalendar = Calendar.getInstance();
targetCalendar.set(2005, Calendar.JUNE, 1, 9, 30, 17);
targetCalendar.setLenient(true);
targetCalendar.add(Calendar.MINUTE, 400); // jump 400 minutes (4 intervals)
targetCalendar.clear(Calendar.MILLISECOND);
List<Date> fireTimes = TriggerUtils.computeFireTimes(yearlyTrigger, null, 6);
Date fifthTime = fireTimes.get(4); // get the fifth fire time
assertEquals("Minutes increment result not as expected.", targetCalendar.getTime(), fifthTime);
}
public void testSecondlyIntervalGetFireTimeAfter() {
Calendar startCalendar = Calendar.getInstance();
startCalendar.set(2005, Calendar.JUNE, 1, 9, 30, 17);
startCalendar.clear(Calendar.MILLISECOND);
CalendarIntervalTriggerImpl yearlyTrigger = new CalendarIntervalTriggerImpl();
yearlyTrigger.setStartTime(startCalendar.getTime());
yearlyTrigger.setRepeatIntervalUnit(DateBuilder.IntervalUnit.SECOND);
yearlyTrigger.setRepeatInterval(100); // every 100 seconds
Calendar targetCalendar = Calendar.getInstance();
targetCalendar.set(2005, Calendar.JUNE, 1, 9, 30, 17);
targetCalendar.setLenient(true);
targetCalendar.add(Calendar.SECOND, 400); // jump 400 seconds (4 intervals)
targetCalendar.clear(Calendar.MILLISECOND);
List<Date> fireTimes = TriggerUtils.computeFireTimes(yearlyTrigger, null, 6);
Date fifthTime = fireTimes.get(4); // get the third fire time
assertEquals("Seconds increment result not as expected.", targetCalendar.getTime(), fifthTime);
}
public void testDaylightSavingsTransitions() {
// Pick a day before a spring daylight savings transition...
Calendar startCalendar = Calendar.getInstance();
startCalendar.set(2010, Calendar.MARCH, 12, 9, 30, 17);
startCalendar.clear(Calendar.MILLISECOND);
CalendarIntervalTriggerImpl dailyTrigger = new CalendarIntervalTriggerImpl();
dailyTrigger.setStartTime(startCalendar.getTime());
dailyTrigger.setRepeatIntervalUnit(DateBuilder.IntervalUnit.DAY);
dailyTrigger.setRepeatInterval(5); // every 5 days
Calendar targetCalendar = Calendar.getInstance();
targetCalendar.setTime(startCalendar.getTime());
targetCalendar.setLenient(true);
targetCalendar.add(Calendar.DAY_OF_YEAR, 10); // jump 10 days (2 intervals)
targetCalendar.clear(Calendar.MILLISECOND);
List<Date> fireTimes = TriggerUtils.computeFireTimes(dailyTrigger, null, 6);
Date testTime = fireTimes.get(2); // get the third fire time
assertEquals("Day increment result not as expected over spring 2010 daylight savings transition.", targetCalendar.getTime(), testTime);
// And again, Pick a day before a spring daylight savings transition... (QTZ-240)
startCalendar = Calendar.getInstance();
startCalendar.set(2011, Calendar.MARCH, 12, 1, 0, 0);
startCalendar.clear(Calendar.MILLISECOND);
dailyTrigger = new CalendarIntervalTriggerImpl();
dailyTrigger.setStartTime(startCalendar.getTime());
dailyTrigger.setRepeatIntervalUnit(DateBuilder.IntervalUnit.DAY);
dailyTrigger.setRepeatInterval(1); // every day
targetCalendar = Calendar.getInstance();
targetCalendar.setTime(startCalendar.getTime());
targetCalendar.setLenient(true);
targetCalendar.add(Calendar.DAY_OF_YEAR, 2); // jump 2 days (2 intervals)
targetCalendar.clear(Calendar.MILLISECOND);
fireTimes = TriggerUtils.computeFireTimes(dailyTrigger, null, 6);
testTime = fireTimes.get(2); // get the third fire time
assertEquals("Day increment result not as expected over spring 2011 daylight savings transition.", targetCalendar.getTime(), testTime);
// And again, Pick a day before a spring daylight savings transition... (QTZ-240) - and prove time of day is not preserved without setPreserveHourOfDayAcrossDaylightSavings(true)
startCalendar = Calendar.getInstance();
startCalendar.setTimeZone(TimeZone.getTimeZone("CET"));
startCalendar.set(2011, Calendar.MARCH, 26, 4, 0, 0);
startCalendar.clear(Calendar.MILLISECOND);
dailyTrigger = new CalendarIntervalTriggerImpl();
dailyTrigger.setStartTime(startCalendar.getTime());
dailyTrigger.setRepeatIntervalUnit(DateBuilder.IntervalUnit.DAY);
dailyTrigger.setRepeatInterval(1); // every day
dailyTrigger.setTimeZone(TimeZone.getTimeZone("EST"));
targetCalendar = Calendar.getInstance();
targetCalendar.setTimeZone(TimeZone.getTimeZone("CET"));
targetCalendar.setTime(startCalendar.getTime());
targetCalendar.setLenient(true);
targetCalendar.add(Calendar.DAY_OF_YEAR, 2); // jump 2 days (2 intervals)
targetCalendar.clear(Calendar.MILLISECOND);
fireTimes = TriggerUtils.computeFireTimes(dailyTrigger, null, 6);
testTime = fireTimes.get(2); // get the third fire time
Calendar testCal = Calendar.getInstance(TimeZone.getTimeZone("CET"));
testCal.setTimeInMillis(testTime.getTime());
assertFalse("Day increment time-of-day result not as expected over spring 2011 daylight savings transition.", targetCalendar.get(Calendar.HOUR_OF_DAY) == testCal.get(Calendar.HOUR_OF_DAY));
// And again, Pick a day before a spring daylight savings transition... (QTZ-240) - and prove time of day is preserved with setPreserveHourOfDayAcrossDaylightSavings(true)
startCalendar = Calendar.getInstance();
startCalendar.setTimeZone(TimeZone.getTimeZone("CET"));
startCalendar.set(2011, Calendar.MARCH, 26, 4, 0, 0);
startCalendar.clear(Calendar.MILLISECOND);
dailyTrigger = new CalendarIntervalTriggerImpl();
dailyTrigger.setStartTime(startCalendar.getTime());
dailyTrigger.setRepeatIntervalUnit(DateBuilder.IntervalUnit.DAY);
dailyTrigger.setRepeatInterval(1); // every day
dailyTrigger.setTimeZone(TimeZone.getTimeZone("CET"));
dailyTrigger.setPreserveHourOfDayAcrossDaylightSavings(true);
targetCalendar = Calendar.getInstance();
targetCalendar.setTimeZone(TimeZone.getTimeZone("CET"));
targetCalendar.setTime(startCalendar.getTime());
targetCalendar.setLenient(true);
targetCalendar.add(Calendar.DAY_OF_YEAR, 2); // jump 2 days (2 intervals)
targetCalendar.clear(Calendar.MILLISECOND);
fireTimes = TriggerUtils.computeFireTimes(dailyTrigger, null, 6);
testTime = fireTimes.get(2); // get the third fire time
testCal = Calendar.getInstance(TimeZone.getTimeZone("CET"));
testCal.setTimeInMillis(testTime.getTime());
assertTrue("Day increment time-of-day result not as expected over spring 2011 daylight savings transition.", targetCalendar.get(Calendar.HOUR_OF_DAY) == testCal.get(Calendar.HOUR_OF_DAY));
// Pick a day before a fall daylight savings transition...
startCalendar = Calendar.getInstance();
startCalendar.set(2010, Calendar.OCTOBER, 31, 9, 30, 17);
startCalendar.clear(Calendar.MILLISECOND);
dailyTrigger = new CalendarIntervalTriggerImpl();
dailyTrigger.setStartTime(startCalendar.getTime());
dailyTrigger.setRepeatIntervalUnit(DateBuilder.IntervalUnit.DAY);
dailyTrigger.setRepeatInterval(5); // every 5 days
targetCalendar = Calendar.getInstance();
targetCalendar.setTime(startCalendar.getTime());
targetCalendar.setLenient(true);
targetCalendar.add(Calendar.DAY_OF_YEAR, 15); // jump 15 days (3 intervals)
targetCalendar.clear(Calendar.MILLISECOND);
fireTimes = TriggerUtils.computeFireTimes(dailyTrigger, null, 6);
testTime = (Date) fireTimes.get(3); // get the fourth fire time
assertEquals("Day increment result not as expected over fall 2010 daylight savings transition.", targetCalendar.getTime(), testTime);
// And again, Pick a day before a fall daylight savings transition... (QTZ-240)
startCalendar = Calendar.getInstance();
startCalendar.setTimeZone(TimeZone.getTimeZone("CEST"));
startCalendar.set(2011, Calendar.OCTOBER, 29, 1, 30, 00);
startCalendar.clear(Calendar.MILLISECOND);
dailyTrigger = new CalendarIntervalTriggerImpl();
dailyTrigger.setStartTime(startCalendar.getTime());
dailyTrigger.setRepeatIntervalUnit(DateBuilder.IntervalUnit.DAY);
dailyTrigger.setRepeatInterval(1); // every day
dailyTrigger.setTimeZone(TimeZone.getTimeZone("EST"));
targetCalendar = Calendar.getInstance();
targetCalendar.setTimeZone(TimeZone.getTimeZone("CEST"));
targetCalendar.setTime(startCalendar.getTime());
targetCalendar.setLenient(true);
targetCalendar.add(Calendar.DAY_OF_YEAR, 3); // jump 3 days (3 intervals)
targetCalendar.clear(Calendar.MILLISECOND);
fireTimes = TriggerUtils.computeFireTimes(dailyTrigger, null, 6);
testTime = (Date) fireTimes.get(3); // get the fourth fire time
assertEquals("Day increment result not as expected over fall 2011 daylight savings transition.", targetCalendar.getTime(), testTime);
}
public void testFinalFireTimes() {
Calendar startCalendar = Calendar.getInstance();
startCalendar.set(2010, Calendar.MARCH, 12, 9, 0, 0);
startCalendar.clear(Calendar.MILLISECOND);
CalendarIntervalTriggerImpl dailyTrigger = new CalendarIntervalTriggerImpl();
dailyTrigger.setStartTime(startCalendar.getTime());
dailyTrigger.setRepeatIntervalUnit(DateBuilder.IntervalUnit.DAY);
dailyTrigger.setRepeatInterval(5); // every 5 days
Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(startCalendar.getTime());
endCalendar.setLenient(true);
endCalendar.add(Calendar.DAY_OF_YEAR, 10); // jump 10 days (2 intervals)
endCalendar.clear(Calendar.MILLISECOND);
dailyTrigger.setEndTime(endCalendar.getTime());
Date testTime = dailyTrigger.getFinalFireTime();
assertEquals("Final fire time not computed correctly for day interval.", endCalendar.getTime(), testTime);
startCalendar = Calendar.getInstance();
startCalendar.set(2010, Calendar.MARCH, 12, 9, 0, 0);
startCalendar.clear(Calendar.MILLISECOND);
dailyTrigger = new CalendarIntervalTriggerImpl();
dailyTrigger.setStartTime(startCalendar.getTime());
dailyTrigger.setRepeatIntervalUnit(DateBuilder.IntervalUnit.MINUTE);
dailyTrigger.setRepeatInterval(5); // every 5 minutes
endCalendar = Calendar.getInstance();
endCalendar.setTime(startCalendar.getTime());
endCalendar.setLenient(true);
endCalendar.add(Calendar.DAY_OF_YEAR, 15); // jump 15 days
endCalendar.add(Calendar.MINUTE,-2); // back up two minutes
endCalendar.clear(Calendar.MILLISECOND);
dailyTrigger.setEndTime(endCalendar.getTime());
testTime = dailyTrigger.getFinalFireTime();
assertTrue("Final fire time not computed correctly for minutely interval.", (endCalendar.getTime().after(testTime)));
endCalendar.add(Calendar.MINUTE,-3); // back up three more minutes
assertTrue("Final fire time not computed correctly for minutely interval.", (endCalendar.getTime().equals(testTime)));
}
public void testMisfireInstructionValidity() throws ParseException {
CalendarIntervalTriggerImpl trigger = new CalendarIntervalTriggerImpl();
try {
trigger.setMisfireInstruction(Trigger.MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY);
trigger.setMisfireInstruction(Trigger.MISFIRE_INSTRUCTION_SMART_POLICY);
trigger.setMisfireInstruction(CalendarIntervalTriggerImpl.MISFIRE_INSTRUCTION_DO_NOTHING);
trigger.setMisfireInstruction(CalendarIntervalTriggerImpl.MISFIRE_INSTRUCTION_FIRE_ONCE_NOW);
}
catch(Exception e) {
fail("Unexpected exception while setting misfire instruction.");
}
try {
trigger.setMisfireInstruction(CalendarIntervalTriggerImpl.MISFIRE_INSTRUCTION_DO_NOTHING + 1);
fail("Expected exception while setting invalid misfire instruction but did not get it.");
}
catch(Exception e) {
}
}
@Override
protected Object getTargetObject() throws Exception {
JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put("A", "B");
CalendarIntervalTriggerImpl t = new CalendarIntervalTriggerImpl();
t.setName("test");
t.setGroup("testGroup");
t.setCalendarName("MyCalendar");
t.setDescription("CronTriggerDesc");
t.setJobDataMap(jobDataMap);
t.setRepeatInterval(5);
t.setRepeatIntervalUnit(IntervalUnit.DAY);
return t;
}
@Override
protected String[] getVersions() {
return VERSIONS;
}
@Override
protected void verifyMatch(Object target, Object deserialized) {
CalendarIntervalTriggerImpl targetCalTrigger = (CalendarIntervalTriggerImpl)target;
CalendarIntervalTriggerImpl deserializedCalTrigger = (CalendarIntervalTriggerImpl)deserialized;
assertNotNull(deserializedCalTrigger);
assertEquals(targetCalTrigger.getName(), deserializedCalTrigger.getName());
assertEquals(targetCalTrigger.getGroup(), deserializedCalTrigger.getGroup());
assertEquals(targetCalTrigger.getJobName(), deserializedCalTrigger.getJobName());
assertEquals(targetCalTrigger.getJobGroup(), deserializedCalTrigger.getJobGroup());
// assertEquals(targetCronTrigger.getStartTime(), deserializedCronTrigger.getStartTime());
assertEquals(targetCalTrigger.getEndTime(), deserializedCalTrigger.getEndTime());
assertEquals(targetCalTrigger.getCalendarName(), deserializedCalTrigger.getCalendarName());
assertEquals(targetCalTrigger.getDescription(), deserializedCalTrigger.getDescription());
assertEquals(targetCalTrigger.getJobDataMap(), deserializedCalTrigger.getJobDataMap());
assertEquals(targetCalTrigger.getRepeatInterval(), deserializedCalTrigger.getRepeatInterval());
assertEquals(targetCalTrigger.getRepeatIntervalUnit(), deserializedCalTrigger.getRepeatIntervalUnit());
}
// execute with version number to generate a new version's serialized form
public static void main(String[] args) throws Exception {
new CalendarIntervalTriggerTest().writeJobDataFile("2.0");
}
}
| zhongfuhua/tsp-quartz | tsp-quartz-parent/tsp-quartz-core/src/test/java/org/quartz/CalendarIntervalTriggerTest.java | Java | apache-2.0 | 23,807 |
package com.lhjz.portal.entity.security;
// default package
// Generated May 6, 2015 11:39:38 AM by Hibernate Tools 4.3.1
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
/**
* Authority generated by hbm2java
*/
@Entity
@Table(name = "authorities", uniqueConstraints = @UniqueConstraint(columnNames = { "username",
"authority" }))
public class Authority implements java.io.Serializable {
/** serialVersionUID long */
private static final long serialVersionUID = 4129724544559824574L;
private AuthorityId id;
private User user;
public Authority() {
}
public Authority(AuthorityId id, User user) {
this.id = id;
this.user = user;
}
@EmbeddedId
@AttributeOverrides({
@AttributeOverride(name = "username", column = @Column(name = "username", nullable = false, length = 50)),
@AttributeOverride(name = "authority", column = @Column(name = "authority", nullable = false, length = 50)) })
public AuthorityId getId() {
return this.id;
}
public void setId(AuthorityId id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "username", nullable = false, insertable = false, updatable = false)
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public String toString() {
return "Authority [id=" + id + "]";
}
}
| czs/lhjz.portal | src/main/java/com/lhjz/portal/entity/security/Authority.java | Java | apache-2.0 | 1,663 |
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.context.support;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanInstantiationException;
import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.io.support.SpringFactoriesLoader;
import org.springframework.test.context.BootstrapContext;
import org.springframework.test.context.CacheAwareContextLoaderDelegate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.ContextConfigurationAttributes;
import org.springframework.test.context.ContextHierarchy;
import org.springframework.test.context.ContextLoader;
import org.springframework.test.context.MergedContextConfiguration;
import org.springframework.test.context.SmartContextLoader;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.TestContextBootstrapper;
import org.springframework.test.context.TestExecutionListener;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.TestExecutionListeners.MergeMode;
import org.springframework.test.util.MetaAnnotationUtils;
import org.springframework.test.util.MetaAnnotationUtils.AnnotationDescriptor;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
/**
* Abstract implementation of the {@link TestContextBootstrapper} interface which
* provides most of the behavior required by a bootstrapper.
*
* <p>Concrete subclasses typically will only need to provide implementations for
* the following methods:
* <ul>
* <li>{@link #getDefaultContextLoaderClass}
* <li>{@link #processMergedContextConfiguration}
* </ul>
*
* <p>To plug in custom
* {@link org.springframework.test.context.cache.ContextCache ContextCache}
* support, override {@link #getCacheAwareContextLoaderDelegate()}.
*
* @author Sam Brannen
* @author Juergen Hoeller
* @since 4.1
*/
public abstract class AbstractTestContextBootstrapper implements TestContextBootstrapper {
private final Log logger = LogFactory.getLog(getClass());
private BootstrapContext bootstrapContext;
/**
* {@inheritDoc}
*/
@Override
public void setBootstrapContext(BootstrapContext bootstrapContext) {
this.bootstrapContext = bootstrapContext;
}
/**
* {@inheritDoc}
*/
@Override
public BootstrapContext getBootstrapContext() {
return this.bootstrapContext;
}
/**
* Build a new {@link DefaultTestContext} using the {@linkplain Class test class}
* in the {@link BootstrapContext} associated with this bootstrapper and
* by delegating to {@link #buildMergedContextConfiguration()} and
* {@link #getCacheAwareContextLoaderDelegate()}.
* <p>Concrete subclasses may choose to override this method to return a
* custom {@link TestContext} implementation.
* @since 4.2
*/
@Override
public TestContext buildTestContext() {
return new DefaultTestContext(getBootstrapContext().getTestClass(), buildMergedContextConfiguration(),
getCacheAwareContextLoaderDelegate());
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
@Override
public final List<TestExecutionListener> getTestExecutionListeners() {
Class<?> clazz = getBootstrapContext().getTestClass();
Class<TestExecutionListeners> annotationType = TestExecutionListeners.class;
List<Class<? extends TestExecutionListener>> classesList = new ArrayList<Class<? extends TestExecutionListener>>();
boolean usingDefaults = false;
AnnotationDescriptor<TestExecutionListeners> descriptor = MetaAnnotationUtils.findAnnotationDescriptor(clazz,
annotationType);
// Use defaults?
if (descriptor == null) {
if (logger.isDebugEnabled()) {
logger.debug(String.format("@TestExecutionListeners is not present for class [%s]: using defaults.",
clazz.getName()));
}
usingDefaults = true;
classesList.addAll(getDefaultTestExecutionListenerClasses());
}
else {
// Traverse the class hierarchy...
while (descriptor != null) {
Class<?> declaringClass = descriptor.getDeclaringClass();
AnnotationAttributes annAttrs = descriptor.getAnnotationAttributes();
if (logger.isTraceEnabled()) {
logger.trace(String.format(
"Retrieved @TestExecutionListeners attributes [%s] for declaring class [%s].", annAttrs,
declaringClass.getName()));
}
Class<? extends TestExecutionListener>[] valueListenerClasses = (Class<? extends TestExecutionListener>[]) annAttrs.getClassArray("value");
Class<? extends TestExecutionListener>[] listenerClasses = (Class<? extends TestExecutionListener>[]) annAttrs.getClassArray("listeners");
if (!ObjectUtils.isEmpty(valueListenerClasses) && !ObjectUtils.isEmpty(listenerClasses)) {
throw new IllegalStateException(String.format(
"Class [%s] configured with @TestExecutionListeners' "
+ "'value' [%s] and 'listeners' [%s] attributes. Use one or the other, but not both.",
declaringClass.getName(), ObjectUtils.nullSafeToString(valueListenerClasses),
ObjectUtils.nullSafeToString(listenerClasses)));
}
else if (!ObjectUtils.isEmpty(valueListenerClasses)) {
listenerClasses = valueListenerClasses;
}
boolean inheritListeners = annAttrs.getBoolean("inheritListeners");
AnnotationDescriptor<TestExecutionListeners> superDescriptor = MetaAnnotationUtils.findAnnotationDescriptor(
descriptor.getRootDeclaringClass().getSuperclass(), annotationType);
// If there are no listeners to inherit, we might need to merge the
// locally declared listeners with the defaults.
if ((!inheritListeners || superDescriptor == null)
&& (annAttrs.getEnum("mergeMode") == MergeMode.MERGE_WITH_DEFAULTS)) {
if (logger.isDebugEnabled()) {
logger.debug(String.format(
"Merging default listeners with listeners configured via @TestExecutionListeners for class [%s].",
descriptor.getRootDeclaringClass().getName()));
}
usingDefaults = true;
classesList.addAll(getDefaultTestExecutionListenerClasses());
}
classesList.addAll(0, Arrays.<Class<? extends TestExecutionListener>> asList(listenerClasses));
descriptor = (inheritListeners ? superDescriptor : null);
}
}
// Remove possible duplicates if we loaded default listeners.
if (usingDefaults) {
Set<Class<? extends TestExecutionListener>> classesSet = new HashSet<Class<? extends TestExecutionListener>>();
classesSet.addAll(classesList);
classesList.clear();
classesList.addAll(classesSet);
}
List<TestExecutionListener> listeners = instantiateListeners(classesList);
// Sort by Ordered/@Order if we loaded default listeners.
if (usingDefaults) {
AnnotationAwareOrderComparator.sort(listeners);
}
if (logger.isInfoEnabled()) {
logger.info(String.format("Using TestExecutionListeners: %s", listeners));
}
return listeners;
}
private List<TestExecutionListener> instantiateListeners(List<Class<? extends TestExecutionListener>> classesList) {
List<TestExecutionListener> listeners = new ArrayList<TestExecutionListener>(classesList.size());
for (Class<? extends TestExecutionListener> listenerClass : classesList) {
NoClassDefFoundError ncdfe = null;
try {
listeners.add(BeanUtils.instantiateClass(listenerClass));
}
catch (NoClassDefFoundError err) {
ncdfe = err;
}
catch (BeanInstantiationException ex) {
if (ex.getCause() instanceof NoClassDefFoundError) {
ncdfe = (NoClassDefFoundError) ex.getCause();
}
}
if (ncdfe != null) {
if (logger.isInfoEnabled()) {
logger.info(String.format("Could not instantiate TestExecutionListener [%s]. "
+ "Specify custom listener classes or make the default listener classes "
+ "(and their required dependencies) available. Offending class: [%s]",
listenerClass.getName(), ncdfe.getMessage()));
}
}
}
return listeners;
}
/**
* Get the default {@link TestExecutionListener} classes for this bootstrapper.
* <p>This method is invoked by {@link #getTestExecutionListeners()} and
* delegates to {@link #getDefaultTestExecutionListenerClassNames()} to
* retrieve the class names.
* <p>If a particular class cannot be loaded, a {@code DEBUG} message will
* be logged, but the associated exception will not be rethrown.
*/
@SuppressWarnings("unchecked")
protected Set<Class<? extends TestExecutionListener>> getDefaultTestExecutionListenerClasses() {
Set<Class<? extends TestExecutionListener>> defaultListenerClasses = new LinkedHashSet<Class<? extends TestExecutionListener>>();
ClassLoader cl = getClass().getClassLoader();
for (String className : getDefaultTestExecutionListenerClassNames()) {
try {
defaultListenerClasses.add((Class<? extends TestExecutionListener>) ClassUtils.forName(className, cl));
}
catch (Throwable ex) {
if (logger.isDebugEnabled()) {
logger.debug("Could not load default TestExecutionListener class [" + className
+ "]. Specify custom listener classes or make the default listener classes available.", ex);
}
}
}
return defaultListenerClasses;
}
/**
* Get the names of the default {@link TestExecutionListener} classes for
* this bootstrapper.
* <p>The default implementation looks up all
* {@code org.springframework.test.context.TestExecutionListener} entries
* configured in all {@code META-INF/spring.factories} files on the classpath.
* <p>This method is invoked by {@link #getDefaultTestExecutionListenerClasses()}.
* @return an <em>unmodifiable</em> list of names of default {@code TestExecutionListener}
* classes
* @see SpringFactoriesLoader#loadFactoryNames
*/
protected List<String> getDefaultTestExecutionListenerClassNames() {
final List<String> classNames = SpringFactoriesLoader.loadFactoryNames(TestExecutionListener.class,
getClass().getClassLoader());
if (logger.isInfoEnabled()) {
logger.info(String.format("Loaded default TestExecutionListener class names from location [%s]: %s",
SpringFactoriesLoader.FACTORIES_RESOURCE_LOCATION, classNames));
}
return Collections.unmodifiableList(classNames);
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
@Override
public final MergedContextConfiguration buildMergedContextConfiguration() {
Class<?> testClass = getBootstrapContext().getTestClass();
CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate = getCacheAwareContextLoaderDelegate();
if (MetaAnnotationUtils.findAnnotationDescriptorForTypes(testClass, ContextConfiguration.class,
ContextHierarchy.class) == null) {
if (logger.isInfoEnabled()) {
logger.info(String.format(
"Neither @ContextConfiguration nor @ContextHierarchy found for test class [%s]",
testClass.getName()));
}
return new MergedContextConfiguration(testClass, null, null, null, null);
}
if (AnnotationUtils.findAnnotation(testClass, ContextHierarchy.class) != null) {
Map<String, List<ContextConfigurationAttributes>> hierarchyMap = ContextLoaderUtils.buildContextHierarchyMap(testClass);
MergedContextConfiguration parentConfig = null;
MergedContextConfiguration mergedConfig = null;
for (List<ContextConfigurationAttributes> list : hierarchyMap.values()) {
List<ContextConfigurationAttributes> reversedList = new ArrayList<ContextConfigurationAttributes>(list);
Collections.reverse(reversedList);
// Don't use the supplied testClass; instead ensure that we are
// building the MCC for the actual test class that declared the
// configuration for the current level in the context hierarchy.
Assert.notEmpty(reversedList, "ContextConfigurationAttributes list must not be empty");
Class<?> declaringClass = reversedList.get(0).getDeclaringClass();
mergedConfig = buildMergedContextConfiguration(declaringClass, reversedList, parentConfig,
cacheAwareContextLoaderDelegate);
parentConfig = mergedConfig;
}
// Return the last level in the context hierarchy
return mergedConfig;
}
else {
return buildMergedContextConfiguration(testClass,
ContextLoaderUtils.resolveContextConfigurationAttributes(testClass), null,
cacheAwareContextLoaderDelegate);
}
}
/**
* Build the {@link MergedContextConfiguration merged context configuration}
* for the supplied {@link Class testClass}, context configuration attributes,
* and parent context configuration.
* @param testClass the test class for which the {@code MergedContextConfiguration}
* should be built (must not be {@code null})
* @param configAttributesList the list of context configuration attributes for the
* specified test class, ordered <em>bottom-up</em> (i.e., as if we were
* traversing up the class hierarchy); never {@code null} or empty
* @param parentConfig the merged context configuration for the parent application
* context in a context hierarchy, or {@code null} if there is no parent
* @param cacheAwareContextLoaderDelegate the cache-aware context loader delegate to
* be passed to the {@code MergedContextConfiguration} constructor
* @return the merged context configuration
* @see #resolveContextLoader
* @see ContextLoaderUtils#resolveContextConfigurationAttributes
* @see SmartContextLoader#processContextConfiguration
* @see ContextLoader#processLocations
* @see ActiveProfilesUtils#resolveActiveProfiles
* @see ApplicationContextInitializerUtils#resolveInitializerClasses
* @see MergedContextConfiguration
*/
private MergedContextConfiguration buildMergedContextConfiguration(Class<?> testClass,
List<ContextConfigurationAttributes> configAttributesList, MergedContextConfiguration parentConfig,
CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate) {
ContextLoader contextLoader = resolveContextLoader(testClass, configAttributesList);
List<String> locationsList = new ArrayList<String>();
List<Class<?>> classesList = new ArrayList<Class<?>>();
for (ContextConfigurationAttributes configAttributes : configAttributesList) {
if (logger.isTraceEnabled()) {
logger.trace(String.format("Processing locations and classes for context configuration attributes %s",
configAttributes));
}
if (contextLoader instanceof SmartContextLoader) {
SmartContextLoader smartContextLoader = (SmartContextLoader) contextLoader;
smartContextLoader.processContextConfiguration(configAttributes);
locationsList.addAll(0, Arrays.asList(configAttributes.getLocations()));
classesList.addAll(0, Arrays.asList(configAttributes.getClasses()));
}
else {
String[] processedLocations = contextLoader.processLocations(configAttributes.getDeclaringClass(),
configAttributes.getLocations());
locationsList.addAll(0, Arrays.asList(processedLocations));
// Legacy ContextLoaders don't know how to process classes
}
if (!configAttributes.isInheritLocations()) {
break;
}
}
String[] locations = StringUtils.toStringArray(locationsList);
Class<?>[] classes = ClassUtils.toClassArray(classesList);
Set<Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>> initializerClasses = //
ApplicationContextInitializerUtils.resolveInitializerClasses(configAttributesList);
String[] activeProfiles = ActiveProfilesUtils.resolveActiveProfiles(testClass);
MergedTestPropertySources mergedTestPropertySources = TestPropertySourceUtils.buildMergedTestPropertySources(testClass);
MergedContextConfiguration mergedConfig = new MergedContextConfiguration(testClass, locations, classes,
initializerClasses, activeProfiles, mergedTestPropertySources.getLocations(),
mergedTestPropertySources.getProperties(), contextLoader, cacheAwareContextLoaderDelegate, parentConfig);
return processMergedContextConfiguration(mergedConfig);
}
/**
* Resolve the {@link ContextLoader} {@linkplain Class class} to use for the
* supplied list of {@link ContextConfigurationAttributes} and then instantiate
* and return that {@code ContextLoader}.
* <p>If the user has not explicitly declared which loader to use, the value
* returned from {@link #getDefaultContextLoaderClass} will be used as the
* default context loader class. For details on the class resolution process,
* see {@link #resolveExplicitContextLoaderClass} and
* {@link #getDefaultContextLoaderClass}.
* @param testClass the test class for which the {@code ContextLoader} should be
* resolved; must not be {@code null}
* @param configAttributesList the list of configuration attributes to process; must
* not be {@code null} or <em>empty</em>; must be ordered <em>bottom-up</em>
* (i.e., as if we were traversing up the class hierarchy)
* @return the resolved {@code ContextLoader} for the supplied {@code testClass}
* (never {@code null})
* @throws IllegalStateException if {@link #getDefaultContextLoaderClass(Class)}
* returns {@code null}
*/
protected ContextLoader resolveContextLoader(Class<?> testClass,
List<ContextConfigurationAttributes> configAttributesList) {
Assert.notNull(testClass, "Class must not be null");
Assert.notEmpty(configAttributesList, "ContextConfigurationAttributes list must not be empty");
Class<? extends ContextLoader> contextLoaderClass = resolveExplicitContextLoaderClass(configAttributesList);
if (contextLoaderClass == null) {
contextLoaderClass = getDefaultContextLoaderClass(testClass);
if (contextLoaderClass == null) {
throw new IllegalStateException("getDefaultContextLoaderClass() must not return null");
}
}
if (logger.isTraceEnabled()) {
logger.trace(String.format("Using ContextLoader class [%s] for test class [%s]",
contextLoaderClass.getName(), testClass.getName()));
}
return BeanUtils.instantiateClass(contextLoaderClass, ContextLoader.class);
}
/**
* Resolve the {@link ContextLoader} {@linkplain Class class} to use for the supplied
* list of {@link ContextConfigurationAttributes}.
* <p>Beginning with the first level in the context configuration attributes hierarchy:
* <ol>
* <li>If the {@link ContextConfigurationAttributes#getContextLoaderClass()
* contextLoaderClass} property of {@link ContextConfigurationAttributes} is
* configured with an explicit class, that class will be returned.</li>
* <li>If an explicit {@code ContextLoader} class is not specified at the current
* level in the hierarchy, traverse to the next level in the hierarchy and return to
* step #1.</li>
* </ol>
* @param configAttributesList the list of configuration attributes to process;
* must not be {@code null} or <em>empty</em>; must be ordered <em>bottom-up</em>
* (i.e., as if we were traversing up the class hierarchy)
* @return the {@code ContextLoader} class to use for the supplied configuration
* attributes, or {@code null} if no explicit loader is found
* @throws IllegalArgumentException if supplied configuration attributes are
* {@code null} or <em>empty</em>
*/
protected Class<? extends ContextLoader> resolveExplicitContextLoaderClass(
List<ContextConfigurationAttributes> configAttributesList) {
Assert.notEmpty(configAttributesList, "ContextConfigurationAttributes list must not be empty");
for (ContextConfigurationAttributes configAttributes : configAttributesList) {
if (logger.isTraceEnabled()) {
logger.trace(String.format("Resolving ContextLoader for context configuration attributes %s",
configAttributes));
}
Class<? extends ContextLoader> contextLoaderClass = configAttributes.getContextLoaderClass();
if (!ContextLoader.class.equals(contextLoaderClass)) {
if (logger.isDebugEnabled()) {
logger.debug(String.format(
"Found explicit ContextLoader class [%s] for context configuration attributes %s",
contextLoaderClass.getName(), configAttributes));
}
return contextLoaderClass;
}
}
return null;
}
/**
* Get the {@link CacheAwareContextLoaderDelegate} to use for transparent
* interaction with the {@code ContextCache}.
* <p>The default implementation simply delegates to
* {@code getBootstrapContext().getCacheAwareContextLoaderDelegate()}.
* <p>Concrete subclasses may choose to override this method to return a
* custom {@code CacheAwareContextLoaderDelegate} implementation with custom
* {@link org.springframework.test.context.cache.ContextCache ContextCache}
* support.
* @return the context loader delegate (never {@code null})
*/
protected CacheAwareContextLoaderDelegate getCacheAwareContextLoaderDelegate() {
return getBootstrapContext().getCacheAwareContextLoaderDelegate();
}
/**
* Determine the default {@link ContextLoader} {@linkplain Class class}
* to use for the supplied test class.
* <p>The class returned by this method will only be used if a {@code ContextLoader}
* class has not been explicitly declared via {@link ContextConfiguration#loader}.
* @param testClass the test class for which to retrieve the default
* {@code ContextLoader} class
* @return the default {@code ContextLoader} class for the supplied test class
* (never {@code null})
*/
protected abstract Class<? extends ContextLoader> getDefaultContextLoaderClass(Class<?> testClass);
/**
* Process the supplied, newly instantiated {@link MergedContextConfiguration} instance.
* <p>The returned {@link MergedContextConfiguration} instance may be a wrapper
* around or a replacement for the original.
* <p>The default implementation simply returns the supplied instance unmodified.
* <p>Concrete subclasses may choose to return a specialized subclass of
* {@link MergedContextConfiguration} based on properties in the supplied instance.
* @param mergedConfig the {@code MergedContextConfiguration} to process;
* never {@code null}
* @return a fully initialized {@code MergedContextConfiguration}; never
* {@code null}
*/
protected MergedContextConfiguration processMergedContextConfiguration(MergedContextConfiguration mergedConfig) {
return mergedConfig;
}
}
| qobel/esoguproject | spring-framework/spring-test/src/main/java/org/springframework/test/context/support/AbstractTestContextBootstrapper.java | Java | apache-2.0 | 23,250 |
package pl.touk.sputnik.connector;
import java.util.HashMap;
import java.util.Map;
public final class FacadeConfigUtil {
public static Integer HTTP_PORT = 8089;
public static Integer HTTPS_PORT = 8443;
public static String PATH = "/review";
public static Map<String, String> getHttpConfig(final String connectorType) {
return new HashMap<String, String>() {{
put("connector.type", connectorType);
put("connector.host", "localhost");
put("connector.path", PATH);
put("connector.port", HTTP_PORT.toString());
put("connector.username", "user");
put("connector.password", "pass");
}};
}
public static Map<String, String> getHttpsConfig(final String connectorType) {
Map<String, String> httpConfig = getHttpConfig(connectorType);
httpConfig.put("connector.port", HTTPS_PORT.toString());
httpConfig.put("connector.useHttps", "true");
return httpConfig;
}
}
| damianszczepanik/sputnik | src/test/java/pl/touk/sputnik/connector/FacadeConfigUtil.java | Java | apache-2.0 | 1,005 |
package com.choices.weather.holder;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* Created by Choices on 2016/3/21.
* email: [email protected]
*/
public abstract class BaseViewHolder<T> extends RecyclerView.ViewHolder {
public BaseViewHolder(View itemView) {
super(itemView);
}
public abstract void onBind(T object);
}
| ChoicesWang/MangoWeather | app/src/main/java/com/choices/weather/holder/BaseViewHolder.java | Java | apache-2.0 | 378 |
/*
* Copyright (c) Connectivity, 2017.
* This program is a free software: you can redistribute it and/or modify
* it under the terms of the Apache License, Version 2.0 (the "License");
*
* You may obtain a copy of the Apache 2 License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Apache 2 License for more details.
*/
package ru.ctvt.cps.sdk.sample.user.device;
import android.app.AlertDialog;
import android.app.DialogFragment;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import ru.ctvt.cps.sdk.sample.R;
import ru.ctvt.cps.sdk.errorprocessing.BaseCpsException;
import ru.ctvt.cps.sdk.model.UserDevice;
import ru.ctvt.cps.sdk.model.User;
import ru.ctvt.cps.sdk.sample.Model;
import ru.ctvt.cps.sdk.sample.commandQueue.CommandQueuesActivity;
import ru.ctvt.cps.sdk.sample.keyValueStorage.KeyValueStorageViewerActivity;
import ru.ctvt.cps.sdk.sample.sequence.SequencesActivity;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Экран, отображающий список устройств текущего пользователя.
* Есть возможность добавления новых устройств
*/
public class DevicesListActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
DevicesAdapter devicesAdapter;
List<UserDevice> list = new ArrayList<>();
ListView lv;
ProgressDialog progressDialog;
Button buttonAddByCode;
EditText editTextCode;
EditText editTextName;
Model model;
User user;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_devices_list);
model = Model.getInstance();
user = model.getCurrentUser();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar.setTitle("Список устройств");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
buttonAddByCode = (Button) findViewById(R.id.addDeviceByCode);
lv = (ListView) findViewById(R.id.listOfDevices);
editTextCode = (EditText) findViewById(R.id.etCode);
editTextName = (EditText) findViewById(R.id.etName);
editTextCode.setFocusable(true);
devicesAdapter = new DevicesAdapter(DevicesListActivity.this, list);
lv.setAdapter(devicesAdapter);
buttonAddByCode.setOnClickListener(this);
lv.setOnItemClickListener(this);
}
/**
* Обработчик нажатия на кнопку добавления нового устройства
* @param view
*/
@Override
public void onClick(View view) {
new Thread(new Runnable() {
ProgressDialog progres;
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
progres = new ProgressDialog(DevicesListActivity.this);
progres.setTitle("Выполнение запроса");
progres.setMessage("Подождите");
progres.show();
}
});
try {
//добавляем новое устройство текущему пользователю, передавая код привязки
//если поле ввода пустое - новое устройство добавится без привязки
if(editTextCode.getText().toString().isEmpty())
user.addDevice(editTextName.getText().toString());
else
user.addDevice(editTextCode.getText().toString(), editTextName.getText().toString());
list = user.fetchDevices();
runOnUiThread(new Runnable() {
@Override
public void run() {
if (editTextCode.getText().toString().isEmpty())
Toast.makeText(getApplicationContext(), "Код не был указан, устройство добавлено без привязки", Toast.LENGTH_LONG).show();
else
//текст в поле ввода нам больше не нужен
editTextCode.setText("");
devicesAdapter.updateData(list);
}
});
} catch (IOException e) {
e.printStackTrace();
} catch (final BaseCpsException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
editTextCode.setText("");
}
});
}
runOnUiThread(new Runnable() {
@Override
public void run() {
progres.dismiss();
}
});
}
}).start();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
deviceContextMenu(view, position);
}
@Override
protected void onResume() {
super.onResume();
getDevices(); //список должен обновляться всякий раз, когда приложение выходит на передний план
}
/**
* Обновление списка устройств пользователя
*/
void getDevices() {
new Thread(new Runnable() {
ProgressDialog dialog;
@Override
public void run() {
runOnUiThread(() -> {
dialog = new ProgressDialog(DevicesListActivity.this);
dialog.setTitle("Выполнение запроса");
dialog.setMessage("Подождите");
dialog.show();
});
try {
list = user.fetchDevices();
runOnUiThread(() -> devicesAdapter.updateData(list));
} catch (final IOException | BaseCpsException e) {
runOnUiThread(() -> {
Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
});
}
runOnUiThread(() -> dialog.dismiss());
}
}).start();
}
/**
* Контестное меню, вызываемое при нажатии на определенный элемент списка
*
* @param view элемент списка
* @param position идентификатор устройства, соответствующий элементу списка
*/
private void deviceContextMenu(View view, final int position) {
PopupMenu menu = new PopupMenu(this, view);
menu.inflate(R.menu.device_menu);
menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
model.setCurrentDevice(list.get(position));
switch (item.getItemId()) {
case R.id.menu_item_kv_storage:
startActivity(KeyValueStorageViewerActivity.createActivity(getApplicationContext(), 0));
break;
case R.id.menu_item_command_queues:
startActivity(CommandQueuesActivity.createActivity(getApplicationContext()));
break;
case R.id.menu_item_sequences:
startActivity(SequencesActivity.createActivity(getApplicationContext()));
break;
case R.id.menu_item_set_device_code:
startActivity(SetDeviceCodeActivity.setDeviceCodeIntent(getApplicationContext()));
break;
case R.id.menu_item_rename_device:
startActivity(RenameDeviceActivity.startActivity(getApplicationContext()));
break;
case R.id.menu_item_delete_device:
deleteDevice(position);
break;
}
return false;
}
});
menu.show();
}
private void deleteDevice(int position) {
new Thread(() -> {
try {
list.get(position).deleteDevice();
list = user.fetchDevices();
runOnUiThread(() -> devicesAdapter.updateData(list));
} catch (IOException e) {
e.printStackTrace();
} catch (final BaseCpsException e) {
runOnUiThread(() -> Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show());
}
}).start();
}
}
| CPS-Platform/CPS-SDK-Sample | app/src/main/java/ru/ctvt/cps/sdk/sample/user/device/DevicesListActivity.java | Java | apache-2.0 | 10,395 |
/*
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
*/
// contest
public class Solution {
public int diameterOfBinaryTree(TreeNode root) {
// 8:57 - 9:01
if(root == null) return 0;
int res = depth(root.left) + depth(root.right); // root path
res = Math.max(res, Math.max(diameterOfBinaryTree(root.left), diameterOfBinaryTree(root.right)));
return res;
}
private int depth(TreeNode root) {
if(root == null) return 0;
return 1 + Math.max(depth(root.left), depth(root.right));
}
}
// v2
public class Solution {
public int diameterOfBinaryTree(TreeNode root) {
// 11:29 - 11:31
if(root == null) {
return 0;
}
return Math.max(depth(root.left) + depth(root.right),
Math.max(diameterOfBinaryTree(root.left), diameterOfBinaryTree(root.right)));
}
public int depth(TreeNode root) {
if(root == null) return 0;
return 1 + Math.max(depth(root.left), depth(root.right));
}
}
| kxingit/LeetCode_Java | Diameter_of_Binary_Tree.java | Java | apache-2.0 | 1,227 |
/**
* Pair.java
*
* @author BJ Premore
*/
package infonet.javasim.bgp4.util;
// ===== class SSF.OS.BGP4.Util.Pair ======================================= //
/**
* A pair of objects.
*/
public class Pair <Obj1,Obj2>{
// ......................... constants ........................... //
// ........................ member data .......................... //
/** The first item in the pair. */
public Obj1 item1;
/** The second item in the pair. */
public Obj2 item2;
// ----- constructor Pair ------------------------------------------------ //
/**
* Builds a pair given two objects.
*/
public Pair(Obj1 obj1, Obj2 obj2) {
item1 = obj1;
item2 = obj2;
}
public Obj1 item1(){return item1;}
public Obj2 item2(){return item2;}
} // end class Pair
| yunxao/JN-Sim | Simulador/src/infonet/javasim/bgp4/util/Pair.java | Java | apache-2.0 | 801 |
package com.camnter.androidutils.utils;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Description:ThreadPoolUtil
* Created by:CaMnter
* Time:2015-11-25 11:12
*/
public class ThreadPoolUtils {
/**
* Create a single thread thread pool.The thread pool is only one thread in
* work, which is equivalent to a single thread serial performs all tasks.If
* this is the only thread for abnormal end, then there will be a new thread
* to replace it.The thread pool to ensure the executing order of tasks was
* all submitted order according to the task.
* 创建一个单线程的线程池。这个线程池只有一个线程在工作,也就是相当于单线程串行执行所有任务.
* 如果这个唯一的线程因为异常结束,那么会有一个新的线程来替代它.此线程池保证所有任务的执行顺
* 序按照任务的提交顺序执.
*
* @return ExecutorService
*/
public static ExecutorService getSingleThreadExecutor() {
return Executors.newSingleThreadExecutor();
}
/**
* To create a fixed-size pool.Every time to submit a task to create a
* thread, thread until reach the maximum size of the thread pool.Once the
* thread pool size maximum will remain the same, if a thread end because of
* abnormal execution, so the thread pool will make up a new thread
* 创建固定大小的线程池.每次提交一个任务就创建一个线程,直到线程达到线程池的最大大小.
* 线程池的大小一旦达到最大值就会保持不变,如果某个线程因为执行异常而结束,那么线程池
* 会补充一个新线程.
*
* @param count thread count
* @return ExecutorService
*/
public static ExecutorService getFixedThreadPool(int count) {
return Executors.newFixedThreadPool(count);
}
/**
* To create a cache of the thread pool.If the thread pool size than the
* thread processing task need, Part will be recycling idle threads (60
* seconds to perform a task), when the number of jobs increased and the
* thread pool can be smart to add a new thread to handle the task.The
* thread pool to the thread pool size do not limit, the thread pool size is
* wholly dependent on the operating system (or the JVM) to create the
* biggest thread size.
* 创建一个可缓存的线程池.如果线程池的大小超过了处理任务所需要的线程,那么就会回收部分
* 空闲(60秒不执行任务)的线程,当任务数增加时,此线程池又可以智能的添加新线程来处理任
* 务.此线程池不会对线程池大小做限制,线程池大小完全依赖于操作系统(或者说JVM)能够创建
* 的最大线程大小.
*
* @return ExecutorService
*/
public static ExecutorService getCachedThreadPool() {
return Executors.newCachedThreadPool();
}
/**
* Create a limitless thread pool size.The thread pool support regular and
* periodic mission requirements.
* 创建一个大小无限的线程池.此线程池支持定时以及周期性执行任务的需求.
*
* @param corePoolSize corePoolSize
* @return ExecutorService
*/
public static ExecutorService getScheduledThreadPool(int corePoolSize) {
return Executors.newScheduledThreadPool(corePoolSize);
}
}
| CaMnter/AndroidUtils | androidutils/src/main/java/com/camnter/androidutils/utils/ThreadPoolUtils.java | Java | apache-2.0 | 3,466 |
/*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.zuul.filters.passport;
import com.netflix.zuul.Filter;
import com.netflix.zuul.filters.FilterType;
import com.netflix.zuul.message.http.HttpRequestMessage;
import com.netflix.zuul.passport.PassportState;
import static com.netflix.zuul.filters.FilterType.INBOUND;
/**
* Created by saroskar on 3/14/17.
*/
@Filter(order = 0, type = INBOUND)
public final class InboundPassportStampingFilter extends PassportStampingFilter<HttpRequestMessage> {
public InboundPassportStampingFilter(PassportState stamp) {
super(stamp);
}
@Override
public FilterType filterType() {
return INBOUND;
}
}
| Netflix/zuul | zuul-core/src/main/java/com/netflix/zuul/filters/passport/InboundPassportStampingFilter.java | Java | apache-2.0 | 1,287 |
/*
* Copyright 2013-2016 iNeunet OpenSource and 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 com.ineunet.knife.security.utils;
import org.apache.shiro.crypto.hash.Sha256Hash;
/**
*
* @author Hilbert
*
* @since 1.0.1
*
*/
public abstract class EncryptUtils {
/**
* current encrypt for account password
*
* @param passwd
* unencrypt passwd
* @return encrypt passwd
*/
public static String encryptPasswd(String passwd) {
return new Sha256Hash(passwd).toHex();
}
}
| ineunetOS/knife | knife-security/src/main/java/com/ineunet/knife/security/utils/EncryptUtils.java | Java | apache-2.0 | 1,062 |
/*
* Licensed to ElasticSearch and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. ElasticSearch licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
/**
* A handy one stop shop for creating indexer requests (make sure to import static this class).
*/
public class IngestRequests {
/**
* The content type used to generate request builders (query / search).
*/
public static XContentType CONTENT_TYPE = XContentType.SMILE;
/**
* The default content type to use to generate source documents when indexing.
*/
public static XContentType INDEX_CONTENT_TYPE = XContentType.JSON;
public static IndexRequest indexRequest() {
return new IndexRequest();
}
/**
* Create an index request against a specific index. Note the {@link IndexRequest#type(String)} must be
* set as well and optionally the {@link IndexRequest#id(String)}.
*
* @param index The index name to index the request against
* @return The index request
* @see org.elasticsearch.client.Client#index(org.elasticsearch.action.index.IndexRequest)
*/
public static IndexRequest indexRequest(String index) {
return new IndexRequest(index);
}
/**
* Creates a delete request against a specific index. Note the {@link DeleteRequest#type(String)} and
* {@link DeleteRequest#id(String)} must be set.
*
* @param index The index name to delete from
* @return The delete request
* @see org.elasticsearch.client.Client#delete(org.elasticsearch.action.delete.DeleteRequest)
*/
public static DeleteRequest deleteRequest(String index) {
return new DeleteRequest(index);
}
/**
* Creats a new bulk request.
*/
public static BulkRequest bulkRequest() {
return new BulkRequest();
}
/**
* Creates a get request to get the JSON source from an index based on a type and id. Note, the
* {@link GetRequest#type(String)} and {@link GetRequest#id(String)} must be set.
*
* @param index The index to get the JSON source from
* @return The get request
* @see org.elasticsearch.client.Client#get(org.elasticsearch.action.get.GetRequest)
*/
public static GetRequest getRequest(String index) {
return new GetRequest(index);
}
}
| jprante/elasticsearch-client | elasticsearch-client-ingest/src/main/java/org/elasticsearch/client/IngestRequests.java | Java | apache-2.0 | 3,259 |
/*
* Copyright (C) 2008 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 android.net;
import android.os.SystemProperties;
import android.util.Log;
import com.android.org.conscrypt.OpenSSLContextImpl;
import com.android.org.conscrypt.OpenSSLSocketImpl;
import com.android.org.conscrypt.SSLClientSessionCache;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.security.KeyManagementException;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import javax.net.SocketFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* SSLSocketFactory implementation with several extra features:
*
* <ul>
* <li>Timeout specification for SSL handshake operations
* <li>Hostname verification in most cases (see WARNINGs below)
* <li>Optional SSL session caching with {@link SSLSessionCache}
* <li>Optionally bypass all SSL certificate checks
* </ul>
*
* The handshake timeout does not apply to actual TCP socket connection.
* If you want a connection timeout as well, use {@link #createSocket()}
* and {@link Socket#connect(SocketAddress, int)}, after which you
* must verify the identity of the server you are connected to.
*
* <p class="caution"><b>Most {@link SSLSocketFactory} implementations do not
* verify the server's identity, allowing man-in-the-middle attacks.</b>
* This implementation does check the server's certificate hostname, but only
* for createSocket variants that specify a hostname. When using methods that
* use {@link InetAddress} or which return an unconnected socket, you MUST
* verify the server's identity yourself to ensure a secure connection.</p>
*
* <p>One way to verify the server's identity is to use
* {@link HttpsURLConnection#getDefaultHostnameVerifier()} to get a
* {@link HostnameVerifier} to verify the certificate hostname.
*
* <p>On development devices, "setprop socket.relaxsslcheck yes" bypasses all
* SSL certificate and hostname checks for testing purposes. This setting
* requires root access.
*/
public class SSLCertificateSocketFactory extends SSLSocketFactory {
private static final String TAG = "SSLCertificateSocketFactory";
private static final TrustManager[] INSECURE_TRUST_MANAGER = new TrustManager[] {
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() { return null; }
public void checkClientTrusted(X509Certificate[] certs, String authType) { }
public void checkServerTrusted(X509Certificate[] certs, String authType) { }
}
};
private SSLSocketFactory mInsecureFactory = null;
private SSLSocketFactory mSecureFactory = null;
private TrustManager[] mTrustManagers = null;
private KeyManager[] mKeyManagers = null;
private byte[] mNpnProtocols = null;
private byte[] mAlpnProtocols = null;
private PrivateKey mChannelIdPrivateKey = null;
private final int mHandshakeTimeoutMillis;
private final SSLClientSessionCache mSessionCache;
private final boolean mSecure;
/** @deprecated Use {@link #getDefault(int)} instead. */
@Deprecated
public SSLCertificateSocketFactory(int handshakeTimeoutMillis) {
this(handshakeTimeoutMillis, null, true);
}
private SSLCertificateSocketFactory(
int handshakeTimeoutMillis, SSLSessionCache cache, boolean secure) {
mHandshakeTimeoutMillis = handshakeTimeoutMillis;
mSessionCache = cache == null ? null : cache.mSessionCache;
mSecure = secure;
}
/**
* Returns a new socket factory instance with an optional handshake timeout.
*
* @param handshakeTimeoutMillis to use for SSL connection handshake, or 0
* for none. The socket timeout is reset to 0 after the handshake.
* @return a new SSLSocketFactory with the specified parameters
*/
public static SocketFactory getDefault(int handshakeTimeoutMillis) {
return new SSLCertificateSocketFactory(handshakeTimeoutMillis, null, true);
}
/**
* Returns a new socket factory instance with an optional handshake timeout
* and SSL session cache.
*
* @param handshakeTimeoutMillis to use for SSL connection handshake, or 0
* for none. The socket timeout is reset to 0 after the handshake.
* @param cache The {@link SSLSessionCache} to use, or null for no cache.
* @return a new SSLSocketFactory with the specified parameters
*/
public static SSLSocketFactory getDefault(int handshakeTimeoutMillis, SSLSessionCache cache) {
return new SSLCertificateSocketFactory(handshakeTimeoutMillis, cache, true);
}
/**
* Returns a new instance of a socket factory with all SSL security checks
* disabled, using an optional handshake timeout and SSL session cache.
*
* <p class="caution"><b>Warning:</b> Sockets created using this factory
* are vulnerable to man-in-the-middle attacks!</p>
*
* @param handshakeTimeoutMillis to use for SSL connection handshake, or 0
* for none. The socket timeout is reset to 0 after the handshake.
* @param cache The {@link SSLSessionCache} to use, or null for no cache.
* @return an insecure SSLSocketFactory with the specified parameters
*/
public static SSLSocketFactory getInsecure(int handshakeTimeoutMillis, SSLSessionCache cache) {
return new SSLCertificateSocketFactory(handshakeTimeoutMillis, cache, false);
}
/**
* Returns a socket factory (also named SSLSocketFactory, but in a different
* namespace) for use with the Apache HTTP stack.
*
* @param handshakeTimeoutMillis to use for SSL connection handshake, or 0
* for none. The socket timeout is reset to 0 after the handshake.
* @param cache The {@link SSLSessionCache} to use, or null for no cache.
* @return a new SocketFactory with the specified parameters
*/
public static org.apache.http.conn.ssl.SSLSocketFactory getHttpSocketFactory(
int handshakeTimeoutMillis, SSLSessionCache cache) {
return new org.apache.http.conn.ssl.SSLSocketFactory(
new SSLCertificateSocketFactory(handshakeTimeoutMillis, cache, true));
}
/**
* Verify the hostname of the certificate used by the other end of a
* connected socket. You MUST call this if you did not supply a hostname
* to {@link #createSocket()}. It is harmless to call this method
* redundantly if the hostname has already been verified.
*
* <p>Wildcard certificates are allowed to verify any matching hostname,
* so "foo.bar.example.com" is verified if the peer has a certificate
* for "*.example.com".
*
* @param socket An SSL socket which has been connected to a server
* @param hostname The expected hostname of the remote server
* @throws IOException if something goes wrong handshaking with the server
* @throws SSLPeerUnverifiedException if the server cannot prove its identity
*
* @hide
*/
public static void verifyHostname(Socket socket, String hostname) throws IOException {
if (!(socket instanceof SSLSocket)) {
throw new IllegalArgumentException("Attempt to verify non-SSL socket");
}
if (!isSslCheckRelaxed()) {
// The code at the start of OpenSSLSocketImpl.startHandshake()
// ensures that the call is idempotent, so we can safely call it.
SSLSocket ssl = (SSLSocket) socket;
ssl.startHandshake();
SSLSession session = ssl.getSession();
if (session == null) {
throw new SSLException("Cannot verify SSL socket without session");
}
if (!HttpsURLConnection.getDefaultHostnameVerifier().verify(hostname, session)) {
throw new SSLPeerUnverifiedException("Cannot verify hostname: " + hostname);
}
}
}
private SSLSocketFactory makeSocketFactory(
KeyManager[] keyManagers, TrustManager[] trustManagers) {
try {
OpenSSLContextImpl sslContext = new OpenSSLContextImpl();
sslContext.engineInit(keyManagers, trustManagers, null);
sslContext.engineGetClientSessionContext().setPersistentCache(mSessionCache);
return sslContext.engineGetSocketFactory();
} catch (KeyManagementException e) {
Log.wtf(TAG, e);
return (SSLSocketFactory) SSLSocketFactory.getDefault(); // Fallback
}
}
private static boolean isSslCheckRelaxed() {
return "1".equals(SystemProperties.get("ro.debuggable")) &&
"yes".equals(SystemProperties.get("socket.relaxsslcheck"));
}
private synchronized SSLSocketFactory getDelegate() {
// Relax the SSL check if instructed (for this factory, or systemwide)
if (!mSecure || isSslCheckRelaxed()) {
if (mInsecureFactory == null) {
if (mSecure) {
Log.w(TAG, "*** BYPASSING SSL SECURITY CHECKS (socket.relaxsslcheck=yes) ***");
} else {
Log.w(TAG, "Bypassing SSL security checks at caller's request");
}
mInsecureFactory = makeSocketFactory(mKeyManagers, INSECURE_TRUST_MANAGER);
}
return mInsecureFactory;
} else {
if (mSecureFactory == null) {
mSecureFactory = makeSocketFactory(mKeyManagers, mTrustManagers);
}
return mSecureFactory;
}
}
/**
* Sets the {@link TrustManager}s to be used for connections made by this factory.
*/
public void setTrustManagers(TrustManager[] trustManager) {
mTrustManagers = trustManager;
// Clear out all cached secure factories since configurations have changed.
mSecureFactory = null;
// Note - insecure factories only ever use the INSECURE_TRUST_MANAGER so they need not
// be cleared out here.
}
/**
* Sets the <a href="http://technotes.googlecode.com/git/nextprotoneg.html">Next
* Protocol Negotiation (NPN)</a> protocols that this peer is interested in.
*
* <p>For servers this is the sequence of protocols to advertise as
* supported, in order of preference. This list is sent unencrypted to
* all clients that support NPN.
*
* <p>For clients this is a list of supported protocols to match against the
* server's list. If there is no protocol supported by both client and
* server then the first protocol in the client's list will be selected.
* The order of the client's protocols is otherwise insignificant.
*
* @param npnProtocols a non-empty list of protocol byte arrays. All arrays
* must be non-empty and of length less than 256.
*/
public void setNpnProtocols(byte[][] npnProtocols) {
this.mNpnProtocols = toLengthPrefixedList(npnProtocols);
}
/**
* Sets the
* <a href="http://tools.ietf.org/html/draft-ietf-tls-applayerprotoneg-01">
* Application Layer Protocol Negotiation (ALPN)</a> protocols that this peer
* is interested in.
*
* <p>For servers this is the sequence of protocols to advertise as
* supported, in order of preference. This list is sent unencrypted to
* all clients that support ALPN.
*
* <p>For clients this is a list of supported protocols to match against the
* server's list. If there is no protocol supported by both client and
* server then the first protocol in the client's list will be selected.
* The order of the client's protocols is otherwise insignificant.
*
* @param protocols a non-empty list of protocol byte arrays. All arrays
* must be non-empty and of length less than 256.
* @hide
*/
public void setAlpnProtocols(byte[][] protocols) {
this.mAlpnProtocols = toLengthPrefixedList(protocols);
}
/**
* Returns an array containing the concatenation of length-prefixed byte
* strings.
*/
static byte[] toLengthPrefixedList(byte[]... items) {
if (items.length == 0) {
throw new IllegalArgumentException("items.length == 0");
}
int totalLength = 0;
for (byte[] s : items) {
if (s.length == 0 || s.length > 255) {
throw new IllegalArgumentException("s.length == 0 || s.length > 255: " + s.length);
}
totalLength += 1 + s.length;
}
byte[] result = new byte[totalLength];
int pos = 0;
for (byte[] s : items) {
result[pos++] = (byte) s.length;
for (byte b : s) {
result[pos++] = b;
}
}
return result;
}
/**
* Returns the <a href="http://technotes.googlecode.com/git/nextprotoneg.html">Next
* Protocol Negotiation (NPN)</a> protocol selected by client and server, or
* null if no protocol was negotiated.
*
* @param socket a socket created by this factory.
* @throws IllegalArgumentException if the socket was not created by this factory.
*/
public byte[] getNpnSelectedProtocol(Socket socket) {
return castToOpenSSLSocket(socket).getNpnSelectedProtocol();
}
/**
* Returns the
* <a href="http://tools.ietf.org/html/draft-ietf-tls-applayerprotoneg-01">Application
* Layer Protocol Negotiation (ALPN)</a> protocol selected by client and server, or null
* if no protocol was negotiated.
*
* @param socket a socket created by this factory.
* @throws IllegalArgumentException if the socket was not created by this factory.
* @hide
*/
public byte[] getAlpnSelectedProtocol(Socket socket) {
return castToOpenSSLSocket(socket).getAlpnSelectedProtocol();
}
/**
* Sets the {@link KeyManager}s to be used for connections made by this factory.
*/
public void setKeyManagers(KeyManager[] keyManagers) {
mKeyManagers = keyManagers;
// Clear out any existing cached factories since configurations have changed.
mSecureFactory = null;
mInsecureFactory = null;
}
/**
* Sets the private key to be used for TLS Channel ID by connections made by this
* factory.
*
* @param privateKey private key (enables TLS Channel ID) or {@code null} for no key (disables
* TLS Channel ID). The private key has to be an Elliptic Curve (EC) key based on the
* NIST P-256 curve (aka SECG secp256r1 or ANSI X9.62 prime256v1).
*
* @hide
*/
public void setChannelIdPrivateKey(PrivateKey privateKey) {
mChannelIdPrivateKey = privateKey;
}
/**
* Enables <a href="http://tools.ietf.org/html/rfc5077#section-3.2">session ticket</a>
* support on the given socket.
*
* @param socket a socket created by this factory
* @param useSessionTickets {@code true} to enable session ticket support on this socket.
* @throws IllegalArgumentException if the socket was not created by this factory.
*/
public void setUseSessionTickets(Socket socket, boolean useSessionTickets) {
castToOpenSSLSocket(socket).setUseSessionTickets(useSessionTickets);
}
/**
* Turns on <a href="http://tools.ietf.org/html/rfc6066#section-3">Server
* Name Indication (SNI)</a> on a given socket.
*
* @param socket a socket created by this factory.
* @param hostName the desired SNI hostname, null to disable.
* @throws IllegalArgumentException if the socket was not created by this factory.
*/
public void setHostname(Socket socket, String hostName) {
castToOpenSSLSocket(socket).setHostname(hostName);
}
/**
* Sets this socket's SO_SNDTIMEO write timeout in milliseconds.
* Use 0 for no timeout.
* To take effect, this option must be set before the blocking method was called.
*
* @param socket a socket created by this factory.
* @param timeout the desired write timeout in milliseconds.
* @throws IllegalArgumentException if the socket was not created by this factory.
*
* @hide
*/
public void setSoWriteTimeout(Socket socket, int writeTimeoutMilliseconds)
throws SocketException {
castToOpenSSLSocket(socket).setSoWriteTimeout(writeTimeoutMilliseconds);
}
private static OpenSSLSocketImpl castToOpenSSLSocket(Socket socket) {
if (!(socket instanceof OpenSSLSocketImpl)) {
throw new IllegalArgumentException("Socket not created by this factory: "
+ socket);
}
return (OpenSSLSocketImpl) socket;
}
/**
* {@inheritDoc}
*
* <p>This method verifies the peer's certificate hostname after connecting
* (unless created with {@link #getInsecure(int, SSLSessionCache)}).
*/
@Override
public Socket createSocket(Socket k, String host, int port, boolean close) throws IOException {
OpenSSLSocketImpl s = (OpenSSLSocketImpl) getDelegate().createSocket(k, host, port, close);
s.setNpnProtocols(mNpnProtocols);
s.setAlpnProtocols(mAlpnProtocols);
s.setHandshakeTimeout(mHandshakeTimeoutMillis);
s.setChannelIdPrivateKey(mChannelIdPrivateKey);
if (mSecure) {
verifyHostname(s, host);
}
return s;
}
/**
* Creates a new socket which is not connected to any remote host.
* You must use {@link Socket#connect} to connect the socket.
*
* <p class="caution"><b>Warning:</b> Hostname verification is not performed
* with this method. You MUST verify the server's identity after connecting
* the socket to avoid man-in-the-middle attacks.</p>
*/
@Override
public Socket createSocket() throws IOException {
OpenSSLSocketImpl s = (OpenSSLSocketImpl) getDelegate().createSocket();
s.setNpnProtocols(mNpnProtocols);
s.setAlpnProtocols(mAlpnProtocols);
s.setHandshakeTimeout(mHandshakeTimeoutMillis);
s.setChannelIdPrivateKey(mChannelIdPrivateKey);
return s;
}
/**
* {@inheritDoc}
*
* <p class="caution"><b>Warning:</b> Hostname verification is not performed
* with this method. You MUST verify the server's identity after connecting
* the socket to avoid man-in-the-middle attacks.</p>
*/
@Override
public Socket createSocket(InetAddress addr, int port, InetAddress localAddr, int localPort)
throws IOException {
OpenSSLSocketImpl s = (OpenSSLSocketImpl) getDelegate().createSocket(
addr, port, localAddr, localPort);
s.setNpnProtocols(mNpnProtocols);
s.setAlpnProtocols(mAlpnProtocols);
s.setHandshakeTimeout(mHandshakeTimeoutMillis);
s.setChannelIdPrivateKey(mChannelIdPrivateKey);
return s;
}
/**
* {@inheritDoc}
*
* <p class="caution"><b>Warning:</b> Hostname verification is not performed
* with this method. You MUST verify the server's identity after connecting
* the socket to avoid man-in-the-middle attacks.</p>
*/
@Override
public Socket createSocket(InetAddress addr, int port) throws IOException {
OpenSSLSocketImpl s = (OpenSSLSocketImpl) getDelegate().createSocket(addr, port);
s.setNpnProtocols(mNpnProtocols);
s.setAlpnProtocols(mAlpnProtocols);
s.setHandshakeTimeout(mHandshakeTimeoutMillis);
s.setChannelIdPrivateKey(mChannelIdPrivateKey);
return s;
}
/**
* {@inheritDoc}
*
* <p>This method verifies the peer's certificate hostname after connecting
* (unless created with {@link #getInsecure(int, SSLSessionCache)}).
*/
@Override
public Socket createSocket(String host, int port, InetAddress localAddr, int localPort)
throws IOException {
OpenSSLSocketImpl s = (OpenSSLSocketImpl) getDelegate().createSocket(
host, port, localAddr, localPort);
s.setNpnProtocols(mNpnProtocols);
s.setAlpnProtocols(mAlpnProtocols);
s.setHandshakeTimeout(mHandshakeTimeoutMillis);
s.setChannelIdPrivateKey(mChannelIdPrivateKey);
if (mSecure) {
verifyHostname(s, host);
}
return s;
}
/**
* {@inheritDoc}
*
* <p>This method verifies the peer's certificate hostname after connecting
* (unless created with {@link #getInsecure(int, SSLSessionCache)}).
*/
@Override
public Socket createSocket(String host, int port) throws IOException {
OpenSSLSocketImpl s = (OpenSSLSocketImpl) getDelegate().createSocket(host, port);
s.setNpnProtocols(mNpnProtocols);
s.setAlpnProtocols(mAlpnProtocols);
s.setHandshakeTimeout(mHandshakeTimeoutMillis);
s.setChannelIdPrivateKey(mChannelIdPrivateKey);
if (mSecure) {
verifyHostname(s, host);
}
return s;
}
@Override
public String[] getDefaultCipherSuites() {
return getDelegate().getSupportedCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return getDelegate().getSupportedCipherSuites();
}
}
| indashnet/InDashNet.Open.UN2000 | android/frameworks/base/core/java/android/net/SSLCertificateSocketFactory.java | Java | apache-2.0 | 22,232 |
package com.rizki.mufrizal.belajar.oauth2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.orm.jpa.EntityScan;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.HashMap;
import java.util.Map;
@SpringBootApplication
@EnableCaching
@EnableJpaRepositories
@EnableTransactionManagement
@EntityScan(basePackages = {"com.rizki.mufrizal.belajar.oauth2.domain"})
public class WebApplication extends WebMvcConfigurerAdapter{
public static void main(String[] args) {
SpringApplication.run(WebApplication.class, args);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry resourceHandlerRegistry) {
resourceHandlerRegistry.addResourceHandler("/**").addResourceLocations("/");
}
@Bean
public JedisConnectionFactory jedisConnectionFactory(){
JedisConnectionFactory connectionFactory = new JedisConnectionFactory();
connectionFactory.setHostName("localhost");
connectionFactory.setPort(6379);
connectionFactory.setUsePool(true);
return connectionFactory;
}
@Bean
public RedisTemplate<Object, Object> redisTemplate(){
RedisTemplate<Object, Object> objectRedisTemplate = new RedisTemplate<>();
objectRedisTemplate.setConnectionFactory(jedisConnectionFactory());
return objectRedisTemplate;
}
@Bean
public RedisCacheManager redisCacheManager(){
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate());
Map<String, Long> keyMap = new HashMap<>();
keyMap.put("user", 100L);
cacheManager.setExpires(keyMap);
return cacheManager;
}
}
| RizkiMufrizal/Belajar-Oauth2 | Belajar-Oauth2-Authorization-Server/src/main/java/com/rizki/mufrizal/belajar/oauth2/WebApplication.java | Java | apache-2.0 | 2,331 |
/*
Copyright 2016 Immutables Authors and Contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.immutables.fixture.deep;
import com.google.common.collect.ImmutableList;
import org.immutables.fixture.deep.Canvas.Line;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Collections;
import static org.immutables.check.Checkers.check;
public class DeepImmutablesDetectionTest {
private static final ModifiableColor MODIFIABLE_COLOR = ModifiableColor.create(0.5, 0.5, 0.5);
private static final ImmutableColor IMMUTABLE_COLOR = MODIFIABLE_COLOR.toImmutable();
private static final ModifiablePoint MODIFIABLE_POINT = ModifiablePoint.create(1, 2);
private static final ImmutablePoint IMMUTABLE_POINT = MODIFIABLE_POINT.toImmutable();
@Test
public void modifiableFieldIsConvertedOnToImmutable() {
Line line = ModifiableLine.create().setColor(MODIFIABLE_COLOR).toImmutable();
check(line.color()).isA(ImmutableColor.class);
check(line.color()).is(IMMUTABLE_COLOR);
}
@Test
public void modifiableCollectionFieldIsConvertedOnToImmutable() {
Line line = ModifiableLine.create()
.setColor(MODIFIABLE_COLOR)
.setPoints(Collections.singleton(MODIFIABLE_POINT))
.addPoint(MODIFIABLE_POINT)
.addPoints(MODIFIABLE_POINT, MODIFIABLE_POINT)
.addAllPoints(Collections.singleton(MODIFIABLE_POINT))
.toImmutable();
check(line.points()).isA(ImmutableList.class);
check(line.points().size()).is(5);
for (Canvas.Point point : line.points()) {
check(point).isA(ImmutablePoint.class);
check(point).is(IMMUTABLE_POINT);
}
}
@Test
public void modifiableFieldIsConvertedInBuilder() {
Line line = ImmutableLine.builder().color(MODIFIABLE_COLOR).build();
check(line.color()).isA(ImmutableColor.class);
check(line.color()).is(IMMUTABLE_COLOR);
}
@Test
public void modifiableCollectionFieldIsConvertedInBuilder() {
Line line = ImmutableLine.builder()
.color(MODIFIABLE_COLOR)
.points(Collections.singleton(MODIFIABLE_POINT))
.addPoint(MODIFIABLE_POINT)
.addPoints(MODIFIABLE_POINT, MODIFIABLE_POINT)
.addAllPoints(Collections.singleton(MODIFIABLE_POINT))
.build();
check(line.points()).isA(ImmutableList.class);
check(line.points().size()).is(5);
for (Canvas.Point point : line.points()) {
check(point).isA(ImmutablePoint.class);
check(point).is(IMMUTABLE_POINT);
}
}
@Test
public void immutableFieldIsConvertedInModifiableFrom() {
Line line = ImmutableLine.builder()
.color(IMMUTABLE_COLOR)
.addPoint(IMMUTABLE_POINT)
.build();
ModifiableLine modifiableLine = ModifiableLine.create().from(line);
check(modifiableLine.color()).isA(ModifiableColor.class);
check(modifiableLine.color()).is(MODIFIABLE_COLOR);
}
@Test
public void immutableFieldIsConvertedInModifiableSetter() {
ModifiableLine modifiableLine = ModifiableLine.create().setColor(IMMUTABLE_COLOR);
check(modifiableLine.color()).isA(ModifiableColor.class);
check(modifiableLine.color()).is(MODIFIABLE_COLOR);
}
@Test
public void immutableCollectionFieldIsConvertedInModifiableSetter() {
ModifiableLine modifiableLine = ModifiableLine.create()
.setPoints(Collections.singleton(IMMUTABLE_POINT))
.addPoint(IMMUTABLE_POINT)
.addPoints(IMMUTABLE_POINT, IMMUTABLE_POINT)
.addAllPoints(Collections.singleton(IMMUTABLE_POINT));
check(modifiableLine.points()).isA(ArrayList.class);
check(modifiableLine.points()).hasSize(5);
for (Canvas.Point point : modifiableLine.points()) {
check(point).isA(ModifiablePoint.class);
check(point).is(MODIFIABLE_POINT);
}
}
}
| immutables/immutables | value-fixture/test/org/immutables/fixture/deep/DeepImmutablesDetectionTest.java | Java | apache-2.0 | 4,304 |
package org.noob.thinking.chapter21.thread;
public class ThreadPractice1 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println("#Thread " + i + "example");
Thread.yield();
}
}
public static void main(String[] args) {
}
}
| wuxinshui/noob | thinking-in-java/src/main/java/org/noob/thinking/chapter21/thread/ThreadPractice1.java | Java | apache-2.0 | 290 |
/**
* Copyright (c) 2013-2019 Contributors to the Eclipse Foundation
*
* <p> See the NOTICE file distributed with this work for additional information regarding copyright
* ownership. All rights reserved. This program and the accompanying materials are made available
* under the terms of the Apache License, Version 2.0 which accompanies this distribution and is
* available at http://www.apache.org/licenses/LICENSE-2.0.txt
*/
package org.locationtech.geowave.analytic.param;
import org.locationtech.geowave.analytic.AnalyticItemWrapperFactory;
import org.locationtech.geowave.analytic.Projection;
import org.locationtech.geowave.analytic.extract.CentroidExtractor;
public class HullParameters {
public enum Hull implements ParameterEnum {
INDEX_NAME(String.class, "hid", "Index Identifier for Centroids", false, true),
DATA_TYPE_ID(String.class, "hdt", "Data Type ID for a centroid item", false, true),
DATA_NAMESPACE_URI(String.class, "hns", "Data Type Namespace for a centroid item", false, true),
REDUCER_COUNT(Integer.class, "hrc", "Centroid Reducer Count", false, true),
PROJECTION_CLASS(Projection.class, "hpe",
"Class to project on to 2D space. Implements org.locationtech.geowave.analytics.tools.Projection",
true, true),
EXTRACTOR_CLASS(CentroidExtractor.class, "hce",
"Centroid Exractor Class implements org.locationtech.geowave.analytics.extract.CentroidExtractor",
true, true),
WRAPPER_FACTORY_CLASS(AnalyticItemWrapperFactory.class, "hfc",
"Class to create analytic item to capture hulls. Implements org.locationtech.geowave.analytics.tools.AnalyticItemWrapperFactory",
true, true),
ITERATION(Integer.class, "hi", "The iteration of the hull calculation", false, true),
HULL_BUILDER(Projection.class, "hhb", "Hull Builder", true, true),
ZOOM_LEVEL(Integer.class, "hzl", "Zoom Level Number", false, true);
private final ParameterHelper<?> helper;
private Hull(
final Class baseClass,
final String name,
final String description,
final boolean isClass,
final boolean hasArg) {
helper = new BasicParameterHelper(this, baseClass, name, description, isClass, hasArg);
}
@Override
public Enum<?> self() {
return this;
}
@Override
public ParameterHelper<?> getHelper() {
return helper;
}
}
}
| spohnan/geowave | analytics/api/src/main/java/org/locationtech/geowave/analytic/param/HullParameters.java | Java | apache-2.0 | 2,399 |
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.virtualbng;
import static org.slf4j.LoggerFactory.getLogger;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.util.Map;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.onlab.packet.IpAddress;
import org.onosproject.rest.AbstractWebResource;
import org.slf4j.Logger;
/**
* This class provides REST services to virtual BNG.
*/
@Path("privateip")
public class VbngResource extends AbstractWebResource {
private final Logger log = getLogger(getClass());
@POST
@Path("{privateip}")
public String privateIpAddNotification(@PathParam("privateip")
String privateIp) {
if (privateIp == null) {
log.info("Private IP address to add is null");
return "0";
}
log.info("Received a private IP address : {} to add", privateIp);
IpAddress privateIpAddress = IpAddress.valueOf(privateIp);
VbngService vbngService = get(VbngService.class);
IpAddress publicIpAddress = null;
// Create a virtual BNG
publicIpAddress = vbngService.createVbng(privateIpAddress);
if (publicIpAddress != null) {
return publicIpAddress.toString();
} else {
return "0";
}
}
@DELETE
@Path("{privateip}")
public String privateIpDeleteNotification(@PathParam("privateip")
String privateIp) {
if (privateIp == null) {
log.info("Private IP address to delete is null");
return "0";
}
log.info("Received a private IP address : {} to delete", privateIp);
IpAddress privateIpAddress = IpAddress.valueOf(privateIp);
VbngService vbngService = get(VbngService.class);
IpAddress assignedPublicIpAddress = null;
// Delete a virtual BNG
assignedPublicIpAddress = vbngService.deleteVbng(privateIpAddress);
if (assignedPublicIpAddress != null) {
return assignedPublicIpAddress.toString();
} else {
return "0";
}
}
@GET
@Path("map")
@Produces(MediaType.APPLICATION_JSON)
public Response privateIpDeleteNotification() {
log.info("Received vBNG IP address map request");
VbngConfigurationService vbngConfigurationService =
get(VbngConfigurationService.class);
Map<IpAddress, IpAddress> map =
vbngConfigurationService.getIpAddressMappings();
ObjectNode result = new ObjectMapper().createObjectNode();
result.set("map", new IpAddressMapEntryCodec().encode(map.entrySet(), this));
return ok(result.toString()).build();
}
} | jmiserez/onos | apps/virtualbng/src/main/java/org/onosproject/virtualbng/VbngResource.java | Java | apache-2.0 | 3,506 |
/**
* Copyright (C) 2016 https://github.com/jottley/spring-social-salesforce
*
* 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.social.salesforce.api;
/**
* @author Umut Utkan
*/
public class RecordTypeInfo {
private String name;
private boolean available;
private String recordTypeId;
private boolean defaultRecordTypeMapping;
public RecordTypeInfo(String name, boolean available, String recordTypeId, boolean defaultRecordTypeMapping) {
this.name = name;
this.available = available;
this.recordTypeId = recordTypeId;
this.defaultRecordTypeMapping = defaultRecordTypeMapping;
}
public String getName() {
return name;
}
public boolean isAvailable() {
return available;
}
public String getRecordTypeId() {
return recordTypeId;
}
public boolean isDefaultRecordTypeMapping() {
return defaultRecordTypeMapping;
}
}
| jottley/spring-social-salesforce | src/main/java/org/springframework/social/salesforce/api/RecordTypeInfo.java | Java | apache-2.0 | 1,490 |
package software.egger.message04;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@SuppressWarnings("Duplicates")
public class Server04 {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(10);
try {
ServerSocket serverSocket = new ServerSocket(5678);
while (true) {
System.out.println("Server waits for a client to connect");
Socket connectionToClient = serverSocket.accept();
System.out.println("Client connected");
executorService.submit(() -> clientConnectionHandler(connectionToClient));
System.out.println("Server is done");
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void clientConnectionHandler(Socket connectionToClient) {
try (
BufferedReader reader = new BufferedReader(new InputStreamReader(connectionToClient.getInputStream()));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(connectionToClient.getOutputStream()));
) {
String line;
while (!(line = reader.readLine()).equals("Exit")) {
System.out.println("Got from client: " + line);
System.out.println("Doing some work which takes long");
Thread.sleep(5000);
writer.println("Response from server: " + line.split(":")[0]);
writer.flush();
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
} finally {
try {
connectionToClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| eggeral/threading-examples | src/main/java/software/egger/message04/Server04.java | Java | apache-2.0 | 1,940 |
/*
* Copyright (C) 2017 Simon Vig Therkildsen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.simonvt.cathode.common.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewOutlineProvider;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.RequestCreator;
import com.squareup.picasso.Target;
import com.squareup.picasso.Transformation;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import net.simonvt.cathode.common.R;
import net.simonvt.cathode.common.dagger.CathodeAndroidInjection;
import net.simonvt.cathode.common.widget.animation.MaterialTransition;
import timber.log.Timber;
/**
* Simple View used to display an image from a remote source. An URL to an image is passed to
* {@link #setImage(String)}, and the view then takes care of loading and displaying it.
* <p/>
* The view must either have a fixed width or a fixed width. Both can also be set. If only one
* dimension is fixed,
* {@link #setAspectRatio(float)} must be called. The non-fixed dimension will then be calculated
* by
* multiplying the
* fixed dimension with this value.
*/
public class RemoteImageView extends AspectRatioView implements Target {
private static final float ANIMATION_DURATION = 1000.0f;
@Inject Picasso picasso;
private Drawable placeHolder;
private Bitmap image;
private boolean animating;
private long startTimeMillis;
private float fraction;
private Paint paint = new Paint();
private ColorMatrix colorMatrix;
private ColorMatrixColorFilter colorMatrixColorFilter;
private String imageUrl;
private int imageResource;
private List<Transformation> transformations = new ArrayList<>();
private int resizeInsetX;
private int resizeInsetY;
public RemoteImageView(Context context) {
this(context, null);
}
public RemoteImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RemoteImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
if (!isInEditMode()) {
CathodeAndroidInjection.inject(this, context);
}
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RemoteImageView,
R.attr.remoteImageViewStyle, 0);
placeHolder = a.getDrawable(R.styleable.RemoteImageView_placeholder);
a.recycle();
setupOutlineProvider();
colorMatrix = new ColorMatrix();
colorMatrixColorFilter = new ColorMatrixColorFilter(colorMatrix);
}
private void setupOutlineProvider() {
setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
}
public void addTransformation(Transformation transformation) {
transformations.add(transformation);
}
public void clearTransformations() {
transformations.clear();
}
public void removeTransformation(Transformation transformation) {
transformations.remove(transformation);
}
public void setResizeInsets(int x, int y) {
resizeInsetX = x;
resizeInsetY = y;
}
public void setImage(String imageUrl) {
setImage(imageUrl, false);
}
public void setImage(String imageUrl, boolean animateIfDifferent) {
picasso.cancelRequest(this);
boolean animate = animateIfDifferent && !TextUtils.equals(imageUrl, this.imageUrl);
this.imageUrl = imageUrl;
this.imageResource = 0;
image = null;
fraction = 0.0f;
startTimeMillis = 0;
animating = false;
if (getWidth() - getPaddingStart() - getPaddingEnd() > 0
&& getHeight() - getPaddingTop() - getPaddingBottom() > 0) {
loadBitmap(animate);
}
invalidate();
}
public void setImage(int imageResource) {
picasso.cancelRequest(this);
this.imageUrl = null;
this.imageResource = imageResource;
image = null;
fraction = 0.0f;
startTimeMillis = 0;
animating = false;
if (getWidth() - getPaddingStart() - getPaddingEnd() > 0
&& getHeight() - getPaddingTop() - getPaddingBottom() > 0) {
loadBitmap(false);
}
invalidate();
}
private void loadBitmap(boolean animate) {
fraction = 0.0f;
image = null;
final int width = getWidth() - getPaddingStart() - getPaddingEnd();
final int height = getHeight() - getPaddingTop() - getPaddingBottom();
RequestCreator creator = null;
if (imageUrl != null) {
creator = picasso.load(imageUrl);
} else if (imageResource > 0) {
creator = picasso.load(imageResource);
}
if (creator != null) {
creator.resize(width - resizeInsetX, height - resizeInsetY).centerCrop();
if (PaletteTransformation.shouldTransform) {
creator.transform(new PaletteTransformation());
}
for (Transformation transformation : transformations) {
creator.transform(transformation);
}
creator.into(this);
}
if (!animate && image != null) {
animating = false;
startTimeMillis = 0;
fraction = 1.0f;
}
}
@Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom loadedFrom) {
image = bitmap;
animating = true;
startTimeMillis = 0;
fraction = 0.0f;
invalidate();
}
@Override public void onBitmapFailed(Drawable drawable) {
Timber.d("[onBitmapFailed] %s", imageUrl);
}
@Override public void onPrepareLoad(Drawable drawable) {
}
@Override protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if ((imageUrl != null || imageResource > 0)
&& w - getPaddingStart() - getPaddingEnd() > 0
&& h - getPaddingTop() - getPaddingBottom() > 0) {
loadBitmap(false);
}
}
public float getFraction() {
return fraction;
}
@Override protected void onDraw(Canvas canvas) {
if (image == null) {
if (placeHolder != null) {
drawPlaceholder(canvas, placeHolder, 255);
}
return;
}
boolean done = true;
int alpha = 0;
if (animating) {
if (startTimeMillis == 0) {
startTimeMillis = SystemClock.uptimeMillis();
done = false;
fraction = 0.0f;
} else {
float normalized = (SystemClock.uptimeMillis() - startTimeMillis) / ANIMATION_DURATION;
done = normalized >= 1.0f;
fraction = Math.min(normalized, 1.0f);
alpha = (int) (0xFF * fraction);
animating = alpha != 0xFF;
}
}
if (done) {
drawBitmap(canvas, image, !done, fraction);
} else {
if (placeHolder != null) {
drawPlaceholder(canvas, placeHolder, 0xFF - alpha);
}
if (alpha > 0) {
drawBitmap(canvas, image, !done, fraction);
}
invalidate();
invalidateOutline();
}
}
protected void drawPlaceholder(Canvas canvas, Drawable placeholder, int alpha) {
final int width = getWidth();
final int height = getHeight();
placeHolder.setBounds(getPaddingStart(), getPaddingTop(), width - getPaddingEnd(),
height - getPaddingBottom());
placeholder.setAlpha(alpha);
placeholder.setAlpha(alpha);
placeholder.draw(canvas);
}
protected void drawBitmap(Canvas canvas, Bitmap bitmap, boolean animating, float fraction) {
if (animating) {
colorMatrix.reset();
MaterialTransition.apply(colorMatrix, fraction);
colorMatrixColorFilter = new ColorMatrixColorFilter(colorMatrix);
paint.setColorFilter(colorMatrixColorFilter);
} else if (paint.getColorFilter() != null) {
paint.setColorFilter(null);
}
canvas.drawBitmap(bitmap, getPaddingStart(), getPaddingTop(), paint);
}
@Override protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState state = new SavedState(superState);
state.imageUrl = imageUrl;
state.imageResource = imageResource;
return state;
}
@Override protected void onRestoreInstanceState(Parcelable state) {
SavedState savedState = (SavedState) state;
super.onRestoreInstanceState(savedState.getSuperState());
setImage(savedState.imageUrl);
}
static class SavedState extends View.BaseSavedState {
String imageUrl;
int imageResource;
SavedState(Parcelable superState) {
super(superState);
}
SavedState(Parcel in) {
super(in);
imageUrl = in.readString();
imageResource = in.readInt();
}
@Override public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeString(imageUrl);
dest.writeInt(imageResource);
}
@SuppressWarnings("UnusedDeclaration") public static final Creator<SavedState> CREATOR =
new Creator<SavedState>() {
@Override public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
@Override public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
| SimonVT/cathode | cathode-common/src/main/java/net/simonvt/cathode/common/widget/RemoteImageView.java | Java | apache-2.0 | 9,841 |
package com.planet_ink.coffee_mud.core.interfaces;
import java.util.Enumeration;
import com.planet_ink.coffee_mud.Abilities.interfaces.Ability;
/*
Copyright 2012-2022 Bo Zimmerman
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.
*/
/**
*
* Something that can know or contain abilities for use.
* @author Bo Zimmerman
*
*/
public interface AbilityContainer
{
/**
* Adds a new ability to this for use.
* No ability with the same ID can be contained twice.
* @see com.planet_ink.coffee_mud.Abilities.interfaces.Ability
* @param to the Ability to add.
*/
public void addAbility(Ability to);
/**
* Removes the exact given ability object from here.
* @see com.planet_ink.coffee_mud.Abilities.interfaces.Ability
* @param to the exact Ability to remove
*/
public void delAbility(Ability to);
/**
* Returns the number of abilities contained herein this object.
* Any extraneous abilities bestowed from other sources will NOT
* be returned -- only the exact abilities owned herein.
* @see com.planet_ink.coffee_mud.Abilities.interfaces.Ability
* @return the number of owned abilities
*/
public int numAbilities();
/**
* Returns the Ability object at that index in this container.
* Any extraneous abilities bestowed from other sources MAY
* be returned, so long as index > numAbilities.
* @see com.planet_ink.coffee_mud.Abilities.interfaces.Ability
* @param index the index of the Ability object to return
* @return the Ability object
*/
public Ability fetchAbility(int index);
/**
* If contained herein, this will return the ability from this
* container of the given ID.
* Any extraneous abilities bestowed from other sources MAY
* be returned by this method.
* @see com.planet_ink.coffee_mud.Abilities.interfaces.Ability
* @param ID the ID of the ability to return.
* @return the Ability object
*/
public Ability fetchAbility(String ID);
/**
* Returns a random ability from this container.
* Any extraneous abilities bestowed from other sources MAY
* be returned by this method.
* @see com.planet_ink.coffee_mud.Abilities.interfaces.Ability
* @return a random Ability
*/
public Ability fetchRandomAbility();
/**
* Returns an enumerator of the Ability objects in this container.
* Any extraneous abilities bestowed from other sources will NOT
* be returned -- only the exact abilities owned herein.
* @return An enumerator for abilities
*/
public Enumeration<Ability> abilities();
/**
* Removes all owned abilities from this container.
* Any extraneous abilities bestowed from other sources will NOT
* be removed.
*/
public void delAllAbilities();
/**
* Returns the number of all abilities in this container.
* Any extraneous abilities bestowed from other sources WILL
* be counted by this.
* @return the number of all abilities in this container
*/
public int numAllAbilities();
/**
* Returns an enumerator of the Ability objects in this container.
* Any extraneous abilities bestowed from other sources WILL ALSO
* be returned.
* @return An enumerator for all abilities, both in the container and not
*/
public Enumeration<Ability> allAbilities();
}
| bozimmerman/CoffeeMud | com/planet_ink/coffee_mud/core/interfaces/AbilityContainer.java | Java | apache-2.0 | 3,808 |
package com.power.common.entity;
import java.math.BigDecimal;
import java.util.Date;
public class GrXuexiRy {
private Integer id;
private Integer xxid;
private String xxrid;
private Integer xxbmid;
private String status;
private Date tjsj;
private Date gxsj;
private BigDecimal fz;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getXxid() {
return xxid;
}
public void setXxid(Integer xxid) {
this.xxid = xxid;
}
public String getXxrid() {
return xxrid;
}
public void setXxrid(String xxrid) {
this.xxrid = xxrid == null ? null : xxrid.trim();
}
public Integer getXxbmid() {
return xxbmid;
}
public void setXxbmid(Integer xxbmid) {
this.xxbmid = xxbmid;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status == null ? null : status.trim();
}
public Date getTjsj() {
return tjsj;
}
public void setTjsj(Date tjsj) {
this.tjsj = tjsj;
}
public Date getGxsj() {
return gxsj;
}
public void setGxsj(Date gxsj) {
this.gxsj = gxsj;
}
public BigDecimal getFz() {
return fz;
}
public void setFz(BigDecimal fz) {
this.fz = fz;
}
} | zhang-li-mark/psas | src/main/java/com/power/common/entity/GrXuexiRy.java | Java | apache-2.0 | 1,522 |
/**
* Copyright 2013 Agustín Miura <"[email protected]">
*
* 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 ar.com.imperium.exception;
public class ImperiumRuntimeException extends RuntimeException
{
private static final long serialVersionUID = -2555505687451397596L;
public ImperiumRuntimeException(String message)
{
super(message);
}
}
| agustinmiura/imperium | src/main/java/ar/com/imperium/exception/ImperiumRuntimeException.java | Java | apache-2.0 | 894 |
/*
* Copyright 2001-2013 Stephen Colebourne
*
* 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.joda.primitives.iterator.impl;
import java.util.NoSuchElementException;
import org.joda.primitives.DoubleUtils;
import org.joda.primitives.iterator.DoubleIterator;
/**
* An iterator over an array of <code>double</code> values.
* <p>
* This class implements {@link java.util.Iterator Iterator} allowing
* seamless integration with other APIs.
* <p>
* The iterator can be reset to the start if required.
* It is unmodifiable and <code>remove()</code> is unsupported.
*
* @author Stephen Colebourne
* @author Jason Tiscione
* @version CODE GENERATED
* @since 1.0
*/
public class ArrayDoubleIterator implements DoubleIterator {
// This file is CODE GENERATED. Do not change manually.
/** The array to iterate over */
protected final double[] array;
/** Cursor position */
protected int cursor;
/**
* Creates an iterator over a copy of an array of <code>double</code> values.
* <p>
* The specified array is copied, making this class effectively immutable.
* Note that the class is not {@code final} thus it is not truly immutable.
*
* @param array the array to iterate over, must not be null
* @return an iterator based on a copy of the input array, not null
* @throws IllegalArgumentException if the array is null
*/
public static ArrayDoubleIterator copyOf(double[] array) {
if (array == null) {
throw new IllegalArgumentException("Array must not be null");
}
return new ArrayDoubleIterator(array.clone());
}
/**
* Constructs an iterator over an array of <code>double</code> values.
* <p>
* The array is assigned internally, thus the caller holds a reference to
* the internal state of the returned iterator. It is not recommended to
* modify the state of the array after construction.
*
* @param array the array to iterate over, must not be null
* @throws IllegalArgumentException if the array is null
*/
public ArrayDoubleIterator(double[] array) {
super();
if (array == null) {
throw new IllegalArgumentException("Array must not be null");
}
this.array = array;
}
//-----------------------------------------------------------------------
public boolean isModifiable() {
return false;
}
public boolean isResettable() {
return true;
}
//-----------------------------------------------------------------------
public boolean hasNext() {
return (cursor < array.length);
}
public double nextDouble() {
if (hasNext() == false) {
throw new NoSuchElementException("No more elements available");
}
return array[cursor++];
}
public Double next() {
return DoubleUtils.toObject(nextDouble());
}
public void remove() {
throw new UnsupportedOperationException("ArrayDoubleIterator does not support remove");
}
public void reset() {
cursor = 0;
}
}
| fengshao0907/joda-primitives | src/main/java/org/joda/primitives/iterator/impl/ArrayDoubleIterator.java | Java | apache-2.0 | 3,769 |
package com.lynn.filepicker.widget.photoview;
/*******************************************************************************
* Copyright 2011, 2012 Chris Banes.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.ScaleGestureDetector.OnScaleGestureListener;
import android.view.VelocityTracker;
import android.view.ViewConfiguration;
public abstract class VersionedGestureDetector {
static final String LOG_TAG = "VersionedGestureDetector";
OnGestureListener mListener;
public static VersionedGestureDetector newInstance(Context context, OnGestureListener listener) {
final int sdkVersion = Build.VERSION.SDK_INT;
VersionedGestureDetector detector = null;
if (sdkVersion < Build.VERSION_CODES.ECLAIR) {
detector = new CupcakeDetector(context);
} else if (sdkVersion < Build.VERSION_CODES.FROYO) {
detector = new EclairDetector(context);
} else {
detector = new FroyoDetector(context);
}
detector.mListener = listener;
return detector;
}
public abstract boolean onTouchEvent(MotionEvent ev);
public abstract boolean isScaling();
public static interface OnGestureListener {
public void onDrag(float dx, float dy);
public void onFling(float startX, float startY, float velocityX, float velocityY);
public void onScale(float scaleFactor, float focusX, float focusY);
}
private static class CupcakeDetector extends VersionedGestureDetector {
float mLastTouchX;
float mLastTouchY;
final float mTouchSlop;
final float mMinimumVelocity;
public CupcakeDetector(Context context) {
final ViewConfiguration configuration = ViewConfiguration.get(context);
mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
mTouchSlop = configuration.getScaledTouchSlop();
}
private VelocityTracker mVelocityTracker;
private boolean mIsDragging;
float getActiveX(MotionEvent ev) {
return ev.getX();
}
float getActiveY(MotionEvent ev) {
return ev.getY();
}
public boolean isScaling() {
return false;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN: {
mVelocityTracker = VelocityTracker.obtain();
mVelocityTracker.addMovement(ev);
mLastTouchX = getActiveX(ev);
mLastTouchY = getActiveY(ev);
mIsDragging = false;
break;
}
case MotionEvent.ACTION_MOVE: {
final float x = getActiveX(ev);
final float y = getActiveY(ev);
final float dx = x - mLastTouchX, dy = y - mLastTouchY;
if (!mIsDragging) {
// Use Pythagoras to see if drag length is larger than
// touch slop
mIsDragging = Math.sqrt((dx * dx) + (dy * dy)) >= mTouchSlop;
}
if (mIsDragging) {
mListener.onDrag(dx, dy);
mLastTouchX = x;
mLastTouchY = y;
if (null != mVelocityTracker) {
mVelocityTracker.addMovement(ev);
}
}
break;
}
case MotionEvent.ACTION_CANCEL: {
// Recycle Velocity Tracker
if (null != mVelocityTracker) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
break;
}
case MotionEvent.ACTION_UP: {
if (mIsDragging) {
if (null != mVelocityTracker) {
mLastTouchX = getActiveX(ev);
mLastTouchY = getActiveY(ev);
// Compute velocity within the last 1000ms
mVelocityTracker.addMovement(ev);
mVelocityTracker.computeCurrentVelocity(1000);
final float vX = mVelocityTracker.getXVelocity(), vY = mVelocityTracker.getYVelocity();
// If the velocity is greater than minVelocity, call
// listener
if (Math.max(Math.abs(vX), Math.abs(vY)) >= mMinimumVelocity) {
mListener.onFling(mLastTouchX, mLastTouchY, -vX, -vY);
}
}
}
// Recycle Velocity Tracker
if (null != mVelocityTracker) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
break;
}
}
return true;
}
}
@TargetApi(5)
private static class EclairDetector extends CupcakeDetector {
private static final int INVALID_POINTER_ID = -1;
private int mActivePointerId = INVALID_POINTER_ID;
private int mActivePointerIndex = 0;
public EclairDetector(Context context) {
super(context);
}
@Override
float getActiveX(MotionEvent ev) {
try {
return ev.getX(mActivePointerIndex);
} catch (Exception e) {
return ev.getX();
}
}
@Override
float getActiveY(MotionEvent ev) {
try {
return ev.getY(mActivePointerIndex);
} catch (Exception e) {
return ev.getY();
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
final int action = ev.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
mActivePointerId = ev.getPointerId(0);
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
mActivePointerId = INVALID_POINTER_ID;
break;
case MotionEvent.ACTION_POINTER_UP:
final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = ev.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mActivePointerId = ev.getPointerId(newPointerIndex);
mLastTouchX = ev.getX(newPointerIndex);
mLastTouchY = ev.getY(newPointerIndex);
}
break;
}
mActivePointerIndex = ev.findPointerIndex(mActivePointerId != INVALID_POINTER_ID ? mActivePointerId : 0);
return super.onTouchEvent(ev);
}
}
@TargetApi(8)
private static class FroyoDetector extends EclairDetector {
private final ScaleGestureDetector mDetector;
// Needs to be an inner class so that we don't hit
// VerifyError's on API 4.
private final OnScaleGestureListener mScaleListener = new OnScaleGestureListener() {
@Override
public boolean onScale(ScaleGestureDetector detector) {
mListener.onScale(detector.getScaleFactor(), detector.getFocusX(), detector.getFocusY());
return true;
}
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
return true;
}
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
// NO-OP
}
};
public FroyoDetector(Context context) {
super(context);
mDetector = new ScaleGestureDetector(context, mScaleListener);
}
@Override
public boolean isScaling() {
return mDetector.isInProgress();
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
mDetector.onTouchEvent(ev);
return super.onTouchEvent(ev);
}
}
} | liuke2016/filepicker | filepicker/src/main/java/com/lynn/filepicker/widget/photoview/VersionedGestureDetector.java | Java | apache-2.0 | 7,470 |
/**
* Copyright 2015 Tikal-Technology
*
*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 technology.tikal.ventas.controller.envio.imp;
import java.util.List;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import technology.tikal.gae.error.exceptions.MessageSourceResolvableException;
import technology.tikal.gae.pagination.model.PaginationDataLong;
import technology.tikal.ventas.controller.almacen.SalidaController;
import technology.tikal.ventas.controller.envio.EnvioController;
import technology.tikal.ventas.controller.pedido.PedidoController;
import technology.tikal.ventas.dao.almacen.RegistroAlmacenFilter;
import technology.tikal.ventas.dao.envio.EnvioDao;
import technology.tikal.ventas.model.almacen.Salida;
import technology.tikal.ventas.model.envio.Envio;
import technology.tikal.ventas.model.envio.ofy.EnvioOfy;
import technology.tikal.ventas.model.pedido.Pedido;
/**
*
* @author Nekorp
*
*/
public class EnvioControllerImp implements EnvioController {
private EnvioDao envioDao;
private PedidoController pedidoController;
private SalidaController salidaController;
@Override
public Envio crear(Long pedidoId, Envio request) {
Pedido pedido = pedidoController.get(pedidoId);
EnvioOfy nuevo = EnvioFactory.build(pedido, request);
nuevo.update(request);
envioDao.guardar(pedido, nuevo);
return nuevo;
}
@Override
public void actualizar(Long pedidoId, Long envioId, Envio request) {
Pedido pedido = pedidoController.get(pedidoId);
EnvioOfy original = envioDao.consultar(pedido, envioId);
original.update(request);
envioDao.guardar(pedido, original);
}
@Override
public Envio[] consultar(Long pedidoId, PaginationDataLong pagination) {
Pedido pedido = pedidoController.get(pedidoId);
List<EnvioOfy> consulta = envioDao.consultarTodos(pedido, null, pagination);
Envio[] response = new Envio[consulta.size()];
consulta.toArray(response);
return response;
}
@Override
public Envio get(Long pedidoId, Long envioId) {
Pedido pedido = pedidoController.get(pedidoId);
return envioDao.consultar(pedido, envioId);
}
@Override
public void borrar(Long pedidoId, Long envioId) {
Pedido pedido = pedidoController.get(pedidoId);
PaginationDataLong pagination= new PaginationDataLong();
pagination.setMaxResults(1);
RegistroAlmacenFilter filter = new RegistroAlmacenFilter();
filter.setReferenciaEnvio(envioId);
Salida[] search = salidaController.consultar(pedidoId, filter, pagination);
if (search.length > 0) {
throw new MessageSourceResolvableException(new DefaultMessageSourceResolvable(
new String[]{"EnvioConAsignaciones.EnvioControllerImp.borrar"},
new String[]{pedidoId + ""},
"Hay salidas en el inventario con este envio"));
}
EnvioOfy target = envioDao.consultar(pedido, envioId);
envioDao.borrar(pedido, target);
}
public void setPedidoController(PedidoController pedidoController) {
this.pedidoController = pedidoController;
}
public void setEnvioDao(EnvioDao envioDao) {
this.envioDao = envioDao;
}
public void setSalidaController(SalidaController salidaController) {
this.salidaController = salidaController;
}
}
| Nekorp/Tikal-Technology | comercializadora-produccion/src/main/java/technology/tikal/ventas/controller/envio/imp/EnvioControllerImp.java | Java | apache-2.0 | 4,108 |
/*
* Copyright 2008 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.base.Preconditions;
import com.google.javascript.jscomp.AbstractCompiler.LifeCycleStage;
import com.google.javascript.jscomp.MakeDeclaredNamesUnique.BoilerplateRenamer;
import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
import com.google.javascript.jscomp.NodeTraversal.Callback;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* The goal with this pass is to simplify the other passes, by making less complex statements.
*
* <p>Starting with statements like: {@code var a = 0, b = foo();}
*
* <p>Which become: {@code var a = 0; var b = foo();}
*
* <p>The key here is only to break down things that help the other passes and can be put back
* together in a form that is at least as small when all is said and done.
*
* <p>This pass currently does the following:
*
* <ol>
* <li>Simplifies the AST by splitting var/let/const statements, moving initializers out of for
* loops, and converting whiles to fors.
* <li>Moves hoisted functions to the top of function scopes.
* <li>Rewrites unhoisted named function declarations to be var declarations.
* <li>Makes all variable names globally unique (extern or otherwise) so that no value is ever
* shadowed (note: "arguments" may require special handling).
* <li>Removes duplicate variable declarations.
* <li>Marks constants with the IS_CONSTANT_NAME annotation.
* <li>Finds properties marked @expose, and rewrites them in [] notation.
* <li>Rewrite body of arrow function as a block
* <li>Removes ES6 shorthand property syntax
* </ol>
*
* @author [email protected] (johnlenz)
*/
class Normalize implements CompilerPass {
private final AbstractCompiler compiler;
private final boolean assertOnChange;
Normalize(AbstractCompiler compiler, boolean assertOnChange) {
this.compiler = compiler;
this.assertOnChange = assertOnChange;
// TODO(nicksantos): assertOnChange should only be true if the tree
// is normalized.
}
static void normalizeSyntheticCode(
AbstractCompiler compiler, Node js, String prefix) {
NodeTraversal.traverseEs6(compiler, js,
new Normalize.NormalizeStatements(compiler, false));
NodeTraversal.traverseEs6(
compiler,
js,
new MakeDeclaredNamesUnique(
new BoilerplateRenamer(
compiler.getCodingConvention(),
compiler.getUniqueNameIdSupplier(),
prefix)));
}
static Node parseAndNormalizeTestCode(
AbstractCompiler compiler, String code) {
Node js = compiler.parseTestCode(code);
NodeTraversal.traverseEs6(compiler, js,
new Normalize.NormalizeStatements(compiler, false));
return js;
}
private void reportCodeChange(String changeDescription, Node n) {
if (assertOnChange) {
throw new IllegalStateException(
"Normalize constraints violated:\n" + changeDescription);
}
compiler.reportChangeToEnclosingScope(n);
}
@Override
public void process(Node externs, Node root) {
NodeTraversal.traverseRootsEs6(
compiler, new NormalizeStatements(compiler, assertOnChange), externs, root);
removeDuplicateDeclarations(externs, root);
MakeDeclaredNamesUnique renamer = new MakeDeclaredNamesUnique();
NodeTraversal.traverseRootsEs6(compiler, renamer, externs, root);
new PropagateConstantAnnotationsOverVars(compiler, assertOnChange)
.process(externs, root);
FindExposeAnnotations findExposeAnnotations = new FindExposeAnnotations();
NodeTraversal.traverseEs6(compiler, root, findExposeAnnotations);
if (!findExposeAnnotations.exposedProperties.isEmpty()) {
NodeTraversal.traverseEs6(compiler, root,
new RewriteExposedProperties(
findExposeAnnotations.exposedProperties));
}
if (!compiler.getLifeCycleStage().isNormalized()) {
compiler.setLifeCycleStage(LifeCycleStage.NORMALIZED);
}
}
/**
* Find all the @expose annotations.
*/
private static class FindExposeAnnotations extends AbstractPostOrderCallback {
private final Set<String> exposedProperties = new HashSet<>();
@Override public void visit(NodeTraversal t, Node n, Node parent) {
if (NodeUtil.isExprAssign(n)) {
Node assign = n.getFirstChild();
Node lhs = assign.getFirstChild();
if (lhs.isGetProp() && isMarkedExpose(assign)) {
exposedProperties.add(lhs.getLastChild().getString());
}
} else if (n.isStringKey() && isMarkedExpose(n)) {
exposedProperties.add(n.getString());
} else if (n.isGetProp() && n.getParent().isExprResult()
&& isMarkedExpose(n)) {
exposedProperties.add(n.getLastChild().getString());
}
}
private static boolean isMarkedExpose(Node n) {
JSDocInfo info = n.getJSDocInfo();
return info != null && info.isExpose();
}
}
/**
* Rewrite all exposed properties in [] form.
*/
private class RewriteExposedProperties
extends AbstractPostOrderCallback {
private final Set<String> exposedProperties;
RewriteExposedProperties(Set<String> exposedProperties) {
this.exposedProperties = exposedProperties;
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (n.isGetProp()) {
String propName = n.getLastChild().getString();
if (exposedProperties.contains(propName)) {
Node obj = n.removeFirstChild();
Node prop = n.removeFirstChild();
compiler.reportChangeToEnclosingScope(n);
n.replaceWith(IR.getelem(obj, prop));
}
} else if (n.isStringKey()) {
String propName = n.getString();
if (exposedProperties.contains(propName)) {
n.setQuotedString();
compiler.reportChangeToEnclosingScope(n);
}
}
}
}
/**
* Propagate constant annotations over the Var graph.
*/
static class PropagateConstantAnnotationsOverVars
extends AbstractPostOrderCallback
implements CompilerPass {
private final AbstractCompiler compiler;
private final boolean assertOnChange;
PropagateConstantAnnotationsOverVars(
AbstractCompiler compiler, boolean forbidChanges) {
this.compiler = compiler;
this.assertOnChange = forbidChanges;
}
@Override
public void process(Node externs, Node root) {
NodeTraversal.traverseRootsEs6(compiler, this, externs, root);
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
// Note: Constant properties annotations are not propagated.
if (n.isName()) {
if (n.getString().isEmpty()) {
return;
}
JSDocInfo info = null;
// Find the JSDocInfo for a top-level variable.
Var var = t.getScope().getVar(n.getString());
if (var != null) {
info = var.getJSDocInfo();
}
boolean shouldBeConstant =
(info != null && info.isConstant())
|| NodeUtil.isConstantByConvention(compiler.getCodingConvention(), n);
boolean isMarkedConstant = n.getBooleanProp(Node.IS_CONSTANT_NAME);
if (shouldBeConstant && !isMarkedConstant) {
if (assertOnChange) {
String name = n.getString();
throw new IllegalStateException(
"Unexpected const change.\n"
+ " name: " + name + "\n"
+ " parent:" + n.getParent().toStringTree());
}
n.putBooleanProp(Node.IS_CONSTANT_NAME, true);
}
}
}
}
/**
* Walk the AST tree and verify that constant names are used consistently.
*/
static class VerifyConstants extends AbstractPostOrderCallback
implements CompilerPass {
private final AbstractCompiler compiler;
private final boolean checkUserDeclarations;
VerifyConstants(AbstractCompiler compiler, boolean checkUserDeclarations) {
this.compiler = compiler;
this.checkUserDeclarations = checkUserDeclarations;
}
@Override
public void process(Node externs, Node root) {
Node externsAndJs = root.getParent();
checkState(externsAndJs != null);
checkState(externsAndJs.hasChild(externs));
NodeTraversal.traverseRootsEs6(compiler, this, externs, root);
}
private Map<String, Boolean> constantMap = new HashMap<>();
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (n.isName()) {
String name = n.getString();
if (n.getString().isEmpty()) {
return;
}
boolean isConst = n.getBooleanProp(Node.IS_CONSTANT_NAME);
if (checkUserDeclarations) {
boolean expectedConst = false;
CodingConvention convention = compiler.getCodingConvention();
if (NodeUtil.isConstantName(n)
|| NodeUtil.isConstantByConvention(convention, n)) {
expectedConst = true;
} else {
expectedConst = false;
JSDocInfo info = null;
Var var = t.getScope().getVar(n.getString());
if (var != null) {
info = var.getJSDocInfo();
}
if (info != null && info.isConstant()) {
expectedConst = true;
} else {
expectedConst = false;
}
}
if (expectedConst) {
Preconditions.checkState(expectedConst == isConst,
"The name %s is not annotated as constant.", name);
} else {
Preconditions.checkState(expectedConst == isConst,
"The name %s should not be annotated as constant.", name);
}
}
Boolean value = constantMap.get(name);
if (value == null) {
constantMap.put(name, isConst);
} else {
Preconditions.checkState(value.booleanValue() == isConst,
"The name %s is not consistently annotated as constant.", name);
}
}
}
}
/**
* Simplify the AST:
* - VAR declarations split, so they represent exactly one child
* declaration.
* - WHILEs are converted to FORs
* - FOR loop are initializers are moved out of the FOR structure
* - LABEL node of children other than LABEL, BLOCK, WHILE, FOR, or DO are
* moved into a block.
* - Add constant annotations based on coding convention.
*/
static class NormalizeStatements implements Callback {
private final AbstractCompiler compiler;
private final boolean assertOnChange;
NormalizeStatements(AbstractCompiler compiler, boolean assertOnChange) {
this.compiler = compiler;
this.assertOnChange = assertOnChange;
}
private void reportCodeChange(Node n, String changeDescription) {
if (assertOnChange) {
throw new IllegalStateException(
"Normalize constraints violated:\n" + changeDescription);
}
compiler.reportChangeToEnclosingScope(n);
}
@Override
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
doStatementNormalizations(n);
return true;
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
switch (n.getToken()) {
case WHILE:
Node expr = n.getFirstChild();
n.setToken(Token.FOR);
Node empty = IR.empty();
empty.useSourceInfoIfMissingFrom(n);
n.addChildBefore(empty, expr);
n.addChildAfter(empty.cloneNode(), expr);
reportCodeChange(n, "WHILE node");
break;
case FUNCTION:
if (visitFunction(n, compiler)) {
reportCodeChange(n, "Function declaration");
}
break;
case STRING_KEY:
if (!n.hasChildren()) {
rewriteEs6ObjectLiteralShorthandPropertySyntax(n, compiler);
reportCodeChange(n, "Normalize ES6 shorthand property syntax");
}
// fall through
case NAME:
case STRING:
case GETTER_DEF:
case SETTER_DEF:
if (!compiler.getLifeCycleStage().isNormalizedObfuscated()) {
annotateConstantsByConvention(n, parent);
}
break;
case CAST:
compiler.reportChangeToEnclosingScope(n);
parent.replaceChild(n, n.removeFirstChild());
break;
default:
break;
}
}
/**
* Mark names and properties that are constants by convention.
*/
private void annotateConstantsByConvention(Node n, Node parent) {
checkState(
n.isName() || n.isString() || n.isStringKey() || n.isGetterDef() || n.isSetterDef());
// There are only two cases where a string token
// may be a variable reference: The right side of a GETPROP
// or an OBJECTLIT key.
boolean isObjLitKey = NodeUtil.isObjectLitKey(n);
boolean isProperty = isObjLitKey || (parent.isGetProp() && parent.getLastChild() == n);
if (n.isName() || isProperty) {
boolean isMarkedConstant = n.getBooleanProp(Node.IS_CONSTANT_NAME);
if (!isMarkedConstant
&& NodeUtil.isConstantByConvention(compiler.getCodingConvention(), n)) {
if (assertOnChange) {
String name = n.getString();
throw new IllegalStateException(
"Unexpected const change.\n"
+ " name: " + name + "\n"
+ " parent:" + n.getParent().toStringTree());
}
n.putBooleanProp(Node.IS_CONSTANT_NAME, true);
}
}
}
/**
* Expand ES6 object literal shorthand property syntax.
*
* <p>From: obj = {x, y} to: obj = {x:x, y:y}
*/
private static void rewriteEs6ObjectLiteralShorthandPropertySyntax(
Node n, AbstractCompiler compiler) {
String objLitName = NodeUtil.getObjectLitKeyName(n);
Node objLitNameNode = Node.newString(Token.NAME, objLitName).useSourceInfoFrom(n);
n.addChildToBack(objLitNameNode);
}
/**
* Rewrite named unhoisted functions declarations to a known
* consistent behavior so we don't to different logic paths for the same
* code.
*
* From:
* function f() {}
* to:
* var f = function () {};
* and move it to the top of the block. This actually breaks
* semantics, but the semantics are also not well-defined
* cross-browser.
*
* @see https://github.com/google/closure-compiler/pull/429
*/
static boolean visitFunction(Node n, AbstractCompiler compiler) {
checkState(n.isFunction(), n);
if (NodeUtil.isFunctionDeclaration(n) && !NodeUtil.isHoistedFunctionDeclaration(n)) {
rewriteFunctionDeclaration(n, compiler);
return true;
} else if (n.isFunction() && !NodeUtil.getFunctionBody(n).isNormalBlock()) {
Node returnValue = NodeUtil.getFunctionBody(n);
Node body = IR.block(IR.returnNode(returnValue.detach()));
body.useSourceInfoIfMissingFromForTree(returnValue);
n.addChildToBack(body);
compiler.reportChangeToEnclosingScope(body);
}
return false;
}
/**
* Rewrite the function declaration from:
* function x() {}
* FUNCTION
* NAME x
* PARAM_LIST
* BLOCK
* to:
* var x = function() {};
* VAR
* NAME x
* FUNCTION
* NAME (w/ empty string)
* PARAM_LIST
* BLOCK
*/
private static void rewriteFunctionDeclaration(Node n, AbstractCompiler compiler) {
// Prepare a spot for the function.
Node oldNameNode = n.getFirstChild();
Node fnNameNode = oldNameNode.cloneNode();
Node var = IR.var(fnNameNode).srcref(n);
// Prepare the function
oldNameNode.setString("");
compiler.reportChangeToEnclosingScope(oldNameNode);
// Move the function if it's not the child of a label node
Node parent = n.getParent();
if (parent.isLabel()) {
parent.replaceChild(n, var);
} else {
parent.removeChild(n);
parent.addChildToFront(var);
}
compiler.reportChangeToEnclosingScope(var);
fnNameNode.addChildToFront(n);
}
/**
* Do normalizations that introduce new siblings or parents.
*/
private void doStatementNormalizations(Node n) {
if (n.isLabel()) {
normalizeLabels(n);
}
// Only inspect the children of SCRIPTs, BLOCKs and LABELs, as all these
// are the only legal place for VARs and FOR statements.
if (NodeUtil.isStatementBlock(n) || n.isLabel()) {
extractForInitializer(n, null, null);
}
// Only inspect the children of SCRIPTs, BLOCKs, as all these
// are the only legal place for VARs.
if (NodeUtil.isStatementBlock(n)) {
splitVarDeclarations(n);
}
if (n.isFunction()) {
moveNamedFunctions(n.getLastChild());
}
if (NodeUtil.isCompoundAssignmentOp(n)) {
normalizeAssignShorthand(n);
}
}
// TODO(johnlenz): Move this to NodeTypeNormalizer once the unit tests are
// fixed.
/**
* Limit the number of special cases where LABELs need to be handled. Only
* BLOCK and loops are allowed to be labeled. Loop labels must remain in
* place as the named continues are not allowed for labeled blocks.
*/
private void normalizeLabels(Node n) {
checkArgument(n.isLabel());
Node last = n.getLastChild();
// TODO(moz): Avoid adding blocks for cases like "label: let x;"
switch (last.getToken()) {
case LABEL:
case BLOCK:
case FOR:
case FOR_IN:
case WHILE:
case DO:
return;
default:
Node block = IR.block();
block.useSourceInfoIfMissingFrom(last);
n.replaceChild(last, block);
block.addChildToFront(last);
reportCodeChange(n, "LABEL normalization");
return;
}
}
/**
* Bring the initializers out of FOR loops. These need to be placed
* before any associated LABEL nodes. This needs to be done from the top
* level label first so this is called as a pre-order callback (from
* shouldTraverse).
*
* @param n The node to inspect.
* @param before The node to insert the initializer before.
* @param beforeParent The parent of the node before which the initializer
* will be inserted.
*/
private void extractForInitializer(
Node n, Node before, Node beforeParent) {
for (Node next, c = n.getFirstChild(); c != null; c = next) {
next = c.getNext();
Node insertBefore = (before == null) ? c : before;
Node insertBeforeParent = (before == null) ? n : beforeParent;
switch (c.getToken()) {
case LABEL:
extractForInitializer(c, insertBefore, insertBeforeParent);
break;
case FOR_IN:
Node first = c.getFirstChild();
if (first.isVar()) {
// Transform:
// for (var a = 1 in b) {}
// to:
// var a = 1; for (a in b) {};
Node newStatement = first;
// Clone just the node, to remove any initialization.
Node name = newStatement.getFirstChild().cloneNode();
first.replaceWith(name);
insertBeforeParent.addChildBefore(newStatement, insertBefore);
reportCodeChange(n, "FOR-IN var declaration");
}
break;
case FOR:
if (!c.getFirstChild().isEmpty()) {
Node init = c.getFirstChild();
if (init.isLet() || init.isConst() || init.isClass() || init.isFunction()) {
return;
}
Node empty = IR.empty();
empty.useSourceInfoIfMissingFrom(c);
c.replaceChild(init, empty);
Node newStatement;
// Only VAR statements, and expressions are allowed,
// but are handled differently.
if (init.isVar()) {
newStatement = init;
} else {
newStatement = NodeUtil.newExpr(init);
}
insertBeforeParent.addChildBefore(newStatement, insertBefore);
reportCodeChange(n, "FOR initializer");
}
break;
default:
break;
}
}
}
/**
* Split a var (or let or const) node such as:
* var a, b;
* into individual statements:
* var a;
* var b;
* @param n The whose children we should inspect.
*/
private void splitVarDeclarations(Node n) {
for (Node next, c = n.getFirstChild(); c != null; c = next) {
next = c.getNext();
if (NodeUtil.isNameDeclaration(c)) {
if (assertOnChange && !c.hasChildren()) {
throw new IllegalStateException("Empty VAR node.");
}
while (c.getFirstChild() != c.getLastChild()) {
Node name = c.getFirstChild();
c.removeChild(name);
Node newVar = new Node(c.getToken(), name).srcref(n);
n.addChildBefore(newVar, c);
reportCodeChange(n, "VAR with multiple children");
}
}
}
}
/**
* Move all the functions that are valid at the execution of the first
* statement of the function to the beginning of the function definition.
*/
private void moveNamedFunctions(Node functionBody) {
checkState(functionBody.getParent().isFunction());
Node insertAfter = null;
Node current = functionBody.getFirstChild();
// Skip any declarations at the beginning of the function body, they
// are already in the right place.
while (current != null && NodeUtil.isFunctionDeclaration(current)) {
insertAfter = current;
current = current.getNext();
}
// Find any remaining declarations and move them.
while (current != null) {
// Save off the next node as the current node maybe removed.
Node next = current.getNext();
if (NodeUtil.isFunctionDeclaration(current)) {
// Remove the declaration from the body.
functionBody.removeChild(current);
// Read the function at the top of the function body (after any
// previous declarations).
insertAfter = addToFront(functionBody, current, insertAfter);
reportCodeChange(functionBody, "Move function declaration not at top of function");
}
current = next;
}
}
private void normalizeAssignShorthand(Node shorthand) {
if (shorthand.getFirstChild().isName()) {
Node name = shorthand.getFirstChild();
shorthand.setToken(NodeUtil.getOpFromAssignmentOp(shorthand));
Node parent = shorthand.getParent();
Node insertPoint = IR.empty();
parent.replaceChild(shorthand, insertPoint);
Node assign = IR.assign(name.cloneNode().useSourceInfoFrom(name), shorthand)
.useSourceInfoFrom(shorthand);
assign.setJSDocInfo(shorthand.getJSDocInfo());
shorthand.setJSDocInfo(null);
parent.replaceChild(insertPoint, assign);
compiler.reportChangeToEnclosingScope(assign);
}
}
/**
* @param after The child node to insert the newChild after, or null if
* newChild should be added to the front of parent's child list.
* @return The inserted child node.
*/
private static Node addToFront(Node parent, Node newChild, Node after) {
if (after == null) {
parent.addChildToFront(newChild);
} else {
parent.addChildAfter(newChild, after);
}
return newChild;
}
}
/**
* Remove duplicate VAR declarations.
*/
private void removeDuplicateDeclarations(Node externs, Node root) {
Callback tickler = new ScopeTicklingCallback();
ScopeCreator scopeCreator =
new Es6SyntacticScopeCreator(compiler, new DuplicateDeclarationHandler());
NodeTraversal t = new NodeTraversal(compiler, tickler, scopeCreator);
t.traverseRoots(externs, root);
}
/**
* ScopeCreator duplicate declaration handler.
*/
private final class DuplicateDeclarationHandler implements
Es6SyntacticScopeCreator.RedeclarationHandler {
private Set<Var> hasOkDuplicateDeclaration = new HashSet<>();
/**
* Remove duplicate VAR declarations encountered discovered during
* scope creation.
*/
@Override
public void onRedeclaration(
Scope s, String name, Node n, CompilerInput input) {
checkState(n.isName());
Node parent = n.getParent();
Var v = s.getVar(name);
if (s.isGlobal()) {
// We allow variables to be duplicate declared if one
// declaration appears in source and the other in externs.
// This deals with issues where a browser built-in is declared
// in one browser but not in another.
if (v.isExtern() && !input.isExtern()) {
if (hasOkDuplicateDeclaration.add(v)) {
return;
}
}
}
if (parent.isFunction()) {
if (v.getParentNode().isVar()) {
s.undeclare(v);
s.declare(name, n, v.input);
replaceVarWithAssignment(v.getNameNode(), v.getParentNode(),
v.getParentNode().getParent());
}
} else if (parent.isVar()) {
checkState(parent.hasOneChild());
replaceVarWithAssignment(n, parent, parent.getParent());
}
}
/**
* Remove the parent VAR. There are three cases that need to be handled:
* 1) "var a = b;" which is replaced with "a = b"
* 2) "label:var a;" which is replaced with "label:;". Ideally, the
* label itself would be removed but that is not possible in the
* context in which "onRedeclaration" is called.
* 3) "for (var a in b) ..." which is replaced with "for (a in b)..."
* Cases we don't need to handle are VARs with multiple children,
* which have already been split into separate declarations, so there
* is no need to handle that here, and "for (var a;;);", which has
* been moved out of the loop.
* The result of this is that in each case the parent node is replaced
* which is generally dangerous in a traversal but is fine here with
* the scope creator, as the next node of interest is the parent's
* next sibling.
*/
private void replaceVarWithAssignment(Node n, Node parent, Node grandparent) {
if (n.hasChildren()) {
// The * is being initialize, preserve the new value.
parent.removeChild(n);
// Convert "var name = value" to "name = value"
Node value = n.getFirstChild();
n.removeChild(value);
Node replacement = IR.assign(n, value);
replacement.setJSDocInfo(parent.getJSDocInfo());
replacement.useSourceInfoIfMissingFrom(parent);
Node statement = NodeUtil.newExpr(replacement);
grandparent.replaceChild(parent, statement);
reportCodeChange("Duplicate VAR declaration", statement);
} else {
// It is an empty reference remove it.
if (NodeUtil.isStatementBlock(grandparent)) {
grandparent.removeChild(parent);
} else if (grandparent.isForIn()) {
// This is the "for (var a in b)..." case. We don't need to worry
// about initializers in "for (var a;;)..." as those are moved out
// as part of the other normalizations.
parent.removeChild(n);
grandparent.replaceChild(parent, n);
} else {
checkState(grandparent.isLabel());
// We should never get here. LABELs with a single VAR statement should
// already have been normalized to have a BLOCK.
throw new IllegalStateException("Unexpected LABEL");
}
reportCodeChange("Duplicate VAR declaration", grandparent);
}
}
}
/**
* A simple class that causes scope to be created.
*/
private static final class ScopeTicklingCallback implements NodeTraversal.ScopedCallback {
@Override
public void enterScope(NodeTraversal t) {
// Cause the scope to be created, which will cause duplicate
// to be found.
t.getScope();
}
@Override
public void exitScope(NodeTraversal t) {
// Nothing to do.
}
@Override
public boolean shouldTraverse(NodeTraversal nodeTraversal, Node n, Node parent) {
return true;
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
// Nothing to do.
}
}
}
| GerHobbelt/closure-compiler | src/com/google/javascript/jscomp/Normalize.java | Java | apache-2.0 | 29,810 |
package com.hu.behavior.iterator.demo1;
public abstract class Aggregate {
/**
* 工厂方法,创建相应迭代子对象的接口
*/
public abstract Iterator createIterator();
}
| jacksonTod/personalDesignPattern | DesignPattern/src/com/hu/behavior/iterator/demo1/Aggregate.java | Java | apache-2.0 | 208 |
/**
* This file is part of the Iritgo/Aktera Framework.
*
* Copyright (C) 2005-2011 Iritgo Technologies.
* Copyright (C) 2003-2005 BueroByte GbR.
*
* Iritgo 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 de.iritgo.aktera.templating;
public interface VelocitySpringResourceLoader
{
public void addTemplate(String name, String template);
public void remoteTemplate(String name);
}
| iritgo/iritgo-aktera | aktera-templating/src/main/java/de/iritgo/aktera/templating/VelocitySpringResourceLoader.java | Java | apache-2.0 | 921 |
package template;
public class User {
private String name;
private String sex;
private int schoolClass;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getSchoolClass() {
return schoolClass;
}
public void setSchoolClass(int schoolClass) {
this.schoolClass = schoolClass;
}
}
| dragonzhou/humor | src/template/User.java | Java | apache-2.0 | 457 |
package io.generators.core;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterators;
import javax.annotation.Nonnull;
import java.util.Iterator;
/**
* Generator that cycles over the given elements infinitely always in the same order.
*
* @param <T> type of the elements
*
* @author David Bliss
*/
public class CyclicGenerator<T> implements Generator<T> {
private final Iterator<T> iterator;
/**
* Creates generator that cycles over provided {@code first} and {@code rest} elements
*
* @param first first element in the set of elements to cycle over
* @param rest rest of the elements
* @throws java.lang.NullPointerException when first or one of the rest elements is null
*/
@SafeVarargs
public CyclicGenerator(@Nonnull T first, @Nonnull T... rest) {
ImmutableList<T> values = ImmutableList.<T>builder()
.add(first)
.add(rest)
.build();
this.iterator = Iterators.cycle(values);
}
@Override
public T next() {
return iterator.next();
}
}
| generators-io-projects/generators | generators-core/src/main/java/io/generators/core/CyclicGenerator.java | Java | apache-2.0 | 1,118 |
package ar.com.kerbrum.kerbrum;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | alel890/Kerbrum | app/src/androidTest/java/ar/com/kerbrum/kerbrum/ApplicationTest.java | Java | apache-2.0 | 353 |
/*
* 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.certificatemanager.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.certificatemanager.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* ThrottlingException JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ThrottlingExceptionUnmarshaller extends EnhancedJsonErrorUnmarshaller {
private ThrottlingExceptionUnmarshaller() {
super(com.amazonaws.services.certificatemanager.model.ThrottlingException.class, "ThrottlingException");
}
@Override
public com.amazonaws.services.certificatemanager.model.ThrottlingException unmarshallFromContext(JsonUnmarshallerContext context) throws Exception {
com.amazonaws.services.certificatemanager.model.ThrottlingException throttlingException = new com.amazonaws.services.certificatemanager.model.ThrottlingException(
null);
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) {
} 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 throttlingException;
}
private static ThrottlingExceptionUnmarshaller instance;
public static ThrottlingExceptionUnmarshaller getInstance() {
if (instance == null)
instance = new ThrottlingExceptionUnmarshaller();
return instance;
}
}
| aws/aws-sdk-java | aws-java-sdk-acm/src/main/java/com/amazonaws/services/certificatemanager/model/transform/ThrottlingExceptionUnmarshaller.java | Java | apache-2.0 | 2,872 |
/*
* 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.storagegateway.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.storagegateway.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* DeleteTapeRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DeleteTapeRequestProtocolMarshaller implements Marshaller<Request<DeleteTapeRequest>, DeleteTapeRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/")
.httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true)
.operationIdentifier("StorageGateway_20130630.DeleteTape").serviceName("AWSStorageGateway").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public DeleteTapeRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<DeleteTapeRequest> marshall(DeleteTapeRequest deleteTapeRequest) {
if (deleteTapeRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<DeleteTapeRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
deleteTapeRequest);
protocolMarshaller.startMarshalling();
DeleteTapeRequestMarshaller.getInstance().marshall(deleteTapeRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| aws/aws-sdk-java | aws-java-sdk-storagegateway/src/main/java/com/amazonaws/services/storagegateway/model/transform/DeleteTapeRequestProtocolMarshaller.java | Java | apache-2.0 | 2,651 |
package nam.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Minion", namespace = "http://nam/model", propOrder = {
"version",
"dnsDomain",
"dnsIP",
"bindAddress",
"volumeDirectory",
"pods"
})
@XmlRootElement(name = "minion", namespace = "http://nam/model")
public class Minion extends Node implements Comparable<Object>, Serializable {
private static final long serialVersionUID = 1L;
@XmlElement(name = "version", namespace = "http://nam/model")
private String version;
@XmlElement(name = "dnsDomain", namespace = "http://nam/model")
private String dnsDomain;
@XmlElement(name = "dnsIP", namespace = "http://nam/model")
private IPAddress dnsIP;
@XmlElement(name = "bindAddress", namespace = "http://nam/model")
private IPAddress bindAddress;
@XmlElement(name = "volumeDirectory", namespace = "http://nam/model")
private String volumeDirectory;
@XmlElement(name = "pods", namespace = "http://nam/model")
private List<Pod> pods;
public Minion() {
pods = new ArrayList<Pod>();
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getDnsDomain() {
return dnsDomain;
}
public void setDnsDomain(String dnsDomain) {
this.dnsDomain = dnsDomain;
}
public IPAddress getDnsIP() {
return dnsIP;
}
public void setDnsIP(IPAddress dnsIP) {
this.dnsIP = dnsIP;
}
public IPAddress getBindAddress() {
return bindAddress;
}
public void setBindAddress(IPAddress bindAddress) {
this.bindAddress = bindAddress;
}
public String getVolumeDirectory() {
return volumeDirectory;
}
public void setVolumeDirectory(String volumeDirectory) {
this.volumeDirectory = volumeDirectory;
}
public List<Pod> getPods() {
synchronized (pods) {
return pods;
}
}
public void setPods(Collection<Pod> pods) {
if (pods == null) {
this.pods = null;
} else {
synchronized (this.pods) {
this.pods = new ArrayList<Pod>();
addToPods(pods);
}
}
}
public void addToPods(Pod pod) {
if (pod != null ) {
synchronized (this.pods) {
this.pods.add(pod);
}
}
}
public void addToPods(Collection<Pod> podCollection) {
if (podCollection != null && !podCollection.isEmpty()) {
synchronized (this.pods) {
this.pods.addAll(podCollection);
}
}
}
public void removeFromPods(Pod pod) {
if (pod != null ) {
synchronized (this.pods) {
this.pods.remove(pod);
}
}
}
public void removeFromPods(Collection<Pod> podCollection) {
if (podCollection != null ) {
synchronized (this.pods) {
this.pods.removeAll(podCollection);
}
}
}
public void clearPods() {
synchronized (pods) {
pods.clear();
}
}
@Override
public int compareTo(Object object) {
if (object.getClass().isAssignableFrom(this.getClass())) {
Minion other = (Minion) object;
int status = compare(dnsDomain, other.dnsDomain);
if (status != 0)
return status;
status = compareObject(dnsIP, other.dnsIP);
if (status != 0)
return status;
}
int status = super.compareTo(object);
return status;
}
protected <T extends Comparable<T>> int compare(T value1, T value2) {
if (value1 == null && value2 == null) return 0;
if (value1 != null && value2 == null) return 1;
if (value1 == null && value2 != null) return -1;
int status = value1.compareTo(value2);
return status;
}
protected <T extends Comparable<Object>> int compareObject(T value1, T value2) {
if (value1 == null && value2 == null) return 0;
if (value1 != null && value2 == null) return 1;
if (value1 == null && value2 != null) return -1;
int status = value1.compareTo(value2);
return status;
}
@Override
public boolean equals(Object object) {
if (object == null)
return false;
if (!object.getClass().isAssignableFrom(this.getClass()))
return false;
Minion other = (Minion) object;
int status = compareTo(other);
return status == 0;
}
@Override
public int hashCode() {
int hashCode = 0;
if (dnsDomain != null)
hashCode += dnsDomain.hashCode();
if (dnsIP != null)
hashCode += dnsIP.hashCode();
if (hashCode == 0)
return super.hashCode();
return hashCode;
}
@Override
public String toString() {
return "Minion: dnsDomain="+dnsDomain+", dnsIP="+dnsIP;
}
}
| tfisher1226/ARIES | nam/nam-model/src/main/java/nam/model/Minion.java | Java | apache-2.0 | 4,659 |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.integration.persistence.datasource.mysql;
import javax.annotation.sql.DataSourceDefinition;
import javax.ejb.Singleton;
import javax.ejb.Startup;
@DataSourceDefinition(name = "java:app/datasources/mysql_ds",
className = "com.mysql.jdbc.jdbc2.optional.MysqlDataSource",
url = "jdbc:mysql://localhost:33306/ape",
user = "ape",
password = "letmein")
@Singleton
@Startup
public class MySqlDataSource {
}
| rmpestano/arquillian-extension-persistence | int-tests/src/test/java/org/jboss/arquillian/integration/persistence/datasource/mysql/MySqlDataSource.java | Java | apache-2.0 | 1,290 |
/**
*
*/
package com.tibco.emea.amxbpm;
/**
* @author mrzedzic
*
*/
public enum AmxBpmProcessState {
ACTIVE, SUSPENDED, HALTED, FAILED, CANCELLED, COMPLETED
}
| mrzedzic/jbehave-amxbpm | jbehave-amx-bpm-tests/src/test/java/com/tibco/emea/amxbpm/AmxBpmProcessState.java | Java | apache-2.0 | 179 |
/*
* 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.harmony.luni.internal.locale;
public class Locale_zh_SG extends java.util.ListResourceBundle {
protected Object[][] getContents() {
Object[][] contents = {
{"Date_SHORT","yyyy/M/d",},
{"Date_MEDIUM","yyyy/M/d",},
{"Date_FULL","yyyy'\u5e74'M'\u6708'd'\u65e5'",},
{"Time_SHORT","a h:mm",},
{"Time_MEDIUM","a hh:mm:ss",},
{"Time_LONG","ahh'\u6642'mm'\u5206'ss'\u79d2'",},
{"Time_FULL","ahh'\u6642'mm'\u5206'ss'\u79d2' z",},
{"CurrencySymbol","$",},
{"IntCurrencySymbol","SGD",},
};
return contents;
}
}
| freeVM/freeVM | enhanced/archive/classlib/java6/modules/luni/src/main/java/org/apache/harmony/luni/internal/locale/Locale_zh_SG.java | Java | apache-2.0 | 1,355 |
package io.virtdata.continuous.long_double;
import io.virtdata.annotations.ThreadSafeMapper;
import org.apache.commons.statistics.distribution.ExponentialDistribution;
@ThreadSafeMapper
public class Exponential extends LongToDoubleContinuousCurve {
public Exponential(double mean, String... mods) {
super(new ExponentialDistribution(mean), mods);
}
}
| virtualdataset/metagen-java | virtdata-lib-curves4/src/main/java/io/virtdata/continuous/long_double/Exponential.java | Java | apache-2.0 | 369 |
/*
* Copyright 2007-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.gradle.api.publication.maven.internal;
import org.gradle.api.artifacts.maven.MavenPom;
public class DefaultArtifactPomFactory implements ArtifactPomFactory {
@Override
public ArtifactPom createArtifactPom(MavenPom pom) {
return new DefaultArtifactPom(pom);
}
}
| robinverduijn/gradle | subprojects/maven/src/main/java/org/gradle/api/publication/maven/internal/DefaultArtifactPomFactory.java | Java | apache-2.0 | 916 |
/*
* Copyright (c) 2015 D. David H. Akehurst
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.akehurst.example.flightSimulator.technology.network;
public interface ISubscriber {
public void update(byte[] bytes);
}
| dhakehurst/net.akehurst.application.framework.examples | net.akehurst.app.flightSystem/technology/network/src/main/java/net/akehurst/example/flightSimulator/technology/network/ISubscriber.java | Java | apache-2.0 | 745 |
package lsp.models;
/**
* Wrapper for Food
*/
public class FoodDecorator {
/**
* Field food
*/
public Food food;
/**
* New flag canReproduct
*/
protected boolean canReproduct;
/**
* Constructor
*/
public FoodDecorator(Food food) {
this.food = food;
}
/**
* Getter for field
*/
public boolean getCanReproduct() {
return canReproduct;
}
/**
* Setter for field
*/
public void setCanReproduct(boolean canReproduct) {
this.canReproduct = canReproduct;
}
} | gr0607/agrigoriev | ood/src/main/java/lsp/models/FoodDecorator.java | Java | apache-2.0 | 583 |
/*
* Copyright 2015-2016 RonCoo(http://www.roncoo.com) Group.
*
* 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.roncoo.adminlte.service.impl.dao;
import java.util.List;
import com.roncoo.adminlte.bean.entity.RcRolePermissions;
/**
* 角色-权限Dao
*
* @author LYQ
*
*/
public interface RolePermissionsDao {
RcRolePermissions selectById(long id);
List<RcRolePermissions> selectByRoleId(long id);
int insert(RcRolePermissions rcRolePermissions);
int update(RcRolePermissions rcRolePermissions);
int delectByRolePermissions(RcRolePermissions rcRolePermissions);
int deleteByRoleId(long roleId);
int countByRoleId(long roleId);
List<RcRolePermissions> listForRoleId(List<Long> idList);
}
| roncoo/roncoo-adminlte-springmvc | src/main/java/com/roncoo/adminlte/service/impl/dao/RolePermissionsDao.java | Java | apache-2.0 | 1,290 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.cache.execute;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.HashMap;
import java.util.Map;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.examples.SimpleSecurityManager;
import org.apache.geode.management.internal.cli.functions.AlterRuntimeConfigFunction;
import org.apache.geode.management.internal.cli.functions.ChangeLogLevelFunction;
import org.apache.geode.management.internal.cli.functions.CloseDurableClientFunction;
import org.apache.geode.management.internal.cli.functions.CloseDurableCqFunction;
import org.apache.geode.management.internal.cli.functions.ContinuousQueryFunction;
import org.apache.geode.management.internal.cli.functions.CreateAsyncEventQueueFunction;
import org.apache.geode.management.internal.cli.functions.CreateDefinedIndexesFunction;
import org.apache.geode.management.internal.cli.functions.CreateDiskStoreFunction;
import org.apache.geode.management.internal.cli.functions.CreateIndexFunction;
import org.apache.geode.management.internal.cli.functions.DataCommandFunction;
import org.apache.geode.management.internal.cli.functions.DeployFunction;
import org.apache.geode.management.internal.cli.functions.DescribeDiskStoreFunction;
import org.apache.geode.management.internal.cli.functions.DestroyAsyncEventQueueFunction;
import org.apache.geode.management.internal.cli.functions.DestroyDiskStoreFunction;
import org.apache.geode.management.internal.cli.functions.DestroyIndexFunction;
import org.apache.geode.management.internal.cli.functions.ExportConfigFunction;
import org.apache.geode.management.internal.cli.functions.ExportDataFunction;
import org.apache.geode.management.internal.cli.functions.ExportLogsFunction;
import org.apache.geode.management.internal.cli.functions.FetchRegionAttributesFunction;
import org.apache.geode.management.internal.cli.functions.FetchSharedConfigurationStatusFunction;
import org.apache.geode.management.internal.cli.functions.GarbageCollectionFunction;
import org.apache.geode.management.internal.cli.functions.GatewayReceiverCreateFunction;
import org.apache.geode.management.internal.cli.functions.GatewaySenderCreateFunction;
import org.apache.geode.management.internal.cli.functions.GatewaySenderDestroyFunction;
import org.apache.geode.management.internal.cli.functions.GetMemberConfigInformationFunction;
import org.apache.geode.management.internal.cli.functions.GetMemberInformationFunction;
import org.apache.geode.management.internal.cli.functions.GetRegionDescriptionFunction;
import org.apache.geode.management.internal.cli.functions.GetRegionsFunction;
import org.apache.geode.management.internal.cli.functions.GetStackTracesFunction;
import org.apache.geode.management.internal.cli.functions.GetSubscriptionQueueSizeFunction;
import org.apache.geode.management.internal.cli.functions.ImportDataFunction;
import org.apache.geode.management.internal.cli.functions.ListAsyncEventQueuesFunction;
import org.apache.geode.management.internal.cli.functions.ListDeployedFunction;
import org.apache.geode.management.internal.cli.functions.ListDiskStoresFunction;
import org.apache.geode.management.internal.cli.functions.ListDurableCqNamesFunction;
import org.apache.geode.management.internal.cli.functions.ListFunctionFunction;
import org.apache.geode.management.internal.cli.functions.ListIndexFunction;
import org.apache.geode.management.internal.cli.functions.NetstatFunction;
import org.apache.geode.management.internal.cli.functions.RebalanceFunction;
import org.apache.geode.management.internal.cli.functions.RegionAlterFunction;
import org.apache.geode.management.internal.cli.functions.RegionCreateFunction;
import org.apache.geode.management.internal.cli.functions.RegionDestroyFunction;
import org.apache.geode.management.internal.cli.functions.ShowMissingDiskStoresFunction;
import org.apache.geode.management.internal.cli.functions.ShutDownFunction;
import org.apache.geode.management.internal.cli.functions.SizeExportLogsFunction;
import org.apache.geode.management.internal.cli.functions.UndeployFunction;
import org.apache.geode.management.internal.cli.functions.UnregisterFunction;
import org.apache.geode.management.internal.cli.functions.UserFunctionExecution;
import org.apache.geode.management.internal.configuration.functions.DownloadJarFunction;
import org.apache.geode.management.internal.configuration.functions.GetClusterConfigurationFunction;
import org.apache.geode.management.internal.configuration.functions.GetRegionNamesFunction;
import org.apache.geode.management.internal.configuration.functions.RecreateCacheFunction;
import org.apache.geode.test.junit.rules.ConnectionConfiguration;
import org.apache.geode.test.junit.rules.GfshCommandRule;
import org.apache.geode.test.junit.rules.ServerStarterRule;
public class CoreFunctionSecurityTest {
private static final String RESULT_HEADER = "Message";
@ClassRule
public static ServerStarterRule server =
new ServerStarterRule().withJMXManager().withSecurityManager(SimpleSecurityManager.class)
.withRegion(RegionShortcut.PARTITION, "testRegion").withAutoStart();
@Rule
public GfshCommandRule gfsh =
new GfshCommandRule(server::getJmxPort, GfshCommandRule.PortType.jmxManager);
private static Map<Function, String> functionStringMap = new HashMap<>();
@BeforeClass
public static void setupClass() {
functionStringMap.put(new AlterRuntimeConfigFunction(), "*");
functionStringMap.put(new ChangeLogLevelFunction(), "*");
functionStringMap.put(new CloseDurableClientFunction(), "*");
functionStringMap.put(new CloseDurableCqFunction(), "*");
functionStringMap.put(new ContinuousQueryFunction(), "*");
functionStringMap.put(new CreateAsyncEventQueueFunction(), "*");
functionStringMap.put(new CreateDefinedIndexesFunction(), "*");
functionStringMap.put(new CreateDiskStoreFunction(), "*");
functionStringMap.put(new CreateIndexFunction(), "*");
functionStringMap.put(new DataCommandFunction(), "*");
functionStringMap.put(new DeployFunction(), "*");
functionStringMap.put(new DescribeDiskStoreFunction(), "*");
functionStringMap.put(new DestroyAsyncEventQueueFunction(), "*");
functionStringMap.put(new DestroyDiskStoreFunction(), "*");
functionStringMap.put(new DestroyIndexFunction(), "*");
functionStringMap.put(new ExportConfigFunction(), "*");
functionStringMap.put(new ExportDataFunction(), "*");
functionStringMap.put(new ExportLogsFunction(), "*");
functionStringMap.put(new FetchRegionAttributesFunction(), "*");
functionStringMap.put(new FetchSharedConfigurationStatusFunction(), "*");
functionStringMap.put(new GarbageCollectionFunction(), "*");
functionStringMap.put(new GatewayReceiverCreateFunction(), "*");
functionStringMap.put(new GatewaySenderCreateFunction(), "*");
functionStringMap.put(new GatewaySenderDestroyFunction(), "*");
functionStringMap.put(new GetClusterConfigurationFunction(), "*");
functionStringMap.put(new GetMemberConfigInformationFunction(), "*");
functionStringMap.put(new GetMemberInformationFunction(), "*");
functionStringMap.put(new GetRegionDescriptionFunction(), "*");
functionStringMap.put(new GetRegionsFunction(), "*");
functionStringMap.put(new GetStackTracesFunction(), "*");
functionStringMap.put(new GetSubscriptionQueueSizeFunction(), "*");
functionStringMap.put(new ImportDataFunction(), "*");
functionStringMap.put(new ListAsyncEventQueuesFunction(), "*");
functionStringMap.put(new ListDeployedFunction(), "*");
functionStringMap.put(new ListDiskStoresFunction(), "*");
functionStringMap.put(new ListDurableCqNamesFunction(), "*");
functionStringMap.put(new ListFunctionFunction(), "*");
functionStringMap.put(new ListIndexFunction(), "*");
functionStringMap.put(new NetstatFunction(), "*");
functionStringMap.put(new RebalanceFunction(), "*");
functionStringMap.put(new RegionAlterFunction(), "*");
functionStringMap.put(new RegionCreateFunction(), "*");
functionStringMap.put(new RegionDestroyFunction(), "*");
functionStringMap.put(new ShowMissingDiskStoresFunction(), "*");
functionStringMap.put(new ShutDownFunction(), "*");
functionStringMap.put(new SizeExportLogsFunction(), "*");
functionStringMap.put(new UndeployFunction(), "*");
functionStringMap.put(new UnregisterFunction(), "*");
functionStringMap.put(new GetRegionNamesFunction(), "*");
functionStringMap.put(new RecreateCacheFunction(), "*");
functionStringMap.put(new DownloadJarFunction(), "*");
functionStringMap.keySet().forEach(FunctionService::registerFunction);
}
@Test
@ConnectionConfiguration(user = "user", password = "user")
public void functionRequireExpectedPermission() {
functionStringMap.forEach((function, permission) -> {
System.out.println("function: " + function.getId() + ", permission: " + permission);
gfsh.executeAndAssertThat("execute function --id=" + function.getId())
.tableHasRowCount(1)
.tableHasRowWithValues(RESULT_HEADER, "Exception: user not authorized for " + permission)
.statusIsError();
});
}
@Test
public void userFunctionExecutionRequiresNoSecurity() {
Function function = new UserFunctionExecution();
assertThat(function.getRequiredPermissions("testRegion")).isEmpty();
}
}
| PurelyApplied/geode | geode-core/src/integrationTest/java/org/apache/geode/cache/execute/CoreFunctionSecurityTest.java | Java | apache-2.0 | 10,297 |
package demkin.sports.api.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
/**
* Description of ru.demkin.sports.api.model
*
* @author evgen1000end
* @since 22.05.2016
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class CurrentUser {
}
| Evgen1000end/SportsBot | sports-api/src/main/java/demkin/sports/api/model/CurrentUser.java | Java | apache-2.0 | 288 |
package stroom.test.common.util.test.data;
import java.util.List;
public class Rec {
final List<Field> fieldDefinitions;
final List<String> values;
public Rec(List<Field> fieldDefinitions, List<String> values) {
this.fieldDefinitions = fieldDefinitions;
this.values = values;
}
public List<Field> getFieldDefinitions() {
return fieldDefinitions;
}
public List<String> getValues() {
return values;
}
}
| gchq/stroom | stroom-test-common/src/main/java/stroom/test/common/util/test/data/Rec.java | Java | apache-2.0 | 471 |
package com.jfixby.r3.api.ui.unit.input;
public interface UserInputFactory {
ButtonSpecs newButtonSpecs ();
Button newButton (ButtonSpecs button_specs);
TouchArea newTouchArea (TouchAreaSpecs specs);
TouchAreaSpecs newTouchAreaSpecs ();
CustomInputSpecs newCustomInputSpecs ();
CustomInput newCustomInput (CustomInputSpecs button_specs);
}
| JFixby/RedTriplane | red-triplane-ui-api/src/com/jfixby/r3/api/ui/unit/input/UserInputFactory.java | Java | apache-2.0 | 355 |
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/dialogflow/v2/intent.proto
package com.google.cloud.dialogflow.v2;
/**
*
*
* <pre>
* The request message for [Intents.ListIntents][google.cloud.dialogflow.v2.Intents.ListIntents].
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.v2.ListIntentsRequest}
*/
public final class ListIntentsRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.dialogflow.v2.ListIntentsRequest)
ListIntentsRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListIntentsRequest.newBuilder() to construct.
private ListIntentsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListIntentsRequest() {
parent_ = "";
languageCode_ = "";
intentView_ = 0;
pageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListIntentsRequest();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private ListIntentsRequest(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
java.lang.String s = input.readStringRequireUtf8();
parent_ = s;
break;
}
case 18:
{
java.lang.String s = input.readStringRequireUtf8();
languageCode_ = s;
break;
}
case 24:
{
int rawValue = input.readEnum();
intentView_ = rawValue;
break;
}
case 32:
{
pageSize_ = input.readInt32();
break;
}
case 42:
{
java.lang.String s = input.readStringRequireUtf8();
pageToken_ = s;
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.v2.IntentProto
.internal_static_google_cloud_dialogflow_v2_ListIntentsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.v2.IntentProto
.internal_static_google_cloud_dialogflow_v2_ListIntentsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.v2.ListIntentsRequest.class,
com.google.cloud.dialogflow.v2.ListIntentsRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
private volatile java.lang.Object parent_;
/**
*
*
* <pre>
* Required. The agent to list all intents from.
* Format: `projects/<Project ID>/agent` or `projects/<Project
* ID>/locations/<Location ID>/agent`.
* Alternatively, you can specify the environment to list intents for.
* Format: `projects/<Project ID>/agent/environments/<Environment ID>`
* or `projects/<Project ID>/locations/<Location
* ID>/agent/environments/<Environment ID>`.
* Note: training phrases of the intents will not be returned for non-draft
* environment.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The agent to list all intents from.
* Format: `projects/<Project ID>/agent` or `projects/<Project
* ID>/locations/<Location ID>/agent`.
* Alternatively, you can specify the environment to list intents for.
* Format: `projects/<Project ID>/agent/environments/<Environment ID>`
* or `projects/<Project ID>/locations/<Location
* ID>/agent/environments/<Environment ID>`.
* Note: training phrases of the intents will not be returned for non-draft
* environment.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int LANGUAGE_CODE_FIELD_NUMBER = 2;
private volatile java.lang.Object languageCode_;
/**
*
*
* <pre>
* Optional. The language used to access language-specific data.
* If not specified, the agent's default language is used.
* For more information, see
* [Multilingual intent and entity
* data](https://cloud.google.com/dialogflow/docs/agents-multilingual#intent-entity).
* </pre>
*
* <code>string language_code = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The languageCode.
*/
@java.lang.Override
public java.lang.String getLanguageCode() {
java.lang.Object ref = languageCode_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
languageCode_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. The language used to access language-specific data.
* If not specified, the agent's default language is used.
* For more information, see
* [Multilingual intent and entity
* data](https://cloud.google.com/dialogflow/docs/agents-multilingual#intent-entity).
* </pre>
*
* <code>string language_code = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for languageCode.
*/
@java.lang.Override
public com.google.protobuf.ByteString getLanguageCodeBytes() {
java.lang.Object ref = languageCode_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
languageCode_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int INTENT_VIEW_FIELD_NUMBER = 3;
private int intentView_;
/**
*
*
* <pre>
* Optional. The resource view to apply to the returned intent.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.IntentView intent_view = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The enum numeric value on the wire for intentView.
*/
@java.lang.Override
public int getIntentViewValue() {
return intentView_;
}
/**
*
*
* <pre>
* Optional. The resource view to apply to the returned intent.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.IntentView intent_view = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The intentView.
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2.IntentView getIntentView() {
@SuppressWarnings("deprecation")
com.google.cloud.dialogflow.v2.IntentView result =
com.google.cloud.dialogflow.v2.IntentView.valueOf(intentView_);
return result == null ? com.google.cloud.dialogflow.v2.IntentView.UNRECOGNIZED : result;
}
public static final int PAGE_SIZE_FIELD_NUMBER = 4;
private int pageSize_;
/**
*
*
* <pre>
* Optional. The maximum number of items to return in a single page. By
* default 100 and at most 1000.
* </pre>
*
* <code>int32 page_size = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 5;
private volatile java.lang.Object pageToken_;
/**
*
*
* <pre>
* Optional. The next_page_token value returned from a previous list request.
* </pre>
*
* <code>string page_token = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. The next_page_token value returned from a previous list request.
* </pre>
*
* <code>string page_token = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(languageCode_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, languageCode_);
}
if (intentView_
!= com.google.cloud.dialogflow.v2.IntentView.INTENT_VIEW_UNSPECIFIED.getNumber()) {
output.writeEnum(3, intentView_);
}
if (pageSize_ != 0) {
output.writeInt32(4, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, pageToken_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(languageCode_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, languageCode_);
}
if (intentView_
!= com.google.cloud.dialogflow.v2.IntentView.INTENT_VIEW_UNSPECIFIED.getNumber()) {
size += com.google.protobuf.CodedOutputStream.computeEnumSize(3, intentView_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(4, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, pageToken_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.dialogflow.v2.ListIntentsRequest)) {
return super.equals(obj);
}
com.google.cloud.dialogflow.v2.ListIntentsRequest other =
(com.google.cloud.dialogflow.v2.ListIntentsRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (!getLanguageCode().equals(other.getLanguageCode())) return false;
if (intentView_ != other.intentView_) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + LANGUAGE_CODE_FIELD_NUMBER;
hash = (53 * hash) + getLanguageCode().hashCode();
hash = (37 * hash) + INTENT_VIEW_FIELD_NUMBER;
hash = (53 * hash) + intentView_;
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.dialogflow.v2.ListIntentsRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2.ListIntentsRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2.ListIntentsRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2.ListIntentsRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2.ListIntentsRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2.ListIntentsRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2.ListIntentsRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2.ListIntentsRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2.ListIntentsRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2.ListIntentsRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2.ListIntentsRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2.ListIntentsRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.dialogflow.v2.ListIntentsRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* The request message for [Intents.ListIntents][google.cloud.dialogflow.v2.Intents.ListIntents].
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.v2.ListIntentsRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.v2.ListIntentsRequest)
com.google.cloud.dialogflow.v2.ListIntentsRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.v2.IntentProto
.internal_static_google_cloud_dialogflow_v2_ListIntentsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.v2.IntentProto
.internal_static_google_cloud_dialogflow_v2_ListIntentsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.v2.ListIntentsRequest.class,
com.google.cloud.dialogflow.v2.ListIntentsRequest.Builder.class);
}
// Construct using com.google.cloud.dialogflow.v2.ListIntentsRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
}
@java.lang.Override
public Builder clear() {
super.clear();
parent_ = "";
languageCode_ = "";
intentView_ = 0;
pageSize_ = 0;
pageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.dialogflow.v2.IntentProto
.internal_static_google_cloud_dialogflow_v2_ListIntentsRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2.ListIntentsRequest getDefaultInstanceForType() {
return com.google.cloud.dialogflow.v2.ListIntentsRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.dialogflow.v2.ListIntentsRequest build() {
com.google.cloud.dialogflow.v2.ListIntentsRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2.ListIntentsRequest buildPartial() {
com.google.cloud.dialogflow.v2.ListIntentsRequest result =
new com.google.cloud.dialogflow.v2.ListIntentsRequest(this);
result.parent_ = parent_;
result.languageCode_ = languageCode_;
result.intentView_ = intentView_;
result.pageSize_ = pageSize_;
result.pageToken_ = pageToken_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.dialogflow.v2.ListIntentsRequest) {
return mergeFrom((com.google.cloud.dialogflow.v2.ListIntentsRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.dialogflow.v2.ListIntentsRequest other) {
if (other == com.google.cloud.dialogflow.v2.ListIntentsRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
onChanged();
}
if (!other.getLanguageCode().isEmpty()) {
languageCode_ = other.languageCode_;
onChanged();
}
if (other.intentView_ != 0) {
setIntentViewValue(other.getIntentViewValue());
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.dialogflow.v2.ListIntentsRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage =
(com.google.cloud.dialogflow.v2.ListIntentsRequest) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The agent to list all intents from.
* Format: `projects/<Project ID>/agent` or `projects/<Project
* ID>/locations/<Location ID>/agent`.
* Alternatively, you can specify the environment to list intents for.
* Format: `projects/<Project ID>/agent/environments/<Environment ID>`
* or `projects/<Project ID>/locations/<Location
* ID>/agent/environments/<Environment ID>`.
* Note: training phrases of the intents will not be returned for non-draft
* environment.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The agent to list all intents from.
* Format: `projects/<Project ID>/agent` or `projects/<Project
* ID>/locations/<Location ID>/agent`.
* Alternatively, you can specify the environment to list intents for.
* Format: `projects/<Project ID>/agent/environments/<Environment ID>`
* or `projects/<Project ID>/locations/<Location
* ID>/agent/environments/<Environment ID>`.
* Note: training phrases of the intents will not be returned for non-draft
* environment.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The agent to list all intents from.
* Format: `projects/<Project ID>/agent` or `projects/<Project
* ID>/locations/<Location ID>/agent`.
* Alternatively, you can specify the environment to list intents for.
* Format: `projects/<Project ID>/agent/environments/<Environment ID>`
* or `projects/<Project ID>/locations/<Location
* ID>/agent/environments/<Environment ID>`.
* Note: training phrases of the intents will not be returned for non-draft
* environment.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The agent to list all intents from.
* Format: `projects/<Project ID>/agent` or `projects/<Project
* ID>/locations/<Location ID>/agent`.
* Alternatively, you can specify the environment to list intents for.
* Format: `projects/<Project ID>/agent/environments/<Environment ID>`
* or `projects/<Project ID>/locations/<Location
* ID>/agent/environments/<Environment ID>`.
* Note: training phrases of the intents will not be returned for non-draft
* environment.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The agent to list all intents from.
* Format: `projects/<Project ID>/agent` or `projects/<Project
* ID>/locations/<Location ID>/agent`.
* Alternatively, you can specify the environment to list intents for.
* Format: `projects/<Project ID>/agent/environments/<Environment ID>`
* or `projects/<Project ID>/locations/<Location
* ID>/agent/environments/<Environment ID>`.
* Note: training phrases of the intents will not be returned for non-draft
* environment.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
onChanged();
return this;
}
private java.lang.Object languageCode_ = "";
/**
*
*
* <pre>
* Optional. The language used to access language-specific data.
* If not specified, the agent's default language is used.
* For more information, see
* [Multilingual intent and entity
* data](https://cloud.google.com/dialogflow/docs/agents-multilingual#intent-entity).
* </pre>
*
* <code>string language_code = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The languageCode.
*/
public java.lang.String getLanguageCode() {
java.lang.Object ref = languageCode_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
languageCode_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. The language used to access language-specific data.
* If not specified, the agent's default language is used.
* For more information, see
* [Multilingual intent and entity
* data](https://cloud.google.com/dialogflow/docs/agents-multilingual#intent-entity).
* </pre>
*
* <code>string language_code = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for languageCode.
*/
public com.google.protobuf.ByteString getLanguageCodeBytes() {
java.lang.Object ref = languageCode_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
languageCode_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. The language used to access language-specific data.
* If not specified, the agent's default language is used.
* For more information, see
* [Multilingual intent and entity
* data](https://cloud.google.com/dialogflow/docs/agents-multilingual#intent-entity).
* </pre>
*
* <code>string language_code = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The languageCode to set.
* @return This builder for chaining.
*/
public Builder setLanguageCode(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
languageCode_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The language used to access language-specific data.
* If not specified, the agent's default language is used.
* For more information, see
* [Multilingual intent and entity
* data](https://cloud.google.com/dialogflow/docs/agents-multilingual#intent-entity).
* </pre>
*
* <code>string language_code = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearLanguageCode() {
languageCode_ = getDefaultInstance().getLanguageCode();
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The language used to access language-specific data.
* If not specified, the agent's default language is used.
* For more information, see
* [Multilingual intent and entity
* data](https://cloud.google.com/dialogflow/docs/agents-multilingual#intent-entity).
* </pre>
*
* <code>string language_code = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for languageCode to set.
* @return This builder for chaining.
*/
public Builder setLanguageCodeBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
languageCode_ = value;
onChanged();
return this;
}
private int intentView_ = 0;
/**
*
*
* <pre>
* Optional. The resource view to apply to the returned intent.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.IntentView intent_view = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The enum numeric value on the wire for intentView.
*/
@java.lang.Override
public int getIntentViewValue() {
return intentView_;
}
/**
*
*
* <pre>
* Optional. The resource view to apply to the returned intent.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.IntentView intent_view = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param value The enum numeric value on the wire for intentView to set.
* @return This builder for chaining.
*/
public Builder setIntentViewValue(int value) {
intentView_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The resource view to apply to the returned intent.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.IntentView intent_view = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The intentView.
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2.IntentView getIntentView() {
@SuppressWarnings("deprecation")
com.google.cloud.dialogflow.v2.IntentView result =
com.google.cloud.dialogflow.v2.IntentView.valueOf(intentView_);
return result == null ? com.google.cloud.dialogflow.v2.IntentView.UNRECOGNIZED : result;
}
/**
*
*
* <pre>
* Optional. The resource view to apply to the returned intent.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.IntentView intent_view = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param value The intentView to set.
* @return This builder for chaining.
*/
public Builder setIntentView(com.google.cloud.dialogflow.v2.IntentView value) {
if (value == null) {
throw new NullPointerException();
}
intentView_ = value.getNumber();
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The resource view to apply to the returned intent.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.IntentView intent_view = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return This builder for chaining.
*/
public Builder clearIntentView() {
intentView_ = 0;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* Optional. The maximum number of items to return in a single page. By
* default 100 and at most 1000.
* </pre>
*
* <code>int32 page_size = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* Optional. The maximum number of items to return in a single page. By
* default 100 and at most 1000.
* </pre>
*
* <code>int32 page_size = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The pageSize to set.
* @return This builder for chaining.
*/
public Builder setPageSize(int value) {
pageSize_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The maximum number of items to return in a single page. By
* default 100 and at most 1000.
* </pre>
*
* <code>int32 page_size = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* Optional. The next_page_token value returned from a previous list request.
* </pre>
*
* <code>string page_token = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. The next_page_token value returned from a previous list request.
* </pre>
*
* <code>string page_token = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. The next_page_token value returned from a previous list request.
* </pre>
*
* <code>string page_token = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The next_page_token value returned from a previous list request.
* </pre>
*
* <code>string page_token = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The next_page_token value returned from a previous list request.
* </pre>
*
* <code>string page_token = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.dialogflow.v2.ListIntentsRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.dialogflow.v2.ListIntentsRequest)
private static final com.google.cloud.dialogflow.v2.ListIntentsRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.dialogflow.v2.ListIntentsRequest();
}
public static com.google.cloud.dialogflow.v2.ListIntentsRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListIntentsRequest> PARSER =
new com.google.protobuf.AbstractParser<ListIntentsRequest>() {
@java.lang.Override
public ListIntentsRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new ListIntentsRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<ListIntentsRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListIntentsRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2.ListIntentsRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| googleapis/java-dialogflow | proto-google-cloud-dialogflow-v2/src/main/java/com/google/cloud/dialogflow/v2/ListIntentsRequest.java | Java | apache-2.0 | 43,613 |
package com.izapolsky.crawler;
import java.net.URL;
import java.util.List;
import java.util.concurrent.Future;
/**
* Service for downloading images
*/
public interface UrlFetcher {
String SC_SKIPPED_CONCURRENCY = "-1";
String SC_IO_ERROR = "-2";
String SC_GENERIC_ERROR = "-3";
/**
* Downloads images from given urls to pre-defined location
* @param imageInfo
* @return
*/
List<Future<String>> downloadImages(List<Pair<URL, String>> imageInfo, ImageFetchedCallback callback);
}
| iggyzap/crawler-java | src/main/java/com/izapolsky/crawler/UrlFetcher.java | Java | apache-2.0 | 524 |
package org.infinispan.loaders.jpa.entity;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
/**
*
* @author <a href="mailto:[email protected]">Ray Tsang</a>
*
*/
@Entity
public class Document implements Serializable {
/**
*
*/
private static final long serialVersionUID = -81291531402946577L;
@Id
private String name;
private String title;
private String article;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getArticle() {
return article;
}
public void setArticle(String article) {
this.article = article;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((article == null) ? 0 : article.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Document other = (Document) obj;
if (article == null) {
if (other.article != null)
return false;
} else if (!article.equals(other.article))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
@Override
public String toString() {
return "Document [name=" + name + ", title=" + title + ", article="
+ article + "]";
}
}
| danberindei/infinispan-cachestore-jpa | src/test/java/org/infinispan/loaders/jpa/entity/Document.java | Java | apache-2.0 | 1,826 |
package com.heart.servlet.common;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.heart.bean.CodeResult;
import com.heart.dao.OldManDao;
import com.heart.util.GenerateCode;
import com.heart.util.SendCodeMsg;
import net.sf.json.JSONObject;
@WebServlet(name = "returnCodeServlet", urlPatterns = { "/returnCode" })
public class returnCode extends HttpServlet {
private static final long serialVersionUID = 601680363654895503L;
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("run return code..");
String phone = request.getParameter("phone");
CodeResult codeResult = new CodeResult();
if(new OldManDao().hasSamePhone(phone))
{
codeResult.setValidValue(1);
codeResult.setInfo("");
}
else {
codeResult.setValidValue(2);
String code = GenerateCode.involk();
codeResult.setInfo(code);
String sendResult = SendCodeMsg.sendMsg(phone, code);
if(!sendResult.startsWith("100"))
{
codeResult.setValidValue(3);
codeResult.setInfo("");
}
}
JSONObject object = JSONObject.fromObject(codeResult);
response.getWriter().write(object.toString());
}
}
| Mrsunsunshine/ForElder | Heart/src/com/heart/servlet/common/returnCode.java | Java | apache-2.0 | 1,443 |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.features.go;
import com.facebook.buck.core.exceptions.HumanReadableException;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.Flavor;
import com.facebook.buck.core.model.FlavorDomain;
import com.facebook.buck.core.model.InternalFlavor;
import com.facebook.buck.core.model.TargetConfiguration;
import com.facebook.buck.core.model.impl.BuildTargetPaths;
import com.facebook.buck.core.path.ForwardRelativePath;
import com.facebook.buck.core.rules.ActionGraphBuilder;
import com.facebook.buck.core.rules.BuildRule;
import com.facebook.buck.core.rules.BuildRuleParams;
import com.facebook.buck.core.rules.SourcePathRuleFinder;
import com.facebook.buck.core.rules.common.BuildableSupport;
import com.facebook.buck.core.rules.impl.MappedSymlinkTree;
import com.facebook.buck.core.rules.impl.SymlinkTree;
import com.facebook.buck.core.rules.tool.BinaryBuildRule;
import com.facebook.buck.core.sourcepath.SourcePath;
import com.facebook.buck.core.sourcepath.resolver.SourcePathResolverAdapter;
import com.facebook.buck.core.toolchain.tool.Tool;
import com.facebook.buck.core.util.graph.AbstractBreadthFirstTraversal;
import com.facebook.buck.core.util.log.Logger;
import com.facebook.buck.cxx.CxxDescriptionEnhancer;
import com.facebook.buck.cxx.toolchain.CxxPlatform;
import com.facebook.buck.cxx.toolchain.linker.Linker;
import com.facebook.buck.cxx.toolchain.linker.impl.Linkers;
import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkableGroup;
import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkableGroups;
import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkableInput;
import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkables;
import com.facebook.buck.features.go.GoListStep.ListType;
import com.facebook.buck.file.WriteFile;
import com.facebook.buck.io.file.MorePaths;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.rules.args.Arg;
import com.facebook.buck.rules.args.SanitizedArg;
import com.facebook.buck.rules.args.StringArg;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import com.google.common.io.Files;
import com.google.common.io.Resources;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
abstract class GoDescriptors {
private static final Logger LOG = Logger.get(GoDescriptors.class);
private static final String TEST_MAIN_GEN_PATH = "testmaingen.go.in";
public static final Flavor TRANSITIVE_LINKABLES_FLAVOR =
InternalFlavor.of("transitive-linkables");
@SuppressWarnings("unchecked")
public static ImmutableSet<GoLinkable> requireTransitiveGoLinkables(
BuildTarget sourceTarget,
ActionGraphBuilder graphBuilder,
GoPlatform platform,
Iterable<BuildTarget> targets,
boolean includeSelf) {
FluentIterable<GoLinkable> linkables =
FluentIterable.from(targets)
.transformAndConcat(
input -> {
BuildTarget flavoredTarget =
input.withAppendedFlavors(platform.getFlavor(), TRANSITIVE_LINKABLES_FLAVOR);
return graphBuilder.requireMetadata(flavoredTarget, ImmutableSet.class).get();
});
if (includeSelf) {
Preconditions.checkArgument(sourceTarget.getFlavors().contains(TRANSITIVE_LINKABLES_FLAVOR));
linkables =
linkables.append(
requireGoLinkable(
sourceTarget,
graphBuilder,
platform,
sourceTarget.withoutFlavors(TRANSITIVE_LINKABLES_FLAVOR)));
}
return linkables.toSet();
}
static CGoLibrary getCGoLibrary(
ActionGraphBuilder graphBuilder, GoPlatform platform, BuildTarget cgoBuildTarget) {
BuildRule rule =
graphBuilder.requireRule(cgoBuildTarget.withAppendedFlavors(platform.getFlavor()));
if (!(rule instanceof CGoLibrary)) {
throw new HumanReadableException(
"%s is not an instance of cgo_library", cgoBuildTarget.getFullyQualifiedName());
}
return (CGoLibrary) rule;
}
static GoCompile createGoCompileRule(
BuildTarget buildTarget,
ProjectFilesystem projectFilesystem,
BuildRuleParams params,
ActionGraphBuilder graphBuilder,
GoBuckConfig goBuckConfig,
Path packageName,
ImmutableSet<SourcePath> srcs,
List<String> compilerFlags,
List<String> assemblerFlags,
GoPlatform platform,
Iterable<BuildTarget> deps,
Iterable<BuildTarget> cgoDeps,
List<ListType> goListTypes) {
Preconditions.checkState(buildTarget.getFlavors().contains(platform.getFlavor()));
ImmutableSet<GoLinkable> linkables =
requireGoLinkables(buildTarget, graphBuilder, platform, deps);
ImmutableList.Builder<BuildRule> linkableDepsBuilder = ImmutableList.builder();
for (GoLinkable linkable : linkables) {
linkableDepsBuilder.addAll(linkable.getDeps(graphBuilder));
}
BuildTarget target = createSymlinkTreeTarget(buildTarget);
MappedSymlinkTree symlinkTree =
makeSymlinkTree(target, projectFilesystem, graphBuilder, linkables);
graphBuilder.addToIndex(symlinkTree);
ImmutableList.Builder<SourcePath> extraAsmOutputsBuilder = ImmutableList.builder();
ImmutableSet.Builder<SourcePath> generatedSrcBuilder = ImmutableSet.builder();
for (BuildTarget cgoBuildTarget : cgoDeps) {
CGoLibrary lib = getCGoLibrary(graphBuilder, platform, cgoBuildTarget);
generatedSrcBuilder.addAll(lib.getGeneratedGoSource());
extraAsmOutputsBuilder.add(lib.getOutput());
linkableDepsBuilder.add(lib);
}
LOG.verbose("Symlink tree for compiling %s: %s", buildTarget, symlinkTree.getLinks());
return new GoCompile(
buildTarget,
projectFilesystem,
params
.copyAppendingExtraDeps(linkableDepsBuilder.build())
.copyAppendingExtraDeps(ImmutableList.of(symlinkTree))
.copyAppendingExtraDeps(getDependenciesFromSources(graphBuilder, srcs)),
symlinkTree,
packageName,
getPackageImportMap(
goBuckConfig.getVendorPaths(),
buildTarget.getCellRelativeBasePath().getPath(),
linkables.stream()
.flatMap(input -> input.getGoLinkInput().keySet().stream())
.collect(ImmutableList.toImmutableList())),
srcs,
generatedSrcBuilder.build(),
ImmutableList.copyOf(compilerFlags),
ImmutableList.copyOf(assemblerFlags),
platform,
goBuckConfig.getGensymabis(),
extraAsmOutputsBuilder.build(),
goListTypes);
}
@VisibleForTesting
static ImmutableMap<Path, Path> getPackageImportMap(
ImmutableList<Path> globalVendorPaths,
ForwardRelativePath basePackagePath,
Iterable<Path> packageNameIter) {
Map<Path, Path> importMapBuilder = new HashMap<>();
ImmutableSortedSet<Path> packageNames = ImmutableSortedSet.copyOf(packageNameIter);
ImmutableList.Builder<Path> vendorPathsBuilder = ImmutableList.builder();
vendorPathsBuilder.addAll(globalVendorPaths);
Path prefix = Paths.get("");
for (Path component :
FluentIterable.from(new Path[] {Paths.get("")})
.append(basePackagePath.toPathDefaultFileSystem())) {
prefix = prefix.resolve(component);
vendorPathsBuilder.add(prefix.resolve("vendor"));
}
for (Path vendorPrefix : vendorPathsBuilder.build()) {
for (Path vendoredPackage : packageNames.tailSet(vendorPrefix)) {
if (!vendoredPackage.startsWith(vendorPrefix)) {
break;
}
importMapBuilder.put(MorePaths.relativize(vendorPrefix, vendoredPackage), vendoredPackage);
}
}
return ImmutableMap.copyOf(importMapBuilder);
}
static GoPlatform getPlatformForRule(
GoToolchain toolchain, GoBuckConfig buckConfig, BuildTarget target, HasGoLinkable arg) {
FlavorDomain<GoPlatform> platforms = toolchain.getPlatformFlavorDomain();
// Check target-defined platform first.
Optional<GoPlatform> platform = platforms.getValue(target);
if (platform.isPresent()) {
return platform.get();
}
// Now try the default Go toolchain platform. This shouldn't be defined
// normally.
platform = buckConfig.getDefaultPlatform().map(InternalFlavor::of).map(platforms::getValue);
if (platform.isPresent()) {
return platform.get();
}
// Next is the platform from the arg.
platform = arg.getPlatform().map(platforms::getValue);
if (platform.isPresent()) {
return platform.get();
}
// Finally, the default overall toolchain platform.
return toolchain.getDefaultPlatform();
}
static Iterable<BuildRule> getCgoLinkableDeps(Iterable<BuildRule> deps) {
ImmutableSet.Builder<BuildRule> linkables = ImmutableSet.builder();
new AbstractBreadthFirstTraversal<BuildRule>(deps) {
@Override
public Iterable<BuildRule> visit(BuildRule rule) {
if (rule instanceof CGoLibrary) {
linkables.addAll(((CGoLibrary) rule).getLinkableDeps());
return ImmutableList.of();
}
return rule.getBuildDeps();
}
}.start();
return linkables.build();
}
static ImmutableList<Arg> getCxxLinkerArgs(
ActionGraphBuilder graphBuilder,
TargetConfiguration targetConfiguration,
CxxPlatform cxxPlatform,
Iterable<BuildRule> linkables,
Linker.LinkableDepType linkStyle,
Iterable<Arg> externalLinkerFlags) {
// cgo library might have C/C++ dependencies which needs to be linked to the
// go binary. This piece of code collects the linker args from all the
// CGoLibrary cxx dependencies.
ImmutableList.Builder<Arg> argsBuilder = ImmutableList.builder();
// Get the topologically sorted native linkables.
ImmutableMap<BuildTarget, NativeLinkableGroup> roots =
NativeLinkableGroups.getNativeLinkableRoots(
linkables,
(Function<? super BuildRule, Optional<Iterable<? extends BuildRule>>>)
r -> Optional.empty());
NativeLinkableInput linkableInput =
NativeLinkables.getTransitiveNativeLinkableInput(
graphBuilder,
targetConfiguration,
Iterables.transform(
roots.values(), g -> g.getNativeLinkable(cxxPlatform, graphBuilder)),
linkStyle);
// skip setting any arg if no linkable inputs are present
if (linkableInput.getArgs().isEmpty() && Iterables.size(externalLinkerFlags) == 0) {
return argsBuilder.build();
}
// pass any platform specific or extra linker flags.
argsBuilder.addAll(
SanitizedArg.from(
cxxPlatform.getCompilerDebugPathSanitizer().sanitizer(Optional.empty()),
cxxPlatform.getLdflags()));
// add all arguments needed to link in the C/C++ platform runtime.
argsBuilder.addAll(StringArg.from(cxxPlatform.getRuntimeLdflags().get(linkStyle)));
argsBuilder.addAll(externalLinkerFlags);
argsBuilder.addAll(linkableInput.getArgs());
return argsBuilder.build();
}
static GoBinary createGoBinaryRule(
BuildTarget buildTarget,
ProjectFilesystem projectFilesystem,
BuildRuleParams params,
ActionGraphBuilder graphBuilder,
GoBuckConfig goBuckConfig,
Linker.LinkableDepType linkStyle,
Optional<GoLinkStep.LinkMode> linkMode,
ImmutableSet<SourcePath> srcs,
ImmutableSortedSet<SourcePath> resources,
List<String> compilerFlags,
List<String> assemblerFlags,
List<String> linkerFlags,
List<String> externalLinkerFlags,
GoPlatform platform) {
ImmutableList.Builder<BuildRule> extraDeps = ImmutableList.builder();
GoCompile library =
GoDescriptors.createGoCompileRule(
buildTarget.withAppendedFlavors(InternalFlavor.of("compile"), platform.getFlavor()),
projectFilesystem,
params,
graphBuilder,
goBuckConfig,
Paths.get("main"),
srcs,
compilerFlags,
assemblerFlags,
platform,
params.getDeclaredDeps().get().stream()
.map(BuildRule::getBuildTarget)
.collect(ImmutableList.toImmutableList()),
ImmutableList.of(),
Collections.singletonList(ListType.GoFiles));
graphBuilder.addToIndex(library);
extraDeps.add(library);
BuildTarget target = createTransitiveSymlinkTreeTarget(buildTarget);
MappedSymlinkTree symlinkTree =
makeSymlinkTree(
target,
projectFilesystem,
graphBuilder,
requireTransitiveGoLinkables(
buildTarget,
graphBuilder,
platform,
params.getDeclaredDeps().get().stream()
.map(BuildRule::getBuildTarget)
.collect(ImmutableList.toImmutableList()),
/* includeSelf */ false));
graphBuilder.addToIndex(symlinkTree);
extraDeps.add(symlinkTree);
LOG.verbose("Symlink tree for linking of %s: %s", buildTarget, symlinkTree);
// find all the CGoLibraries being in direct or non direct dependency to
// declared deps
Iterable<BuildRule> cgoLinkables = getCgoLinkableDeps(library.getBuildDeps());
ImmutableSet.Builder<String> extraFlags = ImmutableSet.builder();
if (linkStyle == Linker.LinkableDepType.SHARED) {
// Create a symlink tree with for all shared libraries needed by this binary.
SymlinkTree sharedLibraries =
graphBuilder.addToIndex(
CxxDescriptionEnhancer.createSharedLibrarySymlinkTree(
buildTarget,
projectFilesystem,
graphBuilder,
platform.getCxxPlatform(),
cgoLinkables,
r -> Optional.empty()));
extraDeps.add(sharedLibraries);
// Embed a origin-relative library path into the binary so it can find the shared libraries.
// The shared libraries root is absolute. Also need an absolute path to the linkOutput
Path absBinaryDir =
projectFilesystem.resolve(
BuildTargetPaths.getGenPath(projectFilesystem, buildTarget, "%s"));
extraFlags.addAll(
Linkers.iXlinker(
"-rpath",
String.format(
"%s/%s",
platform
.getCxxPlatform()
.getLd()
.resolve(graphBuilder, buildTarget.getTargetConfiguration())
.origin(),
absBinaryDir.relativize(sharedLibraries.getRoot()).toString())));
}
ImmutableList<Arg> cxxLinkerArgs =
getCxxLinkerArgs(
graphBuilder,
buildTarget.getTargetConfiguration(),
platform.getCxxPlatform(),
cgoLinkables,
linkStyle,
StringArg.from(
Iterables.concat(
platform.getExternalLinkerFlags(), extraFlags.build(), externalLinkerFlags)));
// collect build rules from args (required otherwise referenced sources
// won't build before linking)
for (Arg arg : cxxLinkerArgs) {
BuildableSupport.deriveDeps(arg, graphBuilder).forEach(extraDeps::add);
}
if (!linkMode.isPresent()) {
linkMode =
Optional.of(
(cxxLinkerArgs.size() > 0)
? GoLinkStep.LinkMode.EXTERNAL
: GoLinkStep.LinkMode.INTERNAL);
}
Linker cxxLinker =
platform
.getCxxPlatform()
.getLd()
.resolve(graphBuilder, buildTarget.getTargetConfiguration());
return new GoBinary(
buildTarget,
projectFilesystem,
params
.withDeclaredDeps(
ImmutableSortedSet.<BuildRule>naturalOrder()
.addAll(graphBuilder.filterBuildRuleInputs(symlinkTree.getLinks().values()))
.addAll(extraDeps.build())
.addAll(BuildableSupport.getDepsCollection(cxxLinker, graphBuilder))
.build())
.withoutExtraDeps(),
resources,
symlinkTree,
library,
platform.getLinker(),
cxxLinker,
linkMode.get(),
ImmutableList.copyOf(linkerFlags),
cxxLinkerArgs,
platform);
}
static Tool getTestMainGenerator(
GoBuckConfig goBuckConfig,
GoPlatform platform,
BuildTarget sourceBuildTarget,
ProjectFilesystem projectFilesystem,
BuildRuleParams sourceParams,
ActionGraphBuilder graphBuilder) {
Optional<Tool> configTool = platform.getTestMainGen();
if (configTool.isPresent()) {
return configTool.get();
}
// TODO(mikekap): Make a single test main gen, rather than one per test. The generator itself
// doesn't vary per test.
BuildRule generator =
graphBuilder.computeIfAbsent(
sourceBuildTarget.withFlavors(InternalFlavor.of("make-test-main-gen")),
generatorTarget -> {
WriteFile writeFile =
(WriteFile)
graphBuilder.computeIfAbsent(
sourceBuildTarget.withAppendedFlavors(
InternalFlavor.of("test-main-gen-source")),
generatorSourceTarget ->
new WriteFile(
generatorSourceTarget,
projectFilesystem,
extractTestMainGenerator(),
BuildTargetPaths.getGenPath(
projectFilesystem, generatorSourceTarget, "%s/main.go"),
/* executable */ false));
return createGoBinaryRule(
generatorTarget,
projectFilesystem,
sourceParams
.withoutDeclaredDeps()
.withExtraDeps(ImmutableSortedSet.of(writeFile)),
graphBuilder,
goBuckConfig,
Linker.LinkableDepType.STATIC_PIC,
Optional.empty(),
ImmutableSet.of(writeFile.getSourcePathToOutput()),
ImmutableSortedSet.of(),
ImmutableList.of(),
ImmutableList.of(),
ImmutableList.of(),
ImmutableList.of(),
platform);
});
return ((BinaryBuildRule) generator).getExecutableCommand();
}
private static String extractTestMainGenerator() {
try {
return Resources.toString(
Resources.getResource(GoDescriptors.class, TEST_MAIN_GEN_PATH), Charsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static BuildTarget createSymlinkTreeTarget(BuildTarget source) {
return source.withAppendedFlavors(InternalFlavor.of("symlink-tree"));
}
private static BuildTarget createTransitiveSymlinkTreeTarget(BuildTarget source) {
return source.withAppendedFlavors(InternalFlavor.of("transitive-symlink-tree"));
}
private static GoLinkable requireGoLinkable(
BuildTarget sourceRule,
ActionGraphBuilder graphBuilder,
GoPlatform platform,
BuildTarget target) {
Optional<GoLinkable> linkable =
graphBuilder.requireMetadata(
target.withAppendedFlavors(platform.getFlavor()), GoLinkable.class);
if (!linkable.isPresent()) {
throw new HumanReadableException(
"%s (needed for %s) is not an instance of go_library!",
target.getFullyQualifiedName(), sourceRule.getFullyQualifiedName());
}
return linkable.get();
}
private static ImmutableSet<GoLinkable> requireGoLinkables(
BuildTarget sourceTarget,
ActionGraphBuilder graphBuilder,
GoPlatform platform,
Iterable<BuildTarget> targets) {
ImmutableSet.Builder<GoLinkable> linkables = ImmutableSet.builder();
new AbstractBreadthFirstTraversal<BuildTarget>(targets) {
@Override
public Iterable<BuildTarget> visit(BuildTarget target) {
GoLinkable linkable = requireGoLinkable(sourceTarget, graphBuilder, platform, target);
linkables.add(linkable);
return linkable.getExportedDeps();
}
}.start();
return linkables.build();
}
/**
* Make sure that if any srcs elements are a build rule, we add it as a dependency, so we wait for
* it to finish running before using the source
*/
private static ImmutableList<BuildRule> getDependenciesFromSources(
SourcePathRuleFinder ruleFinder, ImmutableSet<SourcePath> srcs) {
return srcs.stream()
.map(ruleFinder::getRule)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(ImmutableList.toImmutableList());
}
private static MappedSymlinkTree makeSymlinkTree(
BuildTarget buildTarget,
ProjectFilesystem projectFilesystem,
SourcePathRuleFinder ruleFinder,
ImmutableSet<GoLinkable> linkables) {
ImmutableMap<Path, SourcePath> treeMap;
try {
treeMap =
linkables.stream()
.flatMap(linkable -> linkable.getGoLinkInput().entrySet().stream())
.collect(
ImmutableMap.toImmutableMap(
entry ->
getPathInSymlinkTree(
ruleFinder.getSourcePathResolver(), entry.getKey(), entry.getValue()),
entry -> entry.getValue()));
} catch (IllegalArgumentException ex) {
throw new HumanReadableException(
ex,
"Multiple go targets have the same package name when compiling %s",
buildTarget.getFullyQualifiedName());
}
Path root = BuildTargetPaths.getScratchPath(projectFilesystem, buildTarget, "__%s__tree");
return new MappedSymlinkTree("go_linkable", buildTarget, projectFilesystem, root, treeMap);
}
/**
* @return the path in the symlink tree as used by the compiler. This is usually the package name
* + '.a'.
*/
private static Path getPathInSymlinkTree(
SourcePathResolverAdapter resolver, Path goPackageName, SourcePath ruleOutput) {
Path output = resolver.getRelativePath(ruleOutput);
String extension = Files.getFileExtension(output.toString());
return Paths.get(goPackageName + (extension.equals("") ? "" : "." + extension));
}
}
| zpao/buck | src/com/facebook/buck/features/go/GoDescriptors.java | Java | apache-2.0 | 23,734 |
/**
* Copyright (C) 2011 Flamingo Project (http://www.cloudine.io).
* <p/>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p/>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p/>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.exem.flamingo.web.oozie.workflow.tree;
import org.exem.flamingo.shared.core.exception.ServiceException;
import org.exem.flamingo.shared.core.security.SessionUtils;
import org.exem.flamingo.web.model.rest.NodeType;
import org.exem.flamingo.web.model.rest.Tree;
import org.exem.flamingo.web.model.rest.TreeType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Tree Service.
*
* @author Byoung Gon, Kim
* @since 0.1
*/
@Component
public class TreeServiceImpl implements TreeService {
/**
* Tree Repository
*/
@Autowired
private TreeRepository treeRepository;
@Override
public int rename(Tree tree) {
return treeRepository.update(tree);
}
@Override
public boolean delete(long id) {
if (treeRepository.getChilds(id) != null && treeRepository.getChilds(id).size() > 0) {
throw new ServiceException("Failed to delete a tree node.");
}
return treeRepository.delete(id) > 0;
}
@Override
public Tree create(Tree parent, Tree child, NodeType nodeType) {
Map<String, Object> map = new HashMap<>();
map.put("id", null);
map.put("name", child.getName());
map.put("treeType", child.getTreeType());
map.put("nodeType", child.getNodeType());
map.put("root", false);
map.put("username", child.getUsername());
map.put("parentId", parent.getId());
treeRepository.insertByMap(map);
child.setId((Long) map.get("id"));
return child;
}
@Override
public Tree createRoot(TreeType treeType, String username) {
if (!treeRepository.existRoot(treeType, username)) {
Tree tree = new Tree("/");
tree.setTreeType(treeType);
tree.setNodeType(NodeType.FOLDER);
tree.setRoot(true);
tree.setUsername(username);
treeRepository.insert(tree);
return tree;
}
return treeRepository.getRoot(treeType, username);
}
@Override
public boolean checkSameNode(Tree parent, Tree child, TreeType treeType, NodeType nodeType) {
if (nodeType == NodeType.FOLDER) {
return this.existSubFolder(new Tree(parent.getId()), child.getName(), treeType);
} else {
return this.existSubItem(new Tree(parent.getId()), child.getName(), treeType);
}
}
@Override
public boolean existSubItem(Tree selectedNode, String name, TreeType treeType) {
return true; // FIXME
}
@Override
public boolean existSubFolder(Tree selectedNode, String name, TreeType treeType) {
return true; // FIXME
}
@Override
public Tree getRoot(TreeType treeType, String username) {
return treeRepository.getRoot(treeType, username);
}
@Override
public List<Tree> getChilds(long parentId) {
return treeRepository.getChilds(parentId);
}
@Override
public Tree get(long id) {
return treeRepository.select(id);
}
@Override
public void move(String from, String to, TreeType type) {
Tree source = treeRepository.select(Long.parseLong(from));
Tree target;
if ("/".equals(to)) {
target = treeRepository.getRoot(type, SessionUtils.getUsername());
} else {
target = treeRepository.select(Long.parseLong(to));
}
source.setParent(target);
treeRepository.update(source);
}
@Override
public List<Tree> getWorkflowChilds(long parentId) {
return treeRepository.selectWorkflowChilds(parentId);
}
public void setTreeRepository(TreeRepository treeRepository) {
this.treeRepository = treeRepository;
}
}
| EXEM-OSS/flamingo | flamingo-web/src/main/java/org/exem/flamingo/web/oozie/workflow/tree/TreeServiceImpl.java | Java | apache-2.0 | 4,594 |
/*
* =================================================================================================
* Copyright (C) 2014 Martin Albedinsky
* =================================================================================================
* Licensed under the Apache License, Version 2.0 or later (further "License" only).
* -------------------------------------------------------------------------------------------------
* You may use this file only in compliance with the License. More details and copy of this License
* you may obtain at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* You can redistribute, modify or publish any part of the code written within this file but as it
* is described in the License, the software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES or CONDITIONS OF ANY KIND.
*
* See the License for the specific language governing permissions and limitations under the License.
* =================================================================================================
*/
package com.albedinsky.android.ui.examples.fragment.components;
import com.albedinsky.android.support.fragment.annotation.ActionBarOptions;
import com.albedinsky.android.support.fragment.annotation.ContentView;
import com.albedinsky.android.ui.examples.R;
import com.albedinsky.android.ui.examples.fragment.BaseExamplesFragment;
/**
* @author Martin Albedinsky
*/
@ContentView(R.layout.fragment_components_sliders)
@ActionBarOptions(title = R.string.components_navigation_sliders)
public final class SlidersFragment extends BaseExamplesFragment {
@SuppressWarnings("unused")
private static final String TAG = "SlidersFragment";
}
| android-libraries/android_ui | examples/src/main/java/com/albedinsky/android/ui/examples/fragment/components/SlidersFragment.java | Java | apache-2.0 | 1,754 |
/*
* SamplingFiltering.java
*
* @author Deepayan Bhowmik
*/
package Embedding;
public class SamplingFiltering {
public void SamplingFiltering() {
/* This class and function organisaes all the filtering and up / down sampling parameters.
This particular function is just to check all the values. No operation so far ... Deepayan says so :-)
*/
}
public double[] Lshift(double[] image){
double[] imshift = new double[image.length];
for(int i=1; i<image.length; i++){
imshift[i-1] = image[i];
}
imshift[image.length-1] = image[0];
return imshift;
}
public double[] Rshift(double[] image){
double[] imshift = new double[image.length];
for(int i=1; i<image.length; i++){
imshift[i] = image[i-1];
}
imshift[0] = image[image.length-1];
return imshift;
}
public double[] Highpass(double[] filter_coeff, double[] image){
double[] pixel_coeff = Downsample(ConvHL(filter_coeff,Lshift(image)));
return pixel_coeff;
}
public double[] Lowpass(double[] filter_coeff, double[] image){
double[] pixel_coeff = Downsample(ConvLH(filter_coeff,image));
return pixel_coeff;
}
public double[] InvHighpass(double[] filter_coeff, double[] image){
double[] pixel = ConvLH(filter_coeff, Rshift(Upsample(image)));
return pixel;
}
public double[] InvLowpass(double[] filter_coeff, double[] image){
double[] pixel = ConvHL(filter_coeff,Upsample(image));
return pixel;
}
public double[] ConvLH(double[] filter_coeff, double[] image){
double[] padded_image = new double[image.length+filter_coeff.length];
for(int i=0; i<image.length; i++){
padded_image[i] = image[i];
}
for(int j=image.length; j<(image.length+filter_coeff.length); j++){
padded_image[j] = image[j-image.length];
}
Convolution func = new Convolution();
double[] padout_coeff = func.Convolution(filter_coeff,padded_image);
double[] pixel_coeff_dw = new double[image.length];
for(int i=0;i<image.length;i++){
pixel_coeff_dw[i] = padout_coeff[filter_coeff.length-1+i];
}
return pixel_coeff_dw;
}
public double[] ConvHL(double[] filter_coeff, double[] image){
double[] padded_image = new double[image.length+filter_coeff.length];
for(int i=0; i<(filter_coeff.length);i++){
padded_image[i] = image[(image.length-filter_coeff.length) + i];
}
for(int j=(filter_coeff.length); j<(image.length+filter_coeff.length);j++){
padded_image[j] = image[j-(filter_coeff.length)];
}
Convolution func = new Convolution();
double[] padout_coeff = func.Convolution(filter_coeff,padded_image);
double[] pixel_coeff_dw = new double[image.length];
for(int i=0;i<image.length;i++){
pixel_coeff_dw[i] = padout_coeff[filter_coeff.length+i];
}
return pixel_coeff_dw;
}
public double[] Downsample(double[] image_coeff){
double[] image_ds = new double[image_coeff.length/2];
for(int i=0; i<image_coeff.length/2; i++){
image_ds[i] = image_coeff[i*2];
}
return image_ds;
}
public double[] Upsample(double[] image_coeff){
double[] image_us = new double[image_coeff.length*2];
for(int i=0; i<image_coeff.length*2; i++){
if((i%2)==0){
image_us[i] = image_coeff[i/2];
} else{
image_us[i] = 0;
}
}
return image_us;
}
}
| dbhowmik/scalableWM | RequantisationBlindWM/src/Embedding/SamplingFiltering.java | Java | apache-2.0 | 3,971 |
package com.sap.mlt.xliff12.api.attribute;
import com.sap.mlt.xliff12.api.base.XliffAttribute;
import com.sap.mlt.xliff12.api.element.structural.Target;
import com.sap.mlt.xliff12.api.element.structural.TransUnit;
/**
* Minimum width - The minimum width for the {@link Target} of a
* {@link TransUnit}. This could be interpreted as lines, pixels, or any other
* relevant unit. The unit is determined by the {@link SizeUnit} attribute,
* which defaults to pixel.
*
* @author D049314
*/
public interface MinWidth extends XliffAttribute {
/**
* The attribute's name.
*/
static final String NAME = "minwidth";
}
| SAP/xliff-1-2 | com.sap.mlt.xliff12.api/src/main/java/com/sap/mlt/xliff12/api/attribute/MinWidth.java | Java | apache-2.0 | 648 |
/*
* Copyright (c) 2015 EMC Corporation
* All Rights Reserved
*/
package com.emc.storageos.model.network;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.List;
/**
* This is a list of the SAN zones returned from the NetworkSystem.
*/
@XmlRootElement(name = "san_zones")
public class SanZones {
private List<SanZone> zones;
public SanZones() {
}
public SanZones(List<SanZone> zones) {
this.zones = zones;
}
/**
* A list of San Zones. Each zone has a name and a list of zone members.
*
*/
@XmlElement(name = "san_zone")
public List<SanZone> getZones() {
if (zones == null) {
zones = new ArrayList<SanZone>();
}
return zones;
}
public void setZones(List<SanZone> zones) {
this.zones = zones;
}
}
| emcvipr/controller-client-java | models/src/main/java/com/emc/storageos/model/network/SanZones.java | Java | apache-2.0 | 909 |
/**
* Copyright 2011-2021 Asakusa Framework 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 com.asakusafw.vocabulary.flow;
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;
/**
* An annotation for flow-part classes.
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FlowPart {
// no members
}
| asakusafw/asakusafw | dsl-project/asakusa-dsl-vocabulary/src/main/java/com/asakusafw/vocabulary/flow/FlowPart.java | Java | apache-2.0 | 1,027 |
package com.francelabs.datafari.ldap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.naming.NamingException;
import javax.naming.ldap.LdapContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class LdapUsers {
private static LdapUsers instance = null;
private final Map<String, String> usersDomain;
private final ScheduledExecutorService scheduler;
private static final Logger logger = LogManager.getLogger(LdapUsers.class);
public static synchronized LdapUsers getInstance() {
if (instance == null) {
instance = new LdapUsers();
}
return instance;
}
private LdapUsers() {
usersDomain = new HashMap<>();
scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(new SweepDomains(), 1, 1, TimeUnit.HOURS);
}
public synchronized String getUserDomain(final String username) {
if (usersDomain.containsKey(username)) {
return usersDomain.get(username);
} else {
final List<LdapRealm> realms = LdapConfig.getActiveDirectoryRealms();
for (final LdapRealm realm : realms) {
try {
final LdapContext context = LdapUtils.getLdapContext(realm.getConnectionURL(), realm.getConnectionName(), realm.getDeobfuscatedConnectionPassword());
for (final String userBase : realm.getUserBases()) {
try {
logger.debug("Testing user " + username + " on base " + userBase);
if (LdapUtils.checkUser(username, realm.getUserSearchAttribute(), userBase, context)) {
logger.debug("User " + username + " found in base " + userBase);
final String domain = realm.getDomainName();
logger.debug("Found domain " + domain + " for user " + username);
usersDomain.put(username, domain);
return domain;
} else {
logger.debug("User " + username + " not found in base " + userBase);
}
} catch (final NamingException e) {
logger.error("Error when trying to find user \"" + username + "\" into realm " + realm.getConnectionURL() + " in userBase " + userBase, e);
}
}
context.close();
} catch (final Exception e) {
logger.error("Search error for user " + username + " into realm " + realm.getConnectionURL(), e);
}
}
usersDomain.put(username, "");
return null;
}
}
public void stopSweep() {
scheduler.shutdownNow();
}
private final class SweepDomains implements Runnable {
@Override
public void run() {
LdapUsers.getInstance().usersDomain.clear();
}
}
}
| francelabs/datafari | datafari-core/src/main/java/com/francelabs/datafari/ldap/LdapUsers.java | Java | apache-2.0 | 2,867 |
// 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 boxconnector.actions;
import static boxconnector.proxies.microflows.Microflows.updateCollaborationImpl;
import com.mendix.systemwideinterfaces.core.IContext;
import com.mendix.webui.CustomJavaAction;
import com.mendix.systemwideinterfaces.core.IMendixObject;
/**
* Used to edit an existing collaboration.
*
* Required
* BoxCollaboration
* The _id attribute is required.
*
* Optional
* UpdateRole: The access level of this collaboration.
*
* UpdateStatus: Whether this collaboration has been accepted
* This can be set to accepted or rejected by the accessible_by user if the status is pending
*
* UpdateExpiresAt: The time in the future this collaboration will expire
*
* UpdateCanViewPath: Whether view path collaboration feature is enabled or not.
*/
public class UpdateCollaboration extends CustomJavaAction<IMendixObject>
{
private IMendixObject __boxCollaboration;
private boxconnector.proxies.BoxCollaboration boxCollaboration;
private boxconnector.proxies.CollaborationRole updateRole;
private boxconnector.proxies.CollaborationStatus updateStatus;
private java.util.Date updateExpiresAt;
private boxconnector.proxies.BooleanParameter updateCanViewPath;
private IMendixObject __accessToken;
private boxconnector.proxies.AccessToken accessToken;
private IMendixObject __asUser;
private boxconnector.proxies.BoxUser asUser;
public UpdateCollaboration(IContext context, IMendixObject boxCollaboration, java.lang.String updateRole, java.lang.String updateStatus, java.util.Date updateExpiresAt, java.lang.String updateCanViewPath, IMendixObject accessToken, IMendixObject asUser)
{
super(context);
this.__boxCollaboration = boxCollaboration;
this.updateRole = updateRole == null ? null : boxconnector.proxies.CollaborationRole.valueOf(updateRole);
this.updateStatus = updateStatus == null ? null : boxconnector.proxies.CollaborationStatus.valueOf(updateStatus);
this.updateExpiresAt = updateExpiresAt;
this.updateCanViewPath = updateCanViewPath == null ? null : boxconnector.proxies.BooleanParameter.valueOf(updateCanViewPath);
this.__accessToken = accessToken;
this.__asUser = asUser;
}
@Override
public IMendixObject executeAction() throws Exception
{
this.boxCollaboration = __boxCollaboration == null ? null : boxconnector.proxies.BoxCollaboration.initialize(getContext(), __boxCollaboration);
this.accessToken = __accessToken == null ? null : boxconnector.proxies.AccessToken.initialize(getContext(), __accessToken);
this.asUser = __asUser == null ? null : boxconnector.proxies.BoxUser.initialize(getContext(), __asUser);
// BEGIN USER CODE
boxconnector.proxies.BoxCollaboration boxC = updateCollaborationImpl(getContext(), this.boxCollaboration, this.updateStatus, this.updateCanViewPath, this.updateRole, this.updateExpiresAt, this.accessToken, this.asUser);
if (boxC != null)
return boxC.getMendixObject();
else
return null;
// END USER CODE
}
/**
* Returns a string representation of this action
*/
@Override
public java.lang.String toString()
{
return "UpdateCollaboration";
}
// BEGIN EXTRA CODE
// END EXTRA CODE
}
| Nokavision/BoxConnector | javasource/boxconnector/actions/UpdateCollaboration.java | Java | apache-2.0 | 3,645 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.