hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
32add08fd299a2f631054585019c5d3437eb2e27
| 683 |
package generated;
import java.util.*;
import recaf.core.cps.StmtJavaCPS;
public class TestFor_noBreak {
private StmtJavaCPS<Integer> alg = new StmtJavaCPS<Integer>() {};
Integer meth() {
return (Integer )alg.Method(alg.Decl(() -> 0, (recaf.core.Ref<Integer > sum) -> {return alg.Decl(() -> Arrays.asList(1,2,3,4,5), (recaf.core.Ref<List<Integer>> list) -> {return alg.Seq(alg.<Integer >ForEach(() -> list.value, (recaf.core.Ref<Integer > i) -> alg.ExpStat(() -> { sum.value += (Integer)i.value; return null; })), alg.Return(() -> sum.value));});}));
}
public static void main(String args[]) {
System.out.println(new TestFor_noBreak().meth()); //15
}
}
| 42.6875 | 364 | 0.644217 |
95912731245e164ecf7b231b688a82eebb31f98a
| 1,011 |
/*
* 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 demo;
import java.util.Map;
import java.util.stream.Stream;
/**
*
* @author hantsy
*/
public class StreamSample {
public static final void main(String[] args) {
//Java 9
Stream.of("hello", "java 9", "stream")
.takeWhile(s -> s.contains("h"))
.forEach(System.out::println);
Stream.of("hello", "java 9", "stream")
.dropWhile(s -> s.contains("h"))
.forEach(System.out::println);
Stream.iterate(0, i -> i < 10, i -> i = i + 1)
.forEach(System.out::println);
Map<Integer, String> seeds = Map.of(1, "Hello", 2, "Java 9", 3, "Stream");
Stream.of(1, 3, 4)
.flatMap( i -> Stream.ofNullable(seeds.get(i)))
.forEach(System.out::println);
}
}
| 26.605263 | 82 | 0.55094 |
3dc3871177d5ca7cb1e5292e70b31a27bff2182f
| 6,547 |
/*
* Copyright (c) 2015-2019 Rocket Partners, LLC
* https://github.com/inversion-api
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.inversion;
import java.io.Serializable;
public class Relationship implements Serializable {
public static final String REL_MANY_TO_ONE = "MANY_TO_ONE";
public static final String REL_ONE_TO_MANY = "ONE_TO_MANY";
public static final String REL_MANY_TO_MANY = "MANY_TO_MANY";
protected String name = null;
protected String type = null;
protected Index fkIndex1 = null;
protected Index fkIndex2 = null;
protected Collection collection = null;
protected Collection related = null;
protected boolean exclude = false;
public Relationship() {
}
public Relationship(String name, String type, Collection collection, Collection related, Index fkIndex1, Index fkIndex2) {
withName(name);
withType(type);
withCollection(collection);
withRelated(related);
withFkIndex1(fkIndex1);
withFkIndex2(fkIndex2);
}
public boolean isExclude() {
return exclude || (fkIndex1 != null && fkIndex1.isExclude()) || (fkIndex2 != null && fkIndex2.isExclude());
}
public Relationship withExclude(boolean exclude) {
this.exclude = exclude;
return this;
}
/**
* @return the collection
*/
public Collection getCollection() {
return collection;
}
public Relationship withCollection(Collection collection) {
if (this.collection != collection) {
this.collection = collection;
if (collection != null)
collection.withRelationship(this);
}
return this;
}
/**
* @return the related
*/
public Collection getRelated() {
return related;
}
public Relationship getInverse() {
if (isManyToMany()) {
for (Relationship other : related.getRelationships()) {
if (other == this)
continue;
if (!other.isManyToMany())
continue;
if (getFkIndex1().equals(other.getFkIndex2())) {
return other;
}
}
} else {
for (Relationship other : related.getRelationships()) {
if (other == this)
continue;
if (isManyToOne() && !other.isOneToMany())
continue;
if (isManyToMany() && !other.isManyToOne())
continue;
if (getFkIndex1().equals(other.getFkIndex1()) //
&& getPrimaryKeyTable1().getPrimaryIndex().equals(other.getPrimaryKeyTable1().getPrimaryIndex())) {
return other;
}
}
}
return null;
}
/**
* @param related the related to set
* @return this
*/
public Relationship withRelated(Collection related) {
this.related = related;
return this;
}
public boolean isManyToMany() {
return REL_MANY_TO_MANY.equalsIgnoreCase(type);
}
public boolean isOneToMany() {
return REL_ONE_TO_MANY.equalsIgnoreCase(type);
}
public boolean isManyToOne() {
return REL_MANY_TO_ONE.equalsIgnoreCase(type);
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
* @return this
*/
public Relationship withName(String name) {
this.name = name;
return this;
}
public boolean equals(Object obj) {
if (!(obj instanceof Relationship))
return false;
if (obj == this)
return true;
return toString().equals(obj.toString());
}
public String toString() {
try {
String str = collection.getName() + "." + getName() + " : " + getType() + " ";
if (isManyToOne()) {
str += getFkIndex1() + " -> " + collection.getPrimaryIndex();
} else if (isOneToMany()) {
str += collection.getPrimaryIndex() + " <- " + getFkIndex1();
} else {
str += getFkIndex1() + " <--> " + getFkIndex2();
}
return str;
} catch (NullPointerException ex) {
return "Relationship: " + name + "-" + type + "-" + fkIndex1 + "-" + fkIndex2;
}
}
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @param type the type to set
* @return this
*/
public Relationship withType(String type) {
this.type = type;
return this;
}
public Index getFkIndex1() {
return fkIndex1;
}
public Relationship withFkIndex1(Index fkIndex1) {
this.fkIndex1 = fkIndex1;
return this;
}
public Index getFkIndex2() {
return fkIndex2;
}
public Relationship withFkIndex2(Index fkIndex2) {
this.fkIndex2 = fkIndex2;
return this;
}
public Collection getPrimaryKeyTable1() {
return fkIndex1.getProperty(0).getCollection();
}
public Collection getPrimaryKeyTable2() {
return fkIndex2.getProperty(0).getCollection();
}
/**
* @return the fkCol1
*/
public Property getFk1Col1() {
return fkIndex1.getProperty(0);
}
//
// /**
// * @param fkCol1 the fkCol1 to set
// */
// public Relationship withFkCol1(Column fkCol1)
// {
// this.fkCol1 = fkCol1;
// return this;
// }
//
/**
* @return the fkCol2
*/
public Property getFk2Col1() {
return fkIndex2.getProperty(0);
}
//
// /**
// * @param fkCol2 the fkCol2 to set
// */
// public Relationship withFkCol2(Column fkCol2)
// {
// this.fkCol2 = fkCol2;
// return this;
// }
}
| 25.474708 | 126 | 0.559493 |
8610cc35e761a68ff102d50ff6455128cb837830
| 1,547 |
package pw.cdmi.msm.geo.repositories.jpa;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.repository.query.Param;
import pw.cdmi.msm.geo.model.entity.Town;
import pw.cdmi.msm.geo.repositories.TownRepository;
public interface JpaTownRepository extends TownRepository {
@Override
@Query("FROM Town WHERE districtId = :districtId")
public Iterable<Town> findByDistrictId(Integer districtId);
@Override
@Query("SELECT openId FROM Town WHERE name = :name AND districtId = :districtId")
public long findIdByNameAndDistrictId(String name, int districtId);
@Override
@Query("SELECT new Town(p.openId,p.name) FROM Town WHERE districtId = :districtId")
public Iterable<Town> findNamesByDistrictId(@Param(value = "districtId") Integer districtId);
@Override
@Query("SELECT count(t) FROM Town t WHERE t.countryId = :countryId")
public long countByCountryId(@Param(value = "countryId") Integer countryId);
@Override
@Query(value="SELECT count(t) FROM Town t WHERE t.provinceId = :provinceId")
public long countByProvinceId(@Param(value="provinceId") Integer provinceId);
@Override
@Query(value="SELECT count(t) FROM Town t WHERE t.cityId = :cityId")
public long countByCityId(@Param(value="cityId") Integer cityId);
@Override
@Query(value="SELECT count(t) FROM Town t WHERE t.districtId = :districtId")
public long countByDistrictId(Integer districtId);
}
| 39.666667 | 98 | 0.710407 |
7af86df8f3bb5e02e90ef7d9ffc8ec62b42631e8
| 3,470 |
/*
* The MIT License
*
* Copyright (c) 2016 Steven G. Brown
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.plugins.timestamper.format;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThrows;
import hudson.plugins.timestamper.Timestamp;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
import org.junit.Test;
/**
* Unit test for the {@link ElapsedTimestampFormat} class.
*
* @author Steven G. Brown
*/
public class ElapsedTimestampFormatTest {
@Test
public void testApply() {
String elapsedTimeFormat = "ss.S";
Timestamp timestamp = new Timestamp(123, 42000);
assertThat(new ElapsedTimestampFormat(elapsedTimeFormat).apply(timestamp), is("00.123"));
}
@Test
public void testApply_withInvalidHtml() {
String elapsedTimeFormat = "'<b>'HH:mm:ss.S'</b><script>console.log(\"foo\")</script>'";
Timestamp timestamp = new Timestamp(123, 42000);
assertThat(
new ElapsedTimestampFormat(elapsedTimeFormat).apply(timestamp), is("<b>00:00:00.123</b>"));
}
@Test
public void testValidate() {
String elapsedTimeFormat = "'<b>'HH:mm:ss.S'</b>'";
new ElapsedTimestampFormat(elapsedTimeFormat).validate();
}
@Test
public void testValidate_withFormatParseException() {
String elapsedTimeFormat = "'yMdHms''S";
assertThrows(
FormatParseException.class, () -> new ElapsedTimestampFormat(elapsedTimeFormat).validate());
}
@Test
public void testValidate_withInvalidHtml() {
String elapsedTimeFormat = "'<b>'HH:mm:ss.S'</b><script>console.log(\"foo\")</script>'";
assertThrows(
InvalidHtmlException.class, () -> new ElapsedTimestampFormat(elapsedTimeFormat).validate());
}
@Test
public void testGetPlainTextUrl() {
ElapsedTimestampFormat format = new ElapsedTimestampFormat("'<b>'HH:mm:ss.S'</b> '");
assertThat(format.getPlainTextUrl(), is("timestamps/?elapsed=HH:mm:ss.S&appendLog"));
}
@Test
public void testGetPlainTextUrl_excessWhitespace() {
ElapsedTimestampFormat format = new ElapsedTimestampFormat(" ' <b> ' HH:mm:ss.S ' </b> ' ");
assertThat(format.getPlainTextUrl(), is("timestamps/?elapsed=HH:mm:ss.S&appendLog"));
}
@Test
public void testEqualsAndHashCode() {
EqualsVerifier.forClass(ElapsedTimestampFormat.class).suppress(Warning.NULL_FIELDS).verify();
}
}
| 36.914894 | 100 | 0.7317 |
ebe569da62596914683aff5aca865a284be94327
| 1,312 |
package frc.robot;
import java.beans.Encoder;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public class Dashboard {
public Dashboard() {
display();
}
public void display() {
intakeInfo();
feederInfo();
climberInfo();
shooterInfo();
visionInfo();
}
public void intakeInfo() {
SmartDashboard.putBoolean("String", true); //Example
}
public void feederInfo() {
SmartDashboard.putBoolean("String", true);
//Encoder
//Encoder feederMotorEncoder = new Encoder (10);
//feederMotorEncoder.getDistance();
//Voltage
SmartDashboard.putNumber("Voltage", feeder.getAverageVoltage());
SmartDashboard.putNumber("Feeder encoder", feederMotorEncoder.getEncoderRaw());
}
public void climberInfo() {
SmartDashboard.putNumber("Climber Encoder", climber.getEncoderRaw());
SmartDashboard.putNumber("Climber Low Limit", climber.getLowSetPoint());
SmartDashboard.putNumber("Climber High Limit", climber.getHighSetPoint());
//Get encoder values
}
public void shooterInfo() {
SmartDashboard.putBoolean("String", true);
}
public void visionInfo() {
SmartDashboard.putBoolean("String", true);
}
}
| 25.230769 | 87 | 0.63872 |
ac27434d479a32cb28042b8a4bc61b26529cf2da
| 732 |
package in.hocg.sso2.server.sample;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import java.util.Collections;
/**
* Created by hocgin on 2020/1/9.
* email: hocgin@gmail.com
*
* @author hocgin
*/
@Component
public class UserDetailsServiceImpl implements org.springframework.security.core.userdetails.UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return new User(username, "{noop}hocgin", Collections.emptyList());
}
}
| 29.28 | 113 | 0.795082 |
1c43a38f52e48fd6419ee38758fa406ec571bb96
| 12,870 |
package ch.ahdis.matchbox.provider;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicLong;
import org.hl7.fhir.convertors.VersionConvertor_40_50;
import org.hl7.fhir.dstu2.model.ResourceType;
import org.hl7.fhir.instance.model.api.IIdType;
import org.hl7.fhir.r4.model.Resource;
import org.hl7.fhir.r5.context.SimpleWorkerContext;
import org.hl7.fhir.r5.model.CanonicalResource;
import org.hl7.fhir.r5.model.Questionnaire;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ca.uhn.fhir.rest.annotation.IdParam;
import ca.uhn.fhir.rest.annotation.Read;
import ca.uhn.fhir.rest.annotation.Search;
import ca.uhn.fhir.rest.api.server.RequestDetails;
import ca.uhn.fhir.rest.server.IResourceProvider;
/**
* This class is a simple implementation of the resource provider
* interface that uses a HashMap to store all resources in memory.
* <p>
* This class currently supports the following FHIR operations:
* </p>
* <ul>
* <li>Create</li>
* <li>Update existing resource</li>
* <li>Update non-existing resource (e.g. create with client-supplied ID)</li>
* <li>Delete</li>
* <li>Search by resource type with no parameters</li>
* </ul>
*
* @param <T> The resource type to support
*/
public class SimpleWorkerContextProvider<T extends Resource> implements IResourceProvider {
private static final Logger log = LoggerFactory.getLogger(SimpleWorkerContextProvider.class);
private final Class<T> myResourceType;
protected final SimpleWorkerContext fhirContext;
private final String myResourceName;
protected Map<String, TreeMap<Long, T>> myIdToVersionToResourceMap = Collections.synchronizedMap(new LinkedHashMap<>());
protected Map<String, LinkedList<T>> myIdToHistory = Collections.synchronizedMap(new LinkedHashMap<>());
protected LinkedList<T> myTypeHistory = new LinkedList<>();
private AtomicLong myDeleteCount = new AtomicLong(0);
private AtomicLong mySearchCount = new AtomicLong(0);
private AtomicLong myUpdateCount = new AtomicLong(0);
private AtomicLong myCreateCount = new AtomicLong(0);
private AtomicLong myReadCount = new AtomicLong(0);
/**
* Constructor
*
* @param theFhirContext The FHIR context
* @param theResourceType The resource type to support
*/
public SimpleWorkerContextProvider(SimpleWorkerContext simpleWorkerContext, Class<T> theResourceType) {
fhirContext = simpleWorkerContext;
myResourceType = theResourceType;
// myResourceName = myFhirContext.getResourceDefinition(theResourceType).getName();
myResourceName = theResourceType.getSimpleName();
}
// @Create
// public MethodOutcome create(@ResourceParam T theResource) {
// createInternal(theResource);
//
// myCreateCount.incrementAndGet();
//
// return new MethodOutcome()
// .setCreated(true)
// .setResource(theResource)
// .setId(theResource.getIdElement());
// }
@Override
public Class<T> getResourceType() {
return myResourceType;
}
@Read
public T read(@IdParam IIdType theId, RequestDetails theRequestDetails) {
org.hl7.fhir.r5.model.Resource theResource = fhirContext.fetchResourceById(this.myResourceName,theId.getIdPart());
@SuppressWarnings("unchecked")
T retVal = (T) VersionConvertor_40_50.convertResource(theResource);
// TreeMap<Long, T> versions = myIdToVersionToResourceMap.get(theId.getIdPart());
// if (versions == null || versions.isEmpty()) {
// throw new ResourceNotFoundException(theId);
// }
//
// T retVal;
// if (theId.hasVersionIdPart()) {
// Long versionId = theId.getVersionIdPartAsLong();
// if (!versions.containsKey(versionId)) {
// throw new ResourceNotFoundException(theId);
// } else {
// T resource = versions.get(versionId);
// if (resource == null) {
// throw new ResourceGoneException(theId);
// }
// retVal = resource;
// }
//
// } else {
// retVal = versions.lastEntry().getValue();
// }
myReadCount.incrementAndGet();
// retVal = fireInterceptorsAndFilterAsNeeded(retVal, theRequestDetails);
// if (retVal == null) {
// throw new ResourceNotFoundException(theId);
// }
return retVal;
}
public List<T> search() {
List<org.hl7.fhir.r5.model.Resource> resources = new ArrayList<org.hl7.fhir.r5.model.Resource>();
switch(this.myResourceName) {
case "ImplementationGuide":
resources.addAll(fhirContext.allImplementationGuides());
break;
case "StructureDefinition":
resources.addAll(fhirContext.allStructures());
break;
case "StructureMap":
resources.addAll(fhirContext.listTransforms());
break;
case "ConceptMap":
resources.addAll(fhirContext.listMaps());
break;
case "Questionnaire":
List<CanonicalResource> confResources = fhirContext.allConformanceResources();
confResources.removeIf(filter -> !filter.getClass().equals(Questionnaire.class));
resources.addAll(confResources);
break;
default:
log.error(this.myResourceName + " not supported");
return null;
}
List<T> result = new ArrayList<T>();
for (org.hl7.fhir.r5.model.Resource resource: resources) {
@SuppressWarnings("unchecked")
T retVal = (T) VersionConvertor_40_50.convertResource(resource);
result.add(retVal);
}
return result;
}
@Search
public List<T> searchAll(RequestDetails theRequestDetails) {
List<T> retVal = search();
mySearchCount.incrementAndGet();
return retVal;
// return fireInterceptorsAndFilterAsNeeded(retVal, theRequestDetails);
}
}
// @Search
// public List<T> searchById(
// @RequiredParam(name = "_id") TokenAndListParam theIds, RequestDetails theRequestDetails) {
//
// List<T> retVal = new ArrayList<>();
//
// for (TreeMap<Long, T> next : myIdToVersionToResourceMap.values()) {
// if (next.isEmpty() == false) {
// T nextResource = next.lastEntry().getValue();
//
// boolean matches = true;
// if (theIds != null && theIds.getValuesAsQueryTokens().size() > 0) {
// for (TokenOrListParam nextIdAnd : theIds.getValuesAsQueryTokens()) {
// matches = false;
// for (TokenParam nextOr : nextIdAnd.getValuesAsQueryTokens()) {
// if (nextOr.getValue().equals(nextResource.getIdElement().getIdPart())) {
// matches = true;
// }
// }
// if (!matches) {
// break;
// }
// }
// }
//
// if (!matches) {
// continue;
// }
//
// retVal.add(nextResource);
// }
// }
//
// mySearchCount.incrementAndGet();
//
// return fireInterceptorsAndFilterAsNeeded(retVal, theRequestDetails);
// }
// private IIdType store(@ResourceParam T theResource, String theIdPart, Long theVersionIdPart) {
// IIdType id = myFhirContext.getVersion().newIdType();
// String versionIdPart = Long.toString(theVersionIdPart);
// id.setParts(null, myResourceName, theIdPart, versionIdPart);
// if (theResource != null) {
// theResource.setId(id);
// }
//
// /*
// * This is a bit of magic to make sure that the versionId attribute
// * in the resource being stored accurately represents the version
// * that was assigned by this provider
// */
// if (theResource != null) {
// if (myFhirContext.getVersion().getVersion() == FhirVersionEnum.DSTU2) {
// ResourceMetadataKeyEnum.VERSION.put((IResource) theResource, versionIdPart);
// } else {
// BaseRuntimeChildDefinition metaChild = myFhirContext.getResourceDefinition(myResourceType).getChildByName("meta");
// List<IBase> metaValues = metaChild.getAccessor().getValues(theResource);
// if (metaValues.size() > 0) {
// IBase meta = metaValues.get(0);
// BaseRuntimeElementCompositeDefinition<?> metaDef = (BaseRuntimeElementCompositeDefinition<?>) myFhirContext.getElementDefinition(meta.getClass());
// BaseRuntimeChildDefinition versionIdDef = metaDef.getChildByName("versionId");
// List<IBase> versionIdValues = versionIdDef.getAccessor().getValues(meta);
// if (versionIdValues.size() > 0) {
// IPrimitiveType<?> versionId = (IPrimitiveType<?>) versionIdValues.get(0);
// versionId.setValueAsString(versionIdPart);
// }
// }
// }
// }
//
// ourLog.info("Storing resource with ID: {}", id.getValue());
//
// // Store to ID->version->resource map
// TreeMap<Long, T> versionToResource = getVersionToResource(theIdPart);
// versionToResource.put(theVersionIdPart, theResource);
//
// // Store to type history map
// myTypeHistory.addFirst(theResource);
//
// // Store to ID history map
// myIdToHistory.computeIfAbsent(theIdPart, t -> new LinkedList<>());
// myIdToHistory.get(theIdPart).addFirst(theResource);
//
// // Return the newly assigned ID including the version ID
// return id;
// }
//
// /**
// * @param theConditional This is provided only so that subclasses can implement if they want
// */
// @Update
// public MethodOutcome update(
// @ResourceParam T theResource,
// @ConditionalUrlParam String theConditional) {
//
// ValidateUtil.isTrueOrThrowInvalidRequest(isBlank(theConditional), "This server doesn't support conditional update");
//
// boolean created = updateInternal(theResource);
// myUpdateCount.incrementAndGet();
//
// return new MethodOutcome()
// .setCreated(created)
// .setResource(theResource)
// .setId(theResource.getIdElement());
// }
//
// private boolean updateInternal(@ResourceParam T theResource) {
// String idPartAsString = theResource.getIdElement().getIdPart();
// TreeMap<Long, T> versionToResource = getVersionToResource(idPartAsString);
//
// Long versionIdPart;
// boolean created;
// if (versionToResource.isEmpty()) {
// versionIdPart = 1L;
// created = true;
// } else {
// versionIdPart = versionToResource.lastKey() + 1L;
// created = false;
// }
//
// IIdType id = store(theResource, idPartAsString, versionIdPart);
// theResource.setId(id);
// return created;
// }
//
// /**
// * This is a utility method that can be used to store a resource without
// * having to use the outside API. In this case, the storage happens without
// * any interaction with interceptors, etc.
// *
// * @param theResource The resource to store. If the resource has an ID, that ID is updated.
// * @return Return the ID assigned to the stored resource
// */
// public IIdType store(T theResource) {
// if (theResource.getIdElement().hasIdPart()) {
// updateInternal(theResource);
// } else {
// createInternal(theResource);
// }
// return theResource.getIdElement();
// }
//
// /**
// * Returns an unmodifiable list containing the current version of all resources stored in this provider
// *
// * @since 4.1.0
// */
// public List<T> getStoredResources() {
// List<T> retVal = new ArrayList<>();
// for (TreeMap<Long, T> next : myIdToVersionToResourceMap.values()) {
// retVal.add(next.lastEntry().getValue());
// }
// return Collections.unmodifiableList(retVal);
// }
//
// private static <T extends IBaseResource> T fireInterceptorsAndFilterAsNeeded(T theResource, RequestDetails theRequestDetails) {
// List<T> output = fireInterceptorsAndFilterAsNeeded(Lists.newArrayList(theResource), theRequestDetails);
// if (output.size() == 1) {
// return theResource;
// } else {
// return null;
// }
// }
//
// private static <T extends IBaseResource> List<T> fireInterceptorsAndFilterAsNeeded(List<T> theResources, RequestDetails theRequestDetails) {
// ArrayList<T> resourcesToReturn = new ArrayList<>(theResources);
//
// if (theRequestDetails != null) {
// IInterceptorBroadcaster interceptorBroadcaster = theRequestDetails.getInterceptorBroadcaster();
//
// // Call the STORAGE_PREACCESS_RESOURCES pointcut (used for consent/auth interceptors)
// SimplePreResourceAccessDetails preResourceAccessDetails = new SimplePreResourceAccessDetails(resourcesToReturn);
// HookParams params = new HookParams()
// .add(RequestDetails.class, theRequestDetails)
// .addIfMatchesType(ServletRequestDetails.class, theRequestDetails)
// .add(IPreResourceAccessDetails.class, preResourceAccessDetails);
// interceptorBroadcaster.callHooks(Pointcut.STORAGE_PREACCESS_RESOURCES, params);
// preResourceAccessDetails.applyFilterToList();
//
// // Call the STORAGE_PREACCESS_RESOURCES pointcut (used for consent/auth interceptors)
// SimplePreResourceShowDetails preResourceShowDetails = new SimplePreResourceShowDetails(resourcesToReturn);
// HookParams preShowParams = new HookParams()
// .add(RequestDetails.class, theRequestDetails)
// .addIfMatchesType(ServletRequestDetails.class, theRequestDetails)
// .add(IPreResourceShowDetails.class, preResourceShowDetails);
// interceptorBroadcaster.callHooks(Pointcut.STORAGE_PRESHOW_RESOURCES, preShowParams);
//
// }
//
// return resourcesToReturn;
// }
//}
| 35.163934 | 153 | 0.714219 |
03c77cf2787ea5a03dc2a5b059e19978d878d38e
| 1,905 |
package org.dstadler.poi.fuzz;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.xdgf.usermodel.section.GeometrySection;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import com.microsoft.schemas.office.visio.x2012.main.CellType;
import com.microsoft.schemas.office.visio.x2012.main.RowType;
import com.microsoft.schemas.office.visio.x2012.main.SectionType;
class FuzzTest {
@Test
public void test() {
Fuzz.fuzzerTestOneInput(new byte[] {});
Fuzz.fuzzerTestOneInput(new byte[] {1});
Fuzz.fuzzerTestOneInput(new byte[] {'P', 'K'});
}
@Test
public void testLog() {
// should not be logged
Logger LOG = LogManager.getLogger(FuzzTest.class);
LOG.atError().log("Test log output which should not be visible -----------------------");
}
@Disabled("Fails in Apache POI 5.2.0 and current snapshots if poi-ooxml-lite is used")
@Test
public void testSnapshot() {
SectionType sectionType = mock(SectionType.class);
RowType rowType = mock(RowType.class);
when(sectionType.getCellArray()).thenReturn(new CellType[0]);
when(sectionType.getRowArray()).thenReturn(new RowType[] {
rowType
});
when(rowType.getIX()).thenReturn(0L);
when(rowType.getT()).thenReturn("ArcTo");
when(rowType.getCellArray()).thenReturn(new CellType[0]);
GeometrySection section = new GeometrySection(sectionType, null);
assertNotNull(section);
}
@Disabled("Local test for verifying a slow run")
@Test
public void testSlowUnit() throws IOException {
Fuzz.fuzzerTestOneInput(FileUtils.readFileToByteArray(new File("corpus/032f94b25018b76e1638f5ae7969336cc1ebefc2")));
}
}
| 32.288136 | 118 | 0.753806 |
34cff48a1b19c17ea954306d41c05ff9c9f10bb4
| 1,640 |
package com.mvp;
import android.os.Handler;
import android.os.Looper;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.Executors;
public abstract class MvpPresenterFactory<V extends MvpView, T extends MvpPresenter<V>> implements IMvpPresenterFactory<V, T> {
private final IMvpEventBus eventBus;
public MvpPresenterFactory(IMvpEventBus eventBus){
this.eventBus = eventBus;
}
@SuppressWarnings("unchecked")
public final T build() {
T presenterImpl = create();
try {
String simpleName = presenterImpl.getClass().getSimpleName();
if (simpleName.contains("$MockitoMock$")){
Events.bind(presenterImpl, eventBus, new Handler(Looper.myLooper()), Executors.newSingleThreadExecutor());
return presenterImpl;
}else {
Class<?> clazz = Class.forName(presenterImpl.getClass().getName() + "Proxy");
Constructor<?> constructor = clazz.getDeclaredConstructors()[0];
T presenterProxy = (T) constructor.newInstance(presenterImpl);
presenterProxy.onInitialize();
return presenterProxy;
}
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
} catch (InstantiationException e) {
throw new IllegalStateException(e);
} catch (InvocationTargetException e) {
throw new IllegalStateException(e);
}
}
}
| 37.272727 | 127 | 0.64878 |
018c8e96c593ca0fc28ce79e7ed8414b3cfc2454
| 1,489 |
package com.deadmandungeons.deadmanplugin.command;
import org.bukkit.command.CommandSender;
/**
* This interface defines a Command. Each Command must be registered through the plugin's {@link DeadmanExecutor} instance.
* A standard Command must also define a {@link CommandInfo} annotation which tells the executor the requirements of how
* the command should be executed. The {@link SubCommandInfo} annotation (a member of the CommandInfo annotation) defines the
* separate sub commands and the required arguments for each.
* @author Jon
*/
public interface Command {
/**
* Execute a command as the given {@link CommandSender}. Each command has a specific
* set of argument Objects defined in the classes {@link CommandInfo} annotation. The
* provided Arguments parameter is guaranteed to have a valid set of argument objects
* (if the parameter is not null) based on the defined CommandInfo.
* @param sender - the CommandSender executing the command
* @param args - An {@link Arguments} object containing a valid set of arguments based on the
* defined {@link CommandInfo}, and the index of the matching {@link SubCommandInfo} based on the array of arguments.
* If this Command does not define any SubCommandInfo, this will be null as there are no arguments to the command.
* @return true if the command was executed successfully, and false otherwise.
*/
public boolean execute(CommandSender sender, Arguments args);
}
| 53.178571 | 125 | 0.751511 |
0d822755efa9f1d5aebe2713502a8882b6e95969
| 1,713 |
/**
* Copyright 2011, Big Switch Networks, Inc.
* Originally created by David Erickson, Stanford University
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
**/
package net.floodlightcontroller.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
*
* @author David Erickson (daviderickson@cs.stanford.edu)
*/
public enum BundleAction {
START,
STOP,
UNINSTALL,
REFRESH;
public static List<BundleAction> getAvailableActions(BundleState state) {
List<BundleAction> actions = new ArrayList<BundleAction>();
if (Arrays.binarySearch(new BundleState[] {
BundleState.ACTIVE, BundleState.STARTING,
BundleState.UNINSTALLED }, state) < 0) {
actions.add(START);
}
if (Arrays.binarySearch(new BundleState[] {
BundleState.ACTIVE}, state) >= 0) {
actions.add(STOP);
}
if (Arrays.binarySearch(new BundleState[] {
BundleState.UNINSTALLED}, state) < 0) {
actions.add(UNINSTALL);
}
// Always capable of refresh?
actions.add(REFRESH);
return actions;
}
}
| 31.145455 | 78 | 0.649737 |
07b566f4e46c1cbf36ed1f56ba08a30a141d1cca
| 1,905 |
package io.searchbox.cluster;
import com.google.common.collect.ImmutableMap;
import io.searchbox.client.JestResult;
import io.searchbox.common.AbstractIntegrationTest;
import io.searchbox.indices.reindex.Reindex;
import org.elasticsearch.index.reindex.ReindexPlugin;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.test.ESIntegTestCase;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
@ESIntegTestCase.ClusterScope(scope = ESIntegTestCase.Scope.TEST, numDataNodes = 1)
public class TaskInformationIntegrationTest extends AbstractIntegrationTest {
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
final ArrayList<Class<? extends Plugin>> plugins = new ArrayList<>(super.nodePlugins());
plugins.add(ReindexPlugin.class);
return plugins;
}
@Test
public void shouldReturnTaskInformation() throws IOException {
String sourceIndex = "test_source_index";
String destIndex = "test_dest_index";
String documentType = "test_type";
String documentId = "test_id";
createIndex(sourceIndex);
index(sourceIndex, documentType, documentId, "{}");
flushAndRefresh(sourceIndex);
ImmutableMap<String, Object> source = ImmutableMap.of("index", sourceIndex);
ImmutableMap<String, Object> dest = ImmutableMap.of("index", destIndex);
Reindex reindex = new Reindex.Builder(source, dest).refresh(true).waitForCompletion(false).build();
JestResult result = client.execute(reindex);
String task = (String) result.getValue("task");
assertNotNull(task);
JestResult taskInformation = client.execute(new TasksInformation.Builder().task(task).build());
Boolean completed = (Boolean) taskInformation.getValue("completed");
assertNotNull(completed);
}
}
| 38.1 | 107 | 0.730184 |
8d009a3a3b1f2d7c4968f932d56412b8d3a36691
| 8,653 |
package org.sagebionetworks.bridge.models.upload;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertSame;
import static org.testng.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.common.collect.ImmutableList;
import org.springframework.validation.MapBindingResult;
import org.testng.annotations.Test;
import org.sagebionetworks.bridge.dynamodb.DynamoUpload2;
import org.sagebionetworks.bridge.exceptions.InvalidEntityException;
import org.sagebionetworks.bridge.json.BridgeObjectMapper;
import org.sagebionetworks.bridge.json.JsonUtils;
import org.sagebionetworks.bridge.models.healthdata.HealthDataRecord;
import org.sagebionetworks.bridge.validators.UploadValidationStatusValidator;
@SuppressWarnings({ "ConstantConditions", "unchecked" })
public class UploadValidationStatusTest {
@Test
public void builder() {
UploadValidationStatus status = new UploadValidationStatus.Builder().withId("test-upload")
.withMessageList(Collections.<String>emptyList()).withStatus(UploadStatus.SUCCEEDED).build();
assertEquals(status.getId(), "test-upload");
assertTrue(status.getMessageList().isEmpty());
assertEquals(status.getStatus(), UploadStatus.SUCCEEDED);
assertNull(status.getRecord());
}
@Test
public void withOptionalValues() {
HealthDataRecord dummyRecord = HealthDataRecord.create();
UploadValidationStatus status = new UploadValidationStatus.Builder().withId("happy-case-2")
.withMessageList(ImmutableList.of("foo", "bar", "baz")).withStatus(UploadStatus.VALIDATION_FAILED)
.withRecord(dummyRecord).build();
assertEquals(status.getId(), "happy-case-2");
assertEquals(status.getStatus(), UploadStatus.VALIDATION_FAILED);
assertSame(status.getRecord(), dummyRecord);
List<String> messageList = status.getMessageList();
assertEquals(messageList.size(), 3);
assertEquals(messageList.get(0), "foo");
assertEquals(messageList.get(1), "bar");
assertEquals(messageList.get(2), "baz");
}
@Test
public void fromUpload() {
// make upload
DynamoUpload2 upload2 = new DynamoUpload2();
upload2.setUploadId("from-upload");
upload2.appendValidationMessages(Collections.singletonList("foo"));
upload2.setStatus(UploadStatus.SUCCEEDED);
// construct and validate
UploadValidationStatus status = UploadValidationStatus.from(upload2, null);
assertEquals(status.getId(), "from-upload");
assertEquals(status.getStatus(), UploadStatus.SUCCEEDED);
assertNull(status.getRecord());
assertEquals(status.getMessageList().size(), 1);
assertEquals(status.getMessageList().get(0), "foo");
}
@Test
public void fromUploadWithRecord() {
// make upload
DynamoUpload2 upload2 = new DynamoUpload2();
upload2.setUploadId("from-upload-with-record");
upload2.appendValidationMessages(Collections.singletonList("hasRecord"));
upload2.setStatus(UploadStatus.SUCCEEDED);
HealthDataRecord dummyRecord = HealthDataRecord.create();
// construct and validate
UploadValidationStatus status = UploadValidationStatus.from(upload2, dummyRecord);
assertEquals(status.getId(), "from-upload-with-record");
assertEquals(status.getStatus(), UploadStatus.SUCCEEDED);
assertSame(status.getRecord(), dummyRecord);
assertEquals(status.getMessageList().size(), 1);
assertEquals(status.getMessageList().get(0), "hasRecord");
}
@Test(expectedExceptions = InvalidEntityException.class)
public void fromNullUpload() {
UploadValidationStatus.from(null, null);
}
@Test(expectedExceptions = InvalidEntityException.class)
public void nullMessageList() {
new UploadValidationStatus.Builder().withId("test-upload").withMessageList(null)
.withStatus(UploadStatus.SUCCEEDED).build();
}
@Test(expectedExceptions = InvalidEntityException.class)
public void messageListWithNullString() {
List<String> list = new ArrayList<>();
list.add(null);
new UploadValidationStatus.Builder().withId("test-upload").withMessageList(list)
.withStatus(UploadStatus.SUCCEEDED).build();
}
@Test(expectedExceptions = InvalidEntityException.class)
public void messageListWithEmptyString() {
List<String> list = new ArrayList<>();
list.add("");
new UploadValidationStatus.Builder().withId("test-upload").withMessageList(list)
.withStatus(UploadStatus.SUCCEEDED).build();
}
@Test(expectedExceptions = InvalidEntityException.class)
public void nullId() {
new UploadValidationStatus.Builder().withId(null).withMessageList(Collections.singletonList("foo"))
.withStatus(UploadStatus.SUCCEEDED).build();
}
@Test(expectedExceptions = InvalidEntityException.class)
public void emptyId() {
new UploadValidationStatus.Builder().withId("").withMessageList(Collections.singletonList("foo"))
.withStatus(UploadStatus.SUCCEEDED).build();
}
@Test(expectedExceptions = InvalidEntityException.class)
public void nullStatus() {
new UploadValidationStatus.Builder().withId("test-upload").withMessageList(Collections.singletonList("foo"))
.withStatus(null).build();
}
// branch coverage
@Test
public void validatorSupportsClass() {
assertTrue(UploadValidationStatusValidator.INSTANCE.supports(UploadValidationStatus.class));
}
// branch coverage
@Test
public void validatorDoesntSupportWrongClass() {
assertFalse(UploadValidationStatusValidator.INSTANCE.supports(String.class));
}
// branch coverage
// we call the validator directly, since Validate.validateThrowingException filters out nulls and wrong types
@Test
public void validateNull() {
MapBindingResult errors = new MapBindingResult(new HashMap<>(), "UploadValidationStatus");
UploadValidationStatusValidator.INSTANCE.validate(null, errors);
assertTrue(errors.hasErrors());
}
// branch coverage
// we call the validator directly, since Validate.validateThrowingException filters out nulls and wrong types
@Test
public void validateWrongClass() {
MapBindingResult errors = new MapBindingResult(new HashMap<>(), "UploadValidationStatus");
UploadValidationStatusValidator.INSTANCE.validate("this is the wrong class", errors);
assertTrue(errors.hasErrors());
}
@Test
public void serialization() throws Exception {
// start with JSON
String jsonText = "{\n" +
" \"id\":\"json-upload\",\n" +
" \"status\":\"SUCCEEDED\",\n" +
" \"messageList\":[\n" +
" \"foo\",\n" +
" \"bar\",\n" +
" \"baz\"\n" +
" ]\n" +
"}";
// convert to POJO
UploadValidationStatus status = BridgeObjectMapper.get().readValue(jsonText, UploadValidationStatus.class);
assertEquals(status.getId(), "json-upload");
assertEquals(status.getStatus(), UploadStatus.SUCCEEDED);
List<String> messageList = status.getMessageList();
assertEquals(messageList.size(), 3);
assertEquals(messageList.get(0), "foo");
assertEquals(messageList.get(1), "bar");
assertEquals(messageList.get(2), "baz");
// convert back to JSON
String convertedJson = BridgeObjectMapper.get().writeValueAsString(status);
// then convert to a map so we can validate the raw JSON
Map<String, Object> jsonMap = BridgeObjectMapper.get().readValue(convertedJson, JsonUtils.TYPE_REF_RAW_MAP);
assertEquals(jsonMap.size(), 4);
assertEquals(jsonMap.get("type"), "UploadValidationStatus");
assertEquals(jsonMap.get("id"), "json-upload");
assertEquals(jsonMap.get("status"), "succeeded");
List<String> messageJsonList = (List<String>) jsonMap.get("messageList");
assertEquals(messageJsonList.size(), 3);
assertEquals(messageJsonList.get(0), "foo");
assertEquals(messageJsonList.get(1), "bar");
assertEquals(messageJsonList.get(2), "baz");
}
}
| 40.816038 | 116 | 0.683694 |
4bdb712a4569eadcc6ebac1df7f8430827932f2f
| 13,920 |
/*
* 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 net.purnama.gui.inner.detail;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.jersey.api.client.ClientResponse;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import net.purnama.gui.inner.detail.table.ItemInvoiceSalesDraftTablePanel;
import net.purnama.gui.inner.detail.util.CurrencyComboBoxPanel;
import net.purnama.gui.inner.detail.util.DatePanel;
import net.purnama.gui.inner.detail.util.LabelDecimalTextFieldPanel;
import net.purnama.gui.inner.detail.util.NumberingComboBoxPanel;
import net.purnama.gui.inner.detail.util.PartnerComboBoxPanel;
import net.purnama.gui.inner.home.InvoiceSalesDraftHome;
import net.purnama.gui.main.MainTabbedPane;
import net.purnama.model.transactional.draft.InvoiceSalesDraftEntity;
import net.purnama.rest.RestClient;
import net.purnama.util.GlobalFields;
/**
*
* @author Purnama
*/
public class InvoiceSalesDraftDetail extends InvoiceDraftDetailPanel{
private final DatePanel duedatepanel;
private final LabelDecimalTextFieldPanel ratepanel;
private final PartnerComboBoxPanel partnerpanel;
private final CurrencyComboBoxPanel currencypanel;
private final NumberingComboBoxPanel numberingpanel;
private final ItemInvoiceSalesDraftTablePanel iteminvoicesalesdrafttablepanel;
private InvoiceSalesDraftEntity invoicesalesdraft;
private final String id;
public InvoiceSalesDraftDetail(String id) {
super(GlobalFields.PROPERTIES.getProperty("LABEL_PANEL_INVOICESALESDRAFTDETAIL"));
this.id = id;
partnerpanel = new PartnerComboBoxPanel(true, false, false);
duedatepanel = new DatePanel(
Calendar.getInstance(),
GlobalFields.PROPERTIES.getProperty("LABEL_DUEDATE"),
true);
middledetailpanel.add(partnerpanel);
middledetailpanel.add(duedatepanel);
numberingpanel = new NumberingComboBoxPanel(8);
currencypanel = new CurrencyComboBoxPanel();
ratepanel = new LabelDecimalTextFieldPanel(GlobalFields.PROPERTIES.getProperty("LABEL_RATE"),
1, true, this);
rightdetailpanel.add(numberingpanel);
rightdetailpanel.add(currencypanel);
rightdetailpanel.add(ratepanel);
iteminvoicesalesdrafttablepanel = new ItemInvoiceSalesDraftTablePanel(id, discountsubtotalpanel);
tabbedpane.addTab(GlobalFields.PROPERTIES.getProperty("LABEL_CONTENT"),
iteminvoicesalesdrafttablepanel);
savebutton.addActionListener((ActionEvent e) -> {
save();
iteminvoicesalesdrafttablepanel.submitItemInvoiceSalesDraftList();
iteminvoicesalesdrafttablepanel.submitDeletedItemInvoiceSalesDraftList();
JOptionPane.showMessageDialog(GlobalFields.MAINFRAME,
GlobalFields.PROPERTIES.getProperty("NOTIFICATION_SAVED"),
"", JOptionPane.INFORMATION_MESSAGE);
});
closebutton.addActionListener((ActionEvent e) -> {
save();
iteminvoicesalesdrafttablepanel.submitItemInvoiceSalesDraftList();
iteminvoicesalesdrafttablepanel.submitDeletedItemInvoiceSalesDraftList();
int result = JOptionPane.showConfirmDialog(null, GlobalFields.
PROPERTIES.getProperty("QUESTION_CLOSEINVOICE"),
"", JOptionPane.YES_NO_OPTION);
if(result == JOptionPane.YES_OPTION){
close();
}
});
deletebutton.addActionListener((ActionEvent e) -> {
int result = JOptionPane.showConfirmDialog(null, GlobalFields.
PROPERTIES.getProperty("QUESTION_DELETEINVOICE"),
"", JOptionPane.YES_NO_OPTION);
if(result == JOptionPane.YES_OPTION){
delete();
}
});
load();
}
@Override
public void refresh(){
partnerpanel.refresh();
currencypanel.refresh();
numberingpanel.refresh();
load();
}
@Override
protected final void close(){
SwingWorker<Boolean, String> saveworker = new SwingWorker<Boolean, String>(){
ClientResponse response;
@Override
protected Boolean doInBackground(){
upperpanel.showProgressBar();
publish(GlobalFields.PROPERTIES.getProperty("NOTIFICATION_CONNECTING"));
response = RestClient.get("closeInvoiceSalesDraft?id=" + invoicesalesdraft.getId());
return true;
}
@Override
protected void process(List<String> chunks) {
chunks.stream().forEach((number) -> {
upperpanel.setNotifLabel(number);
});
}
@Override
protected void done() {
upperpanel.hideProgressBar();
if(response == null){
upperpanel.setNotifLabel(GlobalFields.PROPERTIES.getProperty("NOTIFICATION_TIMEDOUT"));
}
else if(response.getStatus() != 200) {
upperpanel.setNotifLabel("");
String output = response.getEntity(String.class);
JOptionPane.showMessageDialog(GlobalFields.MAINFRAME,
output, GlobalFields.PROPERTIES.getProperty("NOTIFICATION_HTTPERROR")
+ response.getStatus(),
JOptionPane.ERROR_MESSAGE);
}
else{
upperpanel.setNotifLabel("");
String output = response.getEntity(String.class);
changepanel(output);
}
}
};
saveworker.execute();
}
@Override
protected final void save(){
SwingWorker<Boolean, String> saveworker = new SwingWorker<Boolean, String>(){
ClientResponse response;
@Override
protected Boolean doInBackground(){
// progressbar.setVisible(true);
upperpanel.showProgressBar();
publish(GlobalFields.PROPERTIES.getProperty("NOTIFICATION_CONNECTING"));
invoicesalesdraft.setCurrency(currencypanel.getComboBoxValue());
invoicesalesdraft.setDate(datepanel.getCalendar());
invoicesalesdraft.setDiscount(discountsubtotalpanel.getDiscount());
invoicesalesdraft.setDuedate(duedatepanel.getCalendar());
invoicesalesdraft.setFreight(expensespanel.getFreight());
invoicesalesdraft.setNote(notepanel.getNote());
invoicesalesdraft.setNumbering(numberingpanel.getComboBoxValue());
invoicesalesdraft.setPartner(partnerpanel.getComboBoxValue());
invoicesalesdraft.setRate(ratepanel.getTextFieldValue());
invoicesalesdraft.setRounding(expensespanel.getRounding());
invoicesalesdraft.setStatus(true);
invoicesalesdraft.setSubtotal(discountsubtotalpanel.getSubtotal());
invoicesalesdraft.setTax(expensespanel.getTax());
response = RestClient.put("updateInvoiceSalesDraft", invoicesalesdraft);
return true;
}
@Override
protected void process(List<String> chunks) {
chunks.stream().forEach((number) -> {
upperpanel.setNotifLabel(number);
});
}
@Override
protected void done() {
// progressbar.setVisible(false);
upperpanel.hideProgressBar();
if(response == null){
upperpanel.setNotifLabel(GlobalFields.PROPERTIES.getProperty("NOTIFICATION_TIMEDOUT"));
}
else if(response.getStatus() != 200) {
upperpanel.setNotifLabel(GlobalFields.PROPERTIES.getProperty("NOTIFICATION_HTTPERROR")
+ response.getStatus());
}
else{
upperpanel.setNotifLabel("");
}
}
};
saveworker.execute();
}
public final void load(){
SwingWorker<Boolean, String> worker = new SwingWorker<Boolean, String>() {
ClientResponse response;
@Override
protected Boolean doInBackground(){
upperpanel.showProgressBar();
publish(GlobalFields.PROPERTIES.getProperty("NOTIFICATION_CONNECTING"));
response = RestClient.get("getInvoiceSalesDraft?id=" + id);
return true;
}
@Override
protected void process(List<String> chunks) {
chunks.stream().forEach((number) -> {
upperpanel.setNotifLabel(number);
});
}
@Override
protected void done() {
upperpanel.hideProgressBar();
if(response == null){
upperpanel.setNotifLabel(GlobalFields.PROPERTIES.getProperty("NOTIFICATION_TIMEDOUT"));
}
else if(response.getStatus() != 200) {
upperpanel.setNotifLabel(GlobalFields.PROPERTIES.getProperty("NOTIFICATION_HTTPERROR")
+ response.getStatus());
}
else{
upperpanel.setNotifLabel("");
String output = response.getEntity(String.class);
ObjectMapper mapper = new ObjectMapper();
try{
invoicesalesdraft = mapper.readValue(output, InvoiceSalesDraftEntity.class);
notepanel.setNote(invoicesalesdraft.getNote());
datepanel.setDate(invoicesalesdraft.getDate());
warehousepanel.setTextFieldValue(invoicesalesdraft.getWarehouse().getCode());
idpanel.setTextFieldValue(invoicesalesdraft.getId());
partnerpanel.setComboBoxValue(invoicesalesdraft.getPartner());
duedatepanel.setDate(invoicesalesdraft.getDuedate());
numberingpanel.setComboBoxValue(invoicesalesdraft.getNumbering());
currencypanel.setComboBoxValue(invoicesalesdraft.getCurrency());
ratepanel.setTextFieldValue(invoicesalesdraft.getRate());
expensespanel.setRounding(invoicesalesdraft.getRounding());
expensespanel.setFreight(invoicesalesdraft.getFreight());
expensespanel.setTax(invoicesalesdraft.getTax());
discountsubtotalpanel.setSubtotal(invoicesalesdraft.getSubtotal());
discountsubtotalpanel.setDiscount(invoicesalesdraft.getDiscount());
}
catch(IOException e){
}
}
}
};
worker.execute();
}
@Override
protected void home() {
MainTabbedPane tabbedPane = (MainTabbedPane)SwingUtilities.
getAncestorOfClass(MainTabbedPane.class, this);
tabbedPane.changeTabPanel(getIndex(), new InvoiceSalesDraftHome());
}
@Override
protected final void delete() {
SwingWorker<Boolean, String> saveworker = new SwingWorker<Boolean, String>(){
ClientResponse response;
@Override
protected Boolean doInBackground() {
upperpanel.showProgressBar();
publish(GlobalFields.PROPERTIES.getProperty("NOTIFICATION_CONNECTING"));
response = RestClient.delete("deleteInvoiceSalesDraft?id=" + invoicesalesdraft.getId());
return true;
}
@Override
protected void process(List<String> chunks) {
chunks.stream().forEach((number) -> {
upperpanel.setNotifLabel(number);
});
}
@Override
protected void done() {
upperpanel.hideProgressBar();
if(response == null){
upperpanel.setNotifLabel(GlobalFields.PROPERTIES.getProperty("NOTIFICATION_TIMEDOUT"));
}
else if(response.getStatus() != 200) {
upperpanel.setNotifLabel(GlobalFields.PROPERTIES.getProperty("NOTIFICATION_HTTPERROR")
+ response.getStatus());
}
else{
upperpanel.setNotifLabel("");
home();
}
}
};
saveworker.execute();
}
@Override
protected void changepanel(String id) {
MainTabbedPane tabbedPane = (MainTabbedPane)SwingUtilities.
getAncestorOfClass(MainTabbedPane.class, this);
tabbedPane.changeTabPanel(getIndex(), new InvoiceSalesDetail(id));
}
}
| 38.882682 | 107 | 0.579095 |
899d2f85d119f8fbb64fd4f7a982993dae273d8f
| 5,978 |
package pages;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.MediaEntityBuilder;
import com.aventstack.extentreports.Status;
import base.BasePage;
import commons.ExceptionCode;
import commons.ScreenShot;
public class ReviewAndApprove extends BasePage {
String concate=".";
String orderDescr = "";
String Reviewer = "Reviewer";
WebElement webElement;
static String taskListXpath = "/html/body/div/div/div[3]/div[1]/pal-narrow-layout/div/ng-transclude/div/div/div/div/div[2]/div[2]/div/a/span";
static String approveTaskListXpath = "/html/body/div/bw-purchase-requisition-details/section/div[1]/pal-title-bar/div/div/div[2]/div/div[2]/pal-title-bar-actions/bw-purchase-requisition-details-actions/div/pal-actions/div/div/div/div[1]/div/button";
static String allTasksXpath= "/html/body/div/div/bw-task-list-all/div/div/div[1]/div/span[1]";
static String taskButtonXpath="document.querySelector('alusta-navigation').shadowRoot.querySelector('div > nav > div.pt-navbar-nav.main-nav > ul > li:nth-child(3) > a')";
public ReviewAndApprove(WebDriver driver) {
super(driver);
}
public String review(JavascriptExecutor javascriptExecutor,String reviewer,String password,String orderDescription,String docType,String PRNumber,String status,String url,int i,int j,ExtentTest test) {
try {
Login login = new Login(driver);
test.log(Status.INFO, "Login for reviewer "+j);
login.logIn(reviewer,password,url);
test.log(Status.INFO, "Login "+reviewer+" reviewer "+j);
}
catch(Exception e) {
status="FAIL";
test.log(Status.FAIL ,"Unable to login : Invalid User/Password/url. ");
try {
String errorSc =concate+ ScreenShot.attachedScreenShot(driver, "PR_REQUISITION "+i);
test.log(Status.FAIL, "Error Snapshot below:", MediaEntityBuilder.createScreenCaptureFromPath(errorSc).build());
} catch(Exception a) {
test.log(Status.INFO, "Error Screenshot not found");
}
return status;
}
// wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(taskListXpath))).click();
webElement = (WebElement) javascriptExecutor.executeScript("return "+taskButtonXpath);
webElement.click();
try {
orderDescr =GetTaskList.getTaskList( orderDescription,docType);
} catch (Exception e) {
ExceptionCode exception =new ExceptionCode(driver);
exception.exception(i, test);
e.printStackTrace();
}
if (orderDescr.toLowerCase().equalsIgnoreCase("\"" + orderDescription + "\"")) {
// test.log(Status.INFO, "Approve");
try {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(approveTaskListXpath))).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(allTasksXpath)));
test.log(Status.PASS, "PR: "+PRNumber+" reviewed by reviewer "+j);
LogOut logOut = new LogOut(driver);
logOut.logout(javascriptExecutor,docType);
}catch(Exception ex) {
ExceptionCode exception =new ExceptionCode(driver);
exception.exception(i, test);
ex.printStackTrace();
}
} else {
status="FAIL";
test.log(Status.FAIL, "NO PR Found for Reviewer"+j);
ExceptionCode exception =new ExceptionCode(driver);
exception.exception(i, test);
try {
LogOut logOut = new LogOut(driver);
logOut.logout(javascriptExecutor,docType);
}catch(Exception ex) {
ex.printStackTrace();
}
}
return status;
}
public String approve(JavascriptExecutor javascriptExecutor,String approver,String password,String orderDescription,String docType,String PRNumber,String status,String url,int i,int j,ExtentTest test) throws Exception {
try {
Login login = new Login(driver);
test.log(Status.INFO, "Loging for approver "+j);
login.logIn(approver,password,url);
test.log(Status.INFO, "Login "+approver+" approver "+j);
}
catch(Exception e) {
status="FAIL";
test.log(Status.FAIL ,"Unable to login : Invalid User/Password/url. ");
try {
String errorSc =concate+ ScreenShot.attachedScreenShot(driver, "PR_REQUISITION "+i);
test.log(Status.FAIL, "Error Snapshot below:", MediaEntityBuilder.createScreenCaptureFromPath(errorSc).build());
} catch(Exception a) {
test.log(Status.INFO, "Error Screenshot not found");
}
return status;
}
// wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(taskListXpath))).click();
webElement = (WebElement) javascriptExecutor.executeScript("return "+taskButtonXpath);
webElement.click();
try {
orderDescr =GetTaskList.getTaskList( orderDescription,docType);
} catch (Exception e) {
ExceptionCode exception =new ExceptionCode(driver);
exception.exception(i, test);
e.printStackTrace();
}
if (orderDescr.toLowerCase().equalsIgnoreCase("\"" + orderDescription + "\"")) {
ApproveTaskList approveTaskList = new ApproveTaskList(driver);
try {
approveTaskList.approveTaskList(docType);
test.log(Status.PASS, "PR: "+PRNumber+" Approved by Approver "+j);
LogOut logOut = new LogOut(driver);
logOut.logout(javascriptExecutor,docType);
} catch (Exception e) {
ExceptionCode exception =new ExceptionCode(driver);
exception.exception(i, test);
e.printStackTrace();
}
}else {
status="FAIL";
test.log(Status.FAIL, "NO PR Found for Approver"+j);
ExceptionCode exception =new ExceptionCode(driver);
exception.exception(j, test);
try {
LogOut logOut = new LogOut(driver);
logOut.logout(javascriptExecutor,docType);
}catch(Exception ex) {
ex.printStackTrace();
}
}
return status;
}
}
| 31.62963 | 250 | 0.702911 |
28c5b9a1890978d5883bb2c4342c7f6cceee6264
| 616 |
package com.yetanotherx.mapnode.converter;
import java.util.Collection;
/**
* Converts a Collection<Object> of values into a Collection<T> instance.
*
* @author yetanotherx
* @param <T>
*/
public class CollectionConverter<T> {
/**
* Converts each value of the collection using the given converter.
*
* @param converter
* @param oldColl
* @param newColl
*/
public void transform(BaseConverter<T> converter, Collection<Object> oldColl, Collection<T> newColl) {
for( Object old : oldColl ) {
newColl.add(converter.transform(old));
}
}
}
| 23.692308 | 106 | 0.644481 |
d18f66996ac79d5f2f149bace394e127e9c6a81f
| 174 |
package io.aftersound.weave.process.pipeline;
public class PipelineNotExistException extends Exception {
public PipelineNotExistException() {
super();
}
}
| 17.4 | 58 | 0.729885 |
b7b89f3f11af054f26e71ea01d508ddffbab05b3
| 2,125 |
package com.didi.carmate.dreambox.core.action;
import com.didi.carmate.dreambox.core.base.DBAction;
import com.didi.carmate.dreambox.core.base.DBConstants;
import com.didi.carmate.dreambox.core.base.DBContext;
import com.didi.carmate.dreambox.core.base.INodeCreator;
import com.didi.carmate.dreambox.core.utils.DBLogger;
import com.didi.carmate.dreambox.core.utils.DBUtils;
import com.didi.carmate.dreambox.wrapper.Log;
import com.didi.carmate.dreambox.wrapper.Wrapper;
import java.util.Map;
/**
* author: chenjing
* date: 2020/4/30
*/
public class DBLog extends DBAction {
private DBLog(DBContext dbContext) {
super(dbContext);
}
@Override
protected void doInvoke(Map<String, String> attrs) {
String level = attrs.get("level");
String tag = attrs.get("tag");
String msg = getString(attrs.get("msg"));
if (DBUtils.isEmpty(level)) {
DBLogger.e(mDBContext, "[level] is null");
return;
}
if (DBUtils.isEmpty(msg)) {
DBLogger.e(mDBContext, "[msg] is null");
return;
}
Log dbLog = Wrapper.get(mDBContext.getAccessKey()).log();
switch (level) {
case DBConstants.LOG_LEVEL_E:
dbLog.e("tag: " + tag + " msg: " + msg);
break;
case DBConstants.LOG_LEVEL_W:
dbLog.w("tag: " + tag + " msg: " + msg);
break;
case DBConstants.LOG_LEVEL_I:
dbLog.i("tag: " + tag + " msg: " + msg);
break;
case DBConstants.LOG_LEVEL_D:
dbLog.d("tag: " + tag + " msg: " + msg);
break;
case DBConstants.LOG_LEVEL_V:
dbLog.v("tag: " + tag + " msg: " + msg);
break;
default:
break;
}
}
public static class NodeCreator implements INodeCreator {
@Override
public DBLog createNode(DBContext dbContext) {
return new DBLog(dbContext);
}
}
public static String getNodeTag() {
return "log";
}
}
| 30.357143 | 65 | 0.568941 |
0a604723aeb2be8a0390b1facbd807cfe8717c91
| 668 |
package com.thoughtworks.gauge.test.common;
public class ExecutionSummary {
private boolean Success;
private String command;
private String stdout;
private String stderr;
public ExecutionSummary(String command, boolean success, String stdout, String stderr) {
this.command = command;
this.stdout = stdout;
this.Success = success;
this.stderr = stderr;
}
public boolean getSuccess() {
return Success;
}
public String getStdout() {
return stdout;
}
public String getStderr() {
return stderr;
}
public String getCommand() {
return command;
}
}
| 20.242424 | 92 | 0.63024 |
6b3cddb1ce849f6765d147b9b985a867ac33314a
| 1,619 |
/** EnumBody = "{" { EnumeratorDeclarationList } [","]
* [ ";" {ClassBodyDeclaration} ] "}"
*/
List<JCTree> enumBody(Name enumName) {
DEBUG.P(this,"enumBody(Name enumName)");
accept(LBRACE);
ListBuffer<JCTree> defs = new ListBuffer<JCTree>();
if (S.token() == COMMA) {
S.nextToken();
} else if (S.token() != RBRACE && S.token() != SEMI) {
defs.append(enumeratorDeclaration(enumName));
while (S.token() == COMMA) {
S.nextToken();
if (S.token() == RBRACE || S.token() == SEMI) break;
defs.append(enumeratorDeclaration(enumName));
}
if (S.token() != SEMI && S.token() != RBRACE) {
defs.append(syntaxError(S.pos(), "expected3",
keywords.token2string(COMMA),
keywords.token2string(RBRACE),
keywords.token2string(SEMI)));
S.nextToken();
}
}
if (S.token() == SEMI) {
S.nextToken();
while (S.token() != RBRACE && S.token() != EOF) {
defs.appendList(classOrInterfaceBodyDeclaration(enumName,
false));
if (S.pos() <= errorEndPos) {
// error recovery
skip(false, true, true, false);
}
}
}
accept(RBRACE);
DEBUG.P(0,this,"enumBody(Name enumName)");
return defs.toList();
}
| 41.512821 | 73 | 0.437307 |
2f55594dcfd893ca0c65d849a395298e887f9bd3
| 19,959 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package userinterface.HospitalAdministrativeRole;
import Business.Directory.BirthMother;
import Business.Enterprise.Enterprise;
import Business.Organization.CounselorOrganization;
import Business.Organization.Organization;
import Business.Directory.Parents;
import Business.Mail.ConfigUtility;
import Business.Mail.EmailUtility;
import Business.Mail.EmailVariables;
import Business.Role.ParentsRole;
import Business.UserAccount.UserAccount;
import Business.Role.Role;
import Business.WorkQueue.CounselorToAdmin;
import java.awt.CardLayout;
import java.io.File;
import java.util.Date;
import java.util.Properties;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.table.DefaultTableModel;
/**
*
* @author Joy
*/
public class ParentsRequestWorkAreaJPanel extends javax.swing.JPanel {
private JPanel userProcessContainer;
private CounselorOrganization organization;
private UserAccount account;
private Enterprise enterprise;
private ConfigUtility configUtil;
private EmailUtility emailUtil;
private Parents parent;
/**
* Creates new form DoctorWorkAreaJPanel
*/
public ParentsRequestWorkAreaJPanel(JPanel userProcessContainer, UserAccount account, Enterprise enterprise) {
initComponents();
this.emailUtil = new EmailUtility();
this.configUtil = new ConfigUtility();
this.userProcessContainer = userProcessContainer;
this.enterprise = enterprise;
this.account = account;
valueLabel.setText(enterprise.getName());
populateRequestTable();
}
public void populateRequestTable(){
DefaultTableModel model = (DefaultTableModel) workRequestJTable.getModel();
model.setRowCount(0);
for (CounselorToAdmin request : enterprise.getWorkQueue().getCounselorToAdmin()){
if(!(request.getParent().getUsername().equals(""))){
Object[] row = new Object[4];
row[0] = request;
row[1] = request.getParent().getUsername();
row[2] = request.getStatus();
String result = request.getRequestResult();
row[3] = result == null ? "Waiting" : result;
model.addRow(row);
}
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
workRequestJTable = new javax.swing.JTable();
btnCreate = new javax.swing.JButton();
refreshTestJButton = new javax.swing.JButton();
enterpriseLabel = new javax.swing.JLabel();
valueLabel = new javax.swing.JLabel();
txtUserName = new javax.swing.JTextField();
txtPassword = new javax.swing.JTextField();
btnView = new javax.swing.JButton();
valueLabel1 = new javax.swing.JLabel();
valueLabel2 = new javax.swing.JLabel();
txtMessage = new javax.swing.JTextField();
valueLabel3 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
setBackground(java.awt.SystemColor.activeCaption);
setMaximumSize(new java.awt.Dimension(1245, 1000));
setMinimumSize(new java.awt.Dimension(1245, 1000));
setPreferredSize(new java.awt.Dimension(1245, 1000));
workRequestJTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Message", "Sender", "Status", "Result"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(workRequestJTable);
if (workRequestJTable.getColumnModel().getColumnCount() > 0) {
workRequestJTable.getColumnModel().getColumn(0).setResizable(false);
workRequestJTable.getColumnModel().getColumn(1).setResizable(false);
workRequestJTable.getColumnModel().getColumn(2).setResizable(false);
workRequestJTable.getColumnModel().getColumn(3).setResizable(false);
}
btnCreate.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
btnCreate.setText("CREATE");
btnCreate.setEnabled(false);
btnCreate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCreateActionPerformed(evt);
}
});
refreshTestJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Refresh.jpg"))); // NOI18N
refreshTestJButton.setText("Refresh");
refreshTestJButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
refreshTestJButtonActionPerformed(evt);
}
});
enterpriseLabel.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
enterpriseLabel.setText("ENTERPRISE:");
valueLabel.setFont(new java.awt.Font("Lucida Grande", 1, 24)); // NOI18N
valueLabel.setText("<value>");
btnView.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
btnView.setText("VIEW");
btnView.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnViewActionPerformed(evt);
}
});
valueLabel1.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
valueLabel1.setText("Username");
valueLabel2.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
valueLabel2.setText("Password");
txtMessage.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtMessageActionPerformed(evt);
}
});
valueLabel3.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
valueLabel3.setText("Message");
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/left-arrow-in-circular-button-black-symbol-2.png"))); // NOI18N
jButton1.setText("Back");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(330, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(201, 201, 201)
.addComponent(valueLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(txtMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(142, 142, 142)
.addComponent(btnView, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(97, 97, 97)
.addComponent(btnCreate, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(202, 202, 202)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(valueLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(valueLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(refreshTestJButton))
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 665, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(enterpriseLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(valueLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 364, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(10, 10, 10)))
.addGap(250, 250, 250))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(187, 187, 187)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(enterpriseLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(valueLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(49, 49, 49)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(refreshTestJButton, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(41, 41, 41)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(44, 44, 44)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(valueLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(valueLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(14, 14, 14)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(valueLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtMessage, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(39, 39, 39)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnView, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnCreate, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(318, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void btnCreateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCreateActionPerformed
int selectedRow = workRequestJTable.getSelectedRow();
// if (selectedRow < 0){
// JOptionPane.showMessageDialog(null, "Please select a row from the table");
// return;
// }
CounselorToAdmin request = (CounselorToAdmin)workRequestJTable.getValueAt(selectedRow, 0);
if(txtMessage.getText().equals("")){
JOptionPane.showMessageDialog(this, "Please enter comments for the operation!");
return;
}
if(!request.getStatus().equals("Completed")){
request.setReceiver(account);
request.setMessage(txtMessage.getText());
request.setStatus("Completed");
request.setResolveDate(new Date());
request.setRequestResult("User Account created");
parent = request.getParent();
Role role = new ParentsRole();
for (Organization org : enterprise.getOrganizationDirectory().getOrganizationList()){
if(org.getName().equals("Parents Organization")){
org.getParentDirectory().addParents(parent);
org.getUserAccountDirectory().createUserAccountParents(request.getParent().getUsername(),request.getParent().getPassword() , parent , role, account.getNetwork());
}
}
sendMail(parent);
populateRequestTable();
}
else {
JOptionPane.showMessageDialog(this, "User Account already created");
}
txtUserName.setText("");
txtPassword.setText("");
txtMessage.setText("");
JOptionPane.showMessageDialog(null, "User Account created Successfully");
btnCreate.setEnabled(false);
btnView.setEnabled(true);
}//GEN-LAST:event_btnCreateActionPerformed
private void refreshTestJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshTestJButtonActionPerformed
populateRequestTable();
}//GEN-LAST:event_refreshTestJButtonActionPerformed
public void sendMail(Parents parent){
String toAddress = parent.getEmail();
String subject = "Hospital Admin Approval";
EmailVariables eVar = new EmailVariables();
String start = eVar.getStart();
String footer = eVar.getFooter();
//FileChooser filePicker = new FileChooser();
String content = " <table cellspacing=\"0\" cellpadding=\"0\" align=\"center\"><tbody><h3><tr><td>Hi "+ parent.getUsername() +"! </td></tr><tr><td>\n <h3>Your Profile ID " + parent.getParentId()
+ " and your Userid: "+parent.getUsername()+" has been approved by Hospital Admin</br></td></tr>"+"</br><tr><td>You can now login to the application with your credentials </br></td></tr></h3></tbody> <h2> Thank you! </h2>";
String message = start + content + footer;
File[] attachFiles = null;
//File selectedFile = new File("..\\images\\adopt.jpg");
//attachFiles = new File[] {selectedFile};
try {
Properties smtpProperties = configUtil.loadProperties();
emailUtil.sendEmail(smtpProperties, toAddress, subject, message, attachFiles);
} catch (Exception ex) {
JOptionPane.showMessageDialog(this,
"Error while sending the e-mail: " + ex.getMessage(),
"Error", JOptionPane.ERROR_MESSAGE);
}
}
private void btnViewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnViewActionPerformed
// TODO add your handling code here:
int selectedRow = workRequestJTable.getSelectedRow();
if (selectedRow < 0){
JOptionPane.showMessageDialog(null, "Please select a row from the table");
return;
}
CounselorToAdmin request = (CounselorToAdmin)workRequestJTable.getValueAt(selectedRow, 0);
txtUserName.setText(request.getParent().getUsername());
txtPassword.setText(request.getParent().getPassword());
btnCreate.setEnabled(true);
btnView.setEnabled(false);
}//GEN-LAST:event_btnViewActionPerformed
private void txtMessageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtMessageActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtMessageActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
userProcessContainer.remove(this);
CardLayout cardlayout = (CardLayout) userProcessContainer.getLayout();
cardlayout.previous(userProcessContainer);
}//GEN-LAST:event_jButton1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnCreate;
private javax.swing.JButton btnView;
private javax.swing.JLabel enterpriseLabel;
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JButton refreshTestJButton;
private javax.swing.JTextField txtMessage;
private javax.swing.JTextField txtPassword;
private javax.swing.JTextField txtUserName;
private javax.swing.JLabel valueLabel;
private javax.swing.JLabel valueLabel1;
private javax.swing.JLabel valueLabel2;
private javax.swing.JLabel valueLabel3;
private javax.swing.JTable workRequestJTable;
// End of variables declaration//GEN-END:variables
}
| 50.022556 | 240 | 0.651385 |
ae5ae15b9272663b91991a629a1e3134ab619741
| 1,618 |
import java.util.Scanner;
import warehouse.Shelving;
import exercise.Replication;
import java.lang.String;
import farm.Director;
public class Rhombohedral {
static double kilo = 0.7824114257027354;
String q = "";
Director r = null;
Director ora = null;
Director righ = null;
public static synchronized void main(String[] param) {
double coin = 0.9284884026816874;
String bcl = "";
String yt = "";
String z = "";
Director equally = null;
Director sb = null;
Director nlsy = null;
Director choy = null;
System.out.print("\f");
int avec = 0;
try {
avec = System.in.available();
} catch (java.lang.Exception cma) {
}
if (avec <= 0) {
System.out.println("ERROR: System.in is empty, no file was passed or it is empty");
} else {
double needDrift = 0, wordMingy = 0;
int needEntrepotRestrain = 0;
try {
java.util.Scanner keys = new java.util.Scanner(System.in);
wordMingy = keys.nextDouble();
needDrift = keys.nextDouble();
needEntrepotRestrain = keys.nextInt();
} catch (java.lang.Exception combatants) {
System.out.println(
"ERROR: There are not enough values or the values passed are in the incorrect format");
System.out.println(
" Values should be in the form mean (double) rng (double) storageLimit (int)");
return;
}
exercise.Replication yes = new exercise.Replication(10000000, wordMingy, needDrift);
warehouse.Shelving.dictatedMemoryCircumscribe(needEntrepotRestrain);
yes.jump();
}
}
}
| 29.418182 | 99 | 0.635352 |
07fe52253343b7f5ed0b4274336c820f0cc47c6e
| 1,766 |
package com.sillykid.app.entity;
import com.common.cklibrary.entity.BaseResult;
import java.util.List;
/**
* Created by Admin on 2017/11/8.
*/
public class AllCountryBean extends BaseResult<List<AllCountryBean.ResultBean>> {
public static class ResultBean {
/**
* id : 8
* parent_id : 1
* name : 日本
* level : 2
* area_code : null
* is_hot : 1
*/
private int id;
private int parent_id;
private String name;
private int level;
private String area_code;
private int is_hot;
private int status;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getParent_id() {
return parent_id;
}
public void setParent_id(int parent_id) {
this.parent_id = parent_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public String getArea_code() {
return area_code;
}
public void setArea_code(String area_code) {
this.area_code = area_code;
}
public int getIs_hot() {
return is_hot;
}
public void setIs_hot(int is_hot) {
this.is_hot = is_hot;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
}
| 19.622222 | 81 | 0.50453 |
be23445868864ffd6a1a4367b49fb85f7a059700
| 3,680 |
/*
* Copyright (C) 2012-2016 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.nifty.ssl;
import com.google.common.base.Throwables;
import org.jboss.netty.handler.ssl.SslContext;
import org.jboss.netty.handler.ssl.SslHandler;
import javax.net.ssl.SSLException;
import java.io.File;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
public class SslClientConfiguration {
public static class Builder {
Iterable<String> ciphers;
File caFile;
long sessionCacheSize = 10000;
long sessionTimeoutSeconds = 86400;
SslContext clientContext;
public Builder ciphers(Iterable<String> ciphers) {
this.ciphers = ciphers;
return this;
}
public Builder caFile(File caFile) {
this.caFile = caFile;
return this;
}
public Builder sessionCacheSize(long sessionCacheSize) {
this.sessionCacheSize = sessionCacheSize;
return this;
}
public Builder sessionTimeoutSeconds(long sessionTimeoutSeconds) {
this.sessionTimeoutSeconds = sessionTimeoutSeconds;
return this;
}
/**
* Overrides the SslContext with one explicitly provided by the caller. If this is not null, the other
* builder parameters will be ignored. Currently only used for testing and may be removed in the future,
* once we have netty support for client-side certs.
*
* @param clientContext the client context.
* @return a reference to this builder.
*/
public Builder sslContext(SslContext clientContext) {
this.clientContext = clientContext;
return this;
}
public SslClientConfiguration build() {
return new SslClientConfiguration(this);
}
}
private SslContext clientContext;
public SslClientConfiguration(Builder builder) {
if (builder.clientContext == null) {
try {
clientContext =
SslContext.newClientContext(
null,
null,
builder.caFile,
null,
builder.ciphers,
null,
builder.sessionCacheSize,
builder.sessionTimeoutSeconds);
} catch (SSLException e) {
Throwables.propagate(e);
}
} else {
clientContext = builder.clientContext;
}
}
public SslHandler createHandler() throws Exception {
return clientContext.newHandler();
}
public SslHandler createHandler(SocketAddress address) throws Exception {
if (!(address instanceof InetSocketAddress)) {
return createHandler();
}
InetSocketAddress netAddress = (InetSocketAddress) address;
String host = netAddress.getHostString();
if (host == null) {
return createHandler();
}
return clientContext.newHandler(host, netAddress.getPort());
}
}
| 32.280702 | 112 | 0.616848 |
8a23698fc28df4c6144c899081095795da70c432
| 90 |
package cn.lliiooll.opq.core.data.message;
public enum MessageFrom {
GROUP,FRIEND;
}
| 15 | 42 | 0.744444 |
cd0cb1a89c62c5a52328e986e3cfc4f2ad00de09
| 787 |
package Greedy.AbsoluteInequation;
import java.util.Arrays;
/**
* 仓库选址
* 在一条数轴上有 N 家商店,它们的坐标分别为 A1~AN。
* 求把货仓建在何处,可以使得货仓到每家商店的距离之和最小。
*
* 绝对值不等式
* f(x) = |x - A1| + |x - A2| + ... + |x - An|
*
* 最小值应该是 x 取 A1, A2, ..., An 的中位数。如果 n 为偶数,则 x 取 中间两个数之间的任意一点
*
* 证明:
* 将 n 个数分组
* f(x) = (|x - A1| + |x - An|) + (|x - A2| + |x - An-1|) + ...
* 考虑每个组里面的两个点 a 和 b
* 1. x < a < b
* x 在 x == a 时取最小
* 2. a < x < b
* x 怎么取,值不变,都是 b - a
* 3. a < b < x
* x 在 x == b 时取最小
* 所以 x 应该取到 [a, b] 之间的
*/
public class ABS_Inequality {
public int minCost(int[] pos) {
int n = pos.length;
Arrays.sort(pos);
int res = 0;
for (int i = 0; i < n; i++) {
res += Math.abs(pos[i] - pos[n / 2]);
}
return res;
}
}
| 19.195122 | 63 | 0.466328 |
6bf61968db707e1421db4fc2d42a090f4774f31a
| 994 |
package com.veben.microservices.developerinformation.ext.db;
import com.veben.microservices.developerinformation.domain.DeveloperInformation;
import com.veben.microservices.developerinformation.domain.DeveloperInformationRepository;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import java.util.HashSet;
import java.util.Set;
@Repository
public interface JpaDeveloperInformationRepository extends
DeveloperInformationRepository,
MongoRepository<DeveloperInformation, ObjectId> {
@Override
default Set<DeveloperInformation> findAllInformations() {
return new HashSet<>(findAll());
}
@Override
default DeveloperInformation findDeveloperInformationForDeveloper(String developerId) {
return findDeveloperInformationByDeveloperId(developerId);
}
DeveloperInformation findDeveloperInformationByDeveloperId(String developerId);
}
| 34.275862 | 91 | 0.815895 |
08ab415c73e5104e3426b2c15c104254d31b2565
| 16,068 |
/*
* Copyright (C) 2016 Jorge Ruesga
*
* 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.ruesga.rview.misc;
import android.text.TextUtils;
import android.util.Log;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.ruesga.rview.gerrit.model.ChangeMessageInfo;
import com.ruesga.rview.model.ContinuousIntegrationInfo;
import com.ruesga.rview.model.ContinuousIntegrationInfo.BuildStatus;
import com.ruesga.rview.model.Repository;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Matcher;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import static com.ruesga.rview.widget.RegExLinkifyTextView.WEB_LINK_REGEX;
public class ContinuousIntegrationHelper {
private static final String TAG = "ContinuousIntegration";
private static final String CI_REGEXP_1 = "\\* .*::((#)?\\d+::)?((OK, )|(WARN, )|(IGNORE, )|(ERROR, )).*";
public static List<ContinuousIntegrationInfo> getContinuousIntegrationStatus(
Repository repository, String changeId, int revisionNumber) {
List<ContinuousIntegrationInfo> ci = new ArrayList<>();
if (!TextUtils.isEmpty(repository.mCiStatusMode)
&& !TextUtils.isEmpty(repository.mCiStatusUrl)) {
// Check status mode
switch (repository.mCiStatusMode) {
case "cq":
// BuildBot CQ status type
return obtainFromCQServer(repository, changeId, revisionNumber);
}
}
return sort(ci);
}
@SuppressWarnings({"ConstantConditions", "TryFinallyCanBeTryWithResources"})
private static List<ContinuousIntegrationInfo> obtainFromCQServer(
Repository repository, String changeId, int revisionNumber) {
List<ContinuousIntegrationInfo> statuses = new ArrayList<>();
// NOTE: Do not fix "Redundant character escape" lint warning. Remove trailing '\'
// will cause an PatternSyntaxException
String url = repository.mCiStatusUrl
.replaceFirst("\\{change\\}", changeId)
.replaceFirst("\\{revision\\}", String.valueOf(revisionNumber));
try {
OkHttpClient okhttp = NetworkingHelper.createNetworkClient().build();
Request request = new Request.Builder().url(url).build();
Response response = okhttp.newCall(request).execute();
try {
String json = response.body().string();
JsonObject root = new JsonParser().parse(json).getAsJsonObject();
if (!root.has("builds")) {
return statuses;
}
JsonArray o = root.getAsJsonArray("builds");
int c1 = o.size();
for (int i = 0; i < c1; i++) {
JsonObject b = o.get(i).getAsJsonObject();
try {
String status = b.get("status").getAsString();
String ciUrl = b.get("url").getAsString();
String ciName = null;
JsonArray tags = b.get("tags").getAsJsonArray();
int c2 = tags.size();
for (int j = 0; j < c2; j++) {
String tag = tags.get(j).getAsJsonPrimitive().getAsString();
if (tag.startsWith("builder:")) {
ciName = tag.substring(tag.indexOf(":") + 1);
}
}
if (!TextUtils.isEmpty(status) && !TextUtils.isEmpty(ciUrl)
&& !TextUtils.isEmpty(ciName)) {
BuildStatus buildStatus = BuildStatus.RUNNING;
if (status.equals("COMPLETED")) {
String result = b.get("result").getAsString();
switch (result) {
case "SUCCESS":
buildStatus = BuildStatus.SUCCESS;
break;
case "FAILURE":
buildStatus = BuildStatus.FAILURE;
break;
default:
buildStatus = BuildStatus.SKIPPED;
break;
}
}
ContinuousIntegrationInfo c =
findContinuousIntegrationInfo(statuses, ciName);
// Attempts are sorted in reversed order, so we need the first one
if (c == null) {
statuses.add(
new ContinuousIntegrationInfo(ciName, ciUrl, buildStatus));
}
}
} catch (Exception ex) {
Log.w(TAG, "Failed to parse ci object" + b, ex);
}
}
} finally {
response.close();
}
} catch (Exception ex) {
Log.w(TAG, "Failed to obtain ci status from " + url, ex);
}
return statuses;
}
public static List<ContinuousIntegrationInfo> extractContinuousIntegrationInfo(
int patchSet, ChangeMessageInfo[] messages, Repository repository) {
List<ContinuousIntegrationInfo> ci = new ArrayList<>();
Set<String> ciNames = new HashSet<>();
try {
boolean checkFromPrevious = false;
for (ChangeMessageInfo message : messages) {
if (message.revisionNumber == patchSet) {
if (ModelHelper.isCIAccount(message.author, repository)) {
final String[] lines = message.message.split("\n");
String prevLine = null;
for (String line : lines) {
// A CI line/s should have:
// - Not a reply
// - Have an url (to the ci backend)
// - Have a build status
// - Have a job name
if (line.trim().startsWith(">")) {
continue;
}
Matcher webMatcher = WEB_LINK_REGEX.mPattern.matcher(line);
ContinuousIntegrationInfo cii = containsBuild(line, ci);
if (checkFromPrevious && cii != null) {
BuildStatus status = getBuildStatus(line);
if (cii.mStatus == null ||
(status != null && !cii.mStatus.equals(status))) {
cii.mStatus = status;
}
if (cii.mUrl == null && webMatcher.find()) {
cii.mUrl = extractUrl(webMatcher);
}
} else if (webMatcher.find()) {
String url = extractUrl(webMatcher);
if (url == null) {
continue;
}
BuildStatus status = null;
String name = null;
for (int i = 0; i <= 1; i++) {
String l = i == 0 ? line : prevLine;
if (status == null) {
status = getBuildStatus(l);
}
if (name == null) {
name = getJobName(l, status, url);
}
if (status != null && name != null) {
if (!ciNames.contains(name)) {
ci.add(new ContinuousIntegrationInfo(name, url, status));
ciNames.add(name);
} else if (cii != null &&
cii.mStatus.equals(BuildStatus.RUNNING)) {
cii.mStatus = status;
}
break;
}
}
} else if (line.startsWith("Building") &&
line.contains("target(s): ")) {
String l = line.substring(line.indexOf("target(s): ") + 10);
String[] jobs = l.trim().replaceAll("\\.", "").split(" ");
for (String job : jobs) {
if (!job.isEmpty()) {
ci.add(new ContinuousIntegrationInfo(
job, null, BuildStatus.SUCCESS));
}
}
checkFromPrevious = true;
} else if (line.matches(CI_REGEXP_1)) {
cii = fromRegExp1(line);
if (cii != null) {
ci.add(cii);
}
}
prevLine = line;
}
}
}
}
} catch (Exception ex) {
Log.d(TAG, "Failed to obtain continuous integration", ex);
ci.clear();
}
return sort(ci);
}
private static BuildStatus getBuildStatus(String line) {
if (line == null || line.trim().length() == 0) {
return null;
}
if (line.contains("PASS: ") || line.contains(": SUCCESS")
|| (line.contains(" succeeded (") && line.contains(" - "))
|| line.contains("\u2705")
|| line.contains("Build Successful")) {
return BuildStatus.SUCCESS;
}
if (line.contains("FAIL: ") || line.contains(": FAILURE") || line.contains("_FAILURE")
|| (line.contains(" failed (") && line.contains(" - ")) || line.contains("\u274C")) {
return BuildStatus.FAILURE;
}
if (line.contains("SKIPPED: ") || line.contains(": ABORTED")
|| line.contains("RETRY_LIMIT")) {
return BuildStatus.SKIPPED;
}
if (line.contains("Build Started")) {
return BuildStatus.RUNNING;
}
return null;
}
private static String getJobName(String line, BuildStatus status, String url) throws Exception {
if (line == null || line.trim().length() == 0) {
return null;
}
String l = line.replace(url, "");
String decodedUrl = URLDecoder.decode(url, "UTF-8");
// Try to extract the name from the url
int c = 0;
for (String part : decodedUrl.split("/")) {
c++;
if (c <= 3 || part.length() == 0) {
continue;
}
if (StringHelper.isOnlyNumeric(part)) {
continue;
}
if (l.toLowerCase(Locale.US).contains(part.toLowerCase(Locale.US))) {
// Found a valid job name
return part;
}
}
// Extract from the initial line
int end = l.indexOf(" : ");
if (end > 0) {
int start = l.indexOf(" ");
return l.substring(start == -1 ? 0 : start, end).trim();
}
// Extract from Url
if (status != null) {
List<String> parts = Arrays.asList(decodedUrl.split("/"));
Collections.reverse(parts);
c = 0;
String bestPart = null;
boolean foundOnlyNumeric = false;
for (String part : parts) {
c++;
if (part.equalsIgnoreCase("console") || part.equalsIgnoreCase("build")
|| part.equalsIgnoreCase("builds") || part.equalsIgnoreCase("job")) {
foundOnlyNumeric = false;
continue;
}
if (StringHelper.isOnlyNumeric(part)) {
foundOnlyNumeric = true;
continue;
}
if (c <= 1) {
foundOnlyNumeric = false;
continue;
}
// Found a valid job name
if (foundOnlyNumeric) {
return part;
}
if (bestPart == null) {
bestPart = part;
}
}
if (bestPart != null) {
return bestPart;
}
}
// Can't find a valid job name
return null;
}
private static String extractUrl(Matcher m) {
String url = m.group();
if (url == null) {
return null;
}
if (StringHelper.endsWithPunctuationMark(url)) {
url = url.substring(0, url.length() - 1);
}
return url;
}
private static ContinuousIntegrationInfo containsBuild(
String line, List<ContinuousIntegrationInfo> cii) {
for (ContinuousIntegrationInfo ci : cii) {
if (!TextUtils.isEmpty(ci.mName) && line.contains(ci.mName)) {
return ci;
}
}
return null;
}
private static ContinuousIntegrationInfo findContinuousIntegrationInfo(
List<ContinuousIntegrationInfo> ci, String name) {
for (ContinuousIntegrationInfo c : ci) {
if (c.mName.equals(name)) {
return c;
}
}
return null;
}
private static List<ContinuousIntegrationInfo> sort(List<ContinuousIntegrationInfo> ci) {
Collections.sort(ci, (c1, c2) -> c1.mName.compareTo(c2.mName));
return ci;
}
private static ContinuousIntegrationInfo fromRegExp1(String line) {
try {
String[] split = line.split("::");
String s = split[split.length -1].substring(0, split[split.length -1].indexOf(","));
BuildStatus status = null;
switch (s) {
case "OK":
status = BuildStatus.SUCCESS;
break;
case "IGNORE":
status = BuildStatus.SKIPPED;
break;
case "WARN":
case "ERROR":
status = BuildStatus.FAILURE;
break;
}
return new ContinuousIntegrationInfo(split[0].substring(2), null, status);
} catch (Exception ex) {
// Ignore
}
return null;
}
}
| 39.870968 | 110 | 0.455502 |
2ee81dc3326e4dc118832c982f0d02b114bc1653
| 975 |
package nu.nerd.entitymeta;
import org.bukkit.event.player.PlayerInteractEntityEvent;
// ----------------------------------------------------------------------------
/**
* Records pending processing of a PlayerInteractEntityEvent for a specific
* player.
*
* An implementation of this interface is attached to a player as transient
* Bukkit metadata and consulted when that player clicks on an entity.
*/
public interface IPendingInteraction {
/**
* Key when instances of this interface are used as Bukkit metadata.
*/
public static final String METADATA_KEY = "IPendingInteraction";// .class.getSimpleName();
// ------------------------------------------------------------------------
/**
* Handle a player interacting with an entity by performing a pending task.
*
* @param event the entity interaction event.
*/
public void onPlayerInteractEntity(PlayerInteractEntityEvent event);
} // class IPendingInteraction
| 37.5 | 94 | 0.617436 |
07909fbe9fcd0d00e9e96e25f0c458cdb94da7b3
| 2,371 |
/* Copyright 2011-2012 Netherlands Forensic Institute and
Centrum Wiskunde & Informatica
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.derric_lang.validator;
import java.io.IOException;
import java.util.List;
import java.util.Map;
public class SkipContentValidator implements ContentValidator {
@Override
public Content validateContent(ValidatorInputStream in, long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException {
if (arguments.containsKey("terminator") && arguments.containsKey("terminatorsize") && configuration.containsKey("includeterminator")) {
ValueSet terminators = new ValueSet();
List<Object> lt = arguments.get("terminator");
for (Object i : lt) {
terminators.addEquals(((Long) i).longValue());
}
int terminatorSize = ((Long) arguments.get("terminatorsize").get(0)).intValue();
boolean includeTerminator = configuration.get("includeterminator").toLowerCase().equals("true") ? true : false;
Content content = in.includeMarker(includeTerminator).readUntil(terminatorSize, terminators);
return new Content (content.validated || allowEOF, content.data);
} else if (size >= 0) {
if (in.available() == 0) {
return new Content(false, new byte[0]);
} else if (in.available() < size) {
int available = in.available();
byte[] data = new byte[available];
in.read(data);
return new Content(false, data);
} else {
byte[] data = new byte[(int) size];
int read = in.read(data);
return new Content((read == size) || allowEOF, data);
}
} else {
throw new RuntimeException("Either the field's size must be defined or a terminator and terminatorsize must be provided.");
}
}
}
| 43.109091 | 192 | 0.688739 |
5f7d2117c99464b018fff61c8080c68f0ad47f25
| 4,291 |
package xyz.cafeconleche.web.chica.app.config.amqp;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import xyz.cafeconleche.web.chica.service.consumer.ConsumerTopicService;
import xyz.cafeconleche.web.chica.service.consumer.impl.ConsumerTopicServiceRabbitMqImpl;
@Configuration
public class SpringRabbitMqTopicConfig {
private static final String TOPIC_EXCHANGE_NAME = "topic.exchange.name";
private static final String TOPIC_BINDING_1_NAME = "*.orange.*";
private static final String TOPIC_BINDING_2_NAME = "*.*.rabbit";
private static final String TOPIC_BINDING_3_NAME = "lazy.#";
private static final String TOPIC_QUEUE_A_NAME = "topic.queue.a.name";
private static final String TOPIC_QUEUE_B_NAME = "topic.queue.b.name";
@Bean
public AmqpAdmin amqpAdmin(ConnectionFactory connectionFactory) {
System.out.println("--- AmqpAdmin ---");
return new RabbitAdmin(connectionFactory);
}
@Bean
@Qualifier("topicQueueA")
public Queue topicQueueA() {
System.out.println("--- topicQueueA ---");
return new Queue(TOPIC_QUEUE_A_NAME);
}
@Bean
@Qualifier("topicQueueB")
public Queue topicQueueB() {
System.out.println("--- topicQueueB ---");
return new Queue(TOPIC_QUEUE_B_NAME);
}
@Bean TopicExchange topicExchange() {
return new TopicExchange(TOPIC_EXCHANGE_NAME);
}
@Bean
public Binding bindingTopicA() {
return BindingBuilder.bind(topicQueueA()).to(topicExchange()).with(TOPIC_BINDING_1_NAME);
}
@Bean
public Binding bindingTopicB() {
return BindingBuilder.bind(topicQueueB()).to(topicExchange()).with(TOPIC_BINDING_2_NAME);
}
@Bean
public Binding bindingTopicC() {
return BindingBuilder.bind(topicQueueB()).to(topicExchange()).with(TOPIC_BINDING_3_NAME);
}
@Bean
public ConsumerTopicService consumerTopicServiceA() {
ConsumerTopicService consumerTopicService = new ConsumerTopicServiceRabbitMqImpl();
consumerTopicService.setConsumerId("CONSUMER-TOPIC-A");
return consumerTopicService;
}
@Bean
public ConsumerTopicService consumerTopicServiceB() {
ConsumerTopicService consumerTopicService = new ConsumerTopicServiceRabbitMqImpl();
consumerTopicService.setConsumerId("CONSUMER-TOPIC-B");
return consumerTopicService;
}
@Bean
public SimpleMessageListenerContainer listenerContainerError(ConnectionFactory connectionFactory, MessageConverter jsonMessageConverter) {
System.out.println("--- listenerContainer routing queue ERROR ---");
SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer();
listenerContainer.setConnectionFactory(connectionFactory);
listenerContainer.setQueues(topicQueueA());
listenerContainer.setMessageConverter(jsonMessageConverter);
listenerContainer.setMessageListener(consumerTopicServiceA());
listenerContainer.setAcknowledgeMode(AcknowledgeMode.AUTO);
return listenerContainer;
}
@Bean
public SimpleMessageListenerContainer listenerContainerLog(ConnectionFactory connectionFactory, MessageConverter jsonMessageConverter) {
System.out.println("--- listenerContainer routing queue LOG ---");
SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer();
listenerContainer.setConnectionFactory(connectionFactory);
listenerContainer.setQueues(topicQueueB());
listenerContainer.setMessageConverter(jsonMessageConverter);
listenerContainer.setMessageListener(consumerTopicServiceB());
listenerContainer.setAcknowledgeMode(AcknowledgeMode.AUTO);
return listenerContainer;
}
}
| 39.366972 | 142 | 0.793288 |
a33551704c8c6d83ca7b70432e7a02e55660fcbe
| 5,049 |
package io.opensphere.core.util.lang;
import java.io.File;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import org.apache.log4j.Logger;
/**
* Utilities for Jar files.
*/
public final class JarUtilities
{
/** Logger reference. */
private static final Logger LOGGER = Logger.getLogger(JarUtilities.class);
/**
* List files available to a class loader.
*
* @param classLoader The class loader.
* @param path The path pointing to the top level of the search.
* @param depth The maximum depth below the path to search. A negative
* number indicates no limit.
* @return A collection of {@link URL}s.
*/
public static Collection<? extends URL> listFiles(ClassLoader classLoader, String path, int depth)
{
Collection<URL> results = new ArrayList<>();
Enumeration<URL> resources;
try
{
resources = classLoader.getResources(path);
while (resources.hasMoreElements())
{
URL url = resources.nextElement();
File file = new File(url.getFile());
if (file.isFile() || depth == 0)
{
results.add(url);
}
else if (file.isDirectory())
{
getFilesInDirectory(path, file, depth - 1, results);
}
else
{
getFilesInJar(path, url, depth, results);
}
}
}
catch (IOException e)
{
LOGGER.warn("Failed to load resources: " + e, e);
}
return results;
}
/**
* Find the classes in a directory that match a path.
*
* @param path The path.
* @param dir The directory.
* @param depth The maximum depth below the path to search. A negative
* number indicates no limit.
* @param results The output collection.
*/
private static void getFilesInDirectory(String path, File dir, int depth, Collection<? super URL> results)
{
File[] files = dir.listFiles();
if (files != null)
{
for (File file : files)
{
if (file.isFile())
{
try
{
results.add(file.toURI().toURL());
}
catch (MalformedURLException e)
{
LOGGER.warn(e, e);
}
}
else if (depth != 0 && file.isDirectory())
{
getFilesInDirectory(path, file, depth - 1, results);
}
}
}
}
/**
* Find the files in a jar that match a path.
*
* @param path The path.
* @param url The URL of the jar file.
* @param depth The maximum depth below the path to search. A negative
* number indicates no limit.
* @param results The output collection.
*/
private static void getFilesInJar(String path, URL url, int depth, Collection<? super URL> results)
{
String jarURI = url.toExternalForm();
int bang = jarURI.indexOf('!');
if (bang > 0)
{
jarURI = jarURI.substring(0, bang);
}
try
{
URLConnection conn = url.openConnection();
if (conn instanceof JarURLConnection)
{
JarURLConnection jarConn = (JarURLConnection)conn;
Enumeration<JarEntry> entries = jarConn.getJarFile().entries();
while (entries.hasMoreElements())
{
JarEntry entry = entries.nextElement();
String name = entry.getName();
if (!name.endsWith("/") && name.startsWith(path))
{
String substring = name.substring(path.length());
if (substring.length() > 0)
{
substring = substring.substring(1);
}
String[] split = substring.split("/");
if (split.length <= depth)
{
results.add(new URL(jarURI + "!/" + name));
}
}
}
}
}
catch (IOException e)
{
LOGGER.warn("Failed to read jar file [" + jarURI + "]: " + e, e);
}
}
/** Disallow instantiation. */
private JarUtilities()
{
}
}
| 32.574194 | 111 | 0.476728 |
b65d29c7b9fe86736b0b7c313536f1f7a587ce5a
| 1,967 |
package parser.multipleturtleparsing;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
public class StringListCreator {
private List<String> toParse;
private List<List<String>> sublists;
private final String BREAKPOINT_1 = "ask";
private final String BREAKPOINT_2 = "tell";
private final String BREAKPOINT_3 = "askwith";
public StringListCreator(List<String> literals){
toParse = new ArrayList<String>(literals);
sublists = new ArrayList<List<String>>();
createSublists();
}
public StringListCreator(String[] split) {
toParse = new ArrayList<String>();
for (String s: split){
toParse.add(s);
}
sublists = new ArrayList<List<String>>();
createSublists();
}
private void createSublists() {
QueueConstructor QC = new QueueConstructor(toParse);
Queue<String> commandQ = QC.getQ();
List<String> currentSublist = new ArrayList<String>();
while(!(commandQ.isEmpty())){
String literal = commandQ.poll();
// tell
if ((literal.equals(BREAKPOINT_2)) ){
sublists.add(currentSublist);
currentSublist = new ArrayList<String>();
currentSublist.add(literal);
}
// ask and ask with
else if ((literal.equals(BREAKPOINT_1)) || (literal.equals(BREAKPOINT_3))){
sublists.add(currentSublist);
currentSublist = new ArrayList<String>();
currentSublist.add(literal);
int bracketCount = 0;
while(bracketCount < 4 && !commandQ.isEmpty()){
String newString = commandQ.poll();
if((newString.equals("[")) || (newString.equals("]"))){
bracketCount++;
}
currentSublist.add(newString);
}
sublists.add(currentSublist);
currentSublist = new ArrayList<String>();
}
else{
currentSublist.add(literal);
}
}
if (!currentSublist.isEmpty()){
sublists.add(currentSublist);
}
}
public List<List<String>> getSublists(){
return sublists;
}
}
| 21.380435 | 78 | 0.657346 |
e20b884d947d695b228d40176d9d5711c1201c1a
| 550 |
package io.github.harvies.charon.tests.spring.inject.staticfactory;
import io.github.harvies.charon.tests.spring.inject.FactoryDao;
import lombok.Data;
/**
* 静态工厂注入
* <p>
* 静态工厂顾名思义,就是通过调用静态工厂的方法来获取自己需要的对象,为了让 spring 管理所
* 有对象,我们不能直接通过"工程类.静态方法()"来获取对象,而是依然通过 spring 注入的形式获
* 取:
*
* @author harvies
*/
@Data
public class StaticFactoryInjectTest {
private FactoryDao staticFactoryDao; //注入对象
//注入对象的 set 方法
public void setStaticFactoryDao(FactoryDao staticFactoryDao) {
this.staticFactoryDao = staticFactoryDao;
}
}
| 22.916667 | 67 | 0.743636 |
a591a7d4ae93b124d76b6119b4e4d9290b59c15c
| 1,552 |
package gate.base.cache;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import gate.concurrent.ThreadFactoryImpl;
import gate.server.Server4Terminal;
/**
* @author 宋建涛 E-mail:1872963677@qq.com
* @version 创建时间:2019年5月23日 下午8:44:44
* 类说明:规约相关缓存
*/
public class ProtocalStrategyCache {
private static final ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor(
new ThreadFactoryImpl("persistent_ProtocalStrategy_", true));
private ProtocalStrategyCache(){
throw new AssertionError();
}
/**
* 网关规约规则缓存---缓存当前网关支持的所有规约类型的 匹配规则,通过"规约编号"唯一标识--key=pId
*/
public static ConcurrentHashMap<String, String> protocalStrategyCache ;
/**
* 网关规约服务缓存---用于规约服务控制-- key=pId
*/
public static ConcurrentHashMap<String, Server4Terminal> protocalServerCache ;
/**
* 缓存IOTGate高级功能中得长度域解析器 Class地址
* key = Pid
* value = 全类名
*/
public static ConcurrentHashMap<String, String> protocalStrategyClassUrlCache ;
static{
protocalStrategyCache = new ConcurrentHashMap<>();
protocalServerCache = new ConcurrentHashMap<>();
protocalStrategyClassUrlCache = new ConcurrentHashMap<>();
}
/**
* 规约规则落地
*/
private static void persistentProtocalStrategy(){
scheduledExecutor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
// TODO 规约规则落地
}
}, 2, 3, TimeUnit.MINUTES);
}
}
| 27.22807 | 111 | 0.728093 |
ad7775a373b30df9ca3c04bb3a5694249e382a2e
| 2,279 |
package us.fjj.spring.learning.springandmybatisusage.multidatasource;
import org.apache.ibatis.annotations.Mapper;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.io.IOException;
@Configuration
@MapperScan(annotationClass = Mapper.class, sqlSessionFactoryRef = ModuleSpringConfig.SQL_SESSION_FACTORY_BEAN_NAME)
@ComponentScan
@EnableTransactionManagement
public class ModuleSpringConfig {
public final static String DATASOURCE_BEAN_NAME = "dataSourceModule1";
public final static String TRANSACTION_MANAGER_BEAN_NAME = "transactionManagerModule1";
public final static String SQL_SESSION_FACTORY_BEAN_NAME = "sqlSessionFactoryModule1";
//定义数据源
@Bean
public DataSource dataSourceModule1() {
org.apache.tomcat.jdbc.pool.DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/test5?characterEncoding=UTF-8");
dataSource.setUsername("e");
dataSource.setPassword("sdfs");
dataSource.setInitialSize(5);
return dataSource;
}
//定义事务管理器
@Bean
public TransactionManager transactionManagerModule1(@Qualifier(DATASOURCE_BEAN_NAME) DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
//定义SqlSessionFactoryBean,用来创建SqlSessionFactory
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBeanModule1(@Qualifier(DATASOURCE_BEAN_NAME) DataSource dataSource) throws IOException {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
return sqlSessionFactoryBean;
}
}
| 31.652778 | 138 | 0.793769 |
da0c880e1b30a309c7030fa433cf18b00a5c233d
| 7,369 |
package com.auth0.jwt.impl;
import com.auth0.jwt.interfaces.Claim;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.node.TextNode;
import org.hamcrest.collection.IsCollectionWithSize;
import org.hamcrest.core.IsIterableContaining;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.time.Instant;
import java.util.*;
import static com.auth0.jwt.impl.JWTParser.getDefaultObjectMapper;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
public class PayloadImplTest {
@Rule
public ExpectedException exception = ExpectedException.none();
private PayloadImpl payload;
private final Instant expiresAt = Instant.now().plusSeconds(10);
private final Instant notBefore = Instant.now();
private final Instant issuedAt = Instant.now();
private ObjectReader objectReader;
@Before
public void setUp() {
ObjectMapper mapper = getDefaultObjectMapper();
objectReader = mapper.reader();
Map<String, JsonNode> tree = new HashMap<>();
tree.put("extraClaim", new TextNode("extraValue"));
payload = new PayloadImpl("issuer", "subject", Collections.singletonList("audience"), expiresAt, notBefore, issuedAt, "jwtId", tree, objectReader);
}
@Test
public void shouldHaveUnmodifiableTree() {
exception.expect(UnsupportedOperationException.class);
PayloadImpl payload = new PayloadImpl(null, null, null, null, null, null, null, new HashMap<>(), objectReader);
payload.getTree().put("something", null);
}
@Test
public void shouldHaveUnmodifiableAudience() {
exception.expect(UnsupportedOperationException.class);
PayloadImpl payload = new PayloadImpl(null, null, new ArrayList<>(), null, null, null, null, null, objectReader);
payload.getAudience().add("something");
}
@Test
public void shouldGetIssuer() {
assertThat(payload, is(notNullValue()));
assertThat(payload.getIssuer(), is("issuer"));
}
@Test
public void shouldGetNullIssuerIfMissing() {
PayloadImpl payload = new PayloadImpl(null, null, null, null, null, null, null, null, objectReader);
assertThat(payload, is(notNullValue()));
assertThat(payload.getIssuer(), is(nullValue()));
}
@Test
public void shouldGetSubject() {
assertThat(payload, is(notNullValue()));
assertThat(payload.getSubject(), is("subject"));
}
@Test
public void shouldGetNullSubjectIfMissing() {
PayloadImpl payload = new PayloadImpl(null, null, null, null, null, null, null, null, objectReader);
assertThat(payload, is(notNullValue()));
assertThat(payload.getSubject(), is(nullValue()));
}
@Test
public void shouldGetAudience() {
assertThat(payload, is(notNullValue()));
assertThat(payload.getAudience(), is(IsCollectionWithSize.hasSize(1)));
assertThat(payload.getAudience(), is(IsIterableContaining.hasItems("audience")));
}
@Test
public void shouldGetNullAudienceIfMissing() {
PayloadImpl payload = new PayloadImpl(null, null, null, null, null, null, null, null, objectReader);
assertThat(payload, is(notNullValue()));
assertThat(payload.getAudience(), is(nullValue()));
}
@Test
public void shouldGetExpiresAt() {
assertThat(payload, is(notNullValue()));
assertThat(payload.getExpiresAt(), is(Date.from(expiresAt)));
assertThat(payload.getExpiresAtAsInstant(), is(expiresAt));
}
@Test
public void shouldGetNullExpiresAtIfMissing() {
PayloadImpl payload = new PayloadImpl(null, null, null, null, null, null, null, null, objectReader);
assertThat(payload, is(notNullValue()));
assertThat(payload.getExpiresAt(), is(nullValue()));
assertThat(payload.getExpiresAtAsInstant(), is(nullValue()));
}
@Test
public void shouldGetNotBefore() {
assertThat(payload, is(notNullValue()));
assertThat(payload.getNotBefore(), is(Date.from(notBefore)));
assertThat(payload.getNotBeforeAsInstant(), is(notBefore));
}
@Test
public void shouldGetNullNotBeforeIfMissing() {
PayloadImpl payload = new PayloadImpl(null, null, null, null, null, null, null, null, objectReader);
assertThat(payload, is(notNullValue()));
assertThat(payload.getNotBefore(), is(nullValue()));
assertThat(payload.getNotBeforeAsInstant(), is(nullValue()));
}
@Test
public void shouldGetIssuedAt() {
assertThat(payload, is(notNullValue()));
assertThat(payload.getIssuedAt(), is(Date.from(issuedAt)));
assertThat(payload.getIssuedAtAsInstant(), is(issuedAt));
}
@Test
public void shouldGetNullIssuedAtIfMissing() {
PayloadImpl payload = new PayloadImpl(null, null, null, null, null, null, null, null, objectReader);
assertThat(payload, is(notNullValue()));
assertThat(payload.getIssuedAt(), is(nullValue()));
assertThat(payload.getIssuedAtAsInstant(), is(nullValue()));
}
@Test
public void shouldGetJWTId() {
assertThat(payload, is(notNullValue()));
assertThat(payload.getId(), is("jwtId"));
}
@Test
public void shouldGetNullJWTIdIfMissing() {
PayloadImpl payload = new PayloadImpl(null, null, null, null, null, null, null, null, objectReader);
assertThat(payload, is(notNullValue()));
assertThat(payload.getId(), is(nullValue()));
}
@Test
public void shouldGetExtraClaim() {
assertThat(payload, is(notNullValue()));
assertThat(payload.getClaim("extraClaim"), is(instanceOf(JsonNodeClaim.class)));
assertThat(payload.getClaim("extraClaim").asString(), is("extraValue"));
}
@Test
public void shouldGetNotNullExtraClaimIfMissing() {
PayloadImpl payload = new PayloadImpl(null, null, null, null, null, null, null, null, objectReader);
assertThat(payload, is(notNullValue()));
assertThat(payload.getClaim("missing"), is(notNullValue()));
assertThat(payload.getClaim("missing").isMissing(), is(true));
assertThat(payload.getClaim("missing").isNull(), is(false));
}
@Test
public void shouldGetClaims() {
Map<String, JsonNode> tree = new HashMap<>();
tree.put("extraClaim", new TextNode("extraValue"));
tree.put("sub", new TextNode("auth0"));
PayloadImpl payload = new PayloadImpl(null, null, null, null, null, null, null, tree, objectReader);
assertThat(payload, is(notNullValue()));
Map<String, Claim> claims = payload.getClaims();
assertThat(claims, is(notNullValue()));
assertThat(claims.get("extraClaim"), is(notNullValue()));
assertThat(claims.get("sub"), is(notNullValue()));
}
@Test
public void shouldNotAllowToModifyClaimsMap() {
assertThat(payload, is(notNullValue()));
Map<String, Claim> claims = payload.getClaims();
assertThat(claims, is(notNullValue()));
exception.expect(UnsupportedOperationException.class);
claims.put("name", null);
}
}
| 37.789744 | 155 | 0.676754 |
d7d441707ecf4f44151054d0423cd3ee3024b461
| 38,729 |
/*
* This file was automatically generated by EvoSuite
* Fri Aug 24 09:56:06 GMT 2018
*/
package com.ib.client;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.runtime.EvoAssertions.*;
import com.ib.client.Contract;
import com.ib.client.ContractDetails;
import com.ib.client.EWrapperMsgGenerator;
import com.ib.client.Execution;
import com.ib.client.Order;
import com.ib.client.OrderState;
import com.ib.client.TagValue;
import com.ib.client.UnderComp;
import java.util.Vector;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.evosuite.runtime.System;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true)
public class EWrapperMsgGenerator_ESTest extends EWrapperMsgGenerator_ESTest_scaffolding {
/**
//Test case number: 0
/*Coverage entropy=2.0794415416798357
*/
@Test(timeout = 4000)
public void test00() throws Throwable {
String string0 = EWrapperMsgGenerator.tickString(1, 1, "S>*@`iBrF");
assertEquals("id=1 bidPrice=S>*@`iBrF", string0);
ContractDetails contractDetails0 = new ContractDetails();
contractDetails0.m_callable = false;
contractDetails0.m_convertible = true;
contractDetails0.m_coupon = 920.0450348;
contractDetails0.m_timeZoneId = "t;:)";
contractDetails0.m_marketName = "";
contractDetails0.m_putable = true;
String string1 = EWrapperMsgGenerator.contractDetails(0, contractDetails0);
assertEquals("reqId = 0 ===================================\n ---- Contract Details begin ----\nconid = 0\nsymbol = null\nsecType = null\nexpiry = null\nstrike = 0.0\nright = null\nmultiplier = null\nexchange = null\nprimaryExch = null\ncurrency = null\nlocalSymbol = null\nmarketName = \ntradingClass = null\nminTick = 0.0\nprice magnifier = 0\norderTypes = null\nvalidExchanges = null\nunderConId = 0\nlongName = null\ncontractMonth = null\nindustry = null\ncategory = null\nsubcategory = null\ntimeZoneId = t;:)\ntradingHours = null\nliquidHours = null\n ---- Contract Details End ----\n", string1);
EWrapperMsgGenerator.scannerParameters((String) null);
contractDetails0.m_liquidHours = "SCANNER PARAMETERS:\nnull";
String string2 = EWrapperMsgGenerator.scannerParameters("");
assertEquals("SCANNER PARAMETERS:\n", string2);
String string3 = EWrapperMsgGenerator.bondContractDetails(0, contractDetails0);
assertEquals("reqId = 0 ===================================\n ---- Bond Contract Details begin ----\nsymbol = null\nsecType = null\ncusip = null\ncoupon = 920.0450348\nmaturity = null\nissueDate = null\nratings = null\nbondType = null\ncouponType = null\nconvertible = true\ncallable = false\nputable = true\ndescAppend = null\nexchange = null\ncurrency = null\nmarketName = \ntradingClass = null\nconid = 0\nminTick = 0.0\norderTypes = null\nvalidExchanges = null\nnextOptionDate = null\nnextOptionType = null\nnextOptionPartial = false\nnotes = null\nlongName = null\n ---- Bond Contract Details End ----\n", string3);
String string4 = EWrapperMsgGenerator.tickGeneric((-1), 0, 0);
assertEquals("id=-1 bidSize=0.0", string4);
String string5 = EWrapperMsgGenerator.openOrderEnd();
assertEquals(" =============== end ===============", string5);
}
/**
//Test case number: 1
/*Coverage entropy=1.6094379124341005
*/
@Test(timeout = 4000)
public void test01() throws Throwable {
String string0 = EWrapperMsgGenerator.updateAccountTime("WIEr#0?KmNe4v{'");
assertEquals("updateAccountTime: WIEr#0?KmNe4v{'", string0);
UnderComp underComp0 = new UnderComp();
underComp0.m_conId = (-2231);
underComp0.m_delta = (double) (-1694);
String string1 = EWrapperMsgGenerator.deltaNeutralValidation((-1694), underComp0);
assertEquals("id = -1694 underComp.conId =-2231 underComp.delta =-1694.0 underComp.price =0.0", string1);
String string2 = EWrapperMsgGenerator.orderStatus((-2514), "updateAccountTime: WIEr#0?KmNe4v{'", 0, (-2231), (-2231), (-2231), (-3034), (-1.0), 3, ":;),'tSTxj9b3ad");
assertEquals("order status: orderId=-2514 clientId=3 permId=-2231 status=updateAccountTime: WIEr#0?KmNe4v{' filled=0 remaining=-2231 avgFillPrice=-2231.0 lastFillPrice=-1.0 parent Id=-3034 whyHeld=:;),'tSTxj9b3ad", string2);
String string3 = EWrapperMsgGenerator.tickSize((-2231), (-2231), 3);
assertEquals("id=-2231 unknown=3", string3);
Contract contract0 = new Contract(241, "com.ib.client.AnyWrapperMsgGenerator", "^9S-8kaPY", "", 0.0, "^9S-8kaPY", "WIEr#0?KmNe4v{'", "", "vBi-V\"-$w&]TO,", ":;),'tSTxj9b3ad", (Vector) null, "id=-2231 unknown=3", false, "ec3u", "");
String string4 = EWrapperMsgGenerator.contractMsg(contract0);
assertEquals("conid = 241\nsymbol = com.ib.client.AnyWrapperMsgGenerator\nsecType = ^9S-8kaPY\nexpiry = \nstrike = 0.0\nright = ^9S-8kaPY\nmultiplier = WIEr#0?KmNe4v{'\nexchange = \nprimaryExch = id=-2231 unknown=3\ncurrency = vBi-V\"-$w&]TO,\nlocalSymbol = :;),'tSTxj9b3ad\n", string4);
}
/**
//Test case number: 2
/*Coverage entropy=1.0986122886681096
*/
@Test(timeout = 4000)
public void test02() throws Throwable {
String string0 = EWrapperMsgGenerator.currentTime((-1L));
assertEquals("current time = -1 (Dec 31, 1969 11:59:59 PM)", string0);
EWrapperMsgGenerator.currentTime(0L);
Vector<Object> vector0 = new Vector<Object>();
Contract contract0 = new Contract((-127), (String) null, "com.ib.client.TagValue", "current time = 0 (Jan 1, 1970 12:00:00 AM)", 0L, "", "com.ib.client.TagValue", "", "current time = -1 (Dec 31, 1969 11:59:59 PM)", "current time = 0 (Jan 1, 1970 12:00:00 AM)", vector0, "", true, "com.ib.client.TagValue", "i9F^IOTv?TofD");
String string1 = EWrapperMsgGenerator.updatePortfolio(contract0, 0, (-127), 4467.065469000946, 4467.065469000946, 0.0, (-127), "0*,`i6mZ");
assertEquals("updatePortfolio: conid = -127\nsymbol = null\nsecType = com.ib.client.TagValue\nexpiry = current time = 0 (Jan 1, 1970 12:00:00 AM)\nstrike = 0.0\nright = \nmultiplier = com.ib.client.TagValue\nexchange = \nprimaryExch = \ncurrency = current time = -1 (Dec 31, 1969 11:59:59 PM)\nlocalSymbol = current time = 0 (Jan 1, 1970 12:00:00 AM)\n0 -127.0 4467.065469000946 4467.065469000946 0.0 -127.0 0*,`i6mZ", string1);
}
/**
//Test case number: 3
/*Coverage entropy=1.6094379124341005
*/
@Test(timeout = 4000)
public void test03() throws Throwable {
EWrapperMsgGenerator.scannerDataEnd((-2081));
EWrapperMsgGenerator.updateMktDepth(13, 13, (-439), 13, (-2081), (-439));
EWrapperMsgGenerator.updateNewsBulletin(13, (-3713), "updateMktDepth: 13 13 -439 13 -2081.0 -439", "K+a");
EWrapperMsgGenerator.tickString(1138, 0, "MXk9*(4u?(Dubk.4@");
// Undeclared exception!
try {
EWrapperMsgGenerator.bondContractDetails(0, (ContractDetails) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.ib.client.EWrapperMsgGenerator", e);
}
}
/**
//Test case number: 4
/*Coverage entropy=1.7917594692280547
*/
@Test(timeout = 4000)
public void test04() throws Throwable {
String string0 = "8:loteeo-oI!kDNUu~";
EWrapperMsgGenerator.managedAccounts("8:loteeo-oI!kDNUu~");
int int0 = 0;
EWrapperMsgGenerator.tickPrice(0, 0, (-1.0), 0);
int int1 = 0;
EWrapperMsgGenerator.historicalData(0, "8:loteeo-oI!kDNUu~", 927.21273431883, 0, 927.21273431883, 0.0, 4434, 0, (-1.0), false);
EWrapperMsgGenerator.fundamentalData(0, "");
String string1 = null;
EWrapperMsgGenerator.updateNewsBulletin(0, 0, "8:loteeo-oI!kDNUu~", (String) null);
int int2 = 0;
EWrapperMsgGenerator.updateNewsBulletin(0, 0, "id=0 date = 8:loteeo-oI!kDNUu~ open=927.21273431883 high=0.0 low=927.21273431883 close=0.0 volume=4434 count=0 WAP=-1.0 hasGaps=false", "");
EWrapperMsgGenerator.openOrderEnd();
EWrapperMsgGenerator.updateNewsBulletin((-785), 0, "MsgId=0 :: MsgType=0 :: Origin=null :: Message=8:loteeo-oI!kDNUu~", "id=0 bidSize=-1.0 noAutoExecute");
// Undeclared exception!
try {
EWrapperMsgGenerator.fundamentalData(0, (String) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.ib.client.EWrapperMsgGenerator", e);
}
}
/**
//Test case number: 5
/*Coverage entropy=1.6094379124341005
*/
@Test(timeout = 4000)
public void test05() throws Throwable {
String string0 = EWrapperMsgGenerator.updateMktDepth(0, 1724, 1724, 1724, 0, 0);
assertEquals("updateMktDepth: 0 1724 1724 1724 0.0 0", string0);
String string1 = EWrapperMsgGenerator.updateAccountValue("updateMktDepth: 0 1724 1724 1724 0.0 0", "updateMktDepth: 0 1724 1724 1724 0.0 0", "updateMktDepth: 0 1724 1724 1724 0.0 0", "");
assertEquals("updateAccountValue: updateMktDepth: 0 1724 1724 1724 0.0 0 updateMktDepth: 0 1724 1724 1724 0.0 0 updateMktDepth: 0 1724 1724 1724 0.0 0 ", string1);
Contract contract0 = new Contract();
String string2 = EWrapperMsgGenerator.contractMsg(contract0);
assertEquals("conid = 0\nsymbol = null\nsecType = null\nexpiry = null\nstrike = 0.0\nright = null\nmultiplier = null\nexchange = null\nprimaryExch = null\ncurrency = null\nlocalSymbol = null\n", string2);
contract0.m_comboLegsDescrip = "conid = 0\nsymbol = null\nsecType = null\nexpiry = null\nstrike = 0.0\nright = null\nmultiplier = null\nexchange = null\nprimaryExch = null\ncurrency = null\nlocalSymbol = null\n";
contract0.m_secType = "";
String string3 = EWrapperMsgGenerator.historicalData(0, "", 0.0, 0, (-393.9041981556), (-2782.0364), 1724, 1724, 0, true);
assertEquals("id=0 date = open=0.0 high=0.0 low=-393.9041981556 close=-2782.0364 volume=1724 count=1724 WAP=0.0 hasGaps=true", string3);
String string4 = EWrapperMsgGenerator.scannerParameters("updateMktDepth: 0 1724 1724 1724 0.0 0");
assertEquals("SCANNER PARAMETERS:\nupdateMktDepth: 0 1724 1724 1724 0.0 0", string4);
String string5 = EWrapperMsgGenerator.updateMktDepth(1724, 0, 2241, 0, (-393.9041981556), 0);
assertEquals("updateMktDepth: 1724 0 2241 0 -393.9041981556 0", string5);
}
/**
//Test case number: 6
/*Coverage entropy=1.6094379124341005
*/
@Test(timeout = 4000)
public void test06() throws Throwable {
int int0 = (-166);
EWrapperMsgGenerator.tickGeneric((-166), (-166), (-166));
EWrapperMsgGenerator.contractDetailsEnd((-166));
EWrapperMsgGenerator.updateAccountValue("id=-166 unknown=-166.0", "id=-166 unknown=-166.0", (String) null, "id=-166 unknown=-166.0");
EWrapperMsgGenerator eWrapperMsgGenerator0 = new EWrapperMsgGenerator();
Vector<TagValue> vector0 = new Vector<TagValue>();
Contract contract0 = new Contract(63, (String) null, "com.ib.client.UnderComp", "d", (-166), " settlingFirm=", "Ft.N&y/G,D]", (String) null, "{G", " settlingFirm=", vector0, " algoStrategy=", false, (String) null, " parent Id=");
Execution execution0 = new Execution((-661), 63, " parent Id=", "id=-166 unknown=-166.0", (String) null, (String) null, "com.ib.client.UnderComp", 2, 1807.302110874, 0, (-166), 13, 63);
EWrapperMsgGenerator.execDetails(63, contract0, execution0);
Vector<String> vector1 = new Vector<String>();
String string0 = "";
Contract contract1 = new Contract((-661), "", "FA:", "{G", (-166), "", "", "reqId = -166 =============== end ===============", "", (String) null, vector1, "", false, "oz(d", "SCANNER PARAMETERS:");
// Undeclared exception!
try {
EWrapperMsgGenerator.execDetails(0, contract1, (Execution) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.ib.client.EWrapperMsgGenerator", e);
}
}
/**
//Test case number: 7
/*Coverage entropy=1.945910149055313
*/
@Test(timeout = 4000)
public void test07() throws Throwable {
EWrapperMsgGenerator.scannerDataEnd(146);
String string0 = EWrapperMsgGenerator.realtimeBar(121, (-1L), 0.0, 146, 0.0, 267.897163622271, 146, 267.897163622271, 13);
assertEquals("id=121 time = -1 open=0.0 high=146.0 low=0.0 close=267.897163622271 volume=146 count=13 WAP=267.897163622271", string0);
String string1 = EWrapperMsgGenerator.fundamentalData(146, "id=121 time = -1 open=0.0 high=146.0 low=0.0 close=267.897163622271 volume=146 count=13 WAP=267.897163622271");
assertEquals("id = 146 len = 108\nid=121 time = -1 open=0.0 high=146.0 low=0.0 close=267.897163622271 volume=146 count=13 WAP=267.897163622271", string1);
String string2 = EWrapperMsgGenerator.managedAccounts("");
assertEquals("Connected : The list of managed accounts are : []", string2);
String string3 = EWrapperMsgGenerator.openOrderEnd();
assertEquals(" =============== end ===============", string3);
String string4 = EWrapperMsgGenerator.scannerDataEnd(146);
assertEquals("id = 146 =============== end ===============", string4);
String string5 = EWrapperMsgGenerator.tickPrice(13, 121, 1.7976931348623157E308, (-4801));
assertEquals("id=13 unknown=1.7976931348623157E308 canAutoExecute", string5);
String string6 = EWrapperMsgGenerator.tickSize(1, 0, (-1203));
assertEquals("id=1 bidSize=-1203", string6);
}
/**
//Test case number: 8
/*Coverage entropy=1.6094379124341005
*/
@Test(timeout = 4000)
public void test08() throws Throwable {
EWrapperMsgGenerator.updateAccountTime("t[1k$o`)M08<J-I8l");
EWrapperMsgGenerator.updateMktDepthL2(1243, 1243, "updateAccountTime: t[1k$o`)M08<J-I8l", 1243, 148, 1243, (-3179));
EWrapperMsgGenerator.realtimeBar(0, (-1L), (-3179), (-3179), 0, 0, (-245L), (-3179), 0);
Contract contract0 = new Contract();
contract0.equals((Object) null);
ContractDetails contractDetails0 = new ContractDetails(contract0, "4bh2LHQY%gs", "", (-1L), (String) null, "", 0, "", "EdPm|vCAe&8dE", "id=0 time = -1 open=-3179.0 high=-3179.0 low=0.0 close=0.0 volume=-245 count=0 WAP=-3179.0", (String) null, (String) null, "", "", "Error - ");
contractDetails0.m_contractMonth = null;
EWrapperMsgGenerator.bondContractDetails(0, contractDetails0);
// Undeclared exception!
try {
EWrapperMsgGenerator.deltaNeutralValidation((-3179), (UnderComp) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.ib.client.EWrapperMsgGenerator", e);
}
}
/**
//Test case number: 9
/*Coverage entropy=1.7917594692280547
*/
@Test(timeout = 4000)
public void test09() throws Throwable {
int int0 = (-2356);
EWrapperMsgGenerator.scannerDataEnd((-2356));
EWrapperMsgGenerator.execDetailsEnd((-2356));
int int1 = 0;
EWrapperMsgGenerator.tickString(0, 0, "reqId = -2356 =============== end ===============");
EWrapperMsgGenerator.openOrderEnd();
EWrapperMsgGenerator.scannerParameters("id = -2356 =============== end ===============");
// Undeclared exception!
try {
EWrapperMsgGenerator.deltaNeutralValidation(0, (UnderComp) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.ib.client.EWrapperMsgGenerator", e);
}
}
/**
//Test case number: 10
/*Coverage entropy=1.7917594692280547
*/
@Test(timeout = 4000)
public void test10() throws Throwable {
EWrapperMsgGenerator.nextValidId(1987);
String string0 = EWrapperMsgGenerator.nextValidId(1987);
assertEquals("Next Valid Order ID: 1987", string0);
String string1 = EWrapperMsgGenerator.tickOptionComputation(0, 10, 2419.8984, 1987, 2419.8984, 2419.8984);
assertEquals("id=0 bidOptComp: vol = 2419.8984 delta = N/A", string1);
Vector<Object> vector0 = new Vector<Object>();
Contract contract0 = new Contract(10, "O", "aM`a", "WC", 3345.0, "Next Valid Order ID: 1987", "Next Valid Order ID: 1987", "", "", "yd{Uop&lqR", vector0, "O", true, " | ", "aM`a");
Order order0 = new Order();
order0.m_referencePriceType = 10;
order0.m_algoParams = contract0.m_comboLegs;
order0.m_rule80A = null;
OrderState orderState0 = new OrderState();
vector0.listIterator();
orderState0.m_status = "";
EWrapperMsgGenerator.openOrder(10, contract0, order0, orderState0);
String string2 = EWrapperMsgGenerator.openOrderEnd();
assertEquals(" =============== end ===============", string2);
String string3 = EWrapperMsgGenerator.execDetailsEnd((-150));
assertEquals("reqId = -150 =============== end ===============", string3);
ContractDetails contractDetails0 = new ContractDetails();
String string4 = EWrapperMsgGenerator.scannerData(0, 0, contractDetails0, " maxCommission=", "com.ib.client.Execution", (String) null, (String) null);
assertEquals("id = 0 rank=0 symbol=null secType=null expiry=null strike=0.0 right=null exchange=null currency=null localSymbol=null marketName=null tradingClass=null distance= maxCommission= benchmark=com.ib.client.Execution projection=null legsStr=null", string4);
}
/**
//Test case number: 11
/*Coverage entropy=2.5649493574615376
*/
@Test(timeout = 4000)
public void test11() throws Throwable {
String string0 = EWrapperMsgGenerator.managedAccounts("Ssp1z<Qy");
assertEquals("Connected : The list of managed accounts are : [Ssp1z<Qy]", string0);
EWrapperMsgGenerator.scannerDataEnd(0);
String string1 = EWrapperMsgGenerator.tickSnapshotEnd((-1666));
assertEquals("id=-1666 =============== end ===============", string1);
EWrapperMsgGenerator.scannerParameters("Ssp1z<Qy");
String string2 = EWrapperMsgGenerator.tickString(0, (-1666), "Connected : The list of managed accounts are : [Ssp1z<Qy]");
assertEquals("id=0 unknown=Connected : The list of managed accounts are : [Ssp1z<Qy]", string2);
String string3 = EWrapperMsgGenerator.currentTime(0);
assertEquals("current time = 0 (Jan 1, 1970 12:00:00 AM)", string3);
String string4 = EWrapperMsgGenerator.realtimeBar(0, 0, (-9.09764175293838), 0, (-2065.6955583549907), 1564.800836, (-1666), 1564.800836, (-1666));
assertEquals("id=0 time = 0 open=-9.09764175293838 high=0.0 low=-2065.6955583549907 close=1564.800836 volume=-1666 count=-1666 WAP=1564.800836", string4);
EWrapperMsgGenerator.scannerParameters("current time = 0 (Jan 1, 1970 12:00:00 AM)");
String string5 = EWrapperMsgGenerator.scannerDataEnd((-1257));
assertEquals("id = -1257 =============== end ===============", string5);
String string6 = EWrapperMsgGenerator.tickOptionComputation(10, 10, (-2065.6955583549907), 10, (-2065.6955583549907), (-9.09764175293838));
assertEquals("id=10 bidOptComp: vol = N/A delta = N/A", string6);
String string7 = EWrapperMsgGenerator.execDetailsEnd((-1698));
assertEquals("reqId = -1698 =============== end ===============", string7);
String string8 = EWrapperMsgGenerator.updateNewsBulletin((-2446), 0, "B aK@s}=u@W3", "O");
assertEquals("MsgId=-2446 :: MsgType=0 :: Origin=O :: Message=B aK@s}=u@W3", string8);
String string9 = EWrapperMsgGenerator.updateMktDepthL2(0, (-1666), "", (-2446), 0, (-1592.7543501), (-1698));
assertEquals("updateMktDepth: 0 -1666 -2446 0 -1592.7543501 -1698", string9);
String string10 = EWrapperMsgGenerator.contractDetailsEnd((-1257));
assertEquals("reqId = -1257 =============== end ===============", string10);
Vector<Object> vector0 = new Vector<Object>();
Contract contract0 = new Contract(10, "", "C[", "id = -1257 =============== end ===============", (-2065.6955583549907), "", "reqId = -1257 =============== end ===============", "current time = 0 (Jan 1, 1970 12:00:00 AM)", "Connection Closed", "7)2-1&xZ>6)", vector0, "", false, "updateMktDepth: 0 -1666 -2446 0 -1592.7543501 -1698", "B[nGLi@'`Xhh6km<.U");
String string11 = EWrapperMsgGenerator.contractMsg(contract0);
assertEquals("conid = 10\nsymbol = \nsecType = C[\nexpiry = id = -1257 =============== end ===============\nstrike = -2065.6955583549907\nright = \nmultiplier = reqId = -1257 =============== end ===============\nexchange = current time = 0 (Jan 1, 1970 12:00:00 AM)\nprimaryExch = \ncurrency = Connection Closed\nlocalSymbol = 7)2-1&xZ>6)\n", string11);
}
/**
//Test case number: 12
/*Coverage entropy=2.1972245773362196
*/
@Test(timeout = 4000)
public void test12() throws Throwable {
EWrapperMsgGenerator eWrapperMsgGenerator0 = new EWrapperMsgGenerator();
Contract contract0 = new Contract();
EWrapperMsgGenerator.contractMsg(contract0);
contract0.m_right = "SCANNER PARAMETERS:";
String string0 = EWrapperMsgGenerator.contractMsg(contract0);
assertEquals("conid = 0\nsymbol = null\nsecType = null\nexpiry = null\nstrike = 0.0\nright = SCANNER PARAMETERS:\nmultiplier = null\nexchange = null\nprimaryExch = null\ncurrency = null\nlocalSymbol = null\n", string0);
String string1 = EWrapperMsgGenerator.currentTime(0L);
assertEquals("current time = 0 (Jan 1, 1970 12:00:00 AM)", string1);
String string2 = EWrapperMsgGenerator.orderStatus(0, "SCANNER PARAMETERS:", 0, 0, 587.4099, 2863, 2863, 0.0, 2863, (String) null);
assertEquals("order status: orderId=0 clientId=2863 permId=2863 status=SCANNER PARAMETERS: filled=0 remaining=0 avgFillPrice=587.4099 lastFillPrice=0.0 parent Id=2863 whyHeld=null", string2);
String string3 = EWrapperMsgGenerator.contractDetailsEnd(1113);
assertEquals("reqId = 1113 =============== end ===============", string3);
String string4 = EWrapperMsgGenerator.tickSnapshotEnd(1113);
assertEquals("id=1113 =============== end ===============", string4);
String string5 = EWrapperMsgGenerator.tickEFP(27, 27, 0.0, (String) null, (-1.0), 13, "current time = 0 (Jan 1, 1970 12:00:00 AM)", (-1.0), (-2230.2983747));
assertEquals("id=27 OptionCallOpenInterest: basisPoints = 0.0/null impliedFuture = -1.0 holdDays = 13 futureExpiry = current time = 0 (Jan 1, 1970 12:00:00 AM) dividendImpact = -1.0 dividends to expiry = -2230.2983747", string5);
String string6 = EWrapperMsgGenerator.tickSize((-1439), (-1), 3450);
assertEquals("id=-1439 unknown=3450", string6);
String string7 = EWrapperMsgGenerator.scannerParameters("QHc3");
assertEquals("SCANNER PARAMETERS:\nQHc3", string7);
}
/**
//Test case number: 13
/*Coverage entropy=1.4750763110546947
*/
@Test(timeout = 4000)
public void test13() throws Throwable {
String string0 = EWrapperMsgGenerator.updateNewsBulletin(0, 0, "`F$ip>E#r?", "RL:v`T#XJE");
assertEquals("MsgId=0 :: MsgType=0 :: Origin=RL:v`T#XJE :: Message=`F$ip>E#r?", string0);
String string1 = EWrapperMsgGenerator.managedAccounts("LO,6W'#wwx'ut7");
assertEquals("Connected : The list of managed accounts are : [LO,6W'#wwx'ut7]", string1);
String string2 = EWrapperMsgGenerator.tickOptionComputation(0, 0, 0.0, 0, 1.0, 1.7976931348623157E308);
assertEquals("id=0 bidSize: vol = 0.0 delta = 0.0", string2);
String string3 = EWrapperMsgGenerator.receiveFA(0, "RL:v`T#XJE");
assertEquals("FA: null RL:v`T#XJE", string3);
String string4 = EWrapperMsgGenerator.updateMktDepthL2(1964, 0, (String) null, 0, (-2399), (-2399), 0);
assertEquals("updateMktDepth: 1964 0 null 0 -2399 -2399.0 0", string4);
}
/**
//Test case number: 14
/*Coverage entropy=2.1972245773362196
*/
@Test(timeout = 4000)
public void test14() throws Throwable {
String string0 = EWrapperMsgGenerator.updateAccountValue("notes = ", "", "notes = ", "zmy:>CqFW");
assertEquals("updateAccountValue: notes = notes = zmy:>CqFW", string0);
String string1 = EWrapperMsgGenerator.execDetailsEnd((-3212));
assertEquals("reqId = -3212 =============== end ===============", string1);
EWrapperMsgGenerator.managedAccounts("notes = ");
String string2 = EWrapperMsgGenerator.tickSnapshotEnd(102);
assertEquals("id=102 =============== end ===============", string2);
String string3 = EWrapperMsgGenerator.openOrderEnd();
assertEquals(" =============== end ===============", string3);
String string4 = EWrapperMsgGenerator.fundamentalData(1040, "Connected : The list of managed accounts are : [notes = ]");
assertEquals("id = 1040 len = 57\nConnected : The list of managed accounts are : [notes = ]", string4);
String string5 = EWrapperMsgGenerator.tickGeneric(1, (-3212), (-2458.08211));
assertEquals("id=1 unknown=-2458.08211", string5);
String string6 = EWrapperMsgGenerator.contractDetailsEnd(1040);
assertEquals("reqId = 1040 =============== end ===============", string6);
String string7 = EWrapperMsgGenerator.accountDownloadEnd("Connected : The list of managed accounts are : [notes = ]");
assertEquals("accountDownloadEnd: Connected : The list of managed accounts are : [notes = ]", string7);
String string8 = EWrapperMsgGenerator.managedAccounts("");
assertEquals("Connected : The list of managed accounts are : []", string8);
}
/**
//Test case number: 15
/*Coverage entropy=1.8143075196071252
*/
@Test(timeout = 4000)
public void test15() throws Throwable {
String string0 = EWrapperMsgGenerator.scannerParameters("\"7\".1k*FdC{<");
assertEquals("SCANNER PARAMETERS:\n\"7\".1k*FdC{<", string0);
String string1 = EWrapperMsgGenerator.updateAccountTime((String) null);
assertEquals("updateAccountTime: null", string1);
Contract contract0 = new Contract();
Vector<Integer> vector0 = new Vector<Integer>();
Integer integer0 = new Integer((-1786));
vector0.add(integer0);
contract0.m_comboLegs = vector0;
contract0.m_primaryExch = null;
String string2 = EWrapperMsgGenerator.updatePortfolio(contract0, 0, 0.0, 0.0, 0, 0.0, 0.0, (String) null);
assertEquals("updatePortfolio: conid = 0\nsymbol = null\nsecType = null\nexpiry = null\nstrike = 0.0\nright = null\nmultiplier = null\nexchange = null\nprimaryExch = null\ncurrency = null\nlocalSymbol = null\n0 0.0 0.0 0.0 0.0 0.0 null", string2);
String string3 = EWrapperMsgGenerator.execDetailsEnd(0);
contract0.m_currency = "putable = ";
String string4 = EWrapperMsgGenerator.contractDetailsEnd(0);
assertTrue(string4.equals((Object)string3));
String string5 = EWrapperMsgGenerator.tickOptionComputation(0, 0, 0, (-225.837896720328), 0, 1.0);
assertEquals("id=0 bidSize: vol = 0.0 delta = N/A", string5);
Order order0 = new Order();
OrderState orderState0 = new OrderState();
EWrapperMsgGenerator.openOrder(0, contract0, order0, orderState0);
String string6 = EWrapperMsgGenerator.tickOptionComputation((-1738), 13, 0, 31.942258105037, 1.7976931348623157E308, 0);
assertEquals("id=-1738 modelOptComp: vol = 0.0 delta = N/A: modelPrice = N/A: pvDividend = 0.0", string6);
}
/**
//Test case number: 16
/*Coverage entropy=0.639031859650177
*/
@Test(timeout = 4000)
public void test16() throws Throwable {
EWrapperMsgGenerator.nextValidId(1987);
EWrapperMsgGenerator.nextValidId(1987);
EWrapperMsgGenerator.tickOptionComputation(0, 10, 2419.8984, 1987, 2419.8984, 2419.8984);
Vector<Object> vector0 = new Vector<Object>();
String string0 = EWrapperMsgGenerator.tickOptionComputation((-513), 13, 1987, (-1.0), 978.92365682549, 0.0);
Contract contract0 = new Contract();
Order order0 = new Order();
OrderState orderState0 = new OrderState();
String string1 = EWrapperMsgGenerator.openOrder(2706, contract0, order0, orderState0);
assertFalse(string1.equals((Object)string0));
}
/**
//Test case number: 17
/*Coverage entropy=2.0431918705451206
*/
@Test(timeout = 4000)
public void test17() throws Throwable {
EWrapperMsgGenerator.scannerParameters("\"7\".1k*FdC{<");
EWrapperMsgGenerator.updateAccountTime((String) null);
Contract contract0 = new Contract();
Vector<Integer> vector0 = new Vector<Integer>();
Integer integer0 = new Integer((-1786));
vector0.add(integer0);
contract0.m_comboLegs = vector0;
contract0.m_primaryExch = null;
EWrapperMsgGenerator.updatePortfolio(contract0, 0, 0.0, 0.0, 0, 0.0, 0.0, (String) null);
EWrapperMsgGenerator.execDetailsEnd(0);
contract0.m_currency = "putable = ";
EWrapperMsgGenerator.contractDetailsEnd(0);
String string0 = EWrapperMsgGenerator.tickOptionComputation(0, 0, 1.7976931348623157E308, 636.0, 31.942258105037, (-1786));
System.setCurrentTimeMillis((-1786));
Order order0 = new Order();
OrderState orderState0 = new OrderState();
String string1 = EWrapperMsgGenerator.openOrder(Integer.MAX_VALUE, contract0, order0, orderState0);
assertFalse(string1.equals((Object)string0));
}
/**
//Test case number: 18
/*Coverage entropy=0.6365141682948128
*/
@Test(timeout = 4000)
public void test18() throws Throwable {
EWrapperMsgGenerator.tickOptionComputation((-691), (-691), 1.0, 1087.1553547611998, (-2567.0202), 0.0);
Contract contract0 = new Contract();
Order order0 = new Order();
contract0.clone();
UnderComp underComp0 = new UnderComp();
underComp0.m_price = 1.0;
contract0.m_underComp = underComp0;
// Undeclared exception!
try {
EWrapperMsgGenerator.openOrder(840, contract0, order0, (OrderState) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.ib.client.EWrapperMsgGenerator", e);
}
}
/**
//Test case number: 19
/*Coverage entropy=0.6001660731596457
*/
@Test(timeout = 4000)
public void test19() throws Throwable {
EWrapperMsgGenerator.nextValidId(1987);
EWrapperMsgGenerator.nextValidId(1987);
EWrapperMsgGenerator.tickOptionComputation(0, 10, 2419.8984, 1987, 2419.8984, 2419.8984);
Vector<Object> vector0 = new Vector<Object>();
EWrapperMsgGenerator.tickOptionComputation((-513), 13, 1987, (-1.0), 978.92365682549, 0.0);
EWrapperMsgGenerator.tickOptionComputation(1987, 13, 13, 1587.410301, 2419.8984, (-1.0));
System.setCurrentTimeMillis((-513));
Order order0 = new Order();
OrderState orderState0 = new OrderState();
// Undeclared exception!
try {
EWrapperMsgGenerator.openOrder(45, (Contract) null, order0, orderState0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.ib.client.EWrapperMsgGenerator", e);
}
}
/**
//Test case number: 20
/*Coverage entropy=0.6829081047004717
*/
@Test(timeout = 4000)
public void test20() throws Throwable {
System.setCurrentTimeMillis(290L);
Contract contract0 = new Contract();
String string0 = EWrapperMsgGenerator.tickOptionComputation((-1842503885), 1378, 362.41, 1660.39, 2146596587, 1.7976931348623157E308);
Order order0 = new Order();
OrderState orderState0 = new OrderState();
order0.m_algoStrategy = "zKdi|s";
Contract contract1 = new Contract(2146841841, "[B>I=BO;", ";KpA", (String) null, (-637.92738), (String) null, "j&1|'v?", "com.ib.client.UnderComp", "OptionImpliedVolatility", (String) null, contract0.m_comboLegs, (String) null, false, (String) null, "ktq!");
String string1 = EWrapperMsgGenerator.openOrder(1805, contract1, order0, orderState0);
assertFalse(string1.equals((Object)string0));
}
/**
//Test case number: 21
/*Coverage entropy=0.639031859650177
*/
@Test(timeout = 4000)
public void test21() throws Throwable {
String string0 = EWrapperMsgGenerator.FINANCIAL_ADVISOR;
EWrapperMsgGenerator.nextValidId(1987);
EWrapperMsgGenerator.tickOptionComputation(5, 5, 2419.8984, 1987, 2419.8984, 2419.8984);
EWrapperMsgGenerator.tickOptionComputation(6, 13, (-1.0), 5, 6, 1141.991);
OrderState orderState0 = new OrderState();
EWrapperMsgGenerator.tickOptionComputation(1, 13, 33, (-1.0), 1141.991, (-1.0));
EWrapperMsgGenerator.contractDetailsEnd(2188);
EWrapperMsgGenerator.tickOptionComputation((-513), 13, 1141.991, 0.0, (-1888.749), 1791.72);
OrderState orderState1 = new OrderState();
EWrapperMsgGenerator.tickOptionComputation(1, 13, 679.52, 0.0, 13, (-1.0));
System.setCurrentTimeMillis(6);
EWrapperMsgGenerator.tickOptionComputation(5, 13, 679.52, 1141.991, 33, 6);
System.setCurrentTimeMillis(1L);
}
/**
//Test case number: 22
/*Coverage entropy=0.9649629230074277
*/
@Test(timeout = 4000)
public void test22() throws Throwable {
System.setCurrentTimeMillis(290L);
Contract contract0 = new Contract();
Order order0 = new Order();
OrderState orderState0 = new OrderState((String) null, (String) null, (String) null, "", Integer.MAX_VALUE, 0, '?', (String) null, (String) null);
order0.m_algoStrategy = "dj'6i|s";
order0.m_algoParams = contract0.m_comboLegs;
order0.m_scalePriceIncrement = (-1.0);
Contract contract1 = new Contract(2146841841, "[B>EI3=BO;", ";KpA", (String) null, (-636.9848928076217), (String) null, (String) null, (String) null, (String) null, (String) null, contract0.m_comboLegs, (String) null, false, (String) null, "kt!");
EWrapperMsgGenerator.openOrder(Integer.MAX_VALUE, contract1, order0, orderState0);
EWrapperMsgGenerator.openOrder((-419), contract0, order0, orderState0);
EWrapperMsgGenerator.openOrder(Integer.MAX_VALUE, contract0, order0, orderState0);
String string0 = EWrapperMsgGenerator.tickGeneric('m', Integer.MAX_VALUE, 1.7976931348623157E308);
assertEquals("id=109 unknown=1.7976931348623157E308", string0);
String string1 = EWrapperMsgGenerator.tickOptionComputation(0, 0, 1.7976931348623157E308, 0.0, 1587.6279306454219, (-1508.3048058704746));
assertEquals("id=0 bidSize: vol = N/A delta = 0.0", string1);
}
/**
//Test case number: 23
/*Coverage entropy=0.2711893730418441
*/
@Test(timeout = 4000)
public void test23() throws Throwable {
System.setCurrentTimeMillis(1L);
String string0 = EWrapperMsgGenerator.tickOptionComputation((-4641), (-866), (-1425.66), 1L, 1801.0, (-4641));
assertEquals("id=-4641 unknown: vol = N/A delta = 1.0", string0);
Contract contract0 = new Contract(13, "id=-4641 unknown: vol = N/A delta = 1.0", "K0f", "id=-4641 unknown: vol = N/A delta = 1.0", 1L, "com.ib.client.TagValue", (String) null, "dj'6i|s", "/N*+ q", "/N*+ q", (Vector) null, (String) null, false, (String) null, "<nZD[<Fr}bhsLrY./a");
contract0.m_localSymbol = "/N*+ q";
Order order0 = new Order();
contract0.m_secId = null;
OrderState orderState0 = new OrderState();
EWrapperMsgGenerator.openOrder((-1444), contract0, order0, orderState0);
System.setCurrentTimeMillis((-819L));
System.setCurrentTimeMillis(0);
System.setCurrentTimeMillis(0);
String string1 = EWrapperMsgGenerator.tickOptionComputation(1, 13, 1143.5626340092024, 861.28, 986.37915462, 0.0);
assertEquals("id=1 modelOptComp: vol = 1143.5626340092024 delta = N/A: modelPrice = 986.37915462: pvDividend = 0.0", string1);
System.setCurrentTimeMillis(3);
EWrapperMsgGenerator.tickOptionComputation((-2801), (-2317), Integer.MAX_VALUE, 986.37915462, 0.0, 0);
String string2 = EWrapperMsgGenerator.tickOptionComputation(0, 13, 13, 2419.8984, 1.7976931348623157E308, 1.7976931348623157E308);
assertEquals("id=0 modelOptComp: vol = 13.0 delta = N/A: modelPrice = N/A: pvDividend = N/A", string2);
}
/**
//Test case number: 24
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test24() throws Throwable {
System.setCurrentTimeMillis(290L);
Contract contract0 = new Contract();
Order order0 = new Order();
OrderState orderState0 = new OrderState((String) null, (String) null, (String) null, "", Integer.MAX_VALUE, 0, '?', (String) null, (String) null);
orderState0.m_status = null;
order0.m_algoStrategy = "dj'6i|s";
Contract contract1 = new Contract((-180), "+D,L", "BAG", "U>V/'&(gP.O", 1.7976931348623157E308, (String) null, (String) null, "dj'6i|s", "", (String) null, (Vector) null, "0N6Jq15lI}e", false, (String) null, "");
EWrapperMsgGenerator.openOrder(4834, contract1, order0, orderState0);
OrderState orderState1 = new OrderState();
Order order1 = new Order();
System.setCurrentTimeMillis(1000L);
System.setCurrentTimeMillis(0L);
Order order2 = new Order();
EWrapperMsgGenerator.openOrder(1665, contract0, order0, orderState1);
EWrapperMsgGenerator.openOrder(0, contract0, order2, orderState1);
EWrapperMsgGenerator.openOrder((-1016), contract0, order2, orderState1);
System.setCurrentTimeMillis(3);
System.setCurrentTimeMillis(Integer.MAX_VALUE);
}
}
| 53.493094 | 626 | 0.662527 |
dc52c6045eb238b5d0f78ee1ada466931ac0e125
| 287 |
package com.batch.android.messaging.view.styled;
import java.util.Map;
/**
* Interface describing a styleable view.
* A styleable view will understand CSS-like rules and apply them on itself.
*
*/
public interface Styleable
{
void applyStyleRules(Map<String, String> rules);
}
| 20.5 | 76 | 0.745645 |
5ff3cd679180dd1eafc0af1a2ee2df28bc1cbac2
| 1,187 |
package com.spiderrobotman.Gamemode4Engine.command;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
/**
* Project: Gamemode4Engine
* Author: SpiderRobotMan
* Date: May 18 2016
* Website: http://www.spiderrobotman.com
*/
public class RealNameTabCompleter implements TabCompleter {
@Override
public List<String> onTabComplete(CommandSender cs, Command command, String s, String[] args) {
if (command.getName().equalsIgnoreCase("realname") && args.length == 1) {
if (cs instanceof Player) {
Player sender = (Player) cs;
List<String> list = new ArrayList<>();
for (String name : NickCommand.nicks.values()) {
String flat = ChatColor.stripColor(name.replace("&", "§"));
if (!name.isEmpty() && flat.beginsWith(args[0])) {
list.add(flat);
}
}
return list;
}
}
return null;
}
}
| 28.95122 | 99 | 0.600674 |
197239a8aea0b2dae452f8a8c5018ef0836dffc8
| 3,157 |
package com.kahveciefendi.shop.models;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* Model representing a row in the table orders.
*
* @author Ayhan Dardagan
*
*/
@Entity
@Table(name = "orders")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "order_id", unique = true, nullable = false)
private Long id;
@Column(name = "date", length = 10, nullable = false)
private String date;
@Column(name = "total_price", nullable = false)
private double totalPrice;
@Column(name = "discount", nullable = false)
private double discount;
@Column(name = "discount_reason")
private String discountReason;
@Column(name = "total_price_with_discount", nullable = false)
private double totalPriceWithDiscount;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "user_id", nullable = false)
private User parentUser;
@OneToMany(mappedBy = "parentOrder", cascade = CascadeType.ALL, orphanRemoval = true, //
fetch = FetchType.LAZY)
@Column(nullable = false)
private List<OrderedDrink> orderedDrinks;
/**
* Constructor.
*/
public Order() {
this.orderedDrinks = new ArrayList<OrderedDrink>(10);
}
/**
* Constructor.
*
* @param date
* Order date in format "YYYY-MM"
* @param parentUser
* {@code User} parent
*/
public Order(String date, User parentUser) {
this.date = date;
this.parentUser = parentUser;
this.orderedDrinks = new ArrayList<OrderedDrink>(10);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public double getTotalPrice() {
return totalPrice;
}
public double getDiscount() {
return discount;
}
public void setDiscount(double discount) {
this.discount = discount;
}
public String getDiscountReason() {
return discountReason;
}
public void setDiscountReason(String discountReason) {
this.discountReason = discountReason;
}
public double getTotalPriceWithDiscount() {
return totalPriceWithDiscount;
}
public void setTotalPriceWithDiscount(double totalPriceWithDiscount) {
this.totalPriceWithDiscount = totalPriceWithDiscount;
}
public void setTotalPrice(double totalPrice) {
this.totalPrice = totalPrice;
}
public User getParentUser() {
return parentUser;
}
public void setParentUser(User parentUser) {
this.parentUser = parentUser;
}
public List<OrderedDrink> getOrderedDrinks() {
return orderedDrinks;
}
public void setOrderedDrinks(List<OrderedDrink> orderedDrinks) {
this.orderedDrinks = orderedDrinks;
}
}
| 22.076923 | 90 | 0.706684 |
ef762c1a6704fa598928bf8c885fa8fc0f095ffc
| 923 |
package io.frictionlessdata.tableschema.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import java.math.BigDecimal;
import java.time.Year;
@JsonPropertyOrder({
"countryName", "countryCode", "year", "amount"
})
public class GrossDomesticProductBean {
//CSV header columns:
// Country Name,Country Code,Year,Value
@JsonProperty("Country Name")
String countryName;
@JsonProperty("Country Code")
String countryCode;
@JsonProperty("Year")
Year year;
@JsonProperty("Value")
BigDecimal amount;
@Override
public String toString() {
return "GrossDomesticProductBean{" +
"countryName='" + countryName + '\'' +
", countryCode='" + countryCode + '\'' +
", year=" + year +
", amount=" + amount +
'}';
}
}
| 23.075 | 58 | 0.619718 |
55e63cff3953a08ba0e881f4200f832466d5b65e
| 5,666 |
/*
* Copyright 2015 Open mHealth
*
* 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.openmhealth.schema.domain.omh;
import org.testng.annotations.Test;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.openmhealth.schema.domain.omh.BloodGlucoseUnit.MILLIGRAMS_PER_DECILITER;
import static org.openmhealth.schema.domain.omh.BloodSpecimenType.PLASMA;
import static org.openmhealth.schema.domain.omh.BloodSpecimenType.WHOLE_BLOOD;
import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MEDIAN;
import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MINIMUM;
import static org.openmhealth.schema.domain.omh.TemporalRelationshipToMeal.FASTING;
import static org.openmhealth.schema.domain.omh.TemporalRelationshipToSleep.BEFORE_SLEEPING;
import static org.openmhealth.schema.domain.omh.TemporalRelationshipToSleep.ON_WAKING;
import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH;
/**
* @author Emerson Farrugia
*/
public class BloodGlucoseUnitTests extends SerializationUnitTests {
public static final String SCHEMA_FILENAME = "schema/omh/blood-glucose-1.0.json";
@Test(expectedExceptions = NullPointerException.class)
public void constructorShouldThrowExceptionOnUndefinedBloodGlucose() {
new BloodGlucose.Builder(null);
}
@Test
public void buildShouldConstructMeasureUsingOnlyRequiredProperties() {
TypedUnitValue<BloodGlucoseUnit> bloodGlucoseLevel = new TypedUnitValue<>(MILLIGRAMS_PER_DECILITER, 110);
BloodGlucose bloodGlucose = new BloodGlucose.Builder(bloodGlucoseLevel).build();
assertThat(bloodGlucose, notNullValue());
assertThat(bloodGlucose.getBloodGlucose(), equalTo(bloodGlucoseLevel));
assertThat(bloodGlucose.getBloodSpecimenType(), nullValue());
assertThat(bloodGlucose.getTemporalRelationshipToMeal(), nullValue());
assertThat(bloodGlucose.getTemporalRelationshipToSleep(), nullValue());
assertThat(bloodGlucose.getEffectiveTimeFrame(), nullValue());
assertThat(bloodGlucose.getDescriptiveStatistic(), nullValue());
assertThat(bloodGlucose.getUserNotes(), nullValue());
}
@Test
public void buildShouldConstructMeasureUsingOptionalProperties() {
TypedUnitValue<BloodGlucoseUnit> bloodGlucoseLevel = new TypedUnitValue<>(MILLIGRAMS_PER_DECILITER, 110);
BloodGlucose bloodGlucose = new BloodGlucose.Builder(bloodGlucoseLevel)
.setBloodSpecimenType(WHOLE_BLOOD)
.setTemporalRelationshipToMeal(FASTING)
.setTemporalRelationshipToSleep(BEFORE_SLEEPING)
.setEffectiveTimeFrame(FIXED_MONTH)
.setDescriptiveStatistic(MEDIAN)
.setUserNotes("feeling fine")
.build();
assertThat(bloodGlucose, notNullValue());
assertThat(bloodGlucose.getBloodGlucose(), equalTo(bloodGlucoseLevel));
assertThat(bloodGlucose.getBloodSpecimenType(), equalTo(WHOLE_BLOOD));
assertThat(bloodGlucose.getTemporalRelationshipToMeal(), equalTo(FASTING));
assertThat(bloodGlucose.getTemporalRelationshipToSleep(), equalTo(BEFORE_SLEEPING));
assertThat(bloodGlucose.getEffectiveTimeFrame(), equalTo(FIXED_MONTH));
assertThat(bloodGlucose.getDescriptiveStatistic(), equalTo(MEDIAN));
assertThat(bloodGlucose.getUserNotes(), equalTo("feeling fine"));
}
@Override
protected String getSchemaFilename() {
return SCHEMA_FILENAME;
}
@Test
public void measureShouldSerializeCorrectly() throws Exception {
BloodGlucose measure = new BloodGlucose.Builder(new TypedUnitValue<>(MILLIGRAMS_PER_DECILITER, 120))
.setBloodSpecimenType(PLASMA)
.setTemporalRelationshipToMeal(FASTING)
.setTemporalRelationshipToSleep(ON_WAKING)
.setEffectiveTimeFrame(FIXED_MONTH)
.setDescriptiveStatistic(MINIMUM)
.setUserNotes("feeling fine")
.build();
String document = "{\n" +
" \"blood_glucose\": {\n" +
" \"unit\": \"mg/dL\",\n" +
" \"value\": 120\n" +
" },\n" +
" \"effective_time_frame\": {\n" +
" \"time_interval\": {\n" +
" \"start_date_time\": \"2015-10-01T00:00:00-07:00\",\n" +
" \"end_date_time\": \"2015-11-01T00:00:00-07:00\"\n" +
" }\n" +
" },\n" +
" \"blood_specimen_type\": \"plasma\",\n" +
" \"temporal_relationship_to_meal\": \"fasting\",\n" +
" \"temporal_relationship_to_sleep\": \"on waking\",\n" +
" \"descriptive_statistic\": \"minimum\",\n" +
" \"user_notes\": \"feeling fine\"\n" +
"}";
serializationShouldCreateValidDocument(measure, document);
deserializationShouldCreateValidObject(document, measure);
}
}
| 44.614173 | 113 | 0.680904 |
69aa420fa1fa093756aa627c483586032f9fe6bb
| 902 |
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Employee;
@WebServlet("/CreateConfirm")
public class CreateConfirm extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("id");
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
Employee emp = new Employee(id, name, age);
request.setAttribute("emp", emp);
String url = "/WEB-INF/jsp/createConfirm.jsp";
request.getRequestDispatcher(url).forward(request, response);
}
}
}
| 29.096774 | 80 | 0.773836 |
08561ab4ffc5fea16ec7c969185dff35592bbc97
| 12,192 |
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.InputMismatchException;
import java.util.MissingFormatArgumentException;
import java.util.Scanner;
public class Aplicacao{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Banco banco = new Banco();
BigDecimal valor = BigDecimal.valueOf(0);
Conta conta;
int opcao_menu = 1, tipo_conta = 0;
boolean excecao = false;
String nome = "", CPF_CNPJ = "", numero_conta = "", agencia = "", numero_conta_remetente = "", numero_conta_destinatario = "";
Pessoa titular;
do{ // Loop do programa
do{ // Loop do menu
try{
excecao = false;
System.out.print("\n0 - Sair.\n1 - Abrir nova conta.\n2 - Sacar.\n3 - Depositar.\n4 - Transferência.\n5 - Investir.\n6 - Consultar saldo.\n-> ");
opcao_menu = input.nextInt();
if(opcao_menu < 0 || opcao_menu > 6){
System.out.println("\nInsira um número inteiro dentro do intervalo do menu para prosseguir.");
input.nextLine();
}
}
catch(InputMismatchException e){ // Caso não seja um número inteiro inserido
System.out.println("\nInsira um número inteiro dentro do intervalo do menu para prosseguir.");
input.nextLine();
excecao = true;
}
}while(excecao || opcao_menu < 0 || opcao_menu > 6);
input.nextLine(); // Limpa o buffer (remove enter)
switch(opcao_menu){ // Ação a se tomar de acordo com a escolha do menu
case 1: // Abre nova conta
// Coleta inicialmnte as informações da pessoa
do{
System.out.print("Digite o nome do titular da nova conta: ");
nome = input.nextLine();
}while(!nome.matches("[A-Za-z]+")); // Verifica se o nome possui apenas letras
do{
System.out.print("Insira o CPF/CNPJ do titular: ");
CPF_CNPJ = input.nextLine();
}while(!CPF_CNPJ.matches("[0-9]+") || CPF_CNPJ.length() != 11 && CPF_CNPJ.length() != 14); // Confere se há somente 11 ou 14 números
if(CPF_CNPJ.length() == 11)
titular = new PessoaFisica(nome, formatarCPF(CPF_CNPJ));
else
titular = new PessoaJuridica(nome, formatarCNPJ(CPF_CNPJ));
// Depois coleta-se as informações da conta a ser criada
do{
try{
excecao = false;
System.out.println("Insira o tipo de conta a ser criada.\n\t1 - Conta corrente.\n\t2 - Conta investimento.\n\t3 - Conta poupança.");
System.out.print("-> ");
tipo_conta = input.nextInt();
}
catch(InputMismatchException e){
System.out.println("\nInsira um número inteiro dentro do intervalo para prosseguir.");
input.nextLine();
excecao = true;
}
}while(excecao || tipo_conta < 1 || tipo_conta > 3);
input.nextLine(); // Limpa o buffer (remove enter)
do{
System.out.print("Insira o número da nova conta.\n-> ");
numero_conta = input.nextLine();
}while(!numero_conta.matches("[0-9]+")); // Continua até que a string tenha apenas números
do{
System.out.print("Insira a agência da nova conta.\n-> ");
agencia = input.nextLine();
}while(!agencia.matches("[0-9]+")); // Continua até que a string tenha apenas números
// Para depois criar a conta no banco
try{
if(banco.abrirConta(tipo_conta == 1 ? new ContaCorrente(numero_conta, titular, agencia) : tipo_conta == 2 ? new ContaInvestimento(numero_conta, titular, agencia) : new ContaPoupanca(numero_conta, titular, agencia)))
System.out.println("Conta criada com sucesso.");
else
System.out.println("Falha ao criar nova conta: número de conta já existente no sistema.");
}
catch(MissingFormatArgumentException e){
System.out.println(e.getFormatSpecifier());
}
break;
case 2: // Sacar
do{
System.out.print("\nInsira o número da conta a ser sacada.\n-> ");
numero_conta = input.nextLine();
}while(!numero_conta.matches("[0-9]+")); // Verifica se há somente números na string
do{
try{
excecao = false;
System.out.print("\nInsira a quantia a ser sacada.\n-> ");
valor = input.nextBigDecimal();
}
catch(InputMismatchException e){
System.out.println("Insira um número positivo para continuar.");
input.nextLine();
excecao = true;
}
}while(excecao || valor.compareTo(BigDecimal.valueOf(0)) <= 0); // Verifica se o valor é positivo
if(banco.sacar(numero_conta, valor))
System.out.println("R$" + valor.setScale(2, RoundingMode.HALF_UP) + " sacado com sucesso.");
else
System.out.println("Erro ao sacar: valor insuficiente na conta ou conta inexistente.");
break;
case 3: // Depositar (conta poupança/corrente)
do{
System.out.print("\nInsira o número da conta que receberá o depósito.\n-> ");
numero_conta = input.nextLine();
}while(!numero_conta.matches("[0-9]+")); // Verifica se há somente números na string
do{
try{
excecao = false;
System.out.print("\nInsira a quantia a ser depositada.\n-> ");
valor = input.nextBigDecimal();
}
catch(InputMismatchException e){
System.out.println("Insira um número positivo para continuar.");
input.nextLine();
excecao = true;
}
}while(excecao || valor.compareTo(BigDecimal.valueOf(0)) <= 0); // Verifica se o valor é positivo
if(banco.depositar(numero_conta, valor))
System.out.println("R$" + valor.setScale(2, RoundingMode.HALF_UP) + " depositado com sucesso.");
else
System.out.println("Erro ao depositar: conta inexistente ou do tipo investimento.");
break;
case 4: // Transferência
do{
System.out.print("\nInsira o número da conta que será descontada a transferência.\n-> ");
numero_conta_remetente = input.nextLine();
}while(!numero_conta_remetente.matches("[0-9]+")); // Verifica se há somente números na string
do{
System.out.print("\nInsira o número da conta que receberá a transferência.\n-> ");
numero_conta_destinatario = input.nextLine();
}while(!numero_conta_destinatario.matches("[0-9]+")); // Verifica se há somente números na string
do{
try{
excecao = false;
System.out.print("\nInsira a quantia a ser transferida.\n-> ");
valor = input.nextBigDecimal();
}
catch(InputMismatchException e){
System.out.println("Insira um número positivo para continuar.");
input.nextLine();
excecao = true;
}
}while(excecao || valor.compareTo(BigDecimal.valueOf(0)) <= 0); // Verifica se o valor é positivo
if(banco.transferir(numero_conta_destinatario, numero_conta_remetente, valor))
System.out.println("Transferência de R$" + valor.setScale(2, RoundingMode.HALF_UP) + " da conta " + numero_conta_remetente + " para a conta " + numero_conta_destinatario + " realizado com sucesso.");
else
System.out.println("Não foi possível realizar a transferência por um dos seguintes motivos:\n\tSaldo do remetente insuficiente.\n\tConta do remetente inexistente no sistema.\n\tConta do destinatário inexistente no sistema.");
break;
case 5: // Investir (conta investimento)
do{
System.out.print("\nInsira o número da conta que receberá o investimento.\n-> ");
numero_conta = input.nextLine();
}while(!numero_conta.matches("[0-9]+")); // Verifica se há somente números na string
do{
try{
excecao = false;
System.out.print("\nInsira a quantia a ser investida.\n-> ");
valor = input.nextBigDecimal();
}
catch(InputMismatchException e){
System.out.println("Insira um número positivo para continuar.");
input.nextLine();
excecao = true;
}
}while(excecao || valor.compareTo(BigDecimal.valueOf(0)) <= 0); // Verifica se o valor é positivo
if(banco.investir(numero_conta, valor))
System.out.println("R$" + valor.setScale(2, RoundingMode.HALF_UP) + " investido com sucesso.");
else
System.out.println("Erro ao depositar: conta inexistente ou dos tipos corrente/poupança.");
break;
case 6: // Consultar saldo
// Coleta o número da conta
do{
System.out.print("\nInsira o número da conta a ser consultada.\n-> ");
numero_conta = input.nextLine();
}while(!numero_conta.matches("[0-9]+")); // Verifica se há somente números na string
// Para procurar na lista de contas se a mesma existe
conta = banco.procurarConta(numero_conta);
if(conta == null) // Caso a conta não seja encontrada na lista de contas, o valor é nulo
System.out.println("Conta inexistente no sistema.");
else
System.out.println(conta.toString());
break;
}
}while(opcao_menu != 0);
}
// Envia o CPF formatado (00000000000 -> 000.000.000-00)
public static String formatarCPF(String CPF){
return CPF.substring(0,3) + '.' + CPF.substring(3,6) + '.' + CPF.substring(6,9) + '-' + CPF.substring(9);
}
// Envia o CNPJ formatado (00000000000000 -> 00.000.000/0000-00)
public static String formatarCNPJ(String CNPJ){
return CNPJ.substring(0,2) + "." + CNPJ.substring(2,5) + "." + CNPJ.substring(5,8) + "/" + CNPJ.substring(8,12) + "-" + CNPJ.substring(12);
}
}
| 60.356436 | 249 | 0.492454 |
6b8724f028796cd766fa1cfc5cc9a2dc6d55bc2e
| 2,092 |
package com.utopia.upload.upload;
import android.util.Base64;
import com.utopia.upload.bean.UploadFile;
import java.io.UnsupportedEncodingException;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
public class FileUploadRequest extends FormUploadRequest {
private List<UploadFile> files;
public FileUploadRequest(String url, List<UploadFile> files, Map<String, String> params, Map<String, String> headers) {
this.url = url;
this.files = files;
this.params = params;
this.headers = headers;
}
@Override
protected void buildRequestBody(MultipartBody.Builder builder) {
if (files != null && !files.isEmpty()) {
for (UploadFile file : files) {
RequestBody fileBody = RequestBody.create(MediaType.parse(getMimeType(file.getName())), file.getFile());
String fileName = file.getFilename();
if (!fileName.startsWith("BEH-") && !fileName.startsWith("FUN-") && !fileName.startsWith("M1701")) {
String suffix = fileName.substring(fileName.lastIndexOf("."));
String encryptFileName = Base64.encodeToString(fileName.getBytes(), Base64.DEFAULT);
fileName = encryptFileName + suffix;
}
builder.addFormDataPart(file.getName(), fileName, fileBody);
}
}
}
/**
* 根据文件名解析contentType
*/
private String getMimeType(String name) {
String contentTypeFor = null;
try {
FileNameMap fileNameMap = URLConnection.getFileNameMap();
contentTypeFor = fileNameMap.getContentTypeFor(URLEncoder.encode(name, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (contentTypeFor == null) {
contentTypeFor = "application/octet-stream";
}
return contentTypeFor;
}
}
| 34.866667 | 123 | 0.640535 |
82b653ed96eb1977de7bf04ead8aca6b96067dfc
| 4,498 |
package org.acelera.saopaulo.soccer;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.joining;
import static org.acelera.saopaulo.soccer.Posicao.ATAQUE;
import static org.acelera.saopaulo.soccer.Posicao.DEFESA;
import static org.acelera.saopaulo.soccer.Posicao.GOLEIRO;
import static org.junit.jupiter.api.Assertions.assertEquals;
class TimeTest {
@Test
public void deveCriarTime() {
Assertions.assertThrows(NullPointerException.class, () -> Time.of(null));
Time bahia = Time.of("Bahia");
Assertions.assertNotNull(bahia);
}
@Test
public void deveAdicionarJogador() {
Time bahia = Time.of("Bahia");
Jogador jogador = Mockito.mock(Jogador.class);
Mockito.when(jogador.getNome()).thenReturn("ahha pegadinho do Malandro");
bahia.adicionar(jogador);
Assertions.assertEquals(1, bahia.total());
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
bahia.getJogadores().clear();
});
}
@Test
public void deveRetornarFantastico() {
Time bahia = Time.of("Bahia");
Jogador bobo = mock("Bobo", 3);
Jogador lima = mock("Lima", 5);;
Jogador neymar = mock("Neymar", 1);
bahia.adicionar(bobo);
bahia.adicionar(lima);
bahia.adicionar(neymar);
List<Jogador> fantastico = bahia.getFantastico();
String fanstastiqueiros = fantastico.stream()
.map(Jogador::getNome)
.sorted()
.collect(joining(","));
Assertions.assertEquals(2, fantastico.size());
Assertions.assertEquals("Bobo,Lima", fanstastiqueiros);
}
@Test
public void deveAgruparPorPosicao() {
Time bahia = Time.of("Bahia");
Jogador bobo = mock("Bobo", 3, DEFESA);
Jogador jorge = mock("Jorge", 3, DEFESA);
Jogador jose = mock("jose", 3, DEFESA);
Jogador lima = mock("Lima", 5, ATAQUE);
Jogador neymar = mock("Neymar", 1, ATAQUE);
Jogador tafarel = mock("Tafarel", 0, GOLEIRO);
bahia.adicionar(bobo);
bahia.adicionar(jorge);
bahia.adicionar(jose);
bahia.adicionar(lima);
bahia.adicionar(neymar);
bahia.adicionar(tafarel);
Map<Posicao, List<Jogador>> jogaborbyPosicao = bahia.getJogadorByPosicao();
assertEquals(1, jogaborbyPosicao.get(GOLEIRO).size());
assertEquals(3, jogaborbyPosicao.get(DEFESA).size());
assertEquals(2, jogaborbyPosicao.get(ATAQUE).size());
assertEquals("Tafarel", convertToName(jogaborbyPosicao.get(GOLEIRO)));
assertEquals("Bobo,Jorge,jose", convertToName(jogaborbyPosicao.get(DEFESA)));
assertEquals("Lima,Neymar", convertToName(jogaborbyPosicao.get(ATAQUE)));
}
@Test
public void deveRetornarOArtilheiro() {
Time bahia = Time.of("Bahia");
Jogador bobo = mock("Bobo", 3);
Jogador lima = mock("Lima", 5);;
Jogador neymar = mock("Neymar", 1);
bahia.adicionar(bobo);
bahia.adicionar(lima);
bahia.adicionar(neymar);
Jogador artilheiro = bahia.getArtilheiro();
assertEquals("Lima", artilheiro.getNome());
assertEquals(5, artilheiro.getGols());
}
@Test
public void deveRetornarOrdenadoPorGols() {
Time bahia = Time.of("Bahia");
Jogador bobo = mock("Bobo", 3);
Jogador lima = mock("Lima", 5);
Jogador neymar = mock("Neymar", 1);
bahia.adicionar(bobo);
bahia.adicionar(lima);
bahia.adicionar(neymar);
List<Jogador> jogadores = bahia.getJogadoresOrderByGols();
assertEquals("Lima,Bobo,Neymar", convertToName(jogadores));
}
private String convertToName(List<Jogador> jogadores) {
return jogadores.stream().map(Jogador::getNome).collect(Collectors.joining(","));
}
private Jogador mock(String nome, int gols) {
return mock(nome, gols, ATAQUE);
}
private Jogador mock(String nome, int gols, Posicao posicao) {
Jogador jogador = Mockito.mock(Jogador.class);
Mockito.when(jogador.getNome()).thenReturn(nome);
Mockito.when(jogador.getGols()).thenReturn(gols);
Mockito.when(jogador.getPosicao()).thenReturn(posicao);
return jogador;
}
}
| 31.02069 | 89 | 0.638284 |
3914c401df9628cf5212747bd5131198c1b8b46a
| 5,237 |
package ai.labs.resources.rest.regulardictionary;
import ai.labs.resources.rest.IRestVersionInfo;
import ai.labs.resources.rest.documentdescriptor.model.DocumentDescriptor;
import ai.labs.resources.rest.method.PATCH;
import ai.labs.resources.rest.patch.PatchInstruction;
import ai.labs.resources.rest.regulardictionary.model.RegularDictionaryConfiguration;
import io.swagger.annotations.*;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;
/**
* @author ginccc
*/
@Api(value = "configurations")
@Path("/regulardictionarystore/regulardictionaries")
public interface IRestRegularDictionaryStore extends IRestVersionInfo {
String resourceURI = "eddi://ai.labs.regulardictionary/regulardictionarystore/regulardictionaries/";
@GET
@Path("/descriptors")
@Produces(MediaType.APPLICATION_JSON)
@ApiImplicitParams({
@ApiImplicitParam(name = "filter", paramType = "query", dataType = "string", format = "string", example = "<name_of_regular_dictionary>"),
@ApiImplicitParam(name = "index", paramType = "query", dataType = "integer", format = "integer", example = "0"),
@ApiImplicitParam(name = "limit", paramType = "query", dataType = "integer", format = "integer", example = "20")})
@ApiResponse(code = 200, response = DocumentDescriptor.class, responseContainer = "List",
message = "Array of DocumentDescriptors")
List<DocumentDescriptor> readRegularDictionaryDescriptors(@QueryParam("filter") @DefaultValue("") String filter,
@QueryParam("index") @DefaultValue("0") Integer index,
@QueryParam("limit") @DefaultValue("20") Integer limit);
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponse(code = 200, response = RegularDictionaryConfiguration.class, message = "configuration of regular dictionary")
RegularDictionaryConfiguration readRegularDictionary(@PathParam("id") String id,
@ApiParam(name = "version", required = true, format = "integer", example = "1")
@QueryParam("version") Integer version,
@QueryParam("filter") @DefaultValue("") String filter,
@QueryParam("order") @DefaultValue("") String order,
@QueryParam("index") @DefaultValue("0") Integer index,
@QueryParam("limit") @DefaultValue("20") Integer limit);
@GET
@Path("/{id}/expressions")
@Produces(MediaType.APPLICATION_JSON)
List<String> readExpressions(@PathParam("id") String id,
@ApiParam(name = "version", required = true, format = "integer", example = "1")
@QueryParam("version") Integer version,
@QueryParam("filter") @DefaultValue("") String filter,
@QueryParam("order") @DefaultValue("") String order,
@QueryParam("index") @DefaultValue("0") Integer index,
@QueryParam("limit") @DefaultValue("20") Integer limit);
@PUT
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
Response updateRegularDictionary(@PathParam("id") String id,
@ApiParam(name = "version", required = true, format = "integer", example = "1")
@QueryParam("version") Integer version, RegularDictionaryConfiguration regularDictionaryConfiguration);
/**
* example dictionary json config:
* <p>
* {
* "language" : "en",
* "words" : [
* {
* "word" : "hello",
* "exp" : "greeting(hello)",
* "frequency" : 0
* }
* ],
* "phrases" : [
* {
* "phrase" : "good afternoon",
* "exp" : "greeting(good_afternoon)"
* }
* ]
* }
*
* @param regularDictionaryConfiguration dictionary resource to be created
* @return no content, http code 201, see Location header for URI of the created resource
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
Response createRegularDictionary(RegularDictionaryConfiguration regularDictionaryConfiguration);
@DELETE
@Path("/{id}")
Response deleteRegularDictionary(@PathParam("id") String id,
@ApiParam(name = "version", required = true, format = "integer", example = "1")
@QueryParam("version") Integer version);
@PATCH
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
Response patchRegularDictionary(@PathParam("id") String id,
@ApiParam(name = "version", required = true, format = "integer", example = "1")
@QueryParam("version") Integer version, PatchInstruction<RegularDictionaryConfiguration>[] patchInstructions);
}
| 48.490741 | 150 | 0.582395 |
99a5110d8969043ff2d5b4c426334f909ff8022d
| 3,103 |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.test.iiop.interfaces;
/**
* org/jboss/test/iiop/interfaces/IdlInterfacePOA.java .
* Generated by the IDL-to-Java compiler (portable), version "3.1"
* from IdlInterface.idl
* Tuesday, October 21, 2003 3:27:17 PM BRST
*/
public abstract class IdlInterfacePOA extends org.omg.PortableServer.Servant
implements org.jboss.test.iiop.interfaces.IdlInterfaceOperations, org.omg.CORBA.portable.InvokeHandler
{
// Constructors
private static java.util.Hashtable _methods = new java.util.Hashtable ();
static
{
_methods.put ("echo", new java.lang.Integer (0));
}
public org.omg.CORBA.portable.OutputStream _invoke (String $method,
org.omg.CORBA.portable.InputStream in,
org.omg.CORBA.portable.ResponseHandler $rh)
{
org.omg.CORBA.portable.OutputStream out = null;
java.lang.Integer __method = (java.lang.Integer)_methods.get ($method);
if (__method == null)
throw new org.omg.CORBA.BAD_OPERATION (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE);
switch (__method.intValue ())
{
case 0: // org/jboss/test/iiop/interfaces/IdlInterface/echo
{
String s = in.read_string ();
String $result = null;
$result = this.echo (s);
out = $rh.createReply();
out.write_string ($result);
break;
}
default:
throw new org.omg.CORBA.BAD_OPERATION (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE);
}
return out;
} // _invoke
// Type-specific CORBA::Object operations
private static String[] __ids = {
"IDL:org/jboss/test/iiop/interfaces/IdlInterface:1.0"};
public String[] _all_interfaces (org.omg.PortableServer.POA poa, byte[] objectId)
{
return (String[])__ids.clone ();
}
public IdlInterface _this()
{
return IdlInterfaceHelper.narrow(
super._this_object());
}
public IdlInterface _this(org.omg.CORBA.ORB orb)
{
return IdlInterfaceHelper.narrow(
super._this_object(orb));
}
} // class IdlInterfacePOA
| 32.663158 | 103 | 0.693522 |
33daa82dea04876222166788bb0ca4c5e36510ac
| 3,209 |
package xdb.layout;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import xdb.layout.NodeInfo;
import xdb.layout.NodeInfoManager;
import junit.framework.TestCase;
public class NodeInfoManagerTest extends TestCase {
private static final String TEST_ROOT = deriveTestRoot();
private NodeInfoManager nim;
public static String deriveTestRoot() {
URL rootMarker = NodeInfoManagerTest.class.getResource("testRoot/index.html");
String markerPath = rootMarker.getPath();
File markerFile = new File(markerPath);
return markerFile.getParentFile().getAbsolutePath() + "/";
}
public NodeInfoManagerTest(String testName) throws IOException {
super(testName);
NodeInfoManager.init("/pdb", TEST_ROOT);
nim = NodeInfoManager.getInstance();
}
public void testDeriveNodeInfo() throws IOException {
NodeInfo root = nim.getRootNode();
assertEquals("Home", root.getTitle());
assertEquals("/pdb/index.html", root.getUri());
assertEquals(null, root.getParent());
}
public void testChildPage() throws IOException {
NodeInfo root = nim.getRootNode();
List<NodeInfo> children = root.getChildren();
NodeInfo page = null;
for (NodeInfo child : children) {
if ("Page 1".equals(child.getTitle())) {
page = child;
}
}
assertEquals("Page 1", page.getTitle());
assertEquals("/pdb/page1.html", page.getUri());
assertEquals(root, page.getParent());
}
public void testChildDirectory() throws IOException {
NodeInfo root = nim.getRootNode();
List<NodeInfo> children = root.getChildren();
NodeInfo subindex = null;
for (NodeInfo child : children) {
if ("Subdirectory".equals(child.getTitle())) {
subindex = child;
}
}
assertEquals("Subdirectory", subindex.getTitle());
assertEquals("/pdb/subdir/index.html", subindex.getUri());
assertEquals(root, subindex.getParent());
List<NodeInfo> subchildren = subindex.getChildren();
NodeInfo page = null;
for (NodeInfo child : subchildren) {
if ("Page 2".equals(child.getTitle())) {
page = child;
}
}
assertEquals("Page 2", page.getTitle());
assertEquals("/pdb/subdir/page2.html", page.getUri());
assertEquals(subindex, page.getParent());
}
public void testGetNode() throws IOException {
NodeInfo page = nim.getNode("/pdb/subdir/page2.html");
assertEquals("Page 2", page.getTitle());
assertEquals("/pdb/subdir/page2.html", page.getUri());
assertEquals("Subdirectory", page.getParent().getTitle());
}
public void testNoRss() throws IOException {
NodeInfo root = nim.getRootNode();
List<NodeInfo> children = root.getChildren();
NodeInfo page = null;
for (NodeInfo child : children) {
if ("/pdb/rss.jsp".equals(child.getUri())) {
page = child;
}
}
assertEquals(null, page);
}
}
| 34.505376 | 86 | 0.614522 |
f2b42b59c8128d73ebdb19310b6a3ea8469536d5
| 798 |
package hr.fer.oop.swing2.properties.console;
import java.beans.PropertyChangeListener;
public class Main {
public static void main(String[] args) {
A a = new A();
PropertyChangeListener listener = evt -> {
System.out.printf("\tProperty %s changed from %d to %d%n",
evt.getPropertyName(),
evt.getOldValue(),
evt.getNewValue());
};
a.addPropertyChangeListener(listener);
System.out.println("Command #1 -> val to 25");
a.setValue(25);
System.out.println("Command #2 -> val to 35");
a.setValue(35);
System.out.println("Command #3 -> val to 35");
a.setValue(35);
System.out.println("Command #4 -> val to 45");
a.setValue(45);
a.removePropertyChangeListener(listener);
System.out.println("Command #5 -> val to 75");
a.setValue(75);
}
}
| 23.470588 | 62 | 0.660401 |
9c299a53ac3465cedc0fc7fb16b066bbaee4d887
| 408 |
package com.jesen.customglide;
import android.app.Application;
public class BaseApplication extends Application {
private static Application INSTANCE;
@Override
public void onCreate() {
super.onCreate();
INSTANCE = this;
}
public static Application getApplication(){
if (INSTANCE != null){
return INSTANCE;
}
return null;
}
}
| 17.73913 | 50 | 0.625 |
a333564445edd63e3e327bca38184365e6a39cf0
| 2,658 |
package owl.translations;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;
import owl.ltl.Conjunction;
import owl.ltl.Disjunction;
import owl.ltl.EquivalenceClass;
import owl.ltl.Formula;
import owl.ltl.SyntacticFragments;
import owl.translations.mastertheorem.Predicates;
public class BlockingElements {
private final BitSet atomicPropositions;
private final Set<Formula.TemporalOperator> blockingCoSafety;
private final Set<Formula.TemporalOperator> blockingSafety;
public BlockingElements(Formula formula) {
this.atomicPropositions = formula.atomicPropositions(true);
formula.subformulas(Predicates.IS_FIXPOINT)
.forEach(x -> atomicPropositions.andNot(x.atomicPropositions(true)));
if (formula instanceof Conjunction) {
var coSafetyTemporalChildren = new ArrayList<Formula.TemporalOperator>();
var otherChildren = new ArrayList<Formula>();
for (Formula child : formula.operands) {
if (child instanceof Formula.TemporalOperator && SyntacticFragments.isCoSafety(child)) {
coSafetyTemporalChildren.add((Formula.TemporalOperator) child);
} else {
otherChildren.add(child);
}
}
coSafetyTemporalChildren
.removeIf(x -> otherChildren.stream().anyMatch(y -> y.anyMatch(x::equals)));
blockingCoSafety = Set.of(coSafetyTemporalChildren.toArray(Formula.TemporalOperator[]::new));
} else {
blockingCoSafety = Set.of();
}
if (formula instanceof Disjunction) {
var fixpoints = formula
.subformulas(Predicates.IS_FIXPOINT)
.stream()
.filter(
x -> !SyntacticFragments.isCoSafety(x) && !SyntacticFragments.isSafety(x))
.collect(Collectors.toSet());
blockingSafety = formula.operands
.stream()
.filter(x -> x instanceof Formula.TemporalOperator
&& SyntacticFragments.isSafety(x)
&& fixpoints.stream().noneMatch(y -> y.anyMatch(x::equals)))
.map(Formula.TemporalOperator.class::cast)
.collect(Collectors.toUnmodifiableSet());
} else {
blockingSafety = Set.of();
}
}
public boolean isBlockedByCoSafety(EquivalenceClass clazz) {
return SyntacticFragments.isCoSafety(clazz)
|| clazz.atomicPropositions(true).intersects(atomicPropositions)
|| !Collections.disjoint(blockingCoSafety, clazz.temporalOperators());
}
public boolean isBlockedBySafety(EquivalenceClass clazz) {
return SyntacticFragments.isSafety(clazz)
|| !Collections.disjoint(blockingSafety, clazz.temporalOperators());
}
}
| 34.973684 | 99 | 0.714447 |
4303f19b98527b4f6b1c313dcba3e9e82e0b05d2
| 509 |
package com.atguigu.gulimall.pms.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.atguigu.gulimall.pms.entity.SkuSaleAttrValueEntity;
import com.atguigu.gulimall.commons.bean.PageVo;
import com.atguigu.gulimall.commons.bean.QueryCondition;
/**
* sku销售属性&值
*
* @author zhangwenliu
* @email zwl@atguigu.com
* @date 2019-08-30 12:03:47
*/
public interface SkuSaleAttrValueService extends IService<SkuSaleAttrValueEntity> {
PageVo queryPage(QueryCondition params);
}
| 24.238095 | 83 | 0.791749 |
9542593d0e4e5919e9ee1a7656a0eb0140593e65
| 339 |
package Demos.Gagarin.dubinCurve;
public class spookyPathing {
static Node start = new Node(2, 3, 0);
static Node end = new Node(0,0, 180);
static curveProcessor curve = new curveProcessor(null);
public static void main(String args[]) {
curve.findCurves(start, end);
curve.telemtry(start, end);
}
}
| 22.6 | 59 | 0.657817 |
7b826f0d23422120181cb54769236767e8904284
| 2,172 |
package com.portfolio.market.springmarket.ControllerTest;
import com.portfolio.market.springmarket.entities.Category;
import com.portfolio.market.springmarket.repository.CategoryRepository;
import com.portfolio.market.springmarket.resources.CategoryResource;
import com.portfolio.market.springmarket.service.CategoryService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import java.util.List;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.when;
@SpringBootTest
public class CategoryResourceTest {
private static final Long ID = 1L;
private static final String NAME = "test";
public static final int INDEX = 0;
@InjectMocks
private CategoryResource resource;
@Mock
private CategoryService service;
@Mock
private CategoryRepository categoryRepository;
private Category category;
private List<Category> list;
@BeforeEach
void setUp(){
MockitoAnnotations.openMocks(this);
category = new Category(NAME);
category.setId(ID);
list = List.of(category);
}
// @Test
// void findById(){
// when(service.getCategory(anyLong())).thenReturn(category);
//
// ResponseEntity<Category> response = resource.findById(ID);
//
// Assertions.assertNotNull(response);
// Assertions.assertNotNull(response.getBody()); //Verificando se o corpo não é nulo
// Assertions.assertEquals(ResponseEntity.class, response.getClass()); // Verificando se a classe do meu retorno é um ResponseEntity
// Assertions.assertEquals(Category.class, response.getBody().getClass()); //Verifiando se a classe do corpo da minha resposta é uma Category
// Assertions.assertEquals(ID, response.getBody().getId()); //Testando todos os campos da entity Category
// Assertions.assertEquals(NAME, response.getBody().getName());
// }
}
| 32.41791 | 148 | 0.741252 |
b15b82c7610e8228ad42e4b97ceea99c53bb655c
| 1,202 |
package com.jfilipczyk.lessonreport.model;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class EventAggregator {
public List<GroupedEvent> aggregate(List<Event> events) {
HashMap<String, GroupedEvent> groupedEventsMap = events.stream()
.collect(
() -> new HashMap<>(),
(map, event) -> {
String groupName = extractGroupName(event.getSummary());
if (map.containsKey(groupName)) {
GroupedEvent groupedEvent = map.get(groupName);
groupedEvent.addDuration(event.getDuration());
groupedEvent.incNumOfEvents();
} else {
GroupedEvent groupedEvent = new GroupedEvent(groupName, event.getDuration(), 1);
map.put(groupName, groupedEvent);
}
},
(mapA, mapB) -> {}); // not required for sequential stream
return new ArrayList<>(groupedEventsMap.values());
}
private String extractGroupName(String name) {
return name.split("#")[0];
}
}
| 36.424242 | 104 | 0.543261 |
147440ea3ef913b6919029dfd376314089d38479
| 461 |
package com.adafruit.pihat;
import com.adafruit.PCA9685;
import com.adafruit.pihat.impl.MotorHatDCMotorImpl;
import com.pi4j.io.i2c.I2CBus;
import java.io.IOException;
public class MotorHat {
PCA9685 device = null;
public MotorHat(I2CBus bus, int address) throws IOException, InterruptedException {
device = new PCA9685(bus.getDevice(address), address);
}
public DCMotor getDCMotor(int i) {
return new MotorHatDCMotorImpl(device, i);
}
}
| 23.05 | 85 | 0.75705 |
b33aad03a990a9f589d235495bed468650976581
| 7,354 |
// This file is auto-generated, don't edit it. Thanks.
package com.aliyun.dingtalkindustry_1_0.models;
import com.aliyun.tea.*;
public class IndustryManufactureFeeListGetResponseBody extends TeaModel {
@NameInMap("list")
public java.util.List<IndustryManufactureFeeListGetResponseBodyList> list;
@NameInMap("nextCursor")
public Long nextCursor;
@NameInMap("totalCount")
public Long totalCount;
@NameInMap("hasMore")
public Boolean hasMore;
public static IndustryManufactureFeeListGetResponseBody build(java.util.Map<String, ?> map) throws Exception {
IndustryManufactureFeeListGetResponseBody self = new IndustryManufactureFeeListGetResponseBody();
return TeaModel.build(map, self);
}
public IndustryManufactureFeeListGetResponseBody setList(java.util.List<IndustryManufactureFeeListGetResponseBodyList> list) {
this.list = list;
return this;
}
public java.util.List<IndustryManufactureFeeListGetResponseBodyList> getList() {
return this.list;
}
public IndustryManufactureFeeListGetResponseBody setNextCursor(Long nextCursor) {
this.nextCursor = nextCursor;
return this;
}
public Long getNextCursor() {
return this.nextCursor;
}
public IndustryManufactureFeeListGetResponseBody setTotalCount(Long totalCount) {
this.totalCount = totalCount;
return this;
}
public Long getTotalCount() {
return this.totalCount;
}
public IndustryManufactureFeeListGetResponseBody setHasMore(Boolean hasMore) {
this.hasMore = hasMore;
return this;
}
public Boolean getHasMore() {
return this.hasMore;
}
public static class IndustryManufactureFeeListGetResponseBodyList extends TeaModel {
@NameInMap("id")
public Long id;
@NameInMap("gmtCreate")
public Long gmtCreate;
@NameInMap("gmtModified")
public Long gmtModified;
@NameInMap("corpId")
public String corpId;
@NameInMap("productionTaskNo")
public String productionTaskNo;
@NameInMap("materialNo")
public String materialNo;
@NameInMap("materialName")
public String materialName;
@NameInMap("count")
public Float count;
@NameInMap("unit")
public String unit;
@NameInMap("type")
public String type;
@NameInMap("amount")
public String amount;
@NameInMap("perAmount")
public Float perAmount;
@NameInMap("isDeleted")
public String isDeleted;
@NameInMap("instanceId")
public String instanceId;
@NameInMap("processCode")
public String processCode;
@NameInMap("ext")
public String ext;
@NameInMap("title")
public String title;
public static IndustryManufactureFeeListGetResponseBodyList build(java.util.Map<String, ?> map) throws Exception {
IndustryManufactureFeeListGetResponseBodyList self = new IndustryManufactureFeeListGetResponseBodyList();
return TeaModel.build(map, self);
}
public IndustryManufactureFeeListGetResponseBodyList setId(Long id) {
this.id = id;
return this;
}
public Long getId() {
return this.id;
}
public IndustryManufactureFeeListGetResponseBodyList setGmtCreate(Long gmtCreate) {
this.gmtCreate = gmtCreate;
return this;
}
public Long getGmtCreate() {
return this.gmtCreate;
}
public IndustryManufactureFeeListGetResponseBodyList setGmtModified(Long gmtModified) {
this.gmtModified = gmtModified;
return this;
}
public Long getGmtModified() {
return this.gmtModified;
}
public IndustryManufactureFeeListGetResponseBodyList setCorpId(String corpId) {
this.corpId = corpId;
return this;
}
public String getCorpId() {
return this.corpId;
}
public IndustryManufactureFeeListGetResponseBodyList setProductionTaskNo(String productionTaskNo) {
this.productionTaskNo = productionTaskNo;
return this;
}
public String getProductionTaskNo() {
return this.productionTaskNo;
}
public IndustryManufactureFeeListGetResponseBodyList setMaterialNo(String materialNo) {
this.materialNo = materialNo;
return this;
}
public String getMaterialNo() {
return this.materialNo;
}
public IndustryManufactureFeeListGetResponseBodyList setMaterialName(String materialName) {
this.materialName = materialName;
return this;
}
public String getMaterialName() {
return this.materialName;
}
public IndustryManufactureFeeListGetResponseBodyList setCount(Float count) {
this.count = count;
return this;
}
public Float getCount() {
return this.count;
}
public IndustryManufactureFeeListGetResponseBodyList setUnit(String unit) {
this.unit = unit;
return this;
}
public String getUnit() {
return this.unit;
}
public IndustryManufactureFeeListGetResponseBodyList setType(String type) {
this.type = type;
return this;
}
public String getType() {
return this.type;
}
public IndustryManufactureFeeListGetResponseBodyList setAmount(String amount) {
this.amount = amount;
return this;
}
public String getAmount() {
return this.amount;
}
public IndustryManufactureFeeListGetResponseBodyList setPerAmount(Float perAmount) {
this.perAmount = perAmount;
return this;
}
public Float getPerAmount() {
return this.perAmount;
}
public IndustryManufactureFeeListGetResponseBodyList setIsDeleted(String isDeleted) {
this.isDeleted = isDeleted;
return this;
}
public String getIsDeleted() {
return this.isDeleted;
}
public IndustryManufactureFeeListGetResponseBodyList setInstanceId(String instanceId) {
this.instanceId = instanceId;
return this;
}
public String getInstanceId() {
return this.instanceId;
}
public IndustryManufactureFeeListGetResponseBodyList setProcessCode(String processCode) {
this.processCode = processCode;
return this;
}
public String getProcessCode() {
return this.processCode;
}
public IndustryManufactureFeeListGetResponseBodyList setExt(String ext) {
this.ext = ext;
return this;
}
public String getExt() {
return this.ext;
}
public IndustryManufactureFeeListGetResponseBodyList setTitle(String title) {
this.title = title;
return this;
}
public String getTitle() {
return this.title;
}
}
}
| 29.18254 | 130 | 0.625374 |
5c4e0a57be9a1d47ecd3d076141f80907a5948da
| 1,772 |
package com.asuka.common.security.handler;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.AntPathMatcher;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author wujiawei
* @see
* @since 2020/7/27 5:01 下午
*/
public class SecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
private final AntPathMatcher antPathMatcher = new AntPathMatcher();
private final Map<String,String> urlRoleMap = new HashMap<String,String>(){{
put("/open/**","ROLE_ANONYMOUS");
put("/health","ROLE_ANONYMOUS");
put("/restart","ROLE_ADMIN");
put("/demo","ROLE_USER");
}};
@Override
public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
FilterInvocation fi = (FilterInvocation) o;
String url = fi.getRequestUrl();
// String httpMethod = fi.getRequest().getMethod();
for(Map.Entry<String,String> entry:urlRoleMap.entrySet()){
if(antPathMatcher.match(entry.getKey(),url)){
return SecurityConfig.createList(entry.getValue());
}
}
//没有匹配到,默认是要登录才能访问
return SecurityConfig.createList("ROLE_ANONYMOUS", "ROLE_USER");
// return null;
}
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
return null;
}
@Override
public boolean supports(Class<?> aClass) {
return FilterInvocation.class.isAssignableFrom(aClass);
}
}
| 31.087719 | 96 | 0.700903 |
86d46fe2a2decb1834ccb1ecd1ee6f404dc25254
| 779 |
package com.erclab.bean;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class Menu implements Serializable {
private String title;
private String price;
private String rating;
public Menu() {}
public Menu(String title, String price) {
this.title = title;
this.price = price;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
}
| 17.704545 | 50 | 0.613607 |
5982ce97831efecff06b624f710460cad505f7a6
| 5,339 |
package com.douwe.notes.resource.impl;
import com.douwe.notes.entities.Niveau;
import com.douwe.notes.entities.Option;
import com.douwe.notes.entities.Parcours;
import com.douwe.notes.entities.Programme;
import com.douwe.notes.resource.IProgrammeResource;
import com.douwe.notes.service.IParcoursService;
import com.douwe.notes.service.IProgrammeService;
import com.douwe.notes.service.ServiceException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ws.rs.Path;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
/**
*
* @author Kenfack Valmy-Roi <roykenvalmy@gmail.com>
*/
@Path("/programmes")
public class ProgrammeResource implements IProgrammeResource{
@EJB
private IProgrammeService service;
@EJB
private IParcoursService parcoursService;
public IProgrammeService getService() {
return service;
}
public void setService(IProgrammeService service) {
this.service = service;
}
public IParcoursService getParcoursService() {
return parcoursService;
}
public void setParcoursService(IParcoursService parcoursService) {
this.parcoursService = parcoursService;
}
@Override
public Programme createProgramme(Programme programme) {
try {
Niveau n = programme.getParcours().getNiveau();
Option o = programme.getParcours().getOption();
Parcours p = parcoursService.findByNiveauOption(n.getId(), o.getId());
programme.setParcours(p);
return service.saveOrUpdateProgramme(programme);
} catch (ServiceException ex) {
Logger.getLogger(ProgrammeResource.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
@Override
public List<Programme> getAllProgrammes() {
try {
return service.getAllProgrammes();
} catch (ServiceException ex) {
Logger.getLogger(ProgrammeResource.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
@Override
public Programme getProgramme(long id) {
try {
Programme programme = service.findProgrammeById(id);
if(programme == null){
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
return null;
} catch (ServiceException ex) {
Logger.getLogger(ProgrammeResource.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
@Override
public Programme updateProgramme(long id, Programme programme) {
try {
Programme programme1 = service.findProgrammeById(id);
if(programme1 != null){
programme1.setAnneeAcademique(programme.getAnneeAcademique());
programme1.setParcours(programme.getParcours());
programme1.setUniteEnseignement(programme.getUniteEnseignement());
return service.saveOrUpdateProgramme(programme1);
}
return null;
} catch (ServiceException ex) {
Logger.getLogger(ProgrammeResource.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
@Override
public void deleteProgramme(long id) {
try {
service.deleteProgramme(id);
} catch (ServiceException ex) {
Logger.getLogger(ProgrammeResource.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public Programme createProgramme(long niveauId, long optionId, Programme programme) {
try {
Parcours p = parcoursService.findByNiveauOption(niveauId, optionId);
programme.setParcours(p);
return service.saveOrUpdateProgramme(programme);
} catch (ServiceException ex) {
Logger.getLogger(ProgrammeResource.class.getName()).log(Level.SEVERE, null, ex);
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
}
@Override
public List<Programme> getAllProgrammes(long anneeId, long niveauId, long optionId, long semestreId) {
try {
return service.findByOptionAnnee(anneeId, niveauId, optionId, semestreId);
} catch (ServiceException ex) {
Logger.getLogger(ProgrammeResource.class.getName()).log(Level.SEVERE, null, ex);
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
}
@Override
public Programme updateProgramme(long niveauId, long optionId, long id, Programme programme) {
try {
Parcours parcours = parcoursService.findByNiveauOption(niveauId, optionId);
Programme prog = service.findProgrammeById(id);
prog.setParcours(parcours);
prog.setAnneeAcademique(programme.getAnneeAcademique());
prog.setSemestre(programme.getSemestre());
prog.setUniteEnseignement(programme.getUniteEnseignement());
return service.saveOrUpdateProgramme(prog);
} catch (ServiceException ex) {
Logger.getLogger(ProgrammeResource.class.getName()).log(Level.SEVERE, null, ex);
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
}
}
| 35.593333 | 106 | 0.656303 |
0b9bbdbc5d9dbcbf3e218b88f84bd84059bb1f02
| 1,879 |
package io.wolfbeacon.server.model;
import javax.persistence.*;
/**
* Created by Aaron on 22/05/2016.
*/
@Entity
@Table(name = "mailing_list")
public class Email implements DomainModel<Long> {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String emailAddress;
private String name;
public Email() {
}
public Email(String emailAddress) {
this.emailAddress = emailAddress;
}
public Email(String emailAddress, String name) {
this(emailAddress);
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static Email fromEmailAddress(String emailAddress) {
return new Email(emailAddress);
}
@Override
public String toString() {
return "Email{" +
"emailAddress='" + emailAddress + '\'' +
", name='" + name + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Email email = (Email) o;
if (!getEmailAddress().equals(email.getEmailAddress())) return false;
return getName() != null ? getName().equals(email.getName()) : email.getName() == null;
}
@Override
public int hashCode() {
int result = getEmailAddress().hashCode();
result = 31 * result + (getName() != null ? getName().hashCode() : 0);
return result;
}
}
| 22.369048 | 95 | 0.579031 |
f029f8567ce2c031e40a12fd18185fba67bb7acf
| 1,831 |
package org.openrdf.repository.object.codegen;
import java.io.File;
import java.io.FileWriter;
import org.openrdf.repository.object.base.CodeGenTestCase;
public class MixedCaseOneOfTest extends CodeGenTestCase {
public void test() throws Exception {
String RDF_XML = "<rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' xmlns:rdfs='http://www.w3.org/2000/01/rdf-schema#' xmlns:owl='http://www.w3.org/2002/07/owl#'>\n" +
"<rdf:Description rdf:about='#UnitSymbol'>\n" +
"<owl:oneOf rdf:nodeID='Xd2X26cfd7d5Xa3X12e4f66a852Xa3X-346'/>\n" +
"<rdfs:label>UnitSymbol</rdfs:label>\n" +
"<rdf:type rdf:resource='http://www.w3.org/2002/07/owl#Class'/>\n" +
"</rdf:Description>\n" +
"<rdf:Description rdf:nodeID='Xd2X26cfd7d5Xa3X12e4f66a852Xa3X-346'>\n" +
"<rdf:rest rdf:nodeID='Xd2X26cfd7d5Xa3X12e4f66a852Xa3X-347'/>\n" +
"<rdf:first rdf:resource='http://iec.ch/TC57/2010/CIM-schema-cim15#UnitSymbol.H'/>\n" +
"</rdf:Description>\n" +
"<rdf:Description rdf:nodeID='Xd2X26cfd7d5Xa3X12e4f66a852Xa3X-347'>\n" +
"<rdf:rest rdf:resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/>\n" +
"<rdf:first rdf:resource='http://iec.ch/TC57/2010/CIM-schema-cim15#UnitSymbol.h'/>\n" +
"</rdf:Description>\n" +
"<rdf:Description rdf:about='http://iec.ch/TC57/2010/CIM-schema-cim15#UnitSymbol.H'>\n" +
"<rdfs:label>H</rdfs:label>\n" +
"</rdf:Description>\n" +
"<rdf:Description rdf:about='http://iec.ch/TC57/2010/CIM-schema-cim15#UnitSymbol.h'>\n" +
"<rdfs:label>h</rdfs:label>\n" +
"</rdf:Description>\n" +
"</rdf:RDF>\n";
File file = new File(targetDir, "mixedCaseOneOf.rdf");
FileWriter writer = new FileWriter(file);
writer.write(RDF_XML);
writer.close();
addImports(file.toURI().toURL());
createJar("mixedCaseOneOf.jar");
}
}
| 43.595238 | 185 | 0.677772 |
71f335ec3fb987b4fc4cd16cf1c0df8779aafa3f
| 8,353 |
package dssc.exam.draughts.core;
import dssc.exam.draughts.IOInterfaces.ScannerPlayerInput;
import dssc.exam.draughts.exceptions.CannotMoveException;
import dssc.exam.draughts.exceptions.SurrenderException;
import dssc.exam.draughts.utilities.Color;
import org.junit.jupiter.api.Test;
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class TestIfGame {
@Test
void changesPlayer() {
Player whitePlayer = createPlayerWithName("Player 1", Color.WHITE);
Player blackPlayer = createPlayerWithName("Player 2", Color.BLACK);
var game = new Game(whitePlayer, blackPlayer);
assertEquals(whitePlayer, game.getCurrentPlayer());
game.changePlayer();
assertEquals(blackPlayer, game.getCurrentPlayer());
}
@Test
void performsAMove() throws CannotMoveException, SurrenderException {
Game game = instantiateGameWithFakeInputPlayer(Arrays.asList(new Point(2, 3),
new Point(3, 4)));
Board board = new Board();
game.loadGame(board, 0);
assertTrue(board.getTile(2, 3).isNotEmpty());
assertTrue(board.getTile(3, 4).isEmpty());
game.playRound();
assertTrue(board.getTile(2, 3).isEmpty());
assertTrue(board.getTile(3, 4).isNotEmpty());
}
@Test
void updatesRoundNumber() throws CannotMoveException, SurrenderException {
Game game = instantiateGameWithFakeInputPlayer(Arrays.asList(new Point(2, 3),
new Point(3, 4)));
game.loadGame(new Board(), 0);
assertEquals(0, game.getRound());
game.playRound();
assertEquals(1, game.getRound());
}
@Test
void doesntAllowToStartMovingFromAnEmptyTile() throws CannotMoveException, SurrenderException {
Game game = instantiateGameWithFakeInputPlayer(Arrays.asList(new Point(0, 2),
new Point(2, 1),
new Point(3, 2)));
game.loadGame(new Board(), 0);
ByteArrayOutputStream fakeStandardOutput = changeStdOutputToFakeOutput();
game.playRound();
String[] actualLines = fakeStandardOutput.toString().split(System.lineSeparator());
String expectedOut = "Invalid move: The first Tile you selected is empty";
assertEquals(expectedOut, actualLines[actualLines.length - 1]);
}
@Test
void doesntAllowToMoveAnOpponentPiece() throws CannotMoveException, SurrenderException {
Game game = instantiateGameWithFakeInputPlayer(Arrays.asList(new Point(5, 0),
new Point(2, 1),
new Point(3, 2)));
game.loadGame(new Board(), 0);
ByteArrayOutputStream fakeStandardOutput = changeStdOutputToFakeOutput();
game.playRound();
String[] actualLines = fakeStandardOutput.toString().split(System.lineSeparator());
String expectedOut = "Invalid move: The piece you intend to move belongs to your opponent";
assertEquals(expectedOut, actualLines[actualLines.length - 1]);
}
@Test
void endsWhenOnePlayerHasNoPiecesLeft() {
CustomizableBoard board = new CustomizableBoard();
removeAllWhitePiecesFromBoard(board);
ByteArrayOutputStream fakeStandardOutput = changeStdOutputToFakeOutput();
Game game = instantiateGameWithPlayers();
game.loadGame(board, 0);
game.play();
String expected = "The winner is Player 2" + System.lineSeparator();
assertEquals(expected, fakeStandardOutput.toString());
}
private void removeAllWhitePiecesFromBoard(CustomizableBoard board) {
board.popPiecesAt(Stream.iterate(1, n -> n + 1)
.limit(board.getSize() / 2)
.collect(Collectors.toList()));
}
@Test
void informsThePlayerThatCanContinueToSkip() throws Exception {
CustomizableBoard board = new CustomizableBoard()
.popPiecesAt(Arrays.asList(12, 17, 33, 42, 44))
.setMultipleManAt(Arrays.asList(28, 33), Color.WHITE)
.setMultipleManAt(Arrays.asList(24, 37), Color.BLACK);
Game game = instantiateGameWithFakeInputPlayer(Arrays.asList(new Point(5, 0),
new Point(3, 2),
new Point(1, 4)));
game.loadGame(board, 1);
ByteArrayOutputStream fakeStandardOutput = changeStdOutputToFakeOutput();
game.playRound();
String[] actualLines = fakeStandardOutput.toString().split(System.lineSeparator());
assertEquals("Player [BLACK]:", actualLines[10]);
assertEquals("You can continue to skip!", actualLines[21]);
}
@Test
void endGameWhenAPlayerCannotMove() {
CustomizableBoard board = setBoardSoThatPlayerCannotMove();
ByteArrayOutputStream fakeStandardOutput = changeStdOutputToFakeOutput();
Game game = instantiateGameWithPlayers();
game.loadGame(board, 0);
game.play();
String[] actualLines = fakeStandardOutput.toString().split(System.lineSeparator());
assertEquals("Cannot perform any move!", actualLines[11]);
assertEquals("*******GAME OVER*******", actualLines[12]);
assertEquals("The winner is Player 2", actualLines[13]);
}
@Test
void endGameWhenAPlayerSurrender() {
ByteArrayOutputStream fakeStandardOutput = changeStdOutputToFakeOutput();
Player whitePlayer = new Player(Color.WHITE,
new SurrenderExceptionRaiserPlayerInputStub(new SurrenderException("You decided to surrender")));
Game game = new Game(whitePlayer, createPlayerWithName("Player 2", Color.BLACK));
game.play();
String[] actualLines = fakeStandardOutput.toString().split(System.lineSeparator());
assertEquals("You decided to surrender", actualLines[13]);
assertEquals("The winner is Player 2", actualLines[14]);
}
private Player createPlayerWithName(String name, Color color) {
Player newPlayer = new Player(color);
newPlayer.setName(name);
return newPlayer;
}
private Game instantiateGameWithPlayers() {
Player whitePlayer = createPlayerWithName("Player 1", Color.WHITE);
Player blackPlayer = createPlayerWithName("Player 2", Color.BLACK);
return new Game(whitePlayer, blackPlayer);
}
private CustomizableBoard setBoardSoThatPlayerCannotMove() {
CustomizableBoard board = new CustomizableBoard();
board.removeAllPieces();
board.setManAtTile(0, 1, Color.WHITE);
board.setManAtTile(1, 0, Color.BLACK);
board.setKingAtTile(1, 2, Color.BLACK);
return board;
}
private ByteArrayOutputStream changeStdOutputToFakeOutput() {
ByteArrayOutputStream fakeStandardOutput = new ByteArrayOutputStream();
System.setOut(new PrintStream(fakeStandardOutput));
return fakeStandardOutput;
}
private Game instantiateGameWithFakeInputPlayer(List<Point> fakeInputList) {
ScannerPlayerInputStub scannerPlayerInputStub = new ScannerPlayerInputStub(fakeInputList);
return new Game(
new Player(Color.WHITE, scannerPlayerInputStub),
new Player(Color.BLACK, scannerPlayerInputStub));
}
private class ScannerPlayerInputStub extends ScannerPlayerInput {
private static int nextPointToReadIndex = 0;
private final List<Point> fakeReadPoints;
ScannerPlayerInputStub(List<Point> points) {
fakeReadPoints = points;
nextPointToReadIndex = 0;
}
@Override
public Point readPosition(String message) {
return fakeReadPoints.get(nextPointToReadIndex++);
}
}
private class SurrenderExceptionRaiserPlayerInputStub extends ScannerPlayerInput {
private final SurrenderException surrenderException;
SurrenderExceptionRaiserPlayerInputStub(SurrenderException surrenderException) {
this.surrenderException = surrenderException;
}
@Override
public int getInt() throws SurrenderException {
throw this.surrenderException;
}
}
}
| 40.746341 | 113 | 0.679277 |
727d512e744dad1226aab31206805b3c0db67335
| 259 |
package mg.blog.dto;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class CommentDto {
private Long id;
private String text;
//private LocalUser author;
//private Article article;
private LocalDateTime lastUpdated;
}
| 16.1875 | 38 | 0.725869 |
b651ef78b93b545d2cee593409f30d7e4c2d669c
| 45,641 |
/**
* Copyright (c) 2016, The National Archives <pronom@nationalarchives.gov.uk>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of the The National Archives nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.gov.nationalarchives.droid.core.signature.compiler;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import net.byteseek.compiler.CompileException;
import net.byteseek.compiler.matcher.SequenceMatcherCompiler;
import net.byteseek.matcher.sequence.SequenceMatcher;
import net.byteseek.parser.ParseException;
import net.byteseek.parser.tree.ParseTree;
import net.byteseek.parser.tree.ParseTreeType;
import net.byteseek.parser.tree.ParseTreeUtils;
import net.byteseek.parser.tree.node.BaseNode;
import net.byteseek.parser.tree.node.ChildrenNode;
import net.byteseek.utils.ByteUtils;
import uk.gov.nationalarchives.droid.core.signature.droid6.ByteSequence;
import uk.gov.nationalarchives.droid.core.signature.droid6.SideFragment;
import uk.gov.nationalarchives.droid.core.signature.droid6.SubSequence;
import static uk.gov.nationalarchives.droid.core.signature.compiler.ByteSequenceAnchor.EOFOffset;
/**
* class to compile a ByteSequence from a DROID syntax regular expression created by {@link ByteSequenceParser}.
* <br/>
* See main method {@link #compile(ByteSequence, String, ByteSequenceAnchor, CompileType)}.
*
* @author Matt Palmer
*/
public final class ByteSequenceCompiler {
/**
* Convenient static parser (there is no state, so we can just have a static compiler).
*/
public static final ByteSequenceCompiler COMPILER = new ByteSequenceCompiler();
/**
* The maximum number of bytes which can match in a single position in an anchoring sequence.
*
* High values can cause performance problems for many search algorithms.
* Low values impact performance a bit by forcing us to process simple matchers as fragments.
* We want to allow some matching constructs in anchors which match more than one byte.
* The biggest downside happens with large numbers of bytes, so we bias towards a lower number of bytes.
*/
private static final int MAX_MATCHING_BYTES = 64;
/**
* Compilation type to build the objects from the expression.
*
* <br/>
* The length of the anchoring sequences can be different - PRONOM only allows straight bytes in anchors.
*/
public enum CompileType {
/**
* Supports PRONOM syntax.
*/
PRONOM,
/**
* Supports a super-set of the PRONOM syntax.
*/
DROID
}
/**
* A byteseek compiler used to compile the SequenceMatchers which are matched and searched for.
*/
private static final SequenceMatcherCompiler MATCHER_COMPILER = new SequenceMatcherCompiler();
/**
* A re-usable node for all * syntax. Reduces garbage collection to re-use it each time.
*/
private static final ParseTree ZERO_TO_MANY = new ChildrenNode(ParseTreeType.ZERO_TO_MANY, BaseNode.ANY_NODE);
/**
* Compiles a ByteSequence from a DROID syntax regular expression, starting from a new byteSequence.
* <p>
* It is assumed that
* <ul>
* <li>the compileType is DROID</li>
* <li>it is anchored to the BOF</li>
* </ul>
*
* @param droidExpression The string containing a DROID syntax regular expression.
* @throws CompileException If there is a problem compiling the DROID regular expression.
* @return the compiled byteSequence
*/
public ByteSequence compile(final String droidExpression) throws CompileException {
return compile(droidExpression, ByteSequenceAnchor.BOFOffset, CompileType.DROID);
}
/**
* Compiles a ByteSequence from a DROID syntax regular expression, compiling for DROID rather than PRONOM.
*
* @param droidExpression The string containing a DROID syntax regular expression.
* @param anchor How the ByteSequence is to be anchored to the BOF, EOF or a variable search from BOF.
* @return a ByteSequence from a DROID syntax regular expression, compiling for DROID rather than PRONOM.
* @throws CompileException If there is a problem compiling the DROID regular expression.
*/
public ByteSequence compile(final String droidExpression, final ByteSequenceAnchor anchor) throws CompileException {
return compile(droidExpression, anchor, CompileType.DROID);
}
/**
* Compiles a {@link ByteSequence} from a DROID syntax regular expression, starting from a new byte sequence.
*
* @param droidExpression The string containing a DROID syntax regular expression.
* @param anchor How the ByteSequence is to be anchored to the BOF, EOF or a variable search from BOF.
* @param compileType how to build the objects from the expression.
* @throws CompileException If there is a problem compiling the DROID regular expression.
* @return the compiled byteSequence
*/
public ByteSequence compile(final String droidExpression,
final ByteSequenceAnchor anchor,
final CompileType compileType) throws CompileException {
final ByteSequence newByteSequence = new ByteSequence();
newByteSequence.setReference(anchor.getAnchorText());
compile(newByteSequence, droidExpression, compileType);
return newByteSequence;
}
/**
* Compiles a {@link ByteSequence} from a DROID syntax regular expression.
* <p>
* It is assumed that
* <ul>
* <li>the compileType is DROID</li>
* <li>it is anchored to the BOF</li>
* </ul>
*
* @param sequence The ByteSequence which will be altered by compilation.
* @param droidExpression The string containing a DROID syntax regular expression.
* @throws CompileException If there is a problem compiling the DROID regular expression.
*/
public void compile(final ByteSequence sequence, final String droidExpression) throws CompileException {
compile(sequence, droidExpression, ByteSequenceAnchor.BOFOffset, CompileType.DROID);
}
/**
* Compiles a ByteSequence from a DROID syntax regular expression, and how it is anchored to the BOF or EOF (or is a
* variable type of anchor).
*
* @param sequence The ByteSequence which will be altered by compilation.
* @param droidExpression The string containing a DROID syntax regular expression.
* @param anchor How the ByteSequence is to be anchored to the BOF, EOF or a variable search from BOF.
* @throws CompileException If there is a problem compiling the DROID regular expression.
*/
public void compile(final ByteSequence sequence, final String droidExpression, ByteSequenceAnchor anchor) throws CompileException {
compile(sequence, droidExpression, anchor, CompileType.DROID);
}
/**
* Compiles a ByteSequence from a DROID syntax regular expression, and how it is anchored to the BOF or EOF (or is a
* variable type of anchor).
*
* @param sequence The ByteSequence which will be altered by compilation.
* @param droidExpression The string containing a DROID syntax regular expression.
* @param anchor How the ByteSequence is to be anchored to the BOF, EOF or a variable search from BOF.
* @param compileType how to build the objects from the expression.
* @throws CompileException If there is a problem compiling the DROID regular expression.
*/
public void compile(final ByteSequence sequence,
final String droidExpression,
final ByteSequenceAnchor anchor,
final CompileType compileType) throws CompileException {
sequence.setReference(anchor.getAnchorText());
compile(sequence, droidExpression, compileType);
}
/**
* Compiles a ByteSequence from a DROID syntax regular expression.
* <p>
* It is assumed that the ByteSequence has already defined how it is anchored to the BOF or EOF (or is a variable
* type of anchor).
*
* @param sequence The ByteSequence which will be altered by compilation.
* @param droidExpression The string containing a DROID syntax regular expression.
* @param compileType how to build the objects from the expression.
* @throws CompileException If there is a problem compiling the DROID regular expression.
*/
public void compile(final ByteSequence sequence,
final String droidExpression,
final CompileType compileType) throws CompileException {
try {
// Parse the expression into an abstract syntax tree (AST)
final ParseTree sequenceNodes = ByteSequenceParser.PARSER.parse(droidExpression);
// Compile the ByteSequence from the AST:
compile(sequence, sequenceNodes, compileType);
} catch (ParseException ex) {
throw new CompileException(ex.getMessage(), ex);
}
}
/**
* Compiles a ByteSequence from an abstract syntax tree (AST).
* <p>
* 1. Pre-processes the AST nodes to ensure wildcards are placed into the correct sub-sequence.
* 2. Compiles each subsequence in turn and adds it to the ByteSequence.
*
* @param sequence The ByteSequence object to which SubSequences will be added.
* @param sequenceNodes An Abstract Syntax Tree of a droid expression.
* @param compileType how to build the objects from the expression.
* @throws CompileException If there is a problem compiling the AST.
*/
private void compile(final ByteSequence sequence,
final ParseTree sequenceNodes,
final CompileType compileType) throws CompileException {
final boolean anchoredToEnd = EOFOffset.getAnchorText().equals(sequence.getReference());
// Pre-process the parse tree, re-ordering some wildcards on subsequence boundaries.
// Some wildcards at the stopValue or beginning of subsequences belong in the next/prior subsequence object,
// depending on whether the overall byte sequence is anchored to the beginning or stopValue of a file.
// It also replaces MIN_TO_MANY nodes with a REPEAT node (MIN) and a ZERO_TO_MANY node (MANY),
// since these are logically equivalent, but easier to subsequently process once split.
// The result of pre-processing is that each distinct subsequence is then trivially identified,
// and contains all the information it needs to be built, without having to refer to information at the
// stopValue or start of another subsequence.
final List<ParseTree> sequenceList = preprocessSequence(sequenceNodes, anchoredToEnd, compileType);
final int numNodes = sequenceList.size();
// Scan through all the syntax tree nodes, building subsequences as we go (separated by * nodes):
int subSequenceStart = 0;
for (int nodeIndex = 0; nodeIndex < numNodes; nodeIndex++) {
if (sequenceList.get(nodeIndex).getParseTreeType() == ParseTreeType.ZERO_TO_MANY) {
sequence.addSubSequence(buildSubSequence(sequenceList, subSequenceStart, nodeIndex, anchoredToEnd, compileType));
subSequenceStart = nodeIndex + 1;
}
}
// Add final SubSequence, if any:
if (subSequenceStart < numNodes) {
sequence.addSubSequence(buildSubSequence(sequenceList, subSequenceStart, numNodes, anchoredToEnd, compileType));
}
// ByteSequence is now compiled. Note that to use it for searching,
// you still need to call prepareForUse() on it afterwards, just as when it's built from XML.
// Don't call prepareForUse() here as you can get an infinite loop.
// (prepareForUse() will invoke this compiler if a sequence attribute is set on a ByteSequence.)
}
//CHECKSTYLE:OFF - cyclomatic complexity too high.
/**
* This method processes the child nodes of a SEQUENCE ParseTree type into a List<ParseTree>.
* We can't directly affect the children of SEQUENCE types, but we want to change some of the children and
* optimise them. So we build a new list, performing whatever optimisations are needed along the way.
*
* Along the way, it optimises nodes it can usefully optimise,
* and re-orders wildcards around * wildcards to make subsequent SubSequence compilation easier.
*
* If there is nothing special to do for a particular type of node, it's just added to the list.
* The switch statement does not need to look for all types of node, only the ones that something needs to
* be done for (or which affect the processing of other nodes).
*
* @param sequenceNodes A ParseTree node with child nodes to process.
* @param anchoredToEnd If the search sequence is anchored to the end .
* @param compileType Whether we are compiling for PRONOM or DROID.
* @return A list of ParseTrees ready for further compilation.
* @throws CompileException If there was a problem processing the sequence.
*/
private List<ParseTree> preprocessSequence(final ParseTree sequenceNodes, final boolean anchoredToEnd, final CompileType compileType) throws CompileException {
// Iterate across the nodes in the SEQUENCE ParseTree type.
// If the sequence is anchored to the end, we process the nodes in reverse order.
final int numNodes = sequenceNodes.getNumChildren();
final IntIterator index = anchoredToEnd ? new IntIterator(numNodes - 1, 0) : new IntIterator(0, numNodes - 1);
final List<ParseTree> sequenceList = new ArrayList<>();
int lastValuePosition = -1;
while (index.hasNext()) {
int currentIndex = index.next();
final ParseTree node = sequenceNodes.getChild(currentIndex);
sequenceList.add(node);
switch (node.getParseTreeType()) {
/*
* Process types that match byte values, tracking the last time we saw something that matches bytes:
*/
case BYTE: case RANGE: case STRING: case ALL_BITMASK: case SET: case ANY: {
lastValuePosition = sequenceList.size() - 1;
break;
}
case ALTERNATIVES: {
lastValuePosition = sequenceList.size() - 1;
if (compileType == CompileType.DROID) {
sequenceList.set(sequenceList.size() - 1, optimiseSingleByteAlternatives(node));
}
break;
}
/*
* Process * wildcard types that form a sub-sequence boundary.
* At this point, we want to ensure that the * wildcard is right next to the last value type we saw.
*
* This is because it makes subsequent compilation into DROID objects easier if we ensure that any
* gaps, e.g. {10}, exist at the start of a subsequence rather than the end of the previous one.
*
* For example, the sequence:
*
* 01 03 04 {10} * 05 06 07
*
* has a {10} gap at the end of the first subsequence. But it's easier to compile if it instead reads:
*
* 01 03 04 * {10} 05 06 07
*
* This is because to model this in DROID objects, the {10} gap is a property of the following
* subsequence, not the one it was actually defined in. It's equivalent whether a fixed gap happens at
* end of one sequence, or the beginning of the next - but the objects expect inter-subsequence gaps
* to be recorded in the following subsequence.
*
*/
case ZERO_TO_MANY: { // subsequence boundary.
// If the last value is not immediately before the * wildcard, we have some wildcard gaps between
// it and the next subsequence. Move the wildcard after the last value position.
if (lastValuePosition + 1 < sequenceList.size() - 1) {
// insert zero to many node after last value position.
sequenceList.add(lastValuePosition + 1, node);
// remove the current zero to many node.
sequenceList.remove(sequenceList.size() - 1);
}
break;
}
case REPEAT_MIN_TO_MANY: { // subsequence boundary {n,*} - Change the {n-*} into a * followed by an {n}.
// Replace the current {n-*} node with a repeat {n} node.
sequenceList.set(sequenceList.size() - 1,
new ChildrenNode(ParseTreeType.REPEAT, node.getChild(0), BaseNode.ANY_NODE));
// Insert the * wildcard just after the last value position.
sequenceList.add(lastValuePosition + 1, ZERO_TO_MANY);
break;
}
default: {
// Do nothing. It is not an error to encounter a type we don't need to pre-process in some way.
}
}
}
// If we processed the nodes in reverse order, reverse the final list to get the nodes back in normal order.
if (anchoredToEnd) {
Collections.reverse(sequenceList);
}
return sequenceList;
}
/**
* Looks for alternatives which match several different single bytes.
* These can be more efficiently represented in DROID using a Set matcher from byteseek,
* rather than a list of SideFragments in DROID itself.
*
* Instead of (01|02|03) we would like [01 02 03].
* Also, instead of (&01|[10:40]|03) we can have [&01 10:40 03]
* If we have alternatives with some sequences in them, we can still optimise the single byte alternatives, e.g.
* Instead of (01|02|03|'something else') we get ([01 02 03] | 'something else')
* <p>
* @param node The node to optimise
* @return An optimised alternative node, or the original node passed in if no optimisations can be done.
*/
private ParseTree optimiseSingleByteAlternatives(final ParseTree node) throws CompileException {
if (node.getParseTreeType() == ParseTreeType.ALTERNATIVES) {
// Locate any single byte alternatives:
final Set<Integer> singleByteIndexes = new HashSet<>();
for (int i = 0; i < node.getNumChildren(); i++) {
ParseTree child = node.getChild(i);
switch (child.getParseTreeType()) {
case BYTE: case RANGE: case ALL_BITMASK: case SET: {
singleByteIndexes.add(i);
break;
}
case STRING: { // A single char (<256) string can be modelled as an ISO-8859-1 byte.
final String value;
try {
value = child.getTextValue();
} catch (ParseException e) {
throw new CompileException(e.getMessage(), e);
}
if (value.length() == 1 && value.charAt(0) < 256) {
singleByteIndexes.add(i);
}
break;
}
}
}
// If there is more than one single byte value, we can optimise them into just one SET:
if (singleByteIndexes.size() > 1) {
final List<ParseTree> newAlternativeChildren = new ArrayList<>();
final List<ParseTree> setChildren = new ArrayList<>();
for (int i = 0; i < node.getNumChildren(); i++) {
final ParseTree child = node.getChild(i);
if (singleByteIndexes.contains(i)) {
setChildren.add(child);
} else {
newAlternativeChildren.add(child);
}
}
final ParseTree setNode = new ChildrenNode(ParseTreeType.SET, setChildren);
// If there are no further alternatives as they were all single byte values, just return the set:
if (newAlternativeChildren.isEmpty()) {
return setNode;
}
// Otherwise we have some single bytes optimised, but part of a bigger set of non single byte alternatives.
newAlternativeChildren.add(setNode);
return new ChildrenNode(ParseTreeType.ALTERNATIVES, newAlternativeChildren);
}
}
// No change to original node - just return it.
return node;
}
private SubSequence buildSubSequence(final List<ParseTree> sequenceList,
final int subSequenceStart, final int subSequenceEnd,
final boolean anchoredToEOF,
final CompileType compileType) throws CompileException {
/// Find the anchoring search sequence:
final IntPair anchorRange = locateSearchSequence(sequenceList, subSequenceStart, subSequenceEnd, compileType);
if (anchorRange == NO_RESULT) {
throw new CompileException("No anchoring sequence could be found in a subsequence.");
}
final ParseTree anchorSequence = createSubSequenceTree(sequenceList, anchorRange.firstInt, anchorRange.secondInt);
final SequenceMatcher anchorMatcher = MATCHER_COMPILER.compile(anchorSequence);
final List<List<SideFragment>> leftFragments = new ArrayList<>();
final IntPair leftOffsets =
createLeftFragments(sequenceList, leftFragments,
anchorRange.firstInt - 1, subSequenceStart);
final List<List<SideFragment>> rightFragments = new ArrayList<>();
final IntPair rightOffsets =
createRightFragments(sequenceList, rightFragments,
anchorRange.secondInt + 1, subSequenceEnd - 1);
// Choose which remaining fragment offsets are used for the subsequence offsets as a whole:
final IntPair subSequenceOffsets = anchoredToEOF ? rightOffsets : leftOffsets;
return new SubSequence(anchorMatcher, leftFragments, rightFragments, subSequenceOffsets.firstInt, subSequenceOffsets.secondInt);
}
//CHECKSTYLE:OFF - cyclomatic complexity too high.
private IntPair createLeftFragments(final List<ParseTree> sequenceList, final List<List<SideFragment>> leftFragments,
final int fragmentStart, final int fragmentEnd) throws CompileException {
int position = 1;
int minGap = 0;
int maxGap = 0;
int startValueIndex = Integer.MAX_VALUE;
int endValueIndex = Integer.MAX_VALUE;
for (int fragmentIndex = fragmentStart; fragmentIndex >= fragmentEnd; fragmentIndex--) {
final ParseTree node = sequenceList.get(fragmentIndex);
switch (node.getParseTreeType()) {
case BYTE:
case ANY:
case RANGE:
case ALL_BITMASK:
case SET:
case STRING: { // nodes carrying a match for a byte or bytes:
// Track when we first encounter the stopValue of a fragment sequence (we hit this first as we go backwards for left fragments):
if (endValueIndex == Integer.MAX_VALUE) {
endValueIndex = fragmentIndex;
}
// Continuously track the start of any fragment.
startValueIndex = fragmentIndex;
break;
}
case REPEAT:
case REPEAT_MIN_TO_MAX: { // wildcard gaps
if (startValueIndex == fragmentIndex + 1) { // Add any previous value not yet processed.
leftFragments.add(buildFragment(sequenceList, startValueIndex, endValueIndex, minGap, maxGap, position));
position++;
minGap = 0;
maxGap = 0;
startValueIndex = Integer.MAX_VALUE;
endValueIndex = Integer.MAX_VALUE;
}
int nodeMin = getMinGap(node);
int nodeMax = getMaxGap(node); // will be zero if no max set.
if (nodeMax == 0) {
nodeMax = nodeMin; // should be minimum of min.
}
minGap += nodeMin;
maxGap += nodeMax;
break;
}
case ALTERNATIVES: { // a set of alternatives - these always form fragments of their own.
if (startValueIndex == fragmentIndex + 1) { // Add any previous value not yet processed:
leftFragments.add(buildFragment(sequenceList, startValueIndex, endValueIndex, minGap, maxGap, position));
position++;
minGap = 0;
maxGap = 0;
}
// Add alternatives
leftFragments.add(compileAlternatives(node, minGap, maxGap, position));
position++;
minGap = 0;
maxGap = 0;
startValueIndex = Integer.MAX_VALUE;
endValueIndex = Integer.MAX_VALUE;
break;
}
default: throw new CompileException("Unknown node type: " + node + " found at node index: " + fragmentIndex);
}
}
// Add any final unprocessed value fragment at start:
if (startValueIndex == fragmentEnd) {
leftFragments.add(buildFragment(sequenceList, startValueIndex, endValueIndex, minGap, maxGap, position));
minGap = 0;
maxGap = 0;
}
// If we never got a min-max range (just min ranges), the max may still be set to zero. Must be at least min.
if (maxGap < minGap) {
maxGap = minGap;
}
// Return any final min / max gap left over at the start of the left fragments:
return new IntPair(minGap, maxGap);
}
private IntPair createRightFragments(final List<ParseTree> sequenceList, final List<List<SideFragment>> rightFragments,
final int fragmentStart, final int fragmentEnd) throws CompileException {
int position = 1;
int minGap = 0;
int maxGap = 0;
int startValueIndex = Integer.MAX_VALUE;
int endValueIndex = Integer.MAX_VALUE;
for (int fragmentIndex = fragmentStart; fragmentIndex <= fragmentEnd; fragmentIndex++) {
final ParseTree node = sequenceList.get(fragmentIndex);
switch (node.getParseTreeType()) {
case BYTE:
case ANY:
case RANGE:
case ALL_BITMASK:
case SET:
case STRING: { // nodes carrying a match for a byte or bytes:
// Track when we first encounter the start of a fragment sequence
if (startValueIndex == Integer.MAX_VALUE) {
startValueIndex = fragmentIndex;
}
// Continuously track the stopValue of any fragment.
endValueIndex = fragmentIndex;
break;
}
case REPEAT:
case REPEAT_MIN_TO_MAX: { // wildcard gaps
if (endValueIndex == fragmentIndex - 1) { // Add any previous value not yet processed.
rightFragments.add(buildFragment(sequenceList, startValueIndex, endValueIndex, minGap, maxGap, position));
position++;
minGap = 0;
maxGap = 0;
startValueIndex = Integer.MAX_VALUE;
endValueIndex = Integer.MAX_VALUE;
}
int nodeMin = getMinGap(node);
int nodeMax = getMaxGap(node); // will be zero if no max set.
if (nodeMax == 0) {
nodeMax = nodeMin; // should be minimum of min.
}
minGap += nodeMin;
maxGap += nodeMax;
break;
}
case ALTERNATIVES: { // a set of alternatives - these always form fragments of their own.
if (endValueIndex == fragmentIndex - 1) { // Add any previous value not yet processed:
rightFragments.add(buildFragment(sequenceList, startValueIndex, endValueIndex, minGap, maxGap, position));
position++;
minGap = 0;
maxGap = 0;
}
// Add alternatives
rightFragments.add(compileAlternatives(node, minGap, maxGap, position));
position++;
minGap = 0;
maxGap = 0;
startValueIndex = Integer.MAX_VALUE;
endValueIndex = Integer.MAX_VALUE;
break;
}
default:
throw new CompileException("Unknown node type: " + node + " found at node index: " + fragmentIndex);
}
}
// Add any final unprocessed value fragment at stopValue:
if (endValueIndex == fragmentEnd) {
rightFragments.add(buildFragment(sequenceList, startValueIndex, endValueIndex, minGap, maxGap, position));
minGap = 0;
maxGap = 0;
}
// If we never got a min-max range (just min ranges), the max may still be set to zero. Must be at least min.
if (maxGap < minGap) {
maxGap = minGap;
}
// Return any final min / max gap left over at the start of the left fragments:
return new IntPair(minGap, maxGap);
}
private List<SideFragment> buildFragment(List<ParseTree> sequenceList, int startValueIndex, int endValueIndex,
int minGap, int maxGap, int position) throws CompileException {
final List<SideFragment> fragments = new ArrayList<>();
final ParseTree fragmentTree = createSubSequenceTree(sequenceList, startValueIndex, endValueIndex);
final SequenceMatcher matcher = MATCHER_COMPILER.compile(fragmentTree);
final int minMax = maxGap < minGap ? minGap : maxGap;
final SideFragment fragment = new SideFragment(matcher, minGap, minMax, position);
fragments.add(fragment);
return fragments;
}
private ParseTree createSubSequenceTree(List<ParseTree> sequenceList, int subSequenceStart, int subSequenceEnd) {
// Sublist uses an exclusive end index, so we have to add one to the end position we have to get the right list.
return new ChildrenNode(ParseTreeType.SEQUENCE, sequenceList.subList(subSequenceStart, subSequenceEnd + 1));
}
private List<SideFragment> compileAlternatives(ParseTree node, int minGap, int maxGap, int position) throws CompileException {
final int numChildren = node.getNumChildren();
final List<SideFragment> alternatives = new ArrayList<>();
for (int childIndex = 0; childIndex < numChildren; childIndex++) {
final ParseTree alternative = node.getChild(childIndex);
final SequenceMatcher fragmentMatcher = MATCHER_COMPILER.compile(alternative);
final int minMax = maxGap < minGap ? minGap : maxGap;
final SideFragment fragment = new SideFragment(fragmentMatcher, minGap, minMax, position);
alternatives.add(fragment);
}
return alternatives;
}
private int getMinGap(final ParseTree node) throws CompileException {
if (node.getParseTreeType() == ParseTreeType.REPEAT
|| node.getParseTreeType() == ParseTreeType.REPEAT_MIN_TO_MAX) {
try {
return node.getNumChildren() > 0 ? node.getChild(0).getIntValue() : 0;
} catch (ParseException ex) {
throw new CompileException(ex.getMessage(), ex);
}
}
return 0;
}
private int getMaxGap(final ParseTree node) throws CompileException {
if (node.getParseTreeType() == ParseTreeType.REPEAT_MIN_TO_MAX) {
try {
return node.getNumChildren() > 1 ? node.getChild(1).getIntValue() : 0;
} catch (ParseException ex) {
throw new CompileException(ex.getMessage(), ex);
}
}
return 0;
}
/**
* Locates the longest possible "anchoring" sequence to use for searching.
* All other parts of the subsequence to the left and right of the anchor become fragments.
* In general, longer anchors can be searched for faster than short anchors.
*
* @param sequence A list of ParseTree nodes which are the sequence we're scanning.
* @param startIndex The index of the node to search from.
* @param endIndex The end index (exclusive) of the last node to search for.
* @param compileType whether to compile for PRONOM (only bytes in anchor) or DROID (more complex matchers in anchor)
* @return The start and end indexes of the search sequence as an IntPair.
* @throws CompileException If a suitable anchoring sequence can't be found.
*/
private IntPair locateSearchSequence(final List<ParseTree> sequence,
final int startIndex, final int endIndex,
final CompileType compileType) throws CompileException {
// PRONOM anchors can only contain bytes.
if (compileType == CompileType.PRONOM) {
return locateSearchSequence(sequence, startIndex, endIndex, PRONOMStrategy);
}
// DROID anchors can contain sets, bitmasks and ranges, as long as they aren't too big.
IntPair result = locateSearchSequence(sequence, startIndex, endIndex, DROIDStrategy);
if (result == NO_RESULT) {
// If we couldn't find an anchor with limited sets, bitmasks or ranges, try again allowing anything:
result = locateSearchSequence(sequence, startIndex, endIndex, AllowAllStrategy);
}
return result;
}
/**
* Locates the longest possible "anchoring" sequence to use for searching.
* All other parts of the subsequence to the left and right of the anchor become fragments.
* In general, longer anchors can be searched for faster than short anchors.
*
* @param sequence The sequence of nodes to search in for an anchoring sequence.
* @param startIndex The index of the node to start searching from.
* @param endIndex The end index (exclusive) of the last node to search for.
* @param anchorStrategy Which elements can appear in anchors (bytes: PRONOM, some sets: DROID, anything: emergency)
* @return The start and end indexes of the search sequence as an IntPair.
* @throws CompileException If a suitable anchoring sequence can't be found.
*/
private IntPair locateSearchSequence(final List<ParseTree> sequence,
final int startIndex, final int endIndex,
final AnchorStrategy anchorStrategy) throws CompileException {
//int length = 0;
int startPos = startIndex;
int bestLength = 0;
int bestStart = 0;
int bestEnd = 0;
for (int childIndex = startIndex; childIndex < endIndex; childIndex++) {
ParseTree child = sequence.get(childIndex);
switch (child.getParseTreeType()) {
/* -----------------------------------------------------------------------------------------------------
* Types which can sometimes be part of an anchoring sequence:
*/
case RANGE: case SET: case ALL_BITMASK: case ANY: {
if (anchorStrategy.canBePartOfAnchor(child)) {
break;
}
// If not part of anchor, FALL THROUGH to final section for things which can't be part of an anchor.
// Intentionally no break statement here - it goes to the ALTERNATIVES, ANY, REPEAT and REPEAT_MIN_TO_MAX section.
}
/* -----------------------------------------------------------------------------------------------------
* Types which can't ever be part of an anchoring sequence:
*/
case ALTERNATIVES: case REPEAT: case REPEAT_MIN_TO_MAX: {
// If we found a longer sequence than we had so far, use that:
int totalLength = calculateLength(sequence, startPos, childIndex - 1);
if (totalLength > bestLength) {
bestLength = totalLength;
bestStart = startPos;
bestEnd = childIndex - 1;
}
// Start looking for a longer suitable sequence:
startPos = childIndex + 1; // next subsequence to look for.
break;
}
default: {
// do nothing - we're only looking for types which aren't part of an anchoring sequence.
}
}
}
// Do a final check to see if the last nodes processed are the longest:
int totalLength = calculateLength(sequence, startPos, endIndex - 1);
if (totalLength > bestLength) {
bestLength = totalLength;
bestStart = startPos;
bestEnd = endIndex - 1;
}
// If we have no best length, then we have no anchoring subsequence - DROID can't process it.
if (bestLength == 0) {
return NO_RESULT;
}
return new IntPair(bestStart, bestEnd);
}
private int calculateLength(List<ParseTree> sequence, int startPos, int endPos) throws CompileException {
int totalLength = 0;
try {
for (int index = startPos; index <= endPos; index++) {
ParseTree node = sequence.get(index);
switch (node.getParseTreeType()) {
case BYTE:
case RANGE:
case ANY:
case ALL_BITMASK:
case SET: {
totalLength++;
break;
}
case STRING: {
totalLength += node.getTextValue().length();
break;
}
case REPEAT: { // a value repeated a number of times - length = num repeats.
totalLength += node.getChild(0).getIntValue();
break;
}
default:
throw new CompileException("Could not calculate length of node " + node);
}
}
} catch (ParseException e) {
throw new CompileException(e.getMessage(), e);
}
return totalLength;
}
private static int countMatchingBitmask(ParseTree node) throws ParseException {
return ByteUtils.countBytesMatchingAllBits(node.getByteValue());
}
private static int countMatchingSet(ParseTree node) throws ParseException {
return ParseTreeUtils.calculateSetValues(node).size();
}
// Only include ranges as potential anchor members if they are not too big.
// Large ranges are poor members for a search anchor, as they can massively impede many search algorithms if they're present.
private static int countMatchingRange(final ParseTree rangeNode) throws CompileException {
if (rangeNode.getParseTreeType() == ParseTreeType.RANGE) {
final int range1, range2;
try {
range1 = rangeNode.getChild(0).getIntValue();
range2 = rangeNode.getChild(1).getIntValue();
} catch (ParseException e) {
throw new CompileException(e.getMessage(), e);
}
return range2 > range1 ? range2 - range1 : range1 - range2; // range values are not necessarily smaller to larger...
}
throw new IllegalArgumentException("Parse tree node is not a RANGE type: " + rangeNode);
}
private static IntPair NO_RESULT = new IntPair(-1, -1);
private static class IntPair {
final int firstInt;
final int secondInt;
public IntPair(final int firstInt, final int secondInt) {
this.firstInt = firstInt;
this.secondInt = secondInt;
}
}
private static class IntIterator {
private final int stopValue;
private final int increment;
private int position;
public IntIterator(final int start, final int end) {
// Won't iterate negative numbers - this is to iterate index positions in a sequence.
if (start < 0 || end < 0) {
this.position = 0;
this.increment = 0;
this.stopValue = 0;
} else {
this.position = start;
this.increment = start < end ? 1 : -1;
this.stopValue = end + increment;
}
}
public boolean hasNext() {
return position != stopValue;
}
public int next() {
if (hasNext()) {
final int currentPosition = position;
position += increment;
return currentPosition;
}
throw new NoSuchElementException("Iterator has position: " + position + " stopValue: " + stopValue + " and increment " + increment);
}
}
private static AnchorStrategy PRONOMStrategy = new PRONOMAnchorStrategy();
private static AnchorStrategy DROIDStrategy = new DROIDAnchorStrategy();
private static AnchorStrategy AllowAllStrategy = new AllowAllAnchorStrategy();
private interface AnchorStrategy {
boolean canBePartOfAnchor(ParseTree node) throws CompileException;
}
private static class PRONOMAnchorStrategy implements AnchorStrategy {
@Override
public boolean canBePartOfAnchor(final ParseTree node) throws CompileException {
return false;
}
}
private static class DROIDAnchorStrategy implements AnchorStrategy {
@Override
public boolean canBePartOfAnchor(final ParseTree node) throws CompileException {
final ParseTreeType type = node.getParseTreeType();
try {
return (type == ParseTreeType.RANGE && countMatchingRange(node) <= MAX_MATCHING_BYTES) ||
(type == ParseTreeType.SET && countMatchingSet(node) <= MAX_MATCHING_BYTES) ||
(type == ParseTreeType.ALL_BITMASK && countMatchingBitmask(node) <= MAX_MATCHING_BYTES);
} catch (ParseException e) {
throw new CompileException(e.getMessage(), e);
}
}
}
private static class AllowAllAnchorStrategy implements AnchorStrategy {
@Override
public boolean canBePartOfAnchor(final ParseTree node) throws CompileException {
return true;
}
}
}
| 48.657783 | 163 | 0.609408 |
949b2e4fa6b9f76c6d09b1c5980fba401cbf28d8
| 2,390 |
package org.oguz.spring.aop.camera;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class Logger
{
@Pointcut ("execution(* org.oguz.spring.aop.camera.Camera.*(..))")
public void cameraSnap(){
}
@Pointcut ("within(org.oguz.spring.aop.camera..*)")
public void withinDemo(){
}
@Pointcut ("target(org.oguz.spring.aop.camera.Camera)")
public void targetDemo(){
}
@Pointcut ("this(org.oguz.spring.aop.camera.ICamera)")
public void thisDemo(){
}
@Pointcut ("execution(* org.oguz.spring.aop.camera.Camera.snap(String))")
public void cameraSnapName(){
}
@Pointcut ("execution(* *.*(..))")
public void cameraRelatedAction(){
}
@Before("withinDemo()")
public void withinDemoAdvice(){
System.out.println("***Before WITHIN demo advice***");
}
@Before("targetDemo()")
public void targetDemoAdvice(){
System.out.println("***Before TARGET demo advice***");
}
@Before("thisDemo()")
public void thisDemoAdvice(){
System.out.println("***Before THIS demo advice***");
}
@Before("cameraSnapName()")
public void aboutToTakePhotoWithName(){
//System.out.println("About to take photo with Name...");
}
@After("cameraRelatedAction()")
public void afterCameraRelatedAction(){
//System.out.println("After advice, something related to camera actions...");
}
@AfterReturning("cameraRelatedAction()")
public void afterReturningCameraRelatedAction(){
//System.out.println("After Returning advice, something related to camera actions...\n");
}
@AfterThrowing("cameraRelatedAction()")
public void afterThrowingCameraRelatedAction(){
//System.out.println("After Throwing advice, something related to camera actions...\n");
}
@Around("cameraRelatedAction()")
public void aroundAdvice(ProceedingJoinPoint p){
//System.out.println("\nAround advice...");
try
{
p.proceed();
}
catch (Throwable e)
{
// TODO Auto-generated catch block
System.out.println("in around advice: "+e.getMessage());
}
}
}
| 23.203883 | 91 | 0.710042 |
c9968b5dd72f60d8c31d8e13cb7b078ff9575730
| 14,908 |
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/dialogflow/v2beta1/context.proto
package com.google.cloud.dialogflow.v2beta1;
public final class ContextProto {
private ContextProto() {}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry);
}
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_dialogflow_v2beta1_Context_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_dialogflow_v2beta1_Context_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_dialogflow_v2beta1_ListContextsRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_dialogflow_v2beta1_ListContextsRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_dialogflow_v2beta1_ListContextsResponse_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_dialogflow_v2beta1_ListContextsResponse_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_dialogflow_v2beta1_GetContextRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_dialogflow_v2beta1_GetContextRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_dialogflow_v2beta1_CreateContextRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_dialogflow_v2beta1_CreateContextRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_dialogflow_v2beta1_UpdateContextRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_dialogflow_v2beta1_UpdateContextRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_dialogflow_v2beta1_DeleteContextRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_dialogflow_v2beta1_DeleteContextRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_dialogflow_v2beta1_DeleteAllContextsRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_dialogflow_v2beta1_DeleteAllContextsRequest_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor descriptor;
static {
java.lang.String[] descriptorData = {
"\n-google/cloud/dialogflow/v2beta1/contex"
+ "t.proto\022\037google.cloud.dialogflow.v2beta1"
+ "\032\034google/api/annotations.proto\032\033google/p"
+ "rotobuf/empty.proto\032 google/protobuf/fie"
+ "ld_mask.proto\032\034google/protobuf/struct.pr"
+ "oto\032\027google/api/client.proto\"\\\n\007Context\022"
+ "\014\n\004name\030\001 \001(\t\022\026\n\016lifespan_count\030\002 \001(\005\022+\n"
+ "\nparameters\030\003 \001(\0132\027.google.protobuf.Stru"
+ "ct\"L\n\023ListContextsRequest\022\016\n\006parent\030\001 \001("
+ "\t\022\021\n\tpage_size\030\002 \001(\005\022\022\n\npage_token\030\003 \001(\t"
+ "\"k\n\024ListContextsResponse\022:\n\010contexts\030\001 \003"
+ "(\0132(.google.cloud.dialogflow.v2beta1.Con"
+ "text\022\027\n\017next_page_token\030\002 \001(\t\"!\n\021GetCont"
+ "extRequest\022\014\n\004name\030\001 \001(\t\"a\n\024CreateContex"
+ "tRequest\022\016\n\006parent\030\001 \001(\t\0229\n\007context\030\002 \001("
+ "\0132(.google.cloud.dialogflow.v2beta1.Cont"
+ "ext\"\202\001\n\024UpdateContextRequest\0229\n\007context\030"
+ "\001 \001(\0132(.google.cloud.dialogflow.v2beta1."
+ "Context\022/\n\013update_mask\030\002 \001(\0132\032.google.pr"
+ "otobuf.FieldMask\"$\n\024DeleteContextRequest"
+ "\022\014\n\004name\030\001 \001(\t\"*\n\030DeleteAllContextsReque"
+ "st\022\016\n\006parent\030\001 \001(\t2\313\025\n\010Contexts\022\261\003\n\014List"
+ "Contexts\0224.google.cloud.dialogflow.v2bet"
+ "a1.ListContextsRequest\0325.google.cloud.di"
+ "alogflow.v2beta1.ListContextsResponse\"\263\002"
+ "\202\323\344\223\002\254\002\0226/v2beta1/{parent=projects/*/age"
+ "nt/sessions/*}/contextsZO\022M/v2beta1/{par"
+ "ent=projects/*/agent/environments/*/user"
+ "s/*/sessions/*}/contextsZD\022B/v2beta1/{pa"
+ "rent=projects/*/locations/*/agent/sessio"
+ "ns/*}/contextsZ[\022Y/v2beta1/{parent=proje"
+ "cts/*/locations/*/agent/environments/*/u"
+ "sers/*/sessions/*}/contexts\022\240\003\n\nGetConte"
+ "xt\0222.google.cloud.dialogflow.v2beta1.Get"
+ "ContextRequest\032(.google.cloud.dialogflow"
+ ".v2beta1.Context\"\263\002\202\323\344\223\002\254\002\0226/v2beta1/{na"
+ "me=projects/*/agent/sessions/*/contexts/"
+ "*}ZO\022M/v2beta1/{name=projects/*/agent/en"
+ "vironments/*/users/*/sessions/*/contexts"
+ "/*}ZD\022B/v2beta1/{name=projects/*/locatio"
+ "ns/*/agent/sessions/*/contexts/*}Z[\022Y/v2"
+ "beta1/{name=projects/*/locations/*/agent"
+ "/environments/*/users/*/sessions/*/conte"
+ "xts/*}\022\312\003\n\rCreateContext\0225.google.cloud."
+ "dialogflow.v2beta1.CreateContextRequest\032"
+ "(.google.cloud.dialogflow.v2beta1.Contex"
+ "t\"\327\002\202\323\344\223\002\320\002\"6/v2beta1/{parent=projects/*"
+ "/agent/sessions/*}/contexts:\007contextZX\"M"
+ "/v2beta1/{parent=projects/*/agent/enviro"
+ "nments/*/users/*/sessions/*}/contexts:\007c"
+ "ontextZM\"B/v2beta1/{parent=projects/*/lo"
+ "cations/*/agent/sessions/*}/contexts:\007co"
+ "ntextZd\"Y/v2beta1/{parent=projects/*/loc"
+ "ations/*/agent/environments/*/users/*/se"
+ "ssions/*}/contexts:\007context\022\352\003\n\rUpdateCo"
+ "ntext\0225.google.cloud.dialogflow.v2beta1."
+ "UpdateContextRequest\032(.google.cloud.dial"
+ "ogflow.v2beta1.Context\"\367\002\202\323\344\223\002\360\0022>/v2bet"
+ "a1/{context.name=projects/*/agent/sessio"
+ "ns/*/contexts/*}:\007contextZ`2U/v2beta1/{c"
+ "ontext.name=projects/*/agent/environment"
+ "s/*/users/*/sessions/*/contexts/*}:\007cont"
+ "extZU2J/v2beta1/{context.name=projects/*"
+ "/locations/*/agent/sessions/*/contexts/*"
+ "}:\007contextZl2a/v2beta1/{context.name=pro"
+ "jects/*/locations/*/agent/environments/*"
+ "/users/*/sessions/*/contexts/*}:\007context"
+ "\022\224\003\n\rDeleteContext\0225.google.cloud.dialog"
+ "flow.v2beta1.DeleteContextRequest\032\026.goog"
+ "le.protobuf.Empty\"\263\002\202\323\344\223\002\254\002*6/v2beta1/{n"
+ "ame=projects/*/agent/sessions/*/contexts"
+ "/*}ZO*M/v2beta1/{name=projects/*/agent/e"
+ "nvironments/*/users/*/sessions/*/context"
+ "s/*}ZD*B/v2beta1/{name=projects/*/locati"
+ "ons/*/agent/sessions/*/contexts/*}Z[*Y/v"
+ "2beta1/{name=projects/*/locations/*/agen"
+ "t/environments/*/users/*/sessions/*/cont"
+ "exts/*}\022\234\003\n\021DeleteAllContexts\0229.google.c"
+ "loud.dialogflow.v2beta1.DeleteAllContext"
+ "sRequest\032\026.google.protobuf.Empty\"\263\002\202\323\344\223\002"
+ "\254\002*6/v2beta1/{parent=projects/*/agent/se"
+ "ssions/*}/contextsZO*M/v2beta1/{parent=p"
+ "rojects/*/agent/environments/*/users/*/s"
+ "essions/*}/contextsZD*B/v2beta1/{parent="
+ "projects/*/locations/*/agent/sessions/*}"
+ "/contextsZ[*Y/v2beta1/{parent=projects/*"
+ "/locations/*/agent/environments/*/users/"
+ "*/sessions/*}/contexts\032x\312A\031dialogflow.go"
+ "ogleapis.com\322AYhttps://www.googleapis.co"
+ "m/auth/cloud-platform,https://www.google"
+ "apis.com/auth/dialogflowB\252\001\n#com.google."
+ "cloud.dialogflow.v2beta1B\014ContextProtoP\001"
+ "ZIgoogle.golang.org/genproto/googleapis/"
+ "cloud/dialogflow/v2beta1;dialogflow\370\001\001\242\002"
+ "\002DF\252\002\037Google.Cloud.Dialogflow.V2beta1b\006p"
+ "roto3"
};
descriptor =
com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(
descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
com.google.api.AnnotationsProto.getDescriptor(),
com.google.protobuf.EmptyProto.getDescriptor(),
com.google.protobuf.FieldMaskProto.getDescriptor(),
com.google.protobuf.StructProto.getDescriptor(),
com.google.api.ClientProto.getDescriptor(),
});
internal_static_google_cloud_dialogflow_v2beta1_Context_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_google_cloud_dialogflow_v2beta1_Context_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_dialogflow_v2beta1_Context_descriptor,
new java.lang.String[] {
"Name", "LifespanCount", "Parameters",
});
internal_static_google_cloud_dialogflow_v2beta1_ListContextsRequest_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_google_cloud_dialogflow_v2beta1_ListContextsRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_dialogflow_v2beta1_ListContextsRequest_descriptor,
new java.lang.String[] {
"Parent", "PageSize", "PageToken",
});
internal_static_google_cloud_dialogflow_v2beta1_ListContextsResponse_descriptor =
getDescriptor().getMessageTypes().get(2);
internal_static_google_cloud_dialogflow_v2beta1_ListContextsResponse_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_dialogflow_v2beta1_ListContextsResponse_descriptor,
new java.lang.String[] {
"Contexts", "NextPageToken",
});
internal_static_google_cloud_dialogflow_v2beta1_GetContextRequest_descriptor =
getDescriptor().getMessageTypes().get(3);
internal_static_google_cloud_dialogflow_v2beta1_GetContextRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_dialogflow_v2beta1_GetContextRequest_descriptor,
new java.lang.String[] {
"Name",
});
internal_static_google_cloud_dialogflow_v2beta1_CreateContextRequest_descriptor =
getDescriptor().getMessageTypes().get(4);
internal_static_google_cloud_dialogflow_v2beta1_CreateContextRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_dialogflow_v2beta1_CreateContextRequest_descriptor,
new java.lang.String[] {
"Parent", "Context",
});
internal_static_google_cloud_dialogflow_v2beta1_UpdateContextRequest_descriptor =
getDescriptor().getMessageTypes().get(5);
internal_static_google_cloud_dialogflow_v2beta1_UpdateContextRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_dialogflow_v2beta1_UpdateContextRequest_descriptor,
new java.lang.String[] {
"Context", "UpdateMask",
});
internal_static_google_cloud_dialogflow_v2beta1_DeleteContextRequest_descriptor =
getDescriptor().getMessageTypes().get(6);
internal_static_google_cloud_dialogflow_v2beta1_DeleteContextRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_dialogflow_v2beta1_DeleteContextRequest_descriptor,
new java.lang.String[] {
"Name",
});
internal_static_google_cloud_dialogflow_v2beta1_DeleteAllContextsRequest_descriptor =
getDescriptor().getMessageTypes().get(7);
internal_static_google_cloud_dialogflow_v2beta1_DeleteAllContextsRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_dialogflow_v2beta1_DeleteAllContextsRequest_descriptor,
new java.lang.String[] {
"Parent",
});
com.google.protobuf.ExtensionRegistry registry =
com.google.protobuf.ExtensionRegistry.newInstance();
registry.add(com.google.api.ClientProto.defaultHost);
registry.add(com.google.api.AnnotationsProto.http);
registry.add(com.google.api.ClientProto.oauthScopes);
com.google.protobuf.Descriptors.FileDescriptor.internalUpdateFileDescriptor(
descriptor, registry);
com.google.api.AnnotationsProto.getDescriptor();
com.google.protobuf.EmptyProto.getDescriptor();
com.google.protobuf.FieldMaskProto.getDescriptor();
com.google.protobuf.StructProto.getDescriptor();
com.google.api.ClientProto.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
| 57.782946 | 98 | 0.713442 |
164889bb6766ad80c9a6b45f5c51eee563be8d30
| 1,473 |
package org.simpleframework.http.validate;
import java.net.InetSocketAddress;
import java.net.Socket;
import org.simpleframework.common.buffer.Buffer;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Transient;
import org.simpleframework.xml.core.Commit;
@Root
public class ConnectionTask {
@Element
private RequestTask request;
@Attribute
private Protocol protocol;
@Attribute
private String host;
@Attribute
private int port;
@Attribute
private int repeat;
@Attribute
private double throttle;
@Transient
private byte[] pipeline;
@Transient
private InetSocketAddress address;
@Transient
private SocketConnector connector;
@Commit
private void commit() throws Exception {
address = new InetSocketAddress(host, port);
pipeline = request.getRequest(repeat);
if(protocol == Protocol.HTTPS) {
connector = new SecureSocketConnector();
} else {
connector = new SocketConnector();
}
}
public int getRepeat() {
return repeat;
}
public Buffer execute(Client client) throws Exception {
String host = address.getHostName();
int port = address.getPort();
Socket socket = connector.connect(host, port);
return client.execute(socket, pipeline, throttle);
}
}
| 21.985075 | 58 | 0.678887 |
4e83773cc83aa55c4c65a77c8753066b23ba7e1c
| 211 |
package br.com.marcosatanaka.easypoi.model;
import lombok.Getter;
@Getter
public class EnumNomeRelatorio {
public static String RELATORIO_REPIQUE_ATENDENTE = "Relatório Repique por Atendente";
}
| 19.181818 | 88 | 0.767773 |
cbde26051cf004add3cddb6cada4ee0aefdc4866
| 2,172 |
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.google.android.gms.internal.ads;
// Referenced classes of package com.google.android.gms.internal.ads:
// zzfs, bhi
public final class bhh
{
public bhh(int l, int i1, long l1, long l2, long l3, zzfs zzfs, int j1, bhi abhi[], int k1, long al[], long al1[])
{
// 0 0:aload_0
// 1 1:invokespecial #25 <Method void Object()>
a = l;
// 2 4:aload_0
// 3 5:iload_1
// 4 6:putfield #27 <Field int a>
b = i1;
// 5 9:aload_0
// 6 10:iload_2
// 7 11:putfield #29 <Field int b>
c = l1;
// 8 14:aload_0
// 9 15:lload_3
// 10 16:putfield #31 <Field long c>
d = l2;
// 11 19:aload_0
// 12 20:lload 5
// 13 22:putfield #33 <Field long d>
e = l3;
// 14 25:aload_0
// 15 26:lload 7
// 16 28:putfield #35 <Field long e>
f = zzfs;
// 17 31:aload_0
// 18 32:aload 9
// 19 34:putfield #37 <Field zzfs f>
g = j1;
// 20 37:aload_0
// 21 38:iload 10
// 22 40:putfield #39 <Field int g>
h = abhi;
// 23 43:aload_0
// 24 44:aload 11
// 25 46:putfield #41 <Field bhi[] h>
k = k1;
// 26 49:aload_0
// 27 50:iload 12
// 28 52:putfield #43 <Field int k>
i = al;
// 29 55:aload_0
// 30 56:aload 13
// 31 58:putfield #45 <Field long[] i>
j = al1;
// 32 61:aload_0
// 33 62:aload 14
// 34 64:putfield #47 <Field long[] j>
// 35 67:return
}
public final int a;
public final int b;
public final long c;
public final long d;
public final long e;
public final zzfs f;
public final int g;
public final bhi h[];
public final long i[];
public final long j[];
public final int k;
}
| 28.207792 | 115 | 0.48849 |
541aea6334d0af40caab2a1f9f3a40c7e8c48d2c
| 860 |
package com.example.lyw.festval_sms.bean;
import java.util.Date;
/**
* Created by LYW on 2016/11/2.
*/
public class Festival_Bean {
private int id;
private String name;
private Date date;
private String des_name;
public Festival_Bean(int id,String name){
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getDes_name() {
return des_name;
}
public void setDes_name(String des_name) {
this.des_name = des_name;
}
}
| 16.538462 | 46 | 0.57093 |
644f51422ef092ddbd4491199866ca404525c62d
| 7,164 |
package org.sagebionetworks.repo.manager.entity;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.sagebionetworks.repo.manager.message.ChangeMessageUtils;
import org.sagebionetworks.repo.model.IdList;
import org.sagebionetworks.repo.model.ObjectType;
import org.sagebionetworks.repo.model.message.ChangeMessage;
import org.sagebionetworks.repo.model.message.ChangeMessages;
import org.sagebionetworks.repo.model.message.ChangeType;
import org.springframework.test.util.ReflectionTestUtils;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.model.CreateQueueResult;
import com.amazonaws.services.sqs.model.GetQueueAttributesRequest;
import com.amazonaws.services.sqs.model.GetQueueAttributesResult;
import com.amazonaws.services.sqs.model.QueueAttributeName;
import com.amazonaws.services.sqs.model.SendMessageRequest;
import com.google.common.collect.Lists;
@RunWith(MockitoJUnitRunner.class)
public class ReplicationMessageManagerImplTest {
@Mock
AmazonSQS mockSqsClient;
ReplicationMessageManagerImpl manager;
String replicationQueueName;
String replicationQueueUrl;
String reconciliationQueueName;
String reconciliationQueueUrl;
long messageCount;
Map<String, String> queueAttributes;
@Before
public void before() {
manager = new ReplicationMessageManagerImpl();
ReflectionTestUtils.setField(manager, "sqsClient", mockSqsClient);
replicationQueueName = "replicationQueueName";
replicationQueueUrl = "replicationQueueUrl";
reconciliationQueueName = "reconciliationQueueName";
reconciliationQueueUrl = "reconciliationQueueUrl";
when(mockSqsClient.createQueue(replicationQueueName)).thenReturn(
new CreateQueueResult().withQueueUrl(replicationQueueUrl));
when(mockSqsClient.createQueue(reconciliationQueueName)).thenReturn(
new CreateQueueResult().withQueueUrl(reconciliationQueueUrl));
manager.setReplicationQueueName(replicationQueueName);
manager.setReconciliationQueueName(reconciliationQueueName);
manager.initialize();
assertEquals(replicationQueueUrl, manager.replicationQueueUrl);
assertEquals(reconciliationQueueUrl, manager.reconciliationQueueUrl);
messageCount = 99L;
queueAttributes = new HashMap<>(0);
queueAttributes.put(QueueAttributeName.ApproximateNumberOfMessages.name(), ""+ messageCount);
when(mockSqsClient.getQueueAttributes(any(GetQueueAttributesRequest.class)))
.thenReturn(new GetQueueAttributesResult().withAttributes(queueAttributes));
}
@Test
public void testPushChangeMessagesToReplicationQueue(){
// single message
List<ChangeMessage> toPush = createMessages(1);
// call under test
manager.pushChangeMessagesToReplicationQueue(toPush);
ChangeMessages messages = new ChangeMessages();
messages.setList(toPush);
String expectedBody = manager.createMessageBodyJSON(messages);
verify(mockSqsClient, times(1)).sendMessage(new SendMessageRequest(replicationQueueUrl,
expectedBody));
}
@Test
public void testPushChangeMessagesToReplicationQueueOverMax(){
// pushing more than the max messages should result in multiple batches.
List<ChangeMessage> toPush = createMessages(ChangeMessageUtils.MAX_NUMBER_OF_CHANGE_MESSAGES_PER_SQS_MESSAGE+1);
// call under test
manager.pushChangeMessagesToReplicationQueue(toPush);
verify(mockSqsClient, times(2)).sendMessage(any(SendMessageRequest.class));
}
@Test
public void testPushChangeMessagesToReplicationQueueEmpty(){
List<ChangeMessage> empty = new LinkedList<ChangeMessage>();
// call under test
manager.pushChangeMessagesToReplicationQueue(empty);
verify(mockSqsClient, never()).sendMessage(any(SendMessageRequest.class));
}
@Test (expected=IllegalArgumentException.class)
public void testPushChangeMessagesToReplicationQueueNull(){
List<ChangeMessage> empty = null;
// call under test
manager.pushChangeMessagesToReplicationQueue(empty);
}
@Test
public void testPushContainerIdsToReconciliationQueue(){
// single message
List<Long> toPush = Lists.newArrayList(111L);
// call under test
manager.pushContainerIdsToReconciliationQueue(toPush);
IdList messages = new IdList();
messages.setList(toPush);
String expectedBody = manager.createMessageBodyJSON(messages);
verify(mockSqsClient, times(1)).sendMessage(new SendMessageRequest(reconciliationQueueUrl,
expectedBody));
}
@Test
public void testPushContainerIdsToReconciliationQueueOverMax(){
// pushing more than the max messages should result in multiple batches.
List<Long> toPush = createLongMessages(ReplicationMessageManagerImpl.MAX_CONTAINERS_IDS_PER_RECONCILIATION_MESSAGE+1);
// call under test
manager.pushContainerIdsToReconciliationQueue(toPush);
verify(mockSqsClient, times(2)).sendMessage(any(SendMessageRequest.class));
}
@Test
public void testPushContainerIdsToReconciliationQueueEmpty(){
List<Long> empty = new LinkedList<Long>();
// call under test
manager.pushContainerIdsToReconciliationQueue(empty);
verify(mockSqsClient, never()).sendMessage(any(SendMessageRequest.class));
}
@Test (expected=IllegalArgumentException.class)
public void testPushContainerIdsToReconciliationQueueNull(){
List<Long> empty = null;
// call under test
manager.pushContainerIdsToReconciliationQueue(empty);
}
@Test
public void testGetApproximateNumberOfMessageOnReplicationQueue() {
// call under test
long count = manager.getApproximateNumberOfMessageOnReplicationQueue();
assertEquals(messageCount, count);
}
@Test (expected=IllegalArgumentException.class)
public void testGetApproximateNumberOfMessageOnReplicationQueueMissingAttribute() {
this.queueAttributes.clear();
// call under test
manager.getApproximateNumberOfMessageOnReplicationQueue();
}
/**
* Helper to create some messages.
* @param count
* @return
*/
public List<ChangeMessage> createMessages(int count){
List<ChangeMessage> list = new LinkedList<ChangeMessage>();
for(int i=0; i<count; i++){
ChangeMessage message = new ChangeMessage();
message.setChangeNumber(new Long(i));
message.setChangeType(ChangeType.UPDATE);
message.setObjectEtag("etag"+i);
message.setObjectId("id"+i);
message.setObjectType(ObjectType.ENTITY);
list.add(message);
}
return list;
}
/**
* Helper to create a list of longs.
* @param count
* @return
*/
public List<Long> createLongMessages(int count){
List<Long> results = new LinkedList<Long>();
for(long i=0; i<count; i++){
results.add(i);
}
return results;
}
}
| 35.117647 | 121 | 0.775126 |
2d080d94b4c5307de98e8316e43a6e27f48a8876
| 1,380 |
/**
*
*/
package io.sipstack;
import io.sipstack.core.Utils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.time.Duration;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
/**
* @author jonas
*
*/
public class UtilsTest {
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {}
/**
* See RFC3261 section 17.1.2.2
*
* Default values of t1 = 500 ms and t4 of 4000 ms will yield:
*
* 500 ms, 1 s, 2 s, 4 s, 4 s, 4 s
*/
@Test
public void testBackoff() {
assertThat(Utils.calculateBackoffTimer(0, 500, 4000), is(Duration.ofMillis(500)));
assertThat(Utils.calculateBackoffTimer(1, 500, 4000), is(Duration.ofMillis(1000)));
assertThat(Utils.calculateBackoffTimer(2, 500, 4000), is(Duration.ofMillis(2000)));
assertThat(Utils.calculateBackoffTimer(3, 500, 4000), is(Duration.ofMillis(4000)));
assertThat(Utils.calculateBackoffTimer(4, 500, 4000), is(Duration.ofMillis(4000)));
assertThat(Utils.calculateBackoffTimer(5, 500, 4000), is(Duration.ofMillis(4000)));
assertThat(Utils.calculateBackoffTimer(6, 500, 4000), is(Duration.ofMillis(4000)));
}
}
| 26.037736 | 91 | 0.649275 |
6f7f108d79c5576e225b960830b6f2d87349e512
| 3,946 |
package com.google.android.gms.games.snapshot;
import android.os.Parcel;
import android.os.ParcelFileDescriptor;
import com.google.android.gms.common.internal.safeparcel.SafeParcelable;
import com.google.android.gms.common.internal.zzx;
import com.google.android.gms.drive.Contents;
import com.google.android.gms.games.internal.GamesLog;
import com.google.android.gms.internal.zznt;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
public final class SnapshotContentsEntity implements SafeParcelable, SnapshotContents {
public static final SnapshotContentsEntityCreator CREATOR = new SnapshotContentsEntityCreator();
private static final Object zzaIa = new Object();
private final int mVersionCode;
private Contents zzaoW;
SnapshotContentsEntity(int versionCode, Contents contents) {
this.mVersionCode = versionCode;
this.zzaoW = contents;
}
public SnapshotContentsEntity(Contents contents) {
this(1, contents);
}
private boolean zza(int i, byte[] bArr, int i2, int i3, boolean z) {
zzx.zza(!isClosed(), (Object) "Must provide a previously opened SnapshotContents");
synchronized (zzaIa) {
OutputStream fileOutputStream = new FileOutputStream(this.zzaoW.getParcelFileDescriptor().getFileDescriptor());
OutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
try {
FileChannel channel = fileOutputStream.getChannel();
channel.position((long) i);
bufferedOutputStream.write(bArr, i2, i3);
if (z) {
channel.truncate((long) bArr.length);
}
bufferedOutputStream.flush();
} catch (Throwable e) {
GamesLog.zza("SnapshotContentsEntity", "Failed to write snapshot data", e);
return false;
}
}
return true;
}
public void close() {
this.zzaoW = null;
}
public int describeContents() {
return 0;
}
public ParcelFileDescriptor getParcelFileDescriptor() {
zzx.zza(!isClosed(), (Object) "Cannot mutate closed contents!");
return this.zzaoW.getParcelFileDescriptor();
}
public int getVersionCode() {
return this.mVersionCode;
}
public boolean isClosed() {
return this.zzaoW == null;
}
public boolean modifyBytes(int dstOffset, byte[] content, int srcOffset, int count) {
return zza(dstOffset, content, srcOffset, content.length, false);
}
public byte[] readFully() throws IOException {
byte[] zza;
boolean z = false;
if (!isClosed()) {
z = true;
}
zzx.zza(z, (Object) "Must provide a previously opened Snapshot");
synchronized (zzaIa) {
InputStream fileInputStream = new FileInputStream(this.zzaoW.getParcelFileDescriptor().getFileDescriptor());
InputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
try {
fileInputStream.getChannel().position(0);
zza = zznt.zza(bufferedInputStream, false);
fileInputStream.getChannel().position(0);
} catch (Throwable e) {
GamesLog.zzb("SnapshotContentsEntity", "Failed to read snapshot data", e);
throw e;
}
}
return zza;
}
public boolean writeBytes(byte[] content) {
return zza(0, content, 0, content.length, true);
}
public void writeToParcel(Parcel out, int flags) {
SnapshotContentsEntityCreator.zza(this, out, flags);
}
public Contents zzsh() {
return this.zzaoW;
}
}
| 34.614035 | 123 | 0.649265 |
f7f2d5ff3c14bdd60a70a5c53f4f6e1f86865ff0
| 47,754 |
package l2f.gameserver.model.pledge;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.napile.primitive.maps.IntObjectMap;
import org.napile.primitive.maps.impl.CTreeIntObjectMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import l2f.commons.collections.JoinedIterator;
import l2f.commons.configuration.Config;
import l2f.commons.dbutils.DbUtils;
import l2f.gameserver.cache.CrestCache;
import l2f.gameserver.cache.Msg;
//import l2f.gameserver.data.ClanRequest;
import l2f.gameserver.data.xml.holder.EventHolder;
import l2f.gameserver.data.xml.holder.ResidenceHolder;
import l2f.gameserver.database.DatabaseFactory;
import l2f.gameserver.database.mysql;
import l2f.gameserver.model.Player;
import l2f.gameserver.model.Skill;
import l2f.gameserver.model.World;
import l2f.gameserver.model.entity.boat.ClanAirShip;
import l2f.gameserver.model.entity.events.impl.DominionSiegeEvent;
import l2f.gameserver.model.entity.residence.Castle;
import l2f.gameserver.model.entity.residence.Fortress;
import l2f.gameserver.model.entity.residence.ResidenceType;
import l2f.gameserver.model.items.ClanWarehouse;
import l2f.gameserver.model.items.ItemInstance;
import l2f.gameserver.network.serverpackets.JoinPledge;
import l2f.gameserver.network.serverpackets.L2GameServerPacket;
import l2f.gameserver.network.serverpackets.PledgeReceiveSubPledgeCreated;
import l2f.gameserver.network.serverpackets.PledgeShowInfoUpdate;
import l2f.gameserver.network.serverpackets.PledgeShowMemberListAdd;
import l2f.gameserver.network.serverpackets.PledgeShowMemberListAll;
import l2f.gameserver.network.serverpackets.PledgeShowMemberListDeleteAll;
import l2f.gameserver.network.serverpackets.PledgeSkillList;
import l2f.gameserver.network.serverpackets.PledgeSkillListAdd;
import l2f.gameserver.network.serverpackets.SkillList;
import l2f.gameserver.network.serverpackets.SystemMessage2;
import l2f.gameserver.network.serverpackets.components.IStaticPacket;
import l2f.gameserver.network.serverpackets.components.SystemMsg;
import l2f.gameserver.tables.ClanTable;
import l2f.gameserver.tables.SkillTable;
import l2f.gameserver.utils.Log;
public class Clan implements Iterable<UnitMember>
{
private static final Logger _log = LoggerFactory.getLogger(Clan.class);
private final int _clanId;
private int _allyId;
private int _level;
private int _hasCastle;
private int _hasFortress;
private int _hasHideout;
private int _warDominion;
private int _crestId;
private int _crestLargeId;
private long _leavedAllyTime;
private long _dissolvedAllyTime;
private long _expelledMemberTime;
private ClanAirShip _airship;
private boolean _airshipLicense;
private int _airshipFuel;
// all these in milliseconds
public static long EXPELLED_MEMBER_PENALTY = Config.CLAN_LEAVE_PENALTY * 60 * 60 * 1000L;
public static long LEAVED_ALLY_PENALTY = Config.ALLY_LEAVE_PENALTY * 60 * 60 * 1000L;
public static long DISSOLVED_ALLY_PENALTY = Config.DISSOLVED_ALLY_PENALTY * 60 * 60 * 1000L;
private ClanWarehouse _warehouse;
private int _whBonus = -1;
private String _notice = null;
// private String _description = null;
private List<Clan> _atWarWith = new ArrayList<Clan>();
private List<Clan> _underAttackFrom = new ArrayList<Clan>();
protected IntObjectMap<Skill> _skills = new CTreeIntObjectMap<Skill>();
protected IntObjectMap<RankPrivs> _privs = new CTreeIntObjectMap<RankPrivs>();
protected IntObjectMap<SubUnit> _subUnits = new CTreeIntObjectMap<SubUnit>();
private int _reputation = 0;
private int _siegeKills = 0;
// Recruitment
private boolean _recruting = false;
private ArrayList<Integer> _classesNeeded = new ArrayList<>();
private String[] _questions = new String[8];
private ArrayList<SinglePetition> _petitions = new ArrayList<>();
// Clan Privileges: system
public static final int CP_NOTHING = 0;
public static final int CP_CL_INVITE_CLAN = 2; // Join clan
public static final int CP_CL_MANAGE_TITLES = 4; // Give a title
public static final int CP_CL_WAREHOUSE_SEARCH = 8; // View warehouse content
public static final int CP_CL_MANAGE_RANKS = 16; // manage clan ranks
public static final int CP_CL_CLAN_WAR = 32;
public static final int CP_CL_DISMISS = 64;
public static final int CP_CL_EDIT_CREST = 128; // Edit clan crest
public static final int CP_CL_APPRENTICE = 256;
public static final int CP_CL_TROOPS_FAME = 512;
public static final int CP_CL_SUMMON_AIRSHIP = 1024;
// Clan Privileges: clan hall
public static final int CP_CH_ENTRY_EXIT = 2048; // open a door
public static final int CP_CH_USE_FUNCTIONS = 4096;
public static final int CP_CH_AUCTION = 8192;
public static final int CP_CH_DISMISS = 16384;
public static final int CP_CH_SET_FUNCTIONS = 32768;
// Clan Privileges: castle/fotress
public static final int CP_CS_ENTRY_EXIT = 65536;
public static final int CP_CS_MANOR_ADMIN = 131072;
public static final int CP_CS_MANAGE_SIEGE = 262144;
public static final int CP_CS_USE_FUNCTIONS = 524288;
public static final int CP_CS_DISMISS = 1048576;
public static final int CP_CS_TAXES = 2097152;
public static final int CP_CS_MERCENARIES = 4194304;
public static final int CP_CS_SET_FUNCTIONS = 8388606;
public static final int CP_ALL = 16777214;
public static final int RANK_FIRST = 1;
public static final int RANK_LAST = 9;
// Sub-unit types
public static final int SUBUNIT_NONE = Byte.MIN_VALUE;
public static final int SUBUNIT_ACADEMY = -1;
public static final int SUBUNIT_MAIN_CLAN = 0;
public static final int SUBUNIT_ROYAL1 = 100;
public static final int SUBUNIT_ROYAL2 = 200;
public static final int SUBUNIT_KNIGHT1 = 1001;
public static final int SUBUNIT_KNIGHT2 = 1002;
public static final int SUBUNIT_KNIGHT3 = 2001;
public static final int SUBUNIT_KNIGHT4 = 2002;
private final static ClanReputationComparator REPUTATION_COMPARATOR = new ClanReputationComparator();
/** Number of places in the table of ranks clans */
private final static int REPUTATION_PLACES = 100;
/**
* The constructor is only used internally to restore a database
* @param clanId
*/
public Clan(int clanId)
{
_clanId = clanId;
// Synerge - Initialize the clan stats module
// _stats = new ClanStats(this);
InitializePrivs();
restoreCWH();
}
public void restoreCWH()
{
_warehouse = new ClanWarehouse(this);
_warehouse.restore();
}
public int getClanId()
{
return _clanId;
}
public int getLeaderId()
{
return getLeaderId(SUBUNIT_MAIN_CLAN);
}
public UnitMember getLeader()
{
return getLeader(SUBUNIT_MAIN_CLAN);
}
public String getLeaderName()
{
return getLeaderName(SUBUNIT_MAIN_CLAN);
}
public String getName()
{
return getUnitName(SUBUNIT_MAIN_CLAN);
}
public void setExpelledMemberTime(long time)
{
_expelledMemberTime = time;
}
public long getExpelledMemberTime()
{
return _expelledMemberTime;
}
public void setExpelledMember()
{
_expelledMemberTime = System.currentTimeMillis();
updateClanInDB();
}
public void setLeavedAllyTime(long time)
{
_leavedAllyTime = time;
}
public long getLeavedAllyTime()
{
return _leavedAllyTime;
}
public void setLeavedAlly()
{
_leavedAllyTime = System.currentTimeMillis();
updateClanInDB();
}
public void setDissolvedAllyTime(long time)
{
_dissolvedAllyTime = time;
}
public long getDissolvedAllyTime()
{
return _dissolvedAllyTime;
}
public void setDissolvedAlly()
{
_dissolvedAllyTime = System.currentTimeMillis();
updateClanInDB();
}
public UnitMember getAnyMember(int id)
{
for (SubUnit unit : getAllSubUnits())
{
UnitMember m = unit.getUnitMember(id);
if (m != null)
{
return m;
}
}
return null;
}
public UnitMember getAnyMember(String name)
{
for (SubUnit unit : getAllSubUnits())
{
UnitMember m = unit.getUnitMember(name);
if (m != null)
{
return m;
}
}
return null;
}
public int getAllSize()
{
int size = 0;
for (SubUnit unit : getAllSubUnits())
{
size += unit.size();
}
return size;
}
public String getUnitName(int unitType)
{
if (unitType == SUBUNIT_NONE || !_subUnits.containsKey(unitType))
{
return StringUtils.EMPTY;
}
return getSubUnit(unitType).getName();
}
public String getLeaderName(int unitType)
{
if (unitType == SUBUNIT_NONE || !_subUnits.containsKey(unitType))
{
return StringUtils.EMPTY;
}
return getSubUnit(unitType).getLeaderName();
}
public int getLeaderId(int unitType)
{
if (unitType == SUBUNIT_NONE || !_subUnits.containsKey(unitType))
{
return 0;
}
return getSubUnit(unitType).getLeaderObjectId();
}
public UnitMember getLeader(int unitType)
{
if (unitType == SUBUNIT_NONE || !_subUnits.containsKey(unitType))
{
return null;
}
return getSubUnit(unitType).getLeader();
}
public void flush()
{
for (UnitMember member : this)
removeClanMember(member.getObjectId());
_warehouse.writeLock();
try
{
for (ItemInstance item : _warehouse.getItems())
_warehouse.destroyItem(item, "Flush");
}
finally
{
_warehouse.writeUnlock();
}
if (_hasCastle != 0)
ResidenceHolder.getInstance().getResidence(Castle.class, _hasCastle).changeOwner(null);
if (_hasFortress != 0)
ResidenceHolder.getInstance().getResidence(Fortress.class, _hasFortress).changeOwner(null);
}
public void removeClanMember(int id)
{
if (id == getLeaderId(SUBUNIT_MAIN_CLAN))
{
return;
}
for (SubUnit unit : getAllSubUnits())
{
if (unit.isUnitMember(id))
{
removeClanMember(unit.getType(), id);
break;
}
}
}
public void removeClanMember(int subUnitId, int objectId)
{
SubUnit subUnit = getSubUnit(subUnitId);
if (subUnit == null)
return;
subUnit.removeUnitMember(objectId);
}
public List<UnitMember> getAllMembers()
{
Collection<SubUnit> units = getAllSubUnits();
int size = 0;
for (SubUnit unit : units)
{
size += unit.size();
}
List<UnitMember> members = new ArrayList<UnitMember>(size);
for (SubUnit unit : units)
{
members.addAll(unit.getUnitMembers());
}
return members;
}
public List<Player> getOnlineMembers(int exclude)
{
if (getAllSize() == 0)
return new ArrayList<Player>();
final List<Player> result = new ArrayList<Player>(getAllSize() - 1);
for (final UnitMember temp : this)
if (temp != null && temp.isOnline() && temp.getObjectId() != exclude)
result.add(temp.getPlayer());
return result;
}
public List<Player> getOnlineMembers()
{
final List<Player> result = new ArrayList<Player>();
for (final UnitMember temp : this)
if (temp != null && temp.isOnline())
result.add(temp.getPlayer());
return result;
}
public int getAllyId()
{
return _allyId;
}
public int getLevel()
{
return _level;
}
/**
* Returns castle owned clan
* @return ID castle
*/
public int getCastle()
{
return _hasCastle;
}
/**
* Returns the strength, which is owned by the clan
* @return ID fortress
*/
public int getHasFortress()
{
return _hasFortress;
}
/**
* Returns clan hall owned by a clan
* @return ID clan hall
*/
public int getHasHideout()
{
return _hasHideout;
}
public int getResidenceId(ResidenceType r)
{
switch (r)
{
case Castle:
return _hasCastle;
case Fortress:
return _hasFortress;
case ClanHall:
return _hasHideout;
default:
return 0;
}
}
public void setAllyId(int allyId)
{
_allyId = allyId;
}
/**
* Sets the lock, which is owned by the clan. <BR>
* At the same time, and hold a castle and fortress can not be
* @param castle
*/
public void setHasCastle(int castle)
{
if (_hasFortress == 0)
_hasCastle = castle;
}
/**
* Sets the fortress, which is owned by the clan. <BR>
* At the same time possess a fortress and castle can not be
* @param fortress
*/
public void setHasFortress(int fortress)
{
if (_hasCastle == 0)
_hasFortress = fortress;
}
public void setHasHideout(int hasHideout)
{
_hasHideout = hasHideout;
}
public void setLevel(int level)
{
_level = level;
// if (_level <= 1)
// ClanRequest.updateList();
}
public boolean isAnyMember(int id)
{
for (SubUnit unit : getAllSubUnits())
{
if (unit.isUnitMember(id))
{
return true;
}
}
return false;
}
public void updateClanInDB()
{
if (getLeaderId() == 0)
{
_log.warn("updateClanInDB with empty LeaderId");
Thread.dumpStack();
return;
}
if (getClanId() == 0)
{
_log.warn("updateClanInDB with empty ClanId");
Thread.dumpStack();
return;
}
Connection con = null;
PreparedStatement statement = null;
try
{
con = DatabaseFactory.getInstance().getConnection();
statement = con.prepareStatement("UPDATE clan_data SET ally_id=?,reputation_score=?,expelled_member=?,leaved_ally=?,dissolved_ally=?,clan_level=?,warehouse=?,airship=? WHERE clan_id=?");
statement.setInt(1, getAllyId());
statement.setInt(2, getReputationScore());
statement.setLong(3, getExpelledMemberTime() / 1000);
statement.setLong(4, getLeavedAllyTime() / 1000);
statement.setLong(5, getDissolvedAllyTime() / 1000);
statement.setInt(6, _level);
statement.setInt(7, getWhBonus());
statement.setInt(8, isHaveAirshipLicense() ? getAirshipFuel() : -1);
statement.setInt(9, getClanId());
statement.execute();
// Synerge - Save all clan stats to the database
// getStats().updateClanStatsToDB();
}
catch (SQLException e)
{
_log.warn("error while updating clan '" + _clanId + "' data in db", e);
}
finally
{
DbUtils.closeQuietly(con, statement);
}
}
public void store()
{
Connection con = null;
PreparedStatement statement = null;
try
{
con = DatabaseFactory.getInstance().getConnection();
statement = con.prepareStatement("INSERT INTO clan_data (clan_id,clan_level,hasCastle,hasFortress,hasHideout,ally_id,expelled_member,leaved_ally,dissolved_ally,airship) values (?,?,?,?,?,?,?,?,?,?)");
statement.setInt(1, _clanId);
statement.setInt(2, _level);
statement.setInt(3, _hasCastle);
statement.setInt(4, _hasFortress);
statement.setInt(5, _hasHideout);
statement.setInt(6, _allyId);
statement.setLong(7, getExpelledMemberTime() / 1000);
statement.setLong(8, getLeavedAllyTime() / 1000);
statement.setLong(9, getDissolvedAllyTime() / 1000);
statement.setInt(10, isHaveAirshipLicense() ? getAirshipFuel() : -1);
statement.execute();
DbUtils.close(statement);
SubUnit mainSubUnit = _subUnits.get(SUBUNIT_MAIN_CLAN);
statement = con.prepareStatement("INSERT INTO clan_subpledges (clan_id, type, leader_id, name) VALUES (?,?,?,?)");
statement.setInt(1, _clanId);
statement.setInt(2, mainSubUnit.getType());
statement.setInt(3, mainSubUnit.getLeaderObjectId());
statement.setString(4, mainSubUnit.getName());
statement.execute();
DbUtils.close(statement);
statement = con.prepareStatement("UPDATE characters SET clanid=?,pledge_type=? WHERE obj_Id=?");
statement.setInt(1, getClanId());
statement.setInt(2, mainSubUnit.getType());
statement.setInt(3, getLeaderId());
statement.execute();
}
catch (SQLException e)
{
_log.warn("Exception while storing Clan", e);
}
finally
{
DbUtils.closeQuietly(con, statement);
}
}
public static Clan restore(int clanId)
{
if (clanId == 0) // no clan
return null;
Clan clan = null;
Connection con1 = null;
PreparedStatement statement1 = null;
ResultSet clanData = null;
try
{
con1 = DatabaseFactory.getInstance().getConnection();
statement1 = con1.prepareStatement("SELECT clan_level,hasCastle,hasFortress,hasHideout,ally_id,reputation_score,expelled_member,leaved_ally,dissolved_ally,warehouse,airship FROM clan_data where clan_id=?");
statement1.setInt(1, clanId);
clanData = statement1.executeQuery();
if (clanData.next())
{
clan = new Clan(clanId);
clan.setLevel(clanData.getInt("clan_level"));
clan.setHasCastle(clanData.getInt("hasCastle"));
clan.setHasFortress(clanData.getInt("hasFortress"));
clan.setHasHideout(clanData.getInt("hasHideout"));
clan.setAllyId(clanData.getInt("ally_id"));
clan._reputation = clanData.getInt("reputation_score");
clan.setExpelledMemberTime(clanData.getLong("expelled_member") * 1000L);
clan.setLeavedAllyTime(clanData.getLong("leaved_ally") * 1000L);
clan.setDissolvedAllyTime(clanData.getLong("dissolved_ally") * 1000L);
clan.setWhBonus(clanData.getInt("warehouse"));
clan.setAirshipLicense(clanData.getInt("airship") != -1);
if (clan.isHaveAirshipLicense())
clan.setAirshipFuel(clanData.getInt("airship"));
}
else
{
_log.warn("Clan " + clanId + " doesnt exists!");
return null;
}
}
catch (SQLException e)
{
_log.error("Error while restoring clan!", e);
}
finally
{
DbUtils.closeQuietly(con1, statement1, clanData);
}
if (clan == null)
{
_log.warn("Clan " + clanId + " does't exist");
return null;
}
clan.restoreSkills();
clan.restoreSubPledges();
clan.restoreClanRecruitment();
for (SubUnit unit : clan.getAllSubUnits())
{
unit.restore();
unit.restoreSkills();
}
clan.restoreRankPrivs();
clan.setCrestId(CrestCache.getInstance().getPledgeCrestId(clanId));
clan.setCrestLargeId(CrestCache.getInstance().getPledgeCrestLargeId(clanId));
// Synerge - Restore all clan stats from the database
// clan.getStats().restoreClanStats();
return clan;
}
public void broadcastToOnlineMembers(IStaticPacket... packets)
{
for (UnitMember member : this)
if (member.isOnline())
member.getPlayer().sendPacket(packets);
}
public void broadcastToOnlineMembers(L2GameServerPacket... packets)
{
for (UnitMember member : this)
if (member.isOnline())
member.getPlayer().sendPacket(packets);
}
public void broadcastToOtherOnlineMembers(L2GameServerPacket packet, Player player)
{
for (UnitMember member : this)
if (member.isOnline() && member.getPlayer() != player)
member.getPlayer().sendPacket(packet);
}
@Override
public String toString()
{
return getName();
}
public void setCrestId(int newcrest)
{
_crestId = newcrest;
}
public int getCrestId()
{
return _crestId;
}
public boolean hasCrest()
{
return _crestId > 0;
}
public int getCrestLargeId()
{
return _crestLargeId;
}
public void setCrestLargeId(int newcrest)
{
_crestLargeId = newcrest;
}
public boolean hasCrestLarge()
{
return _crestLargeId > 0;
}
public long getAdenaCount()
{
return _warehouse.getCountOfAdena();
}
public ClanWarehouse getWarehouse()
{
return _warehouse;
}
public int isAtWar()
{
if (_atWarWith != null && !_atWarWith.isEmpty())
return 1;
return 0;
}
public int isAtWarOrUnderAttack()
{
if (_atWarWith != null && !_atWarWith.isEmpty() || _underAttackFrom != null && !_underAttackFrom.isEmpty())
return 1;
return 0;
}
public boolean isAtWarWith(int id)
{
Clan clan = ClanTable.getInstance().getClan(id);
if (_atWarWith != null && !_atWarWith.isEmpty())
if (_atWarWith.contains(clan))
return true;
return false;
}
public boolean isUnderAttackFrom(int id)
{
Clan clan = ClanTable.getInstance().getClan(id);
if (_underAttackFrom != null && !_underAttackFrom.isEmpty())
if (_underAttackFrom.contains(clan))
return true;
return false;
}
public void setEnemyClan(Clan clan)
{
_atWarWith.add(clan);
}
public void deleteEnemyClan(Clan clan)
{
_atWarWith.remove(clan);
}
// clans that are attacking this clan
public void setAttackerClan(Clan clan)
{
_underAttackFrom.add(clan);
}
public void deleteAttackerClan(Clan clan)
{
_underAttackFrom.remove(clan);
}
public List<Clan> getEnemyClans()
{
return _atWarWith;
}
public int getWarsCount()
{
return _atWarWith.size();
}
public List<Clan> getAttackerClans()
{
return _underAttackFrom;
}
public void broadcastClanStatus(boolean updateList, boolean needUserInfo, boolean relation)
{
List<L2GameServerPacket> listAll = updateList ? listAll() : null;
PledgeShowInfoUpdate update = new PledgeShowInfoUpdate(this);
for (UnitMember member : this)
if (member.isOnline())
{
if (updateList)
{
member.getPlayer().sendPacket(PledgeShowMemberListDeleteAll.STATIC);
member.getPlayer().sendPacket(listAll);
}
member.getPlayer().sendPacket(update);
if (needUserInfo)
member.getPlayer().broadcastCharInfo();
if (relation)
member.getPlayer().broadcastRelationChanged();
}
}
public Alliance getAlliance()
{
return _allyId == 0 ? null : ClanTable.getInstance().getAlliance(_allyId);
}
public boolean canInvite()
{
return System.currentTimeMillis() - _expelledMemberTime >= EXPELLED_MEMBER_PENALTY;
}
public boolean canJoinAlly()
{
return System.currentTimeMillis() - _leavedAllyTime >= LEAVED_ALLY_PENALTY;
}
public boolean canCreateAlly()
{
return System.currentTimeMillis() - _dissolvedAllyTime >= DISSOLVED_ALLY_PENALTY;
}
public int getRank()
{
Clan[] clans = ClanTable.getInstance().getClans();
Arrays.sort(clans, REPUTATION_COMPARATOR);
int place = 1;
for (int i = 0; i < clans.length; i++)
{
if (i == REPUTATION_PLACES)
return 0;
Clan clan = clans[i];
if (clan == this)
return place + i;
}
return 0;
}
public int getReputationScore()
{
return _reputation;
}
private void setReputationScore(int rep)
{
if (_reputation >= 0 && rep < 0)
{
broadcastToOnlineMembers(Msg.SINCE_THE_CLAN_REPUTATION_SCORE_HAS_DROPPED_TO_0_OR_LOWER_YOUR_CLAN_SKILLS_WILL_BE_DE_ACTIVATED);
for (UnitMember member : this)
if (member.isOnline() && member.getPlayer() != null)
disableSkills(member.getPlayer());
}
else if (_reputation < 0 && rep >= 0)
{
broadcastToOnlineMembers(Msg.THE_CLAN_SKILL_WILL_BE_ACTIVATED_BECAUSE_THE_CLANS_REPUTATION_SCORE_HAS_REACHED_TO_0_OR_HIGHER);
for (UnitMember member : this)
if (member.isOnline() && member.getPlayer() != null)
enableSkills(member.getPlayer());
}
if (_reputation != rep)
{
_reputation = rep;
broadcastToOnlineMembers(new PledgeShowInfoUpdate(this));
}
updateClanInDB();
}
public int incReputation(int inc, boolean rate, String source)
{
if (_level < 5)
return 0;
if (rate && Math.abs(inc) <= Config.RATE_CLAN_REP_SCORE_MAX_AFFECTED)
inc = (int) Math.round(inc * Config.RATE_CLAN_REP_SCORE);
setReputationScore(_reputation + inc);
Log.add(getName() + "|" + inc + "|" + _reputation + "|" + source, "clan_reputation");
// Synerge - Add the new reputation to the stats
// if (inc > 0)
// getStats().addClanStats(Ranking.STAT_TOP_CLAN_FAME, inc);
return inc;
}
public int incReputation(int inc)
{
if (_level < 5)
return 0;
setReputationScore(_reputation + inc);
// Synerge - Add the new reputation to the stats
// if (inc > 0)
// getStats().addClanStats(Ranking.STAT_TOP_CLAN_FAME, inc);
return inc;
}
/* ============================ clan skills stuff ============================ */
private void restoreSkills()
{
Connection con = null;
PreparedStatement statement = null;
ResultSet rset = null;
try
{
// Retrieve all skills of this L2Player from the database
con = DatabaseFactory.getInstance().getConnection();
statement = con.prepareStatement("SELECT skill_id,skill_level FROM clan_skills WHERE clan_id=?");
statement.setInt(1, getClanId());
rset = statement.executeQuery();
// Go though the recordset of this SQL query
while (rset.next())
{
int id = rset.getInt("skill_id");
int level = rset.getInt("skill_level");
// Create a L2Skill object for each record
Skill skill = SkillTable.getInstance().getInfo(id, level);
// Add the L2Skill object to the L2Clan _skills
_skills.put(skill.getId(), skill);
}
}
catch (SQLException e)
{
_log.warn("Could not restore clan skills: ", e);
}
finally
{
DbUtils.closeQuietly(con, statement, rset);
}
}
public Collection<Skill> getSkills()
{
return _skills.values();
}
/**
* used to retrieve all skills
* @return
*/
public final Skill[] getAllSkills()
{
if (_reputation < 0)
return Skill.EMPTY_ARRAY;
return _skills.values().toArray(new Skill[_skills.values().size()]);
}
/**
* used to add a new skill to the list, send a packet to all online clan members, update their stats and store it in db
* @param newSkill
* @param store
* @return
*/
public Skill addSkill(Skill newSkill, boolean store)
{
Skill oldSkill = null;
if (newSkill != null)
{
// Replace oldSkill by newSkill or Add the newSkill
oldSkill = _skills.put(newSkill.getId(), newSkill);
if (store)
{
Connection con = null;
PreparedStatement statement = null;
try
{
con = DatabaseFactory.getInstance().getConnection();
if (oldSkill != null)
{
statement = con.prepareStatement("UPDATE clan_skills SET skill_level=? WHERE skill_id=? AND clan_id=?");
statement.setInt(1, newSkill.getLevel());
statement.setInt(2, oldSkill.getId());
statement.setInt(3, getClanId());
statement.execute();
}
else
{
statement = con.prepareStatement("INSERT INTO clan_skills (clan_id,skill_id,skill_level) VALUES (?,?,?)");
statement.setInt(1, getClanId());
statement.setInt(2, newSkill.getId());
statement.setInt(3, newSkill.getLevel());
statement.execute();
}
}
catch (SQLException e)
{
_log.warn("Error could not store char skills: ", e);
}
finally
{
DbUtils.closeQuietly(con, statement);
}
}
PledgeSkillListAdd p = new PledgeSkillListAdd(newSkill.getId(), newSkill.getLevel());
PledgeSkillList p2 = new PledgeSkillList(this);
for (UnitMember temp : this)
{
if (temp.isOnline())
{
Player player = temp.getPlayer();
if (player != null)
{
addSkill(player, newSkill);
player.sendPacket(p, p2, new SkillList(player));
}
}
}
}
return oldSkill;
}
public void addSkillsQuietly(Player player)
{
for (Skill skill : _skills.values())
addSkill(player, skill);
final SubUnit subUnit = getSubUnit(player.getPledgeType());
if (subUnit != null)
subUnit.addSkillsQuietly(player);
}
public void enableSkills(Player player)
{
if (player.isInOlympiadMode()) // do not allow clan skills on Olympiad
return;
for (Skill skill : _skills.values())
if (skill.getMinPledgeClass() <= player.getPledgeClass())
player.removeUnActiveSkill(skill);
final SubUnit subUnit = getSubUnit(player.getPledgeType());
if (subUnit != null)
subUnit.enableSkills(player);
}
public void disableSkills(Player player)
{
for (Skill skill : _skills.values())
player.addUnActiveSkill(skill);
final SubUnit subUnit = getSubUnit(player.getPledgeType());
if (subUnit != null)
subUnit.disableSkills(player);
}
private void addSkill(Player player, Skill skill)
{
if (skill.getMinPledgeClass() <= player.getPledgeClass())
{
player.addSkill(skill, false);
if (_reputation < 0 || player.isInOlympiadMode())
player.addUnActiveSkill(skill);
}
}
/**
* Removes the clan skill, without removing it from the base. Used to remove the skills residences. After removing the skill (s) to be sent out boarcastSkillListToOnlineMembers ()
* @param skill
*/
public void removeSkill(int skill)
{
_skills.remove(skill);
PledgeSkillListAdd p = new PledgeSkillListAdd(skill, 0);
for (UnitMember temp : this)
{
Player player = temp.getPlayer();
if (player != null && player.isOnline())
{
player.removeSkillById(skill);
player.sendPacket(p, new SkillList(player));
}
}
}
public void broadcastSkillListToOnlineMembers()
{
for (UnitMember temp : this)
{
Player player = temp.getPlayer();
if (player != null && player.isOnline())
{
player.sendPacket(new PledgeSkillList(this));
player.sendPacket(new SkillList(player));
}
}
}
/* ============================ clan subpledges stuff ============================ */
public static boolean isAcademy(int pledgeType)
{
return pledgeType == SUBUNIT_ACADEMY;
}
public static boolean isRoyalGuard(int pledgeType)
{
return pledgeType == SUBUNIT_ROYAL1 || pledgeType == SUBUNIT_ROYAL2;
}
public static boolean isOrderOfKnights(int pledgeType)
{
return pledgeType == SUBUNIT_KNIGHT1 || pledgeType == SUBUNIT_KNIGHT2 || pledgeType == SUBUNIT_KNIGHT3 || pledgeType == SUBUNIT_KNIGHT4;
}
public static int getAffiliationRank(int pledgeType)
{
if (isAcademy(pledgeType))
return 9;
else if (isOrderOfKnights(pledgeType))
return 8;
else if (isRoyalGuard(pledgeType))
return 7;
else
return 6;
}
public void restartMembers()
{
for (SubUnit unit : _subUnits.values())
unit.restartMembers();
}
public final SubUnit getSubUnit(int pledgeType)
{
return _subUnits.get(pledgeType);
}
public final void addSubUnit(SubUnit sp, boolean updateDb)
{
_subUnits.put(sp.getType(), sp);
if (updateDb)
{
broadcastToOnlineMembers(new PledgeReceiveSubPledgeCreated(sp));
Connection con = null;
PreparedStatement statement = null;
try
{
con = DatabaseFactory.getInstance().getConnection();
statement = con.prepareStatement("INSERT INTO `clan_subpledges` (clan_id,type,leader_id,name) VALUES (?,?,?,?)");
statement.setInt(1, getClanId());
statement.setInt(2, sp.getType());
statement.setInt(3, sp.getLeaderObjectId());
statement.setString(4, sp.getName());
statement.execute();
}
catch (SQLException e)
{
_log.warn("Could not store clan Sub pledges: ", e);
}
finally
{
DbUtils.closeQuietly(con, statement);
}
}
}
public int createSubPledge(Player player, int pledgeType, UnitMember leader, String name)
{
int temp = pledgeType;
pledgeType = getAvailablePledgeTypes(pledgeType);
if (pledgeType == SUBUNIT_NONE)
{
if (temp == SUBUNIT_ACADEMY)
player.sendPacket(Msg.YOUR_CLAN_HAS_ALREADY_ESTABLISHED_A_CLAN_ACADEMY);
else
player.sendMessage("You can't create any more sub-units of this type");
return SUBUNIT_NONE;
}
switch (pledgeType)
{
case SUBUNIT_ACADEMY:
break;
case SUBUNIT_ROYAL1:
case SUBUNIT_ROYAL2:
if (getReputationScore() < 5000)
{
player.sendPacket(Msg.THE_CLAN_REPUTATION_SCORE_IS_TOO_LOW);
return SUBUNIT_NONE;
}
incReputation(-5000, false, "SubunitCreate");
break;
case SUBUNIT_KNIGHT1:
case SUBUNIT_KNIGHT2:
case SUBUNIT_KNIGHT3:
case SUBUNIT_KNIGHT4:
if (getReputationScore() < 10000)
{
player.sendPacket(Msg.THE_CLAN_REPUTATION_SCORE_IS_TOO_LOW);
return SUBUNIT_NONE;
}
incReputation(-10000, false, "SubunitCreate");
break;
}
addSubUnit(new SubUnit(this, pledgeType, leader, name), true);
return pledgeType;
}
public int getAvailablePledgeTypes(int pledgeType)
{
if (pledgeType == SUBUNIT_MAIN_CLAN)
return SUBUNIT_NONE;
if (_subUnits.get(pledgeType) != null)
switch (pledgeType)
{
case SUBUNIT_ACADEMY:
return SUBUNIT_NONE;
case SUBUNIT_ROYAL1:
pledgeType = getAvailablePledgeTypes(SUBUNIT_ROYAL2);
break;
case SUBUNIT_ROYAL2:
return SUBUNIT_NONE;
case SUBUNIT_KNIGHT1:
pledgeType = getAvailablePledgeTypes(SUBUNIT_KNIGHT2);
break;
case SUBUNIT_KNIGHT2:
pledgeType = getAvailablePledgeTypes(SUBUNIT_KNIGHT3);
break;
case SUBUNIT_KNIGHT3:
pledgeType = getAvailablePledgeTypes(SUBUNIT_KNIGHT4);
break;
case SUBUNIT_KNIGHT4:
return SUBUNIT_NONE;
}
return pledgeType;
}
private void restoreSubPledges()
{
Connection con = null;
PreparedStatement statement = null;
ResultSet rset = null;
try
{
con = DatabaseFactory.getInstance().getConnection();
statement = con.prepareStatement("SELECT * FROM clan_subpledges WHERE clan_id=?");
statement.setInt(1, getClanId());
rset = statement.executeQuery();
// Go though the recordset of this SQL query
while (rset.next())
{
int type = rset.getInt("type");
int leaderId = rset.getInt("leader_id");
String name = rset.getString("name");
SubUnit pledge = new SubUnit(this, type, leaderId, name);
addSubUnit(pledge, false);
}
}
catch (SQLException e)
{
_log.warn("Could not restore clan SubPledges", e);
}
finally
{
DbUtils.closeQuietly(con, statement, rset);
}
}
public int getSubPledgeLimit(int pledgeType)
{
int limit;
switch (_level)
{
case 0:
limit = 10;
break;
case 1:
limit = 15;
break;
case 2:
limit = 20;
break;
case 3:
limit = 30;
break;
default:
limit = 40;
break;
}
switch (pledgeType)
{
case SUBUNIT_ACADEMY:
case SUBUNIT_ROYAL1:
case SUBUNIT_ROYAL2:
if (getLevel() >= 11)
limit = 30;
else
limit = 20;
break;
case SUBUNIT_KNIGHT1:
case SUBUNIT_KNIGHT2:
if (getLevel() >= 9)
limit = 25;
else
limit = 10;
break;
case SUBUNIT_KNIGHT3:
case SUBUNIT_KNIGHT4:
if (getLevel() >= 10)
limit = 25;
else
limit = 10;
break;
}
return limit;
}
public int getUnitMembersSize(int pledgeType)
{
if (pledgeType == Clan.SUBUNIT_NONE || !_subUnits.containsKey(pledgeType))
{
return 0;
}
return getSubUnit(pledgeType).size();
}
public void addMember(Player player, int pledgeType)
{
player.sendPacket(new JoinPledge(getClanId()));
SubUnit subUnit = getSubUnit(pledgeType);
if (subUnit == null)
return;
UnitMember member = new UnitMember(this, player.getName(), player.getTitle(), player.getLevel(), player.getClassId().getId(), player.getObjectId(), pledgeType, player.getPowerGrade(), player.getApprentice(), player.getSex(), Clan.SUBUNIT_NONE);
subUnit.addUnitMember(member);
player.setPledgeType(pledgeType);
player.setClan(this);
member.setPlayerInstance(player, false);
if (pledgeType == Clan.SUBUNIT_ACADEMY)
player.setLvlJoinedAcademy(player.getLevel());
member.setPowerGrade(getAffiliationRank(player.getPledgeType()));
broadcastToOtherOnlineMembers(new PledgeShowMemberListAdd(member), player);
broadcastToOnlineMembers(new SystemMessage2(SystemMsg.S1_HAS_JOINED_THE_CLAN).addString(player.getName()), new PledgeShowInfoUpdate(this));
// this activates the clan tab on the new member
player.sendPacket(SystemMsg.ENTERED_THE_CLAN);
player.sendPacket(player.getClan().listAll());
player.updatePledgeClass();
addSkillsQuietly(player);
player.sendPacket(new PledgeSkillList(this));
player.sendPacket(new SkillList(player));
EventHolder.getInstance().findEvent(player);
if (getWarDominion() > 0)
{
DominionSiegeEvent siegeEvent = player.getEvent(DominionSiegeEvent.class);
siegeEvent.updatePlayer(player, true);
}
else
player.broadcastCharInfo();
player.store(false);
// Synerge - Update the clan stats with the new total member count
// getStats().addClanStats(Ranking.STAT_TOP_CLAN_MEMBERS_COUNT, getAllSize());
// Synerge - Add a new recruited member to the stats
// getStats().addClanStats(Ranking.STAT_TOP_CLAN_MEMBERS_RECRUITED);
}
/* Recruiting members */
private void restoreClanRecruitment()
{
try (Connection con = DatabaseFactory.getInstance().getConnection())
{
try (PreparedStatement statement = con.prepareStatement("SELECT * FROM clan_requiements where clan_id=" + getClanId());
ResultSet rset = statement.executeQuery())
{
while (rset.next())
{
_recruting = (rset.getInt("recruting") == 1 ? true : false);
for (String clas : rset.getString("classes").split(","))
if (clas.length() > 0)
_classesNeeded.add(Integer.parseInt(clas));
for (int i = 1; i <= 8; i++)
_questions[(i - 1)] = rset.getString("question" + i);
}
}
try (PreparedStatement statement = con.prepareStatement("SELECT * FROM clan_petitions where clan_id=" + getClanId());
ResultSet rset = statement.executeQuery())
{
while (rset.next())
{
String[] answers = new String[8];
for (int i = 1; i <= 8; i++)
answers[(i - 1)] = rset.getString("answer" + i);
_petitions.add(new SinglePetition(rset.getInt("sender_id"), answers, rset.getString("comment")));
}
}
}
catch (NumberFormatException | SQLException e)
{
_log.error("Error while restoring Clan Recruitment", e);
}
}
public void updateRecrutationData()
{
try (Connection con = DatabaseFactory.getInstance().getConnection())
{
try (PreparedStatement statement = con.prepareStatement("INSERT INTO clan_requiements VALUES(" + getClanId() + ",0,'','','','','','','','','') ON DUPLICATE KEY UPDATE recruting=?,classes=?,question1=?,question2=?,question3=?,question4=?,question5=?,question6=?,question7=?,question8=?"))
{
statement.setInt(1, (_recruting == true ? 1 : 0));
statement.setString(2, getClassesForData());
for (int i = 0; i < 8; i++)
statement.setString(i + 3, _questions[i] == null ? "" : _questions[i]);
statement.execute();
}
try (PreparedStatement statement = con.prepareStatement("DELETE FROM clan_petitions WHERE clan_id=" + getClanId()))
{
statement.execute();
}
for (SinglePetition petition : getPetitions())
{
try (PreparedStatement statement = con.prepareStatement("INSERT IGNORE INTO clan_petitions VALUES(?,?,?,?,?,?,?,?,?,?,?)"))
{
statement.setInt(1, petition.getSenderId());
statement.setInt(2, getClanId());
for (int i = 0; i < 8; i++)
statement.setString(i + 3, petition.getAnswers()[i] == null ? "" : petition.getAnswers()[i]);
statement.setString(11, petition.getComment());
statement.execute();
}
}
}
catch (SQLException e)
{
_log.warn("Error while updating clan recruitment system on clan id '" + _clanId + "' in db", e);
}
}
public void setQuestions(String[] questions)
{
_questions = questions;
}
public class SinglePetition
{
int _sender;
String[] _answers;
String _comment;
private SinglePetition(int sender, String[] answers, String comment)
{
_sender = sender;
_answers = answers;
_comment = comment;
}
public int getSenderId()
{
return _sender;
}
public String[] getAnswers()
{
return _answers;
}
public String getComment()
{
return _comment;
}
}
public synchronized boolean addPetition(int senderId, String[] answers, String comment)
{
if (getPetition(senderId) != null)
return false;
_petitions.add(new SinglePetition(senderId, answers, comment));
updateRecrutationData();
if (World.getPlayer(getLeaderId()) != null)
World.getPlayer(getLeaderId()).sendMessage("New Clan Petition has arrived!");
return true;
}
public SinglePetition getPetition(int senderId)
{
return _petitions.stream().filter(petition -> petition.getSenderId() == senderId).findAny().orElse(null);
}
public ArrayList<SinglePetition> getPetitions()
{
return _petitions;
}
public synchronized void deletePetition(int senderId)
{
SinglePetition petition = _petitions.stream().filter(p -> p.getSenderId() == senderId).findAny().orElse(null);
if (petition != null)
{
_petitions.remove(petition);
updateRecrutationData();
}
}
public void deletePetition(SinglePetition petition)
{
_petitions.remove(petition);
updateRecrutationData();
}
public void setRecrutating(boolean b)
{
_recruting = b;
}
public void addClassNeeded(int clas)
{
_classesNeeded.add(clas);
}
public void deleteClassNeeded(int clas) // iti arat cum o generez? neahm, ca cred ca stiu care-i baiu :)
{
int indexOfClass = _classesNeeded.indexOf(clas);
if (indexOfClass != -1)
_classesNeeded.remove(indexOfClass);
else
_log.warn("Tried removing inexistent class: " + clas);
}
public String getClassesForData()
{
String text = "";
for (int i = 0; i < getClassesNeeded().size(); i++)
{
if (i != 0)
text += ",";
text += getClassesNeeded().get(i);
}
return text;
}
public ArrayList<Integer> getClassesNeeded()
{
return _classesNeeded;
}
public boolean isRecruting()
{
return _recruting;
}
public String[] getQuestions()
{
return _questions;
}
/* ============================ clan privilege ranks stuff ============================ */
private void restoreRankPrivs()
{
if (_privs == null)
InitializePrivs();
Connection con = null;
PreparedStatement statement = null;
ResultSet rset = null;
try
{
// Retrieve all skills of this L2Player from the database
con = DatabaseFactory.getInstance().getConnection();
statement = con.prepareStatement("SELECT privilleges,rank FROM clan_privs WHERE clan_id=?");
statement.setInt(1, getClanId());
rset = statement.executeQuery();
// Go though the recordset of this SQL query
while (rset.next())
{
int rank = rset.getInt("rank");
// int party = rset.getInt("party"); - unused?
int privileges = rset.getInt("privilleges");
// noinspection ConstantConditions
RankPrivs p = _privs.get(rank);
if (p != null)
p.setPrivs(privileges);
else
_log.warn("Invalid rank value (" + rank + "), please check clan_privs table");
}
}
catch (SQLException e)
{
_log.warn("Could not restore clan privs by rank: ", e);
}
finally
{
DbUtils.closeQuietly(con, statement, rset);
}
}
public void InitializePrivs()
{
for (int i = RANK_FIRST; i <= RANK_LAST; i++)
_privs.put(i, new RankPrivs(i, 0, CP_NOTHING));
}
public void updatePrivsForRank(int rank)
{
for (UnitMember member : this)
if (member.isOnline() && member.getPlayer() != null && member.getPlayer().getPowerGrade() == rank)
{
if (member.getPlayer().isClanLeader())
continue;
member.getPlayer().sendUserInfo();
}
}
public RankPrivs getRankPrivs(int rank)
{
if (rank < RANK_FIRST || rank > RANK_LAST)
{
_log.warn("Requested invalid rank value: " + rank);
Thread.dumpStack();
return null;
}
if (_privs.get(rank) == null)
{
_log.warn("Request of rank before init: " + rank);
Thread.dumpStack();
setRankPrivs(rank, CP_NOTHING);
}
return _privs.get(rank);
}
public int countMembersByRank(int rank)
{
int ret = 0;
for (UnitMember m : this)
if (m.getPowerGrade() == rank)
ret++;
return ret;
}
public void setRankPrivs(int rank, int privs)
{
if (rank < RANK_FIRST || rank > RANK_LAST)
{
_log.warn("Requested set of invalid rank value: " + rank);
Thread.dumpStack();
return;
}
if (_privs.get(rank) != null)
_privs.get(rank).setPrivs(privs);
else
_privs.put(rank, new RankPrivs(rank, countMembersByRank(rank), privs));
Connection con = null;
PreparedStatement statement = null;
try
{
// _log.warn("requested store clan privs in db for rank: " + rank + ", privs: " + privs);
// Retrieve all skills of this L2Player from the database
con = DatabaseFactory.getInstance().getConnection();
statement = con.prepareStatement("REPLACE INTO clan_privs (clan_id,rank,privilleges) VALUES (?,?,?)");
statement.setInt(1, getClanId());
statement.setInt(2, rank);
statement.setInt(3, privs);
statement.execute();
}
catch (SQLException e)
{
_log.warn("Could not store clan privs for rank: ", e);
}
finally
{
DbUtils.closeQuietly(con, statement);
}
}
/**
* used to retrieve all privilege ranks
* @return
*/
public final RankPrivs[] getAllRankPrivs()
{
if (_privs == null)
return new RankPrivs[0];
return _privs.values().toArray(new RankPrivs[_privs.values().size()]);
}
private static class ClanReputationComparator implements Comparator<Clan>, Serializable
{
private static final long serialVersionUID = -240267507300918307L;
@Override
public int compare(Clan o1, Clan o2)
{
if (o1 == null || o2 == null)
return 0;
return Integer.compare(o2.getReputationScore(), o1.getReputationScore());
}
}
public int getWhBonus()
{
return _whBonus;
}
public void setWhBonus(int i)
{
if (_whBonus != -1)
mysql.set("UPDATE `clan_data` SET `warehouse`=? WHERE `clan_id`=?", i, getClanId());
_whBonus = i;
}
public void setAirshipLicense(boolean val)
{
_airshipLicense = val;
}
public boolean isHaveAirshipLicense()
{
return _airshipLicense;
}
public ClanAirShip getAirship()
{
return _airship;
}
public void setAirship(ClanAirShip airship)
{
_airship = airship;
}
public int getAirshipFuel()
{
return _airshipFuel;
}
public void setAirshipFuel(int fuel)
{
_airshipFuel = fuel;
}
public final Collection<SubUnit> getAllSubUnits()
{
return _subUnits.values();
}
public List<L2GameServerPacket> listAll()
{
List<L2GameServerPacket> p = new ArrayList<L2GameServerPacket>(_subUnits.size());
for (SubUnit unit : getAllSubUnits())
p.add(new PledgeShowMemberListAll(this, unit));
return p;
}
public String getNotice()
{
return _notice;
}
public void setNotice(String notice)
{
_notice = notice;
}
public int getSkillLevel(int id, int def)
{
Skill skill = _skills.get(id);
return skill == null ? def : skill.getLevel();
}
public int getSkillLevel(int id)
{
return getSkillLevel(id, -1);
}
public int getWarDominion()
{
return _warDominion;
}
public void setWarDominion(int warDominion)
{
_warDominion = warDominion;
}
public void setSiegeKills(int i)
{
_siegeKills = i;
}
public void incSiegeKills()
{
_siegeKills++;
}
public int getSiegeKills()
{
return _siegeKills;
}
@Override
public Iterator<UnitMember> iterator()
{
List<Iterator<UnitMember>> iterators = new ArrayList<Iterator<UnitMember>>(_subUnits.size());
for (SubUnit subUnit : _subUnits.values())
iterators.add(subUnit.getUnitMembers().iterator());
return new JoinedIterator<UnitMember>(iterators);
}
public boolean isFull()
{
for (SubUnit unit : getAllSubUnits())
if (getUnitMembersSize(unit.getType()) < getSubPledgeLimit(unit.getType()))
{
return false;
}
return true;
}
/**
* @return
*/
public int getAverageLevel()
{
int size = 0;
int level = 0;
for (SubUnit unit : getAllSubUnits())
{
for (UnitMember member : unit.getUnitMembers())
{
size++;
level += member.getLevel();
}
}
return level / size;
}
// /**
// * @param obj
// * @return
// */
// public boolean checkInviteList(int obj)
//{
// for (ClanRequest request : ClanRequest.getInviteList(getClanId()))
// {
// Player invited = request.getPlayer();
// if (invited.getObjectId() == obj)
// return true;
// }
// return false;
// }
// public List<ClanRequest> getInviteList()
// {
// return ClanRequest.getInviteList(getClanId());
// }
//
// /**
// * @return
// */
// public String getDescription()
// {
// return _description;
// }
//
// public void setDescription(String description)
// {
// _description = description;
// }
// Synerge - Clan Stats support for Server Ranking
// private final ClanStats _stats;
// public final ClanStats getStats()
// {
// return _stats;
// }
//}
}
| 24.41411 | 290 | 0.689408 |
2d1ac40fa0d8e537bb8607e0fe3dafd8489bc2c8
| 237 |
package com.foo.bar.repository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.foo.bar.entity.Employee;
public interface EmployeeRepository extends PagingAndSortingRepository<Employee, Integer> {
}
| 23.7 | 91 | 0.843882 |
83a8a0248afbb2bd3166a5eb0feb6f53035bdc1d
| 2,172 |
package nam.model.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang.StringEscapeUtils;
import org.aries.util.BaseUtil;
import nam.model.TransferMode;
public class TransferModeUtil extends BaseUtil {
public static final TransferMode[] VALUES_ARRAY = new TransferMode[] {
TransferMode.TEXT,
TransferMode.BINARY
};
public static final List<TransferMode> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));
public static TransferMode getTransferMode(int ordinal) {
if (ordinal == TransferMode.TEXT.ordinal())
return TransferMode.TEXT;
if (ordinal == TransferMode.BINARY.ordinal())
return TransferMode.BINARY;
return null;
}
public static String toString(TransferMode transferMode) {
return transferMode.name();
}
public static String toString(Collection<TransferMode> transferModeList) {
StringBuffer buf = new StringBuffer();
Iterator<TransferMode> iterator = transferModeList.iterator();
for (int i=0; iterator.hasNext(); i++) {
TransferMode transferMode = iterator.next();
if (i > 0)
buf.append(", ");
String text = toString(transferMode);
buf.append(text);
}
String text = StringEscapeUtils.escapeJavaScript(buf.toString());
return text;
}
public static void sortRecords(List<TransferMode> transferModeList) {
Collections.sort(transferModeList, createTransferModeComparator());
}
public static Collection<TransferMode> sortRecords(Collection<TransferMode> transferModeCollection) {
List<TransferMode> list = new ArrayList<TransferMode>(transferModeCollection);
Collections.sort(list, createTransferModeComparator());
return list;
}
public static Comparator<TransferMode> createTransferModeComparator() {
return new Comparator<TransferMode>() {
public int compare(TransferMode transferMode1, TransferMode transferMode2) {
String text1 = transferMode1.value();
String text2 = transferMode2.value();
int status = text1.compareTo(text2);
return status;
}
};
}
}
| 28.96 | 107 | 0.758748 |
7bd2b4c75437d58d3985a2071b7168ffeb22feaa
| 3,105 |
/*
Copyright 2013 Yen Pai ypai@reign.io
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package io.reign.examples;
import io.reign.Reign;
import io.reign.mesg.MessagingService;
import io.reign.mesg.ResponseMessage;
import io.reign.mesg.SimpleRequestMessage;
import io.reign.presence.PresenceService;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Demonstrate basic usage.
*
* @author ypai
*
*/
public class MessagingServiceExample {
private static final Logger logger = LoggerFactory.getLogger(MessagingServiceExample.class);
public static void main(String[] args) throws Exception {
/** init and start reign using builder **/
Reign reign = Reign.maker().zkClient("localhost:2181", 30000).get();
reign.start();
/** init and start using Spring convenience builder **/
// SpringReignMaker springReignMaker = new SpringReignMaker();
// springReignMaker.setZkConnectString("localhost:2181");
// springReignMaker.setZkSessionTimeout(30000);
// springReignMaker.setCore(true);
// springReignMaker.initializeAndStart();
// Reign reign = springReignMaker.get();
/** messaging example **/
messagingExample(reign);
/** sleep to allow examples to run for a bit **/
Thread.sleep(60000);
/** shutdown reign **/
reign.stop();
/** sleep a bit to observe observer callbacks **/
Thread.sleep(10000);
}
public static void messagingExample(Reign reign) throws Exception {
PresenceService presenceService = reign.getService("presence");
presenceService.announce("examples", "service1", true);
presenceService.announce("examples", "service2", true);
presenceService.waitUntilAvailable("examples", "service1", 30000);
Thread.sleep(5000);
MessagingService messagingService = reign.getService("mesg");
Map<String, ResponseMessage> responseMap = messagingService.sendMessage("examples", "service1",
new SimpleRequestMessage("presence", "/"));
logger.info("Broadcast#1: responseMap={}", responseMap);
responseMap = messagingService.sendMessage("examples", "service1", new SimpleRequestMessage("presence",
"/examples/service1"));
logger.info("Broadcast#2: responseMap={}", responseMap);
responseMap = messagingService.sendMessage("examples", "service1", new SimpleRequestMessage("presence",
"/examples"));
logger.info("Broadcast#3: responseMap={}", responseMap);
}
}
| 33.387097 | 111 | 0.688567 |
0a8111623deebd41a12b4554fcfc7e48c4ccffd2
| 824 |
package com.megait.artrade.offerprice;
import com.megait.artrade.action.Auction;
import com.megait.artrade.member.Member;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.ColumnDefault;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.*;
import java.time.LocalDateTime;
@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@DynamicInsert
@DynamicUpdate
public class OfferPrice {
@Id
@GeneratedValue
private Long id;
@OneToOne
private Member member;
private LocalDateTime offerAt;
@Column(nullable = false)
@ColumnDefault("0")
private double offerPrice;
@ManyToOne
private Auction auction;
}
| 17.531915 | 47 | 0.775485 |
d9bda7e55fbae9349798f73171eb185814533004
| 1,574 |
package com.micro.auth.service.impl;
import com.micro.auth.entity.SysUser;
import com.micro.auth.mapper.SysUserMapper;
import com.micro.auth.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class SysUserServiceImpl implements SysUserService {
@Autowired
private SysUserMapper sysUserMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
SysUser sysUser = sysUserMapper.findByName(username);
if (sysUser ==null) {
throw new UsernameNotFoundException("用户名或密码错误");
}
if (!sysUser.isEnabled()) {
throw new DisabledException("账户已被禁用");
} else if (!sysUser.isAccountNonLocked()) {
throw new LockedException("账号已被锁定");
} else if (!sysUser.isAccountNonExpired()) {
throw new AccountExpiredException("账号已过期");
} else if (!sysUser.isCredentialsNonExpired()) {
throw new CredentialsExpiredException("登录凭证已过期");
}
return sysUser;
}
}
| 39.35 | 93 | 0.753494 |
74df0725c15beacd0e56740f98a5dc9aa8324043
| 2,056 |
package net.ttddyy.dsproxy.proxy;
import net.ttddyy.dsproxy.ConnectionInfo;
import net.ttddyy.dsproxy.listener.MethodExecutionListenerUtils;
import java.lang.reflect.Method;
import java.sql.ResultSet;
/**
* Simply delegate method calls to the actual {@link ResultSet}.
*
* @author Tadaya Tsuyukubo
* @since 1.4.3
*/
public class SimpleResultSetProxyLogic implements ResultSetProxyLogic {
private ResultSet resultSet;
private ConnectionInfo connectionInfo;
private ProxyConfig proxyConfig;
public SimpleResultSetProxyLogic(ResultSet resultSet, ConnectionInfo connectionInfo, ProxyConfig proxyConfig) {
this.resultSet = resultSet;
this.connectionInfo = connectionInfo;
this.proxyConfig = proxyConfig;
}
@Override
public Object invoke(Method method, Object[] args) throws Throwable {
return MethodExecutionListenerUtils.invoke(new MethodExecutionListenerUtils.MethodExecutionCallback() {
@Override
public Object execute(Object proxyTarget, Method method, Object[] args) throws Throwable {
return performQueryExecutionListener(method, args);
}
}, this.proxyConfig, this.resultSet, this.connectionInfo, method, args);
}
private Object performQueryExecutionListener(Method method, Object[] args) throws Throwable {
final String methodName = method.getName();
// special treat for toString method
if ("toString".equals(methodName)) {
final StringBuilder sb = new StringBuilder();
sb.append(this.resultSet.getClass().getSimpleName());
sb.append(" [");
sb.append(this.resultSet.toString());
sb.append("]");
return sb.toString(); // differentiate toString message.
} else if ("getTarget".equals(methodName)) {
// ProxyJdbcObject interface has a method to return original object.
return this.resultSet;
}
return MethodUtils.proceedExecution(method, this.resultSet, args);
}
}
| 36.070175 | 115 | 0.689689 |
782c7187c95043503be581f3218d35120bf36974
| 6,479 |
/*
* 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 ia.base.metier.algorithmes;
import ia.base.metier.TypeMouvement;
import static ia.base.metier.TypeMouvement.*;
import ia.base.metier.carte.Carte;
import ia.base.metier.carte.Coordonnee;
import ia.base.metier.carte.cases.Case;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author simonetma
*/
public class DijkstraTest {
public DijkstraTest() {
}
/**
* Test of calculerDistancesDepuis method, of class Dijkstra.
*/
@Test
public void testCalculerDistancesDepuis() {
System.out.println("calculerDistancesDepuis");
Carte carte = new Carte(
"MDMEEH"
+"MMMEEA"
+"HEEEHH"
+"HAHHHE"
+"HAHEEE"
+"HHHEEE"
);
Case depart = carte.getCase(new Coordonnee(0,1));
Dijkstra instance = new Dijkstra(carte);
instance.calculerDistancesDepuis(depart);
int infini = 1+carte.getTaille()*carte.getTaille()*16;
assertEquals(new Integer(infini), instance.getDistance(carte.getCase(new Coordonnee(0,0))));
assertEquals(new Integer(0), instance.getDistance(carte.getCase(new Coordonnee(0,1))));
assertEquals(new Integer(infini), instance.getDistance(carte.getCase(new Coordonnee(0,2))));
assertEquals(new Integer(infini), instance.getDistance(carte.getCase(new Coordonnee(0,3))));
assertEquals(new Integer(infini), instance.getDistance(carte.getCase(new Coordonnee(0,4))));
assertEquals(new Integer(16), instance.getDistance(carte.getCase(new Coordonnee(0,5))));
assertEquals(new Integer(2), instance.getDistance(carte.getCase(new Coordonnee(1,0))));
assertEquals(new Integer(1), instance.getDistance(carte.getCase(new Coordonnee(1,1))));
assertEquals(new Integer(2), instance.getDistance(carte.getCase(new Coordonnee(1,2))));
assertEquals(new Integer(infini), instance.getDistance(carte.getCase(new Coordonnee(1,3))));
assertEquals(new Integer(infini), instance.getDistance(carte.getCase(new Coordonnee(1,4))));
assertEquals(new Integer(15), instance.getDistance(carte.getCase(new Coordonnee(1,5))));
assertEquals(new Integer(3), instance.getDistance(carte.getCase(new Coordonnee(2,0))));
assertEquals(new Integer(infini), instance.getDistance(carte.getCase(new Coordonnee(2,1))));
assertEquals(new Integer(infini), instance.getDistance(carte.getCase(new Coordonnee(2,2))));
assertEquals(new Integer(infini), instance.getDistance(carte.getCase(new Coordonnee(2,3))));
assertEquals(new Integer(11), instance.getDistance(carte.getCase(new Coordonnee(2,4))));
assertEquals(new Integer(12), instance.getDistance(carte.getCase(new Coordonnee(2,5))));
assertEquals(new Integer(4), instance.getDistance(carte.getCase(new Coordonnee(3,0))));
assertEquals(new Integer(7), instance.getDistance(carte.getCase(new Coordonnee(3,1))));
assertEquals(new Integer(8), instance.getDistance(carte.getCase(new Coordonnee(3,2))));
assertEquals(new Integer(9), instance.getDistance(carte.getCase(new Coordonnee(3,3))));
assertEquals(new Integer(10), instance.getDistance(carte.getCase(new Coordonnee(3,4))));
assertEquals(new Integer(infini), instance.getDistance(carte.getCase(new Coordonnee(3,5))));
assertEquals(new Integer(5), instance.getDistance(carte.getCase(new Coordonnee(4,0))));
assertEquals(new Integer(8), instance.getDistance(carte.getCase(new Coordonnee(4,1))));
assertEquals(new Integer(9), instance.getDistance(carte.getCase(new Coordonnee(4,2))));
assertEquals(new Integer(infini), instance.getDistance(carte.getCase(new Coordonnee(4,3))));
assertEquals(new Integer(infini), instance.getDistance(carte.getCase(new Coordonnee(4,4))));
assertEquals(new Integer(infini), instance.getDistance(carte.getCase(new Coordonnee(4,5))));
assertEquals(new Integer(6), instance.getDistance(carte.getCase(new Coordonnee(5,0))));
assertEquals(new Integer(7), instance.getDistance(carte.getCase(new Coordonnee(5,1))));
assertEquals(new Integer(8), instance.getDistance(carte.getCase(new Coordonnee(5,2))));
assertEquals(new Integer(infini), instance.getDistance(carte.getCase(new Coordonnee(5,3))));
assertEquals(new Integer(infini), instance.getDistance(carte.getCase(new Coordonnee(5,4))));
assertEquals(new Integer(infini), instance.getDistance(carte.getCase(new Coordonnee(5,5))));
}
/**
* Test of getChemin method, of class Dijkstra.
*/
@Test
public void testGetChemin() {
System.out.println("getChemin");
Carte carte = new Carte(
"MDMEEH"
+"MMMEEA"
+"HEEEHH"
+"HAHHHE"
+"HAHEEE"
+"HHHEEE"
);
Case depart = carte.getCase(new Coordonnee(0,1));
Dijkstra instance = new Dijkstra(carte);
instance.calculerDistancesDepuis(depart);
int infini = 1+carte.getTaille()*carte.getTaille()*16;
System.out.println(" - Chemin vers (5,1)");
ArrayList<TypeMouvement> result = instance.getChemin(carte.getCase(new Coordonnee(5,1)));
TypeMouvement[] expResultArray = {BOTTOM, LEFT, BOTTOM, BOTTOM, BOTTOM, BOTTOM, RIGHT};
ArrayList<TypeMouvement> expResult = new ArrayList<>(Arrays.asList(expResultArray));
assertEquals(expResult,result);
System.out.println(" - Chemin vers (0,5)");
ArrayList<TypeMouvement> result2 = instance.getChemin(carte.getCase(new Coordonnee(0,5)));
TypeMouvement[] expResultArray2 = {BOTTOM, LEFT, BOTTOM, BOTTOM, RIGHT, RIGHT, RIGHT, RIGHT, TOP, RIGHT, TOP, TOP};
ArrayList<TypeMouvement> expResult2 = new ArrayList<>(Arrays.asList(expResultArray2));
assertEquals(expResult2,result2);
}
}
| 49.838462 | 124 | 0.652107 |
e1bed1d4ad32f1bced03f4809121b62c4b799269
| 2,672 |
package knf.kuma.videoservers;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public abstract class Server implements Comparable<Server> {
int TIMEOUT = 10000;
Context context;
String baseLink;
private VideoServer server;
public Server(Context context, String baseLink) {
this.context = context;
this.baseLink = baseLink;
}
private static List<Server> getServers(Context context, String base) {
return Arrays.asList(
new FireServer(context, base),
new HyperionServer(context, base),
new IzanagiServer(context, base),
new MegaServer(context, base),
new OkruServer(context, base),
new RVServer(context, base),
new YUServer(context, base)
//new ZippyServer(context, base)
);
}
public static Server check(Context context, String base) {
for (Server server : getServers(context, base)) {
if (server.isValid())
return server;
}
return null;
}
private static int findPosition(List<Server> servers, String name) {
int i = 0;
for (Server server : servers) {
if (server.getName().equals(name))
return i;
i++;
}
return 0;
}
public static boolean existServer(List<Server> servers, int position) {
String name = VideoServer.Names.getDownloadServers()[position - 1];
for (Server server : servers) {
if (server.getName().equals(name))
return true;
}
return false;
}
public static Server findServer(List<Server> servers, int position) {
String name = VideoServer.Names.getDownloadServers()[position - 1];
return servers.get(findPosition(servers, name));
}
public static List<String> getNames(List<Server> servers) {
List<String> names = new ArrayList<>();
for (Server server : servers) {
names.add(server.getName());
}
return names;
}
public abstract boolean isValid();
public abstract String getName();
@Nullable
public abstract VideoServer getVideoServer();
@Nullable
public VideoServer getLink() {
if (server == null)
server = getVideoServer();
return server;
}
@Override
public int compareTo(@NonNull Server server) {
return getName().compareTo(server.getName());
}
}
| 28.126316 | 75 | 0.602919 |
58b6b7011361a16afe654331673854cd8330b750
| 3,247 |
package org.zerock.mreview.security.service;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;
import org.zerock.mreview.entity.ClubMember;
import org.zerock.mreview.entity.ClubMemberRole;
import org.zerock.mreview.repository.ClubMemberRepository;
import org.zerock.mreview.security.dto.ClubAuthMemberDTO;
import java.util.Optional;
import java.util.stream.Collectors;
@Log4j2
@Service
@RequiredArgsConstructor
public class ClubOAuth2UserDetailsService extends DefaultOAuth2UserService {
private final ClubMemberRepository repository;
private final PasswordEncoder passwordEncoder;
@Override
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
log.info("--------------------------------------");
log.info("userRequest:" + userRequest);
String clientName = userRequest.getClientRegistration().getClientName();
log.info("clientName: " + clientName);
log.info(userRequest.getAdditionalParameters());
OAuth2User oAuth2User = super.loadUser(userRequest);
log.info("=====================================");
oAuth2User.getAttributes().forEach((k,v) -> {
log.info(k +":" + v);
});
String email = null;
if(clientName.equals("Google")){
email = oAuth2User.getAttribute("email");
}
log.info("EMAIL: " + email);
// ClubMember member = saveSocialMember(email); //조금 뒤에 사용
//
// return oAuth2User;
ClubMember member = saveSocialMember(email);
ClubAuthMemberDTO clubAuthMember = new ClubAuthMemberDTO(
member.getEmail(),
member.getPassword(),
true, //fromSocial
member.getRoleSet().stream().map(
role -> new SimpleGrantedAuthority("ROLE_" + role.name()))
.collect(Collectors.toList()),
oAuth2User.getAttributes()
);
clubAuthMember.setName(member.getName());
return clubAuthMember;
}
private ClubMember saveSocialMember(String email){
//기존에 동일한 이메일로 가입한 회원이 있는 경우에는 그대로 조회만
Optional<ClubMember> result = repository.findByEmail(email, true);
if(result.isPresent()){
return result.get();
}
//없다면 회원 추가 패스워드는 1111 이름은 그냥 이메일 주소로
ClubMember clubMember = ClubMember.builder().email(email)
.name(email)
.password( passwordEncoder.encode("1111") )
.fromSocial(true)
.build();
clubMember.addMemberRole(ClubMemberRole.USER);
repository.save(clubMember);
return clubMember;
}
}
| 31.221154 | 100 | 0.65907 |
4cb5a87153864f465ede782d5f268c8ee8fe686c
| 277 |
package de.hhu.propra.link.repositories;
import de.hhu.propra.link.entities.Link;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface LinkRepository extends CrudRepository<Link, String> {
}
| 30.777778 | 70 | 0.841155 |
92ea69e0a3d17fab04e189d70396889b6befc649
| 4,874 |
/*
* 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.http;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsException;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.test.ESTestCase;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import java.util.regex.PatternSyntaxException;
import java.util.stream.Collectors;
import static org.elasticsearch.common.Strings.collectionToDelimitedString;
import static org.elasticsearch.http.HttpTransportSettings.SETTING_CORS_ALLOW_CREDENTIALS;
import static org.elasticsearch.http.HttpTransportSettings.SETTING_CORS_ALLOW_HEADERS;
import static org.elasticsearch.http.HttpTransportSettings.SETTING_CORS_ALLOW_METHODS;
import static org.elasticsearch.http.HttpTransportSettings.SETTING_CORS_ALLOW_ORIGIN;
import static org.elasticsearch.http.HttpTransportSettings.SETTING_CORS_ENABLED;
import static org.elasticsearch.http.HttpTransportSettings.SETTING_CORS_MAX_AGE;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.instanceOf;
public class CorsHandlerTests extends ESTestCase {
public void testCorsConfigWithBadRegex() {
final Settings settings = Settings.builder()
.put(SETTING_CORS_ENABLED.getKey(), true)
.put(SETTING_CORS_ALLOW_ORIGIN.getKey(), "/[*/")
.put(SETTING_CORS_ALLOW_CREDENTIALS.getKey(), true)
.build();
SettingsException e = expectThrows(SettingsException.class, () -> CorsHandler.fromSettings(settings));
assertThat(e.getMessage(), containsString("Bad regex in [http.cors.allow-origin]: [/[*/]"));
assertThat(e.getCause(), instanceOf(PatternSyntaxException.class));
}
public void testCorsConfig() {
final Set<String> methods = new HashSet<>(Arrays.asList("get", "options", "post"));
final Set<String> headers = new HashSet<>(Arrays.asList("Content-Type", "Content-Length"));
final String prefix = randomBoolean() ? " " : ""; // sometimes have a leading whitespace between comma delimited elements
final Settings settings = Settings.builder()
.put(SETTING_CORS_ENABLED.getKey(), true)
.put(SETTING_CORS_ALLOW_ORIGIN.getKey(), "*")
.put(SETTING_CORS_ALLOW_METHODS.getKey(), collectionToDelimitedString(methods, ",", prefix, ""))
.put(SETTING_CORS_ALLOW_HEADERS.getKey(), collectionToDelimitedString(headers, ",", prefix, ""))
.put(SETTING_CORS_ALLOW_CREDENTIALS.getKey(), true)
.build();
final CorsHandler.Config corsConfig = CorsHandler.fromSettings(settings);
assertTrue(corsConfig.isAnyOriginSupported());
assertEquals(headers, corsConfig.allowedRequestHeaders());
assertEquals(methods.stream().map(s -> s.toUpperCase(Locale.ENGLISH)).collect(Collectors.toSet()),
corsConfig.allowedRequestMethods().stream().map(RestRequest.Method::name).collect(Collectors.toSet()));
}
public void testCorsConfigWithDefaults() {
final Set<String> methods = Strings.commaDelimitedListToSet(SETTING_CORS_ALLOW_METHODS.getDefault(Settings.EMPTY));
final Set<String> headers = Strings.commaDelimitedListToSet(SETTING_CORS_ALLOW_HEADERS.getDefault(Settings.EMPTY));
final long maxAge = SETTING_CORS_MAX_AGE.getDefault(Settings.EMPTY);
final Settings settings = Settings.builder().put(SETTING_CORS_ENABLED.getKey(), true).build();
final CorsHandler.Config corsConfig = CorsHandler.fromSettings(settings);
assertFalse(corsConfig.isAnyOriginSupported());
assertEquals(Collections.emptySet(), corsConfig.origins().get());
assertEquals(headers, corsConfig.allowedRequestHeaders());
assertEquals(methods, corsConfig.allowedRequestMethods().stream().map(RestRequest.Method::name).collect(Collectors.toSet()));
assertEquals(maxAge, corsConfig.maxAge());
assertFalse(corsConfig.isCredentialsAllowed());
}
}
| 53.56044 | 133 | 0.750308 |
84eeeb5ab1fd1be4a93ca4052cd5097773e12b54
| 106 |
package org.batfish.representation.cisco;
public enum PolicyMapClassAction {
DROP,
INSPECT,
PASS
}
| 13.25 | 41 | 0.764151 |
c4895ac8fb905ea6ff0afacf9070d4c84bbf263f
| 10,204 |
package com.googlecode.android_scripting;
import com.sun.javadoc.AnnotationDesc;
import com.sun.javadoc.AnnotationDesc.ElementValuePair;
import com.sun.javadoc.ClassDoc;
import com.sun.javadoc.Doc;
import com.sun.javadoc.MethodDoc;
import com.sun.javadoc.Parameter;
import com.sun.javadoc.ProgramElementDoc;
import com.sun.javadoc.RootDoc;
import com.sun.javadoc.Tag;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.Vector;
/**
* Doclet to export SL4A API.
*
* Combines javadoc and Rpc annotations into lightweight reference documentation.
*
* Usage:
*
* javadoc -dest <destination folder> -doclet com.googlecode.android_scripting.RpcDoclet -docletpath
* <path to class> -sourcepath <sourcepathlist>
*
* Or use javadoc.xml with the javadoc wizard in eclipse.
*
* @author Robbie Matthews
*
*/
public class RpcDoclet {
private RootDoc mRoot;
private List<ClassDoc> classlist = new Vector<ClassDoc>();
private String mDest;
private PrintWriter mOutput;
public RpcDoclet(RootDoc root) {
mRoot = root;
}
public boolean run() {
System.out.println("Started in " + System.getProperty("user.dir"));
String temp;
for (String[] list : mRoot.options()) {
temp = "";
if (list[0].equals("-dest")) {
mDest = list[1];
}
for (String s : list) {
temp += s + " : ";
}
addln(temp);
}
try {
if (mDest == null) {
System.out.println("Must define destination path (-dest <pathname<>)");
return false;
}
File file = new File(mDest);
if (!file.exists()) {
file.mkdirs();
}
if (!file.isDirectory() || !file.canWrite()) {
System.out.println("Can't write to destination path.");
return false;
}
System.out.println("Classes " + mRoot.classes().length);
for (ClassDoc clazz : mRoot.classes()) {
if (hasRpc(clazz)) {
classlist.add(clazz);
}
}
if (classlist.isEmpty()) {
System.out.println("No Rpc Classes found.");
return false;
}
Collections.sort(classlist);
createIndex(classlist);
for (ClassDoc clazz : classlist) {
dumpClassDetail(clazz);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
private String link(String href, String text) {
if (text.startsWith("#")) {
text = text.substring(1);
}
return "<a href=\"" + href + "\">" + text + "</a>";
}
private String anchor(String name) {
return "<a name=\"" + name + "\"/>";
}
protected String tr(String contents) {
return "<tr>" + contents + "</tr>";
}
protected String td(String contents) {
return "<td>" + contents + "</td>";
}
private void createIndex(List<ClassDoc> classlist) throws IOException {
File file = new File(mDest + "/index.html");
mOutput = new PrintWriter(file);
outputln("<html><head><title>SL4A API Help</title></head>");
outputln("<body>");
outputln("<h1>SL4A API Help</h1>");
outputln("<table border=1>");
for (ClassDoc clazz : classlist) {
outputln("<tr><td>" + link(clazz.name() + ".html", clazz.name()) + "</td><td>"
+ trimComment(clazz.commentText()) + "</td></tr>");
}
outputln("</body></html>");
mOutput.close();
}
private void dumpClassDetail(ClassDoc clazz) throws IOException {
List<MethodDoc> methodlist = new Vector<MethodDoc>();
addln(clazz.name());
File file = new File(mDest + "/" + clazz.name() + ".html");
mOutput = new PrintWriter(file);
outputln("<html><head><title>SL4A API Help -" + clazz.name() + "</title></head>");
outputln("<body>");
outputln("<h1>SL4A API Help -" + clazz.name() + "</h1>");
outputln(link("index.html", "index") + "<br>");
outputln(expandTags(clazz));
for (Tag t : clazz.tags()) {
outputln("<br>" + t.name() + " " + t.text());
}
outputln("<table border=1>");
for (MethodDoc method : clazz.methods()) {
if (methodHasRpc(method)) {
methodlist.add(method);
}
}
Collections.sort(methodlist);
for (MethodDoc method : methodlist) {
output("<tr><td>" + anchor(method.name()) + "<b>" + method.name() + "</b></td>");
output("<td>");
Map<String, AnnotationDesc> amap = buildAnnotations(method);
AnnotationDesc rpc = amap.get("Rpc");
Map<String, String> mlist = buildAnnotationDetails(rpc);
if (mlist.containsKey("description")) {
outputln(htmlLines(mlist.get("description")));
}
listRpcParameters(method);
if (mlist.containsKey("returns")) {
outputln("<br><b>returns: (" + method.returnType().simpleTypeName() + ")</b> "
+ mlist.get("returns"));
}
if (method.commentText() != null && !method.commentText().isEmpty()) {
outputln("<br>" + expandTags(method));
}
if (amap.containsKey("RpcMinSdk")) {
outputln("<br><i>Min SDK level="
+ buildAnnotationDetails(amap.get("RpcMinSdk")).get("value") + "</i>");
}
if (amap.containsKey("RpcDeprecated")) {
Map<String, String> dmap = buildAnnotationDetails(amap.get("RpcDeprecated"));
outputln("<br><i>Deprecated in " + dmap.get("release") + ". Use " + dmap.get("value")
+ " instead.</i>");
}
outputln("</td></tr>");
}
outputln("</table>");
outputln("<br>" + link("index.html", "index") + "<br>");
outputln("</body></html>");
mOutput.close();
}
private void listRpcParameters(MethodDoc m) throws IOException {
AnnotationDesc annotation;
Map<String, String> d;
String s;
for (Parameter parameter : m.parameters()) {
Map<String, AnnotationDesc> paramList = buildAnnotations(parameter.annotations());
if ((annotation = paramList.get("RpcParameter")) != null) {
d = buildAnnotationDetails(annotation);
String name = d.get("name");
if (name == null) {
name = parameter.name();
}
s = "<br><b>" + name + " (" + parameter.type().simpleTypeName() + ")</b> ";
if (d.containsKey("description")) {
s = s + htmlLines(d.get("description"));
}
if (paramList.containsKey("RpcOptional")) {
s = s + " (optional)";
}
if (paramList.containsKey("RpcDefault")) {
d = buildAnnotationDetails(paramList.get("RpcDefault"));
s = s + " (default=" + d.get("value") + ")";
}
outputln(s);
}
}
}
private String expandTags(Doc doc) {
StringBuilder result = new StringBuilder();
for (Tag tag : doc.inlineTags()) {
if (tag.name().equals("Text")) {
result.append(tag.text());
} else {
StringTokenizer tokenizer = new StringTokenizer(tag.text());
if (tag.kind().equals("@see")) {
String link = tokenizer.nextToken();
String name = (tokenizer.hasMoreTokens() ? tokenizer.nextToken() : link);
result.append(link(link, name));
} else {
result.append("[" + tag.name() + ":" + tag.text() + "]");
}
}
}
return result.toString();
}
private Map<String, AnnotationDesc> buildAnnotations(AnnotationDesc[] annotations) {
Map<String, AnnotationDesc> result = new LinkedHashMap<String, AnnotationDesc>();
for (AnnotationDesc annotation : annotations) {
result.put(annotation.annotationType().name(), annotation);
}
return result;
}
private Map<String, AnnotationDesc> buildAnnotations(ProgramElementDoc doc) {
return buildAnnotations(doc.annotations());
}
private String trimQuotes(String value) {
if (!value.startsWith("\"")) {
return value;
}
return value.substring(1, value.lastIndexOf("\""));
}
private Map<String, String> buildAnnotationDetails(AnnotationDesc annotation) {
Map<String, String> result = new HashMap<String, String>();
for (ElementValuePair e : annotation.elementValues()) {
result.put(e.element().name(), trimQuotes(e.value().toString()));
}
return result;
}
private String trimComment(String commentText) {
int i = commentText.indexOf(".");
if (i > 0) {
return commentText.substring(0, i);
}
return commentText;
}
private String htmlLines(String value) {
addln(value);
return value.replace("\\n", "<br>").replace("\n", "<br>");
}
private void addln(Object message) {
System.out.println(message);
}
private void output(String message) throws IOException {
mOutput.print(message);
}
private void outputln(String message) throws IOException {
mOutput.println(message);
}
private boolean hasRpc(ClassDoc clazz) {
for (MethodDoc method : clazz.methods()) {
if (methodHasRpc(method)) {
return true;
}
}
return false;
}
private boolean methodHasRpc(MethodDoc method) {
for (AnnotationDesc a : method.annotations()) {
if (a.annotationType().name().equals("Rpc")) {
return true;
}
}
return false;
}
public Map<String, Object> sortmap(Map<String, Object> map) {
Set<String> list = new TreeSet<String>(map.keySet());
Map<String, Object> result = new LinkedHashMap<String, Object>();
for (String key : list) {
result.put(key, map.get(key));
}
return result;
}
public static boolean start(RootDoc root) {
RpcDoclet mydoclet = new RpcDoclet(root);
return mydoclet.run();
}
public static int optionLength(String option) {
if (option.equals("-dest")) {
return 2;
}
return 0;
}
}
| 31.204893 | 101 | 0.584967 |
8ddcfc5ee18fab46efea7d53340331c43af86aed
| 558 |
package com.annimon.stream.doublestreamtests;
import com.annimon.stream.DoubleStream;
import org.junit.Test;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public final class ToArrayTest {
@Test
public void testToArray() {
assertThat(DoubleStream.of(0.012, 10.347, 3.039, 19.84, 100d).toArray(),
is(new double[] {0.012, 10.347, 3.039, 19.84, 100d}));
}
@Test
public void testToArrayOnEmptyStream() {
assertThat(DoubleStream.empty().toArray().length, is(0));
}
}
| 26.571429 | 80 | 0.677419 |
f73bbc8d9c16a71809f11e3fab9f73b3080e3293
| 1,841 |
/*
* Copyright 2014-2016 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 example.springdata.mongodb.advanced;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.mongodb.core.MongoOperations;
import com.mongodb.MongoClient;
/**
* Test configuration to connect to a MongoDB named "test" and using a {@link MongoClient} with profiling enabled.
*
* @author Christoph Strobl
*/
@SpringBootApplication
class ApplicationConfiguration {
static final String SYSTEM_PROFILE_DB = "system.profile";
@Autowired MongoOperations operations;
/**
* Initialize db instance with defaults.
*/
@PostConstruct
public void initializeWithDefaults() {
// Enable profiling
setProfilingLevel(2);
}
/**
* Clean up resources on shutdown
*/
@PreDestroy
public void cleanUpWhenShuttingDown() {
// Disable profiling
setProfilingLevel(0);
if (operations.collectionExists(SYSTEM_PROFILE_DB)) {
operations.dropCollection(SYSTEM_PROFILE_DB);
}
}
private void setProfilingLevel(int level) {
operations.executeCommand(new Document("profile", level));
}
}
| 27.073529 | 114 | 0.763172 |
a3c573a0e856b8ed0b090d7860be3d404742675a
| 229 |
package cn.znnine.netty.protocol.http.xml.pojo;
/**
* 邮寄方式
*
* @author lihongjian
* @since 2021/11/7
*/
public enum Shipping {
STANDARD_MAIL, PRIORITY_MAIL, INTERNATIONAL_MAIL, DOMESTIC_EXPRESS, INTERNATIONAL_EXPRESS
}
| 19.083333 | 93 | 0.742358 |
70720155be38e94c0e5c321858acc7d2a399c592
| 274 |
package br.com.uol.pagseguro.api.common.domain;
/**
* Interface for phone account
*
* @author PagSeguro Internet Ltda.
*/
public interface PhoneAccount extends Phone {
/**
* Get type of phone account
*
* @return Type
*/
String getType();
}
| 16.117647 | 47 | 0.631387 |
42762bd8b963387b5862f318797603c4b33a1c92
| 5,131 |
package cn.weekdragon.xspider.controller.admin;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.weekdragon.xspider.access.AccessLimit;
import cn.weekdragon.xspider.domain.Film;
import cn.weekdragon.xspider.domain.User;
import cn.weekdragon.xspider.exception.GlobalException;
import cn.weekdragon.xspider.redis.FilmKey;
import cn.weekdragon.xspider.redis.RedisService;
import cn.weekdragon.xspider.result.CodeMsg;
import cn.weekdragon.xspider.service.FilmService;
import cn.weekdragon.xspider.vo.PageVo;
@Controller
@RequestMapping("/admin")
public class AdminFilmController {
@Autowired
private RedisService redisService;
@Autowired
private FilmService filmService;
@AccessLimit(needLogin = true, maxCount = 5, seconds = 5)
@RequestMapping("/film")
public String listFilms(@RequestParam(value = "order", required = false, defaultValue = "new") String order,
@RequestParam(value = "keyword", required = false, defaultValue = "") String keyword,
@RequestParam(value = "async", required = false) boolean async,
@RequestParam(value = "pageIndex", required = false, defaultValue = "0") int pageIndex,
@RequestParam(value = "pageSize", required = false, defaultValue = "15") int pageSize, HttpServletRequest request, HttpServletResponse response,
Model model, User user) {
Page<Film> page = null;
List<Film> list = null;
boolean isEmpty = true; // 系统初始化时,没有电影数据
try {
if (order.equals("new")) { // 最新查询
Sort sort = new Sort(Direction.DESC, "createTime");
Pageable pageable = new PageRequest(pageIndex, pageSize, sort);
page = filmService.listNewestFilms(keyword, pageable);
}
isEmpty = false;
} catch (Exception e) {
Pageable pageable = new PageRequest(pageIndex, pageSize);
page = filmService.listFilms(pageable);
}
list = page.getContent(); // 当前所在页面数据列表
model.addAttribute("test", "test");
model.addAttribute("order", order);
model.addAttribute("keyword", keyword);
model.addAttribute("page", page);
model.addAttribute("films", list);
// 首次访问页面才加载
if (!async && !isEmpty) {
model.addAttribute("username", user.getNickName());
}
return async == true ? "admin/fragment/film::#content" : "admin/fragment/film";
}
@ResponseBody
@RequestMapping("/films")
public String listJsonFilms(@RequestParam(name = "draw") Integer draw, @RequestParam(name = "start") Integer start,
@RequestParam(name = "length") Integer length,@RequestParam(name = "search[value]") String searchValue) {
Pageable pageable = new PageRequest(start/length, length);
Page<Film> listFilms = filmService.listFilms(searchValue,pageable);
Long totalElements = listFilms.getTotalElements();
PageVo pageVo = new PageVo();
pageVo.setDraw(draw);
pageVo.setRecordsFiltered(totalElements.intValue());
pageVo.setRecordsTotal(totalElements.intValue());
pageVo.setData(listFilms.getContent());
return RedisService.beanToString(pageVo);
}
@RequestMapping("/film/add")
public String toFilmAdd(Model model) {
Film film = new Film();
model.addAttribute("film", film);
return "admin/fragment/film-edit :: #content";
}
@RequestMapping("/film/{id}/to_edit")
public String toFilmEdit(@PathVariable("id") Long id, Model model) {
if (id == null) {
throw new GlobalException(CodeMsg.REQUEST_ILLEGAL);
}
Film film = redisService.get(FilmKey.getById, id + "", Film.class);
if (film == null) {
film = filmService.getFilmById(id);
if (film != null) {
redisService.set(FilmKey.getById, id + "", film);
}
}
model.addAttribute("film", film);
return "admin/fragment/film-edit :: #content";
}
@ResponseBody
@RequestMapping("/film/edit")
public CodeMsg filmEdit(@RequestBody String json) {
System.out.println(json);
Film film = RedisService.stringToBean(json, Film.class);
filmService.saveFilm(film);
redisService.delete(FilmKey.getById, film.getId() + "");
return CodeMsg.SUCCESS;
}
@ResponseBody
@AccessLimit(needLogin = true, maxCount = 5, seconds = 5)
@RequestMapping("/film/{id}/to_delete")
public CodeMsg toFilmDelete(@PathVariable(name = "id", required = true) String ids, Model model) {
String[] split = ids.split("_");
for (String id : split) {
try {
filmService.deleteFilm(Long.parseLong(id));
} catch (Exception e) {
throw new GlobalException(CodeMsg.REQUEST_ILLEGAL);
}
}
return CodeMsg.SUCCESS;
}
}
| 35.881119 | 147 | 0.74274 |
7a5b385462e686af7a08a9b6ff7369ac27286523
| 3,377 |
/*
* 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.kafka.raft;
import org.apache.kafka.common.protocol.ApiKeys;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
public class MockNetworkChannel implements NetworkChannel {
private final AtomicInteger correlationIdCounter;
private final Set<Integer> nodeCache;
private final List<RaftRequest.Outbound> sendQueue = new ArrayList<>();
private final Map<Integer, RaftRequest.Outbound> awaitingResponse = new HashMap<>();
public MockNetworkChannel(AtomicInteger correlationIdCounter, Set<Integer> destinationIds) {
this.correlationIdCounter = correlationIdCounter;
this.nodeCache = destinationIds;
}
public MockNetworkChannel(Set<Integer> destinationIds) {
this(new AtomicInteger(0), destinationIds);
}
@Override
public int newCorrelationId() {
return correlationIdCounter.getAndIncrement();
}
@Override
public void send(RaftRequest.Outbound request) {
if (!nodeCache.contains(request.destinationId())) {
throw new IllegalArgumentException("Attempted to send to destination " +
request.destinationId() + ", but its address is not yet known");
}
sendQueue.add(request);
}
public List<RaftRequest.Outbound> drainSendQueue() {
return drainSentRequests(Optional.empty());
}
public List<RaftRequest.Outbound> drainSentRequests(Optional<ApiKeys> apiKeyFilter) {
List<RaftRequest.Outbound> requests = new ArrayList<>();
Iterator<RaftRequest.Outbound> iterator = sendQueue.iterator();
while (iterator.hasNext()) {
RaftRequest.Outbound request = iterator.next();
if (!apiKeyFilter.isPresent() || request.data().apiKey() == apiKeyFilter.get().id) {
awaitingResponse.put(request.correlationId, request);
requests.add(request);
iterator.remove();
}
}
return requests;
}
public boolean hasSentRequests() {
return !sendQueue.isEmpty();
}
public void mockReceive(RaftResponse.Inbound response) {
RaftRequest.Outbound request = awaitingResponse.get(response.correlationId);
if (request == null) {
throw new IllegalStateException("Received response for a request which is not being awaited");
}
request.completion.complete(response);
}
}
| 37.10989 | 106 | 0.702102 |
d7cb152f63adc61d6a1d9f77dc890ac91975d262
| 9,095 |
/**
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (3.3.4).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.github.asyncmc.mojang.api.spring.api;
import com.github.asyncmc.mojang.api.spring.model.Error;
import java.util.List;
import com.github.asyncmc.mojang.api.spring.model.NameChange;
import org.springframework.core.io.Resource;
import com.github.asyncmc.mojang.api.spring.model.SecurityAnswer;
import com.github.asyncmc.mojang.api.spring.model.SecurityChallenge;
import com.github.asyncmc.mojang.api.spring.model.SkinModel;
import io.swagger.annotations.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.Valid;
import javax.validation.constraints.*;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen", date = "2020-06-06T05:02:20.878351200-03:00[America/Sao_Paulo]")
@Validated
@Api(value = "user", description = "the user API")
public interface UserApi {
default Optional<NativeWebRequest> getRequest() {
return Optional.empty();
}
@ApiOperation(value = "Changes the player skin by URL", nickname = "changePlayerSkin", notes = "This will set the skin for the selected profile, but Mojang's servers will fetch the skin from a URL. This will also work for legacy accounts.", authorizations = {
@Authorization(value = "PlayerAccessToken")
}, tags={ "Skin Operations", })
@ApiResponses(value = {
@ApiResponse(code = 204, message = "The skin has been changed. The response has no body"),
@ApiResponse(code = 400, message = "Upon error the server will send back a JSON with the error. (Success is a blank payload)", response = Error.class) })
@RequestMapping(value = "/user/profile/{stripped_uuid}/skin",
produces = { "application/json" },
consumes = { "application/x-www-form-urlencoded" },
method = RequestMethod.POST)
default ResponseEntity<Void> changePlayerSkin(@ApiParam(value = "The player UUID without hyphens",required=true) @PathVariable("stripped_uuid") String strippedUuid,@ApiParam(value = "The URL which Mojang servers will download and apply the skin", required=true) @RequestParam(value="url", required=true) String url,@ApiParam(value = "", defaultValue="null") @RequestParam(value="model", required=false) SkinModel model) {
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
}
@ApiOperation(value = "Check if security questions are needed", nickname = "checkSecurityStatus", notes = "", authorizations = {
@Authorization(value = "PlayerAccessToken")
}, tags={ "Security question-answer", })
@ApiResponses(value = {
@ApiResponse(code = 204, message = "No check is needed."),
@ApiResponse(code = 400, message = "A security check is needed or there is an other issue", response = Error.class) })
@RequestMapping(value = "/user/security/location",
produces = { "application/json" },
method = RequestMethod.GET)
default ResponseEntity<Void> checkSecurityStatus() {
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
}
@ApiOperation(value = "Gets the full player's name history", nickname = "getNameHistory", notes = "", response = NameChange.class, responseContainer = "List", tags={ "Name History", })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "A list of name changes, the first entry usually don't have a change time", response = NameChange.class, responseContainer = "List"),
@ApiResponse(code = 204, message = "Username not found at the given time") })
@RequestMapping(value = "/user/profiles/{stripped_uuid}/names",
produces = { "application/json" },
method = RequestMethod.GET)
default ResponseEntity<List<NameChange>> getNameHistory(@ApiParam(value = "The player UUID without hyphens",required=true) @PathVariable("stripped_uuid") String strippedUuid) {
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
}
@ApiOperation(value = "Get list of questions", nickname = "listPendingSecurityQuestions", notes = "", response = SecurityChallenge.class, responseContainer = "List", authorizations = {
@Authorization(value = "PlayerAccessToken")
}, tags={ "Security question-answer", })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "A list of security questions to be answered", response = SecurityChallenge.class, responseContainer = "List") })
@RequestMapping(value = "/user/security/challenges",
produces = { "application/json" },
method = RequestMethod.GET)
default ResponseEntity<List<SecurityChallenge>> listPendingSecurityQuestions() {
getRequest().ifPresent(request -> {
for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) {
if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) {
ApiUtil.setExampleResponse(request, "application/json", "{ \"question\" : { \"question\" : \"What is your dream job?\", \"id\" : 37 }, \"answer\" : { \"id\" : 593 }}");
break;
}
}
});
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
}
@ApiOperation(value = "Resets the player skin to default", nickname = "resetPlayerSkin", notes = "", authorizations = {
@Authorization(value = "PlayerAccessToken")
}, tags={ "Skin Operations", })
@ApiResponses(value = {
@ApiResponse(code = 204, message = "The skin has been changed. The response has no body"),
@ApiResponse(code = 400, message = "Upon error the server will send back a JSON with the error. (Success is a blank payload)", response = Error.class) })
@RequestMapping(value = "/user/profile/{stripped_uuid}/skin",
produces = { "application/json" },
method = RequestMethod.DELETE)
default ResponseEntity<Void> resetPlayerSkin(@ApiParam(value = "The player UUID without hyphens",required=true) @PathVariable("stripped_uuid") String strippedUuid) {
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
}
@ApiOperation(value = "Send back the answers", nickname = "sendSecurityQuestionAnswers", notes = "", authorizations = {
@Authorization(value = "PlayerAccessToken")
}, tags={ "Security question-answer", })
@ApiResponses(value = {
@ApiResponse(code = 204, message = "The answers were accepted"),
@ApiResponse(code = 400, message = "At least one answer we not accepted", response = Error.class) })
@RequestMapping(value = "/user/security/location",
produces = { "application/json" },
consumes = { "application/json" },
method = RequestMethod.POST)
default ResponseEntity<Void> sendSecurityQuestionAnswers(@ApiParam(value = "An array with all the answers" ,required=true ) @Valid @RequestBody List<SecurityAnswer> securityAnswer) {
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
}
@ApiOperation(value = "Changes the player skin by upload", nickname = "uploadPlayerSkin", notes = "This uploads a skin to Mojang's servers. It also sets the users skin. This works on legacy counts as well.", authorizations = {
@Authorization(value = "PlayerAccessToken")
}, tags={ "Skin Operations", })
@ApiResponses(value = {
@ApiResponse(code = 204, message = "The skin has been changed. The response has no body"),
@ApiResponse(code = 400, message = "Upon error the server will send back a JSON with the error. (Success is a blank payload)", response = Error.class) })
@RequestMapping(value = "/user/profile/{stripped_uuid}/skin",
produces = { "application/json" },
consumes = { "multipart/form-data" },
method = RequestMethod.PUT)
default ResponseEntity<Void> uploadPlayerSkin(@ApiParam(value = "The player UUID without hyphens",required=true) @PathVariable("stripped_uuid") String strippedUuid,@ApiParam(value = "file detail") @Valid @RequestPart("file") MultipartFile file,@ApiParam(value = "", defaultValue="null") @RequestParam(value="model", required=false) SkinModel model) {
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
}
}
| 57.563291 | 427 | 0.705553 |
3ea5e0be868737932fa629b0f2043c979fd2d7c8
| 1,352 |
package com.yundian.blackcard.android.model;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author : created by chuangWu
* @version : 0.01
* @email : chuangwu127@gmail.com
* @created time : 2017-06-07 13:40
* @description : none
* @for your attention : none
* @revise : none
*/
public class DataFractory {
public static List<MyPurseDetailModel> getMyPurseDetailList() {
List<MyPurseDetailModel> modelList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
MyPurseDetailModel model = new MyPurseDetailModel();
model.setAmount(12.3);
model.setCreateTime(new Date().getTime());
model.setTradeName("充值");
model.setTradeNo("12345" + i);
modelList.add(model);
}
return modelList;
}
public static List<PurchaseHistoryModel> getPurchaseHistoryList() {
List<PurchaseHistoryModel> modelList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
PurchaseHistoryModel model = new PurchaseHistoryModel();
model.setTradeNo("201412343212345432");
model.setTradeTime(new Date().getTime());
model.setTradeGoodsName("充值");
model.setTradeNo("12345" + i);
modelList.add(model);
}
return modelList;
}
}
| 30.044444 | 71 | 0.608728 |
3dda47875a26b97f887ef16d0bb6e08d75767f2b
| 710 |
package org.shanhaijing.example.controller;
import org.shanhaijing.example.service.ExampleService;
import org.shanhaijing.framework.beans.annotation.Autowirted;
import org.shanhaijing.framework.beans.annotation.Controller;
import org.shanhaijing.framework.beans.annotation.RequestParam;
import org.shanhaijing.framework.request.annotation.RequestMapping;
import org.shanhaijing.framework.request.annotation.RequestMethod;
@Controller
@RequestMapping
public class ExampleController {
@Autowirted
private ExampleService exampleService;
@RequestMapping(method = RequestMethod.GET)
public String example(@RequestParam("name") String name){
return exampleService.example(name);
}
}
| 30.869565 | 67 | 0.814085 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.