code
stringlengths 10
749k
| repo_name
stringlengths 5
108
| path
stringlengths 7
333
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 10
749k
|
---|---|---|---|---|---|
/**
* Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com).
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.jboot.support.metric.annotation;
import java.lang.annotation.*;
@Documented
@Target(ElementType.METHOD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface EnableMetricTimer {
String value() default "";
}
|
yangfuhai/jboot
|
src/main/java/io/jboot/support/metric/annotation/EnableMetricTimer.java
|
Java
|
apache-2.0
| 888 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.fhuss.kafka.streams.cep.core.state.internal;
import java.util.Objects;
/**
* Class for aggregated state.
*
* @param <K> the record key type.
*/
public class Aggregated<K> {
private final K key;
private final Aggregate aggregate;
/**
* Creates a new {@link Aggregated} instance.
* @param key the record key
* @param aggregate the instance of {@link Aggregate}.
*/
public Aggregated(final K key, final Aggregate aggregate) {
this.key = key;
this.aggregate = aggregate;
}
public K getKey() {
return key;
}
public Aggregate getAggregate() {
return aggregate;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Aggregated<?> that = (Aggregated<?>) o;
return Objects.equals(key, that.key) &&
Objects.equals(aggregate, that.aggregate);
}
@Override
public int hashCode() {
return Objects.hash(key, aggregate);
}
@Override
public String toString() {
return "Aggregated{" +
"key=" + key +
", aggregate=" + aggregate +
'}';
}
}
|
fhussonnois/kafkastreams-cep
|
core/src/main/java/com/github/fhuss/kafka/streams/cep/core/state/internal/Aggregated.java
|
Java
|
apache-2.0
| 2,076 |
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.apigateway.model.transform;
import java.util.List;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.apigateway.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* UpdateMethodResponseRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class UpdateMethodResponseRequestMarshaller {
private static final MarshallingInfo<String> RESTAPIID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PATH)
.marshallLocationName("restapi_id").build();
private static final MarshallingInfo<String> RESOURCEID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PATH)
.marshallLocationName("resource_id").build();
private static final MarshallingInfo<String> HTTPMETHOD_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PATH)
.marshallLocationName("http_method").build();
private static final MarshallingInfo<String> STATUSCODE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PATH)
.marshallLocationName("status_code").build();
private static final MarshallingInfo<List> PATCHOPERATIONS_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("patchOperations").build();
private static final UpdateMethodResponseRequestMarshaller instance = new UpdateMethodResponseRequestMarshaller();
public static UpdateMethodResponseRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(UpdateMethodResponseRequest updateMethodResponseRequest, ProtocolMarshaller protocolMarshaller) {
if (updateMethodResponseRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(updateMethodResponseRequest.getRestApiId(), RESTAPIID_BINDING);
protocolMarshaller.marshall(updateMethodResponseRequest.getResourceId(), RESOURCEID_BINDING);
protocolMarshaller.marshall(updateMethodResponseRequest.getHttpMethod(), HTTPMETHOD_BINDING);
protocolMarshaller.marshall(updateMethodResponseRequest.getStatusCode(), STATUSCODE_BINDING);
protocolMarshaller.marshall(updateMethodResponseRequest.getPatchOperations(), PATCHOPERATIONS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
jentfoo/aws-sdk-java
|
aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/model/transform/UpdateMethodResponseRequestMarshaller.java
|
Java
|
apache-2.0
| 3,397 |
package org.aksw.servicecat.web.api;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import org.aksw.servicecat.core.ServiceAnalyzerProcessor;
import org.springframework.beans.factory.annotation.Autowired;
@org.springframework.stereotype.Service
@Path("/services")
public class ServletServiceApi {
@Autowired
private ServiceAnalyzerProcessor processor;
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/put")
public String registerService(@QueryParam("url") String serviceUrl)
{
processor.process(serviceUrl);
String result = "{}";
return result;
}
}
|
GeoKnow/SparqlServiceCatalogue
|
servicecat-webapp/src/main/java/org/aksw/servicecat/web/api/ServletServiceApi.java
|
Java
|
apache-2.0
| 728 |
/*
* 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.macie2.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.macie2.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* AccountDetailMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class AccountDetailMarshaller {
private static final MarshallingInfo<String> ACCOUNTID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("accountId").build();
private static final MarshallingInfo<String> EMAIL_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("email").build();
private static final AccountDetailMarshaller instance = new AccountDetailMarshaller();
public static AccountDetailMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(AccountDetail accountDetail, ProtocolMarshaller protocolMarshaller) {
if (accountDetail == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(accountDetail.getAccountId(), ACCOUNTID_BINDING);
protocolMarshaller.marshall(accountDetail.getEmail(), EMAIL_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
aws/aws-sdk-java
|
aws-java-sdk-macie2/src/main/java/com/amazonaws/services/macie2/model/transform/AccountDetailMarshaller.java
|
Java
|
apache-2.0
| 2,226 |
package org.apache.rya.indexing.external;
import java.net.UnknownHostException;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.List;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.TableExistsException;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.client.mock.MockInstance;
import org.apache.accumulo.core.client.security.tokens.PasswordToken;
import org.apache.rya.indexing.pcj.storage.PcjException;
import org.apache.rya.indexing.pcj.storage.accumulo.PcjVarOrderFactory;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.openrdf.model.URI;
import org.openrdf.model.impl.LiteralImpl;
import org.openrdf.model.impl.URIImpl;
import org.openrdf.model.vocabulary.RDF;
import org.openrdf.model.vocabulary.RDFS;
import org.openrdf.query.BindingSet;
import org.openrdf.query.MalformedQueryException;
import org.openrdf.query.QueryEvaluationException;
import org.openrdf.query.QueryLanguage;
import org.openrdf.query.QueryResultHandlerException;
import org.openrdf.query.TupleQueryResultHandler;
import org.openrdf.query.TupleQueryResultHandlerException;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.sail.SailRepository;
import org.openrdf.repository.sail.SailRepositoryConnection;
import org.openrdf.sail.SailException;
import com.google.common.base.Optional;
import org.apache.rya.api.persist.RyaDAOException;
import org.apache.rya.rdftriplestore.inference.InferenceEngineException;
public class AccumuloConstantPcjIntegrationTest {
private SailRepositoryConnection conn, pcjConn;
private SailRepository repo, pcjRepo;
private Connector accCon;
String prefix = "table_";
String tablename = "table_INDEX_";
URI obj, obj2, subclass, subclass2, talksTo;
@Before
public void init() throws RepositoryException,
TupleQueryResultHandlerException, QueryEvaluationException,
MalformedQueryException, AccumuloException,
AccumuloSecurityException, TableExistsException,
TableNotFoundException, RyaDAOException, InferenceEngineException,
NumberFormatException, UnknownHostException, SailException {
repo = PcjIntegrationTestingUtil.getNonPcjRepo(prefix, "instance");
conn = repo.getConnection();
pcjRepo = PcjIntegrationTestingUtil.getPcjRepo(prefix, "instance");
pcjConn = pcjRepo.getConnection();
final URI sub = new URIImpl("uri:entity");
subclass = new URIImpl("uri:class");
obj = new URIImpl("uri:obj");
talksTo = new URIImpl("uri:talksTo");
conn.add(sub, RDF.TYPE, subclass);
conn.add(sub, RDFS.LABEL, new LiteralImpl("label"));
conn.add(sub, talksTo, obj);
final URI sub2 = new URIImpl("uri:entity2");
subclass2 = new URIImpl("uri:class2");
obj2 = new URIImpl("uri:obj2");
conn.add(sub2, RDF.TYPE, subclass2);
conn.add(sub2, RDFS.LABEL, new LiteralImpl("label2"));
conn.add(sub2, talksTo, obj2);
accCon = new MockInstance("instance").getConnector("root",new PasswordToken(""));
}
@After
public void close() throws RepositoryException, AccumuloException,
AccumuloSecurityException, TableNotFoundException {
PcjIntegrationTestingUtil.closeAndShutdown(conn, repo);
PcjIntegrationTestingUtil.closeAndShutdown(pcjConn, pcjRepo);
PcjIntegrationTestingUtil.deleteCoreRyaTables(accCon, prefix);
PcjIntegrationTestingUtil.deleteIndexTables(accCon, 2, prefix);
}
@Test
public void testEvaluateTwoIndexVarInstantiate1() throws PcjException,
RepositoryException, AccumuloException, AccumuloSecurityException,
TableNotFoundException, TableExistsException,
MalformedQueryException, SailException, QueryEvaluationException,
TupleQueryResultHandlerException {
final URI superclass = new URIImpl("uri:superclass");
final URI superclass2 = new URIImpl("uri:superclass2");
conn.add(subclass, RDF.TYPE, superclass);
conn.add(subclass2, RDF.TYPE, superclass2);
conn.add(obj, RDFS.LABEL, new LiteralImpl("label"));
conn.add(obj2, RDFS.LABEL, new LiteralImpl("label2"));
conn.add(obj, RDFS.LABEL, new LiteralImpl("label"));
conn.add(obj2, RDFS.LABEL, new LiteralImpl("label2"));
final String indexSparqlString = ""//
+ "SELECT ?dog ?pig ?duck " //
+ "{" //
+ " ?pig a ?dog . "//
+ " ?pig <http://www.w3.org/2000/01/rdf-schema#label> ?duck "//
+ "}";//
final String indexSparqlString2 = ""//
+ "SELECT ?o ?f ?e ?c ?l " //
+ "{" //
+ " ?e <uri:talksTo> ?o . "//
+ " ?o <http://www.w3.org/2000/01/rdf-schema#label> ?l. "//
+ " ?c a ?f . " //
+ "}";//
final String queryString = ""//
+ "SELECT ?c ?l ?f ?o " //
+ "{" //
+ " <uri:entity> a ?c . "//
+ " <uri:entity> <http://www.w3.org/2000/01/rdf-schema#label> ?l. "//
+ " <uri:entity> <uri:talksTo> ?o . "//
+ " ?o <http://www.w3.org/2000/01/rdf-schema#label> ?l. "//
+ " ?c a ?f . " //
+ "}";//
PcjIntegrationTestingUtil.createAndPopulatePcj(conn, accCon, tablename + 1,
indexSparqlString, new String[] { "dog", "pig", "duck" },
Optional.<PcjVarOrderFactory> absent());
PcjIntegrationTestingUtil.createAndPopulatePcj(conn, accCon, tablename + 2,
indexSparqlString2, new String[] { "o", "f", "e", "c", "l" },
Optional.<PcjVarOrderFactory> absent());
final CountingResultHandler crh1 = new CountingResultHandler();
final CountingResultHandler crh2 = new CountingResultHandler();
conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
.evaluate(crh1);
PcjIntegrationTestingUtil.deleteCoreRyaTables(accCon, prefix);
pcjConn.prepareTupleQuery(QueryLanguage.SPARQL, queryString).evaluate(crh2);
Assert.assertEquals(crh1.getCount(), crh2.getCount());
}
@Test
public void testEvaluateThreeIndexVarInstantiate() throws PcjException,
RepositoryException, AccumuloException, AccumuloSecurityException,
TableNotFoundException, TableExistsException,
MalformedQueryException, SailException, QueryEvaluationException,
TupleQueryResultHandlerException {
final URI superclass = new URIImpl("uri:superclass");
final URI superclass2 = new URIImpl("uri:superclass2");
final URI sub = new URIImpl("uri:entity");
subclass = new URIImpl("uri:class");
obj = new URIImpl("uri:obj");
talksTo = new URIImpl("uri:talksTo");
final URI howlsAt = new URIImpl("uri:howlsAt");
final URI subType = new URIImpl("uri:subType");
conn.add(subclass, RDF.TYPE, superclass);
conn.add(subclass2, RDF.TYPE, superclass2);
conn.add(obj, RDFS.LABEL, new LiteralImpl("label"));
conn.add(obj2, RDFS.LABEL, new LiteralImpl("label2"));
conn.add(sub, howlsAt, superclass);
conn.add(superclass, subType, obj);
conn.add(obj, RDFS.LABEL, new LiteralImpl("label"));
conn.add(obj2, RDFS.LABEL, new LiteralImpl("label2"));
final String indexSparqlString = ""//
+ "SELECT ?dog ?pig ?duck " //
+ "{" //
+ " ?pig a ?dog . "//
+ " ?pig <http://www.w3.org/2000/01/rdf-schema#label> ?duck "//
+ "}";//
final String indexSparqlString2 = ""//
+ "SELECT ?o ?f ?e ?c ?l " //
+ "{" //
+ " ?e <uri:talksTo> ?o . "//
+ " ?o <http://www.w3.org/2000/01/rdf-schema#label> ?l. "//
+ " ?c a ?f . " //
+ "}";//
final String indexSparqlString3 = ""//
+ "SELECT ?wolf ?sheep ?chicken " //
+ "{" //
+ " ?wolf <uri:howlsAt> ?sheep . "//
+ " ?sheep <uri:subType> ?chicken. "//
+ "}";//
final String queryString = ""//
+ "SELECT ?c ?l ?f ?o " //
+ "{" //
+ " <uri:entity> a ?c . "//
+ " <uri:entity> <http://www.w3.org/2000/01/rdf-schema#label> ?l. "//
+ " <uri:entity> <uri:talksTo> ?o . "//
+ " ?o <http://www.w3.org/2000/01/rdf-schema#label> ?l. "//
+ " ?c a ?f . " //
+ " <uri:entity> <uri:howlsAt> ?f. "//
+ " ?f <uri:subType> <uri:obj>. "//
+ "}";//
PcjIntegrationTestingUtil.createAndPopulatePcj(conn, accCon, tablename + 1,
indexSparqlString, new String[] { "dog", "pig", "duck" },
Optional.<PcjVarOrderFactory> absent());
PcjIntegrationTestingUtil.createAndPopulatePcj(conn, accCon, tablename + 2,
indexSparqlString2, new String[] { "o", "f", "e", "c", "l" },
Optional.<PcjVarOrderFactory> absent());
PcjIntegrationTestingUtil.createAndPopulatePcj(conn, accCon, tablename + 3,
indexSparqlString3,
new String[] { "wolf", "sheep", "chicken" },
Optional.<PcjVarOrderFactory> absent());
final CountingResultHandler crh1 = new CountingResultHandler();
final CountingResultHandler crh2 = new CountingResultHandler();
conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
.evaluate(crh1);
PcjIntegrationTestingUtil.deleteCoreRyaTables(accCon, prefix);
pcjConn.prepareTupleQuery(QueryLanguage.SPARQL, queryString).evaluate(
crh2);
Assert.assertEquals(crh1.getCount(), crh2.getCount());
}
@Test
public void testEvaluateFilterInstantiate() throws RepositoryException,
PcjException, MalformedQueryException, SailException,
QueryEvaluationException, TableNotFoundException,
TupleQueryResultHandlerException, AccumuloException,
AccumuloSecurityException {
final URI e1 = new URIImpl("uri:e1");
final URI e2 = new URIImpl("uri:e2");
final URI e3 = new URIImpl("uri:e3");
final URI f1 = new URIImpl("uri:f1");
final URI f2 = new URIImpl("uri:f2");
final URI f3 = new URIImpl("uri:f3");
final URI g1 = new URIImpl("uri:g1");
final URI g2 = new URIImpl("uri:g2");
final URI g3 = new URIImpl("uri:g3");
conn.add(e1, talksTo, f1);
conn.add(f1, talksTo, g1);
conn.add(g1, talksTo, e1);
conn.add(e2, talksTo, f2);
conn.add(f2, talksTo, g2);
conn.add(g2, talksTo, e2);
conn.add(e3, talksTo, f3);
conn.add(f3, talksTo, g3);
conn.add(g3, talksTo, e3);
final String queryString = ""//
+ "SELECT ?x ?y ?z " //
+ "{" //
+ "Filter(?x = <uri:e1>) . " //
+ " ?x <uri:talksTo> ?y. " //
+ " ?y <uri:talksTo> ?z. " //
+ " ?z <uri:talksTo> <uri:e1>. " //
+ "}";//
final String indexSparqlString = ""//
+ "SELECT ?a ?b ?c ?d " //
+ "{" //
+ "Filter(?a = ?d) . " //
+ " ?a <uri:talksTo> ?b. " //
+ " ?b <uri:talksTo> ?c. " //
+ " ?c <uri:talksTo> ?d. " //
+ "}";//
PcjIntegrationTestingUtil.createAndPopulatePcj(conn, accCon, tablename + 1,
indexSparqlString, new String[] { "a", "b", "c", "d" },
Optional.<PcjVarOrderFactory> absent());
final CountingResultHandler crh1 = new CountingResultHandler();
final CountingResultHandler crh2 = new CountingResultHandler();
conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
.evaluate(crh1);
PcjIntegrationTestingUtil.deleteCoreRyaTables(accCon, prefix);
pcjConn.prepareTupleQuery(QueryLanguage.SPARQL, queryString).evaluate(crh2);
Assert.assertEquals(crh1.getCount(), crh2.getCount());
}
@Test
public void testEvaluateCompoundFilterInstantiate()
throws RepositoryException, PcjException, MalformedQueryException,
SailException, QueryEvaluationException,
TableNotFoundException,
TupleQueryResultHandlerException, AccumuloException, AccumuloSecurityException {
final URI e1 = new URIImpl("uri:e1");
final URI f1 = new URIImpl("uri:f1");
conn.add(e1, talksTo, e1);
conn.add(e1, talksTo, f1);
conn.add(f1, talksTo, e1);
final String queryString = ""//
+ "SELECT ?x ?y ?z " //
+ "{" //
+ "Filter(?x = <uri:e1> && ?y = <uri:e1>) . " //
+ " ?x <uri:talksTo> ?y. " //
+ " ?y <uri:talksTo> ?z. " //
+ " ?z <uri:talksTo> <uri:e1>. " //
+ "}";//
final String indexSparqlString = ""//
+ "SELECT ?a ?b ?c ?d " //
+ "{" //
+ "Filter(?a = ?d && ?b = ?d) . " //
+ " ?a <uri:talksTo> ?b. " //
+ " ?b <uri:talksTo> ?c. " //
+ " ?c <uri:talksTo> ?d. " //
+ "}";//
PcjIntegrationTestingUtil.createAndPopulatePcj(conn, accCon, tablename + 1,
indexSparqlString, new String[] { "a", "b", "c", "d" },
Optional.<PcjVarOrderFactory> absent());
final CountingResultHandler crh1 = new CountingResultHandler();
final CountingResultHandler crh2 = new CountingResultHandler();
conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
.evaluate(crh1);
PcjIntegrationTestingUtil.deleteCoreRyaTables(accCon, prefix);
pcjConn.prepareTupleQuery(QueryLanguage.SPARQL, queryString).evaluate(
crh2);
Assert.assertEquals(2, crh1.getCount());
Assert.assertEquals(crh1.getCount(), crh2.getCount());
}
public static class CountingResultHandler implements
TupleQueryResultHandler {
private int count = 0;
public int getCount() {
return count;
}
public void resetCount() {
count = 0;
}
@Override
public void startQueryResult(final List<String> arg0)
throws TupleQueryResultHandlerException {
}
@Override
public void handleSolution(final BindingSet arg0)
throws TupleQueryResultHandlerException {
count++;
}
@Override
public void endQueryResult() throws TupleQueryResultHandlerException {
}
@Override
public void handleBoolean(final boolean arg0)
throws QueryResultHandlerException {
}
@Override
public void handleLinks(final List<String> arg0)
throws QueryResultHandlerException {
}
}
}
|
pujav65/incubator-rya
|
extras/indexing/src/test/java/org/apache/rya/indexing/external/AccumuloConstantPcjIntegrationTest.java
|
Java
|
apache-2.0
| 14,058 |
package de.jpaw.fixedpoint.tests;
import java.math.BigDecimal;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import de.jpaw.fixedpoint.types.MicroUnits;
public class TestConversions {
@Test
public void testFromConversions() throws Exception {
MicroUnits fromLong = MicroUnits.valueOf(2);
MicroUnits fromDouble = MicroUnits.valueOf(2.0);
MicroUnits fromString = MicroUnits.valueOf("2.0");
MicroUnits fromBigDecimal = MicroUnits.valueOf(BigDecimal.valueOf(2));
MicroUnits fromMantissa = MicroUnits.of(2_000_000L);
Assertions.assertEquals(fromMantissa, fromBigDecimal, "from BigDecimal");
Assertions.assertEquals(fromMantissa, fromString, "from String");
Assertions.assertEquals(fromMantissa, fromDouble, "from double");
Assertions.assertEquals(fromMantissa, fromLong, "from long");
}
@Test
public void testToConversions() throws Exception {
MicroUnits value = MicroUnits.valueOf(2);
Assertions.assertEquals("2", value.toString(), "to String");
Assertions.assertEquals(BigDecimal.valueOf(2).setScale(6), value.toBigDecimal(), "to BigDecimal");
Assertions.assertEquals(2, value.intValue(), "to int");
Assertions.assertEquals(2.0, value.doubleValue(), "to double");
Assertions.assertEquals(2_000_000L, value.getMantissa(), "to Mantissa");
}
}
|
jpaw/jpaw
|
jpaw-fixedpoint-core/src/test/java/de/jpaw/fixedpoint/tests/TestConversions.java
|
Java
|
apache-2.0
| 1,420 |
package org.dominokit.domino.api.client;
@FunctionalInterface
public
interface ApplicationStartHandler {
void onApplicationStarted();
}
|
GwtDomino/domino
|
domino-api-client/src/main/java/org/dominokit/domino/api/client/ApplicationStartHandler.java
|
Java
|
apache-2.0
| 141 |
/**
* 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.jboss.arquillian.warp.utils;
import java.io.UnsupportedEncodingException;
import org.apache.commons.codec.DecoderException;
/**
* Abstract superclass for Base-N encoders and decoders.
*
* <p>
* This class is not thread-safe. Each thread should use its own instance.
* </p>
*/
public abstract class BaseNCodec {
/**
* MIME chunk size per RFC 2045 section 6.8.
*
* <p>
* The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any equal
* signs.
* </p>
*
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 6.8</a>
*/
public static final int MIME_CHUNK_SIZE = 76;
/**
* PEM chunk size per RFC 1421 section 4.3.2.4.
*
* <p>
* The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any equal
* signs.
* </p>
*
* @see <a href="http://tools.ietf.org/html/rfc1421">RFC 1421 section 4.3.2.4</a>
*/
public static final int PEM_CHUNK_SIZE = 64;
private static final int DEFAULT_BUFFER_RESIZE_FACTOR = 2;
/**
* Defines the default buffer size - currently {@value} - must be large enough for at least one encoded block+separator
*/
private static final int DEFAULT_BUFFER_SIZE = 8192;
/** Mask used to extract 8 bits, used in decoding bytes */
protected static final int MASK_8BITS = 0xff;
/**
* Byte used to pad output.
*/
protected static final byte PAD_DEFAULT = '='; // Allow static access to default
protected final byte PAD = PAD_DEFAULT; // instance variable just in case it needs to vary later
/** Number of bytes in each full block of unencoded data, e.g. 4 for Base64 and 5 for Base32 */
private final int unencodedBlockSize;
/** Number of bytes in each full block of encoded data, e.g. 3 for Base64 and 8 for Base32 */
private final int encodedBlockSize;
/**
* Chunksize for encoding. Not used when decoding. A value of zero or less implies no chunking of the encoded data. Rounded
* down to nearest multiple of encodedBlockSize.
*/
protected final int lineLength;
/**
* Size of chunk separator. Not used unless {@link #lineLength} > 0.
*/
private final int chunkSeparatorLength;
/**
* Buffer for streaming.
*/
protected byte[] buffer;
/**
* Position where next character should be written in the buffer.
*/
protected int pos;
/**
* Position where next character should be read from the buffer.
*/
private int readPos;
/**
* Boolean flag to indicate the EOF has been reached. Once EOF has been reached, this object becomes useless, and must be
* thrown away.
*/
protected boolean eof;
/**
* Variable tracks how many characters have been written to the current line. Only used when encoding. We use it to make
* sure each encoded line never goes beyond lineLength (if lineLength > 0).
*/
protected int currentLinePos;
/**
* Writes to the buffer only occur after every 3/5 reads when encoding, and every 4/8 reads when decoding. This variable
* helps track that.
*/
protected int modulus;
/**
* Note <code>lineLength</code> is rounded down to the nearest multiple of {@link #encodedBlockSize} If
* <code>chunkSeparatorLength</code> is zero, then chunking is disabled.
*
* @param unencodedBlockSize the size of an unencoded block (e.g. Base64 = 3)
* @param encodedBlockSize the size of an encoded block (e.g. Base64 = 4)
* @param lineLength if > 0, use chunking with a length <code>lineLength</code>
* @param chunkSeparatorLength the chunk separator length, if relevant
*/
protected BaseNCodec(int unencodedBlockSize, int encodedBlockSize, int lineLength, int chunkSeparatorLength) {
this.unencodedBlockSize = unencodedBlockSize;
this.encodedBlockSize = encodedBlockSize;
this.lineLength = (lineLength > 0 && chunkSeparatorLength > 0) ? (lineLength / encodedBlockSize) * encodedBlockSize : 0;
this.chunkSeparatorLength = chunkSeparatorLength;
}
/**
* Returns true if this object has buffered data for reading.
*
* @return true if there is data still available for reading.
*/
boolean hasData() { // package protected for access from I/O streams
return this.buffer != null;
}
/**
* Returns the amount of buffered data available for reading.
*
* @return The amount of buffered data available for reading.
*/
int available() { // package protected for access from I/O streams
return buffer != null ? pos - readPos : 0;
}
/**
* Get the default buffer size. Can be overridden.
*
* @return {@link #DEFAULT_BUFFER_SIZE}
*/
protected int getDefaultBufferSize() {
return DEFAULT_BUFFER_SIZE;
}
/** Increases our buffer by the {@link #DEFAULT_BUFFER_RESIZE_FACTOR}. */
private void resizeBuffer() {
if (buffer == null) {
buffer = new byte[getDefaultBufferSize()];
pos = 0;
readPos = 0;
} else {
byte[] b = new byte[buffer.length * DEFAULT_BUFFER_RESIZE_FACTOR];
System.arraycopy(buffer, 0, b, 0, buffer.length);
buffer = b;
}
}
/**
* Ensure that the buffer has room for <code>size</code> bytes
*
* @param size minimum spare space required
*/
protected void ensureBufferSize(int size) {
if ((buffer == null) || (buffer.length < pos + size)) {
resizeBuffer();
}
}
/**
* Extracts buffered data into the provided byte[] array, starting at position bPos, up to a maximum of bAvail bytes.
* Returns how many bytes were actually extracted.
*
* @param b byte[] array to extract the buffered data into.
* @param bPos position in byte[] array to start extraction at.
* @param bAvail amount of bytes we're allowed to extract. We may extract fewer (if fewer are available).
* @return The number of bytes successfully extracted into the provided byte[] array.
*/
int readResults(byte[] b, int bPos, int bAvail) { // package protected for access from I/O streams
if (buffer != null) {
int len = Math.min(available(), bAvail);
System.arraycopy(buffer, readPos, b, bPos, len);
readPos += len;
if (readPos >= pos) {
buffer = null; // so hasData() will return false, and this method can return -1
}
return len;
}
return eof ? -1 : 0;
}
/**
* Checks if a byte value is whitespace or not. Whitespace is taken to mean: space, tab, CR, LF
*
* @param byteToCheck the byte to check
* @return true if byte is whitespace, false otherwise
*/
protected static boolean isWhiteSpace(byte byteToCheck) {
switch (byteToCheck) {
case ' ':
case '\n':
case '\r':
case '\t':
return true;
default:
return false;
}
}
/**
* Resets this object to its initial newly constructed state.
*/
private void reset() {
buffer = null;
pos = 0;
readPos = 0;
currentLinePos = 0;
modulus = 0;
eof = false;
}
/**
* Encodes an Object using the Base-N algorithm. This method is provided in order to satisfy the requirements of the Encoder
* interface, and will throw an IllegalStateException if the supplied object is not of type byte[].
*
* @param pObject Object to encode
* @return An object (of type byte[]) containing the Base-N encoded data which corresponds to the byte[] supplied.
* @throws IllegalStateException if the parameter supplied is not of type byte[]
*/
public Object encode(Object pObject) {
if (!(pObject instanceof byte[])) {
throw new IllegalStateException("Parameter supplied to Base-N encode is not a byte[]");
}
return encode((byte[]) pObject);
}
/**
* Encodes a byte[] containing binary data, into a String containing characters in the Base-N alphabet.
*
* @param pArray a byte array containing binary data
* @return A String containing only Base-N character data
*/
public String encodeToString(byte[] pArray) {
return newStringUtf8(encode(pArray));
}
/**
* Decodes an Object using the Base-N algorithm. This method is provided in order to satisfy the requirements of the Decoder
* interface, and will throw a DecoderException if the supplied object is not of type byte[] or String.
*
* @param pObject Object to decode
* @return An object (of type byte[]) containing the binary data which corresponds to the byte[] or String supplied.
* @throws DecoderException if the parameter supplied is not of type byte[]
*/
public Object decode(Object pObject) throws IllegalStateException {
if (pObject instanceof byte[]) {
return decode((byte[]) pObject);
} else if (pObject instanceof String) {
return decode((String) pObject);
} else {
throw new IllegalStateException("Parameter supplied to Base-N decode is not a byte[] or a String");
}
}
/**
* Decodes a String containing characters in the Base-N alphabet.
*
* @param pArray A String containing Base-N character data
* @return a byte array containing binary data
*/
public byte[] decode(String pArray) {
return decode(getBytesUtf8(pArray));
}
/**
* Decodes a byte[] containing characters in the Base-N alphabet.
*
* @param pArray A byte array containing Base-N character data
* @return a byte array containing binary data
*/
public byte[] decode(byte[] pArray) {
reset();
if (pArray == null || pArray.length == 0) {
return pArray;
}
decode(pArray, 0, pArray.length);
decode(pArray, 0, -1); // Notify decoder of EOF.
byte[] result = new byte[pos];
readResults(result, 0, result.length);
return result;
}
/**
* Encodes a byte[] containing binary data, into a byte[] containing characters in the alphabet.
*
* @param pArray a byte array containing binary data
* @return A byte array containing only the basen alphabetic character data
*/
public byte[] encode(byte[] pArray) {
reset();
if (pArray == null || pArray.length == 0) {
return pArray;
}
encode(pArray, 0, pArray.length);
encode(pArray, 0, -1); // Notify encoder of EOF.
byte[] buf = new byte[pos - readPos];
readResults(buf, 0, buf.length);
return buf;
}
/**
* Encodes a byte[] containing binary data, into a String containing characters in the appropriate alphabet. Uses UTF8
* encoding.
*
* @param pArray a byte array containing binary data
* @return String containing only character data in the appropriate alphabet.
*/
public String encodeAsString(byte[] pArray) {
return newStringUtf8(encode(pArray));
}
abstract void encode(byte[] pArray, int i, int length); // package protected for access from I/O streams
abstract void decode(byte[] pArray, int i, int length); // package protected for access from I/O streams
/**
* Returns whether or not the <code>octet</code> is in the current alphabet. Does not allow whitespace or pad.
*
* @param value The value to test
*
* @return <code>true</code> if the value is defined in the current alphabet, <code>false</code> otherwise.
*/
protected abstract boolean isInAlphabet(byte value);
/**
* Tests a given byte array to see if it contains only valid characters within the alphabet. The method optionally treats
* whitespace and pad as valid.
*
* @param arrayOctet byte array to test
* @param allowWSPad if <code>true</code>, then whitespace and PAD are also allowed
*
* @return <code>true</code> if all bytes are valid characters in the alphabet or if the byte array is empty;
* <code>false</code>, otherwise
*/
public boolean isInAlphabet(byte[] arrayOctet, boolean allowWSPad) {
for (int i = 0; i < arrayOctet.length; i++) {
if (!isInAlphabet(arrayOctet[i]) && (!allowWSPad || (arrayOctet[i] != PAD) && !isWhiteSpace(arrayOctet[i]))) {
return false;
}
}
return true;
}
/**
* Tests a given String to see if it contains only valid characters within the alphabet. The method treats whitespace and
* PAD as valid.
*
* @param basen String to test
* @return <code>true</code> if all characters in the String are valid characters in the alphabet or if the String is empty;
* <code>false</code>, otherwise
* @see #isInAlphabet(byte[], boolean)
*/
public boolean isInAlphabet(String basen) {
return isInAlphabet(getBytesUtf8(basen), true);
}
/**
* Tests a given byte array to see if it contains any characters within the alphabet or PAD.
*
* Intended for use in checking line-ending arrays
*
* @param arrayOctet byte array to test
* @return <code>true</code> if any byte is a valid character in the alphabet or PAD; <code>false</code> otherwise
*/
protected boolean containsAlphabetOrPad(byte[] arrayOctet) {
if (arrayOctet == null) {
return false;
}
for (byte element : arrayOctet) {
if (PAD == element || isInAlphabet(element)) {
return true;
}
}
return false;
}
/**
* Calculates the amount of space needed to encode the supplied array.
*
* @param pArray byte[] array which will later be encoded
*
* @return amount of space needed to encoded the supplied array. Returns a long since a max-len array will require >
* Integer.MAX_VALUE
*/
public long getEncodedLength(byte[] pArray) {
// Calculate non-chunked size - rounded up to allow for padding
// cast to long is needed to avoid possibility of overflow
long len = ((pArray.length + unencodedBlockSize - 1) / unencodedBlockSize) * (long) encodedBlockSize;
if (lineLength > 0) { // We're using chunking
// Round up to nearest multiple
len += ((len + lineLength - 1) / lineLength) * chunkSeparatorLength;
}
return len;
}
/**
* Constructs a new <code>String</code> by decoding the specified array of bytes using the UTF-8 charset.
*
* @param bytes The bytes to be decoded into characters
* @return A new <code>String</code> decoded from the specified array of bytes using the UTF-8 charset, or <code>null</code>
* if the input byte array was <code>null</code>.
* @throws IllegalStateException Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen
* since the charset is required.
*/
public static String newStringUtf8(byte[] bytes) {
if (bytes == null) {
return null;
}
try {
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("UTF-8", e);
}
}
/**
* Encodes the given string into a sequence of bytes using the UTF-8 charset, storing the result into a new byte array.
*
* @param string the String to encode, may be <code>null</code>
* @return encoded bytes, or <code>null</code> if the input string was <code>null</code>
* @throws IllegalStateException Thrown when the charset is missing, which should be never according the the Java
* specification.
* @see <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
* @see #getBytesUnchecked(String, String)
*/
public static byte[] getBytesUtf8(String string) {
if (string == null) {
return null;
}
try {
return string.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("UTF-8", e);
}
}
}
|
aslakknutsen/arquillian-extension-warp
|
impl/src/main/java/org/jboss/arquillian/warp/utils/BaseNCodec.java
|
Java
|
apache-2.0
| 17,879 |
package dk.lessismore.nojpa.reflection.db.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created : with IntelliJ IDEA.
* User: seb
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SearchField {
public static final String NULL = "";
public boolean translate() default false;
public boolean searchReverse() default false;
public float boostFactor() default 3f;
public float reverseBoostFactor() default 0.3f;
public String dynamicSolrPostName() default NULL;
}
|
NoJPA-LESS-IS-MORE/NoJPA
|
nojpa_orm/src/main/java/dk/lessismore/nojpa/reflection/db/annotations/SearchField.java
|
Java
|
apache-2.0
| 664 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.hoang.fu;
/**
*
* @author hoangpt
*/
public class Teacher extends Employee implements ITeacher {
Teacher(String name) {
this.name = name;
}
@Override
float calculateSalary(){
return 500f;
}
@Override
public int calculateBonus() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public float calculateAllowance() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
|
hoangphantich/fu.java192x17.1
|
hoangpt/Assignment_21/src/com/hoang/fu/Teacher.java
|
Java
|
apache-2.0
| 786 |
// Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org)
package org.xbill.DNS;
import java.io.*;
import java.util.*;
import org.xbill.DNS.utils.*;
/**
* Transaction Signature - this record is automatically generated by the
* resolver. TSIG records provide transaction security between the
* sender and receiver of a message, using a shared key.
* @see org.xbill.DNS.Resolver
* @see org.xbill.DNS.TSIG
*
* @author Brian Wellington
*/
public class TSIGRecord extends Record {
private static final long serialVersionUID = -88820909016649306L;
private Name alg;
private Date timeSigned;
private int fudge;
private byte [] signature;
private int originalID;
private int error;
private byte [] other;
TSIGRecord() {}
Record
getObject() {
return new TSIGRecord();
}
/**
* Creates a TSIG Record from the given data. This is normally called by
* the TSIG class
* @param alg The shared key's algorithm
* @param timeSigned The time that this record was generated
* @param fudge The fudge factor for time - if the time that the message is
* received is not in the range [now - fudge, now + fudge], the signature
* fails
* @param signature The signature
* @param originalID The message ID at the time of its generation
* @param error The extended error field. Should be 0 in queries.
* @param other The other data field. Currently used only in BADTIME
* responses.
* @see org.xbill.DNS.TSIG
*/
public
TSIGRecord(Name name, int dclass, long ttl, Name alg, Date timeSigned,
int fudge, byte [] signature, int originalID, int error,
byte other[])
{
super(name, Type.TSIG, dclass, ttl);
this.alg = checkName("alg", alg);
this.timeSigned = timeSigned;
this.fudge = checkU16("fudge", fudge);
this.signature = signature;
this.originalID = checkU16("originalID", originalID);
this.error = checkU16("error", error);
this.other = other;
}
void
rrFromWire(DNSInput in) throws IOException {
alg = new Name(in);
long timeHigh = in.readU16();
long timeLow = in.readU32();
long time = (timeHigh << 32) + timeLow;
timeSigned = new Date(time * 1000);
fudge = in.readU16();
int sigLen = in.readU16();
signature = in.readByteArray(sigLen);
originalID = in.readU16();
error = in.readU16();
int otherLen = in.readU16();
if (otherLen > 0)
other = in.readByteArray(otherLen);
else
other = null;
}
void
rdataFromString(Tokenizer st, Name origin) throws IOException {
throw st.exception("no text format defined for TSIG");
}
/** Converts rdata to a String */
String
rrToString() {
StringBuffer sb = new StringBuffer();
sb.append(alg);
sb.append(" ");
if (Options.check("multiline"))
sb.append("(\n\t");
sb.append (timeSigned.getTime() / 1000);
sb.append (" ");
sb.append (fudge);
sb.append (" ");
sb.append (signature.length);
if (Options.check("multiline")) {
sb.append ("\n");
sb.append (base64.formatString(signature, 64, "\t", false));
} else {
sb.append (" ");
sb.append (base64.toString(signature));
}
sb.append (" ");
sb.append (Rcode.TSIGstring(error));
sb.append (" ");
if (other == null)
sb.append (0);
else {
sb.append (other.length);
if (Options.check("multiline"))
sb.append("\n\n\n\t");
else
sb.append(" ");
if (error == Rcode.BADTIME) {
if (other.length != 6) {
sb.append("<invalid BADTIME other data>");
} else {
long time = ((long)(other[0] & 0xFF) << 40) +
((long)(other[1] & 0xFF) << 32) +
((other[2] & 0xFF) << 24) +
((other[3] & 0xFF) << 16) +
((other[4] & 0xFF) << 8) +
((other[5] & 0xFF) );
sb.append("<server time: ");
sb.append(new Date(time * 1000));
sb.append(">");
}
} else {
sb.append("<");
sb.append(base64.toString(other));
sb.append(">");
}
}
if (Options.check("multiline"))
sb.append(" )");
return sb.toString();
}
/** Returns the shared key's algorithm */
public Name
getAlgorithm() {
return alg;
}
/** Returns the time that this record was generated */
public Date
getTimeSigned() {
return timeSigned;
}
/** Returns the time fudge factor */
public int
getFudge() {
return fudge;
}
/** Returns the signature */
public byte []
getSignature() {
return signature;
}
/** Returns the original message ID */
public int
getOriginalID() {
return originalID;
}
/** Returns the extended error */
public int
getError() {
return error;
}
/** Returns the other data */
public byte []
getOther() {
return other;
}
void
rrToWire(DNSOutput out, Compression c, boolean canonical) {
alg.toWire(out, null, canonical);
long time = timeSigned.getTime() / 1000;
int timeHigh = (int) (time >> 32);
long timeLow = (time & 0xFFFFFFFFL);
out.writeU16(timeHigh);
out.writeU32(timeLow);
out.writeU16(fudge);
out.writeU16(signature.length);
out.writeByteArray(signature);
out.writeU16(originalID);
out.writeU16(error);
if (other != null) {
out.writeU16(other.length);
out.writeByteArray(other);
}
else
out.writeU16(0);
}
}
|
msdx/AndroidPNClient
|
androidpn/src/main/java/org/xbill/DNS/TSIGRecord.java
|
Java
|
apache-2.0
| 4,956 |
package app.monitor.job;
import core.framework.internal.log.LogManager;
import core.framework.json.JSON;
import core.framework.kafka.MessagePublisher;
import core.framework.log.message.StatMessage;
import core.framework.scheduler.Job;
import core.framework.scheduler.JobContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Map;
/**
* @author neo
*/
public class KubeMonitorJob implements Job {
public final MessagePublisher<StatMessage> publisher;
public final KubeClient kubeClient;
public final List<String> namespaces;
private final Logger logger = LoggerFactory.getLogger(KubeMonitorJob.class);
public KubeMonitorJob(List<String> namespaces, KubeClient kubeClient, MessagePublisher<StatMessage> publisher) {
this.publisher = publisher;
this.kubeClient = kubeClient;
this.namespaces = namespaces;
}
@Override
public void execute(JobContext context) {
try {
var now = ZonedDateTime.now();
for (String namespace : namespaces) {
KubePodList pods = kubeClient.listPods(namespace);
for (KubePodList.Pod pod : pods.items) {
String errorMessage = check(pod, now);
if (errorMessage != null) {
publishPodFailure(pod, errorMessage);
}
}
}
} catch (Throwable e) {
logger.error(e.getMessage(), e);
publisher.publish(StatMessageFactory.failedToCollect(LogManager.APP_NAME, null, e));
}
}
String check(KubePodList.Pod pod, ZonedDateTime now) {
if (pod.metadata.deletionTimestamp != null) {
Duration elapsed = Duration.between(pod.metadata.deletionTimestamp, now);
if (elapsed.toSeconds() >= 300) {
return "pod is still in deletion, elapsed=" + elapsed;
}
return null;
}
String phase = pod.status.phase;
if ("Succeeded".equals(phase)) return null; // terminated
if ("Failed".equals(phase) || "Unknown".equals(phase)) return "unexpected pod phase, phase=" + phase;
if ("Pending".equals(phase)) {
// newly created pod may not have container status yet, containerStatuses is initialized as empty
for (KubePodList.ContainerStatus status : pod.status.containerStatuses) {
if (status.state.waiting != null && "ImagePullBackOff".equals(status.state.waiting.reason)) {
return "ImagePullBackOff: " + status.state.waiting.message;
}
}
// for unschedulable pod
for (KubePodList.PodCondition condition : pod.status.conditions) {
if ("PodScheduled".equals(condition.type) && "False".equals(condition.status) && Duration.between(condition.lastTransitionTime, now).toSeconds() >= 300) {
return condition.reason + ": " + condition.message;
}
}
}
if ("Running".equals(phase)) {
boolean ready = true;
for (KubePodList.ContainerStatus status : pod.status.containerStatuses) {
if (status.state.waiting != null && "CrashLoopBackOff".equals(status.state.waiting.reason)) {
return "CrashLoopBackOff: " + status.state.waiting.message;
}
boolean containerReady = Boolean.TRUE.equals(status.ready);
if (!containerReady && status.lastState != null && status.lastState.terminated != null) {
var terminated = status.lastState.terminated;
return "pod was terminated, reason=" + terminated.reason + ", exitCode=" + terminated.exitCode;
}
if (!containerReady) {
ready = false;
}
}
if (ready) return null; // all running, all ready
}
ZonedDateTime startTime = pod.status.startTime != null ? pod.status.startTime : pod.metadata.creationTimestamp; // startTime may not be populated yet if pod is just created
Duration elapsed = Duration.between(startTime, now);
if (elapsed.toSeconds() >= 300) {
// can be: 1) took long to be ready after start, or 2) readiness check failed in the middle run
return "pod is not in ready state, uptime=" + elapsed;
}
return null;
}
private void publishPodFailure(KubePodList.Pod pod, String errorMessage) {
var now = Instant.now();
var message = new StatMessage();
message.id = LogManager.ID_GENERATOR.next(now);
message.date = now;
message.result = "ERROR";
message.app = pod.metadata.labels.getOrDefault("app", pod.metadata.name);
message.host = pod.metadata.name;
message.errorCode = "POD_FAILURE";
message.errorMessage = errorMessage;
message.info = Map.of("pod", JSON.toJSON(pod));
publisher.publish(message);
}
}
|
neowu/core-ng-project
|
ext/monitor/src/main/java/app/monitor/job/KubeMonitorJob.java
|
Java
|
apache-2.0
| 5,150 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.internal.logging.log4j;
import static org.apache.geode.test.util.ResourceUtils.createFileFromResource;
import static org.apache.geode.test.util.ResourceUtils.getResource;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.URL;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.junit.LoggerContextRule;
import org.apache.logging.log4j.test.appender.ListAppender;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TemporaryFolder;
import org.apache.geode.internal.logging.LogService;
import org.apache.geode.test.junit.categories.LoggingTest;
@Category(LoggingTest.class)
public class GemfireVerboseMarkerFilterAcceptIntegrationTest {
private static final String APPENDER_NAME = "LIST";
private static String configFilePath;
private Logger logger;
private String logMessage;
private ListAppender listAppender;
@ClassRule
public static TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public LoggerContextRule loggerContextRule = new LoggerContextRule(configFilePath);
@BeforeClass
public static void setUpLogConfigFile() throws Exception {
String configFileName =
GemfireVerboseMarkerFilterAcceptIntegrationTest.class.getSimpleName() + "_log4j2.xml";
URL resource = getResource(configFileName);
configFilePath = createFileFromResource(resource, temporaryFolder.getRoot(), configFileName)
.getAbsolutePath();
}
@Before
public void setUp() throws Exception {
logger = LogService.getLogger();
logMessage = "this is a log statement";
assertThat(LogService.isUsingGemFireDefaultConfig()).as(LogService.getConfigurationInfo())
.isFalse();
listAppender = loggerContextRule.getListAppender(APPENDER_NAME);
}
@Test
public void gemfireVerboseShouldLogIfGemfireVerboseIsAccept() {
logger.info(LogMarker.GEMFIRE_VERBOSE, logMessage);
LogEvent logEvent = listAppender.getEvents().get(0);
assertThat(logEvent.getLoggerName()).isEqualTo(logger.getName());
assertThat(logEvent.getLevel()).isEqualTo(Level.INFO);
assertThat(logEvent.getMessage().getFormattedMessage()).isEqualTo(logMessage);
}
@Test
public void geodeVerboseShouldLogIfGemfireVerboseIsAccept() {
logger.info(LogMarker.GEODE_VERBOSE, logMessage);
LogEvent logEvent = listAppender.getEvents().get(0);
assertThat(logEvent.getLoggerName()).isEqualTo(logger.getName());
assertThat(logEvent.getLevel()).isEqualTo(Level.INFO);
assertThat(logEvent.getMessage().getFormattedMessage()).isEqualTo(logMessage);
}
}
|
pdxrunner/geode
|
geode-core/src/integrationTest/java/org/apache/geode/internal/logging/log4j/GemfireVerboseMarkerFilterAcceptIntegrationTest.java
|
Java
|
apache-2.0
| 3,615 |
package com.yueny.demo.job.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yueny.demo.common.example.bo.ModifyDemoBo;
import com.yueny.demo.common.example.service.IDataPrecipitationService;
import lombok.extern.slf4j.Slf4j;
/**
* @author yueny09 <deep_blue_yang@163.com>
*
* @DATE 2016年2月16日 下午8:23:11
*
*/
@Controller
@Slf4j
public class DemoController {
@Autowired
private IDataPrecipitationService dataPrecipitationService;
/**
*
*/
@RequestMapping(value = { "/", "welcome" }, method = RequestMethod.GET)
@ResponseBody
public List<ModifyDemoBo> bar() {
try {
return dataPrecipitationService.queryAll();
} catch (final Exception e) {
log.error("exception:", e);
}
return null;
}
@RequestMapping(value = "/healthy", method = RequestMethod.GET)
@ResponseBody
public String healthy() {
return "OK";
}
}
|
yueny/pra
|
job/job_elastic/src/main/java/com/yueny/demo/job/controller/DemoController.java
|
Java
|
apache-2.0
| 1,201 |
/**
* Copyright (C) 2009-2014 Typesafe Inc. <http://www.typesafe.com>
*/
package docs.extension;
//#imports
import akka.actor.Extension;
import akka.actor.AbstractExtensionId;
import akka.actor.ExtensionIdProvider;
import akka.actor.ActorSystem;
import akka.actor.ExtendedActorSystem;
import scala.concurrent.duration.Duration;
import com.typesafe.config.Config;
import java.util.concurrent.TimeUnit;
//#imports
import akka.actor.UntypedActor;
import org.junit.Test;
public class SettingsExtensionDocTest {
static
//#extension
public class SettingsImpl implements Extension {
public final String DB_URI;
public final Duration CIRCUIT_BREAKER_TIMEOUT;
public SettingsImpl(Config config) {
DB_URI = config.getString("myapp.db.uri");
CIRCUIT_BREAKER_TIMEOUT =
Duration.create(config.getDuration("myapp.circuit-breaker.timeout",
TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS);
}
}
//#extension
static
//#extensionid
public class Settings extends AbstractExtensionId<SettingsImpl>
implements ExtensionIdProvider {
public final static Settings SettingsProvider = new Settings();
private Settings() {}
public Settings lookup() {
return Settings.SettingsProvider;
}
public SettingsImpl createExtension(ExtendedActorSystem system) {
return new SettingsImpl(system.settings().config());
}
}
//#extensionid
static
//#extension-usage-actor
public class MyActor extends UntypedActor {
// typically you would use static import of the Settings.SettingsProvider field
final SettingsImpl settings =
Settings.SettingsProvider.get(getContext().system());
Connection connection =
connect(settings.DB_URI, settings.CIRCUIT_BREAKER_TIMEOUT);
//#extension-usage-actor
public Connection connect(String dbUri, Duration circuitBreakerTimeout) {
return new Connection();
}
public void onReceive(Object msg) {
}
//#extension-usage-actor
}
//#extension-usage-actor
public static class Connection {
}
@Test
public void demonstrateHowToCreateAndUseAnAkkaExtensionInJava() {
final ActorSystem system = null;
try {
//#extension-usage
// typically you would use static import of the Settings.SettingsProvider field
String dbUri = Settings.SettingsProvider.get(system).DB_URI;
//#extension-usage
} catch (Exception e) {
//do nothing
}
}
}
|
Horusiath/akka.net
|
Documentation/csharp/code/docs/extension/SettingsExtensionDocTest.java
|
Java
|
apache-2.0
| 2,450 |
/**
* Copyright Intellectual Reserve, 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.gedcomx.build.enunciate;
import org.codehaus.enunciate.main.ClasspathHandler;
import org.codehaus.enunciate.main.ClasspathResource;
import org.codehaus.enunciate.main.Enunciate;
import org.gedcomx.test.Recipe;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* @author Ryan Heaton
*/
public class RecipeClasspathHandler implements ClasspathHandler {
private final Enunciate enunciate;
private final List<Recipe> recipes = new ArrayList<Recipe>();
private final Unmarshaller unmarshaller;
public RecipeClasspathHandler(Enunciate enunciate) {
this.enunciate = enunciate;
try {
unmarshaller = JAXBContext.newInstance(Recipe.class).createUnmarshaller();
}
catch (JAXBException e) {
throw new RuntimeException(e);
}
}
public List<Recipe> getRecipes() {
return recipes;
}
@Override
public void startPathEntry(File pathEntry) {
}
@Override
public void handleResource(ClasspathResource resource) {
if (resource.getPath().endsWith(".recipe.xml")) {
try {
this.recipes.add((Recipe) unmarshaller.unmarshal(resource.read()));
}
catch (Exception e) {
this.enunciate.error("Unable to unmarshal recipe %s: %s.", resource.getPath(), e.getMessage());
}
}
}
@Override
public boolean endPathEntry(File pathEntry) {
return false;
}
}
|
brenthale/gedcomx-java
|
enunciate-gedcomx-support/src/main/java/org/gedcomx/build/enunciate/RecipeClasspathHandler.java
|
Java
|
apache-2.0
| 2,169 |
/*
* 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.devicefarm.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Represents a specific warning or failure.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/Problem" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class Problem implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* Information about the associated run.
* </p>
*/
private ProblemDetail run;
/**
* <p>
* Information about the associated job.
* </p>
*/
private ProblemDetail job;
/**
* <p>
* Information about the associated suite.
* </p>
*/
private ProblemDetail suite;
/**
* <p>
* Information about the associated test.
* </p>
*/
private ProblemDetail test;
/**
* <p>
* Information about the associated device.
* </p>
*/
private Device device;
/**
* <p>
* The problem's result.
* </p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* PENDING
* </p>
* </li>
* <li>
* <p>
* PASSED
* </p>
* </li>
* <li>
* <p>
* WARNED
* </p>
* </li>
* <li>
* <p>
* FAILED
* </p>
* </li>
* <li>
* <p>
* SKIPPED
* </p>
* </li>
* <li>
* <p>
* ERRORED
* </p>
* </li>
* <li>
* <p>
* STOPPED
* </p>
* </li>
* </ul>
*/
private String result;
/**
* <p>
* A message about the problem's result.
* </p>
*/
private String message;
/**
* <p>
* Information about the associated run.
* </p>
*
* @param run
* Information about the associated run.
*/
public void setRun(ProblemDetail run) {
this.run = run;
}
/**
* <p>
* Information about the associated run.
* </p>
*
* @return Information about the associated run.
*/
public ProblemDetail getRun() {
return this.run;
}
/**
* <p>
* Information about the associated run.
* </p>
*
* @param run
* Information about the associated run.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Problem withRun(ProblemDetail run) {
setRun(run);
return this;
}
/**
* <p>
* Information about the associated job.
* </p>
*
* @param job
* Information about the associated job.
*/
public void setJob(ProblemDetail job) {
this.job = job;
}
/**
* <p>
* Information about the associated job.
* </p>
*
* @return Information about the associated job.
*/
public ProblemDetail getJob() {
return this.job;
}
/**
* <p>
* Information about the associated job.
* </p>
*
* @param job
* Information about the associated job.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Problem withJob(ProblemDetail job) {
setJob(job);
return this;
}
/**
* <p>
* Information about the associated suite.
* </p>
*
* @param suite
* Information about the associated suite.
*/
public void setSuite(ProblemDetail suite) {
this.suite = suite;
}
/**
* <p>
* Information about the associated suite.
* </p>
*
* @return Information about the associated suite.
*/
public ProblemDetail getSuite() {
return this.suite;
}
/**
* <p>
* Information about the associated suite.
* </p>
*
* @param suite
* Information about the associated suite.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Problem withSuite(ProblemDetail suite) {
setSuite(suite);
return this;
}
/**
* <p>
* Information about the associated test.
* </p>
*
* @param test
* Information about the associated test.
*/
public void setTest(ProblemDetail test) {
this.test = test;
}
/**
* <p>
* Information about the associated test.
* </p>
*
* @return Information about the associated test.
*/
public ProblemDetail getTest() {
return this.test;
}
/**
* <p>
* Information about the associated test.
* </p>
*
* @param test
* Information about the associated test.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Problem withTest(ProblemDetail test) {
setTest(test);
return this;
}
/**
* <p>
* Information about the associated device.
* </p>
*
* @param device
* Information about the associated device.
*/
public void setDevice(Device device) {
this.device = device;
}
/**
* <p>
* Information about the associated device.
* </p>
*
* @return Information about the associated device.
*/
public Device getDevice() {
return this.device;
}
/**
* <p>
* Information about the associated device.
* </p>
*
* @param device
* Information about the associated device.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Problem withDevice(Device device) {
setDevice(device);
return this;
}
/**
* <p>
* The problem's result.
* </p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* PENDING
* </p>
* </li>
* <li>
* <p>
* PASSED
* </p>
* </li>
* <li>
* <p>
* WARNED
* </p>
* </li>
* <li>
* <p>
* FAILED
* </p>
* </li>
* <li>
* <p>
* SKIPPED
* </p>
* </li>
* <li>
* <p>
* ERRORED
* </p>
* </li>
* <li>
* <p>
* STOPPED
* </p>
* </li>
* </ul>
*
* @param result
* The problem's result.</p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* PENDING
* </p>
* </li>
* <li>
* <p>
* PASSED
* </p>
* </li>
* <li>
* <p>
* WARNED
* </p>
* </li>
* <li>
* <p>
* FAILED
* </p>
* </li>
* <li>
* <p>
* SKIPPED
* </p>
* </li>
* <li>
* <p>
* ERRORED
* </p>
* </li>
* <li>
* <p>
* STOPPED
* </p>
* </li>
* @see ExecutionResult
*/
public void setResult(String result) {
this.result = result;
}
/**
* <p>
* The problem's result.
* </p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* PENDING
* </p>
* </li>
* <li>
* <p>
* PASSED
* </p>
* </li>
* <li>
* <p>
* WARNED
* </p>
* </li>
* <li>
* <p>
* FAILED
* </p>
* </li>
* <li>
* <p>
* SKIPPED
* </p>
* </li>
* <li>
* <p>
* ERRORED
* </p>
* </li>
* <li>
* <p>
* STOPPED
* </p>
* </li>
* </ul>
*
* @return The problem's result.</p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* PENDING
* </p>
* </li>
* <li>
* <p>
* PASSED
* </p>
* </li>
* <li>
* <p>
* WARNED
* </p>
* </li>
* <li>
* <p>
* FAILED
* </p>
* </li>
* <li>
* <p>
* SKIPPED
* </p>
* </li>
* <li>
* <p>
* ERRORED
* </p>
* </li>
* <li>
* <p>
* STOPPED
* </p>
* </li>
* @see ExecutionResult
*/
public String getResult() {
return this.result;
}
/**
* <p>
* The problem's result.
* </p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* PENDING
* </p>
* </li>
* <li>
* <p>
* PASSED
* </p>
* </li>
* <li>
* <p>
* WARNED
* </p>
* </li>
* <li>
* <p>
* FAILED
* </p>
* </li>
* <li>
* <p>
* SKIPPED
* </p>
* </li>
* <li>
* <p>
* ERRORED
* </p>
* </li>
* <li>
* <p>
* STOPPED
* </p>
* </li>
* </ul>
*
* @param result
* The problem's result.</p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* PENDING
* </p>
* </li>
* <li>
* <p>
* PASSED
* </p>
* </li>
* <li>
* <p>
* WARNED
* </p>
* </li>
* <li>
* <p>
* FAILED
* </p>
* </li>
* <li>
* <p>
* SKIPPED
* </p>
* </li>
* <li>
* <p>
* ERRORED
* </p>
* </li>
* <li>
* <p>
* STOPPED
* </p>
* </li>
* @return Returns a reference to this object so that method calls can be chained together.
* @see ExecutionResult
*/
public Problem withResult(String result) {
setResult(result);
return this;
}
/**
* <p>
* The problem's result.
* </p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* PENDING
* </p>
* </li>
* <li>
* <p>
* PASSED
* </p>
* </li>
* <li>
* <p>
* WARNED
* </p>
* </li>
* <li>
* <p>
* FAILED
* </p>
* </li>
* <li>
* <p>
* SKIPPED
* </p>
* </li>
* <li>
* <p>
* ERRORED
* </p>
* </li>
* <li>
* <p>
* STOPPED
* </p>
* </li>
* </ul>
*
* @param result
* The problem's result.</p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* PENDING
* </p>
* </li>
* <li>
* <p>
* PASSED
* </p>
* </li>
* <li>
* <p>
* WARNED
* </p>
* </li>
* <li>
* <p>
* FAILED
* </p>
* </li>
* <li>
* <p>
* SKIPPED
* </p>
* </li>
* <li>
* <p>
* ERRORED
* </p>
* </li>
* <li>
* <p>
* STOPPED
* </p>
* </li>
* @see ExecutionResult
*/
public void setResult(ExecutionResult result) {
withResult(result);
}
/**
* <p>
* The problem's result.
* </p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* PENDING
* </p>
* </li>
* <li>
* <p>
* PASSED
* </p>
* </li>
* <li>
* <p>
* WARNED
* </p>
* </li>
* <li>
* <p>
* FAILED
* </p>
* </li>
* <li>
* <p>
* SKIPPED
* </p>
* </li>
* <li>
* <p>
* ERRORED
* </p>
* </li>
* <li>
* <p>
* STOPPED
* </p>
* </li>
* </ul>
*
* @param result
* The problem's result.</p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* PENDING
* </p>
* </li>
* <li>
* <p>
* PASSED
* </p>
* </li>
* <li>
* <p>
* WARNED
* </p>
* </li>
* <li>
* <p>
* FAILED
* </p>
* </li>
* <li>
* <p>
* SKIPPED
* </p>
* </li>
* <li>
* <p>
* ERRORED
* </p>
* </li>
* <li>
* <p>
* STOPPED
* </p>
* </li>
* @return Returns a reference to this object so that method calls can be chained together.
* @see ExecutionResult
*/
public Problem withResult(ExecutionResult result) {
this.result = result.toString();
return this;
}
/**
* <p>
* A message about the problem's result.
* </p>
*
* @param message
* A message about the problem's result.
*/
public void setMessage(String message) {
this.message = message;
}
/**
* <p>
* A message about the problem's result.
* </p>
*
* @return A message about the problem's result.
*/
public String getMessage() {
return this.message;
}
/**
* <p>
* A message about the problem's result.
* </p>
*
* @param message
* A message about the problem's result.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Problem withMessage(String message) {
setMessage(message);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getRun() != null)
sb.append("Run: ").append(getRun()).append(",");
if (getJob() != null)
sb.append("Job: ").append(getJob()).append(",");
if (getSuite() != null)
sb.append("Suite: ").append(getSuite()).append(",");
if (getTest() != null)
sb.append("Test: ").append(getTest()).append(",");
if (getDevice() != null)
sb.append("Device: ").append(getDevice()).append(",");
if (getResult() != null)
sb.append("Result: ").append(getResult()).append(",");
if (getMessage() != null)
sb.append("Message: ").append(getMessage());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof Problem == false)
return false;
Problem other = (Problem) obj;
if (other.getRun() == null ^ this.getRun() == null)
return false;
if (other.getRun() != null && other.getRun().equals(this.getRun()) == false)
return false;
if (other.getJob() == null ^ this.getJob() == null)
return false;
if (other.getJob() != null && other.getJob().equals(this.getJob()) == false)
return false;
if (other.getSuite() == null ^ this.getSuite() == null)
return false;
if (other.getSuite() != null && other.getSuite().equals(this.getSuite()) == false)
return false;
if (other.getTest() == null ^ this.getTest() == null)
return false;
if (other.getTest() != null && other.getTest().equals(this.getTest()) == false)
return false;
if (other.getDevice() == null ^ this.getDevice() == null)
return false;
if (other.getDevice() != null && other.getDevice().equals(this.getDevice()) == false)
return false;
if (other.getResult() == null ^ this.getResult() == null)
return false;
if (other.getResult() != null && other.getResult().equals(this.getResult()) == false)
return false;
if (other.getMessage() == null ^ this.getMessage() == null)
return false;
if (other.getMessage() != null && other.getMessage().equals(this.getMessage()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getRun() == null) ? 0 : getRun().hashCode());
hashCode = prime * hashCode + ((getJob() == null) ? 0 : getJob().hashCode());
hashCode = prime * hashCode + ((getSuite() == null) ? 0 : getSuite().hashCode());
hashCode = prime * hashCode + ((getTest() == null) ? 0 : getTest().hashCode());
hashCode = prime * hashCode + ((getDevice() == null) ? 0 : getDevice().hashCode());
hashCode = prime * hashCode + ((getResult() == null) ? 0 : getResult().hashCode());
hashCode = prime * hashCode + ((getMessage() == null) ? 0 : getMessage().hashCode());
return hashCode;
}
@Override
public Problem clone() {
try {
return (Problem) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.devicefarm.model.transform.ProblemMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
|
aws/aws-sdk-java
|
aws-java-sdk-devicefarm/src/main/java/com/amazonaws/services/devicefarm/model/Problem.java
|
Java
|
apache-2.0
| 19,577 |
package lesson.types;
public class Classes {
public static void main(String[] args) {
JustClass one = new JustClass();
JustClass two = new JustClass(123, "sdf");
System.out.println(one);
System.out.println(two);
}
}
class JustClass {
private int number;
private String name;
public JustClass() { }
public JustClass(int number, String name) {
this.number = number;
this.name = name;
}
@Override
public String toString() {
return String
.format("JustClass {%s, %d}", name,number);
}
}
|
nesterione/JavaTrainings
|
src/lesson/types/Classes.java
|
Java
|
apache-2.0
| 602 |
/**
* Utility classes for converting between granularities of SI (power-of-ten) and IEC (power-of-two)
* byte units and bit units.
* <p>
* <h3>Example Usage</h3>
* What's the difference in hard drive space between perception and actual?
* <pre><code>
* long perception = BinaryByteUnit.TEBIBYTES.toBytes(2);
* long usable = DecimalByteUnit.TERABYTES.toBytes(2);
* long lost = BinaryByteUnit.BYTES.toGibibytes(perception - usable);
* System.out.println(lost + " GiB lost on a 2TB drive.");
* </code></pre>
* <p>
* Method parameter for specifying a resource size.
* <pre><code>
* public void installDiskCache(long count, ByteUnit unit) {
* long size = unit.toBytes(count);
* // TODO Install disk cache of 'size' bytes.
* }
* </code></pre>
*/
package com.jakewharton.byteunits;
|
JakeWharton/byteunits
|
src/main/java/com/jakewharton/byteunits/package-info.java
|
Java
|
apache-2.0
| 799 |
/*
* 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.pig.experimental.logical.relational;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.pig.data.DataType;
import org.apache.pig.impl.util.Pair;
/**
* Schema, from a logical perspective.
*/
public class LogicalSchema {
public static class LogicalFieldSchema {
public String alias;
public byte type;
public long uid;
public LogicalSchema schema;
public LogicalFieldSchema(String alias, LogicalSchema schema, byte type) {
this(alias, schema, type, -1);
}
public LogicalFieldSchema(String alias, LogicalSchema schema, byte type, long uid) {
this.alias = alias;
this.type = type;
this.schema = schema;
this.uid = uid;
}
/**
* Equality is defined as having the same type and either the same schema
* or both null schema. Alias and uid are not checked.
*/
public boolean isEqual(Object other) {
if (other instanceof LogicalFieldSchema) {
LogicalFieldSchema ofs = (LogicalFieldSchema)other;
if (type != ofs.type) return false;
if (schema == null && ofs.schema == null) return true;
if (schema == null) return false;
else return schema.isEqual(ofs.schema);
} else {
return false;
}
}
public String toString() {
if( type == DataType.BAG ) {
if( schema == null ) {
return ( alias + "#" + uid + ":bag{}#" );
}
return ( alias + "#" + uid + ":bag{" + schema.toString() + "}" );
} else if( type == DataType.TUPLE ) {
if( schema == null ) {
return ( alias + "#" + uid + ":tuple{}" );
}
return ( alias + "#" + uid + ":tuple(" + schema.toString() + ")" );
}
return ( alias + "#" + uid + ":" + DataType.findTypeName(type) );
}
}
private List<LogicalFieldSchema> fields;
private Map<String, Pair<Integer, Boolean>> aliases;
public LogicalSchema() {
fields = new ArrayList<LogicalFieldSchema>();
aliases = new HashMap<String, Pair<Integer, Boolean>>();
}
/**
* Add a field to this schema.
* @param field to be added to the schema
*/
public void addField(LogicalFieldSchema field) {
fields.add(field);
if (field.alias != null && !field.alias.equals("")) {
// put the full name of this field into aliases map
// boolean in the pair indicates if this alias is full name
aliases.put(field.alias, new Pair<Integer, Boolean>(fields.size()-1, true));
int index = 0;
// check and put short names into alias map if there is no conflict
while(index != -1) {
index = field.alias.indexOf("::", index);
if (index != -1) {
String a = field.alias.substring(index+2);
if (aliases.containsKey(a)) {
// remove conflict if the conflict is not full name
// we can never remove full name
if (!aliases.get(a).second) {
aliases.remove(a);
}
}else{
// put alias into map and indicate it is a short name
aliases.put(a, new Pair<Integer, Boolean>(fields.size()-1, false));
}
index = index +2;
}
}
}
}
/**
* Fetch a field by alias
* @param alias
* @return field associated with alias, or null if no such field
*/
public LogicalFieldSchema getField(String alias) {
Pair<Integer, Boolean> p = aliases.get(alias);
if (p == null) {
return null;
}
return fields.get(p.first);
}
/**
* Fetch a field by field number
* @param fieldNum field number to fetch
* @return field
*/
public LogicalFieldSchema getField(int fieldNum) {
return fields.get(fieldNum);
}
/**
* Get all fields
* @return list of all fields
*/
public List<LogicalFieldSchema> getFields() {
return fields;
}
/**
* Get the size of the schema.
* @return size
*/
public int size() {
return fields.size();
}
/**
* Two schemas are equal if they are of equal size and their fields
* schemas considered in order are equal.
*/
public boolean isEqual(Object other) {
if (other != null && other instanceof LogicalSchema) {
LogicalSchema os = (LogicalSchema)other;
if (size() != os.size()) return false;
for (int i = 0; i < size(); i++) {
if (!getField(i).isEqual(os.getField(i))) return false;
}
return true;
} else {
return false;
}
}
/**
* Look for the index of the field that contains the specified uid
* @param uid the uid to look for
* @return the index of the field, -1 if not found
*/
public int findField(long uid) {
for(int i=0; i< size(); i++) {
LogicalFieldSchema f = getField(i);
// if this field has the same uid, then return this field
if (f.uid == uid) {
return i;
}
// if this field has a schema, check its schema
if (f.schema != null) {
if (f.schema.findField(uid) != -1) {
return i;
}
}
}
return -1;
}
/**
* Merge two schemas.
* @param s1
* @param s2
* @return a merged schema, or null if the merge fails
*/
public static LogicalSchema merge(LogicalSchema s1, LogicalSchema s2) {
// TODO
return null;
}
public String toString() {
StringBuilder str = new StringBuilder();
for( LogicalFieldSchema field : fields ) {
str.append( field.toString() + "," );
}
if( fields.size() != 0 ) {
str.deleteCharAt( str.length() -1 );
}
return str.toString();
}
}
|
hirohanin/pig7hadoop21
|
src/org/apache/pig/experimental/logical/relational/LogicalSchema.java
|
Java
|
apache-2.0
| 7,432 |
package com.github.nikolaymakhonin.android_app_example.di.factories;
import android.content.Context;
import android.support.annotation.NonNull;
import com.github.nikolaymakhonin.android_app_example.di.components.AppComponent;
import com.github.nikolaymakhonin.android_app_example.di.components.DaggerAppComponent;
import com.github.nikolaymakhonin.android_app_example.di.components.DaggerServiceComponent;
import com.github.nikolaymakhonin.android_app_example.di.components.ServiceComponent;
import com.github.nikolaymakhonin.common_di.modules.service.ServiceModuleBase;
public final class ComponentsFactory {
public static AppComponent buildAppComponent(@NonNull Context appContext) {
ServiceComponent serviceComponent = buildServiceComponent(appContext);
AppComponent appComponent = DaggerAppComponent.builder()
.serviceComponent(serviceComponent)
.build();
return appComponent;
}
public static ServiceComponent buildServiceComponent(@NonNull Context appContext) {
ServiceComponent serviceComponent = DaggerServiceComponent.builder()
.serviceModuleBase(new ServiceModuleBase(appContext))
.build();
return serviceComponent;
}
}
|
NikolayMakhonin/AndroidAppExample
|
AndroidAppExample/AppExample/src/main/java/com/github/nikolaymakhonin/android_app_example/di/factories/ComponentsFactory.java
|
Java
|
apache-2.0
| 1,243 |
/* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2020, Arnaud Roques
*
* Project Info: https://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* https://plantuml.com/patreon (only 1$ per month!)
* https://plantuml.com/paypal
*
* This file is part of PlantUML.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* Original Author: Arnaud Roques
*/
package net.sourceforge.plantuml.objectdiagram.command;
import net.sourceforge.plantuml.LineLocation;
import net.sourceforge.plantuml.command.CommandExecutionResult;
import net.sourceforge.plantuml.command.SingleLineCommand2;
import net.sourceforge.plantuml.command.regex.IRegex;
import net.sourceforge.plantuml.command.regex.RegexConcat;
import net.sourceforge.plantuml.command.regex.RegexLeaf;
import net.sourceforge.plantuml.command.regex.RegexResult;
import net.sourceforge.plantuml.cucadiagram.IEntity;
import net.sourceforge.plantuml.objectdiagram.AbstractClassOrObjectDiagram;
import net.sourceforge.plantuml.skin.VisibilityModifier;
import net.sourceforge.plantuml.ugraphic.color.NoSuchColorException;
public class CommandAddData extends SingleLineCommand2<AbstractClassOrObjectDiagram> {
public CommandAddData() {
super(getRegexConcat());
}
static IRegex getRegexConcat() {
return RegexConcat.build(CommandAddData.class.getName(), RegexLeaf.start(), //
new RegexLeaf("NAME", "([%pLN_.]+)"), //
RegexLeaf.spaceZeroOrMore(), //
new RegexLeaf(":"), //
RegexLeaf.spaceZeroOrMore(), //
new RegexLeaf("DATA", "(.*)"), RegexLeaf.end()); //
}
@Override
protected CommandExecutionResult executeArg(AbstractClassOrObjectDiagram diagram, LineLocation location,
RegexResult arg) throws NoSuchColorException {
final String name = arg.get("NAME", 0);
final IEntity entity = diagram.getOrCreateLeaf(diagram.buildLeafIdent(name),
diagram.buildCode(name), null, null);
final String field = arg.get("DATA", 0);
if (field.length() > 0 && VisibilityModifier.isVisibilityCharacter(field)) {
diagram.setVisibilityModifierPresent(true);
}
entity.getBodier().addFieldOrMethod(field);
return CommandExecutionResult.ok();
}
}
|
talsma-ict/umldoclet
|
src/plantuml-asl/src/net/sourceforge/plantuml/objectdiagram/command/CommandAddData.java
|
Java
|
apache-2.0
| 2,860 |
/**
* 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.xml.security.test.stax.c14n;
import org.apache.xml.security.stax.impl.transformer.canonicalizer.Canonicalizer20010315_Excl;
import org.junit.Before;
import org.apache.xml.security.stax.ext.stax.XMLSecEvent;
import org.apache.xml.security.stax.impl.transformer.canonicalizer.Canonicalizer20010315_ExclOmitCommentsTransformer;
import org.apache.xml.security.stax.impl.transformer.canonicalizer.Canonicalizer20010315_ExclWithCommentsTransformer;
import org.apache.xml.security.test.stax.utils.XMLSecEventAllocator;
import org.apache.xml.security.utils.XMLUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author $Author: coheigea $
* @version $Revision: 1721336 $ $Date: 2015-12-22 10:45:18 +0000 (Tue, 22 Dec 2015) $
*/
public class Canonicalizer20010315ExclusiveTest extends org.junit.Assert {
private XMLInputFactory xmlInputFactory;
@Before
public void setUp() throws Exception {
this.xmlInputFactory = XMLInputFactory.newInstance();
this.xmlInputFactory.setEventAllocator(new XMLSecEventAllocator());
}
@org.junit.Test
public void test221excl() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Canonicalizer20010315_ExclWithCommentsTransformer c = new Canonicalizer20010315_ExclWithCommentsTransformer();
c.setOutputStream(baos);
XMLEventReader xmlSecEventReader = xmlInputFactory.createXMLEventReader(
this.getClass().getClassLoader().getResourceAsStream(
"org/apache/xml/security/c14n/inExcl/example2_2_1.xml")
);
XMLSecEvent xmlSecEvent = null;
while (xmlSecEventReader.hasNext()) {
xmlSecEvent = (XMLSecEvent) xmlSecEventReader.nextEvent();
if (xmlSecEvent.isStartElement() && xmlSecEvent.asStartElement().getName().equals(new QName("http://example.net", "elem2"))) {
break;
}
}
while (xmlSecEventReader.hasNext()) {
c.transform(xmlSecEvent);
if (xmlSecEvent.isEndElement() && xmlSecEvent.asEndElement().getName().equals(new QName("http://example.net", "elem2"))) {
break;
}
xmlSecEvent = (XMLSecEvent) xmlSecEventReader.nextEvent();
}
byte[] reference =
getBytesFromResource(this.getClass().getClassLoader().getResource(
"org/apache/xml/security/c14n/inExcl/example2_2_c14nized_exclusive.xml"));
boolean equals = java.security.MessageDigest.isEqual(reference, baos.toByteArray());
if (!equals) {
System.out.println("Expected:\n" + new String(reference, "UTF-8"));
System.out.println("");
System.out.println("Got:\n" + new String(baos.toByteArray(), "UTF-8"));
}
assertTrue(equals);
}
@org.junit.Test
public void test222excl() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Canonicalizer20010315_ExclWithCommentsTransformer c = new Canonicalizer20010315_ExclWithCommentsTransformer();
c.setOutputStream(baos);
canonicalize(c,
this.getClass().getClassLoader().getResourceAsStream(
"org/apache/xml/security/c14n/inExcl/example2_2_2.xml"),
new QName("http://example.net", "elem2")
);
byte[] reference =
getBytesFromResource(this.getClass().getClassLoader().getResource(
"org/apache/xml/security/c14n/inExcl/example2_2_c14nized_exclusive.xml"));
boolean equals = java.security.MessageDigest.isEqual(reference, baos.toByteArray());
if (!equals) {
System.out.println("Expected:\n" + new String(reference, "UTF-8"));
System.out.println("");
System.out.println("Got:\n" + new String(baos.toByteArray(), "UTF-8"));
}
assertTrue(equals);
}
@org.junit.Test
public void test24excl() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Canonicalizer20010315_ExclWithCommentsTransformer c = new Canonicalizer20010315_ExclWithCommentsTransformer();
c.setOutputStream(baos);
canonicalize(c,
this.getClass().getClassLoader().getResourceAsStream(
"org/apache/xml/security/c14n/inExcl/example2_4.xml"),
new QName("http://example.net", "elem2")
);
byte[] reference =
getBytesFromResource(this.getClass().getClassLoader().getResource(
"org/apache/xml/security/c14n/inExcl/example2_4_c14nized.xml"));
boolean equals = java.security.MessageDigest.isEqual(reference, baos.toByteArray());
if (!equals) {
System.out.println("Expected:\n" + new String(reference, "UTF-8"));
System.out.println("");
System.out.println("Got:\n" + new String(baos.toByteArray(), "UTF-8"));
}
assertTrue(equals);
}
@org.junit.Test
public void testComplexDocexcl() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Canonicalizer20010315_ExclWithCommentsTransformer c = new Canonicalizer20010315_ExclWithCommentsTransformer();
c.setOutputStream(baos);
canonicalize(c,
this.getClass().getClassLoader().getResourceAsStream(
"org/apache/xml/security/c14n/inExcl/plain-soap-1.1.xml"),
new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body", "env")
);
byte[] reference =
getBytesFromResource(this.getClass().getClassLoader().getResource(
"org/apache/xml/security/c14n/inExcl/plain-soap-c14nized.xml"));
boolean equals = java.security.MessageDigest.isEqual(reference, baos.toByteArray());
if (!equals) {
System.out.println("Expected:\n" + new String(reference, "UTF-8"));
System.out.println("");
System.out.println("Got:\n" + new String(baos.toByteArray(), "UTF-8"));
}
assertTrue(equals);
}
@org.junit.Test
public void testNodeSet() throws Exception {
final String XML =
"<env:Envelope"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</env:Envelope>";
final String c14nXML =
"<env:Body"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("env");
inclusiveNamespaces.add("ns0");
inclusiveNamespaces.add("xsi");
inclusiveNamespaces.add("wsu");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
/**
* Method test24Aexcl - a testcase for SANTUARIO-263
* "Canonicalizer can't handle dynamical created DOM correctly"
* https://issues.apache.org/jira/browse/SANTUARIO-263
*/
@org.junit.Test
public void test24Aexcl() throws Exception {
Document doc = XMLUtils.createDocumentBuilder(false).newDocument();
Element local = doc.createElementNS("foo:bar", "dsig:local");
Element test = doc.createElementNS("http://example.net", "etsi:test");
Element elem2 = doc.createElementNS("http://example.net", "etsi:elem2");
Element stuff = doc.createElementNS("foo:bar", "dsig:stuff");
elem2.appendChild(stuff);
test.appendChild(elem2);
local.appendChild(test);
doc.appendChild(local);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
StringWriter stringWriter = new StringWriter();
StreamResult streamResult = new StreamResult(stringWriter);
t.transform(new DOMSource(doc), streamResult);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
Canonicalizer20010315_ExclWithCommentsTransformer c =
new Canonicalizer20010315_ExclWithCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(stringWriter.toString()), new QName("http://example.net", "elem2"));
byte[] reference =
getBytesFromResource(this.getClass().getClassLoader().getResource(
"org/apache/xml/security/c14n/inExcl/example2_4_c14nized.xml"));
boolean equals = java.security.MessageDigest.isEqual(reference, baos.toByteArray());
assertTrue(equals);
}
/**
* Test default namespace behavior if its in the InclusiveNamespace prefix list.
*
* @throws Exception
*/
@org.junit.Test
public void testDefaultNSInInclusiveNamespacePrefixList1() throws Exception {
final String XML =
"<env:Envelope"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</env:Envelope>";
final String c14nXML =
"<env:Body"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xmlns:ns0=\"http://xmlsoap.org/Ping\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("#default");
inclusiveNamespaces.add("xsi");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
{
//exactly the same outcome is expected if #default is not set:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("xsi");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
}
/**
* Test default namespace behavior if its in the InclusiveNamespace prefix list.
*
* @throws Exception
*/
@org.junit.Test
public void testDefaultNSInInclusiveNamespacePrefixList2() throws Exception {
final String XML =
"<env:Envelope"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns=\"http://example.com\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xmlns=\"\" xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</env:Envelope>";
final String c14nXML1 =
"<env:Body"
+ " xmlns=\"http://example.com\""
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xmlns:ns0=\"http://xmlsoap.org/Ping\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xmlns=\"\" xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
final String c14nXML2 =
"<env:Body"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xmlns:ns0=\"http://xmlsoap.org/Ping\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("#default");
inclusiveNamespaces.add("xsi");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML1);
}
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("xsi");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML2);
}
}
/**
* Test default namespace behavior if its in the InclusiveNamespace prefix list.
*
* @throws Exception
*/
@org.junit.Test
public void testDefaultNSInInclusiveNamespacePrefixList3() throws Exception {
final String XML =
"<env:Envelope"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns=\"\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</env:Envelope>";
final String c14nXML =
"<env:Body"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xmlns:ns0=\"http://xmlsoap.org/Ping\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("#default");
inclusiveNamespaces.add("xsi");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
{
//exactly the same outcome is expected if #default is not set:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("xsi");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
}
/**
* Test default namespace behavior if its in the InclusiveNamespace prefix list.
*
* @throws Exception
*/
@org.junit.Test
public void testDefaultNSInInclusiveNamespacePrefixList4() throws Exception {
final String XML =
"<env:Envelope"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xmlns=\"\" xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</env:Envelope>";
final String c14nXML =
"<env:Body"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xmlns:ns0=\"http://xmlsoap.org/Ping\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("#default");
inclusiveNamespaces.add("xsi");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
{
//exactly the same outcome is expected if #default is not set:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("xsi");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
}
/**
* Test default namespace behavior if its in the InclusiveNamespace prefix list.
*
* @throws Exception
*/
@org.junit.Test
public void testPropagateDefaultNs1() throws Exception {
final String XML =
"<env:Envelope"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</env:Envelope>";
final String c14nXML =
"<env:Body"
+ " xmlns=\"\""
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xmlns:ns0=\"http://xmlsoap.org/Ping\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("#default");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
transformerProperties.put(Canonicalizer20010315_Excl.PROPAGATE_DEFAULT_NAMESPACE, Boolean.TRUE);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
@org.junit.Test
public void testPropagateDefaultNs2() throws Exception {
final String XML =
"<env:Envelope"
+ " xmlns=\"http://example.com\""
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</env:Envelope>";
final String c14nXML =
"<env:Body"
+ " xmlns=\"http://example.com\""
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xmlns:ns0=\"http://xmlsoap.org/Ping\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("#default");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
transformerProperties.put(Canonicalizer20010315_Excl.PROPAGATE_DEFAULT_NAMESPACE, Boolean.TRUE);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
@org.junit.Test
public void testPropagateDefaultNs3() throws Exception {
final String XML =
"<Envelope"
+ " xmlns=\"http://example.com\""
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xmlns=\"\" xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</Envelope>";
final String c14nXML =
"<env:Body"
+ " xmlns=\"http://example.com\""
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xmlns:ns0=\"http://xmlsoap.org/Ping\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xmlns=\"\" xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("#default");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
transformerProperties.put(Canonicalizer20010315_Excl.PROPAGATE_DEFAULT_NAMESPACE, Boolean.TRUE);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
@org.junit.Test
public void testPropagateDefaultNs4() throws Exception {
final String XML =
"<Envelope"
+ " xmlns=\"\""
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</Envelope>";
final String c14nXML =
"<env:Body"
+ " xmlns=\"\""
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xmlns:ns0=\"http://xmlsoap.org/Ping\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("#default");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
transformerProperties.put(Canonicalizer20010315_Excl.PROPAGATE_DEFAULT_NAMESPACE, Boolean.TRUE);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
@org.junit.Test
public void testPropagateDefaultNs5() throws Exception {
final String XML =
"<env:Envelope"
+ " xmlns=\"http://example.com\""
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body xmlns=\"\" wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</env:Envelope>";
final String c14nXML =
"<ns0:Ping xmlns=\"\" xmlns:ns0=\"http://xmlsoap.org/Ping\" " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("#default");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
transformerProperties.put(Canonicalizer20010315_Excl.PROPAGATE_DEFAULT_NAMESPACE, Boolean.TRUE);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://xmlsoap.org/Ping", "Ping"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
private void canonicalize(
Canonicalizer20010315_Excl c, InputStream inputStream, QName elementName)
throws XMLStreamException {
canonicalize(c, xmlInputFactory.createXMLEventReader(inputStream), elementName);
}
private void canonicalize(
Canonicalizer20010315_Excl c, Reader reader, QName elementName)
throws XMLStreamException {
canonicalize(c, xmlInputFactory.createXMLEventReader(reader), elementName);
}
private void canonicalize(
Canonicalizer20010315_Excl c, XMLEventReader xmlEventReader, QName elementName)
throws XMLStreamException {
XMLSecEvent xmlSecEvent = null;
while (xmlEventReader.hasNext()) {
xmlSecEvent = (XMLSecEvent) xmlEventReader.nextEvent();
if (xmlSecEvent.isStartElement() && xmlSecEvent.asStartElement().getName().equals(elementName)) {
break;
}
}
while (xmlEventReader.hasNext()) {
c.transform(xmlSecEvent);
if (xmlSecEvent.isEndElement() && xmlSecEvent.asEndElement().getName().equals(elementName)) {
break;
}
xmlSecEvent = (XMLSecEvent) xmlEventReader.nextEvent();
}
}
public static byte[] getBytesFromResource(URL resource) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream inputStream = resource.openStream();
try {
byte buf[] = new byte[1024];
int len;
while ((len = inputStream.read(buf)) > 0) {
baos.write(buf, 0, len);
}
return baos.toByteArray();
} finally {
inputStream.close();
}
}
}
|
Legostaev/xmlsec-gost
|
src/test/java/org/apache/xml/security/test/stax/c14n/Canonicalizer20010315ExclusiveTest.java
|
Java
|
apache-2.0
| 40,733 |
/*
* Copyright 2015 OpenCB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opencb.biodata.formats.io;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractFormatReader<T> {
protected Path path;
protected Logger logger;
protected AbstractFormatReader() {
path = null;
logger = LoggerFactory.getLogger(AbstractFormatReader.class);
// logger.setLevel(Logger.DEBUG_LEVEL);
}
protected AbstractFormatReader(Path f) throws IOException {
Files.exists(f);
this.path = f;
logger = LoggerFactory.getLogger(AbstractFormatReader.class);
// logger.setLevel(Logger.DEBUG_LEVEL);
}
public abstract int size() throws IOException, FileFormatException;
public abstract T read() throws FileFormatException;
public abstract T read(String regexFilter) throws FileFormatException;
public abstract List<T> read(int size) throws FileFormatException;
public abstract List<T> readAll() throws FileFormatException, IOException;
public abstract List<T> readAll(String pattern) throws FileFormatException;
public abstract void close() throws IOException;
}
|
kalyanreddyemani/biodata
|
biodata-formats/src/main/java/org/opencb/biodata/formats/io/AbstractFormatReader.java
|
Java
|
apache-2.0
| 1,817 |
package org.ovirt.engine.ui.uicommonweb.models.configure.roles_ui;
import java.util.ArrayList;
import org.ovirt.engine.core.common.businessentities.ActionGroup;
import org.ovirt.engine.core.common.mode.ApplicationMode;
import org.ovirt.engine.ui.uicommonweb.models.ApplicationModeHelper;
import org.ovirt.engine.ui.uicommonweb.models.common.SelectionTreeNodeModel;
import org.ovirt.engine.ui.uicompat.ConstantsManager;
@SuppressWarnings("unused")
public class RoleTreeView
{
public static ArrayList<SelectionTreeNodeModel> GetRoleTreeView(boolean isReadOnly, boolean isAdmin)
{
RoleNode tree = initTreeView();
ArrayList<ActionGroup> userActionGroups = null;
if (isAdmin == false)
{
userActionGroups = GetUserActionGroups();
}
ArrayList<SelectionTreeNodeModel> roleTreeView = new ArrayList<SelectionTreeNodeModel>();
SelectionTreeNodeModel firstNode = null, secondNode = null, thirdNode = null;
for (RoleNode first : tree.getLeafRoles())
{
firstNode = new SelectionTreeNodeModel();
firstNode.setTitle(first.getName());
firstNode.setDescription(first.getName());
firstNode.setIsChangable(!isReadOnly);
for (RoleNode second : first.getLeafRoles())
{
secondNode = new SelectionTreeNodeModel();
secondNode.setTitle(second.getName());
secondNode.setDescription(second.getName());
secondNode.setIsChangable(!isReadOnly);
secondNode.setTooltip(second.getTooltip());
for (RoleNode third : second.getLeafRoles())
{
thirdNode = new SelectionTreeNodeModel();
thirdNode.setTitle(third.getName());
thirdNode.setDescription(third.getDesc());
thirdNode.setIsSelectedNotificationPrevent(true);
// thirdNode.IsSelected =
// attachedActions.Contains((VdcActionType) Enum.Parse(typeof (VdcActionType), name)); //TODO:
// suppose to be action group
thirdNode.setIsChangable(!isReadOnly);
thirdNode.setIsSelectedNullable(false);
thirdNode.setTooltip(third.getTooltip());
if (!isAdmin)
{
if (userActionGroups.contains(ActionGroup.valueOf(thirdNode.getTitle())))
{
secondNode.getChildren().add(thirdNode);
}
}
else
{
secondNode.getChildren().add(thirdNode);
}
}
if (secondNode.getChildren().size() > 0)
{
firstNode.getChildren().add(secondNode);
}
}
if (firstNode.getChildren().size() > 0)
{
roleTreeView.add(firstNode);
}
}
return roleTreeView;
}
private static ArrayList<ActionGroup> GetUserActionGroups() {
ArrayList<ActionGroup> array = new ArrayList<ActionGroup>();
array.add(ActionGroup.CREATE_VM);
array.add(ActionGroup.DELETE_VM);
array.add(ActionGroup.EDIT_VM_PROPERTIES);
array.add(ActionGroup.VM_BASIC_OPERATIONS);
array.add(ActionGroup.CHANGE_VM_CD);
array.add(ActionGroup.MIGRATE_VM);
array.add(ActionGroup.CONNECT_TO_VM);
array.add(ActionGroup.CONFIGURE_VM_NETWORK);
array.add(ActionGroup.CONFIGURE_VM_STORAGE);
array.add(ActionGroup.MOVE_VM);
array.add(ActionGroup.MANIPULATE_VM_SNAPSHOTS);
array.add(ActionGroup.CREATE_TEMPLATE);
array.add(ActionGroup.EDIT_TEMPLATE_PROPERTIES);
array.add(ActionGroup.DELETE_TEMPLATE);
array.add(ActionGroup.COPY_TEMPLATE);
array.add(ActionGroup.CONFIGURE_TEMPLATE_NETWORK);
array.add(ActionGroup.CREATE_VM_POOL);
array.add(ActionGroup.EDIT_VM_POOL_CONFIGURATION);
array.add(ActionGroup.DELETE_VM_POOL);
array.add(ActionGroup.VM_POOL_BASIC_OPERATIONS);
array.add(ActionGroup.MANIPULATE_PERMISSIONS);
array.add(ActionGroup.CREATE_DISK);
array.add(ActionGroup.ATTACH_DISK);
array.add(ActionGroup.DELETE_DISK);
array.add(ActionGroup.CONFIGURE_DISK_STORAGE);
array.add(ActionGroup.EDIT_DISK_PROPERTIES);
array.add(ActionGroup.LOGIN);
array.add(ActionGroup.CHANGE_VM_CUSTOM_PROPERTIES);
array.add(ActionGroup.PORT_MIRRORING);
return array;
}
private static RoleNode initTreeView()
{
RoleNode tree =
new RoleNode(ConstantsManager.getInstance().getConstants().rootRoleTree(),
new RoleNode[] {
new RoleNode(ConstantsManager.getInstance().getConstants().systemRoleTree(),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.configureSystemRoleTree(),
new RoleNode[] {
new RoleNode(ActionGroup.MANIPULATE_USERS,
ConstantsManager.getInstance()
.getConstants()
.allowToAddRemoveUsersFromTheSystemRoleTreeTooltip()),
new RoleNode(ActionGroup.MANIPULATE_PERMISSIONS,
ConstantsManager.getInstance()
.getConstants()
.allowToAddRemovePermissionsForUsersOnObjectsInTheSystemRoleTreeTooltip()),
new RoleNode(ActionGroup.MANIPULATE_ROLES,
ConstantsManager.getInstance()
.getConstants()
.allowToDefineConfigureRolesInTheSystemRoleTreeTooltip()),
new RoleNode(ActionGroup.LOGIN,
ConstantsManager.getInstance()
.getConstants()
.allowToLoginToTheSystemRoleTreeTooltip()),
new RoleNode(ActionGroup.CONFIGURE_ENGINE,
ConstantsManager.getInstance()
.getConstants()
.allowToGetOrSetSystemConfigurationRoleTreeTooltip()) })),
new RoleNode(ConstantsManager.getInstance().getConstants().dataCenterRoleTree(),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.configureDataCenterRoleTree(),
new RoleNode[] {
new RoleNode(ActionGroup.CREATE_STORAGE_POOL,
ConstantsManager.getInstance()
.getConstants()
.allowToCreateDataCenterRoleTreeTooltip()),
new RoleNode(ActionGroup.DELETE_STORAGE_POOL,
ConstantsManager.getInstance()
.getConstants()
.allowToRemoveDataCenterRoleTreeTooltip()),
new RoleNode(ActionGroup.EDIT_STORAGE_POOL_CONFIGURATION,
ConstantsManager.getInstance()
.getConstants()
.allowToModifyDataCenterPropertiesRoleTreeTooltip()),
new RoleNode(ActionGroup.CONFIGURE_STORAGE_POOL_NETWORK,
ConstantsManager.getInstance()
.getConstants()
.allowToConfigureLogicalNetworkPerDataCenterRoleTreeTooltip()) })),
new RoleNode(ConstantsManager.getInstance().getConstants().storageDomainRoleTree(),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.configureStorageDomainRoleTree(),
new RoleNode[] {
new RoleNode(ActionGroup.CREATE_STORAGE_DOMAIN,
ConstantsManager.getInstance()
.getConstants()
.allowToCreateStorageDomainRoleTreeTooltip()),
new RoleNode(ActionGroup.DELETE_STORAGE_DOMAIN,
ConstantsManager.getInstance()
.getConstants()
.allowToDeleteStorageDomainRoleTreeTooltip()),
new RoleNode(ActionGroup.EDIT_STORAGE_DOMAIN_CONFIGURATION,
ConstantsManager.getInstance()
.getConstants()
.allowToModifyStorageDomainPropertiesRoleTreeTooltip()),
new RoleNode(ActionGroup.MANIPULATE_STORAGE_DOMAIN,
ConstantsManager.getInstance()
.getConstants()
.allowToChangeStorageDomainStatusRoleTreeTooltip()) })),
new RoleNode(ConstantsManager.getInstance().getConstants().clusterRoleTree(),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.configureClusterRoleTree(),
new RoleNode[] {
new RoleNode(ActionGroup.CREATE_CLUSTER,
ConstantsManager.getInstance()
.getConstants()
.allowToCreateNewClusterRoleTreeTooltip()),
new RoleNode(ActionGroup.DELETE_CLUSTER,
ConstantsManager.getInstance()
.getConstants()
.allowToRemoveClusterRoleTreeTooltip()),
new RoleNode(ActionGroup.EDIT_CLUSTER_CONFIGURATION,
ConstantsManager.getInstance()
.getConstants()
.allowToEditClusterPropertiesRoleTreeTooltip()),
new RoleNode(ActionGroup.CONFIGURE_CLUSTER_NETWORK,
ConstantsManager.getInstance()
.getConstants()
.allowToAddRemoveLogicalNetworksForTheClusterRoleTreeTooltip()) })),
new RoleNode(ConstantsManager.getInstance().getConstants().glusterRoleTree(),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.configureVolumesRoleTree(),
new RoleNode[] {
new RoleNode(ActionGroup.CREATE_GLUSTER_VOLUME,
ConstantsManager.getInstance()
.getConstants()
.allowToCreateGlusterVolumesRoleTree()),
new RoleNode(ActionGroup.MANIPULATE_GLUSTER_VOLUME,
ConstantsManager.getInstance()
.getConstants()
.allowToManipulateGlusterVolumesRoleTree()) })),
new RoleNode(ConstantsManager.getInstance().getConstants().hostRoleTree(),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.configureHostRoleTree(),
new RoleNode[] {
new RoleNode(ActionGroup.CREATE_HOST,
ConstantsManager.getInstance()
.getConstants()
.allowToAddNewHostToTheClusterRoleTreeTooltip()),
new RoleNode(ActionGroup.DELETE_HOST,
ConstantsManager.getInstance()
.getConstants()
.allowToRemoveExistingHostFromTheClusterRoleTreeTooltip()),
new RoleNode(ActionGroup.EDIT_HOST_CONFIGURATION,
ConstantsManager.getInstance()
.getConstants()
.allowToEditHostPropertiesRoleTreeTooltip()),
new RoleNode(ActionGroup.MANIPUTLATE_HOST,
ConstantsManager.getInstance()
.getConstants()
.allowToChangeHostStatusRoleTreeTooltip()),
new RoleNode(ActionGroup.CONFIGURE_HOST_NETWORK,
ConstantsManager.getInstance()
.getConstants()
.allowToConfigureHostsNetworkPhysicalInterfacesRoleTreeTooltip()) })),
new RoleNode(ConstantsManager.getInstance().getConstants().templateRoleTree(),
new RoleNode[] {
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.basicOperationsRoleTree(),
new RoleNode[] {
new RoleNode(ActionGroup.EDIT_TEMPLATE_PROPERTIES,
ConstantsManager.getInstance()
.getConstants()
.allowToChangeTemplatePropertiesRoleTreeTooltip()),
new RoleNode(ActionGroup.CONFIGURE_TEMPLATE_NETWORK,
ConstantsManager.getInstance()
.getConstants()
.allowToConfigureTemlateNetworkRoleTreeTooltip()) }),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.provisioningOperationsRoleTree(),
ConstantsManager.getInstance()
.getConstants()
.notePermissionsContainigTheseOperationsShuoldAssociatSdOrAboveRoleTreeTooltip(),
new RoleNode[] {
new RoleNode(ActionGroup.CREATE_TEMPLATE,
ConstantsManager.getInstance()
.getConstants()
.allowToCreateNewTemplateRoleTreeTooltip()),
new RoleNode(ActionGroup.DELETE_TEMPLATE,
ConstantsManager.getInstance()
.getConstants()
.allowToRemoveExistingTemplateRoleTreeTooltip()),
new RoleNode(ActionGroup.IMPORT_EXPORT_VM,
ConstantsManager.getInstance()
.getConstants()
.allowImportExportOperationsRoleTreeTooltip()),
new RoleNode(ActionGroup.COPY_TEMPLATE,
ConstantsManager.getInstance()
.getConstants()
.allowToCopyTemplateBetweenStorageDomainsRoleTreeTooltip()) }) }),
new RoleNode(ConstantsManager.getInstance().getConstants().vmRoleTree(),
new RoleNode[] {
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.basicOperationsRoleTree(),
new RoleNode[] {
new RoleNode(ActionGroup.VM_BASIC_OPERATIONS,
ConstantsManager.getInstance()
.getConstants()
.allowBasicVmOperationsRoleTreeTooltip()),
new RoleNode(ActionGroup.CHANGE_VM_CD,
ConstantsManager.getInstance()
.getConstants()
.allowToAttachCdToTheVmRoleTreeTooltip()),
new RoleNode(ActionGroup.CONNECT_TO_VM,
ConstantsManager.getInstance()
.getConstants()
.allowViewingTheVmConsoleScreenRoleTreeTooltip()) }),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.provisioningOperationsRoleTree(),
ConstantsManager.getInstance()
.getConstants()
.notePermissionsContainigTheseOperationsShuoldAssociatSdOrAboveRoleTreeTooltip(),
new RoleNode[] {
new RoleNode(ActionGroup.EDIT_VM_PROPERTIES,
ConstantsManager.getInstance()
.getConstants()
.allowChangeVmPropertiesRoleTreeTooltip()),
new RoleNode(ActionGroup.CREATE_VM,
ConstantsManager.getInstance()
.getConstants()
.allowToCreateNewVmsRoleTreeTooltip()),
new RoleNode(ActionGroup.DELETE_VM,
ConstantsManager.getInstance()
.getConstants()
.allowToRemoveVmsFromTheSystemRoleTreeTooltip()),
new RoleNode(ActionGroup.IMPORT_EXPORT_VM,
ConstantsManager.getInstance()
.getConstants()
.allowImportExportOperationsRoleTreeTooltip()),
new RoleNode(ActionGroup.CONFIGURE_VM_NETWORK,
ConstantsManager.getInstance()
.getConstants()
.allowToConfigureVMsNetworkRoleTreeTooltip()),
new RoleNode(ActionGroup.CONFIGURE_VM_STORAGE,
ConstantsManager.getInstance()
.getConstants()
.allowToAddRemoveDiskToTheVmRoleTreeTooltip()),
new RoleNode(ActionGroup.MANIPULATE_VM_SNAPSHOTS,
ConstantsManager.getInstance()
.getConstants()
.allowToCreateDeleteSnapshotsOfTheVmRoleTreeTooltip()) }),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.administrationOperationsRoleTree(),
ConstantsManager.getInstance()
.getConstants()
.notePermissionsContainigTheseOperationsShuoldAssociatDcOrEqualRoleTreeTooltip(),
new RoleNode[] {
new RoleNode(ActionGroup.MOVE_VM,
ConstantsManager.getInstance()
.getConstants()
.allowToMoveVmImageToAnotherStorageDomainRoleTreeTooltip()),
new RoleNode(ActionGroup.MIGRATE_VM,
ConstantsManager.getInstance()
.getConstants()
.allowMigratingVmBetweenHostsInClusterRoleTreeTooltip()),
new RoleNode(ActionGroup.CHANGE_VM_CUSTOM_PROPERTIES,
ConstantsManager.getInstance()
.getConstants()
.allowMigratingVmBetweenHostsInClusterRoleTreeTooltip()),
new RoleNode(ActionGroup.PORT_MIRRORING,
ConstantsManager.getInstance()
.getConstants()
.allowVmNetworkPortMirroringRoleTreeTooltip()) }) }),
new RoleNode(ConstantsManager.getInstance().getConstants().vmPoolRoleTree(),
new RoleNode[] {
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.basicOperationsRoleTree(),
new RoleNode[] { new RoleNode(ActionGroup.VM_POOL_BASIC_OPERATIONS,
ConstantsManager.getInstance()
.getConstants()
.allowToRunPauseStopVmFromVmPoolRoleTreeTooltip()) }),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.provisioningOperationsRoleTree(),
ConstantsManager.getInstance()
.getConstants()
.notePermissionsContainigTheseOperationsShuoldAssociatSdOrAboveRoleTreeTooltip(),
new RoleNode[] {
new RoleNode(ActionGroup.CREATE_VM_POOL,
ConstantsManager.getInstance()
.getConstants()
.allowToCreateVmPoolRoleTreeTooltip()),
new RoleNode(ActionGroup.DELETE_VM_POOL,
ConstantsManager.getInstance()
.getConstants()
.allowToDeleteVmPoolRoleTreeTooltip()),
new RoleNode(ActionGroup.EDIT_VM_POOL_CONFIGURATION,
ConstantsManager.getInstance()
.getConstants()
.allowToChangePropertiesOfTheVmPoolRoleTreeTooltip()) }) }),
new RoleNode(ConstantsManager.getInstance().getConstants().diskRoleTree(),
new RoleNode[] {
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.provisioningOperationsRoleTree(),
ConstantsManager.getInstance()
.getConstants()
.notePermissionsContainingOperationsRoleTreeTooltip(),
new RoleNode[] {
new RoleNode(ActionGroup.CREATE_DISK,
ConstantsManager.getInstance()
.getConstants()
.allowToCreateDiskRoleTreeTooltip()),
new RoleNode(ActionGroup.DELETE_DISK,
ConstantsManager.getInstance()
.getConstants()
.allowToDeleteDiskRoleTreeTooltip()),
new RoleNode(ActionGroup.CONFIGURE_DISK_STORAGE,
ConstantsManager.getInstance()
.getConstants()
.allowToMoveDiskToAnotherStorageDomainRoleTreeTooltip()),
new RoleNode(ActionGroup.ATTACH_DISK,
ConstantsManager.getInstance()
.getConstants()
.allowToAttachDiskToVmRoleTreeTooltip()),
new RoleNode(ActionGroup.EDIT_DISK_PROPERTIES,
ConstantsManager.getInstance()
.getConstants()
.allowToChangePropertiesOfTheDiskRoleTreeTooltip()) }) }) });
// nothing to filter
if (!ApplicationModeHelper.getUiMode().equals(ApplicationMode.AllModes)) {
ApplicationModeHelper.filterActionGroupTreeByApplictionMode(tree);
}
return tree;
}
}
|
derekhiggins/ovirt-engine
|
frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/configure/roles_ui/RoleTreeView.java
|
Java
|
apache-2.0
| 34,814 |
package com.jpattern.core.command;
import com.jpattern.core.IProvider;
import com.jpattern.core.exception.NullProviderException;
import com.jpattern.logger.ILogger;
import com.jpattern.logger.SystemOutLoggerFactory;
/**
*
* @author Francesco Cina'
*
* 11/set/2011
*/
public abstract class ACommand<T extends IProvider> {
private ICommandExecutor commandExecutor;
private IOnExceptionStrategy onExceptionStrategy;
private T provider;
private ILogger logger = null;
private boolean executed = false;
private boolean rolledback = false;
/**
* This method launch the execution of the command (or chain of commands) using the default
* default Executor and catching every runtime exception.
* This command is the same of:
* exec(provider, true);
* @return the result of the execution
*/
public final ACommandResult exec(T provider) {
return exec(provider, new DefaultCommandExecutor());
}
/**
* This method launch the execution of the command (or chain of commands).
* Every command in the chain will be managed by an ICommandExecutor object.
* This command is the same of:
* exec(commandExecutor, true);
* @param aCommandExecutor the pool in which the command will runs
* @return the result of the execution
*/
public final ACommandResult exec(T provider, ICommandExecutor commandExecutor) {
visit(provider);
return exec( commandExecutor, new CommandResult());
}
/**
* This method launch the rollback of the command execution (or chain of commands) using the default
* default Executor and catching every runtime exception.
* The rollback is effectively performed only if the command has been executed with a positive result, otherwise
* the command is intended as "not executed" then no rollback will be performed.
* This command is the same of:
* rollback(provider, true);
* @return the result of the rollback
*/
public final ACommandResult rollback(T provider) {
return rollback(provider, new DefaultCommandExecutor());
}
/**
* This method launch the rollback of the command execution (or chain of commands) using a custom command executor.
* The rollback is effectively performed only if the command has been executed with a positive result, otherwise
* the command is intended as "not executed" then no rollback will be performed.
* This command is the same of:
* rollback(provider, commandExecutor, true);
* @return the result of the rollback
*/
public final ACommandResult rollback(T provider, ICommandExecutor commandExecutor) {
visit(provider);
return rollback(commandExecutor, new CommandResult());
}
void visit(T provider) {
this.provider = provider;
}
protected final ACommandResult exec(ICommandExecutor commandExecutor, ACommandResult commandResult) {
this.commandExecutor = commandExecutor;
commandResult.setExecutionStart(this);
getCommandExecutor().execute(this, commandResult);
return commandResult;
}
protected final ACommandResult rollback(ICommandExecutor commandExecutor, ACommandResult commandResult) {
this.commandExecutor = commandExecutor;
commandResult.setExecutionStart(this);
getCommandExecutor().rollback(this, commandResult);
return commandResult;
}
protected final ICommandExecutor getCommandExecutor() {
if (commandExecutor==null) {
commandExecutor = new DefaultCommandExecutor();
}
return commandExecutor;
}
protected final T getProvider() {
if (provider==null) {
throw new NullProviderException();
}
return provider;
}
protected final ILogger getLogger() {
if (logger == null) {
if (provider == null) {
logger = new SystemOutLoggerFactory().logger(getClass());
} else {
logger = getProvider().getLoggerService().logger(this.getClass());
}
}
return logger;
}
public void setOnExceptionStrategy(IOnExceptionStrategy onExceptionStrategy) {
this.onExceptionStrategy = onExceptionStrategy;
}
public IOnExceptionStrategy getOnExceptionStrategy() {
if (onExceptionStrategy == null) {
onExceptionStrategy = new CatchOnExceptionStrategy();
}
return onExceptionStrategy;
}
protected final void doExec(ACommandResult commandResult) {
try {
int errorSize = commandResult.getErrorMessages().size();
executed = false;
rolledback = false;
execute(commandResult);
executed = commandResult.getErrorMessages().size() == errorSize;
} catch (RuntimeException e) {
getOnExceptionStrategy().onException(e, getLogger(), commandResult, "RuntimeException thrown");
} finally {
try {
postExecute(commandResult);
} finally {
commandResult.setExecutionEnd(this);
}
}
}
void postExecute(ACommandResult commandResult) {
}
void postRollback(ACommandResult commandResult) {
}
protected final void doRollback(ACommandResult commandResult) {
try {
if (executed && !rolledback) {
rollback(commandResult);
rolledback = true;
}
} catch (RuntimeException e) {
getOnExceptionStrategy().onException(e, getLogger(), commandResult, "RuntimeException thrown while rollbacking");
} finally {
try {
postRollback(commandResult);
} finally {
commandResult.setExecutionEnd(this);
}
}
}
protected abstract void execute(ACommandResult commandResult);
protected abstract void rollback(ACommandResult commandResult);
void setExecuted(boolean executed) {
this.executed = executed;
}
boolean isExecuted() {
return executed;
}
void setRolledback(boolean rolledback) {
this.rolledback = rolledback;
}
boolean isRolledback() {
return rolledback;
}
}
|
ufoscout/jpattern
|
core/src/main/java/com/jpattern/core/command/ACommand.java
|
Java
|
apache-2.0
| 5,668 |
/*
* Copyright 2017 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.internal.hash;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Output stream decorator that hashes data written to the stream.
* Inspired by the Google Guava project.
*/
public final class HashingOutputStream extends FilterOutputStream {
private final Hasher hasher;
public HashingOutputStream(HashFunction hashFunction, OutputStream out) {
super(checkNotNull(out));
this.hasher = checkNotNull(hashFunction.newHasher());
}
@Override
public void write(int b) throws IOException {
hasher.putByte((byte) b);
out.write(b);
}
@Override
public void write(byte[] bytes, int off, int len) throws IOException {
hasher.putBytes(bytes, off, len);
out.write(bytes, off, len);
}
public HashCode hash() {
return hasher.hash();
}
@Override
public void close() throws IOException {
out.close();
}
}
|
gstevey/gradle
|
subprojects/base-services/src/main/java/org/gradle/internal/hash/HashingOutputStream.java
|
Java
|
apache-2.0
| 1,665 |
/*
* Copyright (c) 2014 Spotify AB.
*
* 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.spotify.helios.agent;
import com.spotify.docker.client.ContainerNotFoundException;
import com.spotify.docker.client.DockerClient;
import com.spotify.docker.client.DockerException;
import com.spotify.docker.client.messages.ContainerInfo;
import com.spotify.helios.common.descriptors.Goal;
import com.spotify.helios.common.descriptors.Job;
import com.spotify.helios.servicescommon.DefaultReactor;
import com.spotify.helios.servicescommon.Reactor;
import com.spotify.helios.servicescommon.statistics.MetricsContext;
import com.spotify.helios.servicescommon.statistics.SupervisorMetrics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InterruptedIOException;
import java.util.concurrent.TimeUnit;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static com.spotify.helios.common.descriptors.TaskStatus.State.STOPPED;
import static com.spotify.helios.common.descriptors.TaskStatus.State.STOPPING;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
* Supervises docker containers for a single job.
*/
public class Supervisor {
public interface Listener {
void stateChanged(Supervisor supervisor);
}
private static final Logger log = LoggerFactory.getLogger(Supervisor.class);
private final DockerClient docker;
private final Job job;
private final RestartPolicy restartPolicy;
private final SupervisorMetrics metrics;
private final Reactor reactor;
private final Listener listener;
private final TaskRunnerFactory runnerFactory;
private final StatusUpdater statusUpdater;
private final TaskMonitor monitor;
private final Sleeper sleeper;
private volatile Goal goal;
private volatile String containerId;
private volatile TaskRunner runner;
private volatile Command currentCommand;
private volatile Command performedCommand;
public Supervisor(final Builder builder) {
this.job = checkNotNull(builder.job, "job");
this.docker = checkNotNull(builder.dockerClient, "docker");
this.restartPolicy = checkNotNull(builder.restartPolicy, "restartPolicy");
this.metrics = checkNotNull(builder.metrics, "metrics");
this.listener = checkNotNull(builder.listener, "listener");
this.currentCommand = new Nop();
this.containerId = builder.existingContainerId;
this.runnerFactory = checkNotNull(builder.runnerFactory, "runnerFactory");
this.statusUpdater = checkNotNull(builder.statusUpdater, "statusUpdater");
this.monitor = checkNotNull(builder.monitor, "monitor");
this.reactor = new DefaultReactor("supervisor-" + job.getId(), new Update(),
SECONDS.toMillis(30));
this.reactor.startAsync();
statusUpdater.setContainerId(containerId);
this.sleeper = builder.sleeper;
}
public void setGoal(final Goal goal) {
if (this.goal == goal) {
return;
}
log.debug("Supervisor {}: setting goal: {}", job.getId(), goal);
this.goal = goal;
statusUpdater.setGoal(goal);
switch (goal) {
case START:
currentCommand = new Start();
reactor.signal();
metrics.supervisorStarted();
break;
case STOP:
case UNDEPLOY:
currentCommand = new Stop();
reactor.signal();
metrics.supervisorStopped();
break;
}
}
/**
* Close this supervisor. The actual container is left as-is.
*/
public void close() {
reactor.stopAsync();
if (runner != null) {
runner.stopAsync();
}
metrics.supervisorClosed();
monitor.close();
}
/**
* Wait for supervisor to stop after closing it.
*/
public void join() {
reactor.awaitTerminated();
if (runner != null) {
// Stop the runner again in case it was rewritten by the reactor before it terminated.
runner.stopAsync();
runner.awaitTerminated();
}
}
/**
* Check if the current command is start.
* @return True if current command is start, otherwise false.
*/
public boolean isStarting() {
return currentCommand instanceof Start;
}
/**
* Check if the current command is stop.
* @return True if current command is stop, otherwise false.
*/
public boolean isStopping() {
return currentCommand instanceof Stop;
}
/**
* Check whether the last start/stop command is done.
* @return True if last start/stop command is done, otherwise false.
*/
public boolean isDone() {
return currentCommand == performedCommand;
}
/**
* Get the current container id
* @return The container id.
*/
public String containerId() {
return containerId;
}
private class Update implements Reactor.Callback {
@Override
public void run(final boolean timeout) throws InterruptedException {
final Command command = currentCommand;
final boolean done = performedCommand == command;
log.debug("Supervisor {}: update: performedCommand={}, command={}, done={}",
job.getId(), performedCommand, command, done);
command.perform(done);
if (!done) {
performedCommand = command;
fireStateChanged();
}
}
}
private void fireStateChanged() {
log.debug("Supervisor {}: state changed", job.getId());
try {
listener.stateChanged(this);
} catch (Exception e) {
log.error("Listener threw exception", e);
}
}
public static Builder newBuilder() {
return new Builder();
}
public static class Builder {
private Builder() {
}
private Job job;
private String existingContainerId;
private DockerClient dockerClient;
private RestartPolicy restartPolicy;
private SupervisorMetrics metrics;
private Listener listener = new NopListener();
private TaskRunnerFactory runnerFactory;
private StatusUpdater statusUpdater;
private TaskMonitor monitor;
private Sleeper sleeper = new ThreadSleeper();
public Builder setJob(final Job job) {
this.job = job;
return this;
}
public Builder setExistingContainerId(final String existingContainerId) {
this.existingContainerId = existingContainerId;
return this;
}
public Builder setRestartPolicy(final RestartPolicy restartPolicy) {
this.restartPolicy = restartPolicy;
return this;
}
public Builder setDockerClient(final DockerClient dockerClient) {
this.dockerClient = dockerClient;
return this;
}
public Builder setMetrics(SupervisorMetrics metrics) {
this.metrics = metrics;
return this;
}
public Builder setListener(final Listener listener) {
this.listener = listener;
return this;
}
public Builder setRunnerFactory(final TaskRunnerFactory runnerFactory) {
this.runnerFactory = runnerFactory;
return this;
}
public Builder setStatusUpdater(final StatusUpdater statusUpdater) {
this.statusUpdater = statusUpdater;
return this;
}
public Builder setMonitor(final TaskMonitor monitor) {
this.monitor = monitor;
return this;
}
public Builder setSleeper(final Sleeper sleeper) {
this.sleeper = sleeper;
return this;
}
public Supervisor build() {
return new Supervisor(this);
}
private class NopListener implements Listener {
@Override
public void stateChanged(final Supervisor supervisor) {
}
}
}
private interface Command {
/**
* Perform the command. Although this is declared to throw InterruptedException, this will only
* happen when the supervisor is being shut down. During normal operations, the operation will
* be allowed to run until it's done.
* @param done Flag indicating if operation is done.
* @throws InterruptedException If thread is interrupted.
*/
void perform(final boolean done) throws InterruptedException;
}
/**
* Starts a container and attempts to keep it up indefinitely, restarting it when it exits.
*/
private class Start implements Command {
@Override
public void perform(final boolean done) throws InterruptedException {
if (runner == null) {
// There's no active runner, start it to bring up the container.
startAfter(0);
return;
}
if (runner.isRunning()) {
// There's an active runner, brought up by this or another Start command previously.
return;
}
// Check if the runner exited normally or threw an exception
final Result<Integer> result = runner.result();
if (!result.isSuccess()) {
// Runner threw an exception, inspect it.
final Throwable t = result.getException();
if (t instanceof InterruptedException || t instanceof InterruptedIOException) {
// We're probably shutting down, remove the runner and bail.
log.debug("task runner interrupted");
runner = null;
reactor.signal();
return;
} else if (t instanceof DockerException) {
log.error("docker error", t);
} else {
log.error("task runner threw exception", t);
}
}
// Restart the task
startAfter(restartPolicy.delay(monitor.throttle()));
}
private void startAfter(final long delay) {
log.debug("starting job (delay={}): {}", delay, job);
runner = runnerFactory.create(delay, containerId, new TaskListener());
runner.startAsync();
runner.resultFuture().addListener(reactor.signalRunnable(), directExecutor());
}
}
/**
* Stops a container, making sure that the runner spawned by {@link Start} is stopped and the
* container is not running.
*/
private class Stop implements Command {
@Override
public void perform(final boolean done) throws InterruptedException {
if (done) {
return;
}
final Integer gracePeriod = job.getGracePeriod();
if (gracePeriod != null && gracePeriod > 0) {
log.info("Unregistering from service discovery for {} seconds before stopping",
gracePeriod);
statusUpdater.setState(STOPPING);
statusUpdater.update();
if (runner.unregister()) {
log.info("Unregistered. Now sleeping for {} seconds.", gracePeriod);
sleeper.sleep(TimeUnit.MILLISECONDS.convert(gracePeriod, TimeUnit.SECONDS));
}
}
log.info("stopping job: {}", job);
// Stop the runner
if (runner != null) {
runner.stop();
runner = null;
}
final RetryScheduler retryScheduler = BoundedRandomExponentialBackoff.newBuilder()
.setMinIntervalMillis(SECONDS.toMillis(1))
.setMaxIntervalMillis(SECONDS.toMillis(30))
.build().newScheduler();
// Kill the container after stopping the runner
while (!containerNotRunning()) {
killContainer();
Thread.sleep(retryScheduler.nextMillis());
}
statusUpdater.setState(STOPPED);
statusUpdater.setContainerError(containerError());
statusUpdater.update();
}
private void killContainer() throws InterruptedException {
if (containerId == null) {
return;
}
try {
docker.killContainer(containerId);
} catch (DockerException e) {
log.error("failed to kill container {}", containerId, e);
}
}
private boolean containerNotRunning()
throws InterruptedException {
if (containerId == null) {
return true;
}
final ContainerInfo containerInfo;
try {
containerInfo = docker.inspectContainer(containerId);
} catch (ContainerNotFoundException e) {
return true;
} catch (DockerException e) {
log.error("failed to query container {}", containerId, e);
return false;
}
return !containerInfo.state().running();
}
private String containerError() throws InterruptedException {
if (containerId == null) {
return null;
}
final ContainerInfo containerInfo;
try {
containerInfo = docker.inspectContainer(containerId);
} catch (ContainerNotFoundException e) {
return null;
} catch (DockerException e) {
log.error("failed to query container {}", containerId, e);
return null;
}
return containerInfo.state().error();
}
}
private static class Nop implements Command {
@Override
public void perform(final boolean done) {
}
}
@Override
public String toString() {
return "Supervisor{" +
"job=" + job +
", currentCommand=" + currentCommand +
", performedCommand=" + performedCommand +
'}';
}
private class TaskListener extends TaskRunner.NopListener {
private MetricsContext pullContext;
@Override
public void failed(final Throwable t, final String containerError) {
metrics.containersThrewException();
}
@Override
public void pulling() {
pullContext = metrics.containerPull();
}
@Override
public void pullFailed() {
if (pullContext != null) {
pullContext.failure();
}
}
@Override
public void pulled() {
if (pullContext != null) {
pullContext.success();
}
}
@Override
public void created(final String createdContainerId) {
containerId = createdContainerId;
}
}
}
|
gtonic/helios
|
helios-services/src/main/java/com/spotify/helios/agent/Supervisor.java
|
Java
|
apache-2.0
| 14,062 |
package de.saxsys.mvvmfx.examples.contacts.model;
public class Subdivision {
private final String name;
private final String abbr;
private final Country country;
public Subdivision(String name, String abbr, Country country) {
this.name = name;
this.abbr = abbr;
this.country = country;
}
public String getName() {
return name;
}
public String getAbbr() {
return abbr;
}
public Country getCountry() {
return country;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Subdivision that = (Subdivision) o;
if (!abbr.equals(that.abbr)) {
return false;
}
if (!country.equals(that.country)) {
return false;
}
if (!name.equals(that.name)) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + abbr.hashCode();
result = 31 * result + country.hashCode();
return result;
}
}
|
sialcasa/mvvmFX
|
examples/contacts-example/src/main/java/de/saxsys/mvvmfx/examples/contacts/model/Subdivision.java
|
Java
|
apache-2.0
| 1,010 |
package fr.jmini.asciidoctorj.testcases;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.asciidoctor.AttributesBuilder;
import org.asciidoctor.OptionsBuilder;
import org.asciidoctor.ast.Block;
import org.asciidoctor.ast.Document;
import org.asciidoctor.ast.Title;
public class ShowTitleTrueTestCase implements AdocTestCase {
public static final String ASCIIDOC = "" +
"= My page\n" +
"\n" +
"Some text\n" +
"";
@Override
public String getAdocInput() {
return ASCIIDOC;
}
@Override
public Map<String, Object> getInputOptions() {
AttributesBuilder attributesBuilder = AttributesBuilder.attributes()
.showTitle(true);
return OptionsBuilder.options()
.attributes(attributesBuilder)
.asMap();
}
// tag::expected-html[]
public static final String EXPECTED_HTML = "" +
"<h1>My page</h1>\n" +
"<div class=\"paragraph\">\n" +
"<p>Some text</p>\n" +
"</div>";
// end::expected-html[]
@Override
public String getHtmlOutput() {
return EXPECTED_HTML;
}
@Override
// tag::assert-code[]
public void checkAst(Document astDocument) {
Document document1 = astDocument;
assertThat(document1.getId()).isNull();
assertThat(document1.getNodeName()).isEqualTo("document");
assertThat(document1.getParent()).isNull();
assertThat(document1.getContext()).isEqualTo("document");
assertThat(document1.getDocument()).isSameAs(document1);
assertThat(document1.isInline()).isFalse();
assertThat(document1.isBlock()).isTrue();
assertThat(document1.getAttributes()).containsEntry("doctitle", "My page")
.containsEntry("doctype", "article")
.containsEntry("example-caption", "Example")
.containsEntry("figure-caption", "Figure")
.containsEntry("filetype", "html")
.containsEntry("notitle", "")
.containsEntry("prewrap", "")
.containsEntry("showtitle", true)
.containsEntry("table-caption", "Table");
assertThat(document1.getRoles()).isNullOrEmpty();
assertThat(document1.isReftext()).isFalse();
assertThat(document1.getReftext()).isNull();
assertThat(document1.getCaption()).isNull();
assertThat(document1.getTitle()).isNull();
assertThat(document1.getStyle()).isNull();
assertThat(document1.getLevel()).isEqualTo(0);
assertThat(document1.getContentModel()).isEqualTo("compound");
assertThat(document1.getSourceLocation()).isNull();
assertThat(document1.getSubstitutions()).isNullOrEmpty();
assertThat(document1.getBlocks()).hasSize(1);
Block block1 = (Block) document1.getBlocks()
.get(0);
assertThat(block1.getId()).isNull();
assertThat(block1.getNodeName()).isEqualTo("paragraph");
assertThat(block1.getParent()).isSameAs(document1);
assertThat(block1.getContext()).isEqualTo("paragraph");
assertThat(block1.getDocument()).isSameAs(document1);
assertThat(block1.isInline()).isFalse();
assertThat(block1.isBlock()).isTrue();
assertThat(block1.getAttributes()).isNullOrEmpty();
assertThat(block1.getRoles()).isNullOrEmpty();
assertThat(block1.isReftext()).isFalse();
assertThat(block1.getReftext()).isNull();
assertThat(block1.getCaption()).isNull();
assertThat(block1.getTitle()).isNull();
assertThat(block1.getStyle()).isNull();
assertThat(block1.getLevel()).isEqualTo(0);
assertThat(block1.getContentModel()).isEqualTo("simple");
assertThat(block1.getSourceLocation()).isNull();
assertThat(block1.getSubstitutions()).containsExactly("specialcharacters", "quotes", "attributes", "replacements", "macros", "post_replacements");
assertThat(block1.getBlocks()).isNullOrEmpty();
assertThat(block1.getLines()).containsExactly("Some text");
assertThat(block1.getSource()).isEqualTo("Some text");
Title title1 = document1.getStructuredDoctitle();
assertThat(title1.getMain()).isEqualTo("My page");
assertThat(title1.getSubtitle()).isNull();
assertThat(title1.getCombined()).isEqualTo("My page");
assertThat(title1.isSanitized()).isFalse();
assertThat(document1.getDoctitle()).isEqualTo("My page");
assertThat(document1.getOptions()).containsEntry("header_footer", false);
}
// end::assert-code[]
@Override
// tag::mock-code[]
public Document createMock() {
Document mockDocument1 = mock(Document.class);
when(mockDocument1.getId()).thenReturn(null);
when(mockDocument1.getNodeName()).thenReturn("document");
when(mockDocument1.getParent()).thenReturn(null);
when(mockDocument1.getContext()).thenReturn("document");
when(mockDocument1.getDocument()).thenReturn(mockDocument1);
when(mockDocument1.isInline()).thenReturn(false);
when(mockDocument1.isBlock()).thenReturn(true);
Map<String, Object> map1 = new HashMap<>();
map1.put("doctitle", "My page");
map1.put("doctype", "article");
map1.put("example-caption", "Example");
map1.put("figure-caption", "Figure");
map1.put("filetype", "html");
map1.put("notitle", "");
map1.put("prewrap", "");
map1.put("showtitle", true);
map1.put("table-caption", "Table");
when(mockDocument1.getAttributes()).thenReturn(map1);
when(mockDocument1.getRoles()).thenReturn(Collections.emptyList());
when(mockDocument1.isReftext()).thenReturn(false);
when(mockDocument1.getReftext()).thenReturn(null);
when(mockDocument1.getCaption()).thenReturn(null);
when(mockDocument1.getTitle()).thenReturn(null);
when(mockDocument1.getStyle()).thenReturn(null);
when(mockDocument1.getLevel()).thenReturn(0);
when(mockDocument1.getContentModel()).thenReturn("compound");
when(mockDocument1.getSourceLocation()).thenReturn(null);
when(mockDocument1.getSubstitutions()).thenReturn(Collections.emptyList());
Block mockBlock1 = mock(Block.class);
when(mockBlock1.getId()).thenReturn(null);
when(mockBlock1.getNodeName()).thenReturn("paragraph");
when(mockBlock1.getParent()).thenReturn(mockDocument1);
when(mockBlock1.getContext()).thenReturn("paragraph");
when(mockBlock1.getDocument()).thenReturn(mockDocument1);
when(mockBlock1.isInline()).thenReturn(false);
when(mockBlock1.isBlock()).thenReturn(true);
when(mockBlock1.getAttributes()).thenReturn(Collections.emptyMap());
when(mockBlock1.getRoles()).thenReturn(Collections.emptyList());
when(mockBlock1.isReftext()).thenReturn(false);
when(mockBlock1.getReftext()).thenReturn(null);
when(mockBlock1.getCaption()).thenReturn(null);
when(mockBlock1.getTitle()).thenReturn(null);
when(mockBlock1.getStyle()).thenReturn(null);
when(mockBlock1.getLevel()).thenReturn(0);
when(mockBlock1.getContentModel()).thenReturn("simple");
when(mockBlock1.getSourceLocation()).thenReturn(null);
when(mockBlock1.getSubstitutions()).thenReturn(Arrays.asList("specialcharacters", "quotes", "attributes", "replacements", "macros", "post_replacements"));
when(mockBlock1.getBlocks()).thenReturn(Collections.emptyList());
when(mockBlock1.getLines()).thenReturn(Collections.singletonList("Some text"));
when(mockBlock1.getSource()).thenReturn("Some text");
when(mockDocument1.getBlocks()).thenReturn(Collections.singletonList(mockBlock1));
Title mockTitle1 = mock(Title.class);
when(mockTitle1.getMain()).thenReturn("My page");
when(mockTitle1.getSubtitle()).thenReturn(null);
when(mockTitle1.getCombined()).thenReturn("My page");
when(mockTitle1.isSanitized()).thenReturn(false);
when(mockDocument1.getStructuredDoctitle()).thenReturn(mockTitle1);
when(mockDocument1.getDoctitle()).thenReturn("My page");
Map<Object, Object> map2 = new HashMap<>();
map2.put("attributes", "{\"showtitle\"=>true}");
map2.put("header_footer", false);
when(mockDocument1.getOptions()).thenReturn(map2);
return mockDocument1;
}
// end::mock-code[]
}
|
jmini/asciidoctorj-experiments
|
test-cases/adoc-test-cases/src/main/java/fr/jmini/asciidoctorj/testcases/ShowTitleTrueTestCase.java
|
Java
|
apache-2.0
| 8,764 |
package fr.sii.ogham.sms.message;
import fr.sii.ogham.core.util.EqualsBuilder;
import fr.sii.ogham.core.util.HashCodeBuilder;
/**
* Represents a phone number. It wraps a simple string. The aim is to abstracts
* the concept and to be able to provide other fields latter if needed.
*
* @author Aurélien Baudet
*
*/
public class PhoneNumber {
/**
* The phone number as string
*/
private String number;
/**
* Initialize the phone number with the provided number.
*
* @param number
* the phone number
*/
public PhoneNumber(String number) {
super();
this.number = number;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
@Override
public String toString() {
return number;
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(number).hashCode();
}
@Override
public boolean equals(Object obj) {
return new EqualsBuilder(this, obj).appendFields("number").isEqual();
}
}
|
groupe-sii/ogham
|
ogham-core/src/main/java/fr/sii/ogham/sms/message/PhoneNumber.java
|
Java
|
apache-2.0
| 1,017 |
package org.fastnate.generator.converter;
import java.time.Duration;
import org.fastnate.generator.context.GeneratorContext;
import org.fastnate.generator.statements.ColumnExpression;
import org.fastnate.generator.statements.PrimitiveColumnExpression;
/**
* Converts a {@link Duration} to an SQL expression.
*
* @author Tobias Liefke
*/
public class DurationConverter implements ValueConverter<Duration> {
@Override
public ColumnExpression getExpression(final Duration value, final GeneratorContext context) {
return PrimitiveColumnExpression.create(value.toNanos(), context.getDialect());
}
@Override
public ColumnExpression getExpression(final String defaultValue, final GeneratorContext context) {
return getExpression(Duration.parse(defaultValue), context);
}
}
|
liefke/org.fastnate
|
fastnate-generator/src/main/java/org/fastnate/generator/converter/DurationConverter.java
|
Java
|
apache-2.0
| 786 |
//
// Questo file è stato generato dall'architettura JavaTM per XML Binding (JAXB) Reference Implementation, v2.2.8-b130911.1802
// Vedere <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Qualsiasi modifica a questo file andrà persa durante la ricompilazione dello schema di origine.
// Generato il: 2014.10.23 alle 11:27:04 AM CEST
//
package org.cumulus.certificate.model;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Classe Java per HistoryStateType complex type.
*
* <p>Il seguente frammento di schema specifica il contenuto previsto contenuto in questa classe.
*
* <pre>
* <complexType name="HistoryStateType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="stateId" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="refersToStateId" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "HistoryStateType")
public class HistoryStateType {
@XmlAttribute(name = "stateId", required = true)
protected String stateId;
@XmlAttribute(name = "refersToStateId", required = true)
protected String refersToStateId;
/**
* Recupera il valore della proprietà stateId.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStateId() {
return stateId;
}
/**
* Imposta il valore della proprietà stateId.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStateId(String value) {
this.stateId = value;
}
/**
* Recupera il valore della proprietà refersToStateId.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRefersToStateId() {
return refersToStateId;
}
/**
* Imposta il valore della proprietà refersToStateId.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRefersToStateId(String value) {
this.refersToStateId = value;
}
}
|
fgaudenzi/testManager
|
testManager/XMLRepository/CertificationModel/org/cumulus/certificate/model/HistoryStateType.java
|
Java
|
apache-2.0
| 2,497 |
/*
* Copyright 2021 ThoughtWorks, 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.thoughtworks.go.serverhealth;
import com.thoughtworks.go.config.CruiseConfig;
import com.thoughtworks.go.config.CruiseConfigProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@Service
public class ServerHealthService implements ApplicationContextAware {
private static final Logger LOG = LoggerFactory.getLogger(ServerHealthService.class);
private HashMap<ServerHealthState, Set<String>> pipelinesWithErrors;
private Map<HealthStateType, ServerHealthState> serverHealth;
private ApplicationContext applicationContext;
public ServerHealthService() {
this.serverHealth = new ConcurrentHashMap<>();
this.pipelinesWithErrors = new HashMap<>();
}
public void removeByScope(HealthStateScope scope) {
for (HealthStateType healthStateType : entryKeys()) {
if (healthStateType.isSameScope(scope)) {
serverHealth.remove(healthStateType);
}
}
}
private Set<HealthStateType> entryKeys() {
return new HashSet<>(serverHealth.keySet());
}
public List<ServerHealthState> filterByScope(HealthStateScope scope) {
List<ServerHealthState> filtered = new ArrayList<>();
for (Map.Entry<HealthStateType, ServerHealthState> entry : sortedEntries()) {
HealthStateType type = entry.getKey();
if (type.isSameScope(scope)) {
filtered.add(entry.getValue());
}
}
return filtered;
}
public HealthStateType update(ServerHealthState serverHealthState) {
HealthStateType type = serverHealthState.getType();
if (serverHealthState.getLogLevel() == HealthStateLevel.OK) {
if (serverHealth.containsKey(type)) {
serverHealth.remove(type);
}
return null;
} else {
serverHealth.put(type, serverHealthState);
return type;
}
}
// called from spring timer
public synchronized void onTimer() {
CruiseConfig currentConfig = applicationContext.getBean(CruiseConfigProvider.class).getCurrentConfig();
purgeStaleHealthMessages(currentConfig);
LOG.debug("Recomputing material to pipeline mappings.");
HashMap<ServerHealthState, Set<String>> erroredPipelines = new HashMap<>();
for (Map.Entry<HealthStateType, ServerHealthState> entry : serverHealth.entrySet()) {
erroredPipelines.put(entry.getValue(), entry.getValue().getPipelineNames(currentConfig));
}
pipelinesWithErrors = erroredPipelines;
LOG.debug("Done recomputing material to pipeline mappings.");
}
public Set<String> getPipelinesWithErrors(ServerHealthState serverHealthState) {
return pipelinesWithErrors.get(serverHealthState);
}
void purgeStaleHealthMessages(CruiseConfig cruiseConfig) {
removeMessagesForElementsNoLongerInConfig(cruiseConfig);
removeExpiredMessages();
}
@Deprecated(forRemoval = true) // Remove once we get rid of SpringJUnitTestRunner
public void removeAllLogs() {
serverHealth.clear();
}
private void removeMessagesForElementsNoLongerInConfig(CruiseConfig cruiseConfig) {
for (HealthStateType type : entryKeys()) {
if (type.isRemovedFromConfig(cruiseConfig)) {
this.removeByScope(type);
}
}
}
private void removeExpiredMessages() {
for (Map.Entry<HealthStateType, ServerHealthState> entry : new HashSet<>(serverHealth.entrySet())) {
ServerHealthState value = entry.getValue();
if (value.hasExpired()) {
serverHealth.remove(entry.getKey());
}
}
}
private void removeByScope(HealthStateType type) {
removeByScope(type.getScope());
}
public ServerHealthStates logs() {
ArrayList<ServerHealthState> logs = new ArrayList<>();
for (Map.Entry<HealthStateType, ServerHealthState> entry : sortedEntries()) {
logs.add(entry.getValue());
}
return new ServerHealthStates(logs);
}
private List<Map.Entry<HealthStateType, ServerHealthState>> sortedEntries() {
List<Map.Entry<HealthStateType, ServerHealthState>> entries = new ArrayList<>(serverHealth.entrySet());
entries.sort(Comparator.comparing(Map.Entry::getKey));
return entries;
}
public String getLogsAsText() {
StringBuilder text = new StringBuilder();
for (ServerHealthState state : logs()) {
text.append(state.getDescription());
text.append("\n\t");
text.append(state.getMessage());
text.append("\n");
}
return text.toString();
}
public boolean containsError(HealthStateType type, HealthStateLevel level) {
ServerHealthStates allLogs = logs();
for (ServerHealthState log : allLogs) {
if (log.getType().equals(type) && log.getLogLevel() == level) {
return true;
}
}
return false;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
|
GaneshSPatil/gocd
|
common/src/main/java/com/thoughtworks/go/serverhealth/ServerHealthService.java
|
Java
|
apache-2.0
| 6,153 |
package gov.ic.geoint.spreadsheet;
/**
*
*/
public interface ICell extends Hashable {
/**
*
* @return
*/
public int getColumnNum();
/**
*
* @return
*/
public int getRowNum();
/**
*
* @return
*/
public String getValue();
}
|
GEOINT/spreadsheetDiff
|
src/main/java/gov/ic/geoint/spreadsheet/ICell.java
|
Java
|
apache-2.0
| 298 |
package sdk.chat.demo.examples.api;
import io.reactivex.functions.Consumer;
import sdk.guru.common.DisposableMap;
public class BaseExample implements Consumer<Throwable> {
// Add the disposables to a map so you can dispose of them all at one time
protected DisposableMap dm = new DisposableMap();
@Override
public void accept(Throwable throwable) throws Exception {
// Handle exception
}
}
|
chat-sdk/chat-sdk-android
|
chat-sdk-demo/src/main/java/sdk/chat/demo/examples/api/BaseExample.java
|
Java
|
apache-2.0
| 423 |
//Copyright (c) 2014 by Disy Informationssysteme GmbH
package net.disy.eenvplus.tfes.core.api.query;
// NOT_PUBLISHED
public interface ISuggestionQuery extends ISourceQuery {
String getKeyword();
}
|
eENVplus/tf-exploitation-server
|
TF_Exploitation_Server_core/src/main/java/net/disy/eenvplus/tfes/core/api/query/ISuggestionQuery.java
|
Java
|
apache-2.0
| 201 |
package com.jwetherell.algorithms.data_structures.interfaces;
/**
* A tree can be defined recursively (locally) as a collection of nodes (starting at a root node),
* where each node is a data structure consisting of a value, together with a list of nodes (the "children"),
* with the constraints that no node is duplicated. A tree can be defined abstractly as a whole (globally)
* as an ordered tree, with a value assigned to each node.
* <p>
* @see <a href="https://en.wikipedia.org/wiki/Tree_(data_structure)">Tree (Wikipedia)</a>
* <br>
* @author Justin Wetherell <phishman3579@gmail.com>
*/
public interface ITree<T> {
/**
* Add value to the tree. Tree can contain multiple equal values.
*
* @param value to add to the tree.
* @return True if successfully added to tree.
*/
public boolean add(T value);
/**
* Remove first occurrence of value in the tree.
*
* @param value to remove from the tree.
* @return T value removed from tree.
*/
public T remove(T value);
/**
* Clear the entire stack.
*/
public void clear();
/**
* Does the tree contain the value.
*
* @param value to locate in the tree.
* @return True if tree contains value.
*/
public boolean contains(T value);
/**
* Get number of nodes in the tree.
*
* @return Number of nodes in the tree.
*/
public int size();
/**
* Validate the tree according to the invariants.
*
* @return True if the tree is valid.
*/
public boolean validate();
/**
* Get Tree as a Java compatible Collection
*
* @return Java compatible Collection
*/
public java.util.Collection<T> toCollection();
}
|
phishman3579/java-algorithms-implementation
|
src/com/jwetherell/algorithms/data_structures/interfaces/ITree.java
|
Java
|
apache-2.0
| 1,766 |
/*
* Copyright 2014, The Sporting Exchange Limited
* Copyright 2014, Simon Matić Langford
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.exemel.disco.transport.jetty;
import uk.co.exemel.disco.DiscoVersion;
import org.eclipse.jetty.servlets.CrossOriginFilter;
import org.junit.Test;
import java.util.Collections;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;
/**
* Unit tests for {@link uk.co.exemel.disco.transport.jetty.CrossOriginHandler}
*/
public class CrossOriginHandlerTest {
@Test
public void testHandlerSetsServerHeaderInTheResponse() throws Exception {
final CrossOriginHandler victim = new CrossOriginHandler("betfair.com", "GET,POST,HEAD", "X-Requested-With,Content-Type,Accept,Origin", "1800", "true", "");
final MockJettyRequest req = mock(MockJettyRequest.class);
final MockJettyResponse res = mock(MockJettyResponse.class);
victim.handle("/", req, req, res);
verify(res, times(1)).setHeader(eq("Server"), eq("Disco 2 - " + DiscoVersion.getVersion()));
}
@Test
public void testHandlerMarksRequestAsHandledByDefault() throws Exception {
final CrossOriginHandler victim = new CrossOriginHandler("betfair.com", "GET,POST,HEAD", "X-Requested-With,Content-Type,Accept,Origin", "1800", "true", "");
final MockJettyRequest req = mock(MockJettyRequest.class);
final MockJettyResponse res = mock(MockJettyResponse.class);
victim.handle("/", req, req, res);
verify(req, times(1)).setHandled(eq(true));
verify(req, times(1)).setHandled(eq(false));
}
@Test
public void testHandlerUnmarksRequestAsHandledIfFilterContinuesTheChainExplicitDomain() throws Exception {
testHandlesCrossOriginRequest("betfair.com", true);
}
@Test
public void testHandlerUnmarksRequestAsHandledIfFilterContinuesTheChainAllDomains() throws Exception {
testHandlesCrossOriginRequest("*", true);
}
@Test
public void testHandlerUnmarksRequestAsHandledIfFilterContinuesTheChainNoDomains() throws Exception {
testHandlesCrossOriginRequest("", false);
}
private void testHandlesCrossOriginRequest(String domains, boolean wantHandled) throws Exception {
final CrossOriginHandler victim = new CrossOriginHandler(domains, "GET,POST,HEAD", "X-Requested-With,Content-Type,Accept,Origin", "1800", "true", "");
final MockJettyRequest req = mock(MockJettyRequest.class);
final MockJettyResponse res = mock(MockJettyResponse.class);
when(req.getMethod()).thenReturn("OPTIONS");
when(req.getHeader("Origin")).thenReturn("betfair.com");
when(req.getHeader(CrossOriginFilter.ACCESS_CONTROL_REQUEST_METHOD_HEADER)).thenReturn("PUT");
when(req.getHeaders("Connection")).thenReturn(Collections.<String>emptyEnumeration());
victim.handle("/", req, req, res);
// this is always called
verify(req, times(1)).setHandled(eq(true));
if (wantHandled) {
verify(req, never()).setHandled(eq(false));
}
else {
verify(req, times(1)).setHandled(eq(false));
}
}
}
|
eswdd/disco
|
disco-framework/jetty-transport/src/test/java/uk/co/exemel/disco/transport/jetty/CrossOriginHandlerTest.java
|
Java
|
apache-2.0
| 3,706 |
package org.nd4j.linalg.indexing;
import com.google.common.base.Function;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.nd4j.linalg.BaseNd4jTest;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.impl.accum.MatchCondition;
import org.nd4j.linalg.api.ops.impl.transforms.comparison.CompareAndReplace;
import org.nd4j.linalg.api.ops.impl.transforms.comparison.CompareAndSet;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.factory.Nd4jBackend;
import org.nd4j.linalg.indexing.conditions.AbsValueGreaterThan;
import org.nd4j.linalg.indexing.conditions.Condition;
import org.nd4j.linalg.indexing.conditions.Conditions;
import org.nd4j.linalg.indexing.functions.Value;
import java.util.Arrays;
import static org.junit.Assert.*;
/**
* @author raver119@gmail.com
*/
@RunWith(Parameterized.class)
public class BooleanIndexingTest extends BaseNd4jTest {
public BooleanIndexingTest(Nd4jBackend backend) {
super(backend);
}
/*
1D array checks
*/
@Test
public void testAnd1() throws Exception {
INDArray array = Nd4j.create(new float[] {1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
assertTrue(BooleanIndexing.and(array, Conditions.greaterThan(0.5f)));
}
@Test
public void testAnd2() throws Exception {
INDArray array = Nd4j.create(new float[] {1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
assertTrue(BooleanIndexing.and(array, Conditions.lessThan(6.0f)));
}
@Test
public void testAnd3() throws Exception {
INDArray array = Nd4j.create(new float[] {1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
assertFalse(BooleanIndexing.and(array, Conditions.lessThan(5.0f)));
}
@Test
public void testAnd4() throws Exception {
INDArray array = Nd4j.create(new float[] {1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
assertFalse(BooleanIndexing.and(array, Conditions.greaterThan(4.0f)));
}
@Test
public void testAnd5() throws Exception {
INDArray array = Nd4j.create(new float[] {1e-5f, 1e-5f, 1e-5f, 1e-5f, 1e-5f});
assertTrue(BooleanIndexing.and(array, Conditions.greaterThanOrEqual(1e-5f)));
}
@Test
public void testAnd6() throws Exception {
INDArray array = Nd4j.create(new float[] {1e-5f, 1e-5f, 1e-5f, 1e-5f, 1e-5f});
assertFalse(BooleanIndexing.and(array, Conditions.lessThan(1e-5f)));
}
@Test
public void testAnd7() throws Exception {
INDArray array = Nd4j.create(new float[] {1e-5f, 1e-5f, 1e-5f, 1e-5f, 1e-5f});
assertTrue(BooleanIndexing.and(array, Conditions.equals(1e-5f)));
}
@Test
public void testOr1() throws Exception {
INDArray array = Nd4j.create(new float[] {1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
assertTrue(BooleanIndexing.or(array, Conditions.greaterThan(3.0f)));
}
@Test
public void testOr2() throws Exception {
INDArray array = Nd4j.create(new float[] {1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
assertTrue(BooleanIndexing.or(array, Conditions.lessThan(3.0f)));
}
@Test
public void testOr3() throws Exception {
INDArray array = Nd4j.create(new float[] {1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
assertFalse(BooleanIndexing.or(array, Conditions.greaterThan(6.0f)));
}
@Test
public void testApplyWhere1() throws Exception {
INDArray array = Nd4j.create(new float[] {-1f, -1f, -1f, -1f, -1f});
BooleanIndexing.applyWhere(array, Conditions.lessThan(Nd4j.EPS_THRESHOLD), new Value(Nd4j.EPS_THRESHOLD));
//System.out.println("Array contains: " + Arrays.toString(array.data().asFloat()));
assertTrue(BooleanIndexing.and(array, Conditions.equals(Nd4j.EPS_THRESHOLD)));
}
@Test
public void testApplyWhere2() throws Exception {
INDArray array = Nd4j.create(new float[] {0f, 0f, 0f, 0f, 0f});
BooleanIndexing.applyWhere(array, Conditions.lessThan(1.0f), new Value(1.0f));
assertTrue(BooleanIndexing.and(array, Conditions.equals(1.0f)));
}
@Test
public void testApplyWhere3() throws Exception {
INDArray array = Nd4j.create(new float[] {1e-18f, 1e-18f, 1e-18f, 1e-18f, 1e-18f});
BooleanIndexing.applyWhere(array, Conditions.lessThan(1e-12f), new Value(1e-12f));
//System.out.println("Array contains: " + Arrays.toString(array.data().asFloat()));
assertTrue(BooleanIndexing.and(array, Conditions.equals(1e-12f)));
}
@Test
public void testApplyWhere4() throws Exception {
INDArray array = Nd4j.create(new float[] {1e-18f, Float.NaN, 1e-18f, 1e-18f, 1e-18f});
BooleanIndexing.applyWhere(array, Conditions.lessThan(1e-12f), new Value(1e-12f));
//System.out.println("Array contains: " + Arrays.toString(array.data().asFloat()));
BooleanIndexing.applyWhere(array, Conditions.isNan(), new Value(1e-16f));
System.out.println("Array contains: " + Arrays.toString(array.data().asFloat()));
assertFalse(BooleanIndexing.or(array, Conditions.isNan()));
assertTrue(BooleanIndexing.or(array, Conditions.equals(1e-12f)));
assertTrue(BooleanIndexing.or(array, Conditions.equals(1e-16f)));
}
/*
2D array checks
*/
@Test
public void test2dAnd1() throws Exception {
INDArray array = Nd4j.zeros(10, 10);
assertTrue(BooleanIndexing.and(array, Conditions.equals(0f)));
}
@Test
public void test2dAnd2() throws Exception {
INDArray array = Nd4j.zeros(10, 10);
array.slice(4).putScalar(2, 1e-5f);
System.out.println(array);
assertFalse(BooleanIndexing.and(array, Conditions.equals(0f)));
}
@Test
public void test2dAnd3() throws Exception {
INDArray array = Nd4j.zeros(10, 10);
array.slice(4).putScalar(2, 1e-5f);
assertFalse(BooleanIndexing.and(array, Conditions.greaterThan(0f)));
}
@Test
public void test2dAnd4() throws Exception {
INDArray array = Nd4j.zeros(10, 10);
array.slice(4).putScalar(2, 1e-5f);
assertTrue(BooleanIndexing.or(array, Conditions.greaterThan(1e-6f)));
}
@Test
public void test2dApplyWhere1() throws Exception {
INDArray array = Nd4j.ones(4, 4);
array.slice(3).putScalar(2, 1e-5f);
//System.out.println("Array before: " + Arrays.toString(array.data().asFloat()));
BooleanIndexing.applyWhere(array, Conditions.lessThan(1e-4f), new Value(1e-12f));
//System.out.println("Array after 1: " + Arrays.toString(array.data().asFloat()));
assertTrue(BooleanIndexing.or(array, Conditions.equals(1e-12f)));
assertTrue(BooleanIndexing.or(array, Conditions.equals(1.0f)));
assertFalse(BooleanIndexing.and(array, Conditions.equals(1e-12f)));
}
/**
* This test fails, because it highlights current mechanics on SpecifiedIndex stuff.
* Internally there's
*
* @throws Exception
*/
@Test
public void testSliceAssign1() throws Exception {
INDArray array = Nd4j.zeros(4, 4);
INDArray patch = Nd4j.create(new float[] {1e-5f, 1e-5f, 1e-5f});
INDArray slice = array.slice(1);
int[] idx = new int[] {0, 1, 3};
INDArrayIndex[] range = new INDArrayIndex[] {new SpecifiedIndex(idx)};
INDArray subarray = slice.get(range);
System.out.println("Subarray: " + Arrays.toString(subarray.data().asFloat()) + " isView: " + subarray.isView());
slice.put(range, patch);
System.out.println("Array after being patched: " + Arrays.toString(array.data().asFloat()));
assertFalse(BooleanIndexing.and(array, Conditions.equals(0f)));
}
@Test
public void testConditionalAssign1() throws Exception {
INDArray array1 = Nd4j.create(new double[] {1, 2, 3, 4, 5, 6, 7});
INDArray array2 = Nd4j.create(new double[] {7, 6, 5, 4, 3, 2, 1});
INDArray comp = Nd4j.create(new double[] {1, 2, 3, 4, 3, 2, 1});
BooleanIndexing.replaceWhere(array1, array2, Conditions.greaterThan(4));
assertEquals(comp, array1);
}
@Test
public void testCaSTransform1() throws Exception {
INDArray array = Nd4j.create(new double[] {1, 2, 0, 4, 5});
INDArray comp = Nd4j.create(new double[] {1, 2, 3, 4, 5});
Nd4j.getExecutioner().exec(new CompareAndSet(array, 3, Conditions.equals(0)));
assertEquals(comp, array);
}
@Test
public void testCaSTransform2() throws Exception {
INDArray array = Nd4j.create(new double[] {1, 2, 0, 4, 5});
INDArray comp = Nd4j.create(new double[] {3, 2, 3, 4, 5});
Nd4j.getExecutioner().exec(new CompareAndSet(array, 3.0, Conditions.lessThan(2)));
assertEquals(comp, array);
}
@Test
public void testCaSPairwiseTransform1() throws Exception {
INDArray array = Nd4j.create(new double[] {1, 2, 0, 4, 5});
INDArray comp = Nd4j.create(new double[] {1, 2, 3, 4, 5});
Nd4j.getExecutioner().exec(new CompareAndSet(array, comp, Conditions.lessThan(5)));
assertEquals(comp, array);
}
@Test
public void testCaRPairwiseTransform1() throws Exception {
INDArray array = Nd4j.create(new double[] {1, 2, 0, 4, 5});
INDArray comp = Nd4j.create(new double[] {1, 2, 3, 4, 5});
Nd4j.getExecutioner().exec(new CompareAndReplace(array, comp, Conditions.lessThan(1)));
assertEquals(comp, array);
}
@Test
public void testCaSPairwiseTransform2() throws Exception {
INDArray x = Nd4j.create(new double[] {1, 2, 0, 4, 5});
INDArray y = Nd4j.create(new double[] {2, 4, 3, 0, 5});
INDArray comp = Nd4j.create(new double[] {2, 4, 3, 4, 5});
Nd4j.getExecutioner().exec(new CompareAndSet(x, y, Conditions.epsNotEquals(0.0)));
assertEquals(comp, x);
}
@Test
public void testCaRPairwiseTransform2() throws Exception {
INDArray x = Nd4j.create(new double[] {1, 2, 0, 4, 5});
INDArray y = Nd4j.create(new double[] {2, 4, 3, 4, 5});
INDArray comp = Nd4j.create(new double[] {2, 4, 0, 4, 5});
Nd4j.getExecutioner().exec(new CompareAndReplace(x, y, Conditions.epsNotEquals(0.0)));
assertEquals(comp, x);
}
@Test
public void testCaSPairwiseTransform3() throws Exception {
INDArray x = Nd4j.create(new double[] {1, 2, 0, 4, 5});
INDArray y = Nd4j.create(new double[] {2, 4, 3, 4, 5});
INDArray comp = Nd4j.create(new double[] {2, 4, 3, 4, 5});
Nd4j.getExecutioner().exec(new CompareAndReplace(x, y, Conditions.lessThan(4)));
assertEquals(comp, x);
}
@Test
public void testCaRPairwiseTransform3() throws Exception {
INDArray x = Nd4j.create(new double[] {1, 2, 0, 4, 5});
INDArray y = Nd4j.create(new double[] {2, 4, 3, 4, 5});
INDArray comp = Nd4j.create(new double[] {2, 2, 3, 4, 5});
Nd4j.getExecutioner().exec(new CompareAndReplace(x, y, Conditions.lessThan(2)));
assertEquals(comp, x);
}
@Test
public void testMatchConditionAllDimensions1() throws Exception {
INDArray array = Nd4j.create(new double[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
int val = (int) Nd4j.getExecutioner().exec(new MatchCondition(array, Conditions.lessThan(5)), Integer.MAX_VALUE)
.getDouble(0);
assertEquals(5, val);
}
@Test
public void testMatchConditionAllDimensions2() throws Exception {
INDArray array = Nd4j.create(new double[] {0, 1, 2, 3, Double.NaN, 5, 6, 7, 8, 9});
int val = (int) Nd4j.getExecutioner().exec(new MatchCondition(array, Conditions.isNan()), Integer.MAX_VALUE)
.getDouble(0);
assertEquals(1, val);
}
@Test
public void testMatchConditionAllDimensions3() throws Exception {
INDArray array = Nd4j.create(new double[] {0, 1, 2, 3, Double.NEGATIVE_INFINITY, 5, 6, 7, 8, 9});
int val = (int) Nd4j.getExecutioner()
.exec(new MatchCondition(array, Conditions.isInfinite()), Integer.MAX_VALUE).getDouble(0);
assertEquals(1, val);
}
@Test
public void testAbsValueGreaterThan() {
final double threshold = 2;
Condition absValueCondition = new AbsValueGreaterThan(threshold);
Function<Number, Number> clipFn = new Function<Number, Number>() {
@Override
public Number apply(Number number) {
System.out.println("Number: " + number.doubleValue());
return (number.doubleValue() > threshold ? threshold : -threshold);
}
};
Nd4j.getRandom().setSeed(12345);
INDArray orig = Nd4j.rand(1, 20).muli(6).subi(3); //Random numbers: -3 to 3
INDArray exp = orig.dup();
INDArray after = orig.dup();
for (int i = 0; i < exp.length(); i++) {
double d = exp.getDouble(i);
if (d > threshold) {
exp.putScalar(i, threshold);
} else if (d < -threshold) {
exp.putScalar(i, -threshold);
}
}
BooleanIndexing.applyWhere(after, absValueCondition, clipFn);
System.out.println(orig);
System.out.println(exp);
System.out.println(after);
assertEquals(exp, after);
}
@Test
public void testMatchConditionAlongDimension1() throws Exception {
INDArray array = Nd4j.ones(3, 10);
array.getRow(2).assign(0.0);
boolean result[] = BooleanIndexing.and(array, Conditions.equals(0.0), 1);
boolean comp[] = new boolean[] {false, false, true};
System.out.println("Result: " + Arrays.toString(result));
assertArrayEquals(comp, result);
}
@Test
public void testMatchConditionAlongDimension2() throws Exception {
INDArray array = Nd4j.ones(3, 10);
array.getRow(2).assign(0.0).putScalar(0, 1.0);
System.out.println("Array: " + array);
boolean result[] = BooleanIndexing.or(array, Conditions.lessThan(0.9), 1);
boolean comp[] = new boolean[] {false, false, true};
System.out.println("Result: " + Arrays.toString(result));
assertArrayEquals(comp, result);
}
@Test
public void testMatchConditionAlongDimension3() throws Exception {
INDArray array = Nd4j.ones(3, 10);
array.getRow(2).assign(0.0).putScalar(0, 1.0);
boolean result[] = BooleanIndexing.and(array, Conditions.lessThan(0.0), 1);
boolean comp[] = new boolean[] {false, false, false};
System.out.println("Result: " + Arrays.toString(result));
assertArrayEquals(comp, result);
}
@Test
public void testConditionalUpdate() {
INDArray arr = Nd4j.linspace(-2, 2, 5);
INDArray ones = Nd4j.ones(5);
INDArray exp = Nd4j.create(new double[] {1, 1, 0, 1, 1});
Nd4j.getExecutioner().exec(new CompareAndSet(ones, arr, ones, Conditions.equals(0.0)));
assertEquals(exp, ones);
}
@Test
public void testFirstIndex1() {
INDArray arr = Nd4j.create(new double[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0});
INDArray result = BooleanIndexing.firstIndex(arr, Conditions.greaterThanOrEqual(3));
assertEquals(2, result.getDouble(0), 0.0);
}
@Test
public void testFirstIndex2() {
INDArray arr = Nd4j.create(new double[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0});
INDArray result = BooleanIndexing.firstIndex(arr, Conditions.lessThan(3));
assertEquals(0, result.getDouble(0), 0.0);
}
@Test
public void testLastIndex1() {
INDArray arr = Nd4j.create(new double[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0});
INDArray result = BooleanIndexing.lastIndex(arr, Conditions.greaterThanOrEqual(3));
assertEquals(8, result.getDouble(0), 0.0);
}
@Test
public void testFirstIndex2D() {
INDArray arr = Nd4j.create(new double[] {1, 2, 3, 0, 1, 3, 7, 8, 9}).reshape('c', 3, 3);
INDArray result = BooleanIndexing.firstIndex(arr, Conditions.greaterThanOrEqual(2), 1);
INDArray exp = Nd4j.create(new double[] {1, 2, 0});
assertEquals(exp, result);
}
@Test
public void testLastIndex2D() {
INDArray arr = Nd4j.create(new double[] {1, 2, 3, 0, 1, 3, 7, 8, 0}).reshape('c', 3, 3);
INDArray result = BooleanIndexing.lastIndex(arr, Conditions.greaterThanOrEqual(2), 1);
INDArray exp = Nd4j.create(new double[] {2, 2, 1});
assertEquals(exp, result);
}
@Test
public void testEpsEquals1() throws Exception {
INDArray array = Nd4j.create(new double[]{-1, -1, -1e-8, 1e-8, 1, 1});
MatchCondition condition = new MatchCondition(array, Conditions.epsEquals(0.0));
int numZeroes = Nd4j.getExecutioner().exec(condition, Integer.MAX_VALUE).getInt(0);
assertEquals(2, numZeroes);
}
@Override
public char ordering() {
return 'c';
}
}
|
huitseeker/nd4j
|
nd4j-backends/nd4j-tests/src/test/java/org/nd4j/linalg/indexing/BooleanIndexingTest.java
|
Java
|
apache-2.0
| 17,052 |
package com.xiaojinzi.component.error;
public class ServiceRepeatCreateException extends RuntimeException {
public ServiceRepeatCreateException() {
}
public ServiceRepeatCreateException(String message) {
super(message);
}
public ServiceRepeatCreateException(String message, Throwable cause) {
super(message, cause);
}
public ServiceRepeatCreateException(Throwable cause) {
super(cause);
}
}
|
xiaojinzi123/Component
|
ComponentImpl/src/main/java/com/xiaojinzi/component/error/ServiceRepeatCreateException.java
|
Java
|
apache-2.0
| 453 |
package de.uniulm.omi.cloudiator.sword.multicloud.service;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Inject;
import de.uniulm.omi.cloudiator.sword.domain.Cloud;
import de.uniulm.omi.cloudiator.sword.domain.Pricing;
import de.uniulm.omi.cloudiator.sword.multicloud.pricing.PricingSupplierFactory;
import de.uniulm.omi.cloudiator.sword.service.PricingService;
import java.util.*;
import static com.google.common.base.Preconditions.checkNotNull;
public class MultiCloudPricingService implements PricingService {
private final CloudRegistry cloudRegistry;
@Inject
private PricingSupplierFactory pricingSupplierFactory;
@Inject
public MultiCloudPricingService(CloudRegistry cloudRegistry) {
this.cloudRegistry = checkNotNull(cloudRegistry, "cloudRegistry is null");
}
@Override
public Iterable<Pricing> listPricing() {
/*final ImmutableSet.Builder<Pricing> builder = ImmutableSet.builder();
Optional<Cloud> awsCloud = cloudRegistry.list().stream().filter(cloud -> cloud.api().providerName().equals("aws-ec2")).findFirst();
if(awsCloud.isPresent()) {
Supplier<Set<Pricing>> awsPricingSupplier = pricingSupplierFactory.createAWSPricingSupplier(awsCloud.get().credential());
builder.addAll(awsPricingSupplier.get());
}
return builder.build();*/
final ImmutableSet.Builder<Pricing> builder = ImmutableSet.builder();
cloudRegistry
.list()
.stream()
.filter(cloud -> cloud.api().providerName().equals("aws-ec2"))
.findFirst()
.ifPresent(cloud -> builder.addAll(pricingSupplierFactory.createAWSPricingSupplier(cloud.credential()).get()));
return builder.build();
}
}
|
cloudiator/sword
|
multicloud/src/main/java/de/uniulm/omi/cloudiator/sword/multicloud/service/MultiCloudPricingService.java
|
Java
|
apache-2.0
| 1,844 |
/*
* Copyright 2011-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.transform;
import java.lang.reflect.Constructor;
import com.amazonaws.AmazonServiceException;
public abstract class AbstractErrorUnmarshaller<T> implements Unmarshaller<AmazonServiceException, T> {
/**
* The type of AmazonServiceException that will be instantiated. Subclasses
* specialized for a specific type of exception can control this through the
* protected constructor.
*/
protected final Class<? extends AmazonServiceException> exceptionClass;
/**
* Constructs a new error unmarshaller that will unmarshall error responses
* into AmazonServiceException objects.
*/
public AbstractErrorUnmarshaller() {
this(AmazonServiceException.class);
}
/**
* Constructs a new error unmarshaller that will unmarshall error responses
* into objects of the specified class, extending AmazonServiceException.
*
* @param exceptionClass
* The subclass of AmazonServiceException which will be
* instantiated and populated by this class.
*/
public AbstractErrorUnmarshaller(Class<? extends AmazonServiceException> exceptionClass) {
this.exceptionClass = exceptionClass;
}
/**
* Constructs a new exception object of the type specified in this class's
* constructor and sets the specified error message.
*
* @param message
* The error message to set in the new exception object.
*
* @return A new exception object of the type specified in this class's
* constructor and sets the specified error message.
*
* @throws Exception
* If there are any problems using reflection to invoke the
* exception class's constructor.
*/
protected AmazonServiceException newException(String message) throws Exception {
Constructor<? extends AmazonServiceException> constructor = exceptionClass.getConstructor(String.class);
return constructor.newInstance(message);
}
}
|
jentfoo/aws-sdk-java
|
aws-java-sdk-core/src/main/java/com/amazonaws/transform/AbstractErrorUnmarshaller.java
|
Java
|
apache-2.0
| 2,633 |
package com.icfcc.cache.support;
import com.icfcc.cache.Cache;
import java.util.Collection;
/**
* Simple cache manager working against a given collection of caches.
* Useful for testing or simple caching declarations.
*
* @author Costin Leau
* @since 3.1
*/
public class SimpleCacheManager extends AbstractCacheManager {
private Collection<? extends Cache> caches;
/**
* Specify the collection of Cache instances to use for this CacheManager.
*/
public void setCaches(Collection<? extends Cache> caches) {
this.caches = caches;
}
@Override
protected Collection<? extends Cache> loadCaches() {
return this.caches;
}
}
|
Gitpiece/spring-cache-project
|
spring-cache/src/main/java/com/icfcc/cache/support/SimpleCacheManager.java
|
Java
|
apache-2.0
| 684 |
package fr.fablabmars.model;
import java.util.ArrayList;
import fr.fablabmars.observer.Observable;
import fr.fablabmars.observer.Observer;
/**
* Observable contenant le menu courant.
*
* @author Guillaume Perouffe
* @see Observable
*/
public class CardMenu implements Observable {
/**
* Liste des observateurs de cet observable.
*/
private ArrayList<Observer> listObserver = new ArrayList<Observer>();
/**
* Indice du menu courant
*/
private int panel;
/**
* Constructeur de l'observable
* <p>
* On initialise le menu sur le 'panel' par défaut,
* d'indice 0.
* </p>
*
* @see CardMenu#panel
*/
public CardMenu(){
panel = 0;
}
/**
* Change le panneau courant et notifie les observateurs.
*
* @param panel
* Indice du nouveau menu.
*
* @see CardMenu#panel
* @see Observable#notifyObservers()
*/
public void setPanel(int panel){
this.panel = panel;
notifyObservers();
}
@Override
public void addObserver(Observer obs) {
listObserver.add(obs);
}
@Override
public void removeObserver(Observer obs) {
listObserver.remove(obs);
}
@Override
public void notifyObservers() {
for(Observer obs:listObserver){
obs.update(this);
}
}
/**
* Retourne le menu courant
*
* @return Menu courant
*
* @see CardMenu#panel
*/
@Override
public int getState(){
return panel;
}
}
|
gperouffe/FabLabUsers
|
src/fr/fablabmars/model/CardMenu.java
|
Java
|
apache-2.0
| 1,473 |
package ru.job4j.collections.tree;
/**
* Бинарное дерево .
*
* @author Hincu Andrei (andreih1981@gmail.com) by 20.10.17;
* @version $Id$
* @since 0.1
* @param <E> тип данных.
*/
public class BinaryTree<E extends Comparable<E>> extends Tree<E> {
/**
* Корень дерева.
*/
private Node<E> node;
/**
* Размер дерева.
*/
private int size;
/**
* Узел дерева.
* @param <E> значение.
*/
private class Node<E> {
/**
* Значение.
*/
private E value;
/**
* левый сын.
*/
private Node<E> left;
/**
* правый сын.
*/
private Node<E> right;
/**
* Конструктор.
* @param value значение узла.
*/
private Node(E value) {
this.value = value;
}
}
/**
* Добавляем новый элемент или корень дерева.
* @param e значение.
*/
public void add(E e) {
if (node == null) {
node = new Node<>(e);
size++;
} else {
addNewElement(e, node);
}
}
/**
* Метод для поиска места вставки.
* @param e значение.
* @param n текуший узел дерева.
*/
private void addNewElement(E e, Node<E> n) {
if (e.compareTo(n.value) < 0) {
if (n.left == null) {
n.left = new Node<>(e);
size++;
} else {
addNewElement(e, n.left);
}
} else if (e.compareTo(n.value) > 0) {
if (n.right == null) {
n.right = new Node<>(e);
size++;
} else {
addNewElement(e, n.right);
}
}
}
/**
* геттер.
* @return размер дерева.
*/
public int getSize() {
return size;
}
}
|
andreiHi/hincuA
|
chapter_005/src/main/java/ru/job4j/collections/tree/BinaryTree.java
|
Java
|
apache-2.0
| 2,101 |
/**
* 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.pinot.core.startree.v2.store;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.ByteOrder;
import java.util.List;
import java.util.Map;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.pinot.common.segment.ReadMode;
import org.apache.pinot.core.segment.index.column.ColumnIndexContainer;
import org.apache.pinot.core.segment.index.metadata.SegmentMetadataImpl;
import org.apache.pinot.core.segment.memory.PinotDataBuffer;
import org.apache.pinot.core.startree.v2.StarTreeV2;
import org.apache.pinot.core.startree.v2.StarTreeV2Constants;
import static org.apache.pinot.core.startree.v2.store.StarTreeIndexMapUtils.IndexKey;
import static org.apache.pinot.core.startree.v2.store.StarTreeIndexMapUtils.IndexValue;
/**
* The {@code StarTreeIndexContainer} class contains the indexes for multiple star-trees.
*/
public class StarTreeIndexContainer implements Closeable {
private final PinotDataBuffer _dataBuffer;
private final List<StarTreeV2> _starTrees;
public StarTreeIndexContainer(File segmentDirectory, SegmentMetadataImpl segmentMetadata,
Map<String, ColumnIndexContainer> indexContainerMap, ReadMode readMode)
throws ConfigurationException, IOException {
File indexFile = new File(segmentDirectory, StarTreeV2Constants.INDEX_FILE_NAME);
if (readMode == ReadMode.heap) {
_dataBuffer = PinotDataBuffer
.loadFile(indexFile, 0, indexFile.length(), ByteOrder.LITTLE_ENDIAN, "Star-tree V2 data buffer");
} else {
_dataBuffer = PinotDataBuffer
.mapFile(indexFile, true, 0, indexFile.length(), ByteOrder.LITTLE_ENDIAN, "Star-tree V2 data buffer");
}
File indexMapFile = new File(segmentDirectory, StarTreeV2Constants.INDEX_MAP_FILE_NAME);
List<Map<IndexKey, IndexValue>> indexMapList =
StarTreeIndexMapUtils.loadFromFile(indexMapFile, segmentMetadata.getStarTreeV2MetadataList().size());
_starTrees = StarTreeLoaderUtils.loadStarTreeV2(_dataBuffer, indexMapList, segmentMetadata, indexContainerMap);
}
public List<StarTreeV2> getStarTrees() {
return _starTrees;
}
@Override
public void close()
throws IOException {
_dataBuffer.close();
}
}
|
linkedin/pinot
|
pinot-core/src/main/java/org/apache/pinot/core/startree/v2/store/StarTreeIndexContainer.java
|
Java
|
apache-2.0
| 3,059 |
/*
Copyright 2010-2011 Zhengmao HU (James)
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.sf.jabb.util.text;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Given a text string to be tested, and list of matching strings, find out which matching string the
* text string starts with.<br>
* 给定一个待检查的文本字符串,以及一批开头匹配字符串,看看待检查的文本字符串以哪个匹配字符串开头。
* <p>
* The matching is case sensitive.
* If one matching string starts with another,
* and the text string starts with them, then the longer one will be considered to be matched.
* <p>
* 匹配时对大小写敏感。如果匹配字符串之间互相饱含,则匹配其中最长的。
*
* <p>
* If the matching need to be checked upon number segments (start number ~ end number) represented
* as strings, {@link #expandNumberMatchingRange(Map, String, String, Object)} method can be used to
* expand number segments to heading number strings.
* <p>
* 如果需要对代表数字号码(开始号码~结束号码)的字符串进行匹配,可使用
* {@link #expandNumberMatchingRange(Map, String, String, Object)} 方法
* 将号码段字符串(一个开始号码,一个结束号码)转换为号码头字符串。
*
* @author Zhengmao HU (James)
*
*/
public class StringStartWithMatcher extends StartWithMatcher {
private static final long serialVersionUID = -2501231925022032723L;
/**
* Create a new instance according to heading strings and their corresponding attachment objects.<br>
* 根据开头匹配字符串、开头匹配字符串所对应的附件对象,创建一个新的实例。
* <p>
* When initializing internal data structure, choose to consume more memory for better matching speed.
* <p>
* 在创建内部数据结构的时候,选择占用更多内存,而换取速度上的提升。
*
* @param headingDefinitions Key is the heading string, Value is its associated attachment object.
* When the heading string is matched, the attachment object will be returned
* as identifier.<p>
* Key是匹配字符串,Value是附件对象。
* 当进行匹配检查的时候,返回附件对象来标识哪一个匹配字符串被匹配上了。
*/
public StringStartWithMatcher(Map<String, ? extends Object> headingDefinitions) {
super(normalizeMatchingDefinitions(headingDefinitions));
}
/**
* Create a new instance according to heading strings and their corresponding attachment objects.<br>
* 根据开头匹配字符串、开头匹配字符串所对应的附件对象,创建一个新的实例。
*
* @param headingDefinitions Key是匹配字符串,Value是附件对象。
* 当进行匹配检查的时候,返回附件对象来标识哪一个匹配字符串被匹配上了。
* <p>
* Key is the heading string, Value is its associated attachment object.
* When the heading string is matched, the attachment object will be returned
* as identifier.
* @param moreSpaceForSpeed 是否占用更多内存,而换取速度上的提升。
* <p>Whether or not to consume
* more memory for better matching speed.
*/
public StringStartWithMatcher(Map<String, ? extends Object> headingDefinitions, boolean moreSpaceForSpeed) {
super(normalizeMatchingDefinitions(headingDefinitions), moreSpaceForSpeed);
}
/**
* Create a copy, the copy will have exactly the same matching
* definitions as the original copy.<br>
* 创建一个副本,这个副本与原先的对象具有完全相同匹配方式。
*
* @param toBeCopied 原本。<br>The original copy.
*/
public StringStartWithMatcher(StringStartWithMatcher toBeCopied) {
super(toBeCopied);
}
/**
* Normalize matching definitions according to requirements of {@link StartWithMatcher}.<br>
* 根据{@link StartWithMatcher}的需要来规范化匹配条件定义。
*
* @param headingDefinitions Key是匹配字符串,Value是附件对象。
* 当进行匹配检查的时候,返回附件对象来标识哪一个匹配字符串被匹配上了。
* <p>
* Key is the heading string, Value is its associated attachment object.
* When the heading string is matched, the attachment object will be returned
* as identifier.
* @return {@link StartWithMatcher}所需的匹配条件定义。
* <br>Matching definitions for usage of {@link StartWithMatcher}.
*/
static protected List<MatchingDefinition> normalizeMatchingDefinitions(Map<String, ? extends Object> headingDefinitions){
// exactMatchExample自动设置为与regularExpression相同
List<MatchingDefinition> l = new ArrayList<MatchingDefinition>(headingDefinitions.size());
for (Map.Entry<String, ? extends Object> e: headingDefinitions.entrySet()){
MatchingDefinition c = new MatchingDefinition();
c.setRegularExpression(escapeForRegExp(e.getKey()));
c.setAttachment(e.getValue());
c.setExactMatchExample(e.getKey());
l.add(c);
}
return l;
}
/**
* Expand number segments (such as 138000~138999 or 138000~138029) into number headings
* (such as 138 or {13800,13801,13802}).<br>
* 把号码段(类似:138000~138999或138000~138029)展开成号码头(类似:138或13800,13801,13802)。
*
* @param headingDefinitions 可用来对{@link StringStartWithMatcher}进行初始化的展开后的匹配条件
* 会被放到这个Map里。
* <br> Equivalent heading definitions that could be used to
* create instance of {@link StringStartWithMatcher} will be put into this Map.
* @param start 起始号码 <br> first/starting number
* @param end 结束号码 <br> last/ending number
* @param attachment 匹配附件<br>attachment to identify that the segment matches a string
*/
public static <T> void expandNumberMatchingRange(Map<String, T> headingDefinitions, String start, String end, T attachment){
int firstDiff; //第一个不相同字符的位置
int lastDiff; //末尾0:9对应段开始的位置
// 先强行保证起始号码与结束号码长度相同
if (start.length() > end.length()){
StringBuilder sb = new StringBuilder(end);
while (start.length() > sb.length()){
sb.append("9");
}
end = sb.toString();
} else if (end.length() > start.length()){
StringBuilder sb = new StringBuilder(start);
while (end.length() > sb.length()){
sb.append("0");
}
start = sb.toString();
}
// 然后寻找第一个不相同字符的位置
for (firstDiff = 0; firstDiff < start.length(); firstDiff++){
if (start.charAt(firstDiff) != end.charAt(firstDiff)){
break;
}
}
// 再寻找末尾0:9对应段开始的位置
for (lastDiff = start.length() - 1; lastDiff >= 0; lastDiff--){
if (start.charAt(lastDiff) != '0' || end.charAt(lastDiff) != '9'){
break;
}
}
lastDiff++;
if (firstDiff == lastDiff){ // 则表示可合并为一条
headingDefinitions.put(start.substring(0, firstDiff), attachment);
} else { // 则表示要扩展为多条
int j = Integer.parseInt(start.substring(firstDiff, lastDiff));
int k = Integer.parseInt(end.substring(firstDiff, lastDiff));
String head = start.substring(0, firstDiff);
String f = "%" + (lastDiff-firstDiff) + "d";
StringBuilder sb = new StringBuilder();
for (int i = j; i <= k; i++){
sb.setLength(0);
sb.append(head);
sb.append(String.format(f, i));
headingDefinitions.put(sb.toString(), attachment);
}
}
}
}
|
james-hu/jabb-core
|
src/main/java/net/sf/jabb/util/text/StringStartWithMatcher.java
|
Java
|
apache-2.0
| 8,259 |
package com.dexvis.simple.transform;
import javafx.scene.web.HTMLEditor;
import org.simpleframework.xml.transform.Transform;
public class HTMLEditorTransform implements Transform<HTMLEditor>
{
public HTMLEditor read(String value) throws Exception
{
HTMLEditor editor = new HTMLEditor();
editor.setHtmlText(value);
return editor;
}
@Override
public String write(HTMLEditor value) throws Exception
{
return value.getHtmlText();
}
}
|
PatMartin/Dex
|
src/com/dexvis/simple/transform/HTMLEditorTransform.java
|
Java
|
apache-2.0
| 485 |
package ecologylab.bigsemantics.service.crawler;
import java.io.IOException;
/**
* A general framework for crawling resources.
*
* @author quyin
*/
public interface ResourceCrawler<T>
{
/**
* Queue a resource with the given URI.
*
* @param uri
*/
void queue(String uri);
/**
* If the crawler has more resources to crawl.
*
* @return true if there are still resources to crawl.
*/
boolean hasNext();
/**
* Retrieve the next resource.
*
* @return The next crawled resource.
* @throws IOException
* If the resource cannot be accessed.
*/
T next() throws IOException;
/**
* Expand a given resource.
*
* @param resource
*/
void expand(T resource);
/**
* @return The number of resources queued.
*/
int countQueued();
/**
* @return The number of resources that are to be crawled.
*/
int countWaiting();
/**
* @return The number of resources that have been accessed.
*/
int countAccessed();
/**
* @return The number of resources that have been accessed successfully.
*/
int countSuccess();
/**
* @return The number of resources that have been accessed unsuccessfully.
*/
int countFailure();
}
|
ecologylab/BigSemanticsService
|
BasicCrawler/src/ecologylab/bigsemantics/service/crawler/ResourceCrawler.java
|
Java
|
apache-2.0
| 1,304 |
package net.sf.anpr.rcp.widget;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
public class JCanvasPanel extends JLabel {
private static final long serialVersionUID = 1L;
private Rectangle focusArea=new Rectangle();
private BufferedImage image;
public JCanvasPanel() {
super();
this.setVerticalAlignment(SwingConstants.TOP);
this.setHorizontalAlignment(SwingConstants.LEFT);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(focusArea==null) return ;
if (focusArea.width >= 0 && focusArea.height >= 0) {
Color c = g.getColor();
g.setColor(Color.RED);
g.drawRect(focusArea.x, focusArea.y, focusArea.width, focusArea.height);
g.setColor(c);
}
g.dispose();
}
protected void setImage(BufferedImage image){
this.image=image;
this.setIcon(new ImageIcon(image));
}
public void setFocusArea(Rectangle focusArea) {
this.focusArea = focusArea;
}
protected BufferedImage getImage() {
return image;
}
}
|
alexmao86/swing-rcp
|
src/main/java/net/sf/anpr/rcp/widget/JCanvasPanel.java
|
Java
|
apache-2.0
| 1,173 |
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2022 DBeaver Corp and others
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.ui.app.standalone.about;
import org.eclipse.jface.action.IAction;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionDelegate;
public class AboutBoxAction extends ActionDelegate
{
private IWorkbenchWindow window;
public AboutBoxAction(IWorkbenchWindow window) {
this.window = window;
}
@Override
public void run(IAction action)
{
// new AboutDialog(window.getShell()).open();
AboutBoxDialog dialog = new AboutBoxDialog(window.getShell());
dialog.open();
}
}
|
dbeaver/dbeaver
|
plugins/org.jkiss.dbeaver.ui.app.standalone/src/org/jkiss/dbeaver/ui/app/standalone/about/AboutBoxAction.java
|
Java
|
apache-2.0
| 1,230 |
package com.action.design.pattern.chain;
/**
* 创建不同类型的记录器。赋予它们不同的错误级别,并在每个记录器中设置下一个记录器。每个记录器中的下一个记录器代表的是链的一部分。
* Created by wuyunfeng on 2017/6/15.
*/
public class ChainPatternDemo {
private static AbstractLogger getChainOfLoggers() {
AbstractLogger errorLogger = new ErrorLogger(AbstractLogger.ERROR);
AbstractLogger fileLogger = new FileLogger(AbstractLogger.DEBUG);
AbstractLogger consoleLogger = new ConsoleLogger(AbstractLogger.INFO);
errorLogger.setNextLogger(fileLogger);
fileLogger.setNextLogger(consoleLogger);
return errorLogger;
}
public static void main(String[] args) {
AbstractLogger loggerChain = getChainOfLoggers();
loggerChain.logMessage(AbstractLogger.INFO, "This is an information.");
loggerChain.logMessage(AbstractLogger.DEBUG,
"This is an debug level information.");
loggerChain.logMessage(AbstractLogger.ERROR,
"This is an error information.");
}
}
|
pearpai/java_action
|
src/main/java/com/action/design/pattern/chain/ChainPatternDemo.java
|
Java
|
apache-2.0
| 1,140 |
/*
* Copyright (c) 2021, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* 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 boofcv.alg.descriptor;
import boofcv.struct.feature.TupleDesc_B;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.TimeValue;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@SuppressWarnings("ResultOfMethodCallIgnored") @BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 2)
@Measurement(iterations = 5)
@State(Scope.Benchmark)
@Fork(value = 1)
public class BenchmarkDescriptorDistance {
static int NUM_FEATURES = 10000;
List<TupleDesc_B> binaryA = new ArrayList<>();
List<TupleDesc_B> binaryB = new ArrayList<>();
HammingTable16 table = new HammingTable16();
@Setup public void setup() {
Random rand = new Random(234234);
binaryA = new ArrayList<>();
binaryB = new ArrayList<>();
for (int i = 0; i < NUM_FEATURES; i++) {
binaryA.add(randomFeature(rand));
binaryB.add(randomFeature(rand));
}
}
@Benchmark public void hammingTable() {
for (int i = 0; i < binaryA.size(); i++) {
tableScore(binaryA.get(i), binaryB.get(i));
}
}
private int tableScore( TupleDesc_B a, TupleDesc_B b ) {
int score = 0;
for (int i = 0; i < a.data.length; i++) {
int dataA = a.data[i];
int dataB = b.data[i];
score += table.lookup((short)dataA, (short)dataB);
score += table.lookup((short)(dataA >> 16), (short)(dataB >> 16));
}
return score;
}
@Benchmark public void equationOld() {
for (int i = 0; i < binaryA.size(); i++) {
ExperimentalDescriptorDistance.hamming(binaryA.get(i), binaryB.get(i));
}
}
@Benchmark public void equation() {
for (int i = 0; i < binaryA.size(); i++) {
DescriptorDistance.hamming(binaryA.get(i), binaryB.get(i));
}
}
private TupleDesc_B randomFeature( Random rand ) {
TupleDesc_B feat = new TupleDesc_B(512);
for (int j = 0; j < feat.data.length; j++) {
feat.data[j] = rand.nextInt();
}
return feat;
}
public static void main( String[] args ) throws RunnerException {
Options opt = new OptionsBuilder()
.include(BenchmarkDescriptorDistance.class.getSimpleName())
.warmupTime(TimeValue.seconds(1))
.measurementTime(TimeValue.seconds(1))
.build();
new Runner(opt).run();
}
}
|
lessthanoptimal/BoofCV
|
main/boofcv-feature/src/benchmark/java/boofcv/alg/descriptor/BenchmarkDescriptorDistance.java
|
Java
|
apache-2.0
| 3,105 |
package adamin90.com.wpp.model.mostsearch;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
@Generated("org.jsonschema2pojo")
public class MostSearchData {
@SerializedName("data")
@Expose
private List<Datum> data = new ArrayList<Datum>();
@SerializedName("code")
@Expose
private Integer code;
/**
*
* @return
* The data
*/
public List<Datum> getData() {
return data;
}
/**
*
* @param data
* The data
*/
public void setData(List<Datum> data) {
this.data = data;
}
/**
*
* @return
* The code
*/
public Integer getCode() {
return code;
}
/**
*
* @param code
* The code
*/
public void setCode(Integer code) {
this.code = code;
}
}
|
adamin1990/MaterialWpp
|
wpp/app/src/main/java/adamin90/com/wpp/model/mostsearch/MostSearchData.java
|
Java
|
apache-2.0
| 971 |
package com.hangon.saying.viewPager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.example.fd.ourapplication.R;
import com.hangon.common.Constants;
import com.hangon.common.MyApplication;
import com.hangon.common.ViewHolder;
import com.hangon.common.VolleyBitmapCache;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2016/5/31.
*/
public class GradAdapter extends BaseAdapter implements AbsListView.OnScrollListener {
Context context;
List list = new ArrayList();
private static ImageLoader mImageLoader; // imageLoader对象,用来初始化NetworkImageView
/**
* 记录每个子项的高度。
*/
private int mItemHeight = 0;
GradAdapter(Context context, List list) {
this.context = context;
this.list = list;
mImageLoader = new ImageLoader(MyApplication.queues, new VolleyBitmapCache()); // 初始化一个loader对象,可以进行自定义配置
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
ViewGradHolder gradHolder;
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
gradHolder = new ViewGradHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.carlife_grade_content, null);
gradHolder.img = (ImageView) convertView.findViewById(R.id.item_grida_image);
convertView.setTag(gradHolder);
} else {
gradHolder = (ViewGradHolder) convertView.getTag();
}
NetworkImageView networkImageView = (NetworkImageView) gradHolder.img;
// 设置默认的图片
networkImageView.setDefaultImageResId(R.drawable.default_photo);
// 设置图片加载失败后显示的图片
networkImageView.setErrorImageResId(R.drawable.error_photo);
if (list.get(position) != null && !list.get(position).equals("")) {
//getImag(list.get(position).toString());
// 开始加载网络图片
networkImageView.setImageUrl(Constants.LOAD_SAYING_IMG_URL + list.get(position), mImageLoader);
}
return convertView;
}
class ViewGradHolder {
ImageView img;
}
private void getImag(String path) {
String url = Constants.LOAD_SAYING_IMG_URL + path;
ImageRequest request = new ImageRequest(url, new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap bitmap) {
gradHolder.img.setImageBitmap(bitmap);
}
}, 0, 0, Bitmap.Config.ARGB_8888, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(context, "说说图片加载失败", Toast.LENGTH_SHORT).show();
}
});
MyApplication.getHttpQueues().add(request);
}
/**
* 设置item子项的高度。
*/
public void setItemHeight(int height) {
if (height == mItemHeight) {
return;
}
mItemHeight = height;
notifyDataSetChanged();
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// 仅当GridView静止时才去下载图片,GridView滑动时取消所有正在下载的任务
if (scrollState == SCROLL_STATE_IDLE) {
// loadBitmaps(mFirstVisibleItem, mVisibleItemCount);
} else {
// cancelAllTasks();
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
}
|
TangZuopeng/OurApplication
|
app/src/main/java/com/hangon/saying/viewPager/GradAdapter.java
|
Java
|
apache-2.0
| 4,468 |
/**
* Copyright 2013 Agustín Miura <"agustin.miura@gmail.com">
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package ar.com.imperium.common.security;
import org.springframework.stereotype.Component;
@Component("dummyHashService")
public class DummyHashServiceImpl implements IHashService
{
@Override
public String hashString(String input) throws Exception
{
return input;
}
}
|
agustinmiura/imperium
|
src/main/java/ar/com/imperium/common/security/DummyHashServiceImpl.java
|
Java
|
apache-2.0
| 925 |
package com.sadc.game.gameobject.trackobject;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.sadc.game.GameConstants;
import com.sadc.game.gameobject.GameUtils;
import com.sadc.game.gameobject.Player;
/**
* @author f536985 (Tom Farello)
*/
public class Wall extends TrackObject {
public Wall(float distance, float angle) {
setActive(true);
setDistance(distance);
setAngle(angle);
setWidth(22);
setTexture(new Texture("brickWall.png"));
}
@Override
public void update(float delta, Player player) {
if (collide(player)) {
player.crash();
setActive(false);
}
}
@Override
public void draw(float delta, float playerDistance, SpriteBatch spriteBatch) {
float drawDistance = (float)Math.pow(2 , playerDistance - (getDistance()));
GameUtils.setColorByDrawDistance(drawDistance, spriteBatch);
spriteBatch.draw(getTexture(), GameConstants.SCREEN_WIDTH / 2 - 50, 15,
50, GameConstants.SCREEN_HEIGHT / 2 - 15, 100, 70, drawDistance, drawDistance, getAngle(), 0, 0, 100, 70, false, false);
}
}
|
jlturner85/libgdx-gradle-template
|
core/src/main/java/com/sadc/game/gameobject/trackobject/Wall.java
|
Java
|
apache-2.0
| 1,196 |
/*
*
* * Copyright 2010-2016 OrientDB LTD (http://orientdb.com)
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
* * For more information: http://orientdb.com
*
*/
package com.orientechnologies.orient.core.sql.functions.coll;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* This operator can work as aggregate or inline. If only one argument is passed than aggregates,
* otherwise executes, and returns, the SYMMETRIC DIFFERENCE between the collections received as
* parameters. Works also with no collection values.
*
* @author Luca Garulli (l.garulli--(at)--orientdb.com)
*/
public class OSQLFunctionSymmetricDifference extends OSQLFunctionMultiValueAbstract<Set<Object>> {
public static final String NAME = "symmetricDifference";
private Set<Object> rejected;
public OSQLFunctionSymmetricDifference() {
super(NAME, 1, -1);
}
private static void addItemToResult(Object o, Set<Object> accepted, Set<Object> rejected) {
if (!accepted.contains(o) && !rejected.contains(o)) {
accepted.add(o);
} else {
accepted.remove(o);
rejected.add(o);
}
}
private static void addItemsToResult(
Collection<Object> co, Set<Object> accepted, Set<Object> rejected) {
for (Object o : co) {
addItemToResult(o, accepted, rejected);
}
}
@SuppressWarnings("unchecked")
public Object execute(
Object iThis,
OIdentifiable iCurrentRecord,
Object iCurrentResult,
final Object[] iParams,
OCommandContext iContext) {
if (iParams[0] == null) return null;
Object value = iParams[0];
if (iParams.length == 1) {
// AGGREGATION MODE (STATEFUL)
if (context == null) {
context = new HashSet<Object>();
rejected = new HashSet<Object>();
}
if (value instanceof Collection<?>) {
addItemsToResult((Collection<Object>) value, context, rejected);
} else {
addItemToResult(value, context, rejected);
}
return null;
} else {
// IN-LINE MODE (STATELESS)
final Set<Object> result = new HashSet<Object>();
final Set<Object> rejected = new HashSet<Object>();
for (Object iParameter : iParams) {
if (iParameter instanceof Collection<?>) {
addItemsToResult((Collection<Object>) iParameter, result, rejected);
} else {
addItemToResult(iParameter, result, rejected);
}
}
return result;
}
}
@Override
public Set<Object> getResult() {
if (returnDistributedResult()) {
final Map<String, Object> doc = new HashMap<String, Object>();
doc.put("result", context);
doc.put("rejected", rejected);
return Collections.<Object>singleton(doc);
} else {
return super.getResult();
}
}
public String getSyntax() {
return "difference(<field>*)";
}
@Override
public Object mergeDistributedResult(List<Object> resultsToMerge) {
if (returnDistributedResult()) {
final Set<Object> result = new HashSet<Object>();
final Set<Object> rejected = new HashSet<Object>();
for (Object item : resultsToMerge) {
rejected.addAll(unwrap(item, "rejected"));
}
for (Object item : resultsToMerge) {
addItemsToResult(unwrap(item, "result"), result, rejected);
}
return result;
}
if (!resultsToMerge.isEmpty()) return resultsToMerge.get(0);
return null;
}
@SuppressWarnings("unchecked")
private Set<Object> unwrap(Object obj, String field) {
final Set<Object> objAsSet = (Set<Object>) obj;
final Map<String, Object> objAsMap = (Map<String, Object>) objAsSet.iterator().next();
final Set<Object> objAsField = (Set<Object>) objAsMap.get(field);
return objAsField;
}
}
|
orientechnologies/orientdb
|
core/src/main/java/com/orientechnologies/orient/core/sql/functions/coll/OSQLFunctionSymmetricDifference.java
|
Java
|
apache-2.0
| 4,574 |
/*
* Copyright 2012-2017 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.simpleemail.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* <p>
* An empty element returned on a successful request.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/SetReceiptRulePosition" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SetReceiptRulePositionResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof SetReceiptRulePositionResult == false)
return false;
SetReceiptRulePositionResult other = (SetReceiptRulePositionResult) obj;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
return hashCode;
}
@Override
public SetReceiptRulePositionResult clone() {
try {
return (SetReceiptRulePositionResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
|
dagnir/aws-sdk-java
|
aws-java-sdk-ses/src/main/java/com/amazonaws/services/simpleemail/model/SetReceiptRulePositionResult.java
|
Java
|
apache-2.0
| 2,365 |
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.stream.Stream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import com.google.common.base.Optional;
import com.google.common.collect.Iterables;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.daisy.pipeline.client.PipelineClient;
import org.daisy.pipeline.webservice.jaxb.job.Job;
import org.daisy.pipeline.webservice.jaxb.job.JobStatus;
import org.daisy.pipeline.webservice.jaxb.job.Messages;
import org.daisy.pipeline.webservice.jaxb.request.Callback;
import org.daisy.pipeline.webservice.jaxb.request.CallbackType;
import org.daisy.pipeline.webservice.jaxb.request.Input;
import org.daisy.pipeline.webservice.jaxb.request.Item;
import org.daisy.pipeline.webservice.jaxb.request.JobRequest;
import org.daisy.pipeline.webservice.jaxb.request.ObjectFactory;
import org.daisy.pipeline.webservice.jaxb.request.Script;
import org.daisy.pipeline.webservice.jaxb.request.Priority;
import org.junit.Assert;
import org.junit.Test;
public class TestPushNotifications extends Base {
private static final PipelineClient client = newClient(TestClientJobs.CREDS_DEF.clientId, TestClientJobs.CREDS_DEF.secret);
@Override
protected PipelineClient client() {
return client;
}
@Override
protected Properties systemProperties() {
Properties p = super.systemProperties();
// client authentication is required for push notifications
p.setProperty("org.daisy.pipeline.ws.authentication", "true");
p.setProperty("org.daisy.pipeline.ws.authentication.key", TestClientJobs.CREDS_DEF.clientId);
p.setProperty("org.daisy.pipeline.ws.authentication.secret", TestClientJobs.CREDS_DEF.secret);
return p;
}
@Test
public void testPushNotifications() throws Exception {
AbstractCallback testStatusAndMessages = new AbstractCallback() {
JobStatus lastStatus = null;
BigDecimal lastProgress = BigDecimal.ZERO;
Iterator<BigDecimal> mustSee = stream(".25", ".375", ".5", ".55", ".675", ".8", ".9").map(d -> new BigDecimal(d)).iterator();
BigDecimal mustSeeNext = mustSee.next();
List<BigDecimal> seen = new ArrayList<BigDecimal>();
@Override
void handleStatus(JobStatus status) {
lastStatus = status;
}
@Override
void handleMessages(Messages messages) {
BigDecimal progress = messages.getProgress();
if (progress.compareTo(lastProgress) != 0) {
Assert.assertTrue("Progress must be monotonic non-decreasing", progress.compareTo(lastProgress) >= 0);
if (mustSeeNext != null) {
if (progress.compareTo(mustSeeNext) == 0) {
seen.clear();
mustSeeNext = mustSee.hasNext() ? mustSee.next() : null;
} else {
seen.add(progress);
Assert.assertTrue("Expected " + mustSeeNext + " but got " + seen, progress.compareTo(mustSeeNext) < 0);
}
}
lastProgress = progress;
}
}
@Override
void finalTest() {
Assert.assertEquals(JobStatus.SUCCESS, lastStatus);
Assert.assertTrue("Expected " + mustSeeNext + " but got " + seen, mustSeeNext == null);
}
};
HttpServer server; {
server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/notify", testStatusAndMessages);
server.setExecutor(null);
server.start();
}
try {
JobRequest req; {
ObjectFactory oFactory = new ObjectFactory();
req = oFactory.createJobRequest();
Script script = oFactory.createScript(); {
Optional<String> href = getScriptHref("mock-messages-script");
Assert.assertTrue(href.isPresent());
script.setHref(href.get());
}
req.getScriptOrNicenameOrPriority().add(script);
Input input = oFactory.createInput(); {
Item source = oFactory.createItem();
source.setValue(getResource("hello.xml").toURI().toString());
input.getItem().add(source);
input.setName("source");
}
req.getScriptOrNicenameOrPriority().add(input);
req.getScriptOrNicenameOrPriority().add(oFactory.createNicename("NICE_NAME"));
req.getScriptOrNicenameOrPriority().add(oFactory.createPriority(Priority.LOW));
Callback callback = oFactory.createCallback(); {
callback.setType(CallbackType.MESSAGES);
callback.setHref("http://localhost:8080/notify");
callback.setFrequency("1");
}
req.getScriptOrNicenameOrPriority().add(callback);
callback = oFactory.createCallback(); {
callback.setType(CallbackType.STATUS);
callback.setHref("http://localhost:8080/notify");
callback.setFrequency("1");
}
req.getScriptOrNicenameOrPriority().add(callback);
}
Job job = client().sendJob(req);
deleteAfterTest(job);
waitForStatus(JobStatus.SUCCESS, job, 10000);
// wait until all updates have been pushed
Thread.sleep(1000);
testStatusAndMessages.finalTest();
} finally {
server.stop(1);
}
}
public static abstract class AbstractCallback implements HttpHandler {
abstract void handleStatus(JobStatus status);
abstract void handleMessages(Messages messages);
abstract void finalTest();
@Override
public void handle(HttpExchange t) throws IOException {
Job job; {
try {
job = (Job)JAXBContext.newInstance(Job.class).createUnmarshaller().unmarshal(t.getRequestBody());
} catch (JAXBException e) {
throw new RuntimeException(e);
}
}
handleStatus(job.getStatus());
Optional<Messages> messages = getMessages(job);
if (messages.isPresent())
handleMessages(messages.get());
String response = "got it";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
static Optional<Messages> getMessages(Job job) {
return Optional.fromNullable(
Iterables.getOnlyElement(
Iterables.filter(
job.getNicenameOrBatchIdOrScript(),
Messages.class),
null));
}
static <T> Stream<T> stream(T... array) {
return Arrays.<T>stream(array);
}
}
|
daisy/pipeline-issues
|
framework/webservice/src/test/java/TestPushNotifications.java
|
Java
|
apache-2.0
| 6,214 |
/*
* Copyright 2012-2016 JetBrains s.r.o
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.jetpad.base.edt;
public class BufferingEdtManager extends RunningEdtManager {
public BufferingEdtManager() {
super();
}
public BufferingEdtManager(String name) {
super(name);
}
@Override
protected void doSchedule(Runnable r) {
addTaskToQueue(r);
}
@Override
public String toString() {
return "BufferingEdtManager@" + Integer.toHexString(hashCode()) +
("".equals(getName()) ? "" : " (" + getName()+ ")");
}
}
|
timzam/jetpad-mapper
|
util/base/src/test/java/jetbrains/jetpad/base/edt/BufferingEdtManager.java
|
Java
|
apache-2.0
| 1,075 |
/*
* Copyright 2016
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* 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 de.tudarmstadt.ukp.experiments.argumentation.sequence.io.filters;
import de.tudarmstadt.ukp.experiments.argumentation.sequence.DocumentRegister;
import org.apache.uima.jcas.JCas;
import java.util.HashSet;
import java.util.Set;
/**
* Filter wrt document register
*
* @author Ivan Habernal
*/
public class DocumentRegisterFilter
implements DocumentCollectionFilter
{
private final Set<DocumentRegister> documentRegisters = new HashSet<>();
public DocumentRegisterFilter(String documentRegistersString)
{
// parse document registers
if (!documentRegistersString.isEmpty()) {
for (String documentDomainSplit : documentRegistersString.split(" ")) {
String domain = documentDomainSplit.trim();
if (!domain.isEmpty()) {
documentRegisters.add(DocumentRegister.fromString(domain));
}
}
}
}
@Override
public boolean removeFromCollection(JCas jCas)
{
DocumentRegister register = DocumentRegister.fromJCas(jCas);
return !documentRegisters.isEmpty() && !documentRegisters.contains(register);
}
@Override
public boolean applyFilter()
{
return !documentRegisters.isEmpty();
}
}
|
habernal/emnlp2015
|
code/experiments/src/main/java/de/tudarmstadt/ukp/experiments/argumentation/sequence/io/filters/DocumentRegisterFilter.java
|
Java
|
apache-2.0
| 1,948 |
package es.npatarino.android.gotchallenge.chat.message.viewmodel;
import android.net.Uri;
import es.npatarino.android.gotchallenge.chat.message.model.Payload;
public class StickerPayLoad implements Payload {
private String stickerFilePath;
public StickerPayLoad(String stickerFilePath) {
this.stickerFilePath = stickerFilePath;
}
public String getStickerFilePath() {
return stickerFilePath;
}
public Uri getSticker() {
return Uri.parse(stickerFilePath);
}
}
|
tonilopezmr/Game-of-Thrones
|
app/src/main/java/es/npatarino/android/gotchallenge/chat/message/viewmodel/StickerPayLoad.java
|
Java
|
apache-2.0
| 490 |
/* */ package com.hundsun.network.gates.wulin.biz.service.pojo.auction;
/* */
/* */ import com.hundsun.network.gates.luosi.biz.security.ServiceException;
/* */ import com.hundsun.network.gates.luosi.common.enums.EnumActiveStatus;
/* */ import com.hundsun.network.gates.luosi.common.enums.EnumBidCheckStatus;
/* */ import com.hundsun.network.gates.luosi.common.enums.EnumBidPriceStatus;
/* */ import com.hundsun.network.gates.luosi.common.enums.EnumOperatorType;
/* */ import com.hundsun.network.gates.luosi.common.remote.ServiceResult;
/* */ import com.hundsun.network.gates.luosi.wulin.reomte.enums.EnumAuctionErrors;
/* */ import com.hundsun.network.gates.luosi.wulin.reomte.request.AuctionMulitBidRequest;
/* */ import com.hundsun.network.gates.luosi.wulin.reomte.request.SystemMessageRequest;
/* */ import com.hundsun.network.gates.wulin.biz.dao.auction.AuctionBidderDAO;
/* */ import com.hundsun.network.gates.wulin.biz.dao.auction.AuctionFreeBidDAO;
/* */ import com.hundsun.network.gates.wulin.biz.dao.auction.AuctionHallDAO;
/* */ import com.hundsun.network.gates.wulin.biz.dao.auction.AuctionLogDAO;
/* */ import com.hundsun.network.gates.wulin.biz.domain.auction.AuctionBidder;
/* */ import com.hundsun.network.gates.wulin.biz.domain.auction.AuctionFreeBid;
/* */ import com.hundsun.network.gates.wulin.biz.domain.auction.AuctionLog;
/* */ import com.hundsun.network.gates.wulin.biz.domain.auction.AuctionMulitBidProject;
/* */ import com.hundsun.network.gates.wulin.biz.domain.query.AuctionMulitBidProjectQuery;
/* */ import com.hundsun.network.gates.wulin.biz.domain.query.MulitAuctionReviewQuery;
/* */ import com.hundsun.network.gates.wulin.biz.service.BaseService;
/* */ import com.hundsun.network.gates.wulin.biz.service.auction.MulitAuctionService;
/* */ import com.hundsun.network.gates.wulin.biz.service.message.SystemMessageService;
/* */ import com.hundsun.network.gates.wulin.biz.service.project.ProjectListingService;
/* */ import com.hundsun.network.melody.common.util.StringUtil;
/* */ import java.io.IOException;
/* */ import java.util.ArrayList;
/* */ import java.util.HashMap;
/* */ import java.util.List;
/* */ import java.util.Locale;
/* */ import org.apache.commons.logging.Log;
/* */ import org.codehaus.jackson.map.ObjectMapper;
/* */ import org.springframework.beans.factory.annotation.Autowired;
/* */ import org.springframework.context.MessageSource;
/* */ import org.springframework.stereotype.Service;
/* */ import org.springframework.transaction.TransactionStatus;
/* */ import org.springframework.transaction.support.TransactionCallback;
/* */ import org.springframework.transaction.support.TransactionTemplate;
/* */
/* */ @Service("mulitAuctionService")
/* */ public class MulitAuctionServiceImpl extends BaseService
/* */ implements MulitAuctionService
/* */ {
/* */
/* */ @Autowired
/* */ private ProjectListingService projectListingService;
/* */
/* */ @Autowired
/* */ private AuctionFreeBidDAO auctionFreeBidDAO;
/* */
/* */ @Autowired
/* */ private AuctionBidderDAO auctionBidderDAO;
/* */
/* */ @Autowired
/* */ private AuctionLogDAO auctionLogDAO;
/* */
/* */ @Autowired
/* */ private MessageSource messageSource;
/* */
/* */ @Autowired
/* */ private AuctionHallDAO auctionHallDAO;
/* */
/* */ @Autowired
/* */ private SystemMessageService systemMessageService;
/* */
/* */ public ServiceResult review(final AuctionMulitBidRequest request)
/* */ {
/* 70 */ ServiceResult serviceResult = new ServiceResult();
/* */
/* 72 */ if ((null == request) || (StringUtil.isEmpty(request.getBidderAccount())) || (StringUtil.isEmpty(request.getReviewer())) || (StringUtil.isEmpty(request.getProjectCode())) || (StringUtil.isEmpty(request.getRemark())))
/* */ {
/* 76 */ serviceResult.setErrorNOInfo(Integer.valueOf(EnumAuctionErrors.PARAMETER_ERROR.getValue()), EnumAuctionErrors.PARAMETER_ERROR.getInfo());
/* */
/* 78 */ return serviceResult;
/* */ }
/* 80 */ AuctionMulitBidProjectQuery query = new AuctionMulitBidProjectQuery();
/* 81 */ query.setReviewer(request.getReviewer());
/* 82 */ query.setProjectCode(request.getProjectCode());
/* 83 */ List projectList = this.projectListingService.queryAuctionMulitBidProjectUncheckedByProjectCode(query);
/* */
/* 86 */ if ((null == projectList) || (projectList.size() <= 0)) {
/* 87 */ serviceResult.setErrorNOInfo(Integer.valueOf(EnumAuctionErrors.CHECK_PROJECT_LISTING_NULL.getValue()), EnumAuctionErrors.CHECK_PROJECT_LISTING_NULL.getInfo());
/* */
/* 89 */ return serviceResult;
/* */ }
/* */
/* 92 */ AuctionFreeBid auctionFreeBid = queryTopUncheckFreeBid(request.getProjectCode(), request.getBidderAccount());
/* */
/* 94 */ if (null == auctionFreeBid) {
/* 95 */ serviceResult.setErrorNOInfo(Integer.valueOf(EnumAuctionErrors.PARAMETER_ERROR.getValue()), EnumAuctionErrors.PARAMETER_ERROR.getInfo());
/* */
/* 97 */ return serviceResult;
/* */ }
/* */
/* 100 */ AuctionBidder auctionBidder = this.auctionBidderDAO.selectNormalByBidderAccount(request.getProjectCode(), request.getBidderAccount());
/* */
/* 102 */ if (null == auctionBidder) {
/* 103 */ serviceResult.setErrorNOInfo(Integer.valueOf(EnumAuctionErrors.CHECK_BIDDER_NULL.getValue()), EnumAuctionErrors.CHECK_BIDDER_NULL.getInfo());
/* */
/* 105 */ return serviceResult;
/* */ }
/* 107 */ ObjectMapper mapper = new ObjectMapper();
/* 108 */ String auctionBidderJson = "";
/* */ try {
/* 110 */ auctionBidderJson = mapper.writeValueAsString(auctionBidder);
/* */ } catch (IOException e) {
/* 112 */ if (this.log.isErrorEnabled()) {
/* 113 */ this.log.error("convert auctionBidder to json format fail,", e);
/* */ }
/* */ }
/* 116 */ final String fAuctionBidderJson = auctionBidderJson;
/* 117 */ final AuctionFreeBid fAuctionFreeBid = auctionFreeBid;
/* 118 */ final String logRemark = getMessage("project.auction.mulitbid.review.log.remark", new String[] { request.getReviewer(), auctionBidder.getBidderAccount() });
/* */
/* 120 */ final AuctionBidder fAuctionBidder = auctionBidder;
/* 121 */ final AuctionMulitBidProject fAuctionMulitBidProject = (AuctionMulitBidProject)projectList.get(0);
/* */
/* 123 */ serviceResult = (ServiceResult)this.transactionTemplate.execute(new TransactionCallback() {
/* */ public ServiceResult doInTransaction(TransactionStatus status) {
/* 125 */ ServiceResult result = new ServiceResult();
/* 126 */ Object savePoint = status.createSavepoint();
/* */ try
/* */ {
/* 129 */ AuctionFreeBid auctionFreeBid = new AuctionFreeBid();
/* 130 */ auctionFreeBid.setBidderAccount(fAuctionFreeBid.getBidderAccount());
/* 131 */ auctionFreeBid.setBidderTrademark(fAuctionFreeBid.getBidderTrademark());
/* 132 */ auctionFreeBid.setBidOperatorAccount(fAuctionFreeBid.getBidOperatorAccount());
/* 133 */ auctionFreeBid.setCheckRemark(request.getRemark());
/* 134 */ auctionFreeBid.setCheckStatus(EnumBidCheckStatus.Fail.getValue());
/* 135 */ auctionFreeBid.setIp(fAuctionFreeBid.getIp());
/* 136 */ auctionFreeBid.setOperator(request.getOperator());
/* 137 */ auctionFreeBid.setPrice(fAuctionFreeBid.getPrice());
/* 138 */ auctionFreeBid.setProjectCode(request.getProjectCode());
/* 139 */ auctionFreeBid.setStatus(fAuctionFreeBid.getStatus());
/* 140 */ MulitAuctionServiceImpl.this.auctionFreeBidDAO.insert(auctionFreeBid);
/* */
/* 143 */ if (MulitAuctionServiceImpl.this.auctionBidderDAO.deleteByBidderAccount(request.getProjectCode(), request.getBidderAccount()) <= 0)
/* */ {
/* 145 */ throw new ServiceException(EnumAuctionErrors.REVIEW_DELETE_BIDDER_FAIL.getInfo(), Integer.valueOf(EnumAuctionErrors.REVIEW_DELETE_BIDDER_FAIL.getValue()));
/* */ }
/* */
/* 150 */ if (EnumActiveStatus.Yes.getValue().equals(fAuctionBidder.getIsPriority())) {
/* 151 */ HashMap actionHallMap = new HashMap();
/* 152 */ actionHallMap.put("priorityNumSub", Integer.valueOf(1));
/* 153 */ actionHallMap.put("whereProjectCode", request.getProjectCode());
/* 154 */ if (MulitAuctionServiceImpl.this.auctionHallDAO.updateByMap(actionHallMap) <= 0) {
/* 155 */ throw new ServiceException(EnumAuctionErrors.REVIEW_UPDATE_HALL_FALL.getInfo(), Integer.valueOf(EnumAuctionErrors.REVIEW_UPDATE_HALL_FALL.getValue()));
/* */ }
/* */
/* */ }
/* */
/* 172 */ SystemMessageRequest systemMessageRequest = new SystemMessageRequest();
/* 173 */ systemMessageRequest.setSendAccount(EnumOperatorType.SYSTEM.getValue());
/* 174 */ systemMessageRequest.setContent(MulitAuctionServiceImpl.this.getMessage("project.auction.mulitbid.review.message.content", new String[] { fAuctionMulitBidProject.getProjectTitle(), request.getRemark() }));
/* */
/* 177 */ systemMessageRequest.setTitle(MulitAuctionServiceImpl.this.getMessage("project.auction.mulitbid.review.message.title", new String[0]));
/* */
/* 179 */ List userAccountList = new ArrayList();
/* 180 */ userAccountList.add(fAuctionBidder.getBidderAccount());
/* 181 */ systemMessageRequest.setUserAccountList(userAccountList);
/* 182 */ MulitAuctionServiceImpl.this.systemMessageService.sendSystemMessage(systemMessageRequest);
/* */
/* 185 */ AuctionLog auctionLog = new AuctionLog();
/* 186 */ auctionLog.setDataJson(fAuctionBidderJson);
/* 187 */ auctionLog.setProjectCode(request.getProjectCode());
/* 188 */ auctionLog.setRemark(logRemark);
/* 189 */ auctionLog.setOperatorType(EnumOperatorType.REVIEWER.getValue());
/* 190 */ auctionLog.setOperator(request.getReviewer());
/* 191 */ MulitAuctionServiceImpl.this.auctionLogDAO.insert(auctionLog);
/* */ }
/* */ catch (ServiceException e) {
/* 194 */ status.rollbackToSavepoint(savePoint);
/* 195 */ MulitAuctionServiceImpl.this.log.error("MulitAuctionServiceImpl review fail", e);
/* 196 */ result.setErrorNO(e.getErrorNO());
/* 197 */ result.setErrorInfo(e.getErrorInfo());
/* */ } catch (Exception e) {
/* 199 */ status.rollbackToSavepoint(savePoint);
/* 200 */ MulitAuctionServiceImpl.this.log.error("MulitAuctionServiceImpl review error", e);
/* 201 */ result.setErrorNO(Integer.valueOf(EnumAuctionErrors.INTERNAL_ERROR.getValue()));
/* 202 */ result.setErrorInfo(EnumAuctionErrors.INTERNAL_ERROR.getInfo());
/* */ }
/* 204 */ return result;
/* */ }
/* */ });
/* 208 */ return serviceResult;
/* */ }
/* */
/* */ public AuctionFreeBid queryTopUncheckFreeBid(String projectCode, String bidderAccount)
/* */ {
/* 213 */ MulitAuctionReviewQuery query = new MulitAuctionReviewQuery();
/* 214 */ query.setBidderAccount(bidderAccount);
/* 215 */ query.setCheckStatus(EnumBidCheckStatus.Pass);
/* 216 */ query.setProjectCode(projectCode);
/* 217 */ query.setStatus(EnumBidPriceStatus.EFFECTIVE);
/* 218 */ return this.auctionFreeBidDAO.selectTopByMulitAuctionReviewQuery(query);
/* */ }
/* */
/* */ protected String getMessage(String code, String[] args) {
/* 222 */ return this.messageSource.getMessage(code, args, Locale.CHINA);
/* */ }
/* */ }
/* Location: E:\__安装归档\linquan-20161112\deploy16\wulin\webroot\WEB-INF\classes\
* Qualified Name: com.hundsun.network.gates.wulin.biz.service.pojo.auction.MulitAuctionServiceImpl
* JD-Core Version: 0.6.0
*/
|
hnccfr/ccfrweb
|
basecore/src/com/hundsun/network/gates/wulin/biz/service/pojo/auction/MulitAuctionServiceImpl.java
|
Java
|
apache-2.0
| 12,488 |
/*
* Copyright 2002-2013 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.utn.dacs2017.compraventa.vendedor;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author Grego Dadone
*/
@Controller
class VendedorController {
private final VendedorRepository vendedores;
@Autowired
public VendedorController(VendedorRepository vendedorService) {
this.vendedores = vendedorService;
}
@RequestMapping(value = { "/vendedores.html" })
public String showVendedorList(Map<String, Object> model) {
Vendedores vendedores = new Vendedores();
vendedores.getVendedorList().addAll(this.vendedores.findAll());
model.put("vendedores", vendedores);
return "vendedores/vendedorList";
}
@RequestMapping(value = { "/vendedores.json", "/vendedores.xml" })
public @ResponseBody Vendedores showResourcesVendedorList() {
Vendedores vendedores = new Vendedores();
vendedores.getVendedorList().addAll(this.vendedores.findAll());
return vendedores;
}
}
|
gregodadone/spring-compraventa
|
src/main/java/org/utn/dacs2017/compraventa/vendedor/VendedorController.java
|
Java
|
apache-2.0
| 1,812 |
package com.afollestad.breadcrumb;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewCompat;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* @author Aidan Follestad (afollestad)
*/
public class LinearBreadcrumb extends HorizontalScrollView implements View.OnClickListener {
public static class Crumb implements Serializable {
public Crumb(String path,String attachMsg) {
mPath = path;
mAttachMsg = attachMsg;
}
private final String mPath;
private final String mAttachMsg;
private int mScrollY;
private int mScrollOffset;
public int getScrollY() {
return mScrollY;
}
public int getScrollOffset() {
return mScrollOffset;
}
public void setScrollY(int scrollY) {
this.mScrollY = scrollY;
}
public void setScrollOffset(int scrollOffset) {
this.mScrollOffset = scrollOffset;
}
public String getPath() {
return mPath;
}
public String getTitle() {
return (!TextUtils.isEmpty(mAttachMsg)) ? mAttachMsg : mPath;
}
public String getmAttachMsg() {
return mAttachMsg;
}
@Override
public boolean equals(Object o) {
return (o instanceof Crumb) && ((Crumb) o).getPath().equals(getPath());
}
@Override
public String toString() {
return "Crumb{" +
"mAttachMsg='" + mAttachMsg + '\'' +
", mPath='" + mPath + '\'' +
", mScrollY=" + mScrollY +
", mScrollOffset=" + mScrollOffset +
'}';
}
}
public interface SelectionCallback {
void onCrumbSelection(Crumb crumb, String absolutePath, int count, int index);
}
public LinearBreadcrumb(Context context) {
super(context);
init();
}
public LinearBreadcrumb(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public LinearBreadcrumb(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private List<Crumb> mCrumbs;
private List<Crumb> mOldCrumbs;
private LinearLayout mChildFrame;
private int mActive;
private SelectionCallback mCallback;
private void init() {
setMinimumHeight((int) getResources().getDimension(R.dimen.breadcrumb_height));
setClipToPadding(false);
mCrumbs = new ArrayList<>();
mChildFrame = new LinearLayout(getContext());
addView(mChildFrame, new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void setAlpha(View view, int alpha) {
if (view instanceof ImageView && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
((ImageView) view).setImageAlpha(alpha);
} else {
ViewCompat.setAlpha(view, alpha);
}
}
public void addCrumb(@NonNull Crumb crumb, boolean refreshLayout) {
LinearLayout view = (LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.bread_crumb, this, false);
view.setTag(mCrumbs.size());
view.setClickable(true);
view.setFocusable(true);
view.setOnClickListener(this);
mChildFrame.addView(view, new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
mCrumbs.add(crumb);
if (refreshLayout) {
mActive = mCrumbs.size() - 1;
requestLayout();
}
invalidateActivatedAll();
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
//RTL works fine like this
View child = mChildFrame.getChildAt(mActive);
if (child != null)
smoothScrollTo(child.getLeft(), 0);
}
public Crumb findCrumb(@NonNull String forDir) {
for (int i = 0; i < mCrumbs.size(); i++) {
if (mCrumbs.get(i).getPath().equals(forDir))
return mCrumbs.get(i);
}
return null;
}
public void clearCrumbs() {
try {
mOldCrumbs = new ArrayList<>(mCrumbs);
mCrumbs.clear();
mChildFrame.removeAllViews();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
public Crumb getCrumb(int index) {
return mCrumbs.get(index);
}
public void setCallback(SelectionCallback callback) {
mCallback = callback;
}
public boolean setActive(Crumb newActive) {
mActive = mCrumbs.indexOf(newActive);
for(int i = size()-1;size()>mActive+1;i--){
removeCrumbAt(i);
}
((LinearLayout)mChildFrame.getChildAt(mActive)).getChildAt(1).setVisibility(View.GONE);
boolean success = mActive > -1;
if (success)
requestLayout();
return success;
}
private void invalidateActivatedAll() {
for (int i = 0; i < mCrumbs.size(); i++) {
Crumb crumb = mCrumbs.get(i);
invalidateActivated(mChildFrame.getChildAt(i), mActive == mCrumbs.indexOf(crumb),
i < mCrumbs.size() - 1).setText(crumb.getTitle());
}
}
public void removeCrumbAt(int index) {
mCrumbs.remove(index);
mChildFrame.removeViewAt(index);
}
private void updateIndices() {
for (int i = 0; i < mChildFrame.getChildCount(); i++)
mChildFrame.getChildAt(i).setTag(i);
}
private boolean isValidPath(String path) {
return path == null;
}
public int size() {
return mCrumbs.size();
}
private TextView invalidateActivated(View view, boolean isActive, boolean isShowSeparator) {
LinearLayout child = (LinearLayout) view;
if (isShowSeparator)
child.getChildAt(1).setVisibility(View.VISIBLE);
return (TextView) child.getChildAt(0);
}
public int getActiveIndex() {
return mActive;
}
@Override
public void onClick(View v) {
if (mCallback != null) {
int index = (Integer) v.getTag();
if (index >= 0 && index < (size()-1)) {
setActive(mCrumbs.get(index));
mCallback.onCrumbSelection(mCrumbs.get(index),
getAbsolutePath(mCrumbs.get(index), "/"), mCrumbs.size(), index);
}
}
}
public static class SavedStateWrapper implements Serializable {
public final int mActive;
public final List<Crumb> mCrumbs;
public final int mVisibility;
public SavedStateWrapper(LinearBreadcrumb view) {
mActive = view.mActive;
mCrumbs = view.mCrumbs;
mVisibility = view.getVisibility();
}
}
public SavedStateWrapper getStateWrapper() {
return new SavedStateWrapper(this);
}
public void restoreFromStateWrapper(SavedStateWrapper mSavedState, Activity context) {
if (mSavedState != null) {
mActive = mSavedState.mActive;
for (Crumb c : mSavedState.mCrumbs) {
addCrumb(c, false);
}
requestLayout();
setVisibility(mSavedState.mVisibility);
}
}
public String getAbsolutePath(Crumb crumb, @NonNull String separator) {
StringBuilder builder = new StringBuilder();
if (size() > 1 && !crumb.equals(mCrumbs.get(0))) {
List<Crumb> crumbs = mCrumbs.subList(1, size());
for (Crumb mCrumb : crumbs) {
builder.append(mCrumb.getPath());
builder.append(separator);
if (mCrumb.equals(crumb)) {
break;
}
}
String path = builder.toString();
return path.substring(0, path.length() -1);
} else {
return null;
}
}
public String getCurAbsolutePath(@NonNull String separator){
return getAbsolutePath(getCrumb(mActive),separator);
}
public void addRootCrumb() {
clearCrumbs();
addCrumb(new Crumb("/","root"), true);
}
public void addPath(@NonNull String path,@NonNull String sha, @NonNull String separator) {
clearCrumbs();
addCrumb(new Crumb("",""), false);
String[] paths = path.split(separator);
Crumb lastCrumb = null;
for (String splitPath : paths) {
lastCrumb = new Crumb(splitPath,sha);
addCrumb(lastCrumb, false);
}
if (lastCrumb != null) {
setActive(lastCrumb);
}
}
}
|
jbm714060/Github
|
breadcrumb/src/main/java/com/afollestad/breadcrumb/LinearBreadcrumb.java
|
Java
|
apache-2.0
| 9,519 |
/*
* Copyright 2015 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.orc.impl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Random;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.ql.exec.vector.BytesColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch;
import org.apache.orc.CompressionKind;
import org.apache.orc.OrcConf;
import org.apache.orc.OrcFile;
import org.apache.orc.Reader;
import org.apache.orc.RecordReader;
import org.apache.orc.TypeDescription;
import org.apache.orc.Writer;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class TestOrcLargeStripe {
private Path workDir = new Path(System.getProperty("test.tmp.dir", "target" + File.separator + "test"
+ File.separator + "tmp"));
Configuration conf;
FileSystem fs;
private Path testFilePath;
@Rule
public TestName testCaseName = new TestName();
@Before
public void openFileSystem() throws Exception {
conf = new Configuration();
fs = FileSystem.getLocal(conf);
testFilePath = new Path(workDir, "TestOrcFile." + testCaseName.getMethodName() + ".orc");
fs.delete(testFilePath, false);
}
@Mock
private FSDataInputStream mockDataInput;
static class RangeBuilder {
BufferChunkList result = new BufferChunkList();
RangeBuilder range(long offset, int length) {
result.add(new BufferChunk(offset, length));
return this;
}
BufferChunkList build() {
return result;
}
}
@Test
public void testZeroCopy() throws Exception {
BufferChunkList ranges = new RangeBuilder().range(1000, 3000).build();
HadoopShims.ZeroCopyReaderShim mockZcr = mock(HadoopShims.ZeroCopyReaderShim.class);
when(mockZcr.readBuffer(anyInt(), anyBoolean()))
.thenAnswer(invocation -> ByteBuffer.allocate(1000));
RecordReaderUtils.readDiskRanges(mockDataInput, mockZcr, ranges, true);
verify(mockDataInput).seek(1000);
verify(mockZcr).readBuffer(3000, false);
verify(mockZcr).readBuffer(2000, false);
verify(mockZcr).readBuffer(1000, false);
}
@Test
public void testRangeMerge() throws Exception {
BufferChunkList rangeList = new RangeBuilder()
.range(100, 1000)
.range(1000, 10000)
.range(3000, 30000).build();
RecordReaderUtils.readDiskRanges(mockDataInput, null, rangeList, false);
verify(mockDataInput).readFully(eq(100L), any(), eq(0), eq(32900));
}
@Test
public void testRangeSkip() throws Exception {
BufferChunkList rangeList = new RangeBuilder()
.range(1000, 1000)
.range(2000, 1000)
.range(4000, 1000)
.range(4100, 100)
.range(8000, 1000).build();
RecordReaderUtils.readDiskRanges(mockDataInput, null, rangeList, false);
verify(mockDataInput).readFully(eq(1000L), any(), eq(0), eq(2000));
verify(mockDataInput).readFully(eq(4000L), any(), eq(0), eq(1000));
verify(mockDataInput).readFully(eq(8000L), any(), eq(0), eq(1000));
}
@Test
public void testEmpty() throws Exception {
BufferChunkList rangeList = new RangeBuilder().build();
RecordReaderUtils.readDiskRanges(mockDataInput, null, rangeList, false);
verify(mockDataInput, never()).readFully(anyLong(), any(), anyInt(), anyInt());
}
@Test
public void testConfigMaxChunkLimit() throws IOException {
Configuration conf = new Configuration();
FileSystem fs = FileSystem.getLocal(conf);
TypeDescription schema = TypeDescription.createTimestamp();
testFilePath = new Path(workDir, "TestOrcLargeStripe." +
testCaseName.getMethodName() + ".orc");
fs.delete(testFilePath, false);
Writer writer = OrcFile.createWriter(testFilePath,
OrcFile.writerOptions(conf).setSchema(schema).stripeSize(100000).bufferSize(10000)
.version(OrcFile.Version.V_0_11).fileSystem(fs));
writer.close();
OrcFile.ReaderOptions opts = OrcFile.readerOptions(conf);
Reader reader = OrcFile.createReader(testFilePath, opts);
RecordReader recordReader = reader.rows(new Reader.Options().range(0L, Long.MAX_VALUE));
assertTrue(recordReader instanceof RecordReaderImpl);
assertEquals(Integer.MAX_VALUE - 1024, ((RecordReaderImpl) recordReader).getMaxDiskRangeChunkLimit());
conf = new Configuration();
conf.setInt(OrcConf.ORC_MAX_DISK_RANGE_CHUNK_LIMIT.getHiveConfName(), 1000);
opts = OrcFile.readerOptions(conf);
reader = OrcFile.createReader(testFilePath, opts);
recordReader = reader.rows(new Reader.Options().range(0L, Long.MAX_VALUE));
assertTrue(recordReader instanceof RecordReaderImpl);
assertEquals(1000, ((RecordReaderImpl) recordReader).getMaxDiskRangeChunkLimit());
}
@Test
public void testStringDirectGreaterThan2GB() throws IOException {
final Runtime rt = Runtime.getRuntime();
assumeTrue(rt.maxMemory() > 4_000_000_000L);
TypeDescription schema = TypeDescription.createString();
conf.setDouble("hive.exec.orc.dictionary.key.size.threshold", 0.0);
Writer writer = OrcFile.createWriter(
testFilePath,
OrcFile.writerOptions(conf).setSchema(schema)
.compress(CompressionKind.NONE));
// 5000 is the lower bound for a stripe
int size = 5000;
int width = 500_000;
// generate a random string that is width characters long
Random random = new Random(123);
char[] randomChars= new char[width];
int posn = 0;
for(int length = 0; length < width && posn < randomChars.length; ++posn) {
char cp = (char) random.nextInt(Character.MIN_SUPPLEMENTARY_CODE_POINT);
// make sure we get a valid, non-surrogate
while (Character.isSurrogate(cp)) {
cp = (char) random.nextInt(Character.MIN_SUPPLEMENTARY_CODE_POINT);
}
// compute the length of the utf8
length += cp < 0x80 ? 1 : (cp < 0x800 ? 2 : 3);
randomChars[posn] = cp;
}
// put the random characters in as a repeating value.
VectorizedRowBatch batch = schema.createRowBatch();
BytesColumnVector string = (BytesColumnVector) batch.cols[0];
string.setVal(0, new String(randomChars, 0, posn).getBytes(StandardCharsets.UTF_8));
string.isRepeating = true;
for(int rows=size; rows > 0; rows -= batch.size) {
batch.size = Math.min(rows, batch.getMaxSize());
writer.addRowBatch(batch);
}
writer.close();
try {
Reader reader = OrcFile.createReader(testFilePath,
OrcFile.readerOptions(conf).filesystem(fs));
RecordReader rows = reader.rows();
batch = reader.getSchema().createRowBatch();
int rowsRead = 0;
while (rows.nextBatch(batch)) {
rowsRead += batch.size;
}
assertEquals(size, rowsRead);
} finally {
fs.delete(testFilePath, false);
}
}
}
|
omalley/orc
|
java/core/src/test/org/apache/orc/impl/TestOrcLargeStripe.java
|
Java
|
apache-2.0
| 8,450 |
/*
* Solo - A small and beautiful blogging system written in Java.
* Copyright (c) 2010-present, b3log.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.b3log.solo.processor;
import org.apache.commons.lang.StringUtils;
import org.b3log.solo.AbstractTestCase;
import org.b3log.solo.MockHttpServletRequest;
import org.b3log.solo.MockHttpServletResponse;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* {@link ErrorProcessor} test case.
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.0.1.3, Feb 22, 2019
* @since 1.7.0
*/
@Test(suiteName = "processor")
public class ErrorProcessorTestCase extends AbstractTestCase {
/**
* Init.
*
* @throws Exception exception
*/
@Test
public void init() throws Exception {
super.init();
}
/**
* showErrorPage.
*/
@Test(dependsOnMethods = "init")
public void showErrorPage() {
final MockHttpServletRequest request = mockRequest();
request.setRequestURI("/error/403");
final MockHttpServletResponse response = mockResponse();
mockDispatcherServletService(request, response);
final String content = response.body();
Assert.assertTrue(StringUtils.contains(content, "<title>403 Forbidden! - Solo 的个人博客</title>"));
}
}
|
b3log/b3log-solo
|
src/test/java/org/b3log/solo/processor/ErrorProcessorTestCase.java
|
Java
|
apache-2.0
| 1,972 |
/* 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.flowable.engine.impl.cmd;
import java.io.Serializable;
import org.flowable.engine.common.api.FlowableException;
import org.flowable.engine.common.api.FlowableIllegalArgumentException;
import org.flowable.engine.common.api.FlowableObjectNotFoundException;
import org.flowable.engine.common.impl.interceptor.Command;
import org.flowable.engine.common.impl.interceptor.CommandContext;
import org.flowable.engine.form.TaskFormData;
import org.flowable.engine.impl.form.FormEngine;
import org.flowable.engine.impl.form.TaskFormHandler;
import org.flowable.engine.impl.persistence.entity.TaskEntity;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.engine.impl.util.FormHandlerUtil;
import org.flowable.engine.task.Task;
/**
* @author Tom Baeyens
* @author Joram Barrez
*/
public class GetRenderedTaskFormCmd implements Command<Object>, Serializable {
private static final long serialVersionUID = 1L;
protected String taskId;
protected String formEngineName;
public GetRenderedTaskFormCmd(String taskId, String formEngineName) {
this.taskId = taskId;
this.formEngineName = formEngineName;
}
public Object execute(CommandContext commandContext) {
if (taskId == null) {
throw new FlowableIllegalArgumentException("Task id should not be null");
}
TaskEntity task = CommandContextUtil.getTaskEntityManager(commandContext).findById(taskId);
if (task == null) {
throw new FlowableObjectNotFoundException("Task '" + taskId + "' not found", Task.class);
}
TaskFormHandler taskFormHandler = FormHandlerUtil.getTaskFormHandlder(task);
if (taskFormHandler != null) {
FormEngine formEngine = CommandContextUtil.getProcessEngineConfiguration(commandContext).getFormEngines().get(formEngineName);
if (formEngine == null) {
throw new FlowableException("No formEngine '" + formEngineName + "' defined process engine configuration");
}
TaskFormData taskForm = taskFormHandler.createTaskForm(task);
return formEngine.renderTaskForm(taskForm);
}
return null;
}
}
|
stephraleigh/flowable-engine
|
modules/flowable-engine/src/main/java/org/flowable/engine/impl/cmd/GetRenderedTaskFormCmd.java
|
Java
|
apache-2.0
| 2,774 |
package com.stdnull.v2api.model;
import android.os.Bundle;
import android.os.Parcelable;
import java.util.ArrayList;
import java.util.List;
/**
* Created by chen on 2017/8/20.
*/
public class V2MainFragModel {
private static final String KEY_V2EXBEAN = "KEY_V2EXBEAN";
private List<V2ExBean> mContentListModel = new ArrayList<>();
public List<V2ExBean> getContentListModel() {
return mContentListModel;
}
public void addContentListModel(List<V2ExBean> contentListModel) {
if(contentListModel != null) {
this.mContentListModel.addAll(contentListModel);
}
}
public boolean isModelEmpty(){
return mContentListModel.isEmpty() ;
}
public void clearModel(){
mContentListModel.clear();
}
public void save(Bundle bundle){
bundle.putParcelableArrayList(KEY_V2EXBEAN, (ArrayList<? extends Parcelable>) mContentListModel);
}
public boolean restore(Bundle bundle){
if(bundle == null){
return false;
}
mContentListModel = bundle.getParcelableArrayList(KEY_V2EXBEAN);
return mContentListModel != null && !mContentListModel.isEmpty();
}
}
|
stdnull/RunMap
|
v2api/src/main/java/com/stdnull/v2api/model/V2MainFragModel.java
|
Java
|
apache-2.0
| 1,194 |
/*
* Solo - A small and beautiful blogging system written in Java.
* Copyright (c) 2010-present, b3log.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.b3log.solo.model;
/**
* This class defines all link model relevant keys.
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.0.0.2, Oct 31, 2011
* @since 0.3.1
*/
public final class Link {
/**
* Link.
*/
public static final String LINK = "link";
/**
* Links.
*/
public static final String LINKS = "links";
/**
* Key of title.
*/
public static final String LINK_TITLE = "linkTitle";
/**
* Key of address.
*/
public static final String LINK_ADDRESS = "linkAddress";
/**
* Key of description.
*/
public static final String LINK_DESCRIPTION = "linkDescription";
/**
* Key of order.
*/
public static final String LINK_ORDER = "linkOrder";
/**
* Private constructor.
*/
private Link() {
}
}
|
b3log/b3log-solo
|
src/main/java/org/b3log/solo/model/Link.java
|
Java
|
apache-2.0
| 1,646 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.management;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.openmbean.TabularData;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.util.StringHelper;
import org.junit.Ignore;
/**
* @version
*/
public class ManagedCamelContextTest extends ManagementTestSupport {
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext context = super.createCamelContext();
// to force a different management name than the camel id
context.getManagementNameStrategy().setNamePattern("19-#name#");
return context;
}
public void testManagedCamelContext() throws Exception {
// JMX tests dont work well on AIX CI servers (hangs them)
if (isPlatform("aix")) {
return;
}
MBeanServer mbeanServer = getMBeanServer();
ObjectName on = ObjectName.getInstance("org.apache.camel:context=19-camel-1,type=context,name=\"camel-1\"");
assertTrue("Should be registered", mbeanServer.isRegistered(on));
String name = (String) mbeanServer.getAttribute(on, "CamelId");
assertEquals("camel-1", name);
String managementName = (String) mbeanServer.getAttribute(on, "ManagementName");
assertEquals("19-camel-1", managementName);
String uptime = (String) mbeanServer.getAttribute(on, "Uptime");
assertNotNull(uptime);
String status = (String) mbeanServer.getAttribute(on, "State");
assertEquals("Started", status);
Boolean messageHistory = (Boolean) mbeanServer.getAttribute(on, "MessageHistory");
assertEquals(Boolean.TRUE, messageHistory);
Integer total = (Integer) mbeanServer.getAttribute(on, "TotalRoutes");
assertEquals(2, total.intValue());
Integer started = (Integer) mbeanServer.getAttribute(on, "StartedRoutes");
assertEquals(2, started.intValue());
// invoke operations
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceived("Hello World");
mbeanServer.invoke(on, "sendBody", new Object[]{"direct:start", "Hello World"}, new String[]{"java.lang.String", "java.lang.Object"});
assertMockEndpointsSatisfied();
resetMocks();
mock.expectedBodiesReceived("Hello World");
mbeanServer.invoke(on, "sendStringBody", new Object[]{"direct:start", "Hello World"}, new String[]{"java.lang.String", "java.lang.String"});
assertMockEndpointsSatisfied();
Object reply = mbeanServer.invoke(on, "requestBody", new Object[]{"direct:foo", "Hello World"}, new String[]{"java.lang.String", "java.lang.Object"});
assertEquals("Bye World", reply);
reply = mbeanServer.invoke(on, "requestStringBody", new Object[]{"direct:foo", "Hello World"}, new String[]{"java.lang.String", "java.lang.String"});
assertEquals("Bye World", reply);
resetMocks();
mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceived("Hello World");
mock.expectedHeaderReceived("foo", 123);
Map<String, Object> headers = new HashMap<String, Object>();
headers.put("foo", 123);
mbeanServer.invoke(on, "sendBodyAndHeaders", new Object[]{"direct:start", "Hello World", headers}, new String[]{"java.lang.String", "java.lang.Object", "java.util.Map"});
assertMockEndpointsSatisfied();
resetMocks();
mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceived("Hello World");
mock.expectedHeaderReceived("foo", 123);
reply = mbeanServer.invoke(on, "requestBodyAndHeaders", new Object[]{"direct:start", "Hello World", headers}, new String[]{"java.lang.String", "java.lang.Object", "java.util.Map"});
assertEquals("Hello World", reply);
assertMockEndpointsSatisfied();
// test can send
Boolean can = (Boolean) mbeanServer.invoke(on, "canSendToEndpoint", new Object[]{"direct:start"}, new String[]{"java.lang.String"});
assertEquals(true, can.booleanValue());
can = (Boolean) mbeanServer.invoke(on, "canSendToEndpoint", new Object[]{"timer:foo"}, new String[]{"java.lang.String"});
assertEquals(false, can.booleanValue());
// stop Camel
mbeanServer.invoke(on, "stop", null, null);
}
public void testManagedCamelContextCreateEndpoint() throws Exception {
// JMX tests dont work well on AIX CI servers (hangs them)
if (isPlatform("aix")) {
return;
}
MBeanServer mbeanServer = getMBeanServer();
ObjectName on = ObjectName.getInstance("org.apache.camel:context=19-camel-1,type=context,name=\"camel-1\"");
assertNull(context.hasEndpoint("seda:bar"));
// create a new endpoint
Object reply = mbeanServer.invoke(on, "createEndpoint", new Object[]{"seda:bar"}, new String[]{"java.lang.String"});
assertEquals(Boolean.TRUE, reply);
assertNotNull(context.hasEndpoint("seda:bar"));
ObjectName seda = ObjectName.getInstance("org.apache.camel:context=19-camel-1,type=endpoints,name=\"seda://bar\"");
boolean registered = mbeanServer.isRegistered(seda);
assertTrue("Should be registered " + seda, registered);
// create it again
reply = mbeanServer.invoke(on, "createEndpoint", new Object[]{"seda:bar"}, new String[]{"java.lang.String"});
assertEquals(Boolean.FALSE, reply);
registered = mbeanServer.isRegistered(seda);
assertTrue("Should be registered " + seda, registered);
}
public void testManagedCamelContextRemoveEndpoint() throws Exception {
// JMX tests dont work well on AIX CI servers (hangs them)
if (isPlatform("aix")) {
return;
}
MBeanServer mbeanServer = getMBeanServer();
ObjectName on = ObjectName.getInstance("org.apache.camel:context=19-camel-1,type=context,name=\"camel-1\"");
assertNull(context.hasEndpoint("seda:bar"));
// create a new endpoint
Object reply = mbeanServer.invoke(on, "createEndpoint", new Object[]{"seda:bar"}, new String[]{"java.lang.String"});
assertEquals(Boolean.TRUE, reply);
assertNotNull(context.hasEndpoint("seda:bar"));
ObjectName seda = ObjectName.getInstance("org.apache.camel:context=19-camel-1,type=endpoints,name=\"seda://bar\"");
boolean registered = mbeanServer.isRegistered(seda);
assertTrue("Should be registered " + seda, registered);
// remove it
Object num = mbeanServer.invoke(on, "removeEndpoints", new Object[]{"seda:*"}, new String[]{"java.lang.String"});
assertEquals(1, num);
assertNull(context.hasEndpoint("seda:bar"));
registered = mbeanServer.isRegistered(seda);
assertFalse("Should not be registered " + seda, registered);
// remove it again
num = mbeanServer.invoke(on, "removeEndpoints", new Object[]{"seda:*"}, new String[]{"java.lang.String"});
assertEquals(0, num);
assertNull(context.hasEndpoint("seda:bar"));
registered = mbeanServer.isRegistered(seda);
assertFalse("Should not be registered " + seda, registered);
}
public void testFindComponentsInClasspath() throws Exception {
// JMX tests dont work well on AIX CI servers (hangs them)
if (isPlatform("aix")) {
return;
}
MBeanServer mbeanServer = getMBeanServer();
ObjectName on = ObjectName.getInstance("org.apache.camel:context=19-camel-1,type=context,name=\"camel-1\"");
assertTrue("Should be registered", mbeanServer.isRegistered(on));
@SuppressWarnings("unchecked")
Map<String, Properties> info = (Map<String, Properties>) mbeanServer.invoke(on, "findComponents", null, null);
assertNotNull(info);
assertTrue(info.size() > 20);
Properties prop = info.get("seda");
assertNotNull(prop);
assertEquals("seda", prop.get("name"));
assertEquals("org.apache.camel", prop.get("groupId"));
assertEquals("camel-core", prop.get("artifactId"));
}
public void testManagedCamelContextCreateRouteStaticEndpointJson() throws Exception {
// JMX tests dont work well on AIX CI servers (hangs them)
if (isPlatform("aix")) {
return;
}
MBeanServer mbeanServer = getMBeanServer();
ObjectName on = ObjectName.getInstance("org.apache.camel:context=19-camel-1,type=context,name=\"camel-1\"");
// get the json
String json = (String) mbeanServer.invoke(on, "createRouteStaticEndpointJson", null, null);
assertNotNull(json);
assertEquals(7, StringHelper.countChar(json, '{'));
assertEquals(7, StringHelper.countChar(json, '}'));
assertTrue(json.contains("{ \"uri\": \"direct://start\" }"));
assertTrue(json.contains("{ \"uri\": \"direct://foo\" }"));
}
public void testManagedCamelContextExplainEndpointUri() throws Exception {
// JMX tests dont work well on AIX CI servers (hangs them)
if (isPlatform("aix")) {
return;
}
MBeanServer mbeanServer = getMBeanServer();
ObjectName on = ObjectName.getInstance("org.apache.camel:context=19-camel-1,type=context,name=\"camel-1\"");
// get the json
String json = (String) mbeanServer.invoke(on, "explainEndpointJson", new Object[]{"log:foo?groupDelay=2000&groupSize=5", false},
new String[]{"java.lang.String", "boolean"});
assertNotNull(json);
assertEquals(5, StringHelper.countChar(json, '{'));
assertEquals(5, StringHelper.countChar(json, '}'));
assertTrue(json.contains("\"groupDelay\": { \"kind\": \"parameter\", \"type\": \"integer\", \"javaType\": \"java.lang.Long\", \"deprecated\": \"false\", \"value\": \"2000\","
+ " \"description\": \"Set the initial delay for stats (in millis)\" },"));
assertTrue(json.contains("\"groupSize\": { \"kind\": \"parameter\", \"type\": \"integer\", \"javaType\": \"java.lang.Integer\", \"deprecated\": \"false\", \"value\": \"5\","
+ " \"description\": \"An integer that specifies a group size for throughput logging.\" }"));
assertTrue(json.contains("\"loggerName\": { \"kind\": \"path\", \"type\": \"string\", \"javaType\": \"java.lang.String\", \"deprecated\": \"false\","
+ " \"value\": \"foo\", \"description\": \"The logger name to use\" }"));
}
public void testManagedCamelContextExplainEip() throws Exception {
// JMX tests dont work well on AIX CI servers (hangs them)
if (isPlatform("aix")) {
return;
}
MBeanServer mbeanServer = getMBeanServer();
ObjectName on = ObjectName.getInstance("org.apache.camel:context=19-camel-1,type=context,name=\"camel-1\"");
// get the json
String json = (String) mbeanServer.invoke(on, "explainEipJson", new Object[]{"transform", false}, new String[]{"java.lang.String", "boolean"});
assertNotNull(json);
assertTrue(json.contains("\"label\": \"transformation\""));
assertTrue(json.contains("\"expression\": { \"kind\": \"element\", \"required\": \"true\", \"type\": \"object\""));
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start").to("mock:result");
from("direct:foo").transform(constant("Bye World"));
}
};
}
}
|
logzio/camel
|
camel-core/src/test/java/org/apache/camel/management/ManagedCamelContextTest.java
|
Java
|
apache-2.0
| 12,715 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search.aggregations.metrics.stats;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorFactories.Builder;
import org.elasticsearch.search.aggregations.AggregatorFactory;
import org.elasticsearch.search.aggregations.support.ValueType;
import org.elasticsearch.search.aggregations.support.ValuesSource;
import org.elasticsearch.search.aggregations.support.ValuesSource.Numeric;
import org.elasticsearch.search.aggregations.support.ValuesSourceAggregationBuilder;
import org.elasticsearch.search.aggregations.support.ValuesSourceConfig;
import org.elasticsearch.search.aggregations.support.ValuesSourceParserHelper;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.search.SearchContext;
import java.io.IOException;
import java.util.Map;
public class StatsAggregationBuilder extends ValuesSourceAggregationBuilder.LeafOnly<ValuesSource.Numeric, StatsAggregationBuilder> {
public static final String NAME = "stats";
private static final ObjectParser<StatsAggregationBuilder, Void> PARSER;
static {
PARSER = new ObjectParser<>(StatsAggregationBuilder.NAME);
ValuesSourceParserHelper.declareNumericFields(PARSER, true, true, false);
}
public static AggregationBuilder parse(String aggregationName, XContentParser parser) throws IOException {
return PARSER.parse(parser, new StatsAggregationBuilder(aggregationName), null);
}
public StatsAggregationBuilder(String name) {
super(name, ValuesSourceType.NUMERIC, ValueType.NUMERIC);
}
protected StatsAggregationBuilder(StatsAggregationBuilder clone,
Builder factoriesBuilder, Map<String, Object> metaData) {
super(clone, factoriesBuilder, metaData);
}
@Override
public AggregationBuilder shallowCopy(Builder factoriesBuilder, Map<String, Object> metaData) {
return new StatsAggregationBuilder(this, factoriesBuilder, metaData);
}
/**
* Read from a stream.
*/
public StatsAggregationBuilder(StreamInput in) throws IOException {
super(in, ValuesSourceType.NUMERIC, ValueType.NUMERIC);
}
@Override
protected void innerWriteTo(StreamOutput out) {
// Do nothing, no extra state to write to stream
}
@Override
protected StatsAggregatorFactory innerBuild(SearchContext context, ValuesSourceConfig<Numeric> config,
AggregatorFactory<?> parent, Builder subFactoriesBuilder) throws IOException {
return new StatsAggregatorFactory(name, config, context, parent, subFactoriesBuilder, metaData);
}
@Override
public XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException {
return builder;
}
@Override
protected int innerHashCode() {
return 0;
}
@Override
protected boolean innerEquals(Object obj) {
return true;
}
@Override
public String getType() {
return NAME;
}
}
|
jprante/elasticsearch-server
|
server/src/main/java/org/elasticsearch/search/aggregations/metrics/stats/StatsAggregationBuilder.java
|
Java
|
apache-2.0
| 4,154 |
package jenkins.plugins.hygieia;
public class DefaultHygieiaServiceStub extends DefaultHygieiaService {
// private HttpClientStub httpClientStub;
public DefaultHygieiaServiceStub(String host, String token, String name) {
super(host, token, name);
}
// @Override
// public HttpClientStub getHttpClient() {
// return httpClientStub;
// }
// public void setHttpClient(HttpClientStub httpClientStub) {
// this.httpClientStub = httpClientStub;
// }
}
|
tabladrum/hygieia-jenkins-plugin
|
src/test/java/jenkins/plugins/hygieia/DefaultHygieiaServiceStub.java
|
Java
|
apache-2.0
| 499 |
package cn.aezo.demo.rabbitmq.c05_model_topic;
import cn.aezo.demo.rabbitmq.util.RabbitmqU;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import java.io.IOException;
/**
* 测试 topic 类型消息模型
*
* 结果如下:
* consumer1收到消息:[aezo.order.vip] 这是 0 条消息
* consumer2收到消息:[smalle.vip] 这是 2 条消息
* consumer1收到消息:[aezo.user] 这是 1 条消息
* consumer1收到消息:[smalle.vip] 这是 2 条消息
* consumer1收到消息:[aezo.order.vip] 这是 3 条消息
* consumer1收到消息:[aezo.user] 这是 4 条消息
*
* @author smalle
* @date 2020-08-29 16:31
*/
public class Consumer {
private static final String EXCHANGE_NAME = "topic_logs";
public static void main(String[] args) throws IOException {
consumer1();
consumer2();
}
public static void consumer1() throws IOException {
Connection connection = RabbitmqU.getConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME, "topic");
// 获取一个临时队列。管理后台的Queues-Features会增加"AD"(autoDelete)和"Excl"(exclusive)标识
String queueName = channel.queueDeclare().getQueue();
// **将临时队列和交换机绑定,并订阅某些类型的消息**
channel.queueBind(queueName, EXCHANGE_NAME, "aezo.#"); // *匹配一个单词,#匹配多个单词
channel.queueBind(queueName, EXCHANGE_NAME, "*.vip");
channel.basicConsume(queueName, true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("consumer1收到消息:" + new String(body, "UTF-8"));
}
});
}
public static void consumer2() throws IOException {
Connection connection = RabbitmqU.getConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME, "topic");
String queueName = channel.queueDeclare().getQueue();
// * 表示一个单词。此时无法匹配 aezo.order.vip 和 aezo.vip.hello 等
channel.queueBind(queueName, EXCHANGE_NAME, "*.vip");
channel.basicConsume(queueName, true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("consumer2收到消息:" + new String(body, "UTF-8"));
}
});
}
}
|
oldinaction/smjava
|
rabbitmq/src/main/java/cn/aezo/demo/rabbitmq/c05_model_topic/Consumer.java
|
Java
|
apache-2.0
| 2,828 |
/*
* Copyright 2016 The Simple File Server 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.sfs.integration.java;
import io.vertx.core.Context;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpClient;
import io.vertx.core.logging.Logger;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.Rule;
import org.junit.runner.RunWith;
import org.sfs.RunBootedTestOnContextRx;
import org.sfs.Server;
import org.sfs.TestSubscriber;
import org.sfs.VertxContext;
import rx.Observable;
import java.nio.file.Path;
import java.util.concurrent.Callable;
import static io.vertx.core.logging.LoggerFactory.getLogger;
@RunWith(VertxUnitRunner.class)
public class BaseTestVerticle {
private static final Logger LOGGER = getLogger(BaseTestVerticle.class);
@Rule
public RunBootedTestOnContextRx runTestOnContext = new RunBootedTestOnContextRx();
public VertxContext<Server> vertxContext() {
return runTestOnContext.getVertxContext();
}
public HttpClient httpClient() {
return runTestOnContext.getHttpClient();
}
public Vertx vertx() {
return vertxContext().vertx();
}
public Path tmpDir() {
return runTestOnContext.getTmpDir();
}
public void runOnServerContext(TestContext testContext, RunnableWithException callable) {
Async async = testContext.async();
Context c = vertxContext().verticle().getContext();
c.runOnContext(event -> {
try {
callable.run();
async.complete();
} catch (Exception e) {
testContext.fail(e);
}
});
}
public void runOnServerContext(TestContext testContext, Callable<Observable<Void>> callable) {
Async async = testContext.async();
Context c = vertxContext().verticle().getContext();
c.runOnContext(event -> {
try {
callable.call().subscribe(new TestSubscriber(testContext, async));
} catch (Exception e) {
testContext.fail(e);
}
});
}
public interface RunnableWithException {
void run() throws Exception;
}
}
|
pitchpoint-solutions/sfs
|
sfs-server/src/test/java/org/sfs/integration/java/BaseTestVerticle.java
|
Java
|
apache-2.0
| 2,779 |
/*
* Core Utils - Common Utilities.
* Copyright 2015-2016 GRyCAP (Universitat Politecnica de Valencia)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This product combines work with different licenses. See the "NOTICE" text
* file for details on the various modules and licenses.
*
* The "NOTICE" text file is part of the distribution. Any derivative works
* that you distribute must include a readable copy of the "NOTICE" text file.
*/
package es.upv.grycap.coreutils.common;
import com.google.common.collect.Range;
/**
* Hard-coded configuration limits.
* @author Erik Torres
* @since 0.2.0
*/
public interface CoreutilsLimits {
public static final int NUM_AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors();
public static final Range<Long> TRY_LOCK_TIMEOUT_RANGE = Range.closed(1l, 2000l);
public static final Range<Integer> MAX_POOL_SIZE_RANGE = Range.closed(Math.min(2, NUM_AVAILABLE_PROCESSORS), Math.max(128, NUM_AVAILABLE_PROCESSORS));
public static final Range<Long> KEEP_ALIVE_TIME_RANGE = Range.closed(60000l, 3600000l);
public static final Range<Long> WAIT_TERMINATION_TIMEOUT_RANGE = Range.closed(1000l, 60000l);
}
|
grycap/coreutils
|
coreutils-common/src/main/java/es/upv/grycap/coreutils/common/CoreutilsLimits.java
|
Java
|
apache-2.0
| 1,687 |
/*
* Copyright (c) 2016 Ni YueMing<niyueming@163.com>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*
*/
package net.nym.napply.library.cookie.store;
/**
* Created by zhy on 16/3/10.
*/
public interface HasCookieStore
{
CookieStore getCookieStore();
}
|
niyueming/NApply
|
library/src/main/java/net/nym/napply/library/cookie/store/HasCookieStore.java
|
Java
|
apache-2.0
| 754 |
/*
* Copyright 2012-2017 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.kinesisfirehose.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.kinesisfirehose.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* ProcessingConfiguration JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ProcessingConfigurationJsonUnmarshaller implements Unmarshaller<ProcessingConfiguration, JsonUnmarshallerContext> {
public ProcessingConfiguration unmarshall(JsonUnmarshallerContext context) throws Exception {
ProcessingConfiguration processingConfiguration = new ProcessingConfiguration();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("Enabled", targetDepth)) {
context.nextToken();
processingConfiguration.setEnabled(context.getUnmarshaller(Boolean.class).unmarshall(context));
}
if (context.testExpression("Processors", targetDepth)) {
context.nextToken();
processingConfiguration.setProcessors(new ListUnmarshaller<Processor>(ProcessorJsonUnmarshaller.getInstance()).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return processingConfiguration;
}
private static ProcessingConfigurationJsonUnmarshaller instance;
public static ProcessingConfigurationJsonUnmarshaller getInstance() {
if (instance == null)
instance = new ProcessingConfigurationJsonUnmarshaller();
return instance;
}
}
|
dagnir/aws-sdk-java
|
aws-java-sdk-kinesis/src/main/java/com/amazonaws/services/kinesisfirehose/model/transform/ProcessingConfigurationJsonUnmarshaller.java
|
Java
|
apache-2.0
| 3,132 |
/*
* Copyright 2021 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.
*/
package com.google.cloud.compute.v1.stub;
import com.google.api.core.BetaApi;
import com.google.api.gax.httpjson.HttpJsonCallSettings;
import com.google.api.gax.httpjson.HttpJsonCallableFactory;
import com.google.api.gax.httpjson.HttpJsonOperationSnapshotCallable;
import com.google.api.gax.httpjson.HttpJsonStubCallableFactory;
import com.google.api.gax.rpc.BatchingCallSettings;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.OperationCallSettings;
import com.google.api.gax.rpc.OperationCallable;
import com.google.api.gax.rpc.PagedCallSettings;
import com.google.api.gax.rpc.ServerStreamingCallSettings;
import com.google.api.gax.rpc.ServerStreamingCallable;
import com.google.api.gax.rpc.UnaryCallSettings;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.compute.v1.Operation;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* REST callable factory implementation for the Routes service API.
*
* <p>This class is for advanced usage.
*/
@Generated("by gapic-generator-java")
@BetaApi
public class HttpJsonRoutesCallableFactory
implements HttpJsonStubCallableFactory<Operation, GlobalOperationsStub> {
@Override
public <RequestT, ResponseT> UnaryCallable<RequestT, ResponseT> createUnaryCallable(
HttpJsonCallSettings<RequestT, ResponseT> httpJsonCallSettings,
UnaryCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return HttpJsonCallableFactory.createUnaryCallable(
httpJsonCallSettings, callSettings, clientContext);
}
@Override
public <RequestT, ResponseT, PagedListResponseT>
UnaryCallable<RequestT, PagedListResponseT> createPagedCallable(
HttpJsonCallSettings<RequestT, ResponseT> httpJsonCallSettings,
PagedCallSettings<RequestT, ResponseT, PagedListResponseT> callSettings,
ClientContext clientContext) {
return HttpJsonCallableFactory.createPagedCallable(
httpJsonCallSettings, callSettings, clientContext);
}
@Override
public <RequestT, ResponseT> UnaryCallable<RequestT, ResponseT> createBatchingCallable(
HttpJsonCallSettings<RequestT, ResponseT> httpJsonCallSettings,
BatchingCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return HttpJsonCallableFactory.createBatchingCallable(
httpJsonCallSettings, callSettings, clientContext);
}
@BetaApi(
"The surface for long-running operations is not stable yet and may change in the future.")
@Override
public <RequestT, ResponseT, MetadataT>
OperationCallable<RequestT, ResponseT, MetadataT> createOperationCallable(
HttpJsonCallSettings<RequestT, Operation> httpJsonCallSettings,
OperationCallSettings<RequestT, ResponseT, MetadataT> callSettings,
ClientContext clientContext,
GlobalOperationsStub operationsStub) {
UnaryCallable<RequestT, Operation> innerCallable =
HttpJsonCallableFactory.createBaseUnaryCallable(
httpJsonCallSettings, callSettings.getInitialCallSettings(), clientContext);
HttpJsonOperationSnapshotCallable<RequestT, Operation> initialCallable =
new HttpJsonOperationSnapshotCallable<RequestT, Operation>(
innerCallable,
httpJsonCallSettings.getMethodDescriptor().getOperationSnapshotFactory());
return HttpJsonCallableFactory.createOperationCallable(
callSettings, clientContext, operationsStub.longRunningClient(), initialCallable);
}
@Override
public <RequestT, ResponseT>
ServerStreamingCallable<RequestT, ResponseT> createServerStreamingCallable(
HttpJsonCallSettings<RequestT, ResponseT> httpJsonCallSettings,
ServerStreamingCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return HttpJsonCallableFactory.createServerStreamingCallable(
httpJsonCallSettings, callSettings, clientContext);
}
}
|
googleapis/java-compute
|
google-cloud-compute/src/main/java/com/google/cloud/compute/v1/stub/HttpJsonRoutesCallableFactory.java
|
Java
|
apache-2.0
| 4,575 |
/*
Copyright 2013 Semantic Discovery, Inc. (www.semanticdiscovery.com)
This file is part of the Semantic Discovery Toolkit.
The Semantic Discovery Toolkit is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The Semantic Discovery Toolkit is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with The Semantic Discovery Toolkit. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sd.token;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.sd.nlp.NormalizedString;
/**
* An nlp.NormalizedString implementation based on this package's tokenization.
* <p>
* @author Spence Koehler
*/
public class TokenizerNormalizedString implements NormalizedString {
private TokenizerBasedNormalizer normalizer;
private StandardTokenizer tokenizer;
private boolean lowerCaseFlag;
private boolean computed;
private Normalization _normalization;
/**
* Construct with default case-sensitive settings.
*/
public TokenizerNormalizedString(String string) {
this(TokenizerBasedNormalizer.CASE_SENSITIVE_INSTANCE, new StandardTokenizer(string, TokenizerBasedNormalizer.DEFAULT_TOKENIZER_OPTIONS), false);
}
/**
* Construct with the given settings.
*/
public TokenizerNormalizedString(TokenizerBasedNormalizer normalizer, StandardTokenizer tokenizer, boolean lowerCaseFlag) {
this.normalizer = normalizer;
this.tokenizer = tokenizer;
this.lowerCaseFlag = lowerCaseFlag;
this.computed = false;
reset();
}
public StandardTokenizer getTokenizer() {
return tokenizer;
}
public void setLowerCaseFlag(boolean lowerCaseFlag) {
if (lowerCaseFlag != this.lowerCaseFlag) {
this.lowerCaseFlag = lowerCaseFlag;
reset();
}
}
public boolean getLowerCaseFlag() {
return lowerCaseFlag;
}
/**
* Set a flag indicating whether to split on camel-casing.
*/
public void setSplitOnCamelCase(boolean splitOnCamelCase) {
final Break curBreak = tokenizer.getOptions().getLowerUpperBreak();
final Break nextBreak = splitOnCamelCase ? Break.ZERO_WIDTH_SOFT_BREAK : Break.NO_BREAK;
if (curBreak != nextBreak) {
final StandardTokenizerOptions newOptions = new StandardTokenizerOptions(tokenizer.getOptions());
newOptions.setLowerUpperBreak(nextBreak);
this.tokenizer = new StandardTokenizer(tokenizer.getText(), newOptions);
reset();
}
}
private final void reset() {
this.computed = false;
}
/**
* Get the flag indicating whether to split on camel-casing.
*/
public boolean getSplitOnCamelCase() {
return tokenizer.getOptions().getLowerUpperBreak() != Break.NO_BREAK;
}
/**
* Get the length of the normalized string.
*/
public int getNormalizedLength() {
return getNormalized().length();
}
/**
* Get the normalized string.
* <p>
* Note that the normalized string may apply to only a portion of the full
* original string.
*/
public String getNormalized() {
return getNormalization().getNormalized();
}
public String toString() {
return getNormalized();
}
/**
* Get the normalized string from the start (inclusive) to end (exclusive).
* <p>
* Note that the normalized string may apply to only a portion of the full
* original string.
*/
public String getNormalized(int startPos, int endPos) {
return getNormalized().substring(startPos, endPos);
}
/**
* Get the original string that applies to the normalized string.
*/
public String getOriginal() {
return tokenizer.getText();
}
/**
* Get the original string that applies to the normalized string from the
* given index for the given number of normalized characters.
*/
public String getOriginal(int normalizedStartIndex, int normalizedLength) {
final int origStartIdx = getOriginalIndex(normalizedStartIndex);
final int origEndIdx = getOriginalIndex(normalizedStartIndex + normalizedLength);
return getOriginal().substring(origStartIdx, origEndIdx);
}
/**
* Get the index in the original string corresponding to the normalized index.
*/
public int getOriginalIndex(int normalizedIndex) {
final Integer result = getNormalization().getOriginalIndex(normalizedIndex);
return result == null ? -1 : result;
}
/**
* Get a new normalized string for the portion of this normalized string
* preceding the normalized start index (exclusive). Remove extra whitespace
* at the end of the returned string. Ensure that the returned string ends
* on an end token boundary.
*
* @return the preceding normalized string or null if empty (after skipping white).
*/
public NormalizedString getPreceding(int normalizedStartIndex) {
return getPreceding(normalizedStartIndex, true);
}
/**
* Get a new normalized string for the portion of this normalized string
* preceding the normalized start index (exclusive). Remove extra whitespace
* at the end of the returned string.
*
* @param normalizedStartIndex a token start position in the normalized string beyond the result
* @param checkEndBreak when true, skip back over non breaking chars to ensure result ends at a break.
*
* @return the preceding normalized string or null if empty (after skipping white).
*/
public NormalizedString getPreceding(int normalizedStartIndex, boolean checkEndBreak) {
NormalizedString result = null;
final int origIdx = getOriginalIndex(normalizedStartIndex);
if (origIdx >= 0) {
final Token token = tokenizer.getToken(origIdx);
if (token != null) {
final String priorText =
checkEndBreak ? tokenizer.getPriorText(token) :
tokenizer.getText().substring(0, token.getStartIndex()).trim();
if (!"".equals(priorText)) {
result = normalizer.normalize(priorText);
}
}
}
return result;
}
/**
* Find the (normalized) index of the nth token preceding the normalizedPos.
* <p>
* If normalizedPos is -1, start from the end of the string.
* If the beginning of the string is fewer than numTokens prior to normalizedPos,
* return the beginning of the string.
*/
public int getPrecedingIndex(int normalizedPos, int numTokens) {
int result = normalizedPos < 0 ? getNormalization().getNormalizedLength() : normalizedPos;
// skip back to the numTokens-th start break.
int numStarts = 0;
for (; result > 0 && numStarts < numTokens; result = findPrecedingTokenStart(result)) {
++numStarts;
}
return result;
}
/**
* Find the start of the token before the normalizedPos.
* <p>
* If normalizedPos is at a token start, the prior token (or -1 if there is
* no prior token) will be returned; otherwise, the start of the token of
* which normalizedPos is a part will be returned.
*/
public int findPrecedingTokenStart(int normalizedPos) {
final Integer priorStart = getNormalization().getBreaks().lower(normalizedPos);
return priorStart == null ? -1 : priorStart;
}
/**
* Get a new normalized string for the portion of this normalized string
* following the normalized start index (inclusive). Remove extra whitespace
* at the beginning of the returned string.
*
* @return the following normalized string or null if empty (after skipping white).
*/
public NormalizedString getRemaining(int normalizedStartIndex) {
NormalizedString result = null;
final int origIdx = getOriginalIndex(normalizedStartIndex);
if (origIdx >= 0) {
final String origText = tokenizer.getText();
final int origLen = origText.length();
if (origIdx < origLen) {
final String remainingText = origText.substring(origIdx).trim();
if (!"".equals(remainingText)) {
result = normalizer.normalize(remainingText);
}
}
}
return result;
}
/**
* Build a normalized string from this using the given normalized index range.
*/
public NormalizedString buildNormalizedString(int normalizedStartIndex, int normalizedEndIndex) {
NormalizedString result = null;
final int origStartIdx = getOriginalIndex(normalizedStartIndex);
if (origStartIdx >= 0) {
final int origEndIdx = getOriginalIndex(normalizedEndIndex);
if (origEndIdx > origStartIdx) {
final String origText = tokenizer.getText();
final int origLen = origText.length();
if (origStartIdx < origLen) {
final String string = origText.substring(origStartIdx, Math.min(origEndIdx, origLen));
result = normalizer.normalize(string);
}
}
}
return result;
}
/**
* Lowercase the normalized form in this instance.
*
* @return this instance.
*/
public NormalizedString toLowerCase() {
getNormalization().toLowerCase();
return this;
}
/**
* Get the normalized string's chars.
*/
public char[] getNormalizedChars() {
return getNormalization().getNormalizedChars();
}
/**
* Get the normalized char at the given (normalized) index.
* <p>
* NOTE: Bounds checking is left up to the caller.
*/
public char getNormalizedChar(int index) {
return getNormalization().getNormalizedChars()[index];
}
/**
* Get the original code point corresponding to the normalized char at the
* (normalized) index.
* <p>
* NOTE: Bounds checking is left up to the caller.
*/
public int getOriginalCodePoint(int nIndex) {
int result = 0;
final int origIdx = getOriginalIndex(nIndex);
if (origIdx >= 0) {
final String origText = tokenizer.getText();
final int origLen = origText.length();
if (origIdx < origLen) {
result = origText.codePointAt(origIdx);
}
}
return result;
}
/**
* Determine whether the original character corresponding to the normalized
* index is a letter or digit.
*/
public boolean isLetterOrDigit(int nIndex) {
return Character.isLetterOrDigit(getOriginalCodePoint(nIndex));
}
/**
* Get the ORIGINAL index of the first symbol (non-letter, digit, or white
* character) prior to the NORMALIZED index in the full original string.
*
* @return -1 if no symbol is found or the index of the found symbol in the
* original input string.
*/
public int findPreviousSymbolIndex(int nIndex) {
int result = -1;
final int origIdx = getOriginalIndex(nIndex);
if (origIdx >= 0) {
final String origText = tokenizer.getText();
final int origLen = origText.length();
for (result = Math.min(origIdx, origLen) - 1; result >= 0; --result) {
final int cp = origText.codePointAt(result);
if (cp != ' ' && !Character.isLetterOrDigit(cp)) break;
}
}
return result;
}
/**
* Determine whether the normalized string has a digit between the normalized
* start (inclusive) and end (exclusive).
*/
public boolean hasDigit(int nStartIndex, int nEndIndex) {
boolean result = false;
final char[] nchars = getNormalization().getNormalizedChars();
nEndIndex = Math.min(nEndIndex, nchars.length);
for (int idx = Math.max(nStartIndex, 0); idx < nEndIndex; ++idx) {
final char c = nchars[idx];
if (c <= '9' && c >= '0') {
result = true;
break;
}
}
return result;
}
/**
* Count the number of normalized words in the given range.
*/
public int numWords(int nStartIndex, int nEndIndex) {
int result = 0;
final Normalization normalization = getNormalization();
final TreeSet<Integer> breaks = normalization.getBreaks();
final int nLen = normalization.getNormalizedLength();
nEndIndex = Math.min(nEndIndex, nLen);
for (int idx = Math.max(nStartIndex, 0); idx < nEndIndex && idx >= 0; idx = breaks.higher(idx)) {
if (idx == nEndIndex - 1) break; // nEndIdex as at the beginning of a word -- doesn't count
++result;
}
return result;
}
/**
* Determine whether there is a break before the normalized startIndex.
*/
public boolean isStartBreak(int startIndex) {
return getNormalization().isBreak(startIndex - 1);
}
/**
* Determine whether there is a break after the normalized endIndex.
*/
public boolean isEndBreak(int endIndex) {
return getNormalization().isBreak(endIndex + 1);
}
/**
* Get (first) the normalized index that best corresponds to the original index.
*/
public int getNormalizedIndex(int originalIndex) {
return getNormalization().getNormalizedIndex(originalIndex);
}
/**
* Split into normalized token strings.
*/
public String[] split() {
return getNormalization().getNormalized().split("\\s+");
}
/**
* Split into normalized token strings, removing stopwords.
*/
public String[] split(Set<String> stopwords) {
final List<String> result = new ArrayList<String>();
for (NormalizedToken token = getToken(0, true); token != null; token = token.getNext(true)) {
final String ntoken = token.getNormalized();
if (stopwords == null || !stopwords.contains(ntoken)) {
result.add(ntoken);
}
}
return result.toArray(new String[result.size()]);
}
/**
* Split this normalized string into tokens.
*/
public NormalizedToken[] tokenize() {
final List<NormalizedToken> result = new ArrayList<NormalizedToken>();
for (NormalizedToken token = getToken(0, true); token != null; token = token.getNext(true)) {
result.add(token);
}
return result.toArray(new NormalizedToken[result.size()]);
}
/**
* Get the token starting from the start position, optionally skipping to a
* start break first.
*
* @return the token or null if there are no tokens to get.
*/
public NormalizedToken getToken(int startPos, boolean skipToBreak) {
NormalizedToken result = null;
startPos = getTokenStart(startPos, skipToBreak);
if (startPos < getNormalization().getNormalizedLength()) {
final int endPos = getTokenEnd(startPos);
result = new NormalizedToken(this, startPos, endPos);
}
return result;
}
/**
* Get the token after the given token, optionally skipping to a start
* break first.
*/
public NormalizedToken getNextToken(NormalizedToken curToken, boolean skipToBreak) {
NormalizedToken result = null;
if (curToken != null) {
final Normalization normalization = getNormalization();
final TreeSet<Integer> breaks = normalization.getBreaks();
final int nLen = normalization.getNormalizedLength();
int curEndPos = curToken.getEndPos();
if (skipToBreak && !normalization.isBreak(curEndPos)) {
final Integer nextBreak = breaks.higher(curEndPos);
curEndPos = (nextBreak == null) ? nLen : nextBreak;
}
if (curEndPos < nLen) {
final int startPos = getTokenStart(curEndPos + 1, true);
if (startPos < nLen) {
final int nextEndPos = getTokenEnd(startPos);
result = new NormalizedToken(this, startPos, nextEndPos);
}
}
}
return result;
}
/**
* Get the normalized token start pos at or after (normalized) startPos
* after optionally skipping to a token start position (if not already
* at one.)
*/
private final int getTokenStart(int startPos, boolean skipToBreak) {
final Normalization normalization = getNormalization();
final TreeSet<Integer> breaks = normalization.getBreaks();
final int nLen = normalization.getNormalizedLength();
if (skipToBreak && !isStartBreak(startPos)) {
final Integer nextBreak = breaks.ceiling(startPos);
startPos = nextBreak == null ? nLen : nextBreak + 1;
}
return startPos;
}
/**
* Get the normalized index just after the token starting at (normalized) startPos.
*/
private final int getTokenEnd(int startPos) {
final Normalization normalization = getNormalization();
final TreeSet<Integer> breaks = normalization.getBreaks();
final int nLen = normalization.getNormalizedLength();
final Integer endPos = breaks.higher(startPos);
return endPos == null ? nLen : endPos;
}
protected final Normalization getNormalization() {
if (!computed) {
computeNormalization();
}
return _normalization;
}
private final void computeNormalization() {
this._normalization = buildNewNormalization(tokenizer, lowerCaseFlag);
for (Token token = tokenizer.getToken(0); token != null; token = token.getNextToken()) {
_normalization.updateWithToken(token);
}
this.computed = true;
}
protected Normalization buildNewNormalization(StandardTokenizer tokenizer, boolean lowerCaseFlag) {
return new Normalization(tokenizer, lowerCaseFlag);
}
public static class Normalization {
private StandardTokenizer tokenizer;
private boolean lowerCaseFlag;
private StringBuilder normalized;
private Map<Integer, Integer> norm2orig;
private TreeSet<Integer> breaks;
private char[] _nchars;
public Normalization(StandardTokenizer tokenizer, boolean lowerCaseFlag) {
this.tokenizer = tokenizer;
this.lowerCaseFlag = lowerCaseFlag;
this.normalized = new StringBuilder();
this.norm2orig = new HashMap<Integer, Integer>();
this.breaks = new TreeSet<Integer>();
this._nchars = null;
}
public final StandardTokenizer getTokenizer() {
return tokenizer;
}
public final boolean getLowerCaseFlag() {
return lowerCaseFlag;
}
/** Get original input. */
public final String getInput() {
return tokenizer.getText();
}
/** Get the normalized string. */
public final String getNormalized() {
return normalized.toString();
}
public final char[] getNormalizedChars() {
if (_nchars == null) {
_nchars = normalized.toString().toCharArray();
}
return _nchars;
}
public final int getNormalizedLength() {
return normalized.length();
}
public final int getOriginalIndex(int normalizedIndex) {
final Integer result =
(normalizedIndex == normalized.length()) ?
tokenizer.getText().length() :
norm2orig.get(normalizedIndex);
return result == null ? -1 : result;
}
public final int getNormalizedIndex(int originalIndex) {
int result = -1;
for (Map.Entry<Integer, Integer> entry : norm2orig.entrySet()) {
final int normIdx = entry.getKey();
final int origIdx = entry.getValue();
if (originalIndex == origIdx) {
// maps to normalized char
result = normIdx;
break;
}
else if (originalIndex > origIdx) {
// maps back to normalized white (break)
result = normIdx - 1;
break;
}
}
return result;
}
/**
* Determine whether there is a break at the given index.
*/
public final boolean isBreak(int normalizedIndex) {
return !norm2orig.containsKey(normalizedIndex);
}
/** Get the normalized break positions (not including string start or end). */
public final TreeSet<Integer> getBreaks() {
return breaks;
}
/** Lowercase this instance's normalized chars. */
public final void toLowerCase() {
final String newNorm = normalized.toString().toLowerCase();
this.normalized.setLength(0);
this.normalized.append(newNorm);
this._nchars = null;
}
/**
* Build the next normalized chars from the given token using
* the "appendX" method calls.
*/
protected void updateWithToken(Token token) {
final String tokenText = lowerCaseFlag ? token.getText().toLowerCase() : token.getText();
appendNormalizedText(token.getStartIndex(), tokenText, true);
}
/**
* Append each normalized character originally starting at startIdx.
*/
protected final void appendNormalizedText(int startIdx, String normalizedTokenText) {
appendNormalizedText(startIdx, normalizedTokenText, true);
}
/**
* Append each normalized character originally starting at startIdx.
*/
protected final void appendNormalizedText(int startIdx, String normalizedTokenText, boolean addWhite) {
final int len = normalizedTokenText.length();
for (int i = 0; i < len; ++i) {
final char c = normalizedTokenText.charAt(i);
appendNormalizedChar(startIdx++, c, addWhite && i == 0);
}
}
/**
* Append the normalized character originally starting at origIdx.
*/
protected final void appendNormalizedChar(int origIdx, char c, boolean addWhite) {
int normIdx = normalized.length();
if (normIdx > 0 && addWhite) {
normalized.append(' ');
breaks.add(normIdx++);
}
norm2orig.put(normIdx, origIdx);
normalized.append(c);
_nchars = null;
}
/**
* Append the normalized characters all expanding from the originalIdx.
*/
protected final void appendExpandedText(int origIdx, String chars) {
appendExpandedText(origIdx, chars, true);
}
/**
* Append the normalized characters all expanding from the originalIdx.
*/
protected final void appendExpandedText(int origIdx, String chars, boolean addWhite) {
final int len = chars.length();
for (int i = 0; i < chars.length(); ++i) {
final char c = chars.charAt(i);
appendNormalizedChar(origIdx, c, addWhite && i == 0);
}
}
}
}
|
KoehlerSB747/sd-tools
|
src/main/java/org/sd/token/TokenizerNormalizedString.java
|
Java
|
apache-2.0
| 22,049 |
package lodVader.spring.REST.models.degree;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import org.junit.Test;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import lodVader.mongodb.DBSuperClass2;
import lodVader.mongodb.collections.DatasetDB;
import lodVader.mongodb.collections.DatasetLinksetDB;
import lodVader.mongodb.collections.LinksetDB;
import lodVader.mongodb.collections.ResourceDB;
public class IndegreeDatasetModel {
public StringBuilder result = new StringBuilder();
public boolean isVocabulary = true;
public boolean isDeadLinks = false;
/**
* MapReduce functions for indegree linksets
*/
public String mapindegreeWithVocabs;
public String mapindegreeNoVocabs;
public String reduceinDegree;
class Result implements Comparator<Result>, Comparable<Result> {
int targetDataset;
int links = 0;
HashSet<Integer> sourceDatasetList = new HashSet<>();
@Override
public int compare(Result o1, Result o2) {
return o1.links - o2.links;
}
@Override
public int compareTo(Result o) {
return this.sourceDatasetList.size() - o.sourceDatasetList.size();
}
}
HashMap<Integer, Result> tmpResults = new HashMap<Integer, Result>();
ArrayList<Result> finalList = new ArrayList<Result>();
@Test
public void calc() {
/**
* MapReduce to find indegree with vocabularies
*/
result.append("===============================================================\n");
result.append("Comparing with vocabularies\n");
result.append("===============================================================\n\n");
DBCollection collection = DBSuperClass2.getDBInstance().getCollection(DatasetLinksetDB.COLLECTION_NAME);
DBCursor instances;
if(!isDeadLinks){
BasicDBList and = new BasicDBList();
// and.add(new BasicDBObject(DatasetLinksetDB.LINKS, new BasicDBObject("$gt", 0)));
// and.add(new BasicDBObject(DatasetLinksetDB.DATASET_SOURCE, new BasicDBObject("$ne", DatasetLinksetDB.DATASET_TARGET)));
instances = collection.find( new BasicDBObject(DatasetLinksetDB.LINKS, new BasicDBObject("$gt", 0)));
}
else{
BasicDBList and = new BasicDBList();
// and.add(new BasicDBObject(DatasetLinksetDB.DEAD_LINKS, new BasicDBObject("$gt", 0)));
// and.add(new BasicDBObject(DatasetLinksetDB.DATASET_SOURCE, new BasicDBObject("$ne", DatasetLinksetDB.DATASET_TARGET)));
// instances = collection.find( new BasicDBObject("$and", and));
instances = collection.find(new BasicDBObject(DatasetLinksetDB.DEAD_LINKS, new BasicDBObject("$gt", 0)));
}
for (DBObject object : instances) {
DatasetLinksetDB linkset = new DatasetLinksetDB(object);
if (linkset.getDistributionTargetIsVocabulary() == isVocabulary) {
Result result = tmpResults.get(linkset.getDatasetTarget());
if (result == null) {
result = new Result();
}
if (isDeadLinks)
result.links = result.links + linkset.getDeadLinks();
else
result.links = result.links + linkset.getLinks();
result.sourceDatasetList.add(linkset.getDatasetSource());
result.targetDataset = linkset.getDatasetTarget();
tmpResults.put(linkset.getDatasetTarget(), result);
}
}
for (Integer r : tmpResults.keySet()) {
finalList.add(tmpResults.get(r));
}
result.append("\n===== Sorted by links=======");
Collections.sort(finalList, new Result());
printTableindegree();
result.append("\n===== Sorted by number of datasets=======");
Collections.sort(finalList);
printTableindegree();
result.append("\n\n\n\n===============================================================\n");
result.append("Comparing without vocabularies\n");
result.append("===============================================================\n\n");
tmpResults = new HashMap<Integer, Result>();
finalList = new ArrayList<Result>();
isVocabulary = false;
for (DBObject object : instances) {
DatasetLinksetDB linkset = new DatasetLinksetDB(object);
if (linkset.getDistributionTargetIsVocabulary() == isVocabulary) {
Result result = tmpResults.get(linkset.getDatasetTarget());
if (result == null) {
result = new Result();
}
if (isDeadLinks)
result.links = result.links + linkset.getDeadLinks();
else
result.links = result.links + linkset.getLinks();
result.sourceDatasetList.add(linkset.getDatasetSource());
result.targetDataset = linkset.getDatasetTarget();
tmpResults.put(linkset.getDatasetTarget(), result);
}
}
for (Integer r : tmpResults.keySet()) {
finalList.add(tmpResults.get(r));
}
result.append("\n===== Sorted by links=======");
Collections.sort(finalList, new Result());
printTableindegree();
result.append("\n===== Sorted by number of datasets=======");
Collections.sort(finalList);
printTableindegree();
}
private void printTableindegree() {
result.append("\n\nName\t indegree \t Links \n");
DatasetDB tmpDataset;
for (Result r : finalList) {
tmpDataset = new DatasetDB(r.targetDataset);
result.append(tmpDataset.getTitle());
result.append("\t" + r.sourceDatasetList.size());
result.append("\t" + r.links);
result.append("\n");
}
result.append("\n\n\n");
}
}
|
AKSW/LODVader
|
src/main/java/lodVader/spring/REST/models/degree/IndegreeDatasetModel.java
|
Java
|
apache-2.0
| 5,358 |
package no.api.regurgitator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.dropwizard.Configuration;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
@JsonIgnoreProperties(ignoreUnknown = true)
public class RegurgitatorConfiguration extends Configuration {
@Valid
@NotNull
@JsonProperty
private int proxyPort;
@Valid
@JsonProperty
private String archivedFolder;
@Valid
@NotNull
@JsonProperty
private Boolean recordOnStart;
@Valid
@NotNull
@JsonProperty
private String storageManager;
public int getProxyPort() {
return proxyPort;
}
public String getStorageManager() {
return storageManager;
}
public Boolean getRecordOnStart() {
return recordOnStart;
}
public String getArchivedFolder() {
return archivedFolder;
}
}
|
amedia/regurgitator
|
regurgitator-service/src/main/java/no/api/regurgitator/RegurgitatorConfiguration.java
|
Java
|
apache-2.0
| 958 |
package org.minimalj.example.petclinic.frontend;
import org.minimalj.backend.Backend;
import org.minimalj.example.petclinic.model.Vet;
import org.minimalj.frontend.Frontend;
import org.minimalj.frontend.editor.Editor.NewObjectEditor;
import org.minimalj.frontend.form.Form;
public class AddVetEditor extends NewObjectEditor<Vet> {
@Override
protected Form<Vet> createForm() {
Form<Vet> form = new Form<>();
form.line(Vet.$.person.firstName);
form.line(Vet.$.person.lastName);
form.line(Vet.$.specialties);
return form;
}
@Override
protected Vet save(Vet owner) {
return Backend.save(owner);
}
@Override
protected void finished(Vet newVet) {
Frontend.show(new VetTablePage());
}
}
|
BrunoEberhard/minimal-j
|
example/007_PetClinic/src/org/minimalj/example/petclinic/frontend/AddVetEditor.java
|
Java
|
apache-2.0
| 710 |
/*
* Copyright 2019 Frederic Thevenet
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.binjr.common.javafx.controls;
import javafx.scene.Node;
import javafx.scene.SnapshotParameters;
import javafx.scene.image.WritableImage;
import javafx.scene.transform.Transform;
import javafx.stage.Screen;
public final class SnapshotUtils {
public static WritableImage outputScaleAwareSnapshot(Node node) {
return scaledSnapshot(node, 0.0,0.0);
}
public static WritableImage scaledSnapshot(Node node, double scaleX, double scaleY) {
SnapshotParameters spa = new SnapshotParameters();
spa.setTransform(Transform.scale(
scaleX == 0.0 ? Screen.getPrimary().getOutputScaleX() : scaleX,
scaleY == 0.0 ? Screen.getPrimary().getOutputScaleY() : scaleY));
return node.snapshot(spa, null);
}
}
|
fthevenet/binjr
|
binjr-core/src/main/java/eu/binjr/common/javafx/controls/SnapshotUtils.java
|
Java
|
apache-2.0
| 1,413 |
/**
* Copyright (C) 2012 Ness Computing, 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.nesscomputing.jersey.types;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Objects;
import java.util.regex.Pattern;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
/**
* Simple Jersey date parameter class. Accepts either milliseconds since epoch UTC or ISO formatted dates.
* Will convert everything into UTC regardless of input timezone.
*/
public class DateParam
{
private static final Pattern NUMBER_PATTERN = Pattern.compile("-?\\d+");
private final DateTime dateTime;
DateParam(DateTime dateTime)
{
this.dateTime = checkNotNull(dateTime, "null datetime").withZone(DateTimeZone.UTC);
}
public static DateParam valueOf(DateTime dateTime)
{
return new DateParam(dateTime);
}
public static DateParam valueOf(String string)
{
if (string == null) {
return null;
}
if (NUMBER_PATTERN.matcher(string).matches()) {
return new DateParam(new DateTime(Long.parseLong(string), DateTimeZone.UTC));
} else {
return new DateParam(new DateTime(string, DateTimeZone.UTC));
}
}
/**
* @return a DateTime if the parameter was provided, or null otherwise.
*/
// This method is static so that you can handle optional parameters as null instances.
public static DateTime getDateTime(DateParam param)
{
return param == null ? null : param.dateTime;
}
@Override
public String toString()
{
return Objects.toString(dateTime);
}
}
|
NessComputing/components-ness-jersey
|
jersey/src/main/java/com/nesscomputing/jersey/types/DateParam.java
|
Java
|
apache-2.0
| 2,189 |
package hu.akarnokd.rxjava;
import java.util.concurrent.TimeUnit;
import rx.*;
import rx.plugins.RxJavaHooks;
import rx.schedulers.Schedulers;
public class TrackSubscriber1 {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
RxJavaHooks.setOnObservableStart((observable, onSubscribe) -> {
if (!onSubscribe.getClass().getName().toLowerCase().contains("map")) {
return onSubscribe;
}
System.out.println("Started");
return (Observable.OnSubscribe<Object>)observer -> {
class SignalTracker extends Subscriber<Object> {
@Override public void onNext(Object o) {
// handle onNext before or aftern notifying the downstream
observer.onNext(o);
}
@Override public void onError(Throwable t) {
// handle onError
observer.onError(t);
}
@Override public void onCompleted() {
// handle onComplete
System.out.println("Completed");
observer.onCompleted();
}
}
SignalTracker t = new SignalTracker();
onSubscribe.call(t);
};
});
Observable<Integer> observable = Observable.range(1, 5)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.computation())
.map(integer -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
return integer * 3;
});
observable.subscribe(System.out::println);
Thread.sleep(6000L);
}
}
|
akarnokd/akarnokd-misc
|
src/main/java/hu/akarnokd/rxjava/TrackSubscriber1.java
|
Java
|
apache-2.0
| 1,774 |
package tk.zielony.carbonsamples.feature;
import android.app.Activity;
import android.os.Bundle;
import tk.zielony.carbonsamples.R;
/**
* Created by Marcin on 2016-03-13.
*/
public class TextMarkerActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_textmarker);
}
}
|
sevoan/Carbon
|
samples/src/main/java/tk/zielony/carbonsamples/feature/TextMarkerActivity.java
|
Java
|
apache-2.0
| 408 |
/* */ package com.hundsun.network.gates.houchao.biz.services.pojo;
/* */
/* */ import org.springframework.context.annotation.Scope;
/* */ import org.springframework.stereotype.Service;
/* */
/* */ @Service("outFundTrans")
/* */ @Scope("prototype")
/* */ public class OutFundTrans extends InOutFundTrans
/* */ {
/* */ protected boolean isTrans()
/* */ {
/* 26 */ return true;
/* */ }
/* */
/* */ protected boolean isOutFund()
/* */ {
/* 31 */ return true;
/* */ }
/* */
/* */ protected boolean isNeedRecordUncomeFund()
/* */ {
/* 39 */ return false;
/* */ }
/* */
/* */ protected boolean isInOutTrans()
/* */ {
/* 49 */ return true;
/* */ }
/* */ }
/* Location: E:\__安装归档\linquan-20161112\deploy16\houchao\webroot\WEB-INF\classes\
* Qualified Name: com.hundsun.network.gates.houchao.biz.services.pojo.OutFundTrans
* JD-Core Version: 0.6.0
*/
|
hnccfr/ccfrweb
|
fundcore/src/com/hundsun/network/gates/houchao/biz/services/pojo/OutFundTrans.java
|
Java
|
apache-2.0
| 1,022 |
/*
* Copyright 2002-2018 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.bind.support;
import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.core.convert.ConversionService;
import org.springframework.lang.Nullable;
import org.springframework.validation.BindingErrorProcessor;
import org.springframework.validation.MessageCodesResolver;
import org.springframework.validation.Validator;
import org.springframework.web.bind.WebDataBinder;
/**
* Convenient {@link WebBindingInitializer} for declarative configuration
* in a Spring application context. Allows for reusing pre-configured
* initializers with multiple controller/handlers.
*
* @author Juergen Hoeller
* @since 2.5
* @see #setDirectFieldAccess
* @see #setMessageCodesResolver
* @see #setBindingErrorProcessor
* @see #setValidator(Validator)
* @see #setConversionService(ConversionService)
* @see #setPropertyEditorRegistrar
*/
public class ConfigurableWebBindingInitializer implements WebBindingInitializer {
private boolean autoGrowNestedPaths = true;
private boolean directFieldAccess = false;
@Nullable
private MessageCodesResolver messageCodesResolver;
@Nullable
private BindingErrorProcessor bindingErrorProcessor;
@Nullable
private Validator validator;
@Nullable
private ConversionService conversionService;
@Nullable
private PropertyEditorRegistrar[] propertyEditorRegistrars;
/**
* Set whether a binder should attempt to "auto-grow" a nested path that contains a null value.
* <p>If "true", a null path location will be populated with a default object value and traversed
* instead of resulting in an exception. This flag also enables auto-growth of collection elements
* when accessing an out-of-bounds index.
* <p>Default is "true" on a standard DataBinder. Note that this feature is only supported
* for bean property access (DataBinder's default mode), not for field access.
* @see org.springframework.validation.DataBinder#initBeanPropertyAccess()
* @see org.springframework.validation.DataBinder#setAutoGrowNestedPaths
*/
public void setAutoGrowNestedPaths(boolean autoGrowNestedPaths) {
this.autoGrowNestedPaths = autoGrowNestedPaths;
}
/**
* Return whether a binder should attempt to "auto-grow" a nested path that contains a null value.
*/
public boolean isAutoGrowNestedPaths() {
return this.autoGrowNestedPaths;
}
/**
* Set whether to use direct field access instead of bean property access.
* <p>Default is {@code false}, using bean property access.
* Switch this to {@code true} in order to enforce direct field access.
* @see org.springframework.validation.DataBinder#initDirectFieldAccess()
* @see org.springframework.validation.DataBinder#initBeanPropertyAccess()
*/
public final void setDirectFieldAccess(boolean directFieldAccess) {
this.directFieldAccess = directFieldAccess;
}
/**
* Return whether to use direct field access instead of bean property access.
*/
public boolean isDirectFieldAccess() {
return this.directFieldAccess;
}
/**
* Set the strategy to use for resolving errors into message codes.
* Applies the given strategy to all data binders used by this controller.
* <p>Default is {@code null}, i.e. using the default strategy of
* the data binder.
* @see org.springframework.validation.DataBinder#setMessageCodesResolver
*/
public final void setMessageCodesResolver(@Nullable MessageCodesResolver messageCodesResolver) {
this.messageCodesResolver = messageCodesResolver;
}
/**
* Return the strategy to use for resolving errors into message codes.
*/
@Nullable
public final MessageCodesResolver getMessageCodesResolver() {
return this.messageCodesResolver;
}
/**
* Set the strategy to use for processing binding errors, that is,
* required field errors and {@code PropertyAccessException}s.
* <p>Default is {@code null}, that is, using the default strategy
* of the data binder.
* @see org.springframework.validation.DataBinder#setBindingErrorProcessor
*/
public final void setBindingErrorProcessor(@Nullable BindingErrorProcessor bindingErrorProcessor) {
this.bindingErrorProcessor = bindingErrorProcessor;
}
/**
* Return the strategy to use for processing binding errors.
*/
@Nullable
public final BindingErrorProcessor getBindingErrorProcessor() {
return this.bindingErrorProcessor;
}
/**
* Set the Validator to apply after each binding step.
*/
public final void setValidator(@Nullable Validator validator) {
this.validator = validator;
}
/**
* Return the Validator to apply after each binding step, if any.
*/
@Nullable
public final Validator getValidator() {
return this.validator;
}
/**
* Specify a ConversionService which will apply to every DataBinder.
* @since 3.0
*/
public final void setConversionService(@Nullable ConversionService conversionService) {
this.conversionService = conversionService;
}
/**
* Return the ConversionService which will apply to every DataBinder.
*/
@Nullable
public final ConversionService getConversionService() {
return this.conversionService;
}
/**
* Specify a single PropertyEditorRegistrar to be applied to every DataBinder.
*/
public final void setPropertyEditorRegistrar(PropertyEditorRegistrar propertyEditorRegistrar) {
this.propertyEditorRegistrars = new PropertyEditorRegistrar[] {propertyEditorRegistrar};
}
/**
* Specify multiple PropertyEditorRegistrars to be applied to every DataBinder.
*/
public final void setPropertyEditorRegistrars(@Nullable PropertyEditorRegistrar[] propertyEditorRegistrars) {
this.propertyEditorRegistrars = propertyEditorRegistrars;
}
/**
* Return the PropertyEditorRegistrars to be applied to every DataBinder.
*/
@Nullable
public final PropertyEditorRegistrar[] getPropertyEditorRegistrars() {
return this.propertyEditorRegistrars;
}
@Override
public void initBinder(WebDataBinder binder) {
binder.setAutoGrowNestedPaths(this.autoGrowNestedPaths);
if (this.directFieldAccess) {
binder.initDirectFieldAccess();
}
if (this.messageCodesResolver != null) {
binder.setMessageCodesResolver(this.messageCodesResolver);
}
if (this.bindingErrorProcessor != null) {
binder.setBindingErrorProcessor(this.bindingErrorProcessor);
}
if (this.validator != null && binder.getTarget() != null &&
this.validator.supports(binder.getTarget().getClass())) {
binder.setValidator(this.validator);
}
if (this.conversionService != null) {
binder.setConversionService(this.conversionService);
}
if (this.propertyEditorRegistrars != null) {
for (PropertyEditorRegistrar propertyEditorRegistrar : this.propertyEditorRegistrars) {
propertyEditorRegistrar.registerCustomEditors(binder);
}
}
}
}
|
spring-projects/spring-framework
|
spring-web/src/main/java/org/springframework/web/bind/support/ConfigurableWebBindingInitializer.java
|
Java
|
apache-2.0
| 7,350 |
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2014-2015 AS3Boyan
* Copyright 2014-2014 Elias Ku
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// This is a generated file. Not intended for manual editing.
package com.intellij.plugins.haxe.lang.psi.impl;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static com.intellij.plugins.haxe.lang.lexer.HaxeTokenTypes.*;
import com.intellij.plugins.haxe.lang.psi.*;
public class HaxeMultiplicativeExpressionImpl extends HaxeExpressionImpl implements HaxeMultiplicativeExpression {
public HaxeMultiplicativeExpressionImpl(ASTNode node) {
super(node);
}
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof HaxeVisitor) ((HaxeVisitor)visitor).visitMultiplicativeExpression(this);
else super.accept(visitor);
}
@Override
@NotNull
public List<HaxeExpression> getExpressionList() {
return PsiTreeUtil.getChildrenOfTypeAsList(this, HaxeExpression.class);
}
@Override
@Nullable
public HaxeIfStatement getIfStatement() {
return findChildByClass(HaxeIfStatement.class);
}
@Override
@Nullable
public HaxeSwitchStatement getSwitchStatement() {
return findChildByClass(HaxeSwitchStatement.class);
}
@Override
@Nullable
public HaxeTryStatement getTryStatement() {
return findChildByClass(HaxeTryStatement.class);
}
}
|
yanhick/intellij-haxe-nightly-builds
|
gen/com/intellij/plugins/haxe/lang/psi/impl/HaxeMultiplicativeExpressionImpl.java
|
Java
|
apache-2.0
| 2,047 |
package com.yuzhou.viewer.service;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.google.common.eventbus.EventBus;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.SyncHttpClient;
import com.yuzhou.viewer.R;
import com.yuzhou.viewer.model.GoogleImage;
import com.yuzhou.viewer.model.GoogleImageFactory;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by yuzhou on 2015/08/02.
*/
public class GoogleApiTask extends AsyncTask<ApiParam, Integer, List<GoogleImage>>
{
private final SyncHttpClient client = new SyncHttpClient();
private final List<GoogleImage> items = new ArrayList<>();
private final EventBus eventBus;
private final Context context;
private int errorResource;
public GoogleApiTask(EventBus eventBus, Context context)
{
this.eventBus = eventBus;
this.context = context;
}
private List<GoogleImage> interExecute(ApiParam request)
{
Log.d("VIEWER", request.toString());
client.get(request.getUrl(), request.getParams(), new JsonHttpResponseHandler()
{
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject response)
{
Log.i("VIEWER", "status code=" + statusCode + ", response=" + response + ", error=" + throwable.getMessage());
errorResource = R.string.error_unavailable_network;
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response)
{
if (response == null) {
Log.i("VIEWER", "Response no context");
errorResource = R.string.error_server_side;
return;
}
try {
int httpCode = response.getInt("responseStatus");
if (httpCode == 400) {
errorResource = R.string.error_data_not_found;
Log.d("VIEWER", "response=" + response.getString("responseDetails"));
return;
}
if (httpCode != 200) {
errorResource = R.string.error_server_side;
Log.d("VIEWER", "response=" + response.getString("responseDetails"));
return;
}
List<GoogleImage> images = GoogleImageFactory.create(response);
if (images.isEmpty()) {
Log.i("VIEWER", "Can not parse JSON");
Log.d("VIEWER", "response=" + response.toString());
errorResource = R.string.error_server_side;
return;
}
items.addAll(images);
} catch (JSONException e) {
Log.i("VIEWER", "Can not parse JSON");
e.printStackTrace();
}
}
});
return items;
}
@Override
protected List<GoogleImage> doInBackground(ApiParam... requests)
{
ApiParam request = requests[0];
return interExecute(request);
}
@Override
protected void onPreExecute()
{
items.clear();
}
@Override
protected void onPostExecute(List<GoogleImage> googleImages)
{
if (errorResource > 0) {
Toast.makeText(context, errorResource, Toast.LENGTH_LONG).show();
}
eventBus.post(items);
}
}
|
yuzhou2/android_02_grid_image_search
|
app/src/main/java/com/yuzhou/viewer/service/GoogleApiTask.java
|
Java
|
apache-2.0
| 3,730 |
package com.rockhoppertech.music.fx.cmn;
/*
* #%L
* rockymusic-fx
* %%
* Copyright (C) 1996 - 2013 Rockhopper Technologies
* %%
* 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.
* #L%
*/
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.SceneBuilder;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Screen;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author <a href="http://genedelisa.com/">Gene De Lisa</a>
*
*/
public class GrandStaffApp extends Application {
private static final Logger logger = LoggerFactory
.getLogger(GrandStaffApp.class);
private Stage stage;
private Scene scene;
private Pane root;
private GrandStaffAppController controller;
public static void main(String[] args) throws Exception {
launch(args);
}
void loadRootFxml() {
String fxmlFile = "/fxml/GrandStaffPanel.fxml";
logger.debug("Loading FXML for main view from: {}", fxmlFile);
try {
FXMLLoader loader = new FXMLLoader(
GrandStaffApp.class.getResource(fxmlFile));
root = (AnchorPane) loader.load();
controller = loader.getController();
} catch (IOException e) {
logger.error(e.getLocalizedMessage(),e);
}
}
@Override
public void start(Stage stage) throws Exception {
this.stage = stage;
// this.staffModel = new StaffModel();
// MIDITrack track = MIDITrackBuilder
// .create()
// .noteString(
// "E5 F G Ab G# A B C C6 D Eb F# G A B C7 B4 Bf4 A4 Af4")
// .durations(5, 4, 3, 2, 1, 1.5, .5, .75, .25, .25)
// .sequential()
// .build();
// this.staffModel.setTrack(track);
loadRootFxml();
this.scene = SceneBuilder.create()
.root(root)
.fill(Color.web("#1030F0"))
.stylesheets("/styles/grandStaffApp.css")
.build();
this.configureStage();
logger.debug("started");
}
private void configureStage() {
stage.setTitle("Music Notation");
// fullScreen();
stage.setScene(this.scene);
stage.show();
}
private void fullScreen() {
// make it full screen
stage.setX(0);
stage.setY(0);
stage.setWidth(Screen.getPrimary().getVisualBounds().getWidth());
stage.setHeight(Screen.getPrimary().getVisualBounds().getHeight());
}
}
|
genedelisa/rockymusic
|
rockymusic-fx/src/main/java/com/rockhoppertech/music/fx/cmn/GrandStaffApp.java
|
Java
|
apache-2.0
| 3,230 |
package org.tuxdevelop.spring.batch.lightmin.server.cluster.configuration;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
@Data
@ConfigurationProperties(prefix = "spring.batch.lightmin.server.cluster.infinispan")
public class InfinispanServerClusterConfigurationProperties {
@NestedConfigurationProperty
private RepositoryConfigurationProperties repository = new RepositoryConfigurationProperties();
@Data
static class RepositoryConfigurationProperties {
private Boolean initSchedulerExecutionRepository = Boolean.FALSE;
private Boolean initSchedulerConfigurationRepository = Boolean.FALSE;
}
}
|
tuxdevelop/spring-batch-lightmin
|
spring-batch-lightmin-server/spring-batch-lightmin-server-cluster/spring-batch-lightmin-server-cluster-infinispan/src/main/java/org/tuxdevelop/spring/batch/lightmin/server/cluster/configuration/InfinispanServerClusterConfigurationProperties.java
|
Java
|
apache-2.0
| 765 |
package org.ngrinder.home.controller;
import lombok.RequiredArgsConstructor;
import org.ngrinder.common.constant.ControllerConstants;
import org.ngrinder.home.model.PanelEntry;
import org.ngrinder.home.service.HomeService;
import org.ngrinder.infra.config.Config;
import org.ngrinder.script.handler.ScriptHandler;
import org.ngrinder.script.handler.ScriptHandlerFactory;
import org.ngrinder.user.service.UserContext;
import org.springframework.context.MessageSource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.PostConstruct;
import java.util.*;
import static java.util.Comparator.comparing;
import static org.ngrinder.common.constant.ControllerConstants.*;
import static org.ngrinder.common.util.CollectionUtils.buildMap;
import static org.ngrinder.common.util.NoOp.noOp;
/**
* Home index page api controller.
*
* @since 3.5.0
*/
@RestController
@RequestMapping("/home/api")
@RequiredArgsConstructor
public class HomeApiController {
private static final String TIMEZONE_ID_PREFIXES = "^(Africa|America|Asia|Atlantic|Australia|Europe|Indian|Pacific)/.*";
private final HomeService homeService;
private final ScriptHandlerFactory scriptHandlerFactory;
private final UserContext userContext;
private final Config config;
private final MessageSource messageSource;
private List<TimeZone> timeZones = null;
@PostConstruct
public void init() {
timeZones = new ArrayList<>();
final String[] timeZoneIds = TimeZone.getAvailableIDs();
for (final String id : timeZoneIds) {
if (id.matches(TIMEZONE_ID_PREFIXES) && !TimeZone.getTimeZone(id).getDisplayName().contains("GMT")) {
timeZones.add(TimeZone.getTimeZone(id));
}
}
timeZones.sort(comparing(TimeZone::getID));
}
@GetMapping("/handlers")
public List<ScriptHandler> getHandlers() {
return scriptHandlerFactory.getVisibleHandlers();
}
@GetMapping("/panel")
public Map<String, Object> getPanelEntries() {
return buildMap("leftPanelEntries", getLeftPanelEntries(), "rightPanelEntries", getRightPanelEntries());
}
@GetMapping("/timezones")
public List<TimeZone> getTimezones() {
return timeZones;
}
@GetMapping("/config")
public Map<String, Object> getCommonHomeConfig() {
return buildMap(
"askQuestionUrl", config.getControllerProperties().getProperty(PROP_CONTROLLER_FRONT_PAGE_ASK_QUESTION_URL,
getMessages(PROP_CONTROLLER_FRONT_PAGE_ASK_QUESTION_URL)),
"seeMoreQuestionUrl", config.getControllerProperties().getProperty(PROP_CONTROLLER_FRONT_PAGE_QNA_MORE_URL,
getMessages(PROP_CONTROLLER_FRONT_PAGE_QNA_MORE_URL)),
"seeMoreResourcesUrl", config.getControllerProperties().getProperty(PROP_CONTROLLER_FRONT_PAGE_RESOURCES_MORE_URL),
"userLanguage", config.getControllerProperties().getProperty(ControllerConstants.PROP_CONTROLLER_DEFAULT_LANG));
}
private List<PanelEntry> getRightPanelEntries() {
if (config.getControllerProperties().getPropertyBoolean(PROP_CONTROLLER_FRONT_PAGE_ENABLED)) {
// Get nGrinder Resource RSS
String rightPanelRssURL = config.getControllerProperties().getProperty(PROP_CONTROLLER_FRONT_PAGE_RESOURCES_RSS);
return homeService.getRightPanelEntries(rightPanelRssURL);
}
return Collections.emptyList();
}
private List<PanelEntry> getLeftPanelEntries() {
if (config.getControllerProperties().getPropertyBoolean(PROP_CONTROLLER_FRONT_PAGE_ENABLED)) {
// Make the i18n applied QnA panel. Depending on the user language, show the different QnA panel.
String leftPanelRssURLKey = getMessages(PROP_CONTROLLER_FRONT_PAGE_QNA_RSS);
// Make admin configure the QnA panel.
String leftPanelRssURL = config.getControllerProperties().getProperty(PROP_CONTROLLER_FRONT_PAGE_QNA_RSS,
leftPanelRssURLKey);
return homeService.getLeftPanelEntries(leftPanelRssURL);
}
return Collections.emptyList();
}
@GetMapping("/messagesources/{locale}")
public Map<String, String> getUserDefinedMessageSources(@PathVariable String locale) {
return homeService.getUserDefinedMessageSources(locale);
}
/**
* Get the message from messageSource by the given key.
*
* @param key key of message
* @return the found message. If not found, the error message will return.
*/
private String getMessages(String key) {
String userLanguage = "en";
try {
userLanguage = userContext.getCurrentUser().getUserLanguage();
} catch (Exception e) {
noOp();
}
Locale locale = new Locale(userLanguage);
return messageSource.getMessage(key, null, locale);
}
}
|
naver/ngrinder
|
ngrinder-controller/src/main/java/org/ngrinder/home/controller/HomeApiController.java
|
Java
|
apache-2.0
| 4,677 |
package com.huawei.esdk.fusionmanager.local.model.system;
import com.huawei.esdk.fusionmanager.local.model.FMSDKResponse;
/**
* 查询计划任务详情返回信息。
* <p>
* @since eSDK Cloud V100R003C30
*/
public class QueryScheduleTaskDetailResp extends FMSDKResponse
{
/**
* 计划任务。
*/
private ScheduleTask scheduleTask;
public ScheduleTask getScheduleTask()
{
return scheduleTask;
}
public void setScheduleTask(ScheduleTask scheduleTask)
{
this.scheduleTask = scheduleTask;
}
}
|
eSDK/esdk_cloud_fm_r3_native_java
|
source/FM/V1R5/esdk_fm_neadp_1.5_native_java/src/main/java/com/huawei/esdk/fusionmanager/local/model/system/QueryScheduleTaskDetailResp.java
|
Java
|
apache-2.0
| 571 |
//Copyright (c) 2014 by Disy Informationssysteme GmbH
package net.disy.eenvplus.tfes.modules.sparql.expression;
import com.hp.hpl.jena.sparql.expr.E_LogicalAnd;
import com.hp.hpl.jena.sparql.expr.E_LogicalOr;
import com.hp.hpl.jena.sparql.expr.Expr;
import com.hp.hpl.jena.sparql.syntax.ElementFilter;
// NOT_PUBLISHED
public class SparqlExpressionBuilder {
private Expr current;
private SparqlExpressionBuilder(Expr expression) {
this.current = expression;
}
public static SparqlExpressionBuilder use(Expr expression) {
return new SparqlExpressionBuilder(expression);
}
public Expr toExpr() {
return current;
}
public ElementFilter toElementFilter() {
return new ElementFilter(current);
}
public SparqlExpressionBuilder and(Expr expression) {
if (expression != null) {
current = new E_LogicalAnd(current, expression);
}
return this;
}
public SparqlExpressionBuilder and(Expr expression, boolean condition) {
if (condition) {
return and(expression);
}
return this;
}
public SparqlExpressionBuilder or(Expr expression) {
if (expression != null) {
current = new E_LogicalOr(current, expression);
}
return this;
}
}
|
eENVplus/tf-exploitation-server
|
TF_Exploitation_Server_modules/src/main/java/net/disy/eenvplus/tfes/modules/sparql/expression/SparqlExpressionBuilder.java
|
Java
|
apache-2.0
| 1,223 |
package com.sectong.util;
import org.apache.log4j.Logger;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
public class HttpUtil {
private static Logger logger = Logger.getLogger(HttpUtil.class);
private final static int CONNECT_TIMEOUT = 5000; // in milliseconds
private final static String DEFAULT_ENCODING = "UTF-8";
public static String postData(String urlStr, String data){
return postData(urlStr, data, null);
}
public static String postData(String urlStr, String data, String contentType){
BufferedReader reader = null;
try {
URL url = new URL(urlStr);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setConnectTimeout(CONNECT_TIMEOUT);
conn.setReadTimeout(CONNECT_TIMEOUT);
if(contentType != null)
conn.setRequestProperty("content-type", contentType);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING);
if(data == null)
data = "";
writer.write(data);
writer.flush();
writer.close();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_ENCODING));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append("\r\n");
}
return sb.toString();
} catch (IOException e) {
logger.error("Error connecting to " + urlStr + ": " + e.getMessage());
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException e) {
}
}
return null;
}
}
|
xaioyi/yidongyiljwj
|
src/main/java/com/sectong/util/HttpUtil.java
|
Java
|
apache-2.0
| 1,988 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.