hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
9242f48591d718d23681d83fe27c48197450b53c
1,107
java
Java
src/tools/FileTool.java
Johnneba/Johnneba.github.io
001d3641727bbf382643783d37848cafab67104b
[ "MIT" ]
12
2017-04-08T15:01:43.000Z
2021-08-23T20:42:35.000Z
src/tools/FileTool.java
msoftware/aio-video-downloader
d922923ac0ffc827bf90c8b2f2dcd1755e292fbf
[ "MIT" ]
null
null
null
src/tools/FileTool.java
msoftware/aio-video-downloader
d922923ac0ffc827bf90c8b2f2dcd1755e292fbf
[ "MIT" ]
5
2019-10-23T06:59:11.000Z
2021-07-08T10:49:58.000Z
29.131579
109
0.68654
1,002,478
package tools; import android.annotation.TargetApi; import android.os.Build; import android.os.Environment; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; /** * File utility Class. * Created by shibaprasad on 4/13/2015. */ public class FileTool { public static final String ROOT_PATH = Environment.getExternalStorageDirectory() + "/" + "Text To Voice"; //Get string from a text file. @TargetApi(Build.VERSION_CODES.KITKAT) public static String getStringFromFile(File file) throws IOException { BufferedReader bufferedReader = new BufferedReader(new FileReader(file.getPath())); StringBuilder stringBuilder = new StringBuilder(); String line = bufferedReader.readLine(); while (line != null) { stringBuilder.append(line); stringBuilder.append(System.lineSeparator()); line = bufferedReader.readLine(); } String allText = stringBuilder.toString(); //close the buffer. bufferedReader.close(); return allText; } }
9242f7cc3c1b9e521ce24d77d7d48b0baa9d3d69
4,735
java
Java
contribs/src/main/java/com/netflix/conductor/contribs/queue/sqs/config/SQSEventQueueConfiguration.java
trescomm/conductor
601e9824a595a80f31a173211fa32f4b71aded29
[ "Apache-2.0" ]
1
2021-11-02T20:18:46.000Z
2021-11-02T20:18:46.000Z
contribs/src/main/java/com/netflix/conductor/contribs/queue/sqs/config/SQSEventQueueConfiguration.java
trescomm/conductor
601e9824a595a80f31a173211fa32f4b71aded29
[ "Apache-2.0" ]
1
2021-05-25T07:47:41.000Z
2021-05-25T07:47:41.000Z
contribs/src/main/java/com/netflix/conductor/contribs/queue/sqs/config/SQSEventQueueConfiguration.java
trescomm/conductor
601e9824a595a80f31a173211fa32f4b71aded29
[ "Apache-2.0" ]
1
2021-05-22T06:07:43.000Z
2021-05-22T06:07:43.000Z
45.528846
122
0.679409
1,002,479
/* * Copyright 2020 Netflix, Inc. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.contribs.queue.sqs.config; import com.amazonaws.services.sqs.AmazonSQS; import com.netflix.conductor.common.metadata.tasks.Task.Status; import com.netflix.conductor.contribs.queue.sqs.SQSObservableQueue.Builder; import com.netflix.conductor.core.config.ConductorProperties; import com.netflix.conductor.core.events.EventQueueProvider; import com.netflix.conductor.core.events.queue.ObservableQueue; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; import rx.Scheduler; import java.util.HashMap; import java.util.Map; @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") @Configuration @EnableConfigurationProperties(SQSEventQueueProperties.class) @ConditionalOnProperty(name = "conductor.event-queues.sqs.enabled", havingValue = "true") public class SQSEventQueueConfiguration { private static final Logger LOGGER = LoggerFactory.getLogger(SQSEventQueueConfiguration.class); @Bean public EventQueueProvider sqsEventQueueProvider(Map<String, AmazonSQS> sqsClients, SQSEventQueueProperties properties, Scheduler scheduler) { return new SQSEventQueueProvider(sqsClients, properties, scheduler); } /** * * @param conductorProperties app level properties * @param properties SQS queue properties * @param sqsClients map of clients, with key == region and value being the Amazon SQSClient * @return Map with key as region and value as map of status to queues */ @ConditionalOnProperty(name = "conductor.default-event-queue.type", havingValue = "sqs", matchIfMissing = true) @Bean public Map<String, Map<Status, ObservableQueue>> getQueues(ConductorProperties conductorProperties, SQSEventQueueProperties properties, Map<String, AmazonSQS> sqsClients) { String stack = ""; if (conductorProperties.getStack() != null && conductorProperties.getStack().length() > 0) { stack = conductorProperties.getStack() + "_"; } Status[] statuses = new Status[]{Status.COMPLETED, Status.FAILED}; Map<String, Map<Status, ObservableQueue>> queues = new HashMap<>(); for(Map.Entry<String, AmazonSQS> entry : sqsClients.entrySet()) { String region = entry.getKey(); AmazonSQS sqsClient = entry.getValue(); Map<Status, ObservableQueue> queueMap = new HashMap<>(); queues.put(region, queueMap); for (Status status : statuses) { String queuePrefix = StringUtils.isBlank(properties.getListenerQueuePrefix()) ? conductorProperties.getAppId() + "_sqs_notify_" + stack : properties.getListenerQueuePrefix(); String queueName = queuePrefix + status.name(); LOGGER.info("Creating queue by name {} in region {}", queueName, region); Builder builder = new Builder().withClient(sqsClient).withQueueName(queueName); String auth = properties.getAuthorizedAccounts(); //TODO: we should be able to configure authorized accounts per region String[] accounts = auth.split(","); for (String accountToAuthorize : accounts) { accountToAuthorize = accountToAuthorize.trim(); if (accountToAuthorize.length() > 0) { builder.addAccountToAuthorize(accountToAuthorize.trim()); } } ObservableQueue queue = builder.build(); queueMap.put(status, queue); } } return queues; } }
9242f861de521b0b6feaea05c1e49518bc06bd8f
471
java
Java
src/Netbeans/jsop/src/main/java/com/company/jsop/jsonish/JSONObjectFactory.java
jakobehmsen/jsop
f02876005860b6372e8bd6b013c818169132f74c
[ "MIT" ]
null
null
null
src/Netbeans/jsop/src/main/java/com/company/jsop/jsonish/JSONObjectFactory.java
jakobehmsen/jsop
f02876005860b6372e8bd6b013c818169132f74c
[ "MIT" ]
null
null
null
src/Netbeans/jsop/src/main/java/com/company/jsop/jsonish/JSONObjectFactory.java
jakobehmsen/jsop
f02876005860b6372e8bd6b013c818169132f74c
[ "MIT" ]
null
null
null
24.789474
79
0.713376
1,002,480
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.company.jsop.jsonish; /** * * @author jakob */ public interface JSONObjectFactory { Object newMap(); Object newString(String str); Object newNumber(double d); Object newArray(); Object newFunction(String type, String src, String[] parameterNames); }
9242f867c1ecb7e7a0d4c3478a6bfa22d2a7e5ba
5,044
java
Java
src/main/java/uk/gov/ea/wastecarrier/services/core/MetaData.java
DEFRA/waste-carriers-service
717981c516ba85105f862432d146991a3af6b16d
[ "Ruby", "Unlicense" ]
null
null
null
src/main/java/uk/gov/ea/wastecarrier/services/core/MetaData.java
DEFRA/waste-carriers-service
717981c516ba85105f862432d146991a3af6b16d
[ "Ruby", "Unlicense" ]
4
2018-09-06T23:04:15.000Z
2020-10-13T09:06:10.000Z
src/main/java/uk/gov/ea/wastecarrier/services/core/MetaData.java
DEFRA/waste-carriers-service
717981c516ba85105f862432d146991a3af6b16d
[ "Ruby", "Unlicense" ]
1
2021-04-10T21:39:07.000Z
2021-04-10T21:39:07.000Z
23.351852
101
0.629659
1,002,481
package uk.gov.ea.wastecarrier.services.core; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; /** * The MetaData class represents the various operational information * related to a registration but is not information that a user would * provide on screen. This information is intended to be used for * Audit trail and monitoring purposes * */ @JsonIgnoreProperties(ignoreUnknown = true) public class MetaData { private Date dateRegistered; private String anotherString; private Date lastModified; private Date dateActivated; private RegistrationStatus status; private String revokedReason; private RouteType route; private String distance = "n/a"; /** * Statuses and their meaning: * * PENDING: Initial State * ACTIVATE: * ACTIVE: Registration has been Verified and should appear on the register * REVOKED: Registration has been removed from the register by the EA * INACTIVE: Registration has been deleted from the register by the registrant * */ // TODO in next CI: Remove the "ACTIVATE" item; it is unused. public enum RegistrationStatus { PENDING, ACTIVATE, ACTIVE, REVOKED, EXPIRED, INACTIVE, REFUSED } public enum RouteType { DIGITAL, ASSISTED_DIGITAL } /** * Other possible meta data values include the following: * * long versionNumber -- version number to represent the version of the registration model used * * list<Registration> archiveList -- historical list of all version changes; * when a change is made the full details are stored here prior to change * * * String modifiedBy -- user whom modified registration last, e.g. initiator, staff. * By default its initiator unless login mechanic provided * */ /** * This empty default constructor is needed for JSON to be happy. The alternative is add * "@JsonProperty("id")" in-front of the "long id" definition in the fully qualified constructor */ public MetaData() { } public MetaData(Date dateRegistered, String anotherString, RouteType route) { this.dateRegistered = dateRegistered; this.anotherString = anotherString; this.lastModified = dateRegistered; this.dateActivated = null; //The initial status is PENDING for most new registrations. this.status = RegistrationStatus.PENDING; this.route = route; } public Date getDateRegistered() { return dateRegistered; } public String getAnotherString() { return anotherString; } /** * @return the lastModified */ public Date getLastModified() { return lastModified; } /** * @return the dateActivated */ public Date getDateActivated() { return dateActivated; } /** * @return the status */ public RegistrationStatus getStatus() { return status; } /** * @return the revokedReason */ public String getRevokedReason() { return revokedReason; } /** * @return the route */ public RouteType getRoute() { return route; } /** * @return the distance */ public String getDistance() { return distance; } public static Date getCurrentDateTime() { //@SamGriffiths [20150127]- changed the formats of all Dates to Date rather than String Date date = new Date(); return date; } /** * @param dateRegistered the dateRegistered to set */ public void setDateRegistered(Date dateRegistered) { this.dateRegistered = dateRegistered; } /** * @param anotherString the anotherString to set */ public void setAnotherString(String anotherString) { this.anotherString = anotherString; } /** * @param lastModified the lastModified to set */ public void setLastModified(Date lastModified) { this.lastModified = lastModified; } /** * @param dateActivated the dateActivated to set */ public void setDateActivated(Date dateActivated) { this.dateActivated = dateActivated; } /** * @param status the status to set */ public void setStatus(RegistrationStatus status) { this.status = status; } /** * @param revokedReason the revokedReason to set */ public void setRevokedReason(String revokedReason) { this.revokedReason = revokedReason; } /** * @param route the route to set */ public void setRoute(RouteType route) { this.route = route; } /** * @param distance the distance to set */ public void setDistance(String distance) { this.distance = distance; } }
9242f8fb695f6ca9accf7a4d9ab676aecec5889c
322
java
Java
src/main/java/factoid/web/ConverterException.java
PathwayCommons/factoid-biopax-services
fd685d7400e2c17145c90c5da1044d7a1ff8fa46
[ "MIT" ]
2
2018-09-21T09:37:56.000Z
2021-03-30T10:12:03.000Z
src/main/java/factoid/web/ConverterException.java
PathwayCommons/factoid-biopax-services
fd685d7400e2c17145c90c5da1044d7a1ff8fa46
[ "MIT" ]
17
2018-09-21T17:56:51.000Z
2021-03-23T17:42:43.000Z
src/main/java/factoid/web/ConverterException.java
PathwayCommons/factoid-biopax-services
fd685d7400e2c17145c90c5da1044d7a1ff8fa46
[ "MIT" ]
2
2019-01-21T22:02:10.000Z
2021-03-30T10:12:08.000Z
18.941176
58
0.742236
1,002,482
package factoid.web; import org.springframework.http.HttpStatus; public class ConverterException extends RuntimeException { private final HttpStatus status; ConverterException(HttpStatus status, String msg) { super(msg); this.status = status; } public HttpStatus getStatus() { return status; } }
9242fae662b99a4a70d7bac593dee5a3da1c7837
754
java
Java
src/main/java/at/asdf00/avaplus/objects/items/ItemBase.java
00asdf/AvaPlus
c1772ea3763df83d02f5d93e2abc09c62bc7f640
[ "BSD-3-Clause" ]
null
null
null
src/main/java/at/asdf00/avaplus/objects/items/ItemBase.java
00asdf/AvaPlus
c1772ea3763df83d02f5d93e2abc09c62bc7f640
[ "BSD-3-Clause" ]
null
null
null
src/main/java/at/asdf00/avaplus/objects/items/ItemBase.java
00asdf/AvaPlus
c1772ea3763df83d02f5d93e2abc09c62bc7f640
[ "BSD-3-Clause" ]
null
null
null
27.925926
62
0.730769
1,002,483
package at.asdf00.avaplus.objects.items; import at.asdf00.avaplus.Main; import at.asdf00.avaplus.init.ItemInit; import at.asdf00.avaplus.util.IHasModel; import morph.avaritia.Avaritia; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.util.ResourceLocation; public class ItemBase extends Item implements IHasModel { public ItemBase(String name, int maxStackSize) { setRegistryName(name); setUnlocalizedName(name); setMaxDamage(0); setCreativeTab(Avaritia.tab); setMaxStackSize(maxStackSize); ItemInit.ITEM_LIST.add(this); } @Override public void registerModels() { Main.proxy.registerItemRenderer(this, 0, "inventory"); } }
9242fb42fcc10a3ce346f7ec8c229a582a8298f2
13,192
java
Java
hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/OperationMethodBinding.java
shvoidlee/hapi-fhir
26e2e2527d5f9fe3a2ea7e2cc19e95cfa5a8026d
[ "Apache-2.0" ]
1
2016-06-29T06:00:16.000Z
2016-06-29T06:00:16.000Z
hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/OperationMethodBinding.java
shvoidlee/hapi-fhir
26e2e2527d5f9fe3a2ea7e2cc19e95cfa5a8026d
[ "Apache-2.0" ]
null
null
null
hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/OperationMethodBinding.java
shvoidlee/hapi-fhir
26e2e2527d5f9fe3a2ea7e2cc19e95cfa5a8026d
[ "Apache-2.0" ]
null
null
null
34.354167
276
0.741813
1,002,484
package ca.uhn.fhir.rest.method; /* * #%L * HAPI FHIR - Core Library * %% * Copyright (C) 2014 - 2015 University Health Network * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import static org.apache.commons.lang3.StringUtils.isBlank; import static org.apache.commons.lang3.StringUtils.isNotBlank; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.hl7.fhir.instance.model.api.IBase; import org.hl7.fhir.instance.model.api.IBaseDatatype; import org.hl7.fhir.instance.model.api.IBaseParameters; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IPrimitiveType; import ca.uhn.fhir.context.ConfigurationException; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.context.FhirVersionEnum; import ca.uhn.fhir.model.api.Bundle; import ca.uhn.fhir.model.api.annotation.Description; import ca.uhn.fhir.model.primitive.IdDt; import ca.uhn.fhir.model.valueset.BundleTypeEnum; import ca.uhn.fhir.rest.annotation.IdParam; import ca.uhn.fhir.rest.annotation.Operation; import ca.uhn.fhir.rest.annotation.OperationParam; import ca.uhn.fhir.rest.api.RequestTypeEnum; import ca.uhn.fhir.rest.api.RestOperationTypeEnum; import ca.uhn.fhir.rest.client.BaseHttpClientInvocation; import ca.uhn.fhir.rest.server.IBundleProvider; import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import ca.uhn.fhir.rest.server.exceptions.MethodNotAllowedException; import ca.uhn.fhir.util.FhirTerser; public class OperationMethodBinding extends BaseResourceReturningMethodBinding { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(OperationMethodBinding.class); private boolean myCanOperateAtInstanceLevel; private boolean myCanOperateAtServerLevel; private String myDescription; private final boolean myIdempotent; private final Integer myIdParamIndex; private final String myName; private final RestOperationTypeEnum myOtherOperatiopnType; private List<ReturnType> myReturnParams; private final ReturnTypeEnum myReturnType; private boolean myCanOperateAtTypeLevel; protected OperationMethodBinding(Class<?> theReturnResourceType, Class<? extends IBaseResource> theReturnTypeFromRp, Method theMethod, FhirContext theContext, Object theProvider, boolean theIdempotent, String theOperationName, Class<? extends IBaseResource> theOperationType, OperationParam[] theReturnParams) { super(theReturnResourceType, theMethod, theContext, theProvider); myIdempotent = theIdempotent; myIdParamIndex = MethodUtil.findIdParameterIndex(theMethod); if (myIdParamIndex != null) { for (Annotation next : theMethod.getParameterAnnotations()[myIdParamIndex]) { if (next instanceof IdParam) { myCanOperateAtTypeLevel = ((IdParam) next).optional() == true; } } } else { myCanOperateAtTypeLevel = true; } Description description = theMethod.getAnnotation(Description.class); if (description != null) { myDescription = description.formalDefinition(); if (isBlank(myDescription)) { myDescription = description.shortDefinition(); } } if (isBlank(myDescription)) { myDescription = null; } if (isBlank(theOperationName)) { throw new ConfigurationException("Method '" + theMethod.getName() + "' on type " + theMethod.getDeclaringClass().getName() + " is annotated with @" + Operation.class.getSimpleName() + " but this annotation has no name defined"); } if (theOperationName.startsWith("$") == false) { theOperationName = "$" + theOperationName; } myName = theOperationName; if (theContext.getVersion().getVersion().isEquivalentTo(FhirVersionEnum.DSTU1)) { throw new ConfigurationException("@" + Operation.class.getSimpleName() + " methods are not supported on servers for FHIR version " + theContext.getVersion().getVersion().name()); } if (theReturnTypeFromRp != null) { setResourceName(theContext.getResourceDefinition(theReturnTypeFromRp).getName()); } else { if (Modifier.isAbstract(theOperationType.getModifiers()) == false) { setResourceName(theContext.getResourceDefinition(theOperationType).getName()); } else { setResourceName(null); } } if (theMethod.getReturnType().isAssignableFrom(Bundle.class)) { throw new ConfigurationException("Can not return a DSTU1 bundle from an @" + Operation.class.getSimpleName() + " method. Found in method " + theMethod.getName() + " defined in type " + theMethod.getDeclaringClass().getName()); } if (theMethod.getReturnType().equals(IBundleProvider.class)) { myReturnType = ReturnTypeEnum.BUNDLE; } else { myReturnType = ReturnTypeEnum.RESOURCE; } if (getResourceName() == null) { myOtherOperatiopnType = RestOperationTypeEnum.EXTENDED_OPERATION_SERVER; } else if (myIdParamIndex == null) { myOtherOperatiopnType = RestOperationTypeEnum.EXTENDED_OPERATION_TYPE; } else { myOtherOperatiopnType = RestOperationTypeEnum.EXTENDED_OPERATION_INSTANCE; } myReturnParams = new ArrayList<OperationMethodBinding.ReturnType>(); if (theReturnParams != null) { for (OperationParam next : theReturnParams) { ReturnType type = new ReturnType(); type.setName(next.name()); type.setMin(next.min()); type.setMax(next.max()); if (!next.type().equals(IBase.class)) { if (next.type().isInterface() || Modifier.isAbstract(next.type().getModifiers())) { throw new ConfigurationException("Invalid value for @OperationParam.type(): " + next.type().getName()); } type.setType(theContext.getElementDefinition(next.type()).getName()); } myReturnParams.add(type); } } if (myIdParamIndex != null) { myCanOperateAtInstanceLevel = true; } if (getResourceName() == null) { myCanOperateAtServerLevel = true; } } public OperationMethodBinding(Class<?> theReturnResourceType, Class<? extends IBaseResource> theReturnTypeFromRp, Method theMethod, FhirContext theContext, Object theProvider, Operation theAnnotation) { this(theReturnResourceType, theReturnTypeFromRp, theMethod, theContext, theProvider, theAnnotation.idempotent(), theAnnotation.name(), theAnnotation.type(), theAnnotation.returnParameters()); } public String getDescription() { return myDescription; } /** * Returns the name of the operation, starting with "$" */ public String getName() { return myName; } @Override public RestOperationTypeEnum getRestOperationType() { return myOtherOperatiopnType; } @Override protected BundleTypeEnum getResponseBundleType() { return BundleTypeEnum.COLLECTION; } public List<ReturnType> getReturnParams() { return Collections.unmodifiableList(myReturnParams); } @Override public ReturnTypeEnum getReturnType() { return myReturnType; } @Override public boolean incomingServerRequestMatchesMethod(RequestDetails theRequest) { if (getResourceName() == null) { if (isNotBlank(theRequest.getResourceName())) { return false; } } else if (!getResourceName().equals(theRequest.getResourceName())) { return false; } if (!myName.equals(theRequest.getOperation())) { return false; } boolean requestHasId = theRequest.getId() != null; if (requestHasId) { if (isCanOperateAtInstanceLevel() == false) { return false; } } else { if (myCanOperateAtTypeLevel == false) { return false; } } return true; } @Override public BaseHttpClientInvocation invokeClient(Object[] theArgs) throws InternalErrorException { String id = null; if (myIdParamIndex != null) { IdDt idDt = (IdDt) theArgs[myIdParamIndex]; id = idDt.getValue(); } IBaseParameters parameters = (IBaseParameters) getContext().getResourceDefinition("Parameters").newInstance(); if (theArgs != null) { for (int idx = 0; idx < theArgs.length; idx++) { IParameter nextParam = getParameters().get(idx); nextParam.translateClientArgumentIntoQueryArgument(getContext(), theArgs[idx], null, parameters); } } return createOperationInvocation(getContext(), getResourceName(), id, myName, parameters, false); } @Override public Object invokeServer(RestfulServer theServer, RequestDetails theRequest, Object[] theMethodParams) throws BaseServerResponseException { if (theRequest.getRequestType() == RequestTypeEnum.POST) { // always ok } else if (theRequest.getRequestType() == RequestTypeEnum.GET) { if (!myIdempotent) { String message = getContext().getLocalizer().getMessage(OperationMethodBinding.class, "methodNotSupported", theRequest.getRequestType(), RequestTypeEnum.POST.name()); throw new MethodNotAllowedException(message, RequestTypeEnum.POST); } } else { if (!myIdempotent) { String message = getContext().getLocalizer().getMessage(OperationMethodBinding.class, "methodNotSupported", theRequest.getRequestType(), RequestTypeEnum.POST.name()); throw new MethodNotAllowedException(message, RequestTypeEnum.POST); } else { String message = getContext().getLocalizer().getMessage(OperationMethodBinding.class, "methodNotSupported", theRequest.getRequestType(), RequestTypeEnum.GET.name(), RequestTypeEnum.POST.name()); throw new MethodNotAllowedException(message, RequestTypeEnum.GET, RequestTypeEnum.POST); } } if (myIdParamIndex != null) { theMethodParams[myIdParamIndex] = theRequest.getId(); } Object response = invokeServerMethod(theServer, theRequest, theMethodParams); IBundleProvider retVal = toResourceList(response); return retVal; } public boolean isCanOperateAtInstanceLevel() { return this.myCanOperateAtInstanceLevel; } public boolean isCanOperateAtServerLevel() { return this.myCanOperateAtServerLevel; } public boolean isIdempotent() { return myIdempotent; } public void setDescription(String theDescription) { myDescription = theDescription; } public static BaseHttpClientInvocation createOperationInvocation(FhirContext theContext, String theResourceName, String theId, String theOperationName, IBaseParameters theInput, boolean theUseHttpGet) { StringBuilder b = new StringBuilder(); if (theResourceName != null) { b.append(theResourceName); if (isNotBlank(theId)) { b.append('/'); b.append(theId); } } if (b.length() > 0) { b.append('/'); } if (!theOperationName.startsWith("$")) { b.append("$"); } b.append(theOperationName); if (!theUseHttpGet) { return new HttpPostClientInvocation(theContext, theInput, b.toString()); } else { FhirTerser t = theContext.newTerser(); List<Object> parameters = t.getValues(theInput, "Parameters.parameter"); Map<String, List<String>> params = new LinkedHashMap<String, List<String>>(); for (Object nextParameter : parameters) { IPrimitiveType<?> nextNameDt = (IPrimitiveType<?>) t.getSingleValueOrNull((IBase) nextParameter, "name"); if (nextNameDt == null || nextNameDt.isEmpty()) { ourLog.warn("Ignoring input parameter with no value in Parameters.parameter.name in operation client invocation"); continue; } String nextName = nextNameDt.getValueAsString(); if (!params.containsKey(nextName)) { params.put(nextName, new ArrayList<String>()); } IBaseDatatype value = (IBaseDatatype) t.getSingleValueOrNull((IBase) nextParameter, "value[x]"); if (value == null) { continue; } if (!(value instanceof IPrimitiveType)) { throw new IllegalArgumentException("Can not invoke operation as HTTP GET when it has parameters with a composite (non priitive) datatype as the value. Found value: " + value.getClass().getName()); } IPrimitiveType<?> primitive = (IPrimitiveType<?>) value; params.get(nextName).add(primitive.getValueAsString()); } return new HttpGetClientInvocation(params, b.toString()); } } public static class ReturnType { private int myMax; private int myMin; private String myName; /** * http://hl7-fhir.github.io/valueset-operation-parameter-type.html */ private String myType; public int getMax() { return myMax; } public int getMin() { return myMin; } public String getName() { return myName; } public String getType() { return myType; } public void setMax(int theMax) { myMax = theMax; } public void setMin(int theMin) { myMin = theMin; } public void setName(String theName) { myName = theName; } public void setType(String theType) { myType = theType; } } }
9242fb694be56a73eb3d7347c5cf59adc157250f
1,633
java
Java
src/main/java/com/safaribot/Application.java
SammieAce/safaribot
3e5aa0ef50687d2f03f61f9b9a8333e043b043c0
[ "Unlicense" ]
null
null
null
src/main/java/com/safaribot/Application.java
SammieAce/safaribot
3e5aa0ef50687d2f03f61f9b9a8333e043b043c0
[ "Unlicense" ]
null
null
null
src/main/java/com/safaribot/Application.java
SammieAce/safaribot
3e5aa0ef50687d2f03f61f9b9a8333e043b043c0
[ "Unlicense" ]
null
null
null
28.649123
81
0.676056
1,002,485
package com.safaribot; import org.alicebot.ab.Bot; import org.alicebot.ab.Chat; import org.alicebot.ab.configuration.BotConfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; /** * The entry point of the Spring Boot application. */ @SpringBootApplication public class Application extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(Application.class, args); } /*share bot instance with all views*/ @Bean public Bot alice() { return new Bot(BotConfiguration.builder() .name("alice") .path("src/main/resources") .build() ); } @Bean public ScheduledExecutorService executorService() { return Executors.newScheduledThreadPool(2); } private final Chat chatSession; /* creating a bot and chat object. */ public Application() { BotConfiguration botConfiguration = BotConfiguration.builder() .name("alice") .path("src/main/resources") .build(); Bot bot = new Bot(botConfiguration); chatSession = new Chat(bot); } /*getting an answer*/ public String answer(String message) { return chatSession.multisentenceRespond(message); } }
9242fbda30835a94ea5a823c5affc91abea9f2f0
2,348
java
Java
mvvmfx-testing-utils/src/main/java/de/saxsys/mvvmfx/testingutils/GCVerifier.java
guilhermejccavalcanti/mvvmFX
6f8ed3f92e5df381fce10dea76f8190726f8926c
[ "Apache-2.0" ]
460
2015-01-19T16:32:11.000Z
2022-03-16T11:03:21.000Z
mvvmfx-testing-utils/src/main/java/de/saxsys/mvvmfx/testingutils/GCVerifier.java
guilhermejccavalcanti/mvvmFX
6f8ed3f92e5df381fce10dea76f8190726f8926c
[ "Apache-2.0" ]
322
2015-01-04T19:56:56.000Z
2022-03-02T01:41:03.000Z
mvvmfx-testing-utils/src/main/java/de/saxsys/mvvmfx/testingutils/GCVerifier.java
guilhermejccavalcanti/mvvmFX
6f8ed3f92e5df381fce10dea76f8190726f8926c
[ "Apache-2.0" ]
148
2015-01-08T18:40:12.000Z
2022-03-14T15:26:34.000Z
25.521739
116
0.684412
1,002,486
package de.saxsys.mvvmfx.testingutils; import java.lang.ref.WeakReference; /** * This is a small testing helper to verify that a given object is available for Garbage Collection. * * The typical usage is: * * <pre> * Object testObject = new Object(); * * GCVerifier verifier = GCVerifier.create(testObject); * * * testObject = null; // now there is no reference to the object anymore so it should be available for GC * * * verifier.verify(); // this will throw an AssertionError if there is still a reference to the object somewhere * </pre> * */ public class GCVerifier { private final WeakReference reference; private final String objectName; GCVerifier(WeakReference reference, String objectName) { this.reference = reference; this.objectName = objectName; } /** * Create a Verifier instance for the given Object. No hard reference to this object is stored internally. * * @param instance * the instance that is verified. * * @return an instance of the {@link GCVerifier} that can be used to verify the garbage collection of the given * instance. */ @SuppressWarnings("unchecked") public static GCVerifier create(Object instance) { return new GCVerifier(new WeakReference(instance), instance.toString()); } public void verify(String message) { forceGC(); if (!isAvailableForGC()) { throw new AssertionError(message); } } /** * @return <code>true</code> if the object is available */ public boolean isAvailableForGC() { forceGC(); return reference.get() == null; } public void verify() { verify("Expected the given object [" + objectName + "] to be available for Garbage Collection but it isn't"); } /** * This method can be used to "force" the garbage collection. * * This can be useful because with "System.gc()" you can't tell if the GC was actually done. * * * This method will only return when the GC was done. <strong>Be careful</strong>: This method will block until the * GC was done so when for some reason the java runtime doesn't run the GC your application won't continue. */ @SuppressWarnings("unchecked") public static void forceGC() { Object o = new Object(); WeakReference ref = new WeakReference(o); o = null; while (ref.get() != null) { System.gc(); } } }
9242fdf6fdd4cec13c18467806f786ea81806aff
674
java
Java
basics-ctest/src/main/java/com/boot/basics/coding/proxy/cglib/HelloInterceptor.java
cherrishccl/CodingBasics
8c443a1266fbc41dde3889d8ae7c64014ec46772
[ "MIT" ]
null
null
null
basics-ctest/src/main/java/com/boot/basics/coding/proxy/cglib/HelloInterceptor.java
cherrishccl/CodingBasics
8c443a1266fbc41dde3889d8ae7c64014ec46772
[ "MIT" ]
null
null
null
basics-ctest/src/main/java/com/boot/basics/coding/proxy/cglib/HelloInterceptor.java
cherrishccl/CodingBasics
8c443a1266fbc41dde3889d8ae7c64014ec46772
[ "MIT" ]
null
null
null
29.304348
107
0.698813
1,002,487
package com.boot.basics.coding.proxy.cglib; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; import java.lang.reflect.Method; /** * @Author cherrishccl * @Date 2020/8/14 14:16 * @Version 1.0 * @Description */ public class HelloInterceptor implements MethodInterceptor { @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { System.out.println("start time -----> "+ System.currentTimeMillis()); Object result = proxy.invokeSuper(obj, args); System.out.println("end time -----> "+ System.currentTimeMillis()); return result; } }
9242fe68ee2fb677c744a7242c631ae3976aaaf4
1,224
java
Java
app/src/main/java/edu/scse/nehelper/NewsDisplayActivity.java
caoyuanzhao/nehelper
14fd43dc326236aec4bdd3eee0c3462c1e0aae15
[ "Apache-2.0" ]
null
null
null
app/src/main/java/edu/scse/nehelper/NewsDisplayActivity.java
caoyuanzhao/nehelper
14fd43dc326236aec4bdd3eee0c3462c1e0aae15
[ "Apache-2.0" ]
null
null
null
app/src/main/java/edu/scse/nehelper/NewsDisplayActivity.java
caoyuanzhao/nehelper
14fd43dc326236aec4bdd3eee0c3462c1e0aae15
[ "Apache-2.0" ]
null
null
null
30.6
82
0.675654
1,002,488
package edu.scse.nehelper; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.TextView; public class NewsDisplayActivity extends Activity implements View.OnClickListener{ private String newsUrl; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_display_news); newsUrl = getIntent().getStringExtra("news_url"); WebView webView = (WebView) findViewById(R.id.web_view); webView.getSettings().setJavaScriptEnabled(true); webView.setWebViewClient(new WebViewClient()); webView.loadUrl(newsUrl); TextView textView = (TextView) findViewById(R.id.title_text); textView.setText("动态详情"); Button back_button = (Button) findViewById(R.id.back_button); back_button.setOnClickListener(this); } public void onClick(View v) { switch (v.getId()) { case R.id.back_button: finish(); break; default:break; } } }
9242ff9ac4fdb7f37cf9c669dcb3cfff77e2c807
4,901
java
Java
dl4j-examples/src/main/java/org/deeplearning4j/examples/convolution/LenetMnistExample.java
adiel2012/MiDeepLerning4J
47c251824c50477483cc7f74e972783b32fdecc1
[ "Apache-2.0" ]
1
2018-02-18T08:44:05.000Z
2018-02-18T08:44:05.000Z
dl4j-examples/src/main/java/org/deeplearning4j/examples/convolution/LenetMnistExample.java
adiel2012/MiDeepLerning4J
47c251824c50477483cc7f74e972783b32fdecc1
[ "Apache-2.0" ]
null
null
null
dl4j-examples/src/main/java/org/deeplearning4j/examples/convolution/LenetMnistExample.java
adiel2012/MiDeepLerning4J
47c251824c50477483cc7f74e972783b32fdecc1
[ "Apache-2.0" ]
null
null
null
44.554545
129
0.609059
1,002,489
package org.deeplearning4j.examples.convolution; import org.deeplearning4j.datasets.iterator.impl.MnistDataSetIterator; import org.deeplearning4j.eval.Evaluation; import org.deeplearning4j.nn.api.OptimizationAlgorithm; import org.deeplearning4j.nn.conf.MultiLayerConfiguration; import org.deeplearning4j.nn.conf.NeuralNetConfiguration; import org.deeplearning4j.nn.conf.Updater; import org.deeplearning4j.nn.conf.layers.ConvolutionLayer; import org.deeplearning4j.nn.conf.layers.DenseLayer; import org.deeplearning4j.nn.conf.layers.OutputLayer; import org.deeplearning4j.nn.conf.layers.SubsamplingLayer; import org.deeplearning4j.nn.conf.layers.setup.ConvolutionLayerSetup; import org.deeplearning4j.nn.multilayer.MultiLayerNetwork; import org.deeplearning4j.nn.weights.WeightInit; import org.deeplearning4j.optimize.listeners.ScoreIterationListener; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.dataset.DataSet; import org.nd4j.linalg.dataset.api.iterator.DataSetIterator; import org.nd4j.linalg.lossfunctions.LossFunctions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; //import org.deeplearning4j.nn.conf.LearningRatePolicy; /** * Created by agibsonccc on 9/16/15. */ public class LenetMnistExample { private static final Logger log = LoggerFactory.getLogger(LenetMnistExample.class); public static void main(String[] args) throws Exception { int nChannels = 1; int outputNum = 10; int batchSize = 64; int nEpochs = 10; int iterations = 1; int seed = 123; log.info("Load data...."); DataSetIterator mnistTrain = new MnistDataSetIterator(batchSize,true,12345); DataSetIterator mnistTest = new MnistDataSetIterator(batchSize,false,12345); log.info("Build model...."); MultiLayerConfiguration.Builder builder = new NeuralNetConfiguration.Builder() .seed(seed) .iterations(iterations) .regularization(true).l2(0.0005) .learningRate(0.01)//.biasLearningRate(0.02) //.learningRateDecayPolicy(LearningRatePolicy.Inverse).lrPolicyDecayRate(0.001).lrPolicyPower(0.75) .weightInit(WeightInit.XAVIER) .optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT) .updater(Updater.NESTEROVS).momentum(0.9) .list() .layer(0, new ConvolutionLayer.Builder(5, 5) //nIn and nOut specify depth. nIn here is the nChannels and nOut is the number of filters to be applied .nIn(nChannels) .stride(1, 1) .nOut(20) .activation("identity") .build()) .layer(1, new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX) .kernelSize(2,2) .stride(2,2) .build()) .layer(2, new ConvolutionLayer.Builder(5, 5) //Note that nIn need not be specified in later layers .stride(1, 1) .nOut(50) .activation("identity") .build()) .layer(3, new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX) .kernelSize(2,2) .stride(2,2) .build()) .layer(4, new DenseLayer.Builder().activation("relu") .nOut(500).build()) .layer(5, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD) .nOut(outputNum) .activation("softmax") .build()) .backprop(true).pretrain(false); // The builder needs the dimensions of the image along with the number of channels. these are 28x28 images in one channel new ConvolutionLayerSetup(builder,28,28,1); MultiLayerConfiguration conf = builder.build(); MultiLayerNetwork model = new MultiLayerNetwork(conf); model.init(); log.info("Train model...."); model.setListeners(new ScoreIterationListener(1)); for( int i=0; i<nEpochs; i++ ) { model.fit(mnistTrain); log.info("*** Completed epoch {} ***", i); log.info("Evaluate model...."); Evaluation eval = new Evaluation(outputNum); while(mnistTest.hasNext()){ DataSet ds = mnistTest.next(); INDArray output = model.output(ds.getFeatureMatrix(), false); eval.eval(ds.getLabels(), output); } log.info(eval.stats()); mnistTest.reset(); } log.info("****************Example finished********************"); } }
924300491c13545f5448e3582d4358eb6f6ac84e
4,540
java
Java
src/main/java/com/palmelf/eoffice/model/admin/GoodsApply.java
ywtnhm/joffice
f6348275832f3b062304cfc71af76caceeebf61e
[ "Apache-2.0" ]
null
null
null
src/main/java/com/palmelf/eoffice/model/admin/GoodsApply.java
ywtnhm/joffice
f6348275832f3b062304cfc71af76caceeebf61e
[ "Apache-2.0" ]
null
null
null
src/main/java/com/palmelf/eoffice/model/admin/GoodsApply.java
ywtnhm/joffice
f6348275832f3b062304cfc71af76caceeebf61e
[ "Apache-2.0" ]
null
null
null
26.091954
106
0.736123
1,002,490
package com.palmelf.eoffice.model.admin; import java.sql.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Transient; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import com.palmelf.core.model.BaseModel; @Entity @Table(name = "goods_apply") public class GoodsApply extends BaseModel { /** * */ private static final long serialVersionUID = -4754768018318356354L; public static Short PASS_APPLY = 1; public static Short NOTPASS_APPLY = 2; public static Short INIT_APPLY = 0; private Long applyId; private Date applyDate; private String applyNo; private Integer useCounts; private String proposer; private Long userId; private String notes; private Short approvalStatus; private OfficeGoods officeGoods; public GoodsApply() { } public GoodsApply(Long in_applyId) { this.setApplyId(in_applyId); } @Transient public Long getGoodsId() { return this.getOfficeGoods() == null ? null : this.getOfficeGoods().getGoodsId(); } public void setGoodsId(Long aValue) { if (aValue == null) { this.officeGoods = null; } else if (this.officeGoods == null) { this.officeGoods = new OfficeGoods(aValue); this.officeGoods.setVersion(new Integer(0)); } else { this.officeGoods.setGoodsId(aValue); } } @Id @GeneratedValue @Column(name = "applyId", unique = true, nullable = false) public Long getApplyId() { return this.applyId; } public void setApplyId(Long applyId) { this.applyId = applyId; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "goodsId") public OfficeGoods getOfficeGoods() { return this.officeGoods; } public void setOfficeGoods(OfficeGoods officeGoods) { this.officeGoods = officeGoods; } @Column(name = "applyDate", nullable = false, length = 19) public Date getApplyDate() { return this.applyDate; } public void setApplyDate(Date applyDate) { this.applyDate = applyDate; } @Column(name = "userId", nullable = false) public Long getUserId() { return this.userId; } public void setUserId(Long userId) { this.userId = userId; } @Column(name = "applyNo", nullable = false, length = 128) public String getApplyNo() { return this.applyNo; } public void setApplyNo(String applyNo) { this.applyNo = applyNo; } @Column(name = "useCounts", nullable = false) public Integer getUseCounts() { return this.useCounts; } public void setUseCounts(Integer useCounts) { this.useCounts = useCounts; } @Column(name = "proposer", nullable = false, length = 32) public String getProposer() { return this.proposer; } public void setProposer(String proposer) { this.proposer = proposer; } @Column(name = "notes", length = 500) public String getNotes() { return this.notes; } public void setNotes(String notes) { this.notes = notes; } @Column(name = "approvalStatus", nullable = false) public Short getApprovalStatus() { return this.approvalStatus; } public void setApprovalStatus(Short approvalStatus) { this.approvalStatus = approvalStatus; } @Override public boolean equals(Object object) { if (!(object instanceof GoodsApply)) { return false; } GoodsApply rhs = (GoodsApply) object; return new EqualsBuilder().append(this.applyId, rhs.applyId).append(this.applyDate, rhs.applyDate) .append(this.applyNo, rhs.applyNo).append(this.useCounts, rhs.useCounts) .append(this.userId, rhs.userId).append(this.proposer, rhs.proposer).append(this.notes, rhs.notes) .append(this.approvalStatus, rhs.approvalStatus).isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(-82280557, -700257973).append(this.applyId).append(this.applyDate) .append(this.applyNo).append(this.useCounts).append(this.proposer).append(this.userId) .append(this.notes).append(this.approvalStatus).toHashCode(); } @Override public String toString() { return new ToStringBuilder(this).append("applyId", this.applyId).append("applyDate", this.applyDate) .append("applyNo", this.applyNo).append("useCounts", this.useCounts).append("proposer", this.proposer) .append("userId", this.userId).append("notes", this.notes) .append("approvalStatus", this.approvalStatus).toString(); } }
9243015f4beecb16fa049496bb8af89c18924561
26,309
java
Java
src/main/java/com/heliosapm/utils/jmx/JMXManagedThreadPool.java
nickman/heliosutils
62b3faa9987c91a07d3f89fcc2f1f841f08a2fe9
[ "Apache-2.0" ]
null
null
null
src/main/java/com/heliosapm/utils/jmx/JMXManagedThreadPool.java
nickman/heliosutils
62b3faa9987c91a07d3f89fcc2f1f841f08a2fe9
[ "Apache-2.0" ]
null
null
null
src/main/java/com/heliosapm/utils/jmx/JMXManagedThreadPool.java
nickman/heliosutils
62b3faa9987c91a07d3f89fcc2f1f841f08a2fe9
[ "Apache-2.0" ]
null
null
null
36.540278
253
0.712114
1,002,491
/** Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.heliosapm.utils.jmx; import java.lang.Thread.UncaughtExceptionHandler; import java.lang.management.ManagementFactory; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import javax.management.ObjectName; import com.heliosapm.utils.config.ConfigurationHelper; /** * <p>Title: JMXManagedThreadPool</p> * <p>Description: A JMX managed worker pool</p> * <p>Company: Helios Development Group LLC</p> * @author Whitehead (nwhitehead AT heliosdev DOT org) * <p><code>com.heliosapm.jmx.concurrency.JMXManagedThreadPool</code></p> */ public class JMXManagedThreadPool extends ThreadPoolExecutor implements ThreadFactory, RejectedExecutionHandler, UncaughtExceptionHandler, JMXManagedThreadPoolMBean { /** The JMX ObjectName for this pool's MBean */ protected final ObjectName objectName; /** The pool name */ protected final String poolName; /** The task work queue */ protected final BlockingQueue<Runnable> workQueue; /** The count of uncaught exceptions */ protected final AtomicLong uncaughtExceptionCount = new AtomicLong(0L); /** The count of rejected executions where the task queue was full and a new task could not be accepted */ protected final AtomicLong rejectedExecutionCount = new AtomicLong(0L); /** The thread group that threads created for this pool are created in */ protected final ThreadGroup threadGroup; /** The thread factory thread serial number factory */ protected final AtomicInteger threadSerial = new AtomicInteger(0); /** Threadlocal to hold the start time of a given task */ protected final ThreadLocal<long[]> taskStartTime = new ThreadLocal<long[]>() { @Override protected long[] initialValue() { return new long[1]; } }; /** An externally added exception handler */ protected UncaughtExceptionHandler exceptionHandler = null; /** * Creates a new JMXManagedThreadPool, reading all the configuration values from Config and publishes the JMX interface * @param objectName The JMX ObjectName for this pool's MBean * @param poolName The pool name */ public JMXManagedThreadPool(ObjectName objectName, String poolName) { this(objectName, poolName, true); } /** * Creates a new JMXManagedThreadPool, reading all the configuration values from Config * @param objectName The JMX ObjectName for this pool's MBean * @param poolName The pool name * @param publishJMX If true, publishes the JMX interface */ public JMXManagedThreadPool(ObjectName objectName, String poolName, boolean publishJMX) { this( objectName, poolName, ConfigurationHelper.getIntSystemThenEnvProperty(poolName.toLowerCase() + CONFIG_CORE_POOL_SIZE, DEFAULT_CORE_POOL_SIZE), ConfigurationHelper.getIntSystemThenEnvProperty(poolName.toLowerCase() + CONFIG_MAX_POOL_SIZE, DEFAULT_MAX_POOL_SIZE), ConfigurationHelper.getIntSystemThenEnvProperty(poolName.toLowerCase() + CONFIG_MAX_QUEUE_SIZE, DEFAULT_MAX_QUEUE_SIZE), ConfigurationHelper.getLongSystemThenEnvProperty(poolName.toLowerCase() + CONFIG_KEEP_ALIVE, DEFAULT_KEEP_ALIVE), ConfigurationHelper.getIntSystemThenEnvProperty(poolName.toLowerCase() + CONFIG_WINDOW_SIZE, DEFAULT_WINDOW_SIZE), ConfigurationHelper.getIntSystemThenEnvProperty(poolName.toLowerCase() + CONFIG_WINDOW_PERCENTILE, DEFAULT_WINDOW_PERCENTILE), publishJMX ); int prestart = ConfigurationHelper.getIntSystemThenEnvProperty(CONFIG_CORE_PRESTART, DEFAULT_CORE_PRESTART); for(int i = 0; i < prestart; i++) { prestartCoreThread(); } } /** * Creates a new JMXManagedThreadPool and publishes the JMX MBean management interface * @param objectName The JMX ObjectName for this pool's MBean * @param poolName The pool name * @param corePoolSize the number of threads to keep in the pool, even if they are idle. * @param maximumPoolSize the maximum number of threads to allow in the pool. * @param queueSize The maximum number of pending tasks to queue * @param keepAliveTimeMs when the number of threads is greater than the core, this is the maximum time in ms. that excess idle threads will wait for new tasks before terminating. * @param metricWindowSize The maximum size of the metrics sliding window * @param metricDefaultPercentile The default percentile reported in the metrics management */ public JMXManagedThreadPool(ObjectName objectName, String poolName, int corePoolSize, int maximumPoolSize, int queueSize, long keepAliveTimeMs, int metricWindowSize, int metricDefaultPercentile) { this(objectName, poolName, corePoolSize, maximumPoolSize, queueSize, keepAliveTimeMs, metricWindowSize, metricDefaultPercentile, true); } /** * Sets the thread pool's uncaught exception handler * @param exceptionHandler the handler to set */ public void setUncaughtExceptionHandler(final UncaughtExceptionHandler exceptionHandler) { if(exceptionHandler!=null) { this.exceptionHandler = exceptionHandler; } } /** * Creates a new JMXManagedThreadPool * @param objectName The JMX ObjectName for this pool's MBean * @param poolName The pool name * @param corePoolSize the number of threads to keep in the pool, even if they are idle. * @param maximumPoolSize the maximum number of threads to allow in the pool. * @param queueSize The maximum number of pending tasks to queue * @param keepAliveTimeMs when the number of threads is greater than the core, this is the maximum time in ms. that excess idle threads will wait for new tasks before terminating. * @param metricWindowSize The maximum size of the metrics sliding window * @param metricDefaultPercentile The default percentile reported in the metrics management * @param publishJMX If true, publishes the management interface */ public JMXManagedThreadPool(ObjectName objectName, String poolName, int corePoolSize, int maximumPoolSize, int queueSize, long keepAliveTimeMs, int metricWindowSize, int metricDefaultPercentile, boolean publishJMX) { this(null, objectName, poolName, corePoolSize, maximumPoolSize, queueSize, keepAliveTimeMs, metricWindowSize, metricDefaultPercentile, publishJMX); } /** * Creates a new JMXManagedThreadPool * @param threadFactory An optional thread factory to create this pool's threads * @param objectName The JMX ObjectName for this pool's MBean * @param poolName The pool name * @param corePoolSize the number of threads to keep in the pool, even if they are idle. * @param maximumPoolSize the maximum number of threads to allow in the pool. * @param queueSize The maximum number of pending tasks to queue * @param keepAliveTimeMs when the number of threads is greater than the core, this is the maximum time in ms. that excess idle threads will wait for new tasks before terminating. * @param metricWindowSize The maximum size of the metrics sliding window * @param metricDefaultPercentile The default percentile reported in the metrics management * @param publishJMX If true, publishes the management interface */ public JMXManagedThreadPool(final ThreadFactory threadFactory, ObjectName objectName, String poolName, int corePoolSize, int maximumPoolSize, int queueSize, long keepAliveTimeMs, int metricWindowSize, int metricDefaultPercentile, boolean publishJMX) { super(corePoolSize, maximumPoolSize, keepAliveTimeMs, TimeUnit.MILLISECONDS, queueSize==1 ? new SynchronousQueue<Runnable>() : new ArrayBlockingQueue<Runnable>(queueSize, false)); this.threadGroup = new ThreadGroup(poolName + "ThreadGroup"); setThreadFactory(threadFactory==null ? this : threadFactory); setRejectedExecutionHandler(this); this.objectName = objectName; this.poolName = poolName; workQueue = (BlockingQueue<Runnable>)getQueue(); if(publishJMX) { try { JMXHelper.getHeliosMBeanServer().registerMBean(this, objectName); } catch (Exception ex) { System.err.println("Failed to register JMX management interface. Will continue without:" + ex); } System.err.println("Created JMX Managed Thread Pool [" + poolName + "]"); } } /** * {@inheritDoc} * @see com.heliosapm.jmx.concurrency.JMXManagedThreadPoolMBean#getInstance() */ public JMXManagedThreadPool getInstance() { return this; } /** * {@inheritDoc} * @see java.util.concurrent.ThreadPoolExecutor#beforeExecute(java.lang.Thread, java.lang.Runnable) */ @Override protected void beforeExecute(Thread t, Runnable r) { taskStartTime.get()[0] = System.currentTimeMillis(); super.beforeExecute(t, r); } /** * {@inheritDoc} * @see java.util.concurrent.ThreadPoolExecutor#afterExecute(java.lang.Runnable, java.lang.Throwable) */ @Override protected void afterExecute(Runnable r, Throwable t) { if(t==null) { @SuppressWarnings("unused") // TODO: tabulate task elapsed times long elapsed = System.currentTimeMillis() - taskStartTime.get()[0]; } super.afterExecute(r, t); } /** * {@inheritDoc} * @see java.lang.Thread.UncaughtExceptionHandler#uncaughtException(java.lang.Thread, java.lang.Throwable) */ @Override public void uncaughtException(Thread t, Throwable e) { uncaughtExceptionCount.incrementAndGet(); System.err.println("Thread pool [" + this.poolName + "] handled uncaught exception on thread [" + t + "]:" + e); if(exceptionHandler!=null) { exceptionHandler.uncaughtException(t, e); } } /** * {@inheritDoc} * @see java.util.concurrent.RejectedExecutionHandler#rejectedExecution(java.lang.Runnable, java.util.concurrent.ThreadPoolExecutor) */ @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { rejectedExecutionCount.incrementAndGet(); System.err.println("Submitted execution task [" + r + "] was rejected by pool [" + this.poolName + "] due to a full task queue"); } /** * {@inheritDoc} * @see java.util.concurrent.ThreadFactory#newThread(java.lang.Runnable) */ @Override public Thread newThread(Runnable r) { Thread t = new Thread(threadGroup, r, poolName + "Thread#" + threadSerial.incrementAndGet()); t.setDaemon(true); return t; } /** * {@inheritDoc} * @see com.heliosapm.jmx.concurrency.JMXManagedThreadPoolMBean#getObjectName() */ @Override public ObjectName getObjectName() { return objectName; } /** * {@inheritDoc} * @see com.heliosapm.jmx.concurrency.JMXManagedThreadPoolMBean#getPoolName() */ @Override public String getPoolName() { return poolName; } /** * {@inheritDoc} * @see com.heliosapm.jmx.concurrency.JMXManagedThreadPoolMBean#getQueueDepth() */ @Override public int getQueueDepth() { return workQueue.size(); } /** * {@inheritDoc} * @see com.heliosapm.jmx.concurrency.JMXManagedThreadPoolMBean#getQueueCapacity() */ @Override public int getQueueCapacity() { return workQueue.remainingCapacity(); } /** * {@inheritDoc} * @see com.heliosapm.jmx.concurrency.JMXManagedThreadPoolMBean#getUncaughtExceptionCount() */ @Override public long getUncaughtExceptionCount() { return uncaughtExceptionCount.get(); } /** * {@inheritDoc} * @see com.heliosapm.jmx.concurrency.JMXManagedThreadPoolMBean#getRejectedExecutionCount() */ @Override public long getRejectedExecutionCount() { return rejectedExecutionCount.get(); } // /** // * {@inheritDoc} // * @see com.heliosapm.jmx.concurrency.JMXManagedThreadPoolMBean#getMetrics() // */ // @Override // public Map<String, Long> getMetrics() { // Map<String, Long> map = new TreeMap<String, Long>(); // for(Map.Entry<MetricType, Long> ex: metrics.getMetrics().entrySet()) { // map.put(ex.getKey().name(), ex.getValue()); // } // return map; // } // /** // * {@inheritDoc} // * @see com.heliosapm.jmx.concurrency.JMXManagedThreadPoolMBean#getMetricsTable() // */ // @Override // public String getMetricsTable() { // StringBuilder b = new StringBuilder(METRIC_TABLE_HEADER); // b.append("<tr>"); // b.append("<td>").append(poolName).append("</td>"); // for(Map.Entry<String, Long> ex: getMetrics().entrySet()) { // b.append("<td>").append(ex.getValue()).append("</td>"); // } // b.append("</tr>"); // return b.append("</table>").toString(); // } /** * {@inheritDoc} * @see com.heliosapm.jmx.concurrency.JMXManagedThreadPoolMBean#getExecutingTaskCount() */ @Override public long getExecutingTaskCount() { return getTaskCount()-getCompletedTaskCount(); } public void execute(Runnable r) { super.execute(r); } /** * {@inheritDoc} * @see java.util.concurrent.AbstractExecutorService#submit(java.lang.Runnable) */ @Override public Future<?> submit(Runnable task) { return super.submit(task); } /** * Executes a runnable task asynchronously, optionally executing the passed pre and post tasks before and after respectively. * @param task The main task to execute * @param preTask The optional pre-task to execute before the main task. Ignored if null. * @param postTask The optional post-task to execute after the main task. Ignored if null. * @param handler An optional uncaught exception handler, registered with the executing thread for this task. Ignored if null. * @return a Future representing pending completion of the task */ public Future<?> submit(final Runnable task, final Runnable preTask, final Runnable postTask, final UncaughtExceptionHandler handler) { return submit(new Runnable(){ public void run() { final UncaughtExceptionHandler currentHandler = Thread.currentThread().getUncaughtExceptionHandler(); try { if(handler!=null) { Thread.currentThread().setUncaughtExceptionHandler(handler); } if(preTask!=null) preTask.run(); task.run(); if(postTask!=null) postTask.run(); } finally { Thread.currentThread().setUncaughtExceptionHandler(currentHandler); } } }); } /** * {@inheritDoc} * @see com.heliosapm.utils.jmx.JMXManagedThreadPoolMBean#stop() */ @Override public void stop() { shutdownNow(); try { JMXHelper.unregisterMBean(objectName); } catch (Exception x) { /* No Op */} } @Override public void shutdown() { try { super.shutdown(); } finally { try { JMXHelper.unregisterMBean(objectName); } catch (Exception x) {/* No Op */} } } @Override public List<Runnable> shutdownNow() { try { return super.shutdownNow(); } finally { try { JMXHelper.unregisterMBean(objectName); } catch (Exception x) {/* No Op */} } } @Override public boolean awaitTermination(final long timeout, final TimeUnit unit) throws InterruptedException { try { return super.awaitTermination(timeout, unit); } finally { try { JMXHelper.unregisterMBean(objectName); } catch (Exception x) {/* No Op */} } } /** * {@inheritDoc} * @see java.util.concurrent.AbstractExecutorService#submit(java.lang.Runnable, java.lang.Object) */ @Override public <T> Future<T> submit(Runnable task, T result) { return super.submit(task, result); } /** * {@inheritDoc} * @see java.util.concurrent.AbstractExecutorService#submit(java.util.concurrent.Callable) */ @Override public <T> Future<T> submit(Callable<T> task) { return super.submit(task); } /** * {@inheritDoc} * @see com.heliosapm.jmx.concurrency.JMXManagedThreadPoolMBean#getKeepAliveTime() */ @Override public long getKeepAliveTime() { return getKeepAliveTime(TimeUnit.MILLISECONDS); } /** * {@inheritDoc} * @see com.heliosapm.jmx.concurrency.JMXManagedThreadPoolMBean#setKeepAliveTime(long) */ @Override public void setKeepAliveTime(long keepAliveTimeMs) { setKeepAliveTime(keepAliveTimeMs, TimeUnit.MILLISECONDS); } // /** // * {@inheritDoc} // * @see com.heliosapm.jmx.concurrency.JMXManagedThreadPoolMBean#reset() // */ // @Override // public void reset() { // t // } /** * {@inheritDoc} * @see com.heliosapm.jmx.concurrency.JMXManagedThreadPoolMBean#waitForCompletion(java.util.Collection, long) */ @Override public boolean waitForCompletion(Collection<Future<?>> futures, long timeout) { if(futures.isEmpty()) return true; final long expiryTime = System.currentTimeMillis() + timeout; final boolean[] bust = new boolean[]{false}; while(System.currentTimeMillis() <= expiryTime) { if(bust[0]) return false; for(Iterator<Future<?>> fiter = futures.iterator(); fiter.hasNext();) { Future<?> f = fiter.next(); if(f.isDone() || f.isCancelled()) { fiter.remove(); } else { try { f.get(200, TimeUnit.MILLISECONDS); fiter.remove(); } catch (CancellationException e) { System.err.println("Task Was Cancelled:" + e); fiter.remove(); } catch (InterruptedException e) { System.err.println("Thread interrupted while waiting for task check to complete:" + e); bust[0] = true; } catch (ExecutionException e) { System.err.println("Task Failed:" + e); fiter.remove(); } catch (TimeoutException e) { /* No Op */ } catch (Exception e) { System.err.println("Task Failure. Cancelling check:" + e); fiter.remove(); } } } if(futures.isEmpty()) return true; } for(Future<?> f: futures) { f.cancel(true); } System.err.println("Task completion timed out with [" + futures.size() + "] tasks incomplete"); futures.clear(); return false; } public static JMXManagedThreadPoolBuilder builder() { return new JMXManagedThreadPoolBuilder(); } public static class JMXManagedThreadPoolBuilder { public static final int CORES = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors(); public static final String OBJECT_NAME_TEMPLATE = "com.heliosapm.threading:service=ThreadPool,name=%s"; private static final AtomicInteger serial = new AtomicInteger(0); private ObjectName objectName = null; private String poolName = null; private int corePoolSize = CORES; private int maximumPoolSize = CORES * 2; private int queueSize = CORES * 100; private long keepAliveTimeMs = 60000; private int metricWindowSize = 1000; private int metricDefaultPercentile = 99; private boolean publishJMX = true; private int prestart = 0; private ThreadFactory threadFactory = null; private Thread.UncaughtExceptionHandler uncaughtHandler = null; private RejectedExecutionHandler rejectionHandler = null; /** * Builds and returns the configured JMXManagedThreadPool * @return the configured JMXManagedThreadPool */ public JMXManagedThreadPool build() { if(!publishJMX) { objectName = null; if((poolName==null||poolName.trim().isEmpty())) { poolName = "Pool#" + serial.incrementAndGet(); } } else { if(objectName==null && (poolName==null||poolName.trim().isEmpty())) { poolName = "Pool#" + serial.incrementAndGet(); objectName = JMXHelper.objectName(String.format(OBJECT_NAME_TEMPLATE, poolName)); } else { if(objectName==null) { objectName = JMXHelper.objectName(String.format(OBJECT_NAME_TEMPLATE, poolName)); } // else { // poolName = "Pool#" + serial.incrementAndGet(); // } } } if(prestart > 0 && prestart > maximumPoolSize) { prestart = maximumPoolSize; } JMXManagedThreadPool pool = new JMXManagedThreadPool(objectName, poolName, corePoolSize, maximumPoolSize, queueSize, keepAliveTimeMs, metricWindowSize, metricDefaultPercentile, publishJMX); if(rejectionHandler!=null) { pool.setRejectedExecutionHandler(rejectionHandler); } if(uncaughtHandler!=null) { pool.setUncaughtExceptionHandler(uncaughtHandler); } if(prestart > 0) { for(int i = 0; i < prestart; i++) { pool.prestartCoreThread(); } } return pool; } /** * Sets * @param objectName the objectName to set * @return this builder */ public JMXManagedThreadPoolBuilder objectName(final ObjectName objectName) { if(objectName==null) throw new IllegalArgumentException("The passed ObjectName was null"); this.objectName = objectName; return this; } /** * Sets the managed thread pool's thread factory * @param threadFactory The thread factory the pool will use * @return this builder */ public JMXManagedThreadPoolBuilder threadFactory(final ThreadFactory threadFactory) { if(threadFactory==null) throw new IllegalArgumentException("The passed ThreadFactory was null"); this.threadFactory = threadFactory; return this; } /** * Sets the pool name * @param poolName the poolName to set * @return this builder */ public JMXManagedThreadPoolBuilder poolName(final String poolName) { if(poolName==null || poolName.trim().isEmpty()) throw new IllegalArgumentException("The passed Pool Name was null or empty"); this.poolName = poolName; return this; } /** * Sets * @param corePoolSize the corePoolSize to set * @return this builder */ public JMXManagedThreadPoolBuilder corePoolSize(final int corePoolSize) { if(corePoolSize < 1) throw new IllegalArgumentException("Invalid core pool size [" + corePoolSize + "]"); this.corePoolSize = corePoolSize; return this; } /** * Sets * @param maximumPoolSize the maximumPoolSize to set * @return this builder */ public JMXManagedThreadPoolBuilder maxPoolSize(final int maximumPoolSize) { if(maximumPoolSize < 1) throw new IllegalArgumentException("Invalid max pool size [" + maximumPoolSize + "]"); this.maximumPoolSize = maximumPoolSize; return this; } /** * Sets * @param queueSize the queueSize to set * @return this builder */ public JMXManagedThreadPoolBuilder queueSize(final int queueSize) { if(queueSize < 1) throw new IllegalArgumentException("Invalid queue size [" + queueSize + "]"); this.queueSize = queueSize; return this; } /** * Sets * @param keepAliveTimeMs the keepAliveTimeMs to set * @return this builder */ public JMXManagedThreadPoolBuilder keepAliveTimeMs(final long keepAliveTimeMs) { if(keepAliveTimeMs < 1) throw new IllegalArgumentException("Invalid keep alive time [" + keepAliveTimeMs + "] ms."); this.keepAliveTimeMs = keepAliveTimeMs; return this; } /** * Sets * @param metricWindowSize the metricWindowSize to set * @return this builder */ public JMXManagedThreadPoolBuilder metricWindowSize(final int metricWindowSize) { if(metricWindowSize < 1) throw new IllegalArgumentException("Invalid metric window size [" + metricWindowSize + "]"); this.metricWindowSize = metricWindowSize; return this; } /** * Sets * @param metricDefaultPercentile the metricDefaultPercentile to set * @return this builder */ public JMXManagedThreadPoolBuilder metricDefaultPercentile(final int metricDefaultPercentile) { if(metricDefaultPercentile < 1 || metricDefaultPercentile > 99) throw new IllegalArgumentException("Invalid metric default percentile [" + metricDefaultPercentile + "]"); this.metricDefaultPercentile = metricDefaultPercentile; return this; } /** * Sets * @param publishJMX the publishJMX to set * @return this builder */ public JMXManagedThreadPoolBuilder publishJMX(final boolean publishJMX) { this.publishJMX = publishJMX; return this; } /** * Sets * @param prestart the prestart to set * @return this builder */ public JMXManagedThreadPoolBuilder prestart(final int prestart) { if(prestart < 1) throw new IllegalArgumentException("Invalid prestart [" + prestart + "]"); this.prestart = prestart; return this; } /** * Sets * @param uncaughtHandler the uncaughtHandler to set * @return this builder */ public JMXManagedThreadPoolBuilder uncaughtHandler(Thread.UncaughtExceptionHandler uncaughtHandler) { if(uncaughtHandler==null) throw new IllegalArgumentException("The passed UncaughtExceptionHandler was null"); this.uncaughtHandler = uncaughtHandler; return this; } /** * Sets * @param rejectionHandler the rejectionHandler to set * @return this builder */ public JMXManagedThreadPoolBuilder rejectionHandler(RejectedExecutionHandler rejectionHandler) { if(rejectionHandler==null) throw new IllegalArgumentException("The passed RejectedExecutionHandler was null"); this.rejectionHandler = rejectionHandler; return this; } } }
924302ad45ac6bb880128ea3a6f542dee08eef46
398
java
Java
backend/src/main/java/es/udc/paproject/backend/model/exceptions/DateExpiredException.java
Seoane8/pa-project
822d77c4f94b8484b823f8983e6807d52415a618
[ "MIT" ]
null
null
null
backend/src/main/java/es/udc/paproject/backend/model/exceptions/DateExpiredException.java
Seoane8/pa-project
822d77c4f94b8484b823f8983e6807d52415a618
[ "MIT" ]
null
null
null
backend/src/main/java/es/udc/paproject/backend/model/exceptions/DateExpiredException.java
Seoane8/pa-project
822d77c4f94b8484b823f8983e6807d52415a618
[ "MIT" ]
null
null
null
24.875
90
0.711055
1,002,492
package es.udc.paproject.backend.model.exceptions; public class DateExpiredException extends Exception{ private Long sportTestId; public DateExpiredException(Long sportTestId) { super("More than 15 days have passed since the sportTest with ID " + sportTestId); this.sportTestId = sportTestId; } public Long getSportTestId() { return sportTestId; } }
9243061410d31456bed9776cdc8fd3e2d635ea3d
7,591
java
Java
demouiza/src/main/java/uiza/v4/search/FrmSearch.java
haiminhtran810/uiza-android-sdk-player
bfda3753a0932348aeb9f2932eab21c5ed4ed8a8
[ "BSD-2-Clause" ]
11
2018-06-06T03:40:24.000Z
2020-04-02T11:53:12.000Z
demouiza/src/main/java/uiza/v4/search/FrmSearch.java
haiminhtran810/uiza-android-sdk-player
bfda3753a0932348aeb9f2932eab21c5ed4ed8a8
[ "BSD-2-Clause" ]
17
2018-10-30T10:34:50.000Z
2020-10-12T08:02:12.000Z
demouiza/src/main/java/uiza/v4/search/FrmSearch.java
haiminhtran810/uiza-android-sdk-player
bfda3753a0932348aeb9f2932eab21c5ed4ed8a8
[ "BSD-2-Clause" ]
14
2018-07-31T07:56:29.000Z
2020-03-11T05:20:15.000Z
36.68599
132
0.610219
1,002,493
package uiza.v4.search; /** * Created by [email protected] on 12/24/2017. */ import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import uiza.R; import uiza.v4.HomeV4CanSlideActivity; import uiza.v4.entities.EntitiesAdapter; import uizacoresdk.interfaces.IOnBackPressed; import vn.uiza.core.common.Constants; import vn.uiza.core.utilities.LLog; import vn.uiza.core.utilities.LUIUtil; import vn.uiza.restapi.UZAPIMaster; import vn.uiza.restapi.restclient.UZRestClient; import vn.uiza.restapi.uiza.UZService; import vn.uiza.restapi.uiza.model.v3.metadata.getdetailofmetadata.Data; import vn.uiza.restapi.uiza.model.v3.videoondeman.listallentity.ResultListEntity; import vn.uiza.rxandroid.ApiSubscriber; import vn.uiza.utils.util.KeyboardUtils; import vn.uiza.views.LToast; public class FrmSearch extends Fragment implements View.OnClickListener, IOnBackPressed { private final String TAG = getClass().getSimpleName(); private ImageView ivBack; private ImageView ivClearText; private EditText etSearch; private TextView tv; private final int limit = 20; private final String orderBy = "createdAt"; private final String orderType = "DESC"; private final String publishToCdn = "success"; private RecyclerView recyclerView; private EntitiesAdapter mAdapter; private TextView tvMsg; private List<Data> dataList = new ArrayList<>(); private int page = 0; private int totalPage = Integer.MAX_VALUE; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.v4_frm_search, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); recyclerView = (RecyclerView) view.findViewById(R.id.rv); recyclerView = (RecyclerView) view.findViewById(R.id.rv); ivBack = (ImageView) view.findViewById(R.id.iv_back); ivClearText = (ImageView) view.findViewById(R.id.iv_clear_text); etSearch = (EditText) view.findViewById(R.id.et_search); etSearch.requestFocus(); tv = (TextView) view.findViewById(R.id.tv); ivBack.setOnClickListener(this); ivClearText.setOnClickListener(this); mAdapter = new EntitiesAdapter(getActivity(), dataList, new EntitiesAdapter.Callback() { @Override public void onClick(Data data, int position) { ((HomeV4CanSlideActivity) getActivity()).playEntityId(data.getId()); } @Override public void onLongClick(Data data, int position) { } @Override public void onLoadMore() { loadMore(); } }); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity()); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setAdapter(mAdapter); etSearch.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.toString().isEmpty()) { ivClearText.setVisibility(View.GONE); tv.setVisibility(View.GONE); } else { ivClearText.setVisibility(View.VISIBLE); } } @Override public void afterTextChanged(Editable s) { } }); LUIUtil.setImeiActionSearch(etSearch, new LUIUtil.CallbackSearch() { @Override public void onSearch() { search(etSearch.getText().toString()); } }); KeyboardUtils.showSoftInput(etSearch); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.iv_back: getActivity().onBackPressed(); break; case R.id.iv_clear_text: etSearch.setText(""); break; } } private void search(String keyword) { //TODO chia page https://jira.uiza.io/browse/UIZA-3157 tv.setVisibility(View.GONE); page++; if (page >= totalPage) { if (Constants.IS_DEBUG) { LToast.show(getActivity(), getString(R.string.this_is_last_page)); } return; } if (Constants.IS_DEBUG) { LToast.show(getActivity(), getString(R.string.load_page) + page); } LLog.d(TAG, "search " + page + "/" + totalPage); UZService service = UZRestClient.createService(UZService.class); UZAPIMaster.getInstance().subscribe(service.searchEntity(keyword), new ApiSubscriber<ResultListEntity>() { @Override public void onSuccess(ResultListEntity result) { if (result == null || result.getData().isEmpty()) { tv.setText(getString(R.string.empty_list)); tv.setVisibility(View.VISIBLE); return; } if (result == null || result.getMetadata() == null || result.getData().isEmpty()) { tvMsg.setVisibility(View.VISIBLE); tvMsg.setText(getString(R.string.empty_list)); return; } if (totalPage == Integer.MAX_VALUE) { int totalItem = (int) result.getMetadata().getTotal(); float ratio = (float) (totalItem / limit); if (ratio == 0) { totalPage = (int) ratio; } else if (ratio > 0) { totalPage = (int) ratio + 1; } else { totalPage = (int) ratio; } } LLog.d(TAG, "-> totalPage: " + totalPage); dataList.addAll(result.getData()); mAdapter.notifyDataSetChanged(); } @Override public void onFail(Throwable e) { LLog.e(TAG, "search onFail " + e.toString()); tv.setText("Error search " + e.getMessage()); tv.setVisibility(View.VISIBLE); } }); } @Override public boolean onBackPressed() { LLog.d(TAG, "onBackPressed " + TAG); return false; //return ((HomeV4CanSlideActivity) getActivity()).handleOnbackpressFrm(); } @Override public void onDestroyView() { ((HomeV4CanSlideActivity) getActivity()).llActionBar.setVisibility(View.VISIBLE); KeyboardUtils.hideSoftInput(getActivity()); super.onDestroyView(); } private void loadMore() { LLog.d(TAG, "loadMore"); search(etSearch.getText().toString()); } }
9243069eb58447ba026f7b5fc70e9ac8f77f877a
5,149
java
Java
testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/providers/sse/resource/SseReconnectResource.java
iweiss/Resteasy
254e74f84806534f8a2b57cc73693428a2a9fcca
[ "Apache-2.0" ]
841
2015-01-01T10:13:52.000Z
2021-09-17T03:41:49.000Z
testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/providers/sse/resource/SseReconnectResource.java
iweiss/Resteasy
254e74f84806534f8a2b57cc73693428a2a9fcca
[ "Apache-2.0" ]
974
2015-01-23T02:42:23.000Z
2021-09-17T03:35:22.000Z
testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/providers/sse/resource/SseReconnectResource.java
iweiss/Resteasy
254e74f84806534f8a2b57cc73693428a2a9fcca
[ "Apache-2.0" ]
747
2015-01-08T22:48:05.000Z
2021-09-02T15:56:08.000Z
32.383648
116
0.656438
1,002,494
package org.jboss.resteasy.test.providers.sse.resource; import java.util.concurrent.TimeUnit; import jakarta.ejb.Singleton; import jakarta.ws.rs.DefaultValue; import jakarta.ws.rs.GET; import jakarta.ws.rs.HeaderParam; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.sse.OutboundSseEvent; import jakarta.ws.rs.sse.Sse; import jakarta.ws.rs.sse.SseEventSink; import org.junit.Assert; @Singleton @Path("/reconnect") public class SseReconnectResource { private volatile boolean isServiceAvailable = false; private volatile long startTime = 0L; private volatile long endTime = 0L; private volatile long lastEventDeliveryTime; @GET @Path("/defaultReconnectDelay") @Produces(MediaType.TEXT_PLAIN) public Response reconnectDelayNotSet(@Context Sse sse, @Context SseEventSink sseEventSink) { OutboundSseEvent event = sse.newEventBuilder().id("1").data("test").build(); return Response.ok(event.getReconnectDelay()).build(); } @GET @Path("/reconnectDelaySet") @Produces(MediaType.TEXT_PLAIN) public Response reconnectDelaySet(@Context Sse sse, @Context SseEventSink sseEventSink) { OutboundSseEvent event = sse.newEventBuilder().id("1").data("test").reconnectDelay(1000L).build(); return Response.ok(event.getReconnectDelay()).build(); } @GET @Path("/unavailable") @Produces(MediaType.SERVER_SENT_EVENTS) public void sendMessage(@Context SseEventSink sink, @Context Sse sse) { if (!isServiceAvailable) { isServiceAvailable = true; startTime = System.currentTimeMillis(); throw new WebApplicationException(Response.status(503).header(HttpHeaders.RETRY_AFTER, String.valueOf(2)) .build()); } else { endTime = System.currentTimeMillis() - startTime; long elapsedSeconds = TimeUnit.MILLISECONDS.toSeconds(endTime); Assert.assertTrue(elapsedSeconds >= 2); try (SseEventSink s = sink) { s.send(sse.newEvent("ServiceAvailable")); isServiceAvailable = false; } } } @GET @Path("/testReconnectDelayIsUsed") @Produces(MediaType.SERVER_SENT_EVENTS) public void testReconnectDelay(@Context SseEventSink sseEventSink, @Context Sse sse, @HeaderParam(HttpHeaders.LAST_EVENT_ID_HEADER) @DefaultValue("") String lastEventId) { switch (lastEventId) { case "0" : checkReconnectDelay(TimeUnit.SECONDS.toMillis(3)); try (SseEventSink s = sseEventSink) { sendEvent(s, sse, "1", null); } break; case "1" : checkReconnectDelay(TimeUnit.SECONDS.toMillis(3)); throw new WebApplicationException(599); default : try (SseEventSink s = sseEventSink) { sendEvent(s, sse, "0", TimeUnit.SECONDS.toMillis(3)); } break; } } static int tryCount = 1; @GET @Path("sselost") @Produces(MediaType.SERVER_SENT_EVENTS) public void sseLost(@Context SseEventSink sink, @Context Sse sse) { if (tryCount != 0) { tryCount--; sink.close(); } else { try (SseEventSink s = sink) { s.send(sse.newEvent("MESSAGE")); } } } @GET @Path("data") @Produces(MediaType.SERVER_SENT_EVENTS) public void sendData(@Context SseEventSink sink, @Context Sse sse) { try (SseEventSink s = sink) { s.send(sse.newEventBuilder().data("sse message sample").mediaType(MediaType.TEXT_HTML_TYPE) .build()); } } static int retry_cnt = 2; @GET @Path("/unavailableAfterRetry") @Produces(MediaType.SERVER_SENT_EVENTS) public void failAfterRetry(@Context SseEventSink sink, @Context Sse sse) { if (retry_cnt <= 0) { startTime = System.currentTimeMillis(); throw new WebApplicationException(Response.status(503) .build()); } else { throw new WebApplicationException(Response.status(503) .header(HttpHeaders.RETRY_AFTER, String.valueOf(retry_cnt--)) .build()); } } private void sendEvent(SseEventSink sseEventSink, Sse sse, String eventId, Long reconnectDelayInMs) { OutboundSseEvent.Builder outboundSseEventBuilder = sse.newEventBuilder().data("Event " + eventId).id(eventId); if (reconnectDelayInMs != null) { outboundSseEventBuilder.reconnectDelay(reconnectDelayInMs); } sseEventSink.send(outboundSseEventBuilder.build()); lastEventDeliveryTime = System.currentTimeMillis(); } private void checkReconnectDelay(long expectedDelayInMs) { long currentDelayInMs = System.currentTimeMillis() - lastEventDeliveryTime; Assert.assertTrue(currentDelayInMs >= expectedDelayInMs); } }
924306c1b8724635f1a2a1a5e55e458c9b9be448
5,421
java
Java
src/red/UtilXML.java
RedInquisitive/Haxa-Editor
91b282992483bf33807d1e5596865e66d396ddbc
[ "MIT" ]
2
2016-12-14T05:30:45.000Z
2016-12-28T04:33:03.000Z
src/red/UtilXML.java
RedTopper/Haxa-Editor
91b282992483bf33807d1e5596865e66d396ddbc
[ "MIT" ]
2
2020-08-14T01:45:22.000Z
2021-09-13T15:35:21.000Z
src/red/UtilXML.java
RedTopper/Haxa-Editor
91b282992483bf33807d1e5596865e66d396ddbc
[ "MIT" ]
4
2016-12-28T04:28:53.000Z
2017-01-17T21:48:14.000Z
33.257669
103
0.711492
1,002,495
package red; import java.awt.Color; import java.io.File; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import parts.Wall; public class UtilXML { public static final String XML_COLOR = "Color"; public static final String XML_RED = "Red"; public static final String XML_GREEN = "Green"; public static final String XML_BLUE = "Blue"; private UtilXML() throws InstantiationException { throw new InstantiationException(); } /** * Opens an XML document by checking it's root element. * @param patternFile File to open. * @param type Type of the file as a string. * @return A document * @throws Exception */ public static Document openXML(File file, String type) throws Exception { Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file); if(!doc.getDocumentElement().getNodeName().equals(type)) throw new Exception("Failed to open file!"); return doc; } /** * Writes a document to a file. * @param file The file to write. * @param doc The document to write. * @throws Exception */ public static void writeXML(File file, Document doc) throws Exception{ File oldDir = Util.getDir(new File(file.getParent() + Util.OLD)); File backupFile = new File(oldDir, file.getName()); backupFile.delete(); file.renameTo(backupFile); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); DOMSource source = new DOMSource(doc); StreamResult console = new StreamResult(file); transformer.transform(source, console); System.out.println("Backed up and wrote XML file: '" + file.getAbsolutePath() + "'"); } public static int getInt(Element root, String name) { try { Element e = (Element)root.getElementsByTagName(name).item(0); return Integer.parseInt(e.getTextContent()); } catch(Exception e) {System.err.println("Failed to parse int for tag " + name + "!");} return 0; } public static void putInt(Element root, String name, int i) { Element e = root.getOwnerDocument().createElement(name); e.appendChild(root.getOwnerDocument().createTextNode(i + "")); root.appendChild(e); } public static float getFloat(Element root, String name) { try { Element e = (Element)root.getElementsByTagName(name).item(0); return Float.parseFloat(e.getTextContent()); } catch(Exception e) {System.err.println("Failed to parse float for tag " + name + "!");} return 0.0f; } public static void putFloat(Element root, String name, float f) { Element e = root.getOwnerDocument().createElement(name); e.appendChild(root.getOwnerDocument().createTextNode(f + "")); root.appendChild(e); } public static String getString(Element root, String name) { try { Element e = (Element)root.getElementsByTagName(name).item(0); return e.getTextContent(); } catch(Exception e) {System.err.println("Failed to parse String for tag " + name + "!");} return "NOT SET"; } public static void putString(Element root, String name, String string) { Element e = root.getOwnerDocument().createElement(name); e.appendChild(root.getOwnerDocument().createTextNode(string)); root.appendChild(e); } public static Color getColor(Element root) { return new Color(getInt(root, XML_RED), getInt(root, XML_GREEN), getInt(root, XML_BLUE)); } public static void putColor(Element root, Color color) { Element c = root.getOwnerDocument().createElement(XML_COLOR); putInt(c, XML_RED, color.getRed()); putInt(c, XML_GREEN, color.getGreen()); putInt(c, XML_BLUE, color.getBlue()); root.appendChild(c); } public static List<Color> getColors(Element root, String name) { List<Color> colors = new ArrayList<>(); try { Element block = (Element)root.getElementsByTagName(name).item(0); NodeList ecolors = block.getElementsByTagName(XML_COLOR); for(int i = 0; i < ecolors.getLength(); i++) { Element color = (Element)ecolors.item(i); if(color == null) continue; colors.add(getColor(color)); } } catch (Exception e) {System.err.println("Failed to parse Colors for tag " + name + "!");} return colors; } public static void putColors(Element root, String name, List<Color> colors) { Element e = root.getOwnerDocument().createElement(name); for(Color c : colors) UtilXML.putColor(e, c); root.appendChild(e); } public static List<Wall> getWalls(Element root) { List<Wall> walls = new ArrayList<>(); try { NodeList ewalls = root.getElementsByTagName(Wall.XML_HEADER); for(int i = 0; i < ewalls.getLength(); i++) { Element wall = (Element)ewalls.item(i); if(wall == null) continue; walls.add(new Wall(wall)); } } catch (Exception e) {System.err.println("Failed to parse Walls!");} return walls; } public static void putWalls(Element root, List<Wall> walls) { for(Wall w : walls) { Element e = root.getOwnerDocument().createElement(Wall.XML_HEADER); w.writeXML(e); root.appendChild(e); } } }
924307e47cb5803e4a347f43ec3e940750d8b7e3
6,953
java
Java
app/controllers/Random.java
IvDobr/Achievements
fb25806e16362468baa4809473a971f34b89e14a
[ "Apache-2.0" ]
null
null
null
app/controllers/Random.java
IvDobr/Achievements
fb25806e16362468baa4809473a971f34b89e14a
[ "Apache-2.0" ]
null
null
null
app/controllers/Random.java
IvDobr/Achievements
fb25806e16362468baa4809473a971f34b89e14a
[ "Apache-2.0" ]
null
null
null
35.116162
115
0.502229
1,002,496
package controllers; import models.*; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; public class Random { public static void testDataBase() { User userprost = new User( "stud", "Студент", "Обычный", "123123", 2, new java.util.Date(), 1, true, "student"); try { userprost.save(); System.out.println("DONE: Тестовый аккаунт студента создан!"); } catch (Exception e) { System.out.println("ERROR: Невозможно создать тестовый аккаунт студента!"); } User usermoder = new User( "moder", "Председатель", "Факультета", "123123", 2, new java.util.Date(), 1, true, "moder"); try { usermoder.save(); System.out.println("DONE: Тестовый аккаунт председателя создан!"); } catch (Exception e) { System.out.println("ERROR: Невозможно создать тестовый аккаунт председателя!"); } // UserRandomize(); // AchievesRandomize(); // if (checkBander("ALL")) { // System.out.println("MSG: Достижения рандомизированы"); // } } private static void UserRandomize() { //Рандомизация базы пользователей List<String> man_names = LineReader("public/docs/man_names.txt");//609 имен List<String> woman_names = LineReader("public/docs/woman_names.txt");//496 имен List<String> lastnames = LineReader("public/docs/lastnames.txt");//15353 фамилии Integer userCount = intRandom(5000, 6000); System.out.println("MSG: ДОБАВЛЕНИЕ В БАЗУ " + userCount + " ПОЛЬЗОВАТЕЛЕЙ"); int fcl_count = Faculty.find.all().size(), stp_count = Stip.find.all().size(); String Fname, Lname; for (int i = 1; i <= userCount; i++) { if (intRandom(0,1) == 1) { Fname = man_names.get( intRandom( 0, man_names.size() - 1) ); Lname = lastnames.get( intRandom( 0, lastnames.size() - 1) ); } else { Fname = woman_names.get( intRandom( 0, woman_names.size() - 1) ); String str = lastnames.get(intRandom( 0, lastnames.size() - 1)); if (str.endsWith("в") || str.endsWith("н")) { Lname = str + "a"; } else if (str.endsWith("ий")) { Lname = str.replace("ий", "ая"); } else if (str.endsWith("ой")) { Lname = str.replace("ой", "ая"); } else { Lname = str; } } User user = new User( "user_" + i, Fname, Lname, "userpass", intRandom(1, fcl_count), dateRandom(1230829200000L),//зарандомленная дата между 01.01.2009 12:00 и текущим моментом intRandom(1, stp_count), intRandom(1, 100) <= 93, groupRandom()); try { user.save(); } catch (Exception e) { System.out.println("ERROR: Невозможно создать аккаунт # " + i + "!"); } } } private static void AchievesRandomize() { Integer achievCount = intRandom(47000, 55000); List<LongCat> LC = LongCat.find.all(); List<Stip> Stips = Stip.find.all(); Integer userCount = User.find.all().size(); System.out.println("MSG: ДОБАВЛЕНИЕ В БАЗУ " + achievCount + " ДОСТИЖЕНИЙ"); for (int i = 1; i <= achievCount; i++) { Achievement achiev = new Achievement( intRandom(2, userCount), "Тестовое достижение номер 000000" + i, dateRandom(1230829200000L), Stips.get(LC.get( intRandom(1, LC.size()-1)).getParentStip()).getStipTitle(), LC.get( intRandom(1, LC.size()-1)).getLongId(), "(Комментарий: " + i + ") Тестовое достижение номер 000000" + i, "", 1, 1); try { achiev.save(); } catch (Exception e) { System.out.println("ERROR: Невозможно создать достижение # " + i + "!"); } } } public static int intRandom (int min, int max) { if (max == min) return min; if(min>max) { int temp = max; max = min; min = temp; } java.util.Random random = new java.util.Random(); return min + random.nextInt(max - min + 1); } public static Date dateRandom(long lower_range) { java.util.Random r = new java.util.Random(); return new java.util.Date(lower_range + (long)(r.nextDouble()*(System.currentTimeMillis() - lower_range))); } private static String groupRandom() { int prob = intRandom(1, 1000); if (prob <= 2) return "administrator"; else if (prob <= 18) return "moder"; else return "student"; } public static Boolean checkBander(String user) { List<Achievement> achievsList; if (user.equals("ALL")) { achievsList = Achievement.find.all(); } else { achievsList = Achievement.find.where() .ilike("achUserId", user) .findList(); } List<String> lines = LineReader("public/docs/aphorism.txt"); for (Achievement item : achievsList) { item.setAchPrem(intRandom(1, 3)); item.setAchStip(intRandom(1, 3)); item.setAchComment( lines.get( intRandom( 0, lines.size() - 1) ) ); try{ item.update(); } catch(Exception e) { System.out.println("ERROR: Бендер поленился"); return false; } } System.out.println("MSG: Сработал Бендер"); return true; } public static List<String> LineReader(String filepath) { List<String> lines = new ArrayList<String>(); try { FileReader fileReader = new FileReader(new File(filepath)); System.out.println("MSG: Читаю файл: " + filepath); BufferedReader bufferedReader = new BufferedReader(fileReader); String line; while ((line = bufferedReader.readLine()) != null) { lines.add(line); } fileReader.close(); } catch (IOException e) { e.printStackTrace(); } return lines; } }
9243080a9f2e781d7ccff1a643ea54e1ce7db51f
13,682
java
Java
fcrepo-security/fcrepo-security-pdp/src/main/java/org/fcrepo/server/security/xacml/pdp/data/PolicyIndexBase.java
jart/fcrepo
9c41b09a21a3a2615791fa4c614095a14512940f
[ "Apache-2.0" ]
15
2015-02-02T22:38:14.000Z
2018-12-31T19:38:25.000Z
fcrepo-security/fcrepo-security-pdp/src/main/java/org/fcrepo/server/security/xacml/pdp/data/PolicyIndexBase.java
jart/fcrepo
9c41b09a21a3a2615791fa4c614095a14512940f
[ "Apache-2.0" ]
9
2020-11-16T20:45:22.000Z
2022-02-01T01:14:11.000Z
fcrepo-security/fcrepo-security-pdp/src/main/java/org/fcrepo/server/security/xacml/pdp/data/PolicyIndexBase.java
phaidra/fcrepo3
fe01891363e76c75b39762084de4857083519074
[ "Apache-2.0" ]
30
2015-01-08T16:42:35.000Z
2021-03-17T13:36:56.000Z
40.720238
116
0.541734
1,002,497
package org.fcrepo.server.security.xacml.pdp.data; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.fcrepo.server.security.xacml.pdp.finder.policy.PolicyReader; import org.fcrepo.server.security.xacml.util.AttributeBean; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.jboss.security.xacml.sunxacml.AbstractPolicy; import org.jboss.security.xacml.sunxacml.EvaluationCtx; import org.jboss.security.xacml.sunxacml.ParsingException; import org.jboss.security.xacml.sunxacml.Policy; import org.jboss.security.xacml.sunxacml.PolicySet; import org.jboss.security.xacml.sunxacml.attr.AttributeDesignator; import org.jboss.security.xacml.sunxacml.attr.AttributeValue; import org.jboss.security.xacml.sunxacml.attr.BagAttribute; import org.jboss.security.xacml.sunxacml.cond.EvaluationResult; import org.jboss.security.xacml.sunxacml.finder.PolicyFinder; /** * Base abstract class for all PolicyIndex implementations. * * Gets the index configuration common to all implementations. * * @author Stephen Bayliss * @version $Id$ */ public abstract class PolicyIndexBase implements PolicyIndex { protected static final String SUBJECT_KEY = "subjectAttributes"; protected static final String RESOURCE_KEY = "resourceAttributes"; protected static final String ACTION_KEY = "actionAttributes"; protected static final String ENVIRONMENT_KEY = "environmentAttributes"; protected static final URI SUBJECT_CATEGORY_DEFAULT = URI.create(AttributeDesignator.SUBJECT_CATEGORY_DEFAULT); // used in testing - indicates if the implementation returns indexed results // or if false indicates that all policies are returned irrespective of the request public boolean indexed = true; protected Map<String, Map<String, String>> indexMap = null; protected PolicyReader m_policyReader; protected static final String METADATA_POLICY_NS = "metadata"; // xacml namespaces and prefixes public static final Map<String, String> namespaces = new HashMap<String, String>(); static { namespaces.put("p", XACML20_POLICY_NS); namespaces.put("m", METADATA_POLICY_NS); // appears to dbxml specific and probably not used } protected PolicyIndexBase(PolicyReader policyReader) throws PolicyIndexException { m_policyReader = policyReader; String[] indexMapElements = {SUBJECT_KEY, RESOURCE_KEY, ACTION_KEY, ENVIRONMENT_KEY}; indexMap = new HashMap<String, Map<String, String>>(); for (String s : indexMapElements) { indexMap.put(s, new HashMap<String, String>()); } } public void setSubjectAttributes(Map<String, String> attributeMap) { setAttributeMap(SUBJECT_KEY, attributeMap); } public void setResourceAttributes(Map<String, String> attributeMap) { setAttributeMap(RESOURCE_KEY, attributeMap); } public void setActionAttributes(Map<String, String> attributeMap) { setAttributeMap(ACTION_KEY, attributeMap); } public void setEnvironmentAttributes(Map<String, String> attributeMap) { setAttributeMap(ENVIRONMENT_KEY, attributeMap); } protected void setAttributeMap(String mapKey, Map<String, String> attributeMap) { indexMap.get(mapKey).putAll(attributeMap); } /** * This method extracts the attributes listed in the indexMap from the given * evaluation context. * * @param eval * the Evaluation Context from which to extract Attributes * @return a Map of Attributes for each category (Subject, Resource, Action, * Environment) * @throws URISyntaxException */ @SuppressWarnings("unchecked") protected Map<String, Collection<AttributeBean>> getAttributeMap(EvaluationCtx eval) throws URISyntaxException { final URI defaultCategoryURI = SUBJECT_CATEGORY_DEFAULT; Map<String, String> im = null; Map<String, Collection<AttributeBean>> attributeMap = new HashMap<String, Collection<AttributeBean>>(); Map<String, AttributeBean> attributeBeans = null; im = indexMap.get(SUBJECT_KEY); attributeBeans = new HashMap<String, AttributeBean>(); for (String attributeId : im.keySet()) { EvaluationResult result = eval.getSubjectAttribute(new URI(im.get(attributeId)), new URI(attributeId), defaultCategoryURI); if (result.getStatus() == null && !result.indeterminate()) { AttributeValue attr = result.getAttributeValue(); if (attr.returnsBag()) { Iterator<AttributeValue> i = ((BagAttribute) attr).iterator(); if (i.hasNext()) { while (i.hasNext()) { AttributeValue value = i.next(); String attributeType = im.get(attributeId); AttributeBean ab = attributeBeans.get(attributeId); if (ab == null) { ab = new AttributeBean(); ab.setId(attributeId); ab.setType(attributeType); attributeBeans.put(attributeId, ab); } ab.addValue(value.encode()); } } } } } attributeMap.put(SUBJECT_KEY, attributeBeans.values()); im = indexMap.get(RESOURCE_KEY); attributeBeans = new HashMap<String, AttributeBean>(); for (String attributeId : im.keySet()) { EvaluationResult result = eval.getResourceAttribute(new URI(im.get(attributeId)), new URI(attributeId), null); if (result.getStatus() == null && !result.indeterminate()) { AttributeValue attr = result.getAttributeValue(); if (attr.returnsBag()) { Iterator<AttributeValue> i = ((BagAttribute) attr).iterator(); if (i.hasNext()) { while (i.hasNext()) { AttributeValue value = i.next(); String attributeType = im.get(attributeId); AttributeBean ab = attributeBeans.get(attributeId); if (ab == null) { ab = new AttributeBean(); ab.setId(attributeId); ab.setType(attributeType); attributeBeans.put(attributeId, ab); } if (attributeId.equals(XACML_RESOURCE_ID) && value.encode().startsWith("/")) { String[] components = makeComponents(value.encode()); if (components != null && components.length > 0) { for (String c : components) { ab.addValue(c); } } else { ab.addValue(value.encode()); } } else { ab.addValue(value.encode()); } } } } } } attributeMap.put(RESOURCE_KEY, attributeBeans.values()); im = indexMap.get(ACTION_KEY); attributeBeans = new HashMap<String, AttributeBean>(); for (String attributeId : im.keySet()) { EvaluationResult result = eval.getActionAttribute(new URI(im.get(attributeId)), new URI(attributeId), null); if (result.getStatus() == null && !result.indeterminate()) { AttributeValue attr = result.getAttributeValue(); if (attr.returnsBag()) { Iterator<AttributeValue> i = ((BagAttribute) attr).iterator(); if (i.hasNext()) { while (i.hasNext()) { AttributeValue value = i.next(); String attributeType = im.get(attributeId); AttributeBean ab = attributeBeans.get(attributeId); if (ab == null) { ab = new AttributeBean(); ab.setId(attributeId); ab.setType(attributeType); attributeBeans.put(attributeId, ab); } ab.addValue(value.encode()); } } } } } attributeMap.put(ACTION_KEY, attributeBeans.values()); im = indexMap.get(ENVIRONMENT_KEY); attributeBeans = new HashMap<String, AttributeBean>(); for (String attributeId : im.keySet()) { URI imAttrId = new URI(im.get(attributeId)); URI attrId = new URI(attributeId); EvaluationResult result = eval.getEnvironmentAttribute(imAttrId, attrId, null); if (result.getStatus() == null && !result.indeterminate()) { AttributeValue attr = result.getAttributeValue(); if (attr.returnsBag()) { Iterator<AttributeValue> i = ((BagAttribute) attr).iterator(); if (i.hasNext()) { while (i.hasNext()) { AttributeValue value = i.next(); String attributeType = im.get(attributeId); AttributeBean ab = attributeBeans.get(attributeId); if (ab == null) { ab = new AttributeBean(); ab.setId(attributeId); ab.setType(attributeType); attributeBeans.put(attributeId, ab); } ab.addValue(value.encode()); } } } } } attributeMap.put(ENVIRONMENT_KEY, attributeBeans.values()); return attributeMap; } /** * A private method that handles reading the policy and creates the correct * kind of AbstractPolicy. * Because this makes use of the policyFinder, it cannot be reused between finders. * Consider moving to policyManager, which is not intended to be reused outside * of a policyFinderModule, which is not intended to be reused amongst PolicyFinder instances. */ protected AbstractPolicy handleDocument(Document doc, PolicyFinder policyFinder) throws ParsingException { // handle the policy, if it's a known type Element root = doc.getDocumentElement(); String name = root.getTagName(); // see what type of policy this is if (name.equals("Policy")) { return Policy.getInstance(root); } else if (name.equals("PolicySet")) { return PolicySet.getInstance(root, policyFinder); } else { // this isn't a root type that we know how to handle throw new ParsingException("Unknown root document type: " + name); } } /** * Splits a XACML hierarchical resource-id value into a set of resource-id values * that can be matched against a policy. * * Eg an incoming request for /res1/res2/res3/.* should match * /res1/.* * /res1/res2/.* * /res1/res2/res3/.* * * in policies. * * @param resourceId XACML hierarchical resource-id value * @return array of individual resource-id values that can be used to match against policies */ protected static String[] makeComponents(String resourceId) { if (resourceId == null || resourceId.isEmpty() || !resourceId.startsWith("/")) { return null; } List<String> components = new ArrayList<String>(); String[] parts = resourceId.split("\\/"); int bufPrimer = 0; for (int x = 1; x < parts.length; x++) { bufPrimer = Math.max(bufPrimer, (parts[x].length() + 1)); StringBuilder sb = new StringBuilder(bufPrimer); for (int y = 0; y < x; y++) { sb.append("/"); sb.append(parts[y + 1]); } String componentBase = sb.toString(); bufPrimer = componentBase.length() + 16; components.add(componentBase); if (x != parts.length - 1) { components.add(componentBase.concat("/.*")); } else { components.add(componentBase.concat("$")); } } return components.toArray(parts); } }
9243087a700ea44b46ddf4a28ad1ab0d730e7c41
940
java
Java
src/main/Downloader.java
jjf28/SourceExplorer
06f320a59cd35e24ac553bc2dd2abb3f5dcc7a85
[ "MIT" ]
null
null
null
src/main/Downloader.java
jjf28/SourceExplorer
06f320a59cd35e24ac553bc2dd2abb3f5dcc7a85
[ "MIT" ]
null
null
null
src/main/Downloader.java
jjf28/SourceExplorer
06f320a59cd35e24ac553bc2dd2abb3f5dcc7a85
[ "MIT" ]
null
null
null
19.183673
61
0.646809
1,002,498
package main; import java.net.URL; import java.util.Scanner; /** * A class that downloads or otherwise fetches * information about the given addresses. * * @author Justin Forsberg * */ public class Downloader { /** * Attempts to return the source code for the given address. * @param address The web address to get the source from. * @return The source for the web address on success, * null on faliure. */ public static String GetPageSource(URL address) { StringBuilder source = null; Scanner scanner = null; try { scanner = new Scanner(address.openStream(), "utf-8"); source = new StringBuilder(); while ( scanner.hasNextLine() ) { source.append(scanner.nextLine()); source.append('\n'); } scanner.close(); return source.toString(); } catch ( Exception e ) { e.printStackTrace(); if ( scanner != null ) scanner.close(); return null; } } }
924308f6cbb10144a44f7aa8433e322984d7fa4a
2,578
java
Java
src/main/java/org/trypticon/luceneupgrader/lucene6/internal/lucene/search/DocIdSetIterator.java
tonysun83/luceneupgrader
78ba2823e872baa4e08d7f15bdfdbe5811530abd
[ "Apache-2.0" ]
1
2021-07-06T07:11:27.000Z
2021-07-06T07:11:27.000Z
src/main/java/org/trypticon/luceneupgrader/lucene6/internal/lucene/search/DocIdSetIterator.java
tonysun83/luceneupgrader
78ba2823e872baa4e08d7f15bdfdbe5811530abd
[ "Apache-2.0" ]
3
2017-01-12T23:30:18.000Z
2019-02-20T00:17:21.000Z
src/main/java/org/trypticon/luceneupgrader/lucene6/internal/lucene/search/DocIdSetIterator.java
tonysun83/luceneupgrader
78ba2823e872baa4e08d7f15bdfdbe5811530abd
[ "Apache-2.0" ]
1
2021-12-21T21:50:57.000Z
2021-12-21T21:50:57.000Z
24.788462
75
0.635764
1,002,499
/* * 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.trypticon.luceneupgrader.lucene6.internal.lucene.search; import java.io.IOException; public abstract class DocIdSetIterator { public static final DocIdSetIterator empty() { return new DocIdSetIterator() { boolean exhausted = false; @Override public int advance(int target) { assert !exhausted; assert target >= 0; exhausted = true; return NO_MORE_DOCS; } @Override public int docID() { return exhausted ? NO_MORE_DOCS : -1; } @Override public int nextDoc() { assert !exhausted; exhausted = true; return NO_MORE_DOCS; } @Override public long cost() { return 0; } }; } public static final DocIdSetIterator all(int maxDoc) { return new DocIdSetIterator() { int doc = -1; @Override public int docID() { return doc; } @Override public int nextDoc() throws IOException { return advance(doc + 1); } @Override public int advance(int target) throws IOException { doc = target; if (doc >= maxDoc) { doc = NO_MORE_DOCS; } return doc; } @Override public long cost() { return maxDoc; } }; } public static final int NO_MORE_DOCS = Integer.MAX_VALUE; public abstract int docID(); public abstract int nextDoc() throws IOException; public abstract int advance(int target) throws IOException; protected final int slowAdvance(int target) throws IOException { assert docID() < target; int doc; do { doc = nextDoc(); } while (doc < target); return doc; } public abstract long cost(); }
92430b12f403115d95f7265b902ebee3bb2d1da8
13,523
java
Java
commandfamily-system/src/main/java/com/taptrack/tcmptappy2/commandfamilies/systemfamily/SystemCommandResolver.java
TapTrack/TCMPTappy-Android
cbacf81cd24cae06f0475427f02ea1879dd9c655
[ "Apache-2.0" ]
3
2018-09-11T10:26:34.000Z
2020-06-02T04:37:38.000Z
commandfamily-system/src/main/java/com/taptrack/tcmptappy2/commandfamilies/systemfamily/SystemCommandResolver.java
TapTrack/TCMPTappy-Android
cbacf81cd24cae06f0475427f02ea1879dd9c655
[ "Apache-2.0" ]
3
2018-03-13T12:41:33.000Z
2022-01-24T17:31:58.000Z
commandfamily-system/src/main/java/com/taptrack/tcmptappy2/commandfamilies/systemfamily/SystemCommandResolver.java
TapTrack/TCMPTappy-Android
cbacf81cd24cae06f0475427f02ea1879dd9c655
[ "Apache-2.0" ]
2
2019-11-05T16:23:14.000Z
2021-04-30T19:49:07.000Z
44.483553
111
0.716261
1,002,500
package com.taptrack.tcmptappy2.commandfamilies.systemfamily; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.Size; import com.taptrack.tcmptappy2.CommandFamilyMessageResolver; import com.taptrack.tcmptappy2.MalformedPayloadException; import com.taptrack.tcmptappy2.TCMPMessage; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.commands.ActivateBlueLEDCommand; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.commands.ActivateBlueLEDForDurationCommand; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.commands.ActivateBuzzerCommand; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.commands.ActivateBuzzerForDurationCommand; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.commands.ActivateGreenLEDCommand; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.commands.ActivateGreenLEDForDurationCommand; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.commands.ActivateRedLEDCommand; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.commands.ActivateRedLEDForDurationCommand; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.commands.ConfigureKioskModeCommand; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.commands.ConfigureOnboardScanCooldownCommand; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.commands.DeactivateBlueLEDCommand; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.commands.DeactivateBuzzerCommand; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.commands.DeactivateGreenLEDCommand; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.commands.DeactivateRedLEDCommand; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.commands.DisableHostHeartbeatTransmissionCommand; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.commands.GetBatteryLevelCommand; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.commands.GetClockStatusCommand; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.commands.GetFirmwareVersionCommand; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.commands.GetHardwareVersionCommand; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.commands.GetIndicatorStatusCommand; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.commands.GetBootConfigCommand; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.commands.PingCommand; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.commands.SetConfigItemCommand; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.commands.SetBootConfigCommand; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.responses.BlueLEDActivatedResponse; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.responses.BlueLEDDeactivatedResponse; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.responses.BuzzerActivatedResponse; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.responses.BuzzerDeactivatedResponse; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.responses.ClockStatusResponse; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.responses.ConfigItemResponse; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.responses.ConfigureKioskModeResponse; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.responses.ConfigureOnboardScanCooldownResponse; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.responses.CrcMismatchErrorResponse; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.responses.DisableHostHeartbeatTransmissionResponse; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.responses.FirmwareVersionResponse; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.responses.GetBatteryLevelResponse; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.responses.GetBootConfigResponse; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.responses.GreenLEDActivatedResponse; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.responses.GreenLEDDeactivatedResponse; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.responses.HardwareVersionResponse; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.responses.ImproperMessageFormatResponse; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.responses.IndicatorStatusResponse; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.responses.LcsMismatchErrorResponse; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.responses.LengthMismatchErrorResponse; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.responses.PingResponse; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.responses.RedLEDActivatedResponse; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.responses.RedLEDDeactivatedResponse; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.responses.SetBootConfigResponse; import com.taptrack.tcmptappy2.commandfamilies.systemfamily.responses.SystemErrorResponse; import java.util.Arrays; public class SystemCommandResolver implements CommandFamilyMessageResolver { public static final byte[] FAMILY_ID = new byte[]{0x00,0x00}; private static void assertFamilyMatches(@NonNull TCMPMessage message) { if (!Arrays.equals(message.getCommandFamily(),FAMILY_ID)) { throw new IllegalArgumentException("Specified message is for a different command family"); } } @Override @Nullable public TCMPMessage resolveCommand(@NonNull TCMPMessage message) throws MalformedPayloadException { assertFamilyMatches(message); TCMPMessage parsedMessage; switch (message.getCommandCode()) { case GetHardwareVersionCommand.COMMAND_CODE: parsedMessage = new GetHardwareVersionCommand(); break; case GetFirmwareVersionCommand.COMMAND_CODE: parsedMessage = new GetFirmwareVersionCommand(); break; case GetBatteryLevelCommand.COMMAND_CODE: parsedMessage = new GetBatteryLevelCommand(); break; case GetClockStatusCommand.COMMAND_CODE: parsedMessage = new GetClockStatusCommand(); break; case PingCommand.COMMAND_CODE: parsedMessage = new PingCommand(); break; case SetConfigItemCommand.COMMAND_CODE: parsedMessage = new SetConfigItemCommand(); break; case ConfigureKioskModeCommand.COMMAND_CODE: parsedMessage = new ConfigureKioskModeCommand(); break; case ConfigureOnboardScanCooldownCommand.COMMAND_CODE: parsedMessage = new ConfigureOnboardScanCooldownCommand(); break; case ActivateBlueLEDCommand.COMMAND_CODE: parsedMessage = new ActivateBlueLEDCommand(); break; case ActivateRedLEDCommand.COMMAND_CODE: parsedMessage = new ActivateRedLEDCommand(); break; case ActivateGreenLEDCommand.COMMAND_CODE: parsedMessage = new ActivateGreenLEDCommand(); break; case ActivateBuzzerCommand.COMMAND_CODE: parsedMessage = new ActivateBuzzerCommand(); break; case DeactivateBlueLEDCommand.COMMAND_CODE: parsedMessage = new DeactivateBlueLEDCommand(); break; case DeactivateRedLEDCommand.COMMAND_CODE: parsedMessage = new DeactivateRedLEDCommand(); break; case DeactivateGreenLEDCommand.COMMAND_CODE: parsedMessage = new DeactivateGreenLEDCommand(); break; case DeactivateBuzzerCommand.COMMAND_CODE: parsedMessage = new DeactivateBuzzerCommand(); break; case ActivateBlueLEDForDurationCommand.COMMAND_CODE: parsedMessage = new ActivateBlueLEDForDurationCommand(); break; case ActivateRedLEDForDurationCommand.COMMAND_CODE: parsedMessage = new ActivateRedLEDForDurationCommand(); break; case ActivateGreenLEDForDurationCommand.COMMAND_CODE: parsedMessage = new ActivateGreenLEDForDurationCommand(); break; case ActivateBuzzerForDurationCommand.COMMAND_CODE: parsedMessage = new ActivateBuzzerForDurationCommand(); break; case GetIndicatorStatusCommand.COMMAND_CODE: parsedMessage = new GetIndicatorStatusCommand(); break; case DisableHostHeartbeatTransmissionCommand.COMMAND_CODE: parsedMessage = new DisableHostHeartbeatTransmissionCommand(); break; case GetBootConfigCommand.COMMAND_CODE: parsedMessage = new GetBootConfigCommand(); break; case SetBootConfigCommand.COMMAND_CODE: parsedMessage = new SetBootConfigCommand(); break; default: return null; } parsedMessage.parsePayload(message.getPayload()); return parsedMessage; } @Override @Nullable public TCMPMessage resolveResponse(@NonNull TCMPMessage message) throws MalformedPayloadException { assertFamilyMatches(message); TCMPMessage parsedMessage; switch (message.getCommandCode()) { case ConfigItemResponse.COMMAND_CODE: parsedMessage = new ConfigItemResponse(); break; case ConfigureKioskModeResponse.COMMAND_CODE: parsedMessage = new ConfigureKioskModeResponse(); break; case CrcMismatchErrorResponse.COMMAND_CODE: parsedMessage = new CrcMismatchErrorResponse(); break; case FirmwareVersionResponse.COMMAND_CODE: parsedMessage = new FirmwareVersionResponse(); break; case GetBatteryLevelResponse.COMMAND_CODE: parsedMessage = new GetBatteryLevelResponse(); break; case HardwareVersionResponse.COMMAND_CODE: parsedMessage = new HardwareVersionResponse(); break; case ClockStatusResponse.COMMAND_CODE: parsedMessage = new ClockStatusResponse(); break; case ImproperMessageFormatResponse.COMMAND_CODE: parsedMessage = new ImproperMessageFormatResponse(); break; case LcsMismatchErrorResponse.COMMAND_CODE: parsedMessage = new LcsMismatchErrorResponse(); break; case LengthMismatchErrorResponse.COMMAND_CODE: parsedMessage = new LengthMismatchErrorResponse(); break; case PingResponse.COMMAND_CODE: parsedMessage = new PingResponse(); break; case SystemErrorResponse.COMMAND_CODE: parsedMessage = new SystemErrorResponse(); break; case ConfigureOnboardScanCooldownResponse.COMMAND_CODE: parsedMessage = new ConfigureOnboardScanCooldownResponse(); break; case BlueLEDActivatedResponse.COMMAND_CODE: parsedMessage = new BlueLEDActivatedResponse(); break; case RedLEDActivatedResponse.COMMAND_CODE: parsedMessage = new RedLEDActivatedResponse(); break; case GreenLEDActivatedResponse.COMMAND_CODE: parsedMessage = new GreenLEDActivatedResponse(); break; case BuzzerActivatedResponse.COMMAND_CODE: parsedMessage = new BuzzerActivatedResponse(); break; case BlueLEDDeactivatedResponse.COMMAND_CODE: parsedMessage = new BlueLEDDeactivatedResponse(); break; case RedLEDDeactivatedResponse.COMMAND_CODE: parsedMessage = new RedLEDDeactivatedResponse(); break; case GreenLEDDeactivatedResponse.COMMAND_CODE: parsedMessage = new GreenLEDDeactivatedResponse(); break; case BuzzerDeactivatedResponse.COMMAND_CODE: parsedMessage = new BuzzerDeactivatedResponse(); break; case IndicatorStatusResponse.COMMAND_CODE: parsedMessage = new IndicatorStatusResponse(); break; case DisableHostHeartbeatTransmissionResponse.COMMAND_CODE: parsedMessage = new DisableHostHeartbeatTransmissionResponse(); break; case GetBootConfigResponse.COMMAND_CODE: parsedMessage = new GetBootConfigResponse(); break; case SetBootConfigResponse.COMMAND_CODE: parsedMessage = new SetBootConfigResponse(); break; default: return null; } parsedMessage.parsePayload(message.getPayload()); return parsedMessage; } @Override @NonNull @Size(2) public byte[] getCommandFamilyId() { return FAMILY_ID; } }
92430b919ea82b5c705d50bb9c3bd4e9b416a904
1,337
java
Java
Aemora/src/aemora/Camera.java
sahrayusuf/2017-2018
2c795e47e0036e73ff9f88dcb0972cf6c0ec2a91
[ "MIT" ]
null
null
null
Aemora/src/aemora/Camera.java
sahrayusuf/2017-2018
2c795e47e0036e73ff9f88dcb0972cf6c0ec2a91
[ "MIT" ]
null
null
null
Aemora/src/aemora/Camera.java
sahrayusuf/2017-2018
2c795e47e0036e73ff9f88dcb0972cf6c0ec2a91
[ "MIT" ]
null
null
null
26.215686
70
0.532536
1,002,501
package aemora; import org.newdawn.slick.Graphics; import org.newdawn.slick.geom.Rectangle; import org.newdawn.slick.tiled.TiledMap; public class Camera { private int x, y; private int mapWidth, mapHeight; private Rectangle viewPort; public Camera(TiledMap map, int mapWidth, int mapHeight) { x = 0; y = 0; viewPort = new Rectangle(0, 0, Aemora.WIDTH, Aemora.HEIGHT); //viewPort = new Rectangle(0, 0, mapWidth, mapWidth); this.mapWidth = mapWidth; this.mapHeight = mapWidth; } public void translate(Graphics g, Player hero) { if (hero.getX() - Aemora.WIDTH / 2 + 16 < 0) { x = 0; } else if (hero.getX() + Aemora.WIDTH / 2 + 16 > mapWidth) { x = -mapWidth + Aemora.WIDTH; } else { x = (int) -hero.getX() + Aemora.WIDTH / 2 - 16; } if (hero.getY() - Aemora.HEIGHT / 2 + 16 < 0) { y = 0; } else if (hero.getY() + Aemora.HEIGHT / 2 + 16 > mapHeight) { y = -mapHeight + Aemora.HEIGHT; } else { y = (int) -hero.getY() + Aemora.HEIGHT / 2 - 16; } g.translate(x, y); viewPort.setX(-x); viewPort.setY(-y); } public int getX() { return x; } public int getY() { return y; } }
92430bef50fe4550caa8965013f5e989c41df2b8
217
java
Java
src/main/java/com/pubnub/api/models/consumer/presence/PNGetStateResult.java
edgarbravo/prueba
9ae87832baa51daddd3fe44f46d16836cbd2cb4b
[ "MIT" ]
6
2016-03-07T13:51:29.000Z
2018-06-05T09:26:35.000Z
src/main/java/com/pubnub/api/models/consumer/presence/PNGetStateResult.java
edgarbravo/prueba
9ae87832baa51daddd3fe44f46d16836cbd2cb4b
[ "MIT" ]
null
null
null
src/main/java/com/pubnub/api/models/consumer/presence/PNGetStateResult.java
edgarbravo/prueba
9ae87832baa51daddd3fe44f46d16836cbd2cb4b
[ "MIT" ]
null
null
null
14.466667
48
0.774194
1,002,502
package com.pubnub.api.models.consumer.presence; import lombok.Builder; import lombok.Getter; import java.util.Map; @Builder @Getter public class PNGetStateResult { private Map<String, Object> stateByUUID; }
92430c224e58d5b8c9aaf9132d5c6e2f5cec392d
1,034
java
Java
dbapi/src/main/java/com/griddynamics/jagger/dbapi/entity/MetricSummaryEntity.java
MysterionRise/jagger
be56655e3b4538b045a023a13302735275e01bd0
[ "Apache-2.0" ]
46
2015-02-02T03:19:45.000Z
2021-04-26T20:13:13.000Z
dbapi/src/main/java/com/griddynamics/jagger/dbapi/entity/MetricSummaryEntity.java
MysterionRise/jagger
be56655e3b4538b045a023a13302735275e01bd0
[ "Apache-2.0" ]
104
2015-01-12T09:36:59.000Z
2019-04-18T08:43:27.000Z
dbapi/src/main/java/com/griddynamics/jagger/dbapi/entity/MetricSummaryEntity.java
MysterionRise/jagger
be56655e3b4538b045a023a13302735275e01bd0
[ "Apache-2.0" ]
37
2015-01-09T14:46:15.000Z
2021-08-22T09:00:15.000Z
21.102041
81
0.698259
1,002,503
package com.griddynamics.jagger.dbapi.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; @Entity public class MetricSummaryEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private Double total; @OneToOne private MetricDescriptionEntity metricDescription; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Double getTotal() { return total; } public void setTotal(Double total) { this.total = total; } public MetricDescriptionEntity getMetricDescription() { return metricDescription; } public void setMetricDescription(MetricDescriptionEntity metricDescription) { this.metricDescription = metricDescription; } public String getDisplay() { return metricDescription.getDisplay(); } }
92430cf1b0a8ebd46058db3b23e61b8cbef8be63
734
java
Java
FCTRL2/FCTRL2.java
tope96/spoj-solutions
e016697ae548c791f81ccf1c63b07343a8c22708
[ "MIT" ]
null
null
null
FCTRL2/FCTRL2.java
tope96/spoj-solutions
e016697ae548c791f81ccf1c63b07343a8c22708
[ "MIT" ]
null
null
null
FCTRL2/FCTRL2.java
tope96/spoj-solutions
e016697ae548c791f81ccf1c63b07343a8c22708
[ "MIT" ]
null
null
null
23.677419
61
0.641689
1,002,504
import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class FCTRL2 { private static String factorial(int number) { BigInteger result = new BigInteger("1"); for (int i = 1; i <= number; i++) { result = result.multiply(new BigInteger(i + "")); } return result.toString(); } public static void main(String[] args) { Scanner input = new Scanner(System.in); int howManyLines = Short.parseShort(input.nextLine()); List<String> all = new ArrayList<String>(); while(howManyLines != 0){ all.add(factorial(input.nextInt())); howManyLines--; } for(String i : all) { System.out.println(i); } input.close(); } }
92430d4450d5da22f4822a8206c26f109ee05e96
1,854
java
Java
src/net/poczone/framework/tools/Passwords.java
poczone/poczone-backend
bcdea9ea24e88c4fa857d0da517c3e2ab47b3dda
[ "MIT" ]
null
null
null
src/net/poczone/framework/tools/Passwords.java
poczone/poczone-backend
bcdea9ea24e88c4fa857d0da517c3e2ab47b3dda
[ "MIT" ]
null
null
null
src/net/poczone/framework/tools/Passwords.java
poczone/poczone-backend
bcdea9ea24e88c4fa857d0da517c3e2ab47b3dda
[ "MIT" ]
null
null
null
26.485714
95
0.686084
1,002,505
package net.poczone.framework.tools; import java.io.IOException; import java.security.MessageDigest; import java.security.SecureRandom; import java.util.Arrays; import java.util.Random; public class Passwords { private static final String HASH_ALGORITHM = "SHA-256"; private static final int SALT_BYTES = 16; private static Random random = new SecureRandom(); public static synchronized String encode(String password) throws IOException { byte[] salt = generateSalt(); byte[] hash = hash(password, salt); return toHex(salt) + ":" + toHex(hash); } public static boolean check(String inputPassword, String encodedPassword) throws IOException { String[] parts = encodedPassword.split(":"); if (parts.length < 2) { return false; } byte[] salt = fromHex(parts[0]); byte[] prevHash = fromHex(parts[1]); byte[] hash = hash(inputPassword, salt); return Arrays.equals(hash, prevHash); } private static byte[] generateSalt() { byte[] salt = new byte[SALT_BYTES]; random.nextBytes(salt); return salt; } private static byte[] hash(String password, byte[] salt) throws IOException { try { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(salt); if (password != null) { md.update(password.getBytes("UTF-8")); } return md.digest(); } catch (Exception e) { throw new IOException("Failed to compute password hash", e); } } private static String toHex(byte[] bytes) { StringBuilder sb = new StringBuilder(); for (byte b : bytes) { sb.append(Integer.toHexString(0x100 | (0xff & b)).substring(1)); } return sb.toString(); } private static byte[] fromHex(String hex) { byte[] bytes = new byte[hex.length() / 2]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16); } return bytes; } }
92430db83a0a63555a25c13e2370b9702c2c73ec
6,952
java
Java
ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystTouchBubblingTestCase.java
sjchmiela/react-native
9d6d39de86057f92d41a9f7eed7fdddf1ac09582
[ "CC-BY-4.0", "MIT" ]
118,175
2015-03-26T17:08:03.000Z
2022-03-31T21:59:02.000Z
ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystTouchBubblingTestCase.java
sjchmiela/react-native
9d6d39de86057f92d41a9f7eed7fdddf1ac09582
[ "CC-BY-4.0", "MIT" ]
32,609
2015-03-26T17:13:50.000Z
2022-03-31T23:29:53.000Z
ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystTouchBubblingTestCase.java
sjchmiela/react-native
9d6d39de86057f92d41a9f7eed7fdddf1ac09582
[ "CC-BY-4.0", "MIT" ]
29,857
2015-03-26T17:09:01.000Z
2022-03-31T13:25:02.000Z
44.564103
100
0.523734
1,002,506
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.tests; import android.view.View; import com.facebook.react.testing.ReactAppInstrumentationTestCase; import com.facebook.react.testing.ReactInstanceSpecForTest; import com.facebook.react.testing.SingleTouchGestureGenerator; import com.facebook.react.testing.StringRecordingModule; /** * This test is to verify that touch events bubbles up to the right handler. We emulate couple of * different gestures on top of the application reflecting following layout: * * <pre> * +---------------------------------------------------------------------------------------+ * | | * | +----------------------------------------------------------------------------------+ | * | | +-------------+ +----------------+ | | * | | | +---+ | | | | | * | | | | A | | | | | | * | | | +---+ | | C | | | * | | | {B} | | | | | * | | | | {D} | | | | * | | +-------------+ +----------------+ | | * | | | | * | | | | * | +----------------------------------------------------------------------------------+ | * | * | +----------------------------------------------------------------------------------+ | * | | | | * | | | | * | | | | * | | {E} | | * | | | | * | | | | * | +----------------------------------------------------------------------------------+ | * +---------------------------------------------------------------------------------------+ * </pre> * * <p>Then in each test case we either tap the center of a particular view (from A to E) or we start * a gesture in one view and end it with another. View with names in brackets (e.g. {D}) have touch * handlers set whereas all other views are not declared to handler touch events. */ public class CatalystTouchBubblingTestCase extends ReactAppInstrumentationTestCase { private final StringRecordingModule mRecordingModule = new StringRecordingModule(); @Override protected String getReactApplicationKeyUnderTest() { return "TouchBubblingTestAppModule"; } /** * 1) Simulate touch event at view A, expect {B} touch handler to fire 2) Simulate touch event at * view C, expect {D} touch handler to fire */ public void testSimpleClickAtInnerElements() { mRecordingModule.reset(); View innerButton = getViewByTestId("A"); assertNotNull(innerButton); createGestureGenerator().startGesture(innerButton).endGesture(); waitForBridgeAndUIIdle(); assertEquals(1, mRecordingModule.getCalls().size()); assertEquals("inner", mRecordingModule.getCalls().get(0)); mRecordingModule.reset(); innerButton = getViewByTestId("C"); assertNotNull(innerButton); createGestureGenerator().startGesture(innerButton).endGesture(); waitForBridgeAndUIIdle(); assertEquals(1, mRecordingModule.getCalls().size()); assertEquals("outer", mRecordingModule.getCalls().get(0)); } /** * 1) Start touch at view A, then drag and release on view {B} (but outside of A), expect {B}'s * touch handler to fire 2) Do the same with view C and {D} */ public void testDownOnInnerUpOnTouchableParent() { View innerButton = getViewByTestId("A"); View touchableParent = getViewByTestId("B"); SingleTouchGestureGenerator gestureGenerator = createGestureGenerator(); gestureGenerator.startGesture(innerButton); // wait for tapped view measurements waitForBridgeAndUIIdle(); gestureGenerator.dragTo(touchableParent, 15).endGesture(); waitForBridgeAndUIIdle(); assertEquals(1, mRecordingModule.getCalls().size()); assertEquals("inner", mRecordingModule.getCalls().get(0)); // Do same with second inner view mRecordingModule.reset(); touchableParent = getViewByTestId("D"); innerButton = getViewByTestId("C"); gestureGenerator = createGestureGenerator(); gestureGenerator.startGesture(innerButton); // wait for tapped view measurements waitForBridgeAndUIIdle(); gestureGenerator.dragTo(touchableParent, 15).endGesture(); waitForBridgeAndUIIdle(); assertEquals(1, mRecordingModule.getCalls().size()); assertEquals("outer", mRecordingModule.getCalls().get(0)); } /** * Start gesture at view A, then drag and release on view {E}. Expect no touch handlers to fire */ public void testDragOutOfTouchable() { View outsideView = getViewByTestId("E"); View innerButton = getViewByTestId("A"); SingleTouchGestureGenerator gestureGenerator = createGestureGenerator(); gestureGenerator.startGesture(innerButton); // wait for tapped view measurements waitForBridgeAndUIIdle(); gestureGenerator.dragTo(outsideView, 15).endGesture(); waitForBridgeAndUIIdle(); assertTrue(mRecordingModule.getCalls().isEmpty()); } /** * In this scenario we start gesture at view A (has two touchable parents {B} and {D}) then we * drag and release gesture on view {D}, but outside of {B}. We expect no touch handler to fire */ public void testNoEventWhenDragOutOfFirstTouchableParentToItsTouchableParent() { View topLevelTouchable = getViewByTestId("C"); View innerButton = getViewByTestId("A"); SingleTouchGestureGenerator gestureGenerator = createGestureGenerator(); gestureGenerator.startGesture(innerButton); // wait for tapped view measurements waitForBridgeAndUIIdle(); gestureGenerator.dragTo(topLevelTouchable, 15).endGesture(); waitForBridgeAndUIIdle(); assertTrue(mRecordingModule.getCalls().isEmpty()); } @Override protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { return new ReactInstanceSpecForTest().addNativeModule(mRecordingModule); } }
92430e07b495639da4af4944bbdfec8439754fd9
5,278
java
Java
ji-database/src/test/java/ji/migration/SingleMigrationToolTest.java
ondrej-nemec/javain
63493e721495d456765829e76f12af47cb6117ae
[ "MIT" ]
null
null
null
ji-database/src/test/java/ji/migration/SingleMigrationToolTest.java
ondrej-nemec/javain
63493e721495d456765829e76f12af47cb6117ae
[ "MIT" ]
null
null
null
ji-database/src/test/java/ji/migration/SingleMigrationToolTest.java
ondrej-nemec/javain
63493e721495d456765829e76f12af47cb6117ae
[ "MIT" ]
null
null
null
36.652778
176
0.710875
1,002,507
package ji.migration; import static org.junit.Assert.fail; import static org.mockito.Mockito.*; import java.sql.Connection; import org.junit.Test; import org.junit.runner.RunWith; import ji.common.Logger; import ji.migration.SingleMigrationTool; import ji.migration.migrations.JavaMigration; import ji.migration.migrations.SqlMigration; import ji.querybuilder.QueryBuilder; import ji.querybuilder.builders.DeleteBuilder; import ji.querybuilder.builders.InsertBuilder; import junitparams.JUnitParamsRunner; import junitparams.Parameters; @RunWith(JUnitParamsRunner.class) public class SingleMigrationToolTest { private final static String MIGRATION_TABLE = "migrations"; private final static String ALLWAYS_ID = "ALLWAYS"; private static final String SEPARATOR = "__"; @Test @Parameters(method = "dataTransactionWithWorkingMigration") public void testTransactionWithWorkingMigration( String name, String extension, int javaCount, int sqlCount, boolean isRevert) throws Exception { Connection con = mock(Connection.class); InsertBuilder insert = mock(InsertBuilder.class); when(insert.addValue(any(), any())).thenReturn(insert); DeleteBuilder delete = mock(DeleteBuilder.class); when(delete.where(any())).thenReturn(delete); when(delete.andWhere(any())).thenReturn(delete); when(delete.addParameter(any(), any())).thenReturn(delete); QueryBuilder builder = mock(QueryBuilder.class); when(builder.getConnection()).thenReturn(con); when(builder.insert(MIGRATION_TABLE)).thenReturn(insert); when(builder.delete(MIGRATION_TABLE)).thenReturn(delete); SqlMigration sql = mock(SqlMigration.class); JavaMigration java = mock(JavaMigration.class); SingleMigrationTool tool = new SingleMigrationTool("module", MIGRATION_TABLE, ALLWAYS_ID, SEPARATOR, java, sql, mock(Logger.class)); tool.transaction(name + "." + extension, builder, isRevert); if (!isRevert) { verify(insert, times(4)).addValue(any(), any()); verify(insert, times(1)).execute(); } else { verify(delete, times(1)).where(any()); verify(delete, times(1)).andWhere(any()); verify(delete, times(2)).addParameter(any(), any()); verify(delete, times(1)).execute(); } verifyNoMoreInteractions(insert); verifyNoMoreInteractions(delete); verify(builder, times(1)).getConnection(); verify(builder, times(isRevert ? 1 : 0)).delete(MIGRATION_TABLE); verify(builder, times(isRevert ? 0 : 1)).insert(MIGRATION_TABLE); verifyNoMoreInteractions(builder); verify(sql, times(sqlCount)).migrate(name + ".sql", builder); verifyNoMoreInteractions(sql); verify(java, times(javaCount)).migrate(name, builder); verifyNoMoreInteractions(java); verify(con, times(1)).setAutoCommit(false); verify(con, times(1)).commit(); verifyNoMoreInteractions(con); } public Object[] dataTransactionWithWorkingMigration() { return new Object[] { new Object[] {"Id__desc", "sql", 0, 1, false}, new Object[] {"Id__desc", "java", 1, 0, false}, new Object[] {"Id__desc", "sql", 0, 1, true}, new Object[] {"Id__desc", "java", 1, 0, true} }; } @Test @Parameters(method = "dataTransactionWithThrowingMigration") public void testTransactionWithThrowingMigration(String file, int javaCount, int sqlCount, String name, boolean isRevert) throws Exception { Connection con = mock(Connection.class); QueryBuilder builder = mock(QueryBuilder.class); when(builder.getConnection()).thenReturn(con); SingleMigrationTool tool = new SingleMigrationTool("module", MIGRATION_TABLE, ALLWAYS_ID, SEPARATOR, null, null, mock(Logger.class)); // java, sql null for throwing exceptin try { tool.transaction(file, builder, isRevert); fail("NullPointerException required"); } catch (NullPointerException e) { // expected - simulate throwing migration } verify(builder, times(1)).getConnection(); verifyNoMoreInteractions(builder); verify(con, times(1)).setAutoCommit(false); verify(con, times(1)).rollback(); verifyNoMoreInteractions(con); } public Object[] dataTransactionWithThrowingMigration() { return new Object[] { new Object[] {"Id__desc.sql", 0, 1, "Id", false}, new Object[] {"Id__desc.java", 1, 0, "Id", false}, new Object[] {"Id__desc.sql", 0, 1, "Id", true}, new Object[] {"Id__desc.java", 1, 0, "Id", true} }; } @Test public void testTransactionWithAllwaysMigration() throws Exception { Connection con = mock(Connection.class); QueryBuilder builder = mock(QueryBuilder.class); when(builder.getConnection()).thenReturn(con); SqlMigration sql = mock(SqlMigration.class); JavaMigration java = mock(JavaMigration.class); SingleMigrationTool tool = new SingleMigrationTool("module", MIGRATION_TABLE, ALLWAYS_ID, SEPARATOR, java, sql, mock(Logger.class)); tool.transaction("ALLWAYS_1__desc.java", builder, false); tool.transaction("ALLWAYS_1__desc.sql", builder, false); verify(builder, times(2)).getConnection(); verifyNoMoreInteractions(builder); verify(con, times(2)).setAutoCommit(false); verify(con, times(2)).commit(); verifyNoMoreInteractions(con); } }
92430ead971e02ab53f1c0fcc072a0893a8a8678
430
java
Java
org.spoofax.jsglr2.benchmark/src/main/java/org/spoofax/jsglr2/benchmark/jsglr2/datastructures/JSGLR2StateApplicableGotosBenchmarkJava8.java
pmisteliac/jsglr
61c300c5704e65d7d26346f82c4d2b938a0eef95
[ "Apache-2.0" ]
7
2015-03-04T19:04:58.000Z
2021-06-05T07:40:30.000Z
org.spoofax.jsglr2.benchmark/src/main/java/org/spoofax/jsglr2/benchmark/jsglr2/datastructures/JSGLR2StateApplicableGotosBenchmarkJava8.java
pmisteliac/jsglr
61c300c5704e65d7d26346f82c4d2b938a0eef95
[ "Apache-2.0" ]
20
2017-09-14T13:15:52.000Z
2022-01-07T14:59:40.000Z
org.spoofax.jsglr2.benchmark/src/main/java/org/spoofax/jsglr2/benchmark/jsglr2/datastructures/JSGLR2StateApplicableGotosBenchmarkJava8.java
pmisteliac/jsglr
61c300c5704e65d7d26346f82c4d2b938a0eef95
[ "Apache-2.0" ]
8
2015-03-04T19:05:13.000Z
2021-05-21T09:52:55.000Z
33.076923
99
0.839535
1,002,508
package org.spoofax.jsglr2.benchmark.jsglr2.datastructures; import org.spoofax.jsglr2.benchmark.BenchmarkTestSetWithParseTableReader; import org.spoofax.jsglr2.testset.TestSet; public class JSGLR2StateApplicableGotosBenchmarkJava8 extends JSGLR2StateApplicableGotosBenchmark { public JSGLR2StateApplicableGotosBenchmarkJava8() { setTestSetReader(new BenchmarkTestSetWithParseTableReader<>(TestSet.java8)); } }
92430f2e451042f0cc8c6dd10165d35394084c26
383
java
Java
src/main/java/com/alipay/api/response/AlipayOpenMiniInnerversionOnlineResponse.java
alipay/alipay-sdk-java-all
e87bc8e7f6750e168a5f9d37221124c085d1e3c1
[ "Apache-2.0" ]
333
2018-08-28T09:26:55.000Z
2022-03-31T07:26:42.000Z
src/main/java/com/alipay/api/response/AlipayOpenMiniInnerversionOnlineResponse.java
alipay/alipay-sdk-java-all
e87bc8e7f6750e168a5f9d37221124c085d1e3c1
[ "Apache-2.0" ]
46
2018-09-27T03:52:42.000Z
2021-08-10T07:54:57.000Z
src/main/java/com/alipay/api/response/AlipayOpenMiniInnerversionOnlineResponse.java
alipay/alipay-sdk-java-all
e87bc8e7f6750e168a5f9d37221124c085d1e3c1
[ "Apache-2.0" ]
158
2018-12-07T17:03:43.000Z
2022-03-17T09:32:43.000Z
18.238095
79
0.718016
1,002,509
package com.alipay.api.response; import com.alipay.api.AlipayResponse; /** * ALIPAY API: alipay.open.mini.innerversion.online response. * * @author auto create * @since 1.0, 2019-06-13 20:43:23 */ public class AlipayOpenMiniInnerversionOnlineResponse extends AlipayResponse { private static final long serialVersionUID = 6414969935132311221L; }
92430fe78fef11e8f6e0ae4a7d46ee025a47ba69
2,149
java
Java
security/src/main/java/ru/airlightvt/onlinerecognition/security/rest/CustomSavedRequestAwareAuthenticationSuccessHandler.java
ALVirtualTech/PetSearchBackend
a4ec7dfed712afc501b9cbc5f765bcaa5dbf4fa6
[ "Apache-2.0" ]
null
null
null
security/src/main/java/ru/airlightvt/onlinerecognition/security/rest/CustomSavedRequestAwareAuthenticationSuccessHandler.java
ALVirtualTech/PetSearchBackend
a4ec7dfed712afc501b9cbc5f765bcaa5dbf4fa6
[ "Apache-2.0" ]
21
2020-02-15T16:58:19.000Z
2020-03-29T19:19:23.000Z
security/src/main/java/ru/airlightvt/onlinerecognition/security/rest/CustomSavedRequestAwareAuthenticationSuccessHandler.java
ALVirtualTech/OnlinePetSearchService
a4ec7dfed712afc501b9cbc5f765bcaa5dbf4fa6
[ "Apache-2.0" ]
null
null
null
37.701754
118
0.744532
1,002,510
package ru.airlightvt.onlinerecognition.security.rest; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; import org.springframework.security.web.savedrequest.HttpSessionRequestCache; import org.springframework.security.web.savedrequest.RequestCache; import org.springframework.security.web.savedrequest.SavedRequest; import org.springframework.util.StringUtils; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Кастомный обработчик успешной авторизации для REST сервисов: * вместо редиректа с кодом 301 возвращает 200 OK * (@link{SimpleUrlAuthenticationSuccessHandler} позволяет задать URL, на который перейдет после успешной авторизации) * * @author apolyakov * @since 06.01.2019 */ public class CustomSavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { //кэш для хранения данных аутентификации в течении некоторого времени private RequestCache requestCache = new HttpSessionRequestCache(); @Override public void onAuthenticationSuccess( HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { SavedRequest savedRequest = requestCache.getRequest(request, response); if (savedRequest == null) { clearAuthenticationAttributes(request); return; } String targetUrlParam = getTargetUrlParameter(); if (isAlwaysUseDefaultTargetUrl() || (targetUrlParam != null && StringUtils.hasText(request.getParameter(targetUrlParam)))) { requestCache.removeRequest(request, response); clearAuthenticationAttributes(request); return; } clearAuthenticationAttributes(request); } public void setRequestCache(RequestCache requestCache) { this.requestCache = requestCache; } }
92431199f9c3d39eae50c08b486cbeca1e01012f
527
java
Java
Recursion/Recursion_Twins.java
sjsid9/Coding-Problems
fb1a54a19857ce3cc74608afe667bbed3875c0a0
[ "Apache-2.0" ]
1
2018-09-17T13:29:06.000Z
2018-09-17T13:29:06.000Z
Recursion/Recursion_Twins.java
sjsid9/Coding-Problems
fb1a54a19857ce3cc74608afe667bbed3875c0a0
[ "Apache-2.0" ]
null
null
null
Recursion/Recursion_Twins.java
sjsid9/Coding-Problems
fb1a54a19857ce3cc74608afe667bbed3875c0a0
[ "Apache-2.0" ]
null
null
null
17
63
0.616698
1,002,511
import java.util.Scanner; public class Recursion_Twins { public static void main(String[] args) { Scanner s = new Scanner(System.in); String str=s.nextLine(); findTwins(str,0); } private static void findTwins(String str, int count) { if(str.equals("")) { System.out.println(count); return; } char ch=str.charAt(0); String ros=str.substring(1); if(!ros.equals("") && ros.length()>=2 && ch==ros.charAt(1)) { findTwins(ros, count+1); }else { findTwins(ros, count); } } }
924311ecdaccafbb93fe62a2aaf05931f36a3b27
45,510
java
Java
src/test/java/walkingkooka/spreadsheet/engine/SpreadsheetDeltaWindowedTest.java
mP1/walkingkooka-squares
0def91fbbffef8140d1235c14d985faff4a0cb50
[ "Apache-2.0" ]
1
2019-04-07T09:54:47.000Z
2019-04-07T09:54:47.000Z
src/test/java/walkingkooka/spreadsheet/engine/SpreadsheetDeltaWindowedTest.java
mP1/walkingkooka-squares
0def91fbbffef8140d1235c14d985faff4a0cb50
[ "Apache-2.0" ]
70
2018-10-16T08:42:13.000Z
2019-08-22T02:38:18.000Z
src/test/java/walkingkooka/spreadsheet/engine/SpreadsheetDeltaWindowedTest.java
mP1/walkingkooka-squares
0def91fbbffef8140d1235c14d985faff4a0cb50
[ "Apache-2.0" ]
null
null
null
40.852783
135
0.480971
1,002,512
/* * Copyright 2019 Miroslav Pokorny (github.com/mP1) * * 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 walkingkooka.spreadsheet.engine; import org.junit.jupiter.api.Test; import walkingkooka.collect.map.Maps; import walkingkooka.collect.set.Sets; import walkingkooka.spreadsheet.SpreadsheetCell; import walkingkooka.spreadsheet.SpreadsheetColumn; import walkingkooka.spreadsheet.SpreadsheetRow; import walkingkooka.spreadsheet.reference.SpreadsheetCellRange; import walkingkooka.spreadsheet.reference.SpreadsheetCellReference; import walkingkooka.spreadsheet.reference.SpreadsheetColumnReference; import walkingkooka.spreadsheet.reference.SpreadsheetLabelMapping; import walkingkooka.spreadsheet.reference.SpreadsheetLabelName; import walkingkooka.spreadsheet.reference.SpreadsheetRowReference; import walkingkooka.spreadsheet.reference.SpreadsheetSelection; import walkingkooka.spreadsheet.reference.SpreadsheetViewportSelection; import walkingkooka.tree.json.JsonNode; import walkingkooka.tree.json.JsonString; import java.util.Map; import java.util.Optional; import java.util.Set; import static org.junit.jupiter.api.Assertions.assertNotSame; public final class SpreadsheetDeltaWindowedTest extends SpreadsheetDeltaTestCase<SpreadsheetDeltaWindowed> { public SpreadsheetDeltaWindowedTest() { super(); this.checkNotEquals(this.window(), this.differentWindow(), "window v differentWindow must NOT be equal"); } @Test public void testSetLabelsMissingCellKept() { final SpreadsheetDeltaWindowed before = this.createSpreadsheetDelta(); final Set<SpreadsheetLabelMapping> different = Sets.of( SpreadsheetLabelName.labelName("Different") .mapping(SpreadsheetCellReference.parseCell("A3")) ); final SpreadsheetDelta after = before.setLabels(different); assertNotSame(before, after); this.checkLabels(after, different); this.checkCells(after, before.cells()); } @Test public void testSetLabelsOutsideWindowFiltered() { final SpreadsheetDeltaWindowed before = this.createSpreadsheetDelta(); final Set<SpreadsheetLabelMapping> different = Sets.of( SpreadsheetLabelName.labelName("Different").mapping(SpreadsheetCellReference.parseCell("Z99")) ); final SpreadsheetDelta after = before.setLabels(different); assertNotSame(before, after); this.checkLabels(after, SpreadsheetDelta.NO_LABELS); this.checkCells(after, before.cells()); } @Test public void testSetLabelsOutsideWindowFiltered2() { final SpreadsheetDeltaWindowed before = this.createSpreadsheetDelta(); final SpreadsheetCellReference a1 = this.a1().reference(); final SpreadsheetLabelName kept = SpreadsheetLabelName.labelName("Kept"); final SpreadsheetCellReference a3 = SpreadsheetCellReference.parseCell("A3"); final SpreadsheetLabelName kept3 = SpreadsheetLabelName.labelName("Kept2"); final Set<SpreadsheetLabelMapping> different = Sets.of( kept.mapping(a1), kept3.mapping(a3), SpreadsheetLabelName.labelName("Lost").mapping(SpreadsheetCellReference.parseCell("Z99")) ); final SpreadsheetDelta after = before.setLabels(different); assertNotSame(before, after); this.checkLabels(after, Sets.of(kept.mapping(a1), kept3.mapping(a3))); this.checkCells(after, before.cells()); } // setColumnWidths.................................................................................................. @Test public void testSetColumnWidthsOutsideWindowFiltered() { final SpreadsheetDeltaWindowed before = this.createSpreadsheetDelta(); final Map<SpreadsheetColumnReference, Double> different = Map.of( SpreadsheetSelection.parseColumn("F"), 30.0 ); final SpreadsheetDelta after = before.setColumnWidths(different); assertNotSame(before, after); this.checkColumnWidths(after, SpreadsheetDelta.NO_COLUMN_WIDTHS); this.checkCells(after, before.cells()); } @Test public void testSetColumnWidthsOutsideWindowFiltered2() { final SpreadsheetDeltaWindowed before = this.createSpreadsheetDelta(); final SpreadsheetColumnReference kept = SpreadsheetSelection.parseColumn("B"); final Map<SpreadsheetColumnReference, Double> different = Map.of( kept, 20.0, SpreadsheetSelection.parseColumn("F"), 30.0 ); final SpreadsheetDelta after = before.setColumnWidths(different); assertNotSame(before, after); this.checkColumnWidths( after, Map.of(kept, 20.0) ); this.checkCells(after, before.cells()); } // setRowHeights.................................................................................................. @Test public void testSetRowHeightsOutsideWindowFiltered() { final SpreadsheetDeltaWindowed before = this.createSpreadsheetDelta(); final Map<SpreadsheetRowReference, Double> different = Map.of( SpreadsheetSelection.parseRow("6"), 30.0 ); final SpreadsheetDelta after = before.setRowHeights(different); assertNotSame(before, after); this.checkRowHeights(after, SpreadsheetDelta.NO_ROW_HEIGHTS); this.checkCells(after, before.cells()); } @Test public void testSetRowHeightsOutsideWindowFiltered2() { final SpreadsheetDeltaWindowed before = this.createSpreadsheetDelta(); final SpreadsheetRowReference kept = SpreadsheetSelection.parseRow("2"); final Map<SpreadsheetRowReference, Double> different = Map.of( kept, 20.0, SpreadsheetSelection.parseRow("6"), 30.0 ); final SpreadsheetDelta after = before.setRowHeights(different); assertNotSame(before, after); this.checkRowHeights( after, Map.of(kept, 20.0) ); this.checkCells(after, before.cells()); } // setWindow........................................................................................................ @Test public void testSetWindowMultiple() { final Optional<SpreadsheetViewportSelection> selection = this.selection(); final SpreadsheetCell a1 = this.a1(); final SpreadsheetCell b2 = this.b2(); final Set<SpreadsheetCell> cells = Sets.of( a1, b2, this.c3() ); final SpreadsheetColumn a = this.a(); final SpreadsheetColumn b = this.b(); final SpreadsheetColumn c = this.c(); final Set<SpreadsheetColumn> columns = Sets.of( a, b, c ); final SpreadsheetLabelMapping labelA1a = this.label1a().mapping(a1.reference()); final SpreadsheetLabelMapping label2b = SpreadsheetSelection.labelName("label2b").mapping(b2.reference()); final Set<SpreadsheetLabelMapping> labels = Sets.of( labelA1a, label2b ); final SpreadsheetRow row1 = this.row1(); final SpreadsheetRow row2 = this.row2(); final Set<SpreadsheetRow> rows = Sets.of( row1, row2, this.row3() ); final SpreadsheetCellReference d4 = SpreadsheetSelection.parseCell("d4"); final SpreadsheetCellReference e5 = SpreadsheetSelection.parseCell("e5"); final Set<SpreadsheetCellReference> deletedCells = Sets.of( d4, e5 ); final SpreadsheetColumnReference e = SpreadsheetSelection.parseColumn("f"); final Set<SpreadsheetColumnReference> deletedColumns = Sets.of( e ); final SpreadsheetRowReference row5 = SpreadsheetSelection.parseRow("5"); final Set<SpreadsheetRowReference> deletedRows = Sets.of( row5 ); final Map<SpreadsheetColumnReference, Double> columnWidths = Maps.of( a.reference(), 10.0, b.reference(), 20.0, c.reference(), 30.0, e, 60.0 ); final Map<SpreadsheetRowReference, Double> rowHeights = Maps.of( this.row1().reference(), 10.0, this.row2().reference(), 20.0, this.row3().reference(), 30.0, row5, 60.0 ); final Set<SpreadsheetCellRange> window = SpreadsheetDelta.NO_WINDOW; final SpreadsheetDeltaWindowed before = SpreadsheetDeltaWindowed.withWindowed( selection, cells, columns, labels, rows, deletedCells, deletedColumns, deletedRows, columnWidths, rowHeights, window ); this.checkSelection(before, selection); this.checkCells(before, cells); this.checkColumns(before, columns); this.checkLabels(before, labels); this.checkRows(before, rows); this.checkDeletedCells(before, deletedCells); this.checkDeletedColumns(before, deletedColumns); this.checkDeletedRows(before, deletedRows); this.checkWindow(before, window); final Set<SpreadsheetCellRange> window2 = SpreadsheetSelection.parseWindow("a1,e5:f6"); final SpreadsheetDelta after = before.setWindow(window2); this.checkCells(after, Sets.of(a1)); this.checkColumns(after, Sets.of(a)); this.checkLabels(after, Sets.of(labelA1a)); this.checkRows(after, Sets.of(row1)); this.checkDeletedCells(after, Sets.of(e5)); this.checkDeletedColumns(after, Sets.of(e)); this.checkDeletedRows(after, Sets.of(row5)); this.checkWindow(after, window2); } // TreePrintable..................................................................................................... @Test public void testPrintTreeEmptyOnlyWindow() { this.treePrintAndCheck( SpreadsheetDeltaWindowed.withWindowed( SpreadsheetDelta.NO_SELECTION, SpreadsheetDelta.NO_CELLS, SpreadsheetDelta.NO_COLUMNS, SpreadsheetDelta.NO_LABELS, SpreadsheetDelta.NO_ROWS, SpreadsheetDelta.NO_DELETED_CELLS, SpreadsheetDelta.NO_DELETED_COLUMNS, SpreadsheetDelta.NO_DELETED_ROWS, SpreadsheetDelta.NO_COLUMN_WIDTHS, SpreadsheetDelta.NO_ROW_HEIGHTS, this.window() ), "SpreadsheetDelta\n" + " window:\n" + " A1:E5\n" ); } @Test public void testPrintTreeSelection() { this.treePrintAndCheck( SpreadsheetDeltaWindowed.withWindowed( this.selection(), SpreadsheetDelta.NO_CELLS, SpreadsheetDelta.NO_COLUMNS, SpreadsheetDelta.NO_LABELS, SpreadsheetDelta.NO_ROWS, SpreadsheetDelta.NO_DELETED_CELLS, SpreadsheetDelta.NO_DELETED_COLUMNS, SpreadsheetDelta.NO_DELETED_ROWS, SpreadsheetDelta.NO_COLUMN_WIDTHS, SpreadsheetDelta.NO_ROW_HEIGHTS, this.window() ), "SpreadsheetDelta\n" + " selection:\n" + " A1:B2 BOTTOM_RIGHT\n" + " window:\n" + " A1:E5\n" ); } @Test public void testPrintTreeCells() { this.treePrintAndCheck( SpreadsheetDeltaWindowed.withWindowed( SpreadsheetDelta.NO_SELECTION, this.cells(), SpreadsheetDelta.NO_COLUMNS, SpreadsheetDelta.NO_LABELS, SpreadsheetDelta.NO_ROWS, SpreadsheetDelta.NO_DELETED_CELLS, SpreadsheetDelta.NO_DELETED_COLUMNS, SpreadsheetDelta.NO_DELETED_ROWS, SpreadsheetDelta.NO_COLUMN_WIDTHS, SpreadsheetDelta.NO_ROW_HEIGHTS, this.window() ), "SpreadsheetDelta\n" + " cells:\n" + " Cell A1\n" + " Formula\n" + " text: \"1\"\n" + " Cell B2\n" + " Formula\n" + " text: \"2\"\n" + " Cell C3\n" + " Formula\n" + " text: \"3\"\n" + " window:\n" + " A1:E5\n" ); } @Test public void testPrintTreeColumns() { this.treePrintAndCheck( SpreadsheetDeltaWindowed.withWindowed( SpreadsheetDelta.NO_SELECTION, SpreadsheetDelta.NO_CELLS, Sets.of( this.a(), this.hiddenD() ), SpreadsheetDelta.NO_LABELS, SpreadsheetDelta.NO_ROWS, SpreadsheetDelta.NO_DELETED_CELLS, SpreadsheetDelta.NO_DELETED_COLUMNS, SpreadsheetDelta.NO_DELETED_ROWS, SpreadsheetDelta.NO_COLUMN_WIDTHS, SpreadsheetDelta.NO_ROW_HEIGHTS, this.window() ), "SpreadsheetDelta\n" + " columns:\n" + " A\n" + " D\n" + " hidden\n" + " window:\n" + " A1:E5\n" ); } @Test public void testPrintTreeLabels() { this.treePrintAndCheck( SpreadsheetDeltaWindowed.withWindowed( SpreadsheetDelta.NO_SELECTION, SpreadsheetDelta.NO_CELLS, SpreadsheetDelta.NO_COLUMNS, this.labels(), SpreadsheetDelta.NO_ROWS, SpreadsheetDelta.NO_DELETED_CELLS, SpreadsheetDelta.NO_DELETED_COLUMNS, SpreadsheetDelta.NO_DELETED_ROWS, SpreadsheetDelta.NO_COLUMN_WIDTHS, SpreadsheetDelta.NO_ROW_HEIGHTS, this.window() ), "SpreadsheetDelta\n" + " labels:\n" + " LabelA1A: A1\n" + " LabelA1B: A1\n" + " LabelB2: B2\n" + " LabelC3: C3\n" + " window:\n" + " A1:E5\n" ); } @Test public void testPrintTreeRows() { this.treePrintAndCheck( SpreadsheetDeltaWindowed.withWindowed( SpreadsheetDelta.NO_SELECTION, SpreadsheetDelta.NO_CELLS, SpreadsheetDelta.NO_COLUMNS, SpreadsheetDelta.NO_LABELS, Sets.of( this.row1(), this.hiddenRow4() ), SpreadsheetDelta.NO_DELETED_CELLS, SpreadsheetDelta.NO_DELETED_COLUMNS, SpreadsheetDelta.NO_DELETED_ROWS, SpreadsheetDelta.NO_COLUMN_WIDTHS, SpreadsheetDelta.NO_ROW_HEIGHTS, this.window() ), "SpreadsheetDelta\n" + " rows:\n" + " 1\n" + " 4\n" + " hidden\n" + " window:\n" + " A1:E5\n" ); } @Test public void testPrintTreeCellsAndLabels() { this.treePrintAndCheck( SpreadsheetDeltaWindowed.withWindowed( SpreadsheetDelta.NO_SELECTION, this.cells(), SpreadsheetDelta.NO_COLUMNS, this.labels(), SpreadsheetDelta.NO_ROWS, SpreadsheetDelta.NO_DELETED_CELLS, SpreadsheetDelta.NO_DELETED_COLUMNS, SpreadsheetDelta.NO_DELETED_ROWS, SpreadsheetDelta.NO_COLUMN_WIDTHS, SpreadsheetDelta.NO_ROW_HEIGHTS, this.window() ), "SpreadsheetDelta\n" + " cells:\n" + " Cell A1\n" + " Formula\n" + " text: \"1\"\n" + " Cell B2\n" + " Formula\n" + " text: \"2\"\n" + " Cell C3\n" + " Formula\n" + " text: \"3\"\n" + " labels:\n" + " LabelA1A: A1\n" + " LabelA1B: A1\n" + " LabelB2: B2\n" + " LabelC3: C3\n" + " window:\n" + " A1:E5\n" ); } @Test public void testPrintTreeDeletedCells() { this.treePrintAndCheck( SpreadsheetDeltaWindowed.withWindowed( SpreadsheetDelta.NO_SELECTION, this.cells(), SpreadsheetDelta.NO_COLUMNS, this.labels(), SpreadsheetDelta.NO_ROWS, this.deletedCells(), SpreadsheetDelta.NO_DELETED_COLUMNS, SpreadsheetDelta.NO_DELETED_ROWS, SpreadsheetDelta.NO_COLUMN_WIDTHS, SpreadsheetDelta.NO_ROW_HEIGHTS, this.window() ), "SpreadsheetDelta\n" + " cells:\n" + " Cell A1\n" + " Formula\n" + " text: \"1\"\n" + " Cell B2\n" + " Formula\n" + " text: \"2\"\n" + " Cell C3\n" + " Formula\n" + " text: \"3\"\n" + " labels:\n" + " LabelA1A: A1\n" + " LabelA1B: A1\n" + " LabelB2: B2\n" + " LabelC3: C3\n" + " deletedCells:\n" + " C1,C2\n" + " window:\n" + " A1:E5\n" ); } @Test public void testPrintTreeDeletedColumns() { this.treePrintAndCheck( SpreadsheetDeltaWindowed.withWindowed( SpreadsheetDelta.NO_SELECTION, SpreadsheetDelta.NO_CELLS, SpreadsheetDelta.NO_COLUMNS, SpreadsheetDelta.NO_LABELS, SpreadsheetDelta.NO_ROWS, SpreadsheetDelta.NO_DELETED_CELLS, this.deletedColumns(), SpreadsheetDelta.NO_DELETED_ROWS, SpreadsheetDelta.NO_COLUMN_WIDTHS, SpreadsheetDelta.NO_ROW_HEIGHTS, this.window() ), "SpreadsheetDelta\n" + " deletedColumns:\n" + " C,D\n" + " window:\n" + " A1:E5\n" ); } @Test public void testPrintTreeDeletedRows() { this.treePrintAndCheck( SpreadsheetDeltaWindowed.withWindowed( SpreadsheetDelta.NO_SELECTION, SpreadsheetDelta.NO_CELLS, SpreadsheetDelta.NO_COLUMNS, SpreadsheetDelta.NO_LABELS, SpreadsheetDelta.NO_ROWS, SpreadsheetDelta.NO_DELETED_CELLS, SpreadsheetDelta.NO_DELETED_COLUMNS, this.deletedRows(), SpreadsheetDelta.NO_COLUMN_WIDTHS, SpreadsheetDelta.NO_ROW_HEIGHTS, this.window() ), "SpreadsheetDelta\n" + " deletedRows:\n" + " 3,4\n" + " window:\n" + " A1:E5\n" ); } @Test public void testPrintTreeColumnWidths() { this.treePrintAndCheck( SpreadsheetDeltaWindowed.withWindowed( SpreadsheetDelta.NO_SELECTION, this.cells(), SpreadsheetDelta.NO_COLUMNS, SpreadsheetDelta.NO_LABELS, SpreadsheetDelta.NO_ROWS, SpreadsheetDelta.NO_DELETED_CELLS, SpreadsheetDelta.NO_DELETED_COLUMNS, SpreadsheetDelta.NO_DELETED_ROWS, this.columnWidths(), SpreadsheetDelta.NO_ROW_HEIGHTS, this.window() ), "SpreadsheetDelta\n" + " cells:\n" + " Cell A1\n" + " Formula\n" + " text: \"1\"\n" + " Cell B2\n" + " Formula\n" + " text: \"2\"\n" + " Cell C3\n" + " Formula\n" + " text: \"3\"\n" + " columnWidths:\n" + " A: 50.0\n" + " window:\n" + " A1:E5\n" ); } @Test public void testPrintTreeRowHeights() { this.treePrintAndCheck( SpreadsheetDeltaWindowed.withWindowed( SpreadsheetDelta.NO_SELECTION, this.cells(), SpreadsheetDelta.NO_COLUMNS, SpreadsheetDelta.NO_LABELS, SpreadsheetDelta.NO_ROWS, SpreadsheetDelta.NO_DELETED_CELLS, SpreadsheetDelta.NO_DELETED_COLUMNS, SpreadsheetDelta.NO_DELETED_ROWS, SpreadsheetDelta.NO_COLUMN_WIDTHS, this.rowHeights(), this.window() ), "SpreadsheetDelta\n" + " cells:\n" + " Cell A1\n" + " Formula\n" + " text: \"1\"\n" + " Cell B2\n" + " Formula\n" + " text: \"2\"\n" + " Cell C3\n" + " Formula\n" + " text: \"3\"\n" + " rowHeights:\n" + " 1: 75.0\n" + " window:\n" + " A1:E5\n" ); } @Test public void testPrintTreeNothingEmpty() { this.treePrintAndCheck( SpreadsheetDeltaWindowed.withWindowed( this.selection(), this.cells(), SpreadsheetDelta.NO_COLUMNS, this.labels(), SpreadsheetDelta.NO_ROWS, this.deletedCells(), this.deletedColumns(), this.deletedRows(), this.columnWidths(), this.rowHeights(), this.window() ), "SpreadsheetDelta\n" + " selection:\n" + " A1:B2 BOTTOM_RIGHT\n" + " cells:\n" + " Cell A1\n" + " Formula\n" + " text: \"1\"\n" + " Cell B2\n" + " Formula\n" + " text: \"2\"\n" + " Cell C3\n" + " Formula\n" + " text: \"3\"\n" + " labels:\n" + " LabelA1A: A1\n" + " LabelA1B: A1\n" + " LabelB2: B2\n" + " LabelC3: C3\n" + " deletedCells:\n" + " C1,C2\n" + " deletedColumns:\n" + " C,D\n" + " deletedRows:\n" + " 3,4\n" + " columnWidths:\n" + " A: 50.0\n" + " rowHeights:\n" + " 1: 75.0\n" + " window:\n" + " A1:E5\n" ); } // JsonNodeMarshallingTesting........................................................................................... private final static JsonString WINDOW_JSON_STRING = JsonNode.string("A1:E5"); @Override void unmarshallSelectionAndCheck(final SpreadsheetViewportSelection selection) { this.unmarshallAndCheck( JsonNode.object() .set( SpreadsheetDelta.SELECTION_PROPERTY, this.marshallContext() .marshall(selection) ) .set(SpreadsheetDelta.WINDOW_PROPERTY, WINDOW_JSON_STRING), SpreadsheetDeltaWindowed.withWindowed( Optional.ofNullable( selection ), SpreadsheetDelta.NO_CELLS, SpreadsheetDelta.NO_COLUMNS, SpreadsheetDelta.NO_LABELS, SpreadsheetDelta.NO_ROWS, SpreadsheetDelta.NO_DELETED_CELLS, SpreadsheetDelta.NO_DELETED_COLUMNS, SpreadsheetDelta.NO_DELETED_ROWS, SpreadsheetDelta.NO_COLUMN_WIDTHS, SpreadsheetDelta.NO_ROW_HEIGHTS, this.window() ) ); } @Test public void testMarshallCells() { this.marshallAndCheck( SpreadsheetDeltaWindowed.withWindowed( SpreadsheetDelta.NO_SELECTION, this.cells(), SpreadsheetDelta.NO_COLUMNS, SpreadsheetDelta.NO_LABELS, SpreadsheetDelta.NO_ROWS, SpreadsheetDelta.NO_DELETED_CELLS, SpreadsheetDelta.NO_DELETED_COLUMNS, SpreadsheetDelta.NO_DELETED_ROWS, SpreadsheetDelta.NO_COLUMN_WIDTHS, SpreadsheetDelta.NO_ROW_HEIGHTS, this.window() ), JsonNode.object() .set(SpreadsheetDelta.CELLS_PROPERTY, cellsJson()) .set(SpreadsheetDeltaWindowed.WINDOW_PROPERTY, WINDOW_JSON_STRING) ); } @Test public void testMarshallColumns() { this.marshallAndCheck( SpreadsheetDeltaWindowed.withWindowed( SpreadsheetDelta.NO_SELECTION, SpreadsheetDelta.NO_CELLS, this.columns(), SpreadsheetDelta.NO_LABELS, SpreadsheetDelta.NO_ROWS, SpreadsheetDelta.NO_DELETED_CELLS, SpreadsheetDelta.NO_DELETED_COLUMNS, SpreadsheetDelta.NO_DELETED_ROWS, SpreadsheetDelta.NO_COLUMN_WIDTHS, SpreadsheetDelta.NO_ROW_HEIGHTS, this.window() ), JsonNode.object() .set(SpreadsheetDelta.COLUMNS_PROPERTY, this.columnsJson()) .set(SpreadsheetDeltaWindowed.WINDOW_PROPERTY, WINDOW_JSON_STRING) ); } @Test public void testMarshallRows() { this.marshallAndCheck( SpreadsheetDeltaWindowed.withWindowed( SpreadsheetDelta.NO_SELECTION, SpreadsheetDelta.NO_CELLS, SpreadsheetDelta.NO_COLUMNS, SpreadsheetDelta.NO_LABELS, this.rows(), SpreadsheetDelta.NO_DELETED_CELLS, SpreadsheetDelta.NO_DELETED_COLUMNS, SpreadsheetDelta.NO_DELETED_ROWS, SpreadsheetDelta.NO_COLUMN_WIDTHS, SpreadsheetDelta.NO_ROW_HEIGHTS, this.window() ), JsonNode.object() .set(SpreadsheetDelta.ROWS_PROPERTY, this.rowsJson()) .set(SpreadsheetDeltaWindowed.WINDOW_PROPERTY, WINDOW_JSON_STRING) ); } @Test public void testMarshallCellsLabels() { this.marshallAndCheck( SpreadsheetDeltaWindowed.withWindowed( SpreadsheetDelta.NO_SELECTION, this.cells(), SpreadsheetDelta.NO_COLUMNS, this.labels(), SpreadsheetDelta.NO_ROWS, SpreadsheetDelta.NO_DELETED_CELLS, SpreadsheetDelta.NO_DELETED_COLUMNS, SpreadsheetDelta.NO_DELETED_ROWS, SpreadsheetDelta.NO_COLUMN_WIDTHS, SpreadsheetDelta.NO_ROW_HEIGHTS, this.window() ), JsonNode.object() .set(SpreadsheetDelta.CELLS_PROPERTY, cellsJson()) .set(SpreadsheetDelta.LABELS_PROPERTY, labelsJson()) .set(SpreadsheetDeltaWindowed.WINDOW_PROPERTY, WINDOW_JSON_STRING) ); } @Test public void testMarshallCellsColumnWidthsWindow() { this.marshallAndCheck( SpreadsheetDeltaWindowed.withWindowed( SpreadsheetDelta.NO_SELECTION, this.cells(), SpreadsheetDelta.NO_COLUMNS, SpreadsheetDelta.NO_LABELS, SpreadsheetDelta.NO_ROWS, SpreadsheetDelta.NO_DELETED_CELLS, SpreadsheetDelta.NO_DELETED_COLUMNS, SpreadsheetDelta.NO_DELETED_ROWS, this.columnWidths(), SpreadsheetDelta.NO_ROW_HEIGHTS, this.window() ), JsonNode.object() .set(SpreadsheetDelta.CELLS_PROPERTY, cellsJson()) .set(SpreadsheetDelta.COLUMN_WIDTHS_PROPERTY, COLUMN_WIDTHS_JSON) .set(SpreadsheetDeltaWindowed.WINDOW_PROPERTY, WINDOW_JSON_STRING) ); } @Test public void testMarshallCellsRowHeightsWindow() { this.marshallAndCheck( SpreadsheetDeltaWindowed.withWindowed( SpreadsheetDelta.NO_SELECTION, this.cells(), SpreadsheetDelta.NO_COLUMNS, SpreadsheetDelta.NO_LABELS, SpreadsheetDelta.NO_ROWS, SpreadsheetDelta.NO_DELETED_CELLS, SpreadsheetDelta.NO_DELETED_COLUMNS, SpreadsheetDelta.NO_DELETED_ROWS, SpreadsheetDelta.NO_COLUMN_WIDTHS, this.rowHeights(), this.window() ), JsonNode.object() .set(SpreadsheetDelta.CELLS_PROPERTY, cellsJson()) .set(SpreadsheetDelta.ROW_HEIGHTS_PROPERTY, ROW_HEIGHTS_JSON) .set(SpreadsheetDeltaWindowed.WINDOW_PROPERTY, WINDOW_JSON_STRING) ); } @Test public void testMarshallNothingEmpty() { this.marshallAndCheck( SpreadsheetDeltaWindowed.withWindowed( this.selection(), this.cells(), SpreadsheetDelta.NO_COLUMNS, this.labels(), SpreadsheetDelta.NO_ROWS, this.deletedCells(), this.deletedColumns(), this.deletedRows(), this.columnWidths(), this.rowHeights(), this.window() ), JsonNode.object() .set(SpreadsheetDelta.SELECTION_PROPERTY, this.selectionJson()) .set(SpreadsheetDelta.CELLS_PROPERTY, cellsJson()) .set(SpreadsheetDelta.LABELS_PROPERTY, labelsJson()) .set(SpreadsheetDelta.DELETED_CELLS_PROPERTY, deletedCellsJson()) .set(SpreadsheetDelta.DELETED_COLUMNS_PROPERTY, deletedColumnsJson()) .set(SpreadsheetDelta.DELETED_ROWS_PROPERTY, deletedRowsJson()) .set(SpreadsheetDelta.COLUMN_WIDTHS_PROPERTY, COLUMN_WIDTHS_JSON) .set(SpreadsheetDelta.ROW_HEIGHTS_PROPERTY, ROW_HEIGHTS_JSON) .set(SpreadsheetDeltaWindowed.WINDOW_PROPERTY, WINDOW_JSON_STRING) ); } @Test public void testMarshallEmptyWindow() { this.marshallAndCheck( SpreadsheetDeltaWindowed.withWindowed( SpreadsheetDelta.NO_SELECTION, SpreadsheetDelta.NO_CELLS, SpreadsheetDelta.NO_COLUMNS, SpreadsheetDelta.NO_LABELS, SpreadsheetDelta.NO_ROWS, SpreadsheetDelta.NO_DELETED_CELLS, SpreadsheetDelta.NO_DELETED_COLUMNS, SpreadsheetDelta.NO_DELETED_ROWS, SpreadsheetDelta.NO_COLUMN_WIDTHS, SpreadsheetDelta.NO_ROW_HEIGHTS, this.window() ), JsonNode.object() .set(SpreadsheetDeltaWindowed.WINDOW_PROPERTY, WINDOW_JSON_STRING) ); } // toString.......................................................................................................... @Test public void testToStringSelection() { this.toStringAndCheck( SpreadsheetDeltaWindowed.withWindowed( this.selection(), SpreadsheetDelta.NO_CELLS, SpreadsheetDelta.NO_COLUMNS, SpreadsheetDelta.NO_LABELS, SpreadsheetDelta.NO_ROWS, SpreadsheetDelta.NO_DELETED_CELLS, SpreadsheetDelta.NO_DELETED_COLUMNS, SpreadsheetDelta.NO_DELETED_ROWS, SpreadsheetDelta.NO_COLUMN_WIDTHS, SpreadsheetDelta.NO_ROW_HEIGHTS, this.window() ), "selection: A1:B2 BOTTOM_RIGHT window: A1:E5"); } @Test public void testToStringCells() { this.toStringAndCheck( SpreadsheetDeltaWindowed.withWindowed( SpreadsheetDelta.NO_SELECTION, this.cells(), SpreadsheetDelta.NO_COLUMNS, SpreadsheetDelta.NO_LABELS, SpreadsheetDelta.NO_ROWS, SpreadsheetDelta.NO_DELETED_CELLS, SpreadsheetDelta.NO_DELETED_COLUMNS, SpreadsheetDelta.NO_DELETED_ROWS, SpreadsheetDelta.NO_COLUMN_WIDTHS, SpreadsheetDelta.NO_ROW_HEIGHTS, this.window() ), "cells: A1=1, B2=2, C3=3 window: A1:E5"); } @Test public void testToStringLabels() { this.toStringAndCheck( SpreadsheetDeltaWindowed.withWindowed( SpreadsheetDelta.NO_SELECTION, this.cells(), SpreadsheetDelta.NO_COLUMNS, this.labels(), SpreadsheetDelta.NO_ROWS, SpreadsheetDelta.NO_DELETED_CELLS, SpreadsheetDelta.NO_DELETED_COLUMNS, SpreadsheetDelta.NO_DELETED_ROWS, SpreadsheetDelta.NO_COLUMN_WIDTHS, SpreadsheetDelta.NO_ROW_HEIGHTS, this.window() ), "cells: A1=1, B2=2, C3=3 labels: LabelA1A=A1, LabelA1B=A1, LabelB2=B2, LabelC3=C3 window: A1:E5"); } @Test public void testToStringDeletedCells() { this.toStringAndCheck( SpreadsheetDeltaWindowed.withWindowed( SpreadsheetDelta.NO_SELECTION, this.cells(), SpreadsheetDelta.NO_COLUMNS, this.labels(), SpreadsheetDelta.NO_ROWS, this.deletedCells(), SpreadsheetDelta.NO_DELETED_COLUMNS, SpreadsheetDelta.NO_DELETED_ROWS, SpreadsheetDelta.NO_COLUMN_WIDTHS, SpreadsheetDelta.NO_ROW_HEIGHTS, this.window() ), "cells: A1=1, B2=2, C3=3 labels: LabelA1A=A1, LabelA1B=A1, LabelB2=B2, LabelC3=C3 deletedCells: C1, C2 window: A1:E5"); } @Test public void testToStringDeletedColumns() { this.toStringAndCheck( SpreadsheetDeltaWindowed.withWindowed( SpreadsheetDelta.NO_SELECTION, SpreadsheetDelta.NO_CELLS, SpreadsheetDelta.NO_COLUMNS, SpreadsheetDelta.NO_LABELS, SpreadsheetDelta.NO_ROWS, SpreadsheetDelta.NO_DELETED_CELLS, this.deletedColumns(), SpreadsheetDelta.NO_DELETED_ROWS, SpreadsheetDelta.NO_COLUMN_WIDTHS, SpreadsheetDelta.NO_ROW_HEIGHTS, this.window() ), "deletedColumns: C, D window: A1:E5"); } @Test public void testToStringDeletedRows() { this.toStringAndCheck( SpreadsheetDeltaWindowed.withWindowed( SpreadsheetDelta.NO_SELECTION, SpreadsheetDelta.NO_CELLS, SpreadsheetDelta.NO_COLUMNS, SpreadsheetDelta.NO_LABELS, SpreadsheetDelta.NO_ROWS, SpreadsheetDelta.NO_DELETED_CELLS, SpreadsheetDelta.NO_DELETED_COLUMNS, this.deletedRows(), SpreadsheetDelta.NO_COLUMN_WIDTHS, SpreadsheetDelta.NO_ROW_HEIGHTS, this.window() ), "deletedRows: 3, 4 window: A1:E5"); } @Test public void testToStringColumnWidths() { this.toStringAndCheck( SpreadsheetDeltaWindowed.withWindowed( SpreadsheetDelta.NO_SELECTION, this.cells(), SpreadsheetDelta.NO_COLUMNS, SpreadsheetDelta.NO_LABELS, SpreadsheetDelta.NO_ROWS, SpreadsheetDelta.NO_DELETED_CELLS, SpreadsheetDelta.NO_DELETED_COLUMNS, SpreadsheetDelta.NO_DELETED_ROWS, this.columnWidths(), SpreadsheetDelta.NO_ROW_HEIGHTS, this.window() ), "cells: A1=1, B2=2, C3=3 max: A=50.0 window: A1:E5"); } @Test public void testToStringMaxRowHeights() { this.toStringAndCheck( SpreadsheetDeltaWindowed.withWindowed( SpreadsheetDelta.NO_SELECTION, this.cells(), SpreadsheetDelta.NO_COLUMNS, SpreadsheetDelta.NO_LABELS, SpreadsheetDelta.NO_ROWS, SpreadsheetDelta.NO_DELETED_CELLS, SpreadsheetDelta.NO_DELETED_COLUMNS, SpreadsheetDelta.NO_DELETED_ROWS, SpreadsheetDelta.NO_COLUMN_WIDTHS, this.rowHeights(), this.window() ), "cells: A1=1, B2=2, C3=3 max: 1=75.0 window: A1:E5"); } @Test public void testToStringColumnWidthsRowHeights() { this.toStringAndCheck( SpreadsheetDeltaWindowed.withWindowed( SpreadsheetDelta.NO_SELECTION, this.cells(), SpreadsheetDelta.NO_COLUMNS, SpreadsheetDelta.NO_LABELS, SpreadsheetDelta.NO_ROWS, SpreadsheetDelta.NO_DELETED_CELLS, SpreadsheetDelta.NO_DELETED_COLUMNS, SpreadsheetDelta.NO_DELETED_ROWS, this.columnWidths(), this.rowHeights(), this.window() ), "cells: A1=1, B2=2, C3=3 max: A=50.0, 1=75.0 window: A1:E5"); } // helpers.......................................................................................................... @Override Set<SpreadsheetCellRange> window() { return SpreadsheetSelection.parseWindow("A1:E5"); } @Override SpreadsheetDeltaWindowed createSpreadsheetDelta(final Set<SpreadsheetCell> cells) { return this.createSpreadsheetDelta( cells, this.window() ); } private SpreadsheetDeltaWindowed createSpreadsheetDelta(final Set<SpreadsheetCell> cells, final Set<SpreadsheetCellRange> window) { return SpreadsheetDeltaWindowed.withWindowed( this.selection(), cells, this.columns(), this.labels(), this.rows(), this.deletedCells(), this.deletedColumns(), this.deletedRows(), this.columnWidths(), this.rowHeights(), window ); } @Override public Class<SpreadsheetDeltaWindowed> type() { return SpreadsheetDeltaWindowed.class; } }
92431206f9bb1fa736425a16481098cb1f640d1b
2,208
java
Java
atlas-api/src/test/java/org/atlasapi/query/v4/content/IndexBackedEquivalentContentQueryExecutorTest.java
atlasapi/atlas-deer
87ba43f06200e9d940f5786713f24380f1ce7951
[ "Apache-2.0" ]
4
2015-10-16T15:45:25.000Z
2021-11-08T08:35:28.000Z
atlas-api/src/test/java/org/atlasapi/query/v4/content/IndexBackedEquivalentContentQueryExecutorTest.java
atlasapi/atlas-deer
87ba43f06200e9d940f5786713f24380f1ce7951
[ "Apache-2.0" ]
206
2015-02-05T18:59:46.000Z
2021-08-23T12:51:45.000Z
atlas-api/src/test/java/org/atlasapi/query/v4/content/IndexBackedEquivalentContentQueryExecutorTest.java
atlasapi/atlas-deer
87ba43f06200e9d940f5786713f24380f1ce7951
[ "Apache-2.0" ]
null
null
null
34.5
103
0.731884
1,002,513
package org.atlasapi.query.v4.content; import javax.servlet.http.HttpServletRequest; import org.atlasapi.content.Content; import org.atlasapi.content.ContentSearcher; import org.atlasapi.entity.Id; import org.atlasapi.equivalence.MergingEquivalentsResolver; import org.atlasapi.equivalence.ResolvedEquivalents; import org.atlasapi.output.NotFoundException; import org.atlasapi.query.annotation.ActiveAnnotations; import org.atlasapi.query.common.Query; import org.atlasapi.query.common.context.QueryContext; import com.metabroadcast.applications.client.model.internal.Application; import com.google.common.collect.ImmutableSet; import com.google.common.util.concurrent.Futures; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class IndexBackedEquivalentContentQueryExecutorTest { private @Mock ContentSearcher contentIndex; private @Mock MergingEquivalentsResolver<Content> equivalentContentResolver; private IndexBackedEquivalentContentQueryExecutor qe; @Before public void setup() { qe = IndexBackedEquivalentContentQueryExecutor.create(contentIndex, equivalentContentResolver); } @Test(expected = NotFoundException.class) public void testNoContentForSingleQueryThrowsNotFoundException() throws Exception { Query<Content> query = Query.singleQuery( Id.valueOf(1), QueryContext.create( mock(Application.class), ActiveAnnotations.standard(), mock(HttpServletRequest.class) ) ); QueryContext ctxt = query.getContext(); when(equivalentContentResolver.resolveIds(ImmutableSet.of(query.getOnlyId()), ctxt.getApplication(), ImmutableSet.copyOf(ctxt.getAnnotations().values()), ImmutableSet.of() )) .thenReturn(Futures.immediateFuture(ResolvedEquivalents.<Content>empty())); qe.execute(query); } }
9243120733f208fb685b81ecdd4d072cf4024194
20,995
java
Java
core/src/main/java/org/apache/spark/util/collection/unsafe/sort/UnsafeExternalSorter.java
tophua/spark1.52
464f406d04329634d5a8a0d6956d6d803a59d897
[ "Apache-2.0" ]
53
2016-04-22T03:57:05.000Z
2020-08-11T02:54:15.000Z
core/src/main/java/org/apache/spark/util/collection/unsafe/sort/UnsafeExternalSorter.java
tophua/spark1.52
464f406d04329634d5a8a0d6956d6d803a59d897
[ "Apache-2.0" ]
null
null
null
core/src/main/java/org/apache/spark/util/collection/unsafe/sort/UnsafeExternalSorter.java
tophua/spark1.52
464f406d04329634d5a8a0d6956d6d803a59d897
[ "Apache-2.0" ]
42
2016-04-22T03:56:50.000Z
2020-11-23T09:32:25.000Z
40.925926
106
0.715694
1,002,514
/* * 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.spark.util.collection.unsafe.sort; import java.io.File; import java.io.IOException; import java.util.LinkedList; import javax.annotation.Nullable; import scala.runtime.AbstractFunction0; import scala.runtime.BoxedUnit; import com.google.common.annotations.VisibleForTesting; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.spark.TaskContext; import org.apache.spark.executor.ShuffleWriteMetrics; import org.apache.spark.shuffle.ShuffleMemoryManager; import org.apache.spark.storage.BlockManager; import org.apache.spark.unsafe.array.ByteArrayMethods; import org.apache.spark.unsafe.Platform; import org.apache.spark.unsafe.memory.MemoryBlock; import org.apache.spark.unsafe.memory.TaskMemoryManager; import org.apache.spark.util.Utils; /** * External sorter based on {@link UnsafeInMemorySorter}. */ public final class UnsafeExternalSorter { private final Logger logger = LoggerFactory.getLogger(UnsafeExternalSorter.class); private final long pageSizeBytes; private final PrefixComparator prefixComparator; private final RecordComparator recordComparator; private final int initialSize; private final TaskMemoryManager taskMemoryManager; private final ShuffleMemoryManager shuffleMemoryManager; private final BlockManager blockManager; private final TaskContext taskContext; private ShuffleWriteMetrics writeMetrics; /** The buffer size to use when writing spills using DiskBlockObjectWriter */ private final int fileBufferSizeBytes; /** * Memory pages that hold the records being sorted. The pages in this list are freed when * spilling, although in principle we could recycle these pages across spills (on the other hand, * this might not be necessary if we maintained a pool of re-usable pages in the TaskMemoryManager * itself). */ private final LinkedList<MemoryBlock> allocatedPages = new LinkedList<>(); private final LinkedList<UnsafeSorterSpillWriter> spillWriters = new LinkedList<>(); // These variables are reset after spilling: @Nullable private UnsafeInMemorySorter inMemSorter; // Whether the in-mem sorter is created internally, or passed in from outside. // If it is passed in from outside, we shouldn't release the in-mem sorter's memory. private boolean isInMemSorterExternal = false; private MemoryBlock currentPage = null; private long currentPagePosition = -1; private long freeSpaceInCurrentPage = 0; private long peakMemoryUsedBytes = 0; public static UnsafeExternalSorter createWithExistingInMemorySorter( TaskMemoryManager taskMemoryManager, ShuffleMemoryManager shuffleMemoryManager, BlockManager blockManager, TaskContext taskContext, RecordComparator recordComparator, PrefixComparator prefixComparator, int initialSize, long pageSizeBytes, UnsafeInMemorySorter inMemorySorter) throws IOException { return new UnsafeExternalSorter(taskMemoryManager, shuffleMemoryManager, blockManager, taskContext, recordComparator, prefixComparator, initialSize, pageSizeBytes, inMemorySorter); } public static UnsafeExternalSorter create( TaskMemoryManager taskMemoryManager, ShuffleMemoryManager shuffleMemoryManager, BlockManager blockManager, TaskContext taskContext, RecordComparator recordComparator, PrefixComparator prefixComparator, int initialSize, long pageSizeBytes) throws IOException { return new UnsafeExternalSorter(taskMemoryManager, shuffleMemoryManager, blockManager, taskContext, recordComparator, prefixComparator, initialSize, pageSizeBytes, null); } private UnsafeExternalSorter( TaskMemoryManager taskMemoryManager, ShuffleMemoryManager shuffleMemoryManager, BlockManager blockManager, TaskContext taskContext, RecordComparator recordComparator, PrefixComparator prefixComparator, int initialSize, long pageSizeBytes, @Nullable UnsafeInMemorySorter existingInMemorySorter) throws IOException { this.taskMemoryManager = taskMemoryManager; this.shuffleMemoryManager = shuffleMemoryManager; this.blockManager = blockManager; this.taskContext = taskContext; this.recordComparator = recordComparator; this.prefixComparator = prefixComparator; this.initialSize = initialSize; // Use getSizeAsKb (not bytes) to maintain backwards compatibility for units // this.fileBufferSizeBytes = (int) conf.getSizeAsKb("spark.shuffle.file.buffer", "32k") * 1024; this.fileBufferSizeBytes = 32 * 1024; this.pageSizeBytes = pageSizeBytes; this.writeMetrics = new ShuffleWriteMetrics(); if (existingInMemorySorter == null) { initializeForWriting(); // Acquire a new page as soon as we construct the sorter to ensure that we have at // least one page to work with. Otherwise, other operators in the same task may starve // this sorter (SPARK-9709). We don't need to do this if we already have an existing sorter. acquireNewPage(); } else { this.isInMemSorterExternal = true; this.inMemSorter = existingInMemorySorter; } // Register a cleanup task with TaskContext to ensure that memory is guaranteed to be freed at // the end of the task. This is necessary to avoid memory leaks in when the downstream operator // does not fully consume the sorter's output (e.g. sort followed by limit). taskContext.addOnCompleteCallback(new AbstractFunction0<BoxedUnit>() { @Override public BoxedUnit apply() { cleanupResources(); return null; } }); } // TODO: metrics tracking + integration with shuffle write metrics // need to connect the write metrics to task metrics so we count the spill IO somewhere. /** * Allocates new sort data structures. Called when creating the sorter and after each spill. */ private void initializeForWriting() throws IOException { // Note: Do not track memory for the pointer array for now because of SPARK-10474. // In more detail, in TungstenAggregate we only reserve a page, but when we fall back to // sort-based aggregation we try to acquire a page AND a pointer array, which inevitably // fails if all other memory is already occupied. It should be safe to not track the array // because its memory footprint is frequently much smaller than that of a page. This is a // temporary hack that we should address in 1.6.0. // TODO: track the pointer array memory! this.writeMetrics = new ShuffleWriteMetrics(); this.inMemSorter = new UnsafeInMemorySorter(taskMemoryManager, recordComparator, prefixComparator, initialSize); this.isInMemSorterExternal = false; } /** * Marks the current page as no-more-space-available, and as a result, either allocate a * new page or spill when we see the next record. */ @VisibleForTesting public void closeCurrentPage() { freeSpaceInCurrentPage = 0; } /** * Sort and spill the current records in response to memory pressure. */ public void spill() throws IOException { assert(inMemSorter != null); logger.info("Thread {} spilling sort data of {} to disk ({} {} so far)", //Thread.currentThread().getContextClassLoader,可以获取当前线程的引用,getContextClassLoader用来获取线程的上下文类加载器 Thread.currentThread().getId(), Utils.bytesToString(getMemoryUsage()), spillWriters.size(), spillWriters.size() > 1 ? " times" : " time"); // We only write out contents of the inMemSorter if it is not empty. if (inMemSorter.numRecords() > 0) { final UnsafeSorterSpillWriter spillWriter = new UnsafeSorterSpillWriter(blockManager, fileBufferSizeBytes, writeMetrics, inMemSorter.numRecords()); spillWriters.add(spillWriter); final UnsafeSorterIterator sortedRecords = inMemSorter.getSortedIterator(); while (sortedRecords.hasNext()) { sortedRecords.loadNext(); final Object baseObject = sortedRecords.getBaseObject(); final long baseOffset = sortedRecords.getBaseOffset(); final int recordLength = sortedRecords.getRecordLength(); spillWriter.write(baseObject, baseOffset, recordLength, sortedRecords.getKeyPrefix()); } spillWriter.close(); } final long spillSize = freeMemory(); // Note that this is more-or-less going to be a multiple of the page size, so wasted space in // pages will currently be counted as memory spilled even though that space isn't actually // written to disk. This also counts the space needed to store the sorter's pointer array. taskContext.taskMetrics().incMemoryBytesSpilled(spillSize); initializeForWriting(); } /** * Return the total memory usage of this sorter, including the data pages and the sorter's pointer * array. */ private long getMemoryUsage() { long totalPageSize = 0; for (MemoryBlock page : allocatedPages) { totalPageSize += page.size(); } return ((inMemSorter == null) ? 0 : inMemSorter.getMemoryUsage()) + totalPageSize; } private void updatePeakMemoryUsed() { long mem = getMemoryUsage(); if (mem > peakMemoryUsedBytes) { peakMemoryUsedBytes = mem; } } /** * Return the peak memory used so far, in bytes. */ public long getPeakMemoryUsedBytes() { updatePeakMemoryUsed(); return peakMemoryUsedBytes; } @VisibleForTesting public int getNumberOfAllocatedPages() { return allocatedPages.size(); } /** * Free this sorter's in-memory data structures, including its data pages and pointer array. * * @return the number of bytes freed. */ private long freeMemory() { updatePeakMemoryUsed(); long memoryFreed = 0; for (MemoryBlock block : allocatedPages) { taskMemoryManager.freePage(block); shuffleMemoryManager.release(block.size()); memoryFreed += block.size(); } // TODO: track in-memory sorter memory usage (SPARK-10474) allocatedPages.clear(); currentPage = null; currentPagePosition = -1; freeSpaceInCurrentPage = 0; return memoryFreed; } /** * Deletes any spill files created by this sorter. */ private void deleteSpillFiles() { for (UnsafeSorterSpillWriter spill : spillWriters) { File file = spill.getFile(); if (file != null && file.exists()) { if (!file.delete()) { logger.error("Was unable to delete spill file {}", file.getAbsolutePath()); } } } } /** * Frees this sorter's in-memory data structures and cleans up its spill files. */ public void cleanupResources() { deleteSpillFiles(); freeMemory(); } /** * Checks whether there is enough space to insert an additional record in to the sort pointer * array and grows the array if additional space is required. If the required space cannot be * obtained, then the in-memory data will be spilled to disk. */ private void growPointerArrayIfNecessary() throws IOException { assert(inMemSorter != null); if (!inMemSorter.hasSpaceForAnotherRecord()) { // TODO: track the pointer array memory! (SPARK-10474) inMemSorter.expandPointerArray(); } } /** * Allocates more memory in order to insert an additional record. This will request additional * memory from the {@link ShuffleMemoryManager} and spill if the requested memory can not be * obtained. * * @param requiredSpace the required space in the data page, in bytes, including space for storing * the record size. This must be less than or equal to the page size (records * that exceed the page size are handled via a different code path which uses * special overflow pages). */ private void acquireNewPageIfNecessary(int requiredSpace) throws IOException { assert (requiredSpace <= pageSizeBytes); if (requiredSpace > freeSpaceInCurrentPage) { logger.trace("Required space {} is less than free space in current page ({})", requiredSpace, freeSpaceInCurrentPage); // TODO: we should track metrics on the amount of space wasted when we roll over to a new page // without using the free space at the end of the current page. We should also do this for // BytesToBytesMap. if (requiredSpace > pageSizeBytes) { throw new IOException("Required space " + requiredSpace + " is greater than page size (" + pageSizeBytes + ")"); } else { acquireNewPage(); } } } /** * Acquire a new page from the {@link ShuffleMemoryManager}. * * If there is not enough space to allocate the new page, spill all existing ones * and try again. If there is still not enough space, report error to the caller. */ private void acquireNewPage() throws IOException { final long memoryAcquired = shuffleMemoryManager.tryToAcquire(pageSizeBytes); if (memoryAcquired < pageSizeBytes) { shuffleMemoryManager.release(memoryAcquired); spill(); final long memoryAcquiredAfterSpilling = shuffleMemoryManager.tryToAcquire(pageSizeBytes); if (memoryAcquiredAfterSpilling != pageSizeBytes) { shuffleMemoryManager.release(memoryAcquiredAfterSpilling); throw new IOException("Unable to acquire " + pageSizeBytes + " bytes of memory"); } } currentPage = taskMemoryManager.allocatePage(pageSizeBytes); currentPagePosition = currentPage.getBaseOffset(); freeSpaceInCurrentPage = pageSizeBytes; allocatedPages.add(currentPage); } /** * Write a record to the sorter. */ public void insertRecord( Object recordBaseObject, long recordBaseOffset, int lengthInBytes, long prefix) throws IOException { growPointerArrayIfNecessary(); // Need 4 bytes to store the record length. final int totalSpaceRequired = lengthInBytes + 4; // --- Figure out where to insert the new record ---------------------------------------------- final MemoryBlock dataPage; long dataPagePosition; boolean useOverflowPage = totalSpaceRequired > pageSizeBytes; if (useOverflowPage) { long overflowPageSize = ByteArrayMethods.roundNumberOfBytesToNearestWord(totalSpaceRequired); // The record is larger than the page size, so allocate a special overflow page just to hold // that record. final long memoryGranted = shuffleMemoryManager.tryToAcquire(overflowPageSize); if (memoryGranted != overflowPageSize) { shuffleMemoryManager.release(memoryGranted); spill(); final long memoryGrantedAfterSpill = shuffleMemoryManager.tryToAcquire(overflowPageSize); if (memoryGrantedAfterSpill != overflowPageSize) { shuffleMemoryManager.release(memoryGrantedAfterSpill); throw new IOException("Unable to acquire " + overflowPageSize + " bytes of memory"); } } MemoryBlock overflowPage = taskMemoryManager.allocatePage(overflowPageSize); allocatedPages.add(overflowPage); dataPage = overflowPage; dataPagePosition = overflowPage.getBaseOffset(); } else { // The record is small enough to fit in a regular data page, but the current page might not // have enough space to hold it (or no pages have been allocated yet). acquireNewPageIfNecessary(totalSpaceRequired); dataPage = currentPage; dataPagePosition = currentPagePosition; // Update bookkeeping information freeSpaceInCurrentPage -= totalSpaceRequired; currentPagePosition += totalSpaceRequired; } final Object dataPageBaseObject = dataPage.getBaseObject(); // --- Insert the record ---------------------------------------------------------------------- final long recordAddress = taskMemoryManager.encodePageNumberAndOffset(dataPage, dataPagePosition); Platform.putInt(dataPageBaseObject, dataPagePosition, lengthInBytes); dataPagePosition += 4; Platform.copyMemory( recordBaseObject, recordBaseOffset, dataPageBaseObject, dataPagePosition, lengthInBytes); assert(inMemSorter != null); inMemSorter.insertRecord(recordAddress, prefix); } /** * Write a key-value record to the sorter. The key and value will be put together in-memory, * using the following format: * * record length (4 bytes), key length (4 bytes), key data, value data * * record length = key length + value length + 4 */ public void insertKVRecord( Object keyBaseObj, long keyOffset, int keyLen, Object valueBaseObj, long valueOffset, int valueLen, long prefix) throws IOException { growPointerArrayIfNecessary(); final int totalSpaceRequired = keyLen + valueLen + 4 + 4; // --- Figure out where to insert the new record ---------------------------------------------- final MemoryBlock dataPage; long dataPagePosition; boolean useOverflowPage = totalSpaceRequired > pageSizeBytes; if (useOverflowPage) { long overflowPageSize = ByteArrayMethods.roundNumberOfBytesToNearestWord(totalSpaceRequired); // The record is larger than the page size, so allocate a special overflow page just to hold // that record. final long memoryGranted = shuffleMemoryManager.tryToAcquire(overflowPageSize); if (memoryGranted != overflowPageSize) { shuffleMemoryManager.release(memoryGranted); spill(); final long memoryGrantedAfterSpill = shuffleMemoryManager.tryToAcquire(overflowPageSize); if (memoryGrantedAfterSpill != overflowPageSize) { shuffleMemoryManager.release(memoryGrantedAfterSpill); throw new IOException("Unable to acquire " + overflowPageSize + " bytes of memory"); } } MemoryBlock overflowPage = taskMemoryManager.allocatePage(overflowPageSize); allocatedPages.add(overflowPage); dataPage = overflowPage; dataPagePosition = overflowPage.getBaseOffset(); } else { // The record is small enough to fit in a regular data page, but the current page might not // have enough space to hold it (or no pages have been allocated yet). acquireNewPageIfNecessary(totalSpaceRequired); dataPage = currentPage; dataPagePosition = currentPagePosition; // Update bookkeeping information freeSpaceInCurrentPage -= totalSpaceRequired; currentPagePosition += totalSpaceRequired; } final Object dataPageBaseObject = dataPage.getBaseObject(); // --- Insert the record ---------------------------------------------------------------------- final long recordAddress = taskMemoryManager.encodePageNumberAndOffset(dataPage, dataPagePosition); Platform.putInt(dataPageBaseObject, dataPagePosition, keyLen + valueLen + 4); dataPagePosition += 4; Platform.putInt(dataPageBaseObject, dataPagePosition, keyLen); dataPagePosition += 4; Platform.copyMemory(keyBaseObj, keyOffset, dataPageBaseObject, dataPagePosition, keyLen); dataPagePosition += keyLen; Platform.copyMemory(valueBaseObj, valueOffset, dataPageBaseObject, dataPagePosition, valueLen); assert(inMemSorter != null); inMemSorter.insertRecord(recordAddress, prefix); } /** * Returns a sorted iterator. It is the caller's responsibility to call `cleanupResources()` * after consuming this iterator. */ public UnsafeSorterIterator getSortedIterator() throws IOException { assert(inMemSorter != null); final UnsafeInMemorySorter.SortedIterator inMemoryIterator = inMemSorter.getSortedIterator(); int numIteratorsToMerge = spillWriters.size() + (inMemoryIterator.hasNext() ? 1 : 0); if (spillWriters.isEmpty()) { return inMemoryIterator; } else { final UnsafeSorterSpillMerger spillMerger = new UnsafeSorterSpillMerger(recordComparator, prefixComparator, numIteratorsToMerge); for (UnsafeSorterSpillWriter spillWriter : spillWriters) { spillMerger.addSpillIfNotEmpty(spillWriter.getReader(blockManager)); } spillWriters.clear(); spillMerger.addSpillIfNotEmpty(inMemoryIterator); return spillMerger.getSortedIterator(); } } }
9243128027e81fab951f2667b326b24312a61a4b
2,417
java
Java
MAGPIE/watch/src/main/java/hevs/aislab/magpie/watch/agents/StepBehaviour.java
kflauri2312lffds/Android_watch_magpie
75bba533bf31279973dddcd984cdea56b3dd7dc8
[ "BSD-3-Clause" ]
1
2017-07-12T08:34:37.000Z
2017-07-12T08:34:37.000Z
MAGPIE/watch/src/main/java/hevs/aislab/magpie/watch/agents/StepBehaviour.java
kflauri2312lffds/Android_watch_magpie
75bba533bf31279973dddcd984cdea56b3dd7dc8
[ "BSD-3-Clause" ]
null
null
null
MAGPIE/watch/src/main/java/hevs/aislab/magpie/watch/agents/StepBehaviour.java
kflauri2312lffds/Android_watch_magpie
75bba533bf31279973dddcd984cdea56b3dd7dc8
[ "BSD-3-Clause" ]
null
null
null
30.987179
96
0.709557
1,002,515
package hevs.aislab.magpie.watch.agents; import android.content.Context; import ch.hevs.aislab.magpie.agent.MagpieAgent; import ch.hevs.aislab.magpie.behavior.Behavior; import ch.hevs.aislab.magpie.event.LogicTupleEvent; import ch.hevs.aislab.magpie.event.MagpieEvent; import hevs.aislab.magpie.watch.models.Alertes; import hevs.aislab.magpie.watch.models.CustomRules; import hevs.aislab.magpie.watch.models.Measure; import hevs.aislab.magpie.watch.repository.AlertRepository; import hevs.aislab.magpie.watch.repository.MeasuresRepository; import hevs.aislab.magpie.watch.repository.RulesRepository; import hevs.aislab.magpie.watch_library.lib.Const; /** * Steps agent that will take care of the glucose data and trigger an alert */ public class StepBehaviour extends Behavior { public StepBehaviour(Context context, MagpieAgent agent, int priority) { setContext(context); setAgent(agent); setPriority(priority); } @Override public void action(MagpieEvent event) { LogicTupleEvent lte = (LogicTupleEvent) event; final double steps = Double.parseDouble(lte.getArguments().get(0)); //write the measure in the database, only 1 time a day Measure measure=new Measure(); measure.setValue1(steps); measure.setCategory(Const.CATEGORY_STEP); measure.setTimeStamp(event.getTimestamp()); MeasuresRepository.getInstance().insert(measure); //We do not need to set the value in GUI her //APPLY THE RULES FOR THE STEP //Get the rules CustomRules stepRules= RulesRepository.getInstance().getByCategory(Const.CATEGORY_STEP); //get min and max value allowed, based on the rules double minValue=stepRules.getVal_1_min(); double maxValue=stepRules.getVal_1_max(); //now we apply the rules //no alert trigered if the steps are in the range if (steps>minValue && steps<maxValue) return; //insert the alere in the db, but we don't display Alertes alertes=new Alertes(); alertes.setRule(stepRules); alertes.setMeasure(measure); AlertRepository.getINSTANCE().insert(alertes); } @Override public boolean isTriggered(MagpieEvent event) { LogicTupleEvent condition = (LogicTupleEvent) event; return condition.getName().equals(Const.CATEGORY_STEP); } }
924313023728e5519e68c28b68d96372928e0673
15,416
java
Java
app/src/androidTest/java/de/test/antennapod/espresso/CommentsFeature/CommentsUITests.java
Khalidbaraka/SOEN390
0df53fe92155f3d0478c286eb6b4e1b373ec0c9c
[ "MIT" ]
null
null
null
app/src/androidTest/java/de/test/antennapod/espresso/CommentsFeature/CommentsUITests.java
Khalidbaraka/SOEN390
0df53fe92155f3d0478c286eb6b4e1b373ec0c9c
[ "MIT" ]
null
null
null
app/src/androidTest/java/de/test/antennapod/espresso/CommentsFeature/CommentsUITests.java
Khalidbaraka/SOEN390
0df53fe92155f3d0478c286eb6b4e1b373ec0c9c
[ "MIT" ]
null
null
null
41.329759
138
0.698495
1,002,516
package de.test.antennapod.espresso.CommentsFeature; import android.app.Activity; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.support.test.espresso.Espresso; import android.support.test.espresso.NoMatchingViewException; import android.support.test.espresso.ViewAction; import android.support.test.espresso.ViewAssertion; import android.support.test.espresso.contrib.DrawerActions; import android.support.test.espresso.contrib.RecyclerViewActions; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.support.test.runner.lifecycle.ActivityLifecycleMonitorRegistry; import android.support.test.runner.lifecycle.Stage; import android.view.View; import android.widget.GridView; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.robotium.solo.Solo; import com.robotium.solo.Timeout; import org.hamcrest.Matcher; import org.junit.After; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import java.util.Collection; import java.util.Iterator; import androidx.test.espresso.UiController; import de.danoeh.antennapod.R; import de.danoeh.antennapod.activity.CommentListActivity; import de.danoeh.antennapod.activity.LoginActivity; import de.danoeh.antennapod.activity.MainActivity; import de.danoeh.antennapod.activity.OnlineFeedViewActivity; import de.danoeh.antennapod.activity.RegisterAndLoginActivity; import de.danoeh.antennapod.activity.ReplyListActivity; import de.danoeh.antennapod.model.Comment; import static android.support.test.InstrumentationRegistry.getInstrumentation; import static android.support.test.espresso.Espresso.onData; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.clearText; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.typeText; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static androidx.test.espresso.matcher.ViewMatchers.hasDescendant; import static androidx.test.espresso.matcher.ViewMatchers.isRoot; import static org.hamcrest.CoreMatchers.anything; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.hamcrest.core.IsNull.notNullValue; import static org.junit.Assert.assertEquals; @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(AndroidJUnit4.class) public class CommentsUITests { private Solo solo; private Solo soloRegisterAndLogin; private Solo soloLogin; private FirebaseUser user; @Rule public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(MainActivity.class); public ActivityTestRule<CommentListActivity> mActivityTestRule = new ActivityTestRule<>(CommentListActivity.class); public ActivityTestRule<RegisterAndLoginActivity> mActivityRuleRegisterLogin = new ActivityTestRule<>(RegisterAndLoginActivity.class); public ActivityTestRule<LoginActivity> mActivityRuleLogin = new ActivityTestRule<>(LoginActivity.class); @Before public void setUp() { solo = new Solo(getInstrumentation(), mActivityRule.getActivity()); soloRegisterAndLogin = new Solo(getInstrumentation(), mActivityRuleRegisterLogin.getActivity()); soloLogin = new Solo(getInstrumentation(), mActivityRuleLogin.getActivity()); Timeout.setSmallTimeout(5000); Timeout.setLargeTimeout(10000); } @After public void tearDown() { solo.finishOpenedActivities(); } @Test public void test01GoFirstToProfilePage() { solo = new Solo(getInstrumentation(), mActivityRule.getActivity()); // queue page onView(withId(R.id.drawer_layout)).perform(DrawerActions.open()); String currentPage = getActionbarTitle(); if (("Profile Page").equals(currentPage)){ assertEquals(solo.getString(R.string.profile_page_label), getActionbarTitle()); }else{ solo.clickOnText(solo.getString(R.string.profile_page_label)); solo.waitForView(android.R.id.list); assertEquals(solo.getString(R.string.profile_page_label), getActionbarTitle()); } } @Test public void test02fLogInIfNotLoggedIn() { //Code added from Login UI test //Create User Based on Registered User getUser(); solo.waitForView(android.R.id.list); //Assert current activity ActionBar is "Authentication". assertEquals("Profile Page", getActionbarTitle()); //if user is already logged do nothing if (user != null && user.isEmailVerified()) { } //Else login else { //Checks button is there onView(withId(R.id.profile_register_and_login_btn)).check(matches(notNullValue())); //Checks button name matches onView(withId(R.id.profile_register_and_login_btn)).check(matches(withText("Authentication"))); assertEquals("Authentication", solo.getString(R.string.authentication)); //Press the Authentication button in the profile Page onView(withId(R.id.profile_register_and_login_btn)).perform(click()); //--------Now in Authentication Activity ---------- soloRegisterAndLogin.waitForView(0); //Assert current activity ActionBar is "Authentication". assertEquals(soloRegisterAndLogin.getString(R.string.title_activity_register_and_login), getActionbarTitleRegisterLogin()); //Checks button / EditText is there onView(withId(R.id.login_main_layout_button)).check(matches(notNullValue())); //Checks button / EditText name matches onView(withId(R.id.login_main_layout_button)).check(matches(withText("Login"))); assertEquals("Login", soloRegisterAndLogin.getString(R.string.login)); //Press the Login button in the Authentication Page onView(withId(R.id.login_main_layout_button)).perform(click()); //--------Now in Login Activity ---------- soloLogin.waitForView(0); Espresso.closeSoftKeyboard(); //Assert current activity ActionBar is "Login". assertEquals(soloLogin.getString(R.string.title_activity_login), getActionbarTitleLogin()); //Write user info in editTexts soloLogin.waitForView(0); onView(withId(R.id.input_email_login)).perform(clearText(),typeText("[email protected]")); Espresso.closeSoftKeyboard(); onView(withId(R.id.input_password_login)).perform(clearText(),typeText("password")); Espresso.closeSoftKeyboard(); //Checks button / EditText is there onView(withId(R.id.btn_login)).check(matches(notNullValue())); //Checks button / EditText name matches onView(withId(R.id.btn_login)).check(matches(withText("Login"))); assertEquals("Login", soloLogin.getString(R.string.login)); //Press the Login button in the Login Page onView(withId(R.id.btn_login)).perform(click()); solo.waitForView(android.R.id.list); //--------Now in Main Activity ---------- solo.waitForView(android.R.id.list); solo.waitForView(android.R.id.list); //Assert current activity ActionBar is "Profile Page". assertEquals("Profile Page", getActionbarTitle()); } } @Test public void test03LoginTest() { } @Test public void test1GoToAddPodcastTest() { // Add Podcast page onView(withId(R.id.drawer_layout)).perform(DrawerActions.open()); String currentPage = getActionbarTitle(); if (("Add Podcast").equals(currentPage)){ assertEquals(solo.getString(R.string.add_feed_label), getActionbarTitle()); }else{ solo.clickOnText(solo.getString(R.string.add_feed_label)); solo.waitForView(R.id.list); assertEquals(solo.getString(R.string.add_feed_label), getActionbarTitle()); } } @Test public void test2AddFeedFragmentAccessTest() { // in podcast we want to click on Itunes btn onView(withId(R.id.butSearchItunes)).perform(click()); solo.waitForView(R.id.layout_1); assertEquals(solo.getString(R.string.add_feed_label), getActionbarTitle()); } @Test public void test3CommentListActivityViewTest() { onView(withId(R.id.butSearchItunes)).perform(click()); solo.waitForView(R.id.list);//layout_1 listview onData(anything()).inAdapterView(withId(R.id.gridView)).atPosition(0). onChildView(withId(R.id.imgvCover)).perform(click()); //clicks on podcast solo.waitForView(R.id.relativeLayout); onView(withId(R.id.viewCommentsBtn)).perform(click()); solo.waitForView(R.id.constraintLayout); assertEquals(CommentListActivity.class, getActivityInstance().getClass()); } @Test public void test4CommentListActivityElementsTest(){ onView(withId(R.id.butSearchItunes)).perform(click()); solo.waitForView(R.id.layout_1); onData(anything()).inAdapterView(withId(R.id.gridView)).atPosition(0). onChildView(withId(R.id.imgvCover)).perform(click()); //clicks on podcast solo.waitForView(R.id.relativeLayout); onView(withId(R.id.viewCommentsBtn)).perform(click()); solo.waitForView(R.id.constraintLayout); onView(withId(R.id.commentContent_1)).check(matches(notNullValue() )); onView(withId(R.id.submitComment_1)).check(matches(notNullValue() )); onView(withId(R.id.submitComment_1)).check(matches(withText(solo.getString(R.string.submit)))); assertEquals("submit", solo.getString(R.string.submit)); } //posting a comment @Test public void test5AddCommentTest(){ onView(withId(R.id.butSearchItunes)).perform(click()); solo.waitForView(R.id.layout_1); onData(anything()).inAdapterView(withId(R.id.gridView)).atPosition(0). onChildView(withId(R.id.imgvCover)).perform(click()); //clicks on podcast solo.waitForView(R.id.relativeLayout); onView(withId(R.id.viewCommentsBtn)).perform(click()); solo.waitForView(R.id.constraintLayout); onView(withId(R.id.commentContent_1)).check(matches(notNullValue() )); onView(withId(R.id.submitComment_1)).check(matches(notNullValue() )); onView(withId(R.id.submitComment_1)).check(matches(withText(solo.getString(R.string.submit)))); onView(withId(R.id.commentContent_1)).perform(clearText(),typeText("Testing")); Espresso.closeSoftKeyboard(); solo.waitForView(android.R.id.list); onView(withId(R.id.submitComment_1)).perform(click()); solo.waitForView(android.R.id.list); assertEquals(OnlineFeedViewActivity.class, getActivityInstance().getClass()); } @Test public void test6AddReplyTest(){ onView(withId(R.id.butSearchItunes)).perform(click()); solo.waitForView(R.id.layout_1); onData(anything()).inAdapterView(withId(R.id.gridView)).atPosition(0). onChildView(withId(R.id.imgvCover)).perform(click()); //clicks on podcast solo.waitForView(R.id.relativeLayout); onView(withId(R.id.viewCommentsBtn)).perform(click()); solo.waitForView(R.id.constraintLayout); onView(withId(R.id.recyclerView_1)).perform( RecyclerViewActions.actionOnItemAtPosition(0, MyViewAction.clickChildViewWithId(R.id.addReplyBtn))); solo.waitForView(R.id.constraintLayout); onView(withId(R.id.replyContent_1)).check(matches(notNullValue() )); onView(withId(R.id.submitReply_1)).check(matches(notNullValue() )); onView(withId(R.id.submitReply_1)).check(matches(withText(solo.getString(R.string.submit)))); onView(withId(R.id.replyContent_1)).perform(clearText(),typeText("Nice!")); Espresso.closeSoftKeyboard(); solo.waitForView(android.R.id.list); onView(withId(R.id.submitReply_1)).perform(click()); solo.waitForView(android.R.id.list); assertEquals(CommentListActivity.class, getActivityInstance().getClass()); } @Test public void test7LikeCommentTest(){ onView(withId(R.id.butSearchItunes)).perform(click()); solo.waitForView(R.id.layout_1); onData(anything()).inAdapterView(withId(R.id.gridView)).atPosition(0). onChildView(withId(R.id.imgvCover)).perform(click()); //clicks on podcast solo.waitForView(R.id.relativeLayout); onView(withId(R.id.viewCommentsBtn)).perform(click()); solo.waitForView(R.id.constraintLayout); onView(withId(R.id.recyclerView_1)).perform( RecyclerViewActions.actionOnItemAtPosition(0, MyViewAction.clickChildViewWithId(R.id.like_btn))); assertEquals(CommentListActivity.class, getActivityInstance().getClass()); } @Test public void test8UnLikeCommentTest(){ onView(withId(R.id.butSearchItunes)).perform(click()); solo.waitForView(R.id.layout_1); onData(anything()).inAdapterView(withId(R.id.gridView)).atPosition(0). onChildView(withId(R.id.imgvCover)).perform(click()); //clicks on podcast solo.waitForView(R.id.relativeLayout); onView(withId(R.id.viewCommentsBtn)).perform(click()); solo.waitForView(R.id.constraintLayout); onView(withId(R.id.recyclerView_1)).perform( RecyclerViewActions.actionOnItemAtPosition(0, MyViewAction.clickChildViewWithId(R.id.like_btn))); assertEquals(CommentListActivity.class, getActivityInstance().getClass()); } private Activity getActivityInstance(){ final Activity[] currentActivity = {null}; getInstrumentation().runOnMainSync(new Runnable(){ public void run(){ Collection<Activity> resumedActivity = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED); Iterator<Activity> it = resumedActivity.iterator(); currentActivity[0] = it.next(); } }); return currentActivity[0]; } private String getActionbarTitle() { return ((MainActivity) solo.getCurrentActivity()).getSupportActionBar().getTitle().toString(); } private String getActionbarTitleRegisterLogin() { return ((RegisterAndLoginActivity) soloRegisterAndLogin.getCurrentActivity()).getSupportActionBar().getTitle().toString(); } private String getActionbarTitleLogin() { return ((LoginActivity) soloLogin.getCurrentActivity()).getSupportActionBar().getTitle().toString(); } private void getUser() { //Create User Based on Registered User user = FirebaseAuth.getInstance().getCurrentUser(); } }
924313d7349a56390363ede9eb31b4b6417c6a33
4,366
java
Java
src/com/jeffdisher/cacophony/logic/CacheAlgorithm.java
jmdisher/Cacophony
6b7063c86236920705984f4036c68b169b115a54
[ "MIT" ]
null
null
null
src/com/jeffdisher/cacophony/logic/CacheAlgorithm.java
jmdisher/Cacophony
6b7063c86236920705984f4036c68b169b115a54
[ "MIT" ]
null
null
null
src/com/jeffdisher/cacophony/logic/CacheAlgorithm.java
jmdisher/Cacophony
6b7063c86236920705984f4036c68b169b115a54
[ "MIT" ]
null
null
null
36.383333
120
0.734311
1,002,517
package com.jeffdisher.cacophony.logic; import java.util.ArrayList; import java.util.List; /** * A cache management algorithm which is intended to be used by a higher-level cache manager of some sort. * The implementation operates only on the data given to it, with no on-disk representation, so it should be applicable * to cache managers which want to do per-channel cache accounting or global cache accounting, equally well. * The general idea is to facilitate cache decisions which favour adding/retaining entries at the beginning of the given * lists, meaning the lists can be ordered to favour recent entries, large/small entries, or some other ordering. * The cache decisions are internally random but will tend toward being mostly full but will not make overflowing * decisions, itself (although it can handle the cases where it asked to overflow). */ public class CacheAlgorithm { /** * The type used to communicate cache decisions through this API. * * @param <T> The type of arbitrary user data required by the user's implementation. */ public static record Candidate<T>(long byteSize, T data) { } private final long _maximumSizeBytes; private long _currentSizeBytes; /** * Creates the cache algorithm with the given limit and initial state. * * @param maximumSizeBytes The maximum size the cache should be allowed to become, in bytes. * @param currentSizeBytes The current occupancy of the cache, in bytes. */ public CacheAlgorithm(long maximumSizeBytes, long currentSizeBytes) { _maximumSizeBytes = maximumSizeBytes; _currentSizeBytes = currentSizeBytes; } /** * @return The number of bytes currently available in the cache. */ public long getBytesAvailable() { return (_maximumSizeBytes - _currentSizeBytes); } /** * Updates the internal size of the cache to assume bytesAdded has been added by some external decision-maker. * * @param bytesAdded The number of bytes explicitly added to the cache. * @return True if the cache is now overflowing and needs to be cleaned. */ public boolean needsCleanAfterAddition(long bytesAdded) { _currentSizeBytes += bytesAdded; return (_currentSizeBytes > _maximumSizeBytes); } /** * Returns a subset of the given candidatesList which should be removed. Selection is done at random until the * cache is back within its limits. * * @param candidatesList The list of cache eviction Candidates. * @return The list of cache Candidates which should be evicted. */ public <T> List<Candidate<T>> toRemoveInResize(List<Candidate<T>> candidatesList) { List<Candidate<T>> candidates = new ArrayList<>(candidatesList); List<Candidate<T>> evictions = new ArrayList<>(); while (!candidates.isEmpty() && (_currentSizeBytes > _maximumSizeBytes)) { int index = (int)((double)candidates.size() * Math.random()); Candidate<T> candidate = candidates.remove(index); evictions.add(candidate); _currentSizeBytes -= candidate.byteSize; } return evictions; } /** * Called when a new channel is to be cached. The implementation will walk candidatesList, returning a subset which * should be added to the cache. The algorithm favours the entries at the beginning of the list for selection. * Note that the cache must be cleaned before adding this list or it may not add anything as it will not overflow. * * @param candidatesList The list of Candidates to consider for adding to the cache. * @return The list of Candidates which should be added to the cache (may be empty if the cache is full). */ public <T> List<Candidate<T>> toAddInNewAddition(List<Candidate<T>> candidatesList) { List<Candidate<T>> additions = new ArrayList<>(); for (Candidate<T> candidate : candidatesList) { if (_currentSizeBytes > _maximumSizeBytes) { // Exit case will be if we fill up (could be first iteration so we check before changing anything) break; } else if ((_currentSizeBytes + candidate.byteSize) > _maximumSizeBytes) { // This would have caused overflow so skip it. } else { double chanceToAdd = 1.0 - ((double)_currentSizeBytes / (double)_maximumSizeBytes); if (Math.random() < chanceToAdd) { // This has been selected for addition. additions.add(candidate); _currentSizeBytes += candidate.byteSize; } } } return additions; } }
9243153aaca01d9ddbd7f8d13f4f2cffa5b97a0f
27,663
java
Java
modules/scheduler/scheduler/src/test/java/org/motechproject/scheduler/it/MotechSchedulerDatabaseServiceImplBundleIT.java
afijal/motech
82b73483740e7e5130d8b0656ce150555716a909
[ "BSD-3-Clause" ]
17
2015-08-11T07:39:39.000Z
2021-08-30T04:24:51.000Z
modules/scheduler/scheduler/src/test/java/org/motechproject/scheduler/it/MotechSchedulerDatabaseServiceImplBundleIT.java
afijal/motech
82b73483740e7e5130d8b0656ce150555716a909
[ "BSD-3-Clause" ]
474
2015-08-11T08:15:03.000Z
2018-03-29T16:11:11.000Z
modules/scheduler/scheduler/src/test/java/org/motechproject/scheduler/it/MotechSchedulerDatabaseServiceImplBundleIT.java
afijal/motech
82b73483740e7e5130d8b0656ce150555716a909
[ "BSD-3-Clause" ]
71
2015-09-03T15:09:11.000Z
2018-07-24T04:34:30.000Z
43.156006
134
0.568919
1,002,518
package org.motechproject.scheduler.it; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.Period; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.motechproject.commons.date.model.DayOfWeek; import org.motechproject.commons.date.model.Time; import org.motechproject.event.MotechEvent; import org.motechproject.scheduler.contract.CronSchedulableJob; import org.motechproject.scheduler.contract.DayOfWeekSchedulableJob; import org.motechproject.scheduler.contract.JobBasicInfo; import org.motechproject.scheduler.contract.JobDetailedInfo; import org.motechproject.scheduler.contract.JobsSearchSettings; import org.motechproject.scheduler.contract.RepeatingSchedulableJob; import org.motechproject.scheduler.contract.RunOnceSchedulableJob; import org.motechproject.scheduler.contract.RepeatingPeriodSchedulableJob; import org.motechproject.scheduler.factory.MotechSchedulerFactoryBean; import org.motechproject.scheduler.service.MotechSchedulerDatabaseService; import org.motechproject.scheduler.service.MotechSchedulerService; import org.motechproject.testing.osgi.BasePaxIT; import org.motechproject.testing.osgi.container.MotechNativeTestContainerFactory; import org.ops4j.pax.exam.ExamFactory; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerSuite; import org.osgi.framework.BundleContext; import org.quartz.JobKey; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.impl.matchers.GroupMatcher; import javax.inject.Inject; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import static ch.lambdaj.Lambda.extract; import static ch.lambdaj.Lambda.on; import static java.lang.String.format; import static java.util.Arrays.asList; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static org.motechproject.commons.date.util.DateUtil.newDateTime; import static org.motechproject.testing.utils.TimeFaker.fakeNow; import static org.motechproject.testing.utils.TimeFaker.stopFakingTime; @RunWith(PaxExam.class) @ExamReactorStrategy(PerSuite.class) @ExamFactory(MotechNativeTestContainerFactory.class) public class MotechSchedulerDatabaseServiceImplBundleIT extends BasePaxIT { private static final int CURRENT_YEAR = DateTime.now().getYear(); private static final String DEFAULT_GROUP = "default-group"; @Inject private BundleContext context; @Inject private MotechSchedulerService schedulerService; @Inject private MotechSchedulerDatabaseService databaseService; MotechSchedulerFactoryBean motechSchedulerFactoryBean; Scheduler scheduler; @Before public void setUp() { setUpSecurityContextForDefaultUser("viewSchedulerJobs"); motechSchedulerFactoryBean = (MotechSchedulerFactoryBean) getBeanFromBundleContext(context, "org.motechproject.motech-scheduler", "motechSchedulerFactoryBean"); scheduler = motechSchedulerFactoryBean.getQuartzScheduler(); } @After public void tearDown() throws SchedulerException { schedulerService.unscheduleAllJobs("test_event"); } @Test public void shouldGetJobTimes() { try { fakeNow(newDateTime(CURRENT_YEAR + 6, 7, 15, 10, 0, 0)); Map<String, Object> params = new HashMap<>(); params.put(MotechSchedulerService.JOB_ID_KEY, "job_id"); schedulerService.scheduleJob( new CronSchedulableJob( new MotechEvent("test_event", params), "0 0 12 * * ?" )); List<DateTime> eventTimes = schedulerService.getScheduledJobTimings("test_event", "job_id", newDateTime(CURRENT_YEAR + 6, 7, 15, 12, 0, 0), newDateTime(CURRENT_YEAR + 6, 7, 17, 12, 0, 0)); assertEquals(asList( newDateTime(CURRENT_YEAR + 6, 7, 15, 12, 0, 0), newDateTime(CURRENT_YEAR + 6, 7, 16, 12, 0, 0), newDateTime(CURRENT_YEAR + 6, 7, 17, 12, 0, 0)), eventTimes); } finally { stopFakingTime(); } } @Test public void shouldCheckIFJobIsUIDefined() { try { fakeNow(newDateTime(CURRENT_YEAR + 6, 7, 15, 10, 0, 0)); Map<String, Object> params = new HashMap<>(); params.put(MotechSchedulerService.JOB_ID_KEY, "job_id"); schedulerService.scheduleRepeatingJob( new RepeatingSchedulableJob( new MotechEvent("test_event_2", params), null, DateTimeConstants.SECONDS_PER_DAY, newDateTime(CURRENT_YEAR + 6, 7, 15, 12, 0, 0), newDateTime(CURRENT_YEAR + 6, 7, 18, 12, 0, 0), false, false, true ) ); schedulerService.scheduleRepeatingPeriodJob( new RepeatingPeriodSchedulableJob( new MotechEvent("test_event_2", params), newDateTime(CURRENT_YEAR + 6, 7, 15, 12, 0, 0), newDateTime(CURRENT_YEAR + 6, 7, 18, 12, 0, 0), new Period(4, 0, 0, 0), false, false, false ) ); List<JobBasicInfo> expectedJobBasicInfos = new ArrayList<>(); expectedJobBasicInfos.add( new JobBasicInfo( JobBasicInfo.ACTIVITY_NOTSTARTED, JobBasicInfo.STATUS_OK, "test_event_2-job_id-repeat", DEFAULT_GROUP, format("%s-07-15 12:00:00", CURRENT_YEAR +6), format("%s-07-15 12:00:00", CURRENT_YEAR +6), format("%s-07-18 12:00:00", CURRENT_YEAR +6), JobBasicInfo.JOBTYPE_REPEATING, "", true ) ); expectedJobBasicInfos.add( new JobBasicInfo( JobBasicInfo.ACTIVITY_NOTSTARTED, JobBasicInfo.STATUS_OK, "test_event_2-job_id-period", DEFAULT_GROUP, format("%s-07-15 12:00:00", CURRENT_YEAR +6), format("%s-07-15 12:00:00", CURRENT_YEAR +6), format("%s-07-18 12:00:00", CURRENT_YEAR +6), JobBasicInfo.JOBTYPE_PERIOD, "", false ) ); int testJobsCount = 0; for (JobBasicInfo job : expectedJobBasicInfos) { for (JobBasicInfo expectedJob : expectedJobBasicInfos) { if(job.getName().equals(expectedJob.getName())) { testJobsCount+=1; assertEquals(expectedJob.isUiDefined(), job.isUiDefined()); } } } assertEquals(2, testJobsCount); } finally { stopFakingTime(); } } @Test public void shouldGetScheduledJobsBasicInfo() throws SchedulerException, SQLException { try { fakeNow(newDateTime(CURRENT_YEAR + 6, 7, 15, 10, 0, 0)); Map<String, Object> params = new HashMap<>(); params.put(MotechSchedulerService.JOB_ID_KEY, "job_id"); schedulerService.scheduleJob( new CronSchedulableJob( new MotechEvent("test_event_2", params), "0 0 12 * * ?" ) ); schedulerService.scheduleRunOnceJob( new RunOnceSchedulableJob( new MotechEvent("test_event_2", params), newDateTime(CURRENT_YEAR + 6, 7, 15, 12, 0, 0) ) ); schedulerService.scheduleRepeatingJob( new RepeatingSchedulableJob( new MotechEvent("test_event_2", params), DateTimeConstants.SECONDS_PER_DAY, newDateTime(CURRENT_YEAR + 6, 7, 15, 12, 0, 0), newDateTime(CURRENT_YEAR + 6, 7, 18, 12, 0, 0), false ) ); schedulerService.scheduleRepeatingPeriodJob( new RepeatingPeriodSchedulableJob( new MotechEvent("test_event_2", params), newDateTime(CURRENT_YEAR + 6, 7, 15, 12, 0, 0), newDateTime(CURRENT_YEAR + 6, 7, 18, 12, 0, 0), new Period(4, 0, 0, 0), false ) ); for (String groupName : scheduler.getJobGroupNames()) { for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) { if (jobKey.getName().equals("test_event_2-job_id")) { scheduler.pauseJob(jobKey); } } } List<JobBasicInfo> expectedJobBasicInfos = new ArrayList<>(); expectedJobBasicInfos.add( new JobBasicInfo( JobBasicInfo.ACTIVITY_NOTSTARTED, JobBasicInfo.STATUS_PAUSED, "test_event_2-job_id", DEFAULT_GROUP, format("%s-07-15 10:00:00", CURRENT_YEAR + 6), format("%s-07-15 12:00:00", CURRENT_YEAR + 6), "-", JobBasicInfo.JOBTYPE_CRON, "", false ) ); expectedJobBasicInfos.add( new JobBasicInfo( JobBasicInfo.ACTIVITY_NOTSTARTED, JobBasicInfo.STATUS_OK, "test_event_2-job_id-runonce", DEFAULT_GROUP, format("%s-07-15 12:00:00", CURRENT_YEAR + 6), format("%s-07-15 12:00:00", CURRENT_YEAR + 6), format("%s-07-15 12:00:00", CURRENT_YEAR + 6), JobBasicInfo.JOBTYPE_RUNONCE, "", false ) ); expectedJobBasicInfos.add( new JobBasicInfo( JobBasicInfo.ACTIVITY_NOTSTARTED, JobBasicInfo.STATUS_OK, "test_event_2-job_id-repeat", DEFAULT_GROUP, format("%s-07-15 12:00:00", CURRENT_YEAR +6), format("%s-07-15 12:00:00", CURRENT_YEAR +6), format("%s-07-18 12:00:00", CURRENT_YEAR +6), JobBasicInfo.JOBTYPE_REPEATING, "", false ) ); expectedJobBasicInfos.add( new JobBasicInfo( JobBasicInfo.ACTIVITY_NOTSTARTED, JobBasicInfo.STATUS_OK, "test_event_2-job_id-period", DEFAULT_GROUP, format("%s-07-15 12:00:00", CURRENT_YEAR +6), format("%s-07-15 12:00:00", CURRENT_YEAR +6), format("%s-07-18 12:00:00", CURRENT_YEAR +6), JobBasicInfo.JOBTYPE_PERIOD, "", false ) ); List<JobBasicInfo> jobBasicInfos; JobsSearchSettings jobsSearchSettings = getGridSettings(0, 10, "name", "asc"); jobBasicInfos = databaseService.getScheduledJobsBasicInfo(jobsSearchSettings); int testJobsCount = 0; for (JobBasicInfo job : jobBasicInfos) { for (JobBasicInfo expectedJob : expectedJobBasicInfos) { if(job.getName().equals(expectedJob.getName())) { testJobsCount+=1; assertEquals(expectedJob.getActivity(), job.getActivity()); assertEquals(expectedJob.getStatus(), job.getStatus()); assertEquals(expectedJob.getStartDate(), job.getStartDate()); assertEquals(expectedJob.getNextFireDate(), job.getNextFireDate()); } } } assertEquals(4, testJobsCount); } finally { stopFakingTime(); } } @Test public void shouldGetScheduledJobsBasicInfoWithSortingAndPagination() throws SchedulerException, SQLException { try { fakeNow(newDateTime(CURRENT_YEAR + 6, 7, 15, 10, 0, 0)); Map<String, Object> params = new HashMap<>(); params.put(MotechSchedulerService.JOB_ID_KEY, "job_id"); schedulerService.scheduleJob( new CronSchedulableJob( new MotechEvent("test_event_2a", params), "0 0 12 * * ?" ) ); schedulerService.scheduleRunOnceJob( new RunOnceSchedulableJob( new MotechEvent("test_event_2b", params), newDateTime(CURRENT_YEAR + 6, 7, 15, 12, 0, 0) ) ); schedulerService.scheduleRepeatingJob( new RepeatingSchedulableJob( new MotechEvent("test_event_2c", params), DateTimeConstants.SECONDS_PER_DAY, newDateTime(CURRENT_YEAR + 6, 7, 15, 12, 0, 0), newDateTime(CURRENT_YEAR + 6, 7, 18, 12, 0, 0), false ) ); JobBasicInfo expected = new JobBasicInfo( JobBasicInfo.ACTIVITY_NOTSTARTED, JobBasicInfo.STATUS_OK, "test_event_2a-job_id", DEFAULT_GROUP, format("%s-07-15 10:00:00", CURRENT_YEAR + 6), format("%s-07-15 12:00:00", CURRENT_YEAR + 6), "-", JobBasicInfo.JOBTYPE_CRON, "", false ); List<JobBasicInfo> jobBasicInfos; JobsSearchSettings jobsSearchSettings = getGridSettings(2, 2, "name", "desc"); jobBasicInfos = databaseService.getScheduledJobsBasicInfo(jobsSearchSettings); assertEquals(expected.getActivity(), jobBasicInfos.get(0).getActivity()); assertEquals(expected.getStatus(), jobBasicInfos.get(0).getStatus()); assertEquals(expected.getStartDate(), jobBasicInfos.get(0).getStartDate()); assertEquals(expected.getNextFireDate(), jobBasicInfos.get(0).getNextFireDate()); } finally { stopFakingTime(); } } @Test public void shouldGetScheduledJobDetailedInfo() throws SchedulerException, SQLException { try { fakeNow(newDateTime(CURRENT_YEAR + 6, 7, 15, 10, 0, 0)); JobDetailedInfo jobDetailedInfo = null; Map<String, Object> params = new HashMap<>(); params.put(MotechSchedulerService.JOB_ID_KEY, "job_id_2"); params.put("param1","value1"); params.put("param2","value2"); schedulerService.scheduleRunOnceJob( new RunOnceSchedulableJob( new MotechEvent("test_event_2", params), newDateTime(CURRENT_YEAR + 6, 7, 15, 12, 0, 0) )); JobsSearchSettings jobsSearchSettings = getGridSettings(0, 10, "name", "asc"); for (JobBasicInfo job : databaseService.getScheduledJobsBasicInfo(jobsSearchSettings)) { if (job.getName().equals("test_event_2-job_id_2-runonce")) { jobDetailedInfo = databaseService.getScheduledJobDetailedInfo(job); } } assertNotNull(jobDetailedInfo); assertEquals("test_event_2", jobDetailedInfo.getEventInfoList().get(0).getSubject()); assertEquals(4, jobDetailedInfo.getEventInfoList().get(0).getParameters().size()); } finally { stopFakingTime(); } } @Test public void shouldFilterJobsByDate() { try { fakeNow(newDateTime(CURRENT_YEAR + 1, 7, 13, 5, 0, 0)); addTestJobs(); JobsSearchSettings jobsSearchSettings = getGridSettings(null, null, "name", "asc"); jobsSearchSettings.setTimeTo(format("%s-03-15 9:30:00", CURRENT_YEAR + 7)); jobsSearchSettings.setTimeFrom(format("%s-03-15 9:30:00", CURRENT_YEAR + 3)); List<JobBasicInfo> jobs = databaseService.getScheduledJobsBasicInfo(jobsSearchSettings); assertNotNull(jobs); assertEquals(3, jobs.size()); assertEquals("test_event_3-job_id3", jobs.get(0).getName()); assertEquals("test_event_5-job_id5-runonce", jobs.get(1).getName()); assertEquals("test_event_6-job_id6-repeat", jobs.get(2).getName()); jobsSearchSettings.setTimeTo(format("%s-03-15 9:30:00", CURRENT_YEAR + 5)); jobs = databaseService.getScheduledJobsBasicInfo(jobsSearchSettings); assertNotNull(jobs); assertEquals(2, jobs.size()); jobsSearchSettings.setTimeFrom(""); jobs = databaseService.getScheduledJobsBasicInfo(jobsSearchSettings); assertNotNull(jobs); assertEquals(5, jobs.size()); } finally { stopFakingTime(); } } @Test public void shouldReturnAllJobsWhenNoFiltersSet() { try { fakeNow(newDateTime(CURRENT_YEAR + 1, 7, 13, 5, 0, 0)); addTestJobs(); JobsSearchSettings jobsSearchSettings = new JobsSearchSettings(); List<JobBasicInfo> jobs = databaseService.getScheduledJobsBasicInfo(jobsSearchSettings); assertNotNull(jobs); assertEquals(6, jobs.size()); } finally { stopFakingTime(); } } @Test public void shouldFilterJobsByName() { try { fakeNow(newDateTime(CURRENT_YEAR + 1, 7, 13, 5, 0, 0)); addTestJobs(); JobsSearchSettings jobsSearchSettings = getGridSettings(null, null, "name", "asc"); jobsSearchSettings.setName("id1"); List<JobBasicInfo> jobs = databaseService.getScheduledJobsBasicInfo(jobsSearchSettings); assertNotNull(jobs); assertEquals(1, jobs.size()); assertEquals(jobs.get(0).getName(), "test_event_1-job_id1"); int rowCount = databaseService.countJobs(jobsSearchSettings); assertEquals(1, rowCount); jobsSearchSettings.setName("test_ev"); jobs = databaseService.getScheduledJobsBasicInfo(jobsSearchSettings); assertNotNull(jobs); assertEquals(6, jobs.size()); rowCount = databaseService.countJobs(jobsSearchSettings); assertEquals(6, rowCount); jobsSearchSettings.setName("test_event_2-job_id2"); jobs = databaseService.getScheduledJobsBasicInfo(jobsSearchSettings); assertNotNull(jobs); assertEquals(1, jobs.size()); assertEquals(jobs.get(0).getName(), "test_event_2-job_id2"); rowCount = databaseService.countJobs(jobsSearchSettings); assertEquals(1, rowCount); } finally { stopFakingTime(); } } @Test public void shouldFilterJobsByActivity() { try { fakeNow(newDateTime(CURRENT_YEAR + 1, 7, 13, 5, 0, 0)); addTestJobs(); JobsSearchSettings jobsSearchSettings = getGridSettings(null, null, "name", "asc"); jobsSearchSettings.setActivity(JobBasicInfo.ACTIVITY_NOTSTARTED); List<JobBasicInfo> jobs = databaseService.getScheduledJobsBasicInfo(jobsSearchSettings); assertNotNull(jobs); assertEquals(5, jobs.size()); jobsSearchSettings.setActivity(JobBasicInfo.ACTIVITY_ACTIVE); jobs = databaseService.getScheduledJobsBasicInfo(jobsSearchSettings); assertEquals(1, jobs.size()); } finally { stopFakingTime(); } } @Test public void shouldFilterJobsWithSortingAndPagination() { try { fakeNow(newDateTime(CURRENT_YEAR + 1, 7, 13, 10, 0, 0)); addTestJobs(); JobsSearchSettings jobsSearchSettings = getGridSettings(1, 5, "name", "asc"); jobsSearchSettings.setName("event"); List<JobBasicInfo> jobs = databaseService.getScheduledJobsBasicInfo(jobsSearchSettings); assertNotNull(jobs); assertEquals(5, jobs.size()); assertEquals(6, databaseService.countJobs(jobsSearchSettings)); assertEquals(printJobNames(jobs), "test_event_1-job_id1", jobs.get(0).getName()); jobsSearchSettings.setPage(2); jobsSearchSettings.setName("test"); jobs = databaseService.getScheduledJobsBasicInfo(jobsSearchSettings); assertNotNull(jobs); assertEquals(1, jobs.size()); assertEquals(6, databaseService.countJobs(jobsSearchSettings)); jobsSearchSettings.setPage(3); jobsSearchSettings.setRows(2); jobsSearchSettings.setSortDirection("desc"); jobsSearchSettings.setActivity(JobBasicInfo.ACTIVITY_NOTSTARTED); jobs = databaseService.getScheduledJobsBasicInfo(jobsSearchSettings); assertNotNull(jobs); assertEquals(1, jobs.size()); assertEquals(JobBasicInfo.ACTIVITY_NOTSTARTED, jobs.get(0).getActivity()); assertEquals(5, databaseService.countJobs(jobsSearchSettings)); jobsSearchSettings = getGridSettings(1, 2, "name", "asc"); jobsSearchSettings.setTimeTo(format("%s-03-15 9:30:00", CURRENT_YEAR + 7)); jobsSearchSettings.setTimeFrom(format("%s-03-15 9:30:00", CURRENT_YEAR + 3)); jobs = databaseService.getScheduledJobsBasicInfo(jobsSearchSettings); assertEquals(2, jobs.size()); assertEquals(printJobNames(jobs), "test_event_3-job_id3", jobs.get(0).getName()); assertEquals(3, databaseService.countJobs(jobsSearchSettings)); jobsSearchSettings.setSortDirection("desc"); jobs = databaseService.getScheduledJobsBasicInfo(jobsSearchSettings); assertEquals(2, jobs.size()); assertEquals(printJobNames(jobs), "test_event_6-job_id6-repeat", jobs.get(0).getName()); assertEquals(3, databaseService.countJobs(jobsSearchSettings)); } finally { stopFakingTime(); } } private void addTestJobs() { Map<String, Object> params = new HashMap<>(); params.put(MotechSchedulerService.JOB_ID_KEY, "job_id1"); // this job should be active schedulerService.scheduleDayOfWeekJob( new DayOfWeekSchedulableJob( new MotechEvent("test_event_1", params), new DateTime(CURRENT_YEAR - 1, 3, 10, 0, 0), new DateTime(CURRENT_YEAR + 2, 3, 22, 0, 0), Arrays.asList(DayOfWeek.Monday, DayOfWeek.Thursday), new Time(10, 10), false) ); params = new HashMap<>(); params.put(MotechSchedulerService.JOB_ID_KEY, "job_id2"); schedulerService.scheduleDayOfWeekJob( new DayOfWeekSchedulableJob( new MotechEvent("test_event_2", params), new DateTime(CURRENT_YEAR + 1, 7, 10, 0, 0), new DateTime(CURRENT_YEAR + 3, 7, 22, 0, 0), Arrays.asList(DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday), new Time(10, 10), false) ); params = new HashMap<>(); params.put(MotechSchedulerService.JOB_ID_KEY, "job_id3"); schedulerService.scheduleDayOfWeekJob( new DayOfWeekSchedulableJob( new MotechEvent("test_event_3", params), new DateTime(CURRENT_YEAR + 4, 7, 10, 0, 0), new DateTime(CURRENT_YEAR + 5, 7, 22, 0, 0), Arrays.asList(DayOfWeek.Monday, DayOfWeek.Thursday), new Time(10, 10), false) ); params = new HashMap<>(); params.put(MotechSchedulerService.JOB_ID_KEY, "job_id4"); schedulerService.scheduleJob( new CronSchedulableJob( new MotechEvent("test_event_4", params), "0 0 12 * * ?" ) ); params = new HashMap<>(); params.put(MotechSchedulerService.JOB_ID_KEY, "job_id5"); schedulerService.scheduleRunOnceJob( new RunOnceSchedulableJob( new MotechEvent("test_event_5", params), newDateTime(CURRENT_YEAR + 6, 7, 15, 12, 0, 0) ) ); params = new HashMap<>(); params.put(MotechSchedulerService.JOB_ID_KEY, "job_id6"); schedulerService.scheduleRepeatingJob( new RepeatingSchedulableJob( new MotechEvent("test_event_6", params), DateTimeConstants.SECONDS_PER_DAY, newDateTime(CURRENT_YEAR + 4, 7, 15, 12, 0, 0), newDateTime(CURRENT_YEAR + 4, 7, 18, 12, 0, 0), false ) ); } private JobsSearchSettings getGridSettings(Integer page, Integer rows, String sortColumn, String direction) { JobsSearchSettings jobsSearchSettings = new JobsSearchSettings(); jobsSearchSettings.setActivity(format("%s,%s,%s", JobBasicInfo.ACTIVITY_ACTIVE, JobBasicInfo.ACTIVITY_FINISHED, JobBasicInfo.ACTIVITY_NOTSTARTED )); jobsSearchSettings.setName(""); jobsSearchSettings.setPage(page); jobsSearchSettings.setRows(rows); jobsSearchSettings.setSortColumn(sortColumn); jobsSearchSettings.setStatus(format("%s,%s,%s,%s", JobBasicInfo.STATUS_BLOCKED, JobBasicInfo.STATUS_ERROR, JobBasicInfo.STATUS_OK, JobBasicInfo.STATUS_PAUSED )); jobsSearchSettings.setSortDirection(direction); jobsSearchSettings.setTimeFrom(""); jobsSearchSettings.setTimeTo(""); return jobsSearchSettings; } private String printJobNames(Collection<JobBasicInfo> jobs) { return "Job names: " + extract(jobs, on(JobBasicInfo.class).getName()); } }
9243157021b6f3573a7eefb484e46da814902e23
1,482
java
Java
src/utils/FXMLLoad.java
hitong/ChartRoom
dc25fdec9728dd002027c776bfe54990b0f71ee4
[ "Apache-2.0" ]
1
2019-08-30T14:42:25.000Z
2019-08-30T14:42:25.000Z
src/utils/FXMLLoad.java
hitong/ChartRoom
dc25fdec9728dd002027c776bfe54990b0f71ee4
[ "Apache-2.0" ]
null
null
null
src/utils/FXMLLoad.java
hitong/ChartRoom
dc25fdec9728dd002027c776bfe54990b0f71ee4
[ "Apache-2.0" ]
null
null
null
26.945455
104
0.688934
1,002,519
package utils; import java.io.IOException; import client.AddFriendControl; import client.ChatViewControl; import client.ContextControl; import client.LaunchClient; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import model.Friend; public class FXMLLoad { public static <V extends InversionControl<LaunchClient>> Scene load(String sourse, LaunchClient main){ FXMLLoader loader = new FXMLLoader(); loader.setLocation(LaunchClient.class.getResource(sourse)); try { Parent parent = loader.load(); Scene scene = new Scene(parent); V c = loader.getController(); c.setMain(main); main.setViewControl(c); return scene; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public static Parent load(String sourse, ChatViewControl main, Friend friend){ FXMLLoader loader = new FXMLLoader(); loader.setLocation(LaunchClient.class.getResource(sourse)); try { Parent parent = loader.load(); if(friend != null){ ContextControl c = loader.getController(); c.setMain(main); c.setFriend(friend); main.addChat(friend.getUserId().getValue(), c); } else { AddFriendControl c = loader.getController(); c.setMain(main); main.setAddCtl(c); } return parent; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
9243160db150a20ba65fad40c88239281d955df7
3,281
java
Java
core/src/main/java/com/orientechnologies/common/log/OLogFormatter.java
bernhardriegler/orientdb
9d1e4ff1bb5ebb52092856baad40c35cf27295f8
[ "Apache-2.0" ]
3,651
2015-01-02T23:58:10.000Z
2022-03-31T21:12:12.000Z
core/src/main/java/com/orientechnologies/common/log/OLogFormatter.java
bernhardriegler/orientdb
9d1e4ff1bb5ebb52092856baad40c35cf27295f8
[ "Apache-2.0" ]
6,890
2015-01-01T09:41:48.000Z
2022-03-29T08:39:49.000Z
core/src/main/java/com/orientechnologies/common/log/OLogFormatter.java
bernhardriegler/orientdb
9d1e4ff1bb5ebb52092856baad40c35cf27295f8
[ "Apache-2.0" ]
923
2015-01-01T20:40:08.000Z
2022-03-21T07:26:56.000Z
30.95283
88
0.698568
1,002,520
/* * * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * * For more information: http://orientdb.com * */ package com.orientechnologies.common.log; import java.io.PrintWriter; import java.io.StringWriter; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.IllegalFormatException; import java.util.logging.Formatter; import java.util.logging.Level; import java.util.logging.LogRecord; /** * Basic Log formatter. * * @author Luca Garulli (l.garulli--(at)--orientdb.com) */ public class OLogFormatter extends Formatter { protected static final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS"); /** The end-of-line character for this platform. */ protected static final String EOL = System.getProperty("line.separator"); @Override public String format(final LogRecord record) { if (record.getThrown() == null) { return customFormatMessage(record); } // FORMAT THE STACK TRACE final StringBuilder buffer = new StringBuilder(512); buffer.append(record.getMessage()); final Throwable current = record.getThrown(); if (current != null) { buffer.append(EOL); StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); current.printStackTrace(printWriter); printWriter.flush(); buffer.append(writer.getBuffer()); printWriter.close(); } return buffer.toString(); } protected String customFormatMessage(final LogRecord iRecord) { final Level level = iRecord.getLevel(); final String message = OAnsiCode.format(iRecord.getMessage(), false); final Object[] additionalArgs = iRecord.getParameters(); final String requester = getSourceClassSimpleName(iRecord.getLoggerName()); final StringBuilder buffer = new StringBuilder(512); buffer.append(EOL); buffer.append(dateFormatter.format(LocalDateTime.now())); buffer.append(String.format(" %-5.5s ", level.getName())); // FORMAT THE MESSAGE try { if (additionalArgs != null) buffer.append(String.format(message, additionalArgs)); else buffer.append(message); } catch (IllegalFormatException ignore) { buffer.append(message); } if (requester != null) { buffer.append(" ["); buffer.append(requester); buffer.append(']'); } return OAnsiCode.format(buffer.toString(), false); } protected String getSourceClassSimpleName(final String iSourceClassName) { if (iSourceClassName == null) return null; return iSourceClassName.substring(iSourceClassName.lastIndexOf(".") + 1); } }
924316bbbf67bb65b5539f61f92c1d7fe7432489
1,858
java
Java
May-05-2020/Cloud-Native-API-Management-on-Kubernetes/Hospital-Service/src/main/java/org/wso2/service/hospital/daos/HospitalDAO.java
knightbeat/labs
c9c4bda9462aa337618d873523253f4cae524d3f
[ "Apache-2.0" ]
2
2020-06-25T08:28:33.000Z
2022-02-17T14:12:43.000Z
May-05-2020/Cloud-Native-API-Management-on-Kubernetes/Hospital-Service/src/main/java/org/wso2/service/hospital/daos/HospitalDAO.java
knightbeat/labs
c9c4bda9462aa337618d873523253f4cae524d3f
[ "Apache-2.0" ]
4
2020-04-30T18:25:31.000Z
2020-07-15T21:36:41.000Z
May-05-2020/Cloud-Native-API-Management-on-Kubernetes/Hospital-Service/src/main/java/org/wso2/service/hospital/daos/HospitalDAO.java
knightbeat/labs
c9c4bda9462aa337618d873523253f4cae524d3f
[ "Apache-2.0" ]
13
2020-04-30T18:19:53.000Z
2020-07-21T16:27:51.000Z
26.927536
87
0.614639
1,002,521
package org.wso2.service.hospital.daos; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Created by vijitha on 7/8/16. */ public class HospitalDAO { private List<Doctor> doctorsList = new ArrayList<>(); private List<String> catergories = new ArrayList<>(); private HashMap<String, Patient> patientMap= new HashMap(); private HashMap<String, PatientRecord> patientRecordMap = new HashMap(); public List<Doctor> findDoctorByCategory(String category) { List<Doctor> list = new ArrayList<>(); for (Doctor doctor: doctorsList) { if (category.equals(doctor.getCategory())) { list.add(doctor); } } return list; } public Doctor findDoctorByName(String name) { for (Doctor doctor: doctorsList) { if (doctor.getName().equals(name)) { return doctor; } } return null; } public List<Doctor> getDoctorsList() { return doctorsList; } public void setDoctorsList(List<Doctor> doctorsList) { this.doctorsList = doctorsList; } public List<String> getCatergories() { return catergories; } public void setCatergories(List<String> catergories) { this.catergories = catergories; } public HashMap<String, Patient> getPatientMap() { return patientMap; } public void setPatientMap(HashMap<String, Patient> patientMap) { this.patientMap = patientMap; } public HashMap<String, PatientRecord> getPatientRecordMap() { return patientRecordMap; } public void setPatientRecordMap(HashMap<String, PatientRecord> patientRecordMap) { this.patientRecordMap = patientRecordMap; } }
924317396b90ad72394210e14afa39520cd1d23f
1,866
java
Java
src/test/java/cl/guaman/microservice/user/application/util/CryptoUtilTest.java
fguaman/microservice-user
52e10fca6636bb74351b925234540f9aea873dda
[ "MIT" ]
1
2019-07-05T16:36:41.000Z
2019-07-05T16:36:41.000Z
src/test/java/cl/guaman/microservice/user/application/util/CryptoUtilTest.java
fguaman/api-user
52e10fca6636bb74351b925234540f9aea873dda
[ "MIT" ]
1
2019-07-30T02:30:41.000Z
2019-07-30T02:30:41.000Z
src/test/java/cl/guaman/microservice/user/application/util/CryptoUtilTest.java
fguaman/api-user
52e10fca6636bb74351b925234540f9aea873dda
[ "MIT" ]
1
2019-07-30T01:21:48.000Z
2019-07-30T01:21:48.000Z
35.207547
112
0.721329
1,002,522
package cl.guaman.microservice.user.application.util; import lombok.extern.slf4j.Slf4j; import org.assertj.core.util.VisibleForTesting; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.util.Assert; @Slf4j @SpringBootTest @ExtendWith(SpringExtension.class) @WebAppConfiguration @TestInstance(TestInstance.Lifecycle.PER_CLASS) public class CryptoUtilTest { @Autowired private CryptoUtil cryptoUtil; @Test @VisibleForTesting void encodeTest() { String text = "1234567890"; String encodedText = cryptoUtil.encode(text); log.info("encodeTest | text={}, encodeText={}", text, encodedText); Assert.notNull(encodedText, "is null"); } @Test @VisibleForTesting void validateTest() { String text = "Hello Country!!!"; String encodedText = cryptoUtil.encode(text); boolean validateText = cryptoUtil.validate(text, encodedText); log.info("validateTest | validateText={}, text={}, encodeText={}", validateText, text, encodedText); Assert.isTrue(validateText, "is false"); } @Test @VisibleForTesting void validateFailTest() { String text = "Hello Country!!!"; String encodedText = cryptoUtil.encode(text); boolean validateText = cryptoUtil.validate(text.concat("other text"), encodedText); log.info("validateFailTest | validateText={}, text={}, encodeText={}", validateText, text, encodedText); Assert.isTrue(!validateText, "is true"); } }
924319437a78d4caa8dade7215ad2dfb804eec7f
4,695
java
Java
main/plugins/org.talend.designer.core/src/main/java/org/talend/designer/core/ui/action/ShowBreakpointAction.java
coheigea/tdi-studio-se
c4cd4df0fc841c497b51718e623145d29d0bf030
[ "Apache-2.0" ]
114
2015-03-05T15:34:59.000Z
2022-02-22T03:48:44.000Z
main/plugins/org.talend.designer.core/src/main/java/org/talend/designer/core/ui/action/ShowBreakpointAction.java
coheigea/tdi-studio-se
c4cd4df0fc841c497b51718e623145d29d0bf030
[ "Apache-2.0" ]
1,137
2015-03-04T01:35:42.000Z
2022-03-29T06:03:17.000Z
main/plugins/org.talend.designer.core/src/main/java/org/talend/designer/core/ui/action/ShowBreakpointAction.java
coheigea/tdi-studio-se
c4cd4df0fc841c497b51718e623145d29d0bf030
[ "Apache-2.0" ]
219
2015-01-21T10:42:18.000Z
2022-02-17T07:57:20.000Z
38.483607
128
0.64558
1,002,523
// ============================================================================ // // Copyright (C) 2006-2021 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.designer.core.ui.action; import java.util.List; import org.eclipse.gef.ui.actions.SelectionAction; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.talend.core.PluginChecker; import org.talend.core.model.process.EComponentCategory; import org.talend.designer.core.i18n.Messages; import org.talend.designer.core.ui.editor.connections.ConnLabelEditPart; import org.talend.designer.core.ui.editor.connections.Connection; import org.talend.designer.core.ui.editor.connections.ConnectionPart; import org.talend.designer.core.ui.editor.connections.ConnectionTraceEditPart; import org.talend.designer.core.ui.views.properties.ComponentSettingsView; /** * DOC Administrator class global comment. Detailled comment */ public class ShowBreakpointAction extends SelectionAction { private static final String SHOW_BREAKPOINT_TITLE = Messages.getString("ShowBreakpointAction.ShowBreakpoint"); //$NON-NLS-1$ private Connection connection; private IWorkbenchPart part; /** * DOC Administrator ShowBreakpointAction constructor comment. * * @param part */ public ShowBreakpointAction(IWorkbenchPart part) { super(part); this.part = part; // TODO Auto-generated constructor stub setText(SHOW_BREAKPOINT_TITLE); setToolTipText(SHOW_BREAKPOINT_TITLE); setDescription(SHOW_BREAKPOINT_TITLE); } /* * (non-Javadoc) * * @see org.eclipse.gef.ui.actions.WorkbenchPartAction#calculateEnabled() */ @Override protected boolean calculateEnabled() { // TODO Auto-generated method stub List parts = getSelectedObjects(); if (parts.size() != 1) { return false; } Object input = parts.get(0); if (input instanceof ConnectionPart) { ConnectionPart connPart = (ConnectionPart) input; List childParts = connPart.getChildren(); for (Object part : childParts) { if (part != null && part instanceof ConnectionTraceEditPart) { connection = (Connection) connPart.getModel(); return connection.enableTraces() && PluginChecker.isTraceDebugPluginLoaded(); } } } if (input instanceof ConnLabelEditPart) { ConnLabelEditPart labelPart = (ConnLabelEditPart) input; ConnectionPart connPart = (ConnectionPart) labelPart.getParent(); List childParts = connPart.getChildren(); for (Object part : childParts) { if (part != null && part instanceof ConnectionTraceEditPart) { connection = (Connection) connPart.getModel(); return connection.enableTraces() && PluginChecker.isTraceDebugPluginLoaded(); } } } if (input instanceof ConnectionTraceEditPart) { ConnectionTraceEditPart connTrace = (ConnectionTraceEditPart) input; if (connTrace.getParent() instanceof ConnectionPart) { ConnectionPart connPart = (ConnectionPart) connTrace.getParent(); connection = (Connection) connPart.getModel(); return connection.enableTraces() && PluginChecker.isTraceDebugPluginLoaded(); } } return false; } public void run() { IWorkbench workbench = PlatformUI.getWorkbench(); IWorkbenchPage page = workbench.getActiveWorkbenchWindow().getActivePage(); ComponentSettingsView view; try { view = (ComponentSettingsView) page.showView(ComponentSettingsView.ID); view.setElement(connection); view.selectTab(EComponentCategory.BREAKPOINT); } catch (PartInitException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String getViewId() { // return "org.eclipse.ui.views.PropertySheet"; //$NON-NLS-1$ return ComponentSettingsView.ID; } }
9243194435d10915bb061d37bb5d450301518ae8
76
java
Java
client/src/test/java/com/echo/client/demo/HelloWorld.java
DickensTone/StrageEcho
526095f208ed211d05845b43e73e04d8ffb603ca
[ "Apache-2.0" ]
1
2021-10-17T14:09:02.000Z
2021-10-17T14:09:02.000Z
client/src/test/java/com/echo/client/demo/HelloWorld.java
DickensTone/StrageEcho
526095f208ed211d05845b43e73e04d8ffb603ca
[ "Apache-2.0" ]
null
null
null
client/src/test/java/com/echo/client/demo/HelloWorld.java
DickensTone/StrageEcho
526095f208ed211d05845b43e73e04d8ffb603ca
[ "Apache-2.0" ]
null
null
null
12.666667
41
0.789474
1,002,524
package com.echo.client.demo; public class HelloWorld implements Greet{ }
92431a186ce80e28f1a15adb204137a46576699a
853
java
Java
app/src/androidTest/java/jacksonmeyer/com/earthquakemadness/MapsActivityInstrumentedTest.java
meyerjac/EarthquakeMadness
5cd3171384d9d01f15c2e3eeb80e784367c383d7
[ "Unlicense" ]
null
null
null
app/src/androidTest/java/jacksonmeyer/com/earthquakemadness/MapsActivityInstrumentedTest.java
meyerjac/EarthquakeMadness
5cd3171384d9d01f15c2e3eeb80e784367c383d7
[ "Unlicense" ]
null
null
null
app/src/androidTest/java/jacksonmeyer/com/earthquakemadness/MapsActivityInstrumentedTest.java
meyerjac/EarthquakeMadness
5cd3171384d9d01f15c2e3eeb80e784367c383d7
[ "Unlicense" ]
null
null
null
24.371429
98
0.685815
1,002,525
package jacksonmeyer.com.earthquakemadness; import android.content.Intent; import android.support.test.filters.SmallTest; import android.test.ActivityInstrumentationTestCase2; /** * Created by jacksonmeyer on 5/8/17. */ public class MapsActivityInstrumentedTest extends ActivityInstrumentationTestCase2<MapsActivity> { public MapsActivityInstrumentedTest() { super(MapsActivity.class); } //just testing intent extras are sent, and activity starts @Override public void setUp() throws Exception { super.setUp(); Intent i = new Intent(); i.putExtra("lat", "45.45"); i.putExtra("lng", "45.45"); setActivityIntent(i); } @SmallTest public void testActivityIntents() { // checks that the activity will even start and grab intents getActivity(); } }
92431a5ac38e26d593dcbaf8bc629b76dad020f1
1,970
java
Java
FitBuddy/src/main/java/com/revature/services/FoodService.java
Three-of-Kind-Project2/FitBuddy-backend
90bc49694569ab8f77a7f7751b2e79b36070909c
[ "MIT" ]
null
null
null
FitBuddy/src/main/java/com/revature/services/FoodService.java
Three-of-Kind-Project2/FitBuddy-backend
90bc49694569ab8f77a7f7751b2e79b36070909c
[ "MIT" ]
null
null
null
FitBuddy/src/main/java/com/revature/services/FoodService.java
Three-of-Kind-Project2/FitBuddy-backend
90bc49694569ab8f77a7f7751b2e79b36070909c
[ "MIT" ]
1
2020-09-29T15:58:18.000Z
2020-09-29T15:58:18.000Z
18.761905
62
0.667513
1,002,526
package com.revature.services; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.revature.models.Food; import com.revature.models.Meal; import com.revature.models.User; import com.revature.repositories.IFoodDAO; import com.revature.repositories.IMealDAO; import com.revature.repositories.IUserDAO; @Service public class FoodService { @Autowired private IFoodDAO foodDao; @Autowired private IMealDAO mealDao; @Autowired private IUserDAO userDao; public List<Food> getAllFood() { return foodDao.allFood(); } public List<Food> getFoodByUser(int userId) { User u = userDao.findById(userId); List<Meal> meals = mealDao.findByUser(u); List<Food> food = new ArrayList<>(); for (Meal m : meals) { List<Food> mealFood = foodByMeal(m); for (Food f : mealFood) { food.add(f); } } return food; } public List<Food> foodByMeal(Meal m) { return foodDao.findByMeal(m); } public List<Food> foodByMeal(int mealId) { Meal m = mealDao.findById(mealId); if (m != null) { return foodDao.findByMeal(m); } return null; } public Food addFood(Food f, Meal m) { f.setMeal(m); return update(f); } public Food addFood(Food f, int mealId) { Meal m = mealDao.findById(mealId); if (m != null) { f.setMeal(m); return update(f); } return null; } public Food insert(Food f) { int id = foodDao.insert(f); if (id != 0) { f.setId(id); return update(f); } return null; } public Food update(Food f) { return foodDao.update(f); } public void delete(Food f) { foodDao.delete(f); } public void deleteAllFromUser(User u) { List<Meal> meals = mealDao.findByUser(u); for (Meal m : meals) { List<Food> foods = foodDao.findByMeal(m); if (foods.size() != 0) { for (Food f : foods) { delete(f); } } mealDao.delete(m); } } }
92431b75ff2132cf3af7d302a6aa1b662a8d6356
1,875
java
Java
couteau-lang/src/main/java/com/mmnaseri/couteau/lang/support/impl/GenericLanguageOutput.java
agileapes/couteau
e39931bf492d9f52f5af96c19d89853aac61188f
[ "MIT" ]
null
null
null
couteau-lang/src/main/java/com/mmnaseri/couteau/lang/support/impl/GenericLanguageOutput.java
agileapes/couteau
e39931bf492d9f52f5af96c19d89853aac61188f
[ "MIT" ]
null
null
null
couteau-lang/src/main/java/com/mmnaseri/couteau/lang/support/impl/GenericLanguageOutput.java
agileapes/couteau
e39931bf492d9f52f5af96c19d89853aac61188f
[ "MIT" ]
null
null
null
36.173077
85
0.751196
1,002,527
/* * The MIT License (MIT) * * Copyright (c) 2013 Milad Naseri. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mmnaseri.couteau.lang.support.impl; import com.mmnaseri.couteau.lang.support.Language; import com.mmnaseri.couteau.lang.support.LanguageOutput; import java.io.OutputStream; /** * This is a generic language output that can be used to give access to a target * output stream for any language * * @author Milad Naseri ([email protected]) * @since 1.0 (5/20/13, 8:04 PM) */ public class GenericLanguageOutput<L extends Language> implements LanguageOutput<L> { private final OutputStream outputStream; public GenericLanguageOutput(OutputStream outputStream) { this.outputStream = outputStream; } @Override public OutputStream getOutputStream() { return outputStream; } }
92431b9a4889fadc4a5ab1b55880d3becb8b95bd
1,489
java
Java
hibernate-release-5.3.7.Final/project/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/LogicalAuditExpression.java
lauracristinaes/aula-java
cb8d5b314b65a9914b93f3b5792bc98b548fe260
[ "Apache-2.0" ]
1
2021-11-11T01:36:23.000Z
2021-11-11T01:36:23.000Z
hibernate-release-5.3.7.Final/project/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/LogicalAuditExpression.java
lauracristinaes/aula-java
cb8d5b314b65a9914b93f3b5792bc98b548fe260
[ "Apache-2.0" ]
null
null
null
hibernate-release-5.3.7.Final/project/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/LogicalAuditExpression.java
lauracristinaes/aula-java
cb8d5b314b65a9914b93f3b5792bc98b548fe260
[ "Apache-2.0" ]
null
null
null
33.840909
123
0.778375
1,002,528
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.envers.query.criteria.internal; import java.util.Map; import org.hibernate.envers.boot.internal.EnversService; import org.hibernate.envers.internal.reader.AuditReaderImplementor; import org.hibernate.envers.internal.tools.query.Parameters; import org.hibernate.envers.internal.tools.query.QueryBuilder; import org.hibernate.envers.query.criteria.AuditCriterion; /** * @author Adam Warski (adam at warski dot org) */ public class LogicalAuditExpression implements AuditCriterion { private AuditCriterion lhs; private AuditCriterion rhs; private String op; public LogicalAuditExpression(AuditCriterion lhs, AuditCriterion rhs, String op) { this.lhs = lhs; this.rhs = rhs; this.op = op; } public void addToQuery( EnversService enversService, AuditReaderImplementor versionsReader, Map<String, String> aliasToEntityNameMap, String alias, QueryBuilder qb, Parameters parameters) { Parameters opParameters = parameters.addSubParameters( op ); lhs.addToQuery( enversService, versionsReader, aliasToEntityNameMap, alias, qb, opParameters.addSubParameters( "and" ) ); rhs.addToQuery( enversService, versionsReader, aliasToEntityNameMap, alias, qb, opParameters.addSubParameters( "and" ) ); } }
92431c82a7174318ce7f04c46450ffb258e28f90
3,224
java
Java
uberfire-extensions/uberfire-commons-editor/uberfire-commons-editor-api/src/main/java/org/uberfire/ext/editor/commons/file/exports/PdfExportPreferences.java
LeonidLapshin/appformer
2cf15393aeb922cab813938aee2c665d51ede57f
[ "Apache-2.0" ]
157
2017-09-26T17:42:08.000Z
2022-03-11T06:48:15.000Z
uberfire-extensions/uberfire-commons-editor/uberfire-commons-editor-api/src/main/java/org/uberfire/ext/editor/commons/file/exports/PdfExportPreferences.java
LeonidLapshin/appformer
2cf15393aeb922cab813938aee2c665d51ede57f
[ "Apache-2.0" ]
940
2017-03-21T08:15:36.000Z
2022-03-25T13:18:36.000Z
uberfire-extensions/uberfire-commons-editor/uberfire-commons-editor-api/src/main/java/org/uberfire/ext/editor/commons/file/exports/PdfExportPreferences.java
LeonidLapshin/appformer
2cf15393aeb922cab813938aee2c665d51ede57f
[ "Apache-2.0" ]
178
2017-03-14T10:44:31.000Z
2022-03-28T23:02:29.000Z
24.8
101
0.549628
1,002,529
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.uberfire.ext.editor.commons.file.exports; import org.jboss.errai.common.client.api.annotations.MapsTo; import org.jboss.errai.common.client.api.annotations.Portable; import static org.uberfire.preferences.shared.impl.validation.EnumValuePropertyValidator.parseString; /** * The pdf document's settings. */ @Portable public final class PdfExportPreferences { public static PdfExportPreferences create(final String orientation, final String unit, final String format) { return create(Orientation.valueOf(parseString(orientation)), Unit.valueOf(parseString(unit)), Format.valueOf(parseString(format))); } public static PdfExportPreferences create(final Orientation orientation, final Unit unit, final Format format) { return new PdfExportPreferences(orientation, unit, format); } public enum Orientation { PORTRAIT, LANDSCAPE } public enum Unit { PT, MM, CM, IN } public enum Format { A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, B0, B1, B2, B3, B4, B5, B6, B7, B8, B9, B10, C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, } private Orientation orientation; private Unit unit; private Format format; private PdfExportPreferences(final @MapsTo("orientation") Orientation orientation, final @MapsTo("unit") Unit unit, final @MapsTo("format") Format format) { this.orientation = orientation; this.unit = unit; this.format = format; } public Orientation getOrientation() { return orientation; } public void setOrientation(final Orientation orientation) { this.orientation = orientation; } public Unit getUnit() { return unit; } public void setUnit(final Unit unit) { this.unit = unit; } public Format getFormat() { return format; } public void setFormat(final Format format) { this.format = format; } }
92431d86f969e928d57d995021a97f5663a545bf
1,893
java
Java
drools-compiler/src/main/java/org/drools/rule/builder/ConditionalBranchBuilder.java
psiroky/drools
65df41d217471ee6039afd95372378f9d67a3413
[ "Apache-2.0" ]
null
null
null
drools-compiler/src/main/java/org/drools/rule/builder/ConditionalBranchBuilder.java
psiroky/drools
65df41d217471ee6039afd95372378f9d67a3413
[ "Apache-2.0" ]
null
null
null
drools-compiler/src/main/java/org/drools/rule/builder/ConditionalBranchBuilder.java
psiroky/drools
65df41d217471ee6039afd95372378f9d67a3413
[ "Apache-2.0" ]
null
null
null
46.170732
147
0.783413
1,002,530
package org.drools.rule.builder; import org.drools.lang.descr.BaseDescr; import org.drools.lang.descr.ConditionalBranchDescr; import org.drools.lang.descr.EvalDescr; import org.drools.lang.descr.NamedConsequenceDescr; import org.drools.rule.ConditionalBranch; import org.drools.rule.EvalCondition; import org.drools.rule.GroupElement; import org.drools.rule.NamedConsequence; import org.drools.rule.Pattern; import org.drools.rule.RuleConditionElement; import java.util.List; public class ConditionalBranchBuilder implements RuleConditionBuilder { public ConditionalBranch build(RuleBuildContext context, BaseDescr descr) { return build( context, descr, null ); } public ConditionalBranch build(RuleBuildContext context, BaseDescr descr, Pattern prefixPattern) { ConditionalBranchDescr conditionalBranch = (ConditionalBranchDescr) descr; RuleConditionBuilder evalBuilder = (RuleConditionBuilder) context.getDialect().getBuilder( EvalDescr.class ); EvalCondition condition = (EvalCondition) evalBuilder.build(context, conditionalBranch.getCondition(), getLastPattern(context)); NamedConsequenceBuilder namedConsequenceBuilder = (NamedConsequenceBuilder) context.getDialect().getBuilder( NamedConsequenceDescr.class ); NamedConsequence consequence = namedConsequenceBuilder.build(context, conditionalBranch.getConsequence()); ConditionalBranchDescr elseBranchDescr = conditionalBranch.getElseBranch(); return new ConditionalBranch( condition, consequence, elseBranchDescr != null ? build(context, elseBranchDescr, prefixPattern) : null ); } private Pattern getLastPattern(RuleBuildContext context) { GroupElement ge = (GroupElement)context.getBuildStack().peek(); List<RuleConditionElement> siblings = ge.getChildren(); return (Pattern) siblings.get(siblings.size()-1); } }
92431ef426afae26c466e86bdc1e14d61554ef9f
538
java
Java
prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/util/PrimeCertaintyCalculator.java
matheus-eyng/bc-java
b35d626619a564db860e59e1cda353dec8d7a4fa
[ "MIT" ]
1,604
2015-01-01T16:53:59.000Z
2022-03-31T13:21:39.000Z
prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/util/PrimeCertaintyCalculator.java
matheus-eyng/bc-java
b35d626619a564db860e59e1cda353dec8d7a4fa
[ "MIT" ]
1,015
2015-01-08T08:15:43.000Z
2022-03-31T11:05:41.000Z
prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/util/PrimeCertaintyCalculator.java
matheus-eyng/bc-java
b35d626619a564db860e59e1cda353dec8d7a4fa
[ "MIT" ]
885
2015-01-01T16:54:08.000Z
2022-03-31T22:46:25.000Z
24.454545
85
0.650558
1,002,531
package org.bouncycastle.jcajce.provider.asymmetric.util; public class PrimeCertaintyCalculator { private PrimeCertaintyCalculator() { } /** * Return the current wisdom on prime certainty requirements. * * @param keySizeInBits size of the key being generated. * @return a certainty value. */ public static int getDefaultCertainty(int keySizeInBits) { // Based on FIPS 186-4 Table C.1 return keySizeInBits <= 1024 ? 80 : (96 + 16 * ((keySizeInBits - 1) / 1024)); } }
92431f511bc3e6aa9f9fa3228c8b6c3946adf896
2,038
java
Java
src/main/java/DiscUtils/OpticalDiscSharing/DiscInfo.java
umjammer/vavi-nio-file-discutils
21abbae058932eb1c0e71793c309cdfbcdbc7aee
[ "MIT" ]
null
null
null
src/main/java/DiscUtils/OpticalDiscSharing/DiscInfo.java
umjammer/vavi-nio-file-discutils
21abbae058932eb1c0e71793c309cdfbcdbc7aee
[ "MIT" ]
3
2020-10-02T10:46:22.000Z
2021-11-12T10:49:48.000Z
src/main/java/DiscUtils/OpticalDiscSharing/DiscInfo.java
umjammer/vavi-nio-file-discutils
21abbae058932eb1c0e71793c309cdfbcdbc7aee
[ "MIT" ]
null
null
null
29.114286
78
0.694308
1,002,532
// // Copyright (c) 2008-2011, Kenneth Bell // // 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 DiscUtils.OpticalDiscSharing; /** * Information about a shared Optical Disc. */ public final class DiscInfo { /** * Gets or sets the name of the disc (unique within an instance of * OpticalDiscService). */ private String _name; public String getName() { return _name; } public void setName(String value) { _name = value; } /** * Gets or sets the displayable volume label for the disc. */ private String _volumeLabel; public String getVolumeLabel() { return _volumeLabel; } public void setVolumeLabel(String value) { _volumeLabel = value; } /** * Gets or sets the volume type of the disc. */ private String _volumeType; public String getVolumeType() { return _volumeType; } public void setVolumeType(String value) { _volumeType = value; } }
92431f7eda8b0a40dea5814722e743deca07d305
1,292
java
Java
algorithms/java/src/main/java/org/jessenpan/leetcode/dsu/S685RedundantConnectionII.java
JessenPan/leetcode-java
7181adeb0a9f43a3ebb3d95f0ccf51e8ec99e1bf
[ "Apache-2.0" ]
6
2019-05-04T09:02:41.000Z
2022-01-09T00:26:34.000Z
algorithms/java/src/main/java/org/jessenpan/leetcode/dsu/S685RedundantConnectionII.java
JessenPan/leetcode-java
7181adeb0a9f43a3ebb3d95f0ccf51e8ec99e1bf
[ "Apache-2.0" ]
null
null
null
algorithms/java/src/main/java/org/jessenpan/leetcode/dsu/S685RedundantConnectionII.java
JessenPan/leetcode-java
7181adeb0a9f43a3ebb3d95f0ccf51e8ec99e1bf
[ "Apache-2.0" ]
1
2019-11-06T08:14:24.000Z
2019-11-06T08:14:24.000Z
22.666667
66
0.427245
1,002,533
package org.jessenpan.leetcode.dsu; /** * @author jessenpan * tag:disjointset */ public class S685RedundantConnectionII { private int[] parent = null; private int find(int u) { while (u != parent[u]) { //压缩路径 parent[u] = parent[parent[u]]; u = parent[u]; } return u; } public int[] findRedundantDirectedConnection(int[][] edges) { int[] backedge = new int[2];//存放最后一个后向边(环) int[] pending = new int[2];//存放最后一个重复的父节点 parent = new int[edges.length + 1]; for (int[] edge : edges) { if (parent[edge[1]] == 0) {//合并有向边 parent[edge[1]] = edge[0]; } else {//有重复的父节点 pending = new int[] { edge[0], edge[1] }; backedge = new int[] { parent[edge[1]], edge[1] }; edge[1] = 0; } } for (int i = 0; i <= edges.length; i++) { parent[i] = i; } for (int[] e : edges) { if (e[1] == 0) { continue; } //判断有没有环 if (find(e[0]) == e[1]) { return backedge[0] != 0 ? backedge : e; } parent[e[1]] = e[0]; } return pending; } }
92431fa7f8ec6a975611fa118a4a5fc4b7c5ea25
15,112
java
Java
swing/src/main/java/global/namespace/truelicense/swing/DisplayPanel.java
christian-schlichtherle/truelicense
242568d8a419495c9de122ff42d17a37a3971790
[ "Apache-2.0" ]
156
2017-09-28T07:06:03.000Z
2022-03-28T07:58:27.000Z
swing/src/main/java/global/namespace/truelicense/swing/DisplayPanel.java
Vilasdeboas/truelicense
313cf54b4cb4b52e4b8ec033fecdccce3c7bb0e0
[ "Apache-2.0" ]
25
2018-08-15T07:34:49.000Z
2022-03-30T10:48:04.000Z
swing/src/main/java/global/namespace/truelicense/swing/DisplayPanel.java
Vilasdeboas/truelicense
313cf54b4cb4b52e4b8ec033fecdccce3c7bb0e0
[ "Apache-2.0" ]
46
2017-09-28T07:06:09.000Z
2022-03-29T12:49:15.000Z
48.435897
227
0.716053
1,002,534
/* * Copyright (C) 2005 - 2019 Schlichtherle IT Services. * All rights reserved. Use is subject to license terms. */ package global.namespace.truelicense.swing; import global.namespace.truelicense.api.License; import global.namespace.truelicense.ui.LicenseWizardMessage; import global.namespace.truelicense.api.LicenseValidationException; import javax.swing.*; import java.util.Date; final class DisplayPanel extends LicensePanel { private static final long serialVersionUID = 1L; private License license; DisplayPanel(final LicenseManagementWizard wizard) { super(wizard); initComponents(); } /** Updates the view with the contents of the license and verifies it. */ @Override public void onAfterStateSwitch() { assert SwingUtilities.isEventDispatchThread(); assert isVisible(); try { license = manager().load(); onLicenseChange(); manager().verify(); } catch (final Exception failure) { JOptionPane.showMessageDialog( this, failure instanceof LicenseValidationException ? failure.getLocalizedMessage() : format(LicenseWizardMessage.display_failure), format(LicenseWizardMessage.failure_title), JOptionPane.ERROR_MESSAGE); } } private void onLicenseChange() { if (null == license) return; subjectComponent.setText(nonNullOrEmptyString(license.getSubject())); holderComponent.setText(nonNullOrEmptyString(license.getHolder())); issuerComponent.setText(nonNullOrEmptyString(license.getIssuer())); issuedComponent.setText(format(license.getIssued())); notBeforeComponent.setText(format(license.getNotBefore())); notAfterComponent.setText(format(license.getNotAfter())); consumerComponent.setText(LicenseWizardMessage.display_consumerFormat.format( subject(), license.getConsumerType(), license.getConsumerAmount()).toString()); infoComponent.setText(nonNullOrEmptyString(license.getInfo())); } private static String nonNullOrEmptyString(Object obj) { return null != obj ? obj.toString() : ""; } private String format(Date date) { return LicenseWizardMessage.display_dateTimeFormat(subject(), date); } /** 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. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; javax.swing.JLabel subjectLabel = new javax.swing.JLabel(); subjectComponent = new javax.swing.JTextArea(); javax.swing.JLabel holderLabel = new javax.swing.JLabel(); javax.swing.JScrollPane holderScrollPane = new javax.swing.JScrollPane(); holderComponent = new javax.swing.JTextArea(); javax.swing.JLabel issuerLabel = new javax.swing.JLabel(); javax.swing.JScrollPane issuerScrollPane = new javax.swing.JScrollPane(); issuerComponent = new javax.swing.JTextArea(); javax.swing.JLabel issuedLabel = new javax.swing.JLabel(); issuedComponent = new javax.swing.JTextArea(); javax.swing.JLabel notBeforeLabel = new javax.swing.JLabel(); notBeforeComponent = new javax.swing.JTextArea(); javax.swing.JLabel notAfterLabel = new javax.swing.JLabel(); notAfterComponent = new javax.swing.JTextArea(); javax.swing.JLabel consumerLabel = new javax.swing.JLabel(); consumerComponent = new javax.swing.JTextArea(); javax.swing.JLabel infoLabel = new javax.swing.JLabel(); javax.swing.JScrollPane infoScrollPane = new javax.swing.JScrollPane(); infoComponent = new javax.swing.JTextArea(); setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createTitledBorder(format(LicenseWizardMessage.display_title)), javax.swing.BorderFactory.createEmptyBorder(10, 10, 10, 10))); // NOI18N setName(DisplayPanel.class.getSimpleName()); setLayout(new java.awt.GridBagLayout()); subjectLabel.setLabelFor(subjectComponent); subjectLabel.setText(format(LicenseWizardMessage.display_subject)); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.ipadx = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.BASELINE_TRAILING; add(subjectLabel, gridBagConstraints); subjectComponent.setEditable(false); subjectComponent.setFont(getFont()); subjectComponent.setBorder(javax.swing.BorderFactory.createEtchedBorder()); subjectComponent.setName(LicenseWizardMessage.display_subject.name()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.BASELINE_LEADING; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(subjectComponent, gridBagConstraints); holderLabel.setLabelFor(holderComponent); holderLabel.setText(format(LicenseWizardMessage.display_holder)); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.ipadx = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.BASELINE_TRAILING; add(holderLabel, gridBagConstraints); holderScrollPane.setBorder(javax.swing.BorderFactory.createEtchedBorder()); holderScrollPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); holderScrollPane.setPreferredSize(new java.awt.Dimension(300, 65)); holderComponent.setEditable(false); holderComponent.setFont(getFont()); holderComponent.setLineWrap(true); holderComponent.setWrapStyleWord(true); holderComponent.setBorder(null); holderComponent.setName(LicenseWizardMessage.display_holder.name()); holderScrollPane.setViewportView(holderComponent); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.BASELINE_LEADING; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(holderScrollPane, gridBagConstraints); issuerLabel.setLabelFor(issuerComponent); issuerLabel.setText(format(LicenseWizardMessage.display_issuer)); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.ipadx = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.BASELINE_TRAILING; add(issuerLabel, gridBagConstraints); issuerScrollPane.setBorder(javax.swing.BorderFactory.createEtchedBorder()); issuerScrollPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); issuerScrollPane.setPreferredSize(new java.awt.Dimension(300, 65)); issuerComponent.setEditable(false); issuerComponent.setFont(getFont()); issuerComponent.setLineWrap(true); issuerComponent.setWrapStyleWord(true); issuerComponent.setBorder(null); issuerComponent.setName(LicenseWizardMessage.display_issuer.name()); issuerScrollPane.setViewportView(issuerComponent); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.BASELINE_LEADING; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(issuerScrollPane, gridBagConstraints); issuedLabel.setLabelFor(issuedComponent); issuedLabel.setText(format(LicenseWizardMessage.display_issued)); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.ipadx = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.BASELINE_TRAILING; add(issuedLabel, gridBagConstraints); issuedComponent.setEditable(false); issuedComponent.setFont(getFont()); issuedComponent.setBorder(javax.swing.BorderFactory.createEtchedBorder()); issuedComponent.setName(LicenseWizardMessage.display_issued.name()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.BASELINE_LEADING; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(issuedComponent, gridBagConstraints); notBeforeLabel.setLabelFor(notBeforeComponent); notBeforeLabel.setText(format(LicenseWizardMessage.display_notBefore)); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.ipadx = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.BASELINE_TRAILING; add(notBeforeLabel, gridBagConstraints); notBeforeComponent.setEditable(false); notBeforeComponent.setFont(getFont()); notBeforeComponent.setBorder(javax.swing.BorderFactory.createEtchedBorder()); notBeforeComponent.setName(LicenseWizardMessage.display_notBefore.name()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.BASELINE_LEADING; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(notBeforeComponent, gridBagConstraints); notAfterLabel.setLabelFor(notAfterComponent); notAfterLabel.setText(format(LicenseWizardMessage.display_notAfter)); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.ipadx = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.BASELINE_TRAILING; add(notAfterLabel, gridBagConstraints); notAfterComponent.setEditable(false); notAfterComponent.setFont(getFont()); notAfterComponent.setBorder(javax.swing.BorderFactory.createEtchedBorder()); notAfterComponent.setName(LicenseWizardMessage.display_notAfter.name()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.BASELINE_LEADING; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(notAfterComponent, gridBagConstraints); consumerLabel.setLabelFor(consumerComponent); consumerLabel.setText(format(LicenseWizardMessage.display_consumer)); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.ipadx = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.BASELINE_TRAILING; add(consumerLabel, gridBagConstraints); consumerComponent.setEditable(false); consumerComponent.setFont(getFont()); consumerComponent.setBorder(javax.swing.BorderFactory.createEtchedBorder()); consumerComponent.setName(LicenseWizardMessage.display_consumer.name()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 6; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.BASELINE_LEADING; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(consumerComponent, gridBagConstraints); infoLabel.setLabelFor(infoComponent); infoLabel.setText(format(LicenseWizardMessage.display_info)); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 7; gridBagConstraints.ipadx = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.BASELINE_TRAILING; add(infoLabel, gridBagConstraints); infoScrollPane.setBorder(javax.swing.BorderFactory.createEtchedBorder()); infoScrollPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); infoScrollPane.setPreferredSize(new java.awt.Dimension(300, 65)); infoComponent.setEditable(false); infoComponent.setFont(getFont()); infoComponent.setLineWrap(true); infoComponent.setWrapStyleWord(true); infoComponent.setBorder(null); infoComponent.setName(LicenseWizardMessage.display_info.name()); infoScrollPane.setViewportView(infoComponent); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 7; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.BASELINE_LEADING; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(infoScrollPane, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextArea consumerComponent; private javax.swing.JTextArea holderComponent; private javax.swing.JTextArea infoComponent; private javax.swing.JTextArea issuedComponent; private javax.swing.JTextArea issuerComponent; private javax.swing.JTextArea notAfterComponent; private javax.swing.JTextArea notBeforeComponent; private javax.swing.JTextArea subjectComponent; // End of variables declaration//GEN-END:variables }
92431fd05de821427dbe9018086fb80fbecf404a
556
java
Java
java/src/main/java/codingdojo/ContentTempFileHelper.java
emilybache/Cloud-Migration-Refactoring-Kata
e562a249df6a92270eaf2bfea08384640e5263fe
[ "MIT" ]
3
2019-06-17T14:47:05.000Z
2019-06-19T11:12:01.000Z
java/src/main/java/codingdojo/ContentTempFileHelper.java
HoucemNaffati/Cloud-Migration-Refactoring-Kata
e562a249df6a92270eaf2bfea08384640e5263fe
[ "MIT" ]
null
null
null
java/src/main/java/codingdojo/ContentTempFileHelper.java
HoucemNaffati/Cloud-Migration-Refactoring-Kata
e562a249df6a92270eaf2bfea08384640e5263fe
[ "MIT" ]
3
2020-03-13T08:12:26.000Z
2021-05-19T22:33:07.000Z
22.24
70
0.633094
1,002,535
package codingdojo; import java.io.File; import java.nio.file.Path; public class ContentTempFileHelper { Path tempDir; public ContentTempFileHelper() { this(Path.of(System.getProperty("user.dir"),"content_cache")); } public ContentTempFileHelper(Path tempDir) { this.tempDir = tempDir; } public File getFile(Content content) { File result = null; if (content.getFilename() != null) { result = tempDir.resolve(content.getFilename()).toFile(); } return result; } }
92432093ec17c303e066a05c3da80413894b9ee3
1,894
java
Java
src/main/java/com/leprofi/bwlevels/utils/logger/Color.java
LeNinjaHD/MBedwars-Levels
b151b406a50938613e3e24edebbc7783367cc2a8
[ "MIT" ]
1
2021-09-02T16:16:56.000Z
2021-09-02T16:16:56.000Z
src/main/java/com/leprofi/bwlevels/utils/logger/Color.java
LeNinjaHD/MBedwars-Levels
b151b406a50938613e3e24edebbc7783367cc2a8
[ "MIT" ]
null
null
null
src/main/java/com/leprofi/bwlevels/utils/logger/Color.java
LeNinjaHD/MBedwars-Levels
b151b406a50938613e3e24edebbc7783367cc2a8
[ "MIT" ]
null
null
null
46.195122
74
0.651531
1,002,536
package com.leprofi.bwlevels.utils.logger; /* * Class Created by LeNinjaHD at 02.09.2021 */ public class Color { // Reset public static final String RESET = "\033[0m"; // Text Reset // Regular Colors public static final String BLACK = "\033[0;30m"; // BLACK public static final String RED = "\033[0;31m"; // RED public static final String GREEN = "\033[0;32m"; // GREEN public static final String YELLOW = "\033[0;33m"; // YELLOW public static final String BLUE = "\033[0;34m"; // BLUE public static final String PURPLE = "\033[0;35m"; // PURPLE public static final String CYAN = "\033[0;36m"; // CYAN public static final String WHITE = "\033[0;37m"; // WHITE // Bold public static final String BLACK_BOLD = "\033[1;30m"; // BLACK public static final String RED_BOLD = "\033[1;31m"; // RED public static final String GREEN_BOLD = "\033[1;32m"; // GREEN public static final String YELLOW_BOLD = "\033[1;33m"; // YELLOW public static final String BLUE_BOLD = "\033[1;34m"; // BLUE public static final String PURPLE_BOLD = "\033[1;35m"; // PURPLE public static final String CYAN_BOLD = "\033[1;36m"; // CYAN public static final String WHITE_BOLD = "\033[1;37m"; // WHITE // Underline public static final String BLACK_UNDERLINED = "\033[4;30m"; // BLACK public static final String RED_UNDERLINED = "\033[4;31m"; // RED public static final String GREEN_UNDERLINED = "\033[4;32m"; // GREEN public static final String YELLOW_UNDERLINED = "\033[4;33m"; // YELLOW public static final String BLUE_UNDERLINED = "\033[4;34m"; // BLUE public static final String PURPLE_UNDERLINED = "\033[4;35m"; // PURPLE public static final String CYAN_UNDERLINED = "\033[4;36m"; // CYAN public static final String WHITE_UNDERLINED = "\033[4;37m"; // WHITE }
924320efb99438d3dbb52d1f883c039c7032e4be
1,807
java
Java
src/game/components/AABBComponent.java
notdezzi/Ninjas-World
bb2e66db54c24ff19d3688eeb6bd55b61447681a
[ "MIT" ]
null
null
null
src/game/components/AABBComponent.java
notdezzi/Ninjas-World
bb2e66db54c24ff19d3688eeb6bd55b61447681a
[ "MIT" ]
null
null
null
src/game/components/AABBComponent.java
notdezzi/Ninjas-World
bb2e66db54c24ff19d3688eeb6bd55b61447681a
[ "MIT" ]
null
null
null
22.036585
107
0.702822
1,002,537
package game.components; import engine.GameContainer; import engine.Renderer; import game.GameManager; import game.GameObject; import game.Physics; public class AABBComponent extends Component { private GameObject parent; private int centerX, centerY; private int halfWidth, halfHeight; public AABBComponent(GameObject parent) { this.parent = parent; this.tag = "aabb"; } @Override public void update(GameContainer gc, GameManager gm, float dt) { centerX = (int) (parent.getPositionX() + (parent.getWidth() / 2)); centerY = (int) (parent.getPositionY() + (parent.getHeight() / 2) + (parent.getPaddingTop() / 2)); halfWidth = parent.getWidth() - parent.getPadding(); halfHeight = parent.getHeight() - parent.getPaddingTop() / 2; Physics.addAABBComponent(this); } @Override public void render(GameContainer gc, Renderer r) { int positionX = (int) parent.getPositionX(); int positionY = (int) parent.getPositionY(); // r.drawRect(parent.getWidth(), parent.getHeight(), positionX, positionY, 0xffffffff); // r.drawRect(halfHeight * 2, halfWidth * 2, centerX - halfWidth, centerY - halfHeight, 0xffffffff); } public GameObject getParent() { return parent; } public void setParent(GameObject parent) { this.parent = parent; } public int getCenterX() { return centerX; } public void setCenterX(int centerX) { this.centerX = centerX; } public int getCenterY() { return centerY; } public void setCenterY(int centerY) { this.centerY = centerY; } public int getHalfWidth() { return halfWidth; } public void setHalfWidth(int halfWidth) { this.halfWidth = halfWidth; } public int getHalfHeight() { return halfHeight; } public void setHalfHeight(int halfHeight) { this.halfHeight = halfHeight; } }
9243210c98f04f0a7ec5863e85ca3d64a6370125
104
java
Java
src/main/java/org/motechproject/mots/domain/enums/CallFlowElementType.java
DominikaHatala/mots
eda5f723fda35863d2a8d07e8894befbddb373b5
[ "Apache-2.0" ]
3
2017-10-23T21:15:27.000Z
2018-02-16T12:20:03.000Z
src/main/java/org/motechproject/mots/domain/enums/CallFlowElementType.java
DominikaHatala/mots
eda5f723fda35863d2a8d07e8894befbddb373b5
[ "Apache-2.0" ]
44
2017-11-08T11:13:55.000Z
2022-02-12T04:02:22.000Z
src/main/java/org/motechproject/mots/domain/enums/CallFlowElementType.java
DominikaHatala/mots
eda5f723fda35863d2a8d07e8894befbddb373b5
[ "Apache-2.0" ]
5
2017-10-06T17:17:42.000Z
2020-10-05T23:32:00.000Z
14.857143
44
0.788462
1,002,538
package org.motechproject.mots.domain.enums; public enum CallFlowElementType { MESSAGE, QUESTION }
9243217437460ac1cccd8b2e954b9285f7513622
3,892
java
Java
Dianping_server/dianping/src/com/dianping/dao/impl/UserDaoImpl.java
uniquefrog/MaiZiProject
a0d467b25712b2b0a2fcf0227172f02e39a80a6f
[ "Apache-2.0" ]
1
2019-07-19T00:28:30.000Z
2019-07-19T00:28:30.000Z
Dianping_server/dianping/src/com/dianping/dao/impl/UserDaoImpl.java
uniquefrog/MaiZiProject
a0d467b25712b2b0a2fcf0227172f02e39a80a6f
[ "Apache-2.0" ]
null
null
null
Dianping_server/dianping/src/com/dianping/dao/impl/UserDaoImpl.java
uniquefrog/MaiZiProject
a0d467b25712b2b0a2fcf0227172f02e39a80a6f
[ "Apache-2.0" ]
null
null
null
36.373832
111
0.635663
1,002,539
package com.dianping.dao.impl; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import com.dianping.dao.UserDao; import com.dianping.enity.User; public class UserDaoImpl extends BaseDao implements UserDao { public User register(String name, String pwd) { Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { connection = getConn(); statement = connection.createStatement(); String sqlForCheck = "select * from user where user_name = '"+name+"'"; resultSet = statement.executeQuery(sqlForCheck); if(resultSet.next()){ return null; } String sqlForInsert = "insert into user (user_name,user_login_pwd) values('"+name+"','"+pwd+"')"; statement.execute(sqlForInsert); resultSet = statement.executeQuery(sqlForCheck); if(resultSet.next()){ User user = new User(); user.setId(resultSet.getString("user_id")); user.setName(resultSet.getString("user_name")); user.setLoginPwd(resultSet.getString("user_login_pwd")); user.setPayPwd(resultSet.getString("user_pay_pwd")); user.setTel(resultSet.getString("user_tel")); return user; } } catch (Exception e) { e.printStackTrace(); }finally{ close(resultSet, statement, connection); } return null; } public User login(String name, String pwd) { Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { connection = getConn(); statement = connection.createStatement(); String sqlForCheck = "select * from user where user_name = '"+name+"' and user_login_pwd = '"+pwd+"'"; resultSet = statement.executeQuery(sqlForCheck); if(resultSet.next()){ User user = new User(); user.setId(resultSet.getString("user_id")); user.setName(resultSet.getString("user_name")); user.setLoginPwd(resultSet.getString("user_login_pwd")); user.setPayPwd(resultSet.getString("user_pay_pwd")); user.setTel(resultSet.getString("user_tel")); return user; } } catch (Exception e) { e.printStackTrace(); }finally{ close(resultSet, statement, connection); } return null; } public User social(String name, String pwd) { Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { connection = getConn(); statement = connection.createStatement(); String sqlForCheck = "select * from user where user_name = '"+name+"' and user_login_pwd = '"+pwd+"'"; resultSet = statement.executeQuery(sqlForCheck); if(resultSet.next()){ User user = new User(); user.setId(resultSet.getString("user_id")); user.setName(resultSet.getString("user_name")); user.setLoginPwd(resultSet.getString("user_login_pwd")); user.setPayPwd(resultSet.getString("user_pay_pwd")); user.setTel(resultSet.getString("user_tel")); return user; } String sqlForInsert = "insert into user (user_name,user_login_pwd) values('"+name+"','"+pwd+"')"; statement.execute(sqlForInsert); resultSet = statement.executeQuery(sqlForCheck); if(resultSet.next()){ User user = new User(); user.setId(resultSet.getString("user_id")); user.setName(resultSet.getString("user_name")); user.setLoginPwd(resultSet.getString("user_login_pwd")); user.setPayPwd(resultSet.getString("user_pay_pwd")); user.setTel(resultSet.getString("user_tel")); return user; } } catch (Exception e) { e.printStackTrace(); }finally{ close(resultSet, statement, connection); } return null; }}
9243238be30dd7780addd47cb347c1034d4ffaf8
2,421
java
Java
sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/SpatialIndex.java
yiliuTo/azure-sdk-for-java
4536b6e99ded1b2b77f79bc2c31f42566c97b704
[ "MIT" ]
1,350
2015-01-17T05:22:05.000Z
2022-03-29T21:00:37.000Z
sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/SpatialIndex.java
yiliuTo/azure-sdk-for-java
4536b6e99ded1b2b77f79bc2c31f42566c97b704
[ "MIT" ]
16,834
2015-01-07T02:19:09.000Z
2022-03-31T23:29:10.000Z
sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/SpatialIndex.java
yiliuTo/azure-sdk-for-java
4536b6e99ded1b2b77f79bc2c31f42566c97b704
[ "MIT" ]
1,586
2015-01-02T01:50:28.000Z
2022-03-31T11:25:34.000Z
31.441558
120
0.651797
1,002,540
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.cosmos.implementation; import com.azure.cosmos.implementation.apachecommons.lang.StringUtils; import com.fasterxml.jackson.databind.node.ObjectNode; /** * Represents a spatial index in the Azure Cosmos DB database service. */ public final class SpatialIndex extends Index { /** * Initializes a new instance of the SpatialIndex class. * <p> * Here is an example to instantiate SpatialIndex class passing in the DataType * <pre>{@code SpatialIndex spatialIndex = new SpatialIndex(DataType.POINT);}</pre> * * @param dataType specifies the target data type for the index path specification. */ SpatialIndex(DataType dataType) { super(IndexKind.SPATIAL); this.setDataType(dataType); } /** * Initializes a new instance of the SpatialIndex class. * * @param jsonString the json string that represents the index. */ public SpatialIndex(String jsonString) { super(jsonString, IndexKind.SPATIAL); if (this.getDataType() == null) { throw new IllegalArgumentException("The jsonString doesn't contain a valid 'dataType'."); } } /** * Initializes a new instance of the SpatialIndex class. * * @param objectNode the object node that represents the index. */ SpatialIndex(ObjectNode objectNode) { super(objectNode, IndexKind.SPATIAL); if (this.getDataType() == null) { throw new IllegalArgumentException("The jsonString doesn't contain a valid 'dataType'."); } } /** * Gets data type. * * @return the data type. */ public DataType getDataType() { DataType result = null; try { result = DataType.valueOf(StringUtils.upperCase(super.getString(Constants.Properties.DATA_TYPE))); } catch (IllegalArgumentException e) { super.getLogger().warn("INVALID index dataType value {}.", super.getString(Constants.Properties.DATA_TYPE)); } return result; } /** * Sets data type. * * @param dataType the data type. * @return the SpatialIndex. */ public SpatialIndex setDataType(DataType dataType) { super.set(Constants.Properties.DATA_TYPE, dataType.toString()); return this; } }
9243242c545ca3b5fe315b90163074877b57375e
6,074
java
Java
Kazak-Android/app/src/main/java/io/kazak/schedule/ScheduleActivity.java
novoda/kazak-android
a33a0271ee8235fd23f90ad33b818ce4d3b7c856
[ "MIT" ]
null
null
null
Kazak-Android/app/src/main/java/io/kazak/schedule/ScheduleActivity.java
novoda/kazak-android
a33a0271ee8235fd23f90ad33b818ce4d3b7c856
[ "MIT" ]
null
null
null
Kazak-Android/app/src/main/java/io/kazak/schedule/ScheduleActivity.java
novoda/kazak-android
a33a0271ee8235fd23f90ad33b818ce4d3b7c856
[ "MIT" ]
null
null
null
29.201923
107
0.614257
1,002,541
package io.kazak.schedule; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.Snackbar; import android.view.View; import javax.inject.Inject; import java.util.List; import io.kazak.KazakApplication; import io.kazak.NavigationDrawerActivity; import io.kazak.R; import io.kazak.base.DeveloperError; import io.kazak.model.Id; import io.kazak.repository.DataRepository; import io.kazak.repository.event.SyncEvent; import io.kazak.schedule.view.ScheduleEventView; import io.kazak.schedule.view.table.ScheduleTableAdapter; import io.kazak.schedule.view.table.ScheduleTableView; import io.kazak.schedule.view.table.base.RulerView; import rx.Observer; import rx.android.schedulers.AndroidSchedulers; import rx.subscriptions.CompositeSubscription; public class ScheduleActivity extends NavigationDrawerActivity implements ScheduleEventView.Listener { private final CompositeSubscription subscriptions; @Inject DataRepository dataRepository; private View contentRootView; private ScheduleTableView scheduleView; public ScheduleActivity() { subscriptions = new CompositeSubscription(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); KazakApplication.injector().inject(this); setContentView(R.layout.activity_schedule); contentRootView = findViewById(R.id.content_root); scheduleView = (ScheduleTableView) findViewById(R.id.schedule); setupScheduleView(); subscribeToSchedule(); } private void setupScheduleView() { scheduleView.setListener(this); scheduleView.setRoomsRuler((RulerView) findViewById(R.id.rooms_ruler)); scheduleView.setTimeRuler((RulerView) findViewById(R.id.time_ruler)); } private void subscribeToSchedule() { subscriptions.add( dataRepository.getSchedule() .map(ScheduleActivityFunctions.createAdapterData(scheduleView)) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new ScheduleObserver()) ); subscriptions.add( dataRepository.getFavoriteIds() .observeOn(AndroidSchedulers.mainThread()) .subscribe(new FavoritesObserver()) ); subscriptions.add( dataRepository.getScheduleSyncEvents() .observeOn(AndroidSchedulers.mainThread()) .subscribe(new SyncEventObserver()) ); } @Override protected void onAppbarNavigationClick() { openNavigationDrawer(); } @Override protected void onDestroy() { super.onDestroy(); subscriptions.clear(); } private void updateWith(@NonNull ScheduleTableAdapter.Data data) { scheduleView.updateWith(data); } private void updateWith(@NonNull List<? extends Id> favorites) { scheduleView.updateWith(favorites); } @Override public void onTalkClicked(Id talkId) { navigate().toSessionDetails(talkId); } @SuppressWarnings("ThrowableResultOfMethodCallIgnored") private void handleSyncError(SyncEvent syncEvent) { Throwable error = syncEvent.getError(); if (error instanceof DeveloperError) { showSyncDeveloperError(error); } else { showSyncError(); } } private void showSyncDeveloperError(Throwable error) { String message = getString(R.string.developer_error_loading_schedule, error.getMessage()); Snackbar.make(contentRootView, message, Snackbar.LENGTH_INDEFINITE) .show(); } private void showSyncError() { Snackbar.make(contentRootView, R.string.error_loading_schedule, Snackbar.LENGTH_LONG) .setAction( R.string.action_retry, new View.OnClickListener() { @Override public void onClick(View v) { subscribeToSchedule(); } } ) .show(); } @Override protected int getNavigationDrawerMenuIdForThisActivity() { return R.id.menu_nav_schedule; } private class ScheduleObserver implements Observer<ScheduleTableAdapter.Data> { @Override public void onCompleted() { // No-op } @Override public void onError(Throwable e) { throw new IllegalStateException(e); } @Override public void onNext(ScheduleTableAdapter.Data data) { updateWith(data); } } private class FavoritesObserver implements Observer<List<? extends Id>> { @Override public void onCompleted() { // No-op } @Override public void onError(Throwable e) { throw new IllegalStateException(e); } @Override public void onNext(List<? extends Id> favorites) { updateWith(favorites); } } private class SyncEventObserver implements Observer<SyncEvent> { @Override public void onCompleted() { // Ignore } @Override public void onError(Throwable e) { throw new IllegalStateException(e); } @Override public void onNext(SyncEvent syncEvent) { switch (syncEvent.getState()) { case ERROR: handleSyncError(syncEvent); break; case IDLE: //Display empty screen if no data break; case LOADING: //Display loading screen break; default: throw new DeveloperError("Sync event '" + syncEvent.getState() + "' is not supported"); } } } }
92432491c3ce12c284c9a704a887192592d24442
366
java
Java
soluciones/coche/src/main/java/org/example/App.java
JeremyRamos01/Programacion-04-Ejercicios-2021-2022
d547e32a91fa913f516e1b72be8293d93c482e10
[ "MIT" ]
10
2022-01-24T09:03:25.000Z
2022-03-25T10:57:19.000Z
soluciones/coche/src/main/java/org/example/App.java
idanirf/Programacion-04-Ejercicios-2021-2022
0ad760c516c8d74bf417539a7ce9bc420d69baa4
[ "MIT" ]
8
2022-02-04T21:19:14.000Z
2022-02-22T17:50:26.000Z
soluciones/coche/src/main/java/org/example/App.java
idanirf/Programacion-04-Ejercicios-2021-2022
0ad760c516c8d74bf417539a7ce9bc420d69baa4
[ "MIT" ]
13
2022-01-24T13:22:30.000Z
2022-03-07T20:57:19.000Z
15.25
49
0.628415
1,002,542
package org.example; import org.example.Models.Coche; import org.example.Utils.IotHK; import java.util.Locale; // STOPSHIP: 01/02/2022 public class App { public static void main( String[] args ) { IotHK sc =new IotHK(); Coche coche = new Coche("0616cnd"); System.out.println(coche); coche.funiconamiento(); } }
924324a9f02afc794ab44eebfd20ac0b1c470a3e
1,314
java
Java
galaxy-emq-client/src/main/java/com/xiaomi/infra/galaxy/emq/client/EMQClient.java
XiaoMi/galaxy-sdk-java
97952feb934e2f64e5b1a14cfe47b7ff566b9637
[ "Apache-2.0" ]
60
2015-01-19T09:52:20.000Z
2022-02-10T11:08:43.000Z
galaxy-emq-client/src/main/java/com/xiaomi/infra/galaxy/emq/client/EMQClient.java
szknb/galaxy-sdk-java
bf65a64777e9294b88141d651e11e4e7d6c112b1
[ "Apache-2.0" ]
3
2015-05-19T01:50:52.000Z
2021-12-16T07:33:35.000Z
galaxy-emq-client/src/main/java/com/xiaomi/infra/galaxy/emq/client/EMQClient.java
szknb/galaxy-sdk-java
bf65a64777e9294b88141d651e11e4e7d6c112b1
[ "Apache-2.0" ]
52
2015-11-24T16:36:47.000Z
2021-11-29T06:36:13.000Z
28.06383
75
0.702805
1,002,543
package com.xiaomi.infra.galaxy.emq.client; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Arrays; /** * Copyright 2015, Xiaomi. * All rights reserved. * Author: [email protected] */ public class EMQClient { private static class EMQClientHandler<T> implements InvocationHandler { private final Object instance; public EMQClientHandler(Class<T> interfaceClass, Object instance) { this.instance = instance; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (!Arrays.asList(Object.class.getMethods()).contains(method)) { EMQRequestCheckUtils.checkRequest(args); } try { return method.invoke(instance, args); } catch (InvocationTargetException e) { throw e.getCause(); } } } /** * Create client wrapper which validate parameters of client. */ @SuppressWarnings("unchecked") public static <T> T getClient(Class<T> interfaceClass, Object instance) { return (T) Proxy.newProxyInstance(EMQClient.class.getClassLoader(), new Class[]{interfaceClass}, new EMQClientHandler(interfaceClass, instance)); } }
92432521333a5a6a716244b62ebc0c1a67c2ee0a
368
java
Java
sources/com/google/android/gms/internal/ads/zzcdf.java
tusharchoudhary0003/Custom-Football-Game
47283462b2066ad5c53b3c901182e7ae62a34fc8
[ "MIT" ]
1
2019-10-01T11:34:10.000Z
2019-10-01T11:34:10.000Z
sources/com/google/android/gms/internal/ads/zzcdf.java
tusharchoudhary0003/Custom-Football-Game
47283462b2066ad5c53b3c901182e7ae62a34fc8
[ "MIT" ]
null
null
null
sources/com/google/android/gms/internal/ads/zzcdf.java
tusharchoudhary0003/Custom-Football-Game
47283462b2066ad5c53b3c901182e7ae62a34fc8
[ "MIT" ]
1
2020-05-26T05:10:33.000Z
2020-05-26T05:10:33.000Z
23
61
0.657609
1,002,544
package com.google.android.gms.internal.ads; public abstract class zzcdf { /* renamed from: a */ public abstract zzbrm mo28258a(); /* renamed from: a */ public abstract zzcdc mo28259a(zzbpr zzbpr, zzcdd zzcdd); /* renamed from: b */ public abstract zzbbh<zzcdb> mo28260b(); /* renamed from: c */ public abstract zzbss mo28261c(); }
9243252f0395089403c23bd33c5c0393844f786a
5,981
java
Java
support/cas-server-support-oidc-core-api/src/main/java/org/apereo/cas/oidc/jwks/OidcDefaultJsonWebKeystoreCacheLoader.java
doddi/cas
e57e32c2cfe2b0fef65ffac3987d5dc5385a5493
[ "Apache-2.0" ]
4
2015-10-31T14:57:03.000Z
2020-11-16T01:39:42.000Z
support/cas-server-support-oidc-core-api/src/main/java/org/apereo/cas/oidc/jwks/OidcDefaultJsonWebKeystoreCacheLoader.java
doddi/cas
e57e32c2cfe2b0fef65ffac3987d5dc5385a5493
[ "Apache-2.0" ]
12
2020-07-03T06:06:14.000Z
2022-01-27T00:37:19.000Z
support/cas-server-support-oidc-core-api/src/main/java/org/apereo/cas/oidc/jwks/OidcDefaultJsonWebKeystoreCacheLoader.java
doddi/cas
e57e32c2cfe2b0fef65ffac3987d5dc5385a5493
[ "Apache-2.0" ]
1
2016-06-22T00:54:09.000Z
2016-06-22T00:54:09.000Z
37.85443
120
0.621802
1,002,545
package org.apereo.cas.oidc.jwks; import org.apereo.cas.oidc.jwks.generator.OidcJsonWebKeystoreGeneratorService; import org.apereo.cas.util.LoggingUtils; import com.github.benmanes.caffeine.cache.CacheLoader; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.apache.commons.lang3.StringUtils; import org.jose4j.jwk.JsonWebKeySet; import org.jose4j.jwk.PublicJsonWebKey; import org.springframework.core.io.Resource; import java.util.Optional; /** * This is {@link OidcDefaultJsonWebKeystoreCacheLoader}. * Only attempts to cache the default CAS keystore. * * @author Misagh Moayyed * @since 5.1.0 */ @Slf4j @RequiredArgsConstructor @Getter public class OidcDefaultJsonWebKeystoreCacheLoader implements CacheLoader<String, Optional<PublicJsonWebKey>> { private final OidcJsonWebKeystoreGeneratorService oidcJsonWebKeystoreGeneratorService; @Override public Optional<PublicJsonWebKey> load(final String issuer) { val jwks = buildJsonWebKeySet(); if (jwks.isEmpty()) { LOGGER.warn("JSON web keystore retrieved is empty for issuer [{}]", issuer); return Optional.empty(); } val keySet = jwks.get(); if (keySet.getJsonWebKeys().isEmpty()) { LOGGER.warn("JSON web keystore retrieved [{}] contains no JSON web keys", keySet); return Optional.empty(); } val key = getJsonSigningWebKeyFromJwks(keySet); if (key == null) { LOGGER.warn("Unable to locate public key from [{}]", keySet); return Optional.empty(); } LOGGER.debug("Found public JSON web key as [{}]", key); return Optional.of(key); } /** * Gets json signing web key from jwks. * * @param jwks the jwks * @return the json signing web key from jwks */ protected PublicJsonWebKey getJsonSigningWebKeyFromJwks(final JsonWebKeySet jwks) { if (jwks.getJsonWebKeys().isEmpty()) { LOGGER.warn("No JSON web keys are available in the keystore"); return null; } val key = jwks.getJsonWebKeys() .stream() .filter(k -> k instanceof PublicJsonWebKey) .filter(k -> OidcJsonWebKeystoreRotationService.JsonWebKeyLifecycleStates.getJsonWebKeyState(k).isCurrent()) .findFirst() .map(PublicJsonWebKey.class::cast) .orElseThrow(() -> new RuntimeException("Unable to locate current JSON web key from the keystore")); if (StringUtils.isBlank(key.getAlgorithm())) { LOGGER.debug("Located JSON web key [{}] has no algorithm defined", key); } if (StringUtils.isBlank(key.getKeyId())) { LOGGER.debug("Located JSON web key [{}] has no key id defined", key); } if (key.getPrivateKey() == null) { LOGGER.warn("Located JSON web key [{}] has no private key", key); return null; } return key; } /** * Build json web key set. * * @param resource the resource * @return the json web key set * @throws Exception the exception */ protected JsonWebKeySet buildJsonWebKeySet(final Resource resource) throws Exception { val jsonWebKeySet = OidcJsonWebKeystoreGeneratorService.toJsonWebKeyStore(resource); val webKey = getJsonSigningWebKeyFromJwks(jsonWebKeySet); if (webKey == null || webKey.getPrivateKey() == null) { LOGGER.warn("JSON web key retrieved [{}] is not found or has no associated private key", webKey); return null; } return jsonWebKeySet; } /** * Build json web key set. * * @return the json web key set */ protected Optional<JsonWebKeySet> buildJsonWebKeySet() { try { val resource = generateJwksResource(); if (resource == null) { LOGGER.warn("Unable to load or generate a JWKS resource"); return Optional.empty(); } LOGGER.trace("Retrieving default JSON web key from [{}]", resource); val jsonWebKeySet = buildJsonWebKeySet(resource); if (jsonWebKeySet == null || jsonWebKeySet.getJsonWebKeys().isEmpty()) { LOGGER.warn("No JSON web keys could be found"); return Optional.empty(); } val badKeysCount = jsonWebKeySet.getJsonWebKeys().stream().filter(k -> StringUtils.isBlank(k.getAlgorithm()) && StringUtils.isBlank(k.getKeyId()) && StringUtils.isBlank(k.getKeyType())).count(); if (badKeysCount == jsonWebKeySet.getJsonWebKeys().size()) { LOGGER.warn("No valid JSON web keys could be found. The keys that are found in the keystore " + "do not define an algorithm, key id or key type and cannot be used for JWKS operations."); return Optional.empty(); } val webKey = getJsonSigningWebKeyFromJwks(jsonWebKeySet); if (webKey != null && webKey.getPrivateKey() == null) { LOGGER.warn("JSON web key retrieved [{}] has no associated private key.", webKey.getKeyId()); return Optional.empty(); } LOGGER.trace("Loaded JSON web key set as [{}]", jsonWebKeySet.toJson()); return Optional.of(jsonWebKeySet); } catch (final Exception e) { LoggingUtils.warn(LOGGER, e); } return Optional.empty(); } /** * Generate jwks resource. * * @return the resource * @throws Exception the exception */ protected Resource generateJwksResource() throws Exception { val resource = getOidcJsonWebKeystoreGeneratorService().generate(); LOGGER.debug("Loading default JSON web key from [{}]", resource); return resource; } }
924325a3b1a9caf4c575d46edea2856e8ba94559
9,492
java
Java
scm-webapp/src/test/java/sonia/scm/importexport/ExportServiceTest.java
boost-entropy-java/scm-manager
123bf5c86224e1b86d9b9320ba2ca5a548704cbe
[ "MIT" ]
79
2020-03-09T09:43:50.000Z
2022-03-03T13:53:45.000Z
scm-webapp/src/test/java/sonia/scm/importexport/ExportServiceTest.java
boost-entropy-java/scm-manager
123bf5c86224e1b86d9b9320ba2ca5a548704cbe
[ "MIT" ]
1,047
2020-03-11T10:33:41.000Z
2022-03-31T13:59:28.000Z
scm-webapp/src/test/java/sonia/scm/importexport/ExportServiceTest.java
boost-entropy-java/scm-manager
123bf5c86224e1b86d9b9320ba2ca5a548704cbe
[ "MIT" ]
25
2020-03-11T10:22:54.000Z
2022-03-09T12:52:43.000Z
37.840637
99
0.768688
1,002,546
/* * MIT License * * Copyright (c) 2020-present Cloudogu GmbH and Contributors * * 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 sonia.scm.importexport; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.subject.Subject; import org.apache.shiro.util.ThreadContext; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Answers; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import sonia.scm.NotFoundException; import sonia.scm.notifications.Type; import sonia.scm.repository.Repository; import sonia.scm.repository.RepositoryTestData; import sonia.scm.store.Blob; import sonia.scm.store.BlobStore; import sonia.scm.store.BlobStoreFactory; import sonia.scm.store.DataStore; import sonia.scm.store.DataStoreFactory; import sonia.scm.store.InMemoryBlobStore; import sonia.scm.store.InMemoryDataStore; import sonia.scm.user.User; import java.io.IOException; import java.io.OutputStream; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static sonia.scm.importexport.ExportService.STORE_NAME; @ExtendWith(MockitoExtension.class) class ExportServiceTest { private static final Repository REPOSITORY = RepositoryTestData.createHeartOfGold(); @Mock(answer = Answers.RETURNS_DEEP_STUBS) private BlobStoreFactory blobStoreFactory; @Mock(answer = Answers.RETURNS_DEEP_STUBS) private DataStoreFactory dataStoreFactory; @Mock private ExportFileExtensionResolver resolver; @Mock private ExportNotificationHandler notificationHandler; private BlobStore blobStore; private DataStore<RepositoryExportInformation> dataStore; @Mock private Subject subject; @InjectMocks private ExportService exportService; @BeforeEach void initMocks() { ThreadContext.bind(subject); PrincipalCollection principalCollection = mock(PrincipalCollection.class); lenient().when(subject.getPrincipals()).thenReturn(principalCollection); lenient().when(principalCollection.oneByType(User.class)).thenReturn( new User("trillian", "Trillian", "[email protected]") ); blobStore = new InMemoryBlobStore(); when(blobStoreFactory.withName(STORE_NAME).forRepository(REPOSITORY.getId()).build()) .thenReturn(blobStore); dataStore = new InMemoryDataStore<>(); when(dataStoreFactory.withType(RepositoryExportInformation.class).withName(STORE_NAME).build()) .thenReturn(dataStore); } @AfterEach void tearDown() { ThreadContext.unbindSubject(); } @Test void shouldClearStoreIfEntryAlreadyExists() throws IOException { //Old content blob blobStore.create(REPOSITORY.getId()); String newContent = "Scm-Manager-Export"; OutputStream os = exportService.store(REPOSITORY, true, true, true); os.write(newContent.getBytes()); os.flush(); os.close(); // Only new blob should exist List<Blob> blobs = blobStore.getAll(); assertThat(blobs).hasSize(1); //Verify content byte[] bytes = new byte[18]; exportService.getData(REPOSITORY).read(bytes); assertThat(new String(bytes)).isEqualTo(newContent); } @Test void shouldShowCorrectExportStatus() { doNothing().when(subject).checkPermission("repository:export:" + REPOSITORY.getId()); exportService.store(REPOSITORY, false, false, false); assertThat(exportService.isExporting(REPOSITORY)).isTrue(); exportService.setExportFinished(REPOSITORY); assertThat(exportService.isExporting(REPOSITORY)).isFalse(); verify(notificationHandler).handleSuccessfulExport(REPOSITORY); } @Test void shouldOnlyClearRepositoryExports() { doNothing().when(subject).checkPermission("repository:export:" + REPOSITORY.getId()); Repository hvpt = RepositoryTestData.createHappyVerticalPeopleTransporter(); dataStore.put(hvpt.getId(), new RepositoryExportInformation()); blobStore.create(REPOSITORY.getId()); dataStore.put(REPOSITORY.getId(), new RepositoryExportInformation()); exportService.clear(REPOSITORY.getId()); assertThat(dataStore.get(REPOSITORY.getId())).isNull(); assertThat(dataStore.get(hvpt.getId())).isNotNull(); assertThat(blobStore.getAll()).isEmpty(); } @Test void shouldGetExportInformation() { doNothing().when(subject).checkPermission("repository:export:" + REPOSITORY.getId()); exportService.store(REPOSITORY, true, true, false); RepositoryExportInformation exportInformation = exportService.getExportInformation(REPOSITORY); assertThat(exportInformation.getExporterName()).isEqualTo("trillian"); assertThat(exportInformation.getCreated()).isNotNull(); } @Test void shouldThrowNotFoundException() { assertThrows(NotFoundException.class, () -> exportService.getExportInformation(REPOSITORY)); assertThrows(NotFoundException.class, () -> exportService.getFileExtension(REPOSITORY)); assertThrows(NotFoundException.class, () -> exportService.getData(REPOSITORY)); } @Test void shouldResolveFileExtension() { doNothing().when(subject).checkPermission("repository:export:" + REPOSITORY.getId()); String extension = "tar.gz.enc"; RepositoryExportInformation info = new RepositoryExportInformation(); dataStore.put(REPOSITORY.getId(), info); when(resolver.resolve(REPOSITORY, false, false, false)).thenReturn(extension); String fileExtension = exportService.getFileExtension(REPOSITORY); assertThat(fileExtension).isEqualTo(extension); } @Test void shouldOnlyCleanupUnfinishedExports() { blobStore.create(REPOSITORY.getId()); RepositoryExportInformation info = new RepositoryExportInformation(); info.setStatus(ExportStatus.EXPORTING); dataStore.put( REPOSITORY.getId(), info ); Repository finishedExport = RepositoryTestData.createHappyVerticalPeopleTransporter(); BlobStore finishedExportBlobStore = new InMemoryBlobStore(); Blob finishedExportBlob = finishedExportBlobStore.create(finishedExport.getId()); RepositoryExportInformation finishedExportInfo = new RepositoryExportInformation(); finishedExportInfo.setStatus(ExportStatus.FINISHED); dataStore.put( finishedExport.getId(), finishedExportInfo ); when(blobStoreFactory.withName(STORE_NAME).forRepository(finishedExport.getId()).build()) .thenReturn(finishedExportBlobStore); exportService.cleanupUnfinishedExports(); assertThat(blobStore.getAll()).isEmpty(); assertThat(dataStore.get(REPOSITORY.getId()).getStatus()).isEqualTo(ExportStatus.INTERRUPTED); assertThat(finishedExportBlobStore.get(finishedExport.getId())).isEqualTo(finishedExportBlob); assertThat(dataStore.get(finishedExport.getId()).getStatus()).isEqualTo(ExportStatus.FINISHED); } @Test void shouldOnlyCleanupOutdatedExports() { blobStore.create(REPOSITORY.getId()); Instant now = Instant.now(); RepositoryExportInformation newExportInfo = new RepositoryExportInformation(); newExportInfo.setCreated(now); dataStore.put(REPOSITORY.getId(), newExportInfo); Repository oldExportRepo = RepositoryTestData.createHappyVerticalPeopleTransporter(); BlobStore oldExportBlobStore = new InMemoryBlobStore(); oldExportBlobStore.create(oldExportRepo.getId()); RepositoryExportInformation oldExportInfo = new RepositoryExportInformation(); Instant old = Instant.now().minus(11, ChronoUnit.DAYS); oldExportInfo.setCreated(old); dataStore.put(oldExportRepo.getId(), oldExportInfo); when(blobStoreFactory.withName(STORE_NAME).forRepository(oldExportRepo.getId()).build()) .thenReturn(oldExportBlobStore); exportService.cleanupOutdatedExports(); assertThat(blobStore.getAll()).hasSize(1); assertThat(oldExportBlobStore.getAll()).isEmpty(); assertThat(dataStore.get(REPOSITORY.getId()).getCreated()).isEqualTo(now); assertThat(dataStore.get(oldExportRepo.getId())).isNull(); } }
924325eb47f6b98284c1268b8029c545dfe5dba2
719
java
Java
spec/java/src/io/kaitai/struct/spec/TestSwitchManualEnumInvalid.java
dgelessus/kaitai_struct_tests
93a13cd899960794ec7a70c8e1412ac123537f5c
[ "MIT" ]
11
2018-04-01T03:58:15.000Z
2021-08-14T09:04:55.000Z
spec/java/src/io/kaitai/struct/spec/TestSwitchManualEnumInvalid.java
dgelessus/kaitai_struct_tests
93a13cd899960794ec7a70c8e1412ac123537f5c
[ "MIT" ]
73
2016-07-20T10:27:15.000Z
2020-12-17T18:56:46.000Z
spec/java/src/io/kaitai/struct/spec/TestSwitchManualEnumInvalid.java
dgelessus/kaitai_struct_tests
93a13cd899960794ec7a70c8e1412ac123537f5c
[ "MIT" ]
37
2016-08-15T08:25:56.000Z
2021-08-28T14:48:46.000Z
29.958333
100
0.714882
1,002,547
package io.kaitai.struct.spec; import io.kaitai.struct.testformats.SwitchManualEnumInvalid; import io.kaitai.struct.testformats.SwitchManualEnumInvalid.Opcode.*; import org.testng.annotations.Test; import static org.testng.Assert.*; public class TestSwitchManualEnumInvalid extends CommonSpec { @Test public void testSwitchManualEnumInvalid() throws Exception { SwitchManualEnumInvalid r = SwitchManualEnumInvalid.fromFile(SRC_DIR + "enum_negative.bin"); assertEquals(r.opcodes().size(), 2); assertNull(r.opcodes().get(0).code()); assertNull(r.opcodes().get(0).body()); assertNull(r.opcodes().get(1).code()); assertNull(r.opcodes().get(1).body()); } }
924325f4bdfe08544f9130eb72c95b61aeb9beca
1,345
java
Java
src/main/java/io/choerodon/iam/infra/dto/payload/UserEventPayload.java
choerodon/base-service
50d39cffb2c306757b12c3af6dab97443386cfa4
[ "Apache-2.0" ]
5
2020-03-20T02:31:52.000Z
2020-07-25T02:35:23.000Z
src/main/java/io/choerodon/iam/infra/dto/payload/UserEventPayload.java
choerodon/base-service
50d39cffb2c306757b12c3af6dab97443386cfa4
[ "Apache-2.0" ]
2
2020-04-13T02:46:40.000Z
2020-07-30T07:13:51.000Z
src/main/java/io/choerodon/iam/infra/dto/payload/UserEventPayload.java
choerodon/base-service
50d39cffb2c306757b12c3af6dab97443386cfa4
[ "Apache-2.0" ]
15
2019-12-05T01:05:49.000Z
2020-09-27T02:43:39.000Z
17.025316
56
0.60223
1,002,548
package io.choerodon.iam.infra.dto.payload; /** * @author flyleft * @since 2018/4/9 */ public class UserEventPayload { private String id; private String name; private String username; private String email; private String phone; private Long fromUserId; private Long organizationId; public Long getOrganizationId() { return organizationId; } public void setOrganizationId(Long organizationId) { this.organizationId = organizationId; } public Long getFromUserId() { return fromUserId; } public void setFromUserId(Long fromUserId) { this.fromUserId = fromUserId; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } }
924326bb46280590f6d4390bf77b4ae5975e46b4
4,954
java
Java
dev.jeka.core/src/main/java/dev/jeka/core/api/java/project/JkJavaProjectConstruction.java
treilhes/jeka
877cf5f507da8edb1b370b7dbbf780d58f68fc59
[ "Apache-2.0" ]
null
null
null
dev.jeka.core/src/main/java/dev/jeka/core/api/java/project/JkJavaProjectConstruction.java
treilhes/jeka
877cf5f507da8edb1b370b7dbbf780d58f68fc59
[ "Apache-2.0" ]
null
null
null
dev.jeka.core/src/main/java/dev/jeka/core/api/java/project/JkJavaProjectConstruction.java
treilhes/jeka
877cf5f507da8edb1b370b7dbbf780d58f68fc59
[ "Apache-2.0" ]
null
null
null
35.640288
112
0.705692
1,002,549
package dev.jeka.core.api.java.project; import dev.jeka.core.api.depmanagement.*; import dev.jeka.core.api.file.JkPathMatcher; import dev.jeka.core.api.file.JkPathTreeSet; import dev.jeka.core.api.java.JkJarPacker; import dev.jeka.core.api.java.JkManifest; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.util.function.Consumer; /** * Responsible to produce jar files. It involves compilation and unit testing. * Compilation and tests can be run independently without creating jars. * <p> * Java Project Jar Production has common characteristics : * <ul> * <li>Contains Java source files to be compiled</li> * <li>All Java sources file (prod + test) are wrote against the same Java version and encoding</li> * <li>The project may contain unit tests</li> * <li>It can depends on any accepted dependencies (Maven module, other project, files on fs, ...)</li> * <li>Part of the sources/resources may be generated</li> * <li>By default, passing test suite is required to produce Jars.</li> * </ul> * Integration tests are outside of {@link JkJavaProjectConstruction} scope. */ public class JkJavaProjectConstruction { private final JkJavaProject project; private final JkDependencyManagement<JkJavaProjectConstruction> dependencyManagement; private final JkJavaProjectCompilation<JkJavaProjectConstruction> compilation; private final JkJavaProjectTesting testing; private PathMatcher fatJarFilter = JkPathMatcher.of(); // take all private final JkManifest manifest; private JkPathTreeSet extraFilesToIncludeInFatJar = JkPathTreeSet.ofEmpty(); /** * For Parent chaining */ public JkJavaProject __; JkJavaProjectConstruction(JkJavaProject project) { this.project = project; this.__ = project; dependencyManagement = JkDependencyManagement.ofParent(this); compilation = JkJavaProjectCompilation.ofProd(this); testing = new JkJavaProjectTesting(this); manifest = JkManifest.ofParent(this); } public JkJavaProjectConstruction apply(Consumer<JkJavaProjectConstruction> consumer) { consumer.accept(this); return this; } public JkDependencyManagement<JkJavaProjectConstruction> getDependencyManagement() { return dependencyManagement; } public JkJavaProjectCompilation<JkJavaProjectConstruction> getCompilation() { return compilation; } public JkJavaProjectTesting getTesting() { return testing; } public JkManifest<JkJavaProjectConstruction> getManifest() { return manifest; } public JkJavaProject getProject() { return project; } private void addManifestDefaults() { JkModuleId moduleId = project.getPublication().getModuleId(); JkVersion version = project.getPublication().getVersion(); if (manifest.getMainAttribute(JkManifest.IMPLEMENTATION_TITLE) == null) { manifest.addMainAttribute(JkManifest.IMPLEMENTATION_TITLE, moduleId.getName()); } if (manifest.getMainAttribute(JkManifest.IMPLEMENTATION_VENDOR) == null) { manifest.addMainAttribute(JkManifest.IMPLEMENTATION_VENDOR, moduleId.getGroup()); } if (manifest.getMainAttribute(JkManifest.IMPLEMENTATION_VERSION) == null) { manifest.addMainAttribute(JkManifest.IMPLEMENTATION_VERSION, version.getValue()); } } public void createBinJar(Path target) { compilation.runIfNecessary(); testing.runIfNecessary(); addManifestDefaults(); JkJarPacker.of(compilation.getLayout().resolveClassDir()) .withManifest(manifest) .withExtraFiles(getExtraFilesToIncludeInJar()) .makeJar(target); } public void createBinJar() { createBinJar(project.getArtifactPath(JkArtifactId.ofMainArtifact("jar"))); } public void createFatJar(Path target) { compilation.runIfNecessary(); testing.runIfNecessary(); Iterable<Path> classpath = dependencyManagement.fetchDependencies(JkScope.RUNTIME).getFiles(); addManifestDefaults(); JkJarPacker.of(compilation.getLayout().resolveClassDir()) .withManifest(manifest) .withExtraFiles(getExtraFilesToIncludeInJar()) .makeFatJar(target, classpath, this.fatJarFilter); } public void createFatJar() { createFatJar(project.getArtifactPath(JkArtifactId.of("fat", "jar"))); } public JkPathTreeSet getExtraFilesToIncludeInJar() { return this.extraFilesToIncludeInFatJar; } /** * File trees specified here will be added to the fat jar. */ public JkJavaProjectConstruction setExtraFilesToIncludeInFatJar(JkPathTreeSet extraFilesToIncludeInFatJar) { this.extraFilesToIncludeInFatJar = extraFilesToIncludeInFatJar; return this; } }
9243271ff70324d154b3bd9dec7696c5ad45dd33
1,899
java
Java
src/main/java/nl/moj/server/test/model/TestCase.java
mastersofjava/mastersofjava
ec6b655af0baf828202fac2d9cb29a696ce4b9fc
[ "Apache-2.0" ]
1
2020-05-22T16:38:02.000Z
2020-05-22T16:38:02.000Z
src/main/java/nl/moj/server/test/model/TestCase.java
mastersofjava/mastersofjava
ec6b655af0baf828202fac2d9cb29a696ce4b9fc
[ "Apache-2.0" ]
null
null
null
src/main/java/nl/moj/server/test/model/TestCase.java
mastersofjava/mastersofjava
ec6b655af0baf828202fac2d9cb29a696ce4b9fc
[ "Apache-2.0" ]
null
null
null
27.521739
81
0.7109
1,002,550
/* Copyright 2020 First Eight BV (The Netherlands) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file / these files 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 nl.moj.server.test.model; import javax.persistence.*; import java.time.Instant; import java.util.UUID; import lombok.*; @Entity @Table(name = "test_cases") @SequenceGenerator(name = "id_seq", sequenceName = "test_cases_seq") @Builder(toBuilder = true) @NoArgsConstructor(force = true) @AllArgsConstructor @Data @EqualsAndHashCode(of = {"uuid"}) @ToString(exclude = {"testAttempt"}) public class TestCase { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_seq") @Column(name = "id", nullable = false) private Long id; @Column(name = "uuid", nullable = false, updatable = false) private UUID uuid; @ManyToOne @JoinColumn(name = "test_attempt_id", nullable = false) private TestAttempt testAttempt; @Column(name = "date_time_start", nullable = false) private Instant dateTimeStart; @Column(name = "date_time_end", nullable = false) private Instant dateTimeEnd; @Column(name = "name", nullable = false) private String name; @Column(name = "success", nullable = false) private boolean success; @Column(name = "timeout", nullable = false) private boolean timeout; @Column(name = "test_output", columnDefinition = "TEXT") private String testOutput; }
9243274fd2fc74ffcd258e00a0c1a0d984f5cba5
2,358
java
Java
websockets-jsr/src/main/java/io/undertow/websockets/jsr/handshake/PerConnectionServerEndpointConfig.java
jasondlee/undertow
20d777c181264f749a39fca7003dc9441687faa9
[ "Apache-2.0" ]
null
null
null
websockets-jsr/src/main/java/io/undertow/websockets/jsr/handshake/PerConnectionServerEndpointConfig.java
jasondlee/undertow
20d777c181264f749a39fca7003dc9441687faa9
[ "Apache-2.0" ]
null
null
null
websockets-jsr/src/main/java/io/undertow/websockets/jsr/handshake/PerConnectionServerEndpointConfig.java
jasondlee/undertow
20d777c181264f749a39fca7003dc9441687faa9
[ "Apache-2.0" ]
null
null
null
28.083333
103
0.710047
1,002,551
/* * JBoss, Home of Professional Open Source. * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.undertow.websockets.jsr.handshake; import jakarta.websocket.Decoder; import jakarta.websocket.Encoder; import jakarta.websocket.Extension; import jakarta.websocket.server.ServerEndpointConfig; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author <a href="mailto:[email protected]">Richard Opalka</a> */ final class PerConnectionServerEndpointConfig implements ServerEndpointConfig { private final ServerEndpointConfig delegate; private final Map<String, Object> userProperties; PerConnectionServerEndpointConfig(final ServerEndpointConfig delegate) { this.delegate = delegate; this.userProperties = Collections.synchronizedMap(new HashMap<>(delegate.getUserProperties())); } @Override public Class<?> getEndpointClass() { return delegate.getEndpointClass(); } @Override public String getPath() { return delegate.getPath(); } @Override public List<String> getSubprotocols() { return delegate.getSubprotocols(); } @Override public List<Extension> getExtensions() { return delegate.getExtensions(); } @Override public Configurator getConfigurator() { return delegate.getConfigurator(); } @Override public List<Class<? extends Encoder>> getEncoders() { return delegate.getEncoders(); } @Override public List<Class<? extends Decoder>> getDecoders() { return delegate.getDecoders(); } @Override public Map<String, Object> getUserProperties() { return userProperties; } }
924327692ff353bf264a004833835234e04c322a
21,247
java
Java
java-dynamic-sqs-listener-core/src/main/java/com/jashmore/sqs/container/CoreMessageListenerContainer.java
bart-blommaerts/java-dynamic-sqs-listener
ff573f1b07e5b1dff911063f2ab68adcc03152d5
[ "MIT" ]
null
null
null
java-dynamic-sqs-listener-core/src/main/java/com/jashmore/sqs/container/CoreMessageListenerContainer.java
bart-blommaerts/java-dynamic-sqs-listener
ff573f1b07e5b1dff911063f2ab68adcc03152d5
[ "MIT" ]
null
null
null
java-dynamic-sqs-listener-core/src/main/java/com/jashmore/sqs/container/CoreMessageListenerContainer.java
bart-blommaerts/java-dynamic-sqs-listener
ff573f1b07e5b1dff911063f2ab68adcc03152d5
[ "MIT" ]
null
null
null
51.445521
159
0.690309
1,002,552
package com.jashmore.sqs.container; import static com.jashmore.sqs.container.CoreMessageListenerContainerConstants.DEFAULT_SHOULD_INTERRUPT_MESSAGE_PROCESSING_ON_SHUTDOWN; import static com.jashmore.sqs.container.CoreMessageListenerContainerConstants.DEFAULT_SHOULD_PROCESS_EXTRA_MESSAGES_ON_SHUTDOWN; import static com.jashmore.sqs.container.CoreMessageListenerContainerConstants.DEFAULT_SHUTDOWN_TIME_IN_SECONDS; import static com.jashmore.sqs.util.thread.ThreadUtils.threadFactory; import static java.util.concurrent.TimeUnit.SECONDS; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.jashmore.sqs.broker.MessageBroker; import com.jashmore.sqs.processor.MessageProcessor; import com.jashmore.sqs.resolver.MessageResolver; import com.jashmore.sqs.retriever.MessageRetriever; import com.jashmore.sqs.util.properties.PropertyUtils; import lombok.extern.slf4j.Slf4j; import software.amazon.awssdk.services.sqs.model.Message; import software.amazon.awssdk.utils.StringUtils; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.Queue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.function.Consumer; import java.util.function.Supplier; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe; /** * Container that allows for the safe start and stop of all the components for the SQS Library. * * <p>This container handles graceful shutdown by allowing any extra batched messages to be processed after the shutdown process has been triggered. It * also will wait for all background threads to finish, for example it will wait until all of the resolved messages in a {@link MessageResolver} to * be completed before finishing the shutdown. * * <p>This container expects a new instance of each component (e.g. {@link MessageResolver}) each time that it is started up to remove the need for each * component to maintain state between start up. */ @Slf4j @ThreadSafe public class CoreMessageListenerContainer implements MessageListenerContainer { private final String identifier; private final Supplier<MessageBroker> messageBrokerSupplier; private final Supplier<MessageRetriever> messageRetrieverSupplier; private final Supplier<MessageProcessor> messageProcessorSupplier; private final Supplier<MessageResolver> messageResolverSupplier; private final CoreMessageListenerContainerProperties properties; /** * The service that is running this container's thread. */ @GuardedBy("this") private ExecutorService executorService; /** * Future that will be resolved when the container's thread has finished. */ @GuardedBy("this") private CompletableFuture<?> containerFuture; public CoreMessageListenerContainer(final String identifier, final Supplier<MessageBroker> messageBrokerSupplier, final Supplier<MessageRetriever> messageRetrieverSupplier, final Supplier<MessageProcessor> messageProcessorSupplier, final Supplier<MessageResolver> messageResolverSupplier) { this( identifier, messageBrokerSupplier, messageRetrieverSupplier, messageProcessorSupplier, messageResolverSupplier, StaticCoreMessageListenerContainerProperties.builder().build() ); } public CoreMessageListenerContainer(final String identifier, final Supplier<MessageBroker> messageBrokerSupplier, final Supplier<MessageRetriever> messageRetrieverSupplier, final Supplier<MessageProcessor> messageProcessorSupplier, final Supplier<MessageResolver> messageResolverSupplier, final CoreMessageListenerContainerProperties properties) { Preconditions.checkArgument(StringUtils.isNotBlank(identifier), "identifier should not be empty"); this.identifier = identifier; this.messageBrokerSupplier = messageBrokerSupplier; this.messageRetrieverSupplier = messageRetrieverSupplier; this.messageProcessorSupplier = messageProcessorSupplier; this.messageResolverSupplier = messageResolverSupplier; this.properties = properties; } @Override public String getIdentifier() { return identifier; } @Override public synchronized CompletableFuture<?> start() { if (executorService != null) { log.info("Container '{}' has already been started. No action taken", identifier); } else { log.info("Container '{}' is being started", identifier); executorService = Executors.newSingleThreadExecutor(threadFactory(identifier + "-message-container")); containerFuture = CompletableFuture.runAsync(this::runContainer, executorService); } return containerFuture; } @Override public synchronized void stop() { stop(Duration.of(1, ChronoUnit.MINUTES)); } @Override public synchronized void stop(final Duration duration) { final long shutdownTimeLimitInSeconds = duration.get(ChronoUnit.SECONDS); log.info("Container '{}' is being stopped and will wait {} seconds", identifier, shutdownTimeLimitInSeconds); try { if (executorService != null) { executorService.shutdownNow(); final boolean isTerminated = executorService.awaitTermination(shutdownTimeLimitInSeconds, SECONDS); if (!isTerminated) { log.error("Container '{}' did not shutdown in timeout", identifier); } } } catch (final InterruptedException interruptedException) { log.warn("Thread interrupted waiting for container to stop. All threads may not be successfully completed"); Thread.currentThread().interrupt(); } finally { executorService = null; containerFuture = null; } } /** * This contains the main execution for the container where it controls how the container is started and the process for gracefully shutting down. * * <p>This is visible for testing to simplify testing so that it doesn't need to be run on separate threads, etc. */ @VisibleForTesting void runContainer() { final MessageRetriever messageRetriever = messageRetrieverSupplier.get(); final MessageResolver messageResolver = messageResolverSupplier.get(); final MessageBroker messageBroker = messageBrokerSupplier.get(); final MessageProcessor messageProcessor = messageProcessorSupplier.get(); final ExecutorService messageBrokerExecutorService = Executors.newSingleThreadExecutor(threadFactory(identifier + "-message-broker")); final BlockingRunnable shutdownMessageResolver = startupMessageResolver(messageResolver); final ExecutorService messageProcessingExecutorService = buildMessageProcessingExecutorService(); final Queue<Message> extraMessages = new LinkedList<>(); // As the AsyncMessageRetriever may have extra messages batched, they will be placed in here final BlockingRunnable shutdownMessageRetriever = startupMessageRetriever(messageRetriever, extraMessages::addAll); try { processMessagesFromRetriever(messageBroker, messageRetriever, messageProcessor, messageResolver, messageBrokerExecutorService, messageProcessingExecutorService); log.info("Container '{}' is being shutdown", identifier); shutdownMessageRetriever.run(); processExtraMessages(messageBroker, messageProcessor, messageResolver, messageBrokerExecutorService, messageProcessingExecutorService, extraMessages); shutdownMessageProcessingThreads(messageProcessingExecutorService); shutdownMessageResolver.run(); log.info("Container '{}' has stopped", identifier); } catch (final InterruptedException interruptedException) { log.error("Container '{}' was interrupted during the shutdown process. Doing a forceful shutdown that may eventually complete", identifier); } } /** * Executes the main flow of the application for processing messages. * * <p>This performs the main execution by taking messages by calling into the {@link MessageBroker} which will get new messages from the * {@link MessageRetriever} which for each new message will be processed by the {@link MessageProcessor} and then finally resolved by calling into * the {@link MessageResolver}. * * <p>This will keep running until the thread is interrupted via a call to {@link #stop()}. * * @param messageBroker the broker that handles the concurrent processing of messages and how to flow messages between the components * @param messageRetriever the retriever for obtaining new messages * @param messageProcessor the processor that will execute the message * @param messageResolver the resolver that will resolve the message on successful processing * @param messageProcessingExecutorService the executor service that the message processing will run on */ private void processMessagesFromRetriever(final MessageBroker messageBroker, final MessageRetriever messageRetriever, final MessageProcessor messageProcessor, final MessageResolver messageResolver, final ExecutorService brokerExecutorService, final ExecutorService messageProcessingExecutorService) throws InterruptedException { log.info("Container '{}' is beginning to process messages", identifier); try { runUntilInterruption(brokerExecutorService, () -> messageBroker.processMessages( messageProcessingExecutorService, messageRetriever::retrieveMessage, message -> messageProcessor.processMessage(message, () -> messageResolver.resolveMessage(message)) )); } catch (final ExecutionException executionException) { log.error("Error processing messages", executionException.getCause()); } } /** * This processes any extra messages that may have been batched by the {@link MessageRetriever}. * * @param messageBroker the broker that handles the concurrent processing of messages and how to flow messages between the components * @param messageProcessor the processor that will execute the message * @param messageResolver the resolver that will resolve the message on successful processing * @param executorService the executor service that the message processing will run on * @param messages the messages to be processed * @throws InterruptedException if the thread was interrupted during this process */ private void processExtraMessages(final MessageBroker messageBroker, final MessageProcessor messageProcessor, final MessageResolver messageResolver, final ExecutorService messageBrokerExecutorService, final ExecutorService executorService, final Queue<Message> messages) throws InterruptedException { if (!messages.isEmpty() && shouldProcessAnyExtraRetrievedMessagesOnShutdown()) { log.debug("Container '{}' is processing {} extra messages before shutdown", identifier, messages.size()); try { runUntilInterruption(messageBrokerExecutorService, () -> messageBroker.processMessages( executorService, () -> !messages.isEmpty(), () -> CompletableFuture.completedFuture(messages.poll()), message -> messageProcessor.processMessage(message, () -> messageResolver.resolveMessage(message)) )); } catch (final ExecutionException executionException) { log.error("Exception thrown processing extra messages", executionException.getCause()); } } } /** * Run the provided {@link Runnable} on the {@link ExecutorService} and wait until the thread is interrupted in which case the {@link Runnable} should * also be interrupted. * * @param executorService the executor service to execute the runnable * @param runnable the runnable to run which should keep running until an interruption * @throws InterruptedException if it was interrupted again waiting for the runnable to exit * @throws ExecutionException if there was an error running the runnable */ private void runUntilInterruption(final ExecutorService executorService, final BlockingRunnable runnable) throws InterruptedException, ExecutionException { final CompletableFuture<?> runnableCompleted = new CompletableFuture<>(); Future<?> processingFuture = null; try { processingFuture = executorService.submit(() -> { try { runnable.run(); } catch (final InterruptedException interruptedException) { Thread.currentThread().interrupt(); } finally { runnableCompleted.complete(null); } }); processingFuture.get(); } catch (final InterruptedException interruptedException) { processingFuture.cancel(true); } runnableCompleted.get(); } /** * Shuts down the {@link ExecutorService} that is processing the messages. * * <p>Depending on {@link CoreMessageListenerContainerProperties#shouldInterruptThreadsProcessingMessagesOnShutdown()} it will interrupt the message * processing threads. * * @param executorService the executor service used to run these messages * @throws InterruptedException if the thread was interrupted during this process */ private void shutdownMessageProcessingThreads(final ExecutorService executorService) throws InterruptedException { log.debug("Container '{}' is waiting for all message processing threads to finish...", identifier); if (shouldInterruptMessageProcessingThreadsOnShutdown()) { executorService.shutdownNow(); log.debug("Container '{}' interrupted the message processing threads", identifier); } else { executorService.shutdown(); } executorService.awaitTermination(getMessageProcessingShutdownTimeoutInSeconds(), SECONDS); } /** * Start the background thread of the {@link MessageRetriever}, returning a {@link BlockingRunnable} that can be executed * when it needs to be shutdown. * * <p>A callback is provided that will be called when the {@link MessageRetriever} finishes which will contain a drain of any of the extra messages * that had not been processed yet. * * @param messageRetriever the retriever to start * @param extraMessagesConsumer the callback for consuming leftover messages * @return the method for shutting down the retriever background thread */ private BlockingRunnable startupMessageRetriever(final MessageRetriever messageRetriever, final Consumer<List<Message>> extraMessagesConsumer) { final ExecutorService executorService = Executors.newSingleThreadExecutor(threadFactory(getIdentifier() + "-message-retriever")); CompletableFuture.supplyAsync(messageRetriever::run, executorService) .thenAccept(extraMessagesConsumer); return () -> { log.info("Shutting down MessageRetriever"); executorService.shutdownNow(); final boolean retrieverShutdown; final int retrieverShutdownTimeoutInSeconds = getMessageRetrieverShutdownTimeoutInSeconds(); retrieverShutdown = executorService.awaitTermination(retrieverShutdownTimeoutInSeconds, SECONDS); if (!retrieverShutdown) { log.error("MessageRetriever did not shutdown within {} seconds", retrieverShutdownTimeoutInSeconds); } }; } /** * Start a background thread of the {@link MessageResolver}, returning a {@link BlockingRunnable} that can be executed * when it needs to be shutdown. * * @param messageResolver the resolver to start if it is async * @return the optional {@link ExecutorService} for this background thread if it was started */ private BlockingRunnable startupMessageResolver(final MessageResolver messageResolver) { final ExecutorService executorService = Executors.newSingleThreadExecutor(threadFactory(getIdentifier() + "-message-resolver")); CompletableFuture.runAsync(messageResolver::run, executorService); return () -> { log.info("Shutting down MessageResolver"); executorService.shutdownNow(); final long messageResolverShutdownTimeInSeconds = getMessageResolverShutdownTimeoutInSeconds(); final boolean messageResolverShutdown = executorService.awaitTermination(getMessageResolverShutdownTimeoutInSeconds(), SECONDS); if (!messageResolverShutdown) { log.error("MessageResolver did not shutdown within {} seconds", messageResolverShutdownTimeInSeconds); } }; } /** * Build the {@link ExecutorService} that will be used for the threads that are processing the messages. * * @return the executor service that will be used for processing messages */ private ExecutorService buildMessageProcessingExecutorService() { return Executors.newCachedThreadPool(threadFactory(getIdentifier() + "-message-processing-%d")); } /** * Get the amount of time in seconds that we should wait for the messages that are currently being processed to finish. * * @return the amount of time in seconds to wait for the message processing to finish */ private int getMessageProcessingShutdownTimeoutInSeconds() { return PropertyUtils.safelyGetPositiveOrZeroIntegerValue( "messageProcessingShutdownTimeoutInSeconds", properties::getMessageProcessingShutdownTimeoutInSeconds, DEFAULT_SHUTDOWN_TIME_IN_SECONDS ); } /** * Get the amount of time in seconds that we should wait for the {@link MessageRetriever} to shutdown when requested. * * @return the amount of time in seconds to wait for shutdown */ private int getMessageRetrieverShutdownTimeoutInSeconds() { return PropertyUtils.safelyGetPositiveOrZeroIntegerValue( "messageRetrieverShutdownTimeoutInSeconds", properties::getMessageRetrieverShutdownTimeoutInSeconds, DEFAULT_SHUTDOWN_TIME_IN_SECONDS ); } /** * Get the amount of time in seconds that we should wait for the {@link MessageResolver} to shutdown when requested. * * @return the amount of time in seconds to wait for shutdown */ private int getMessageResolverShutdownTimeoutInSeconds() { return PropertyUtils.safelyGetPositiveOrZeroIntegerValue( "messageRetrieverShutdownTimeoutInSeconds", properties::getMessageResolverShutdownTimeoutInSeconds, DEFAULT_SHUTDOWN_TIME_IN_SECONDS ); } private boolean shouldInterruptMessageProcessingThreadsOnShutdown() { return Optional.ofNullable(properties.shouldInterruptThreadsProcessingMessagesOnShutdown()) .orElse(DEFAULT_SHOULD_INTERRUPT_MESSAGE_PROCESSING_ON_SHUTDOWN); } private boolean shouldProcessAnyExtraRetrievedMessagesOnShutdown() { return Optional.ofNullable(properties.shouldProcessAnyExtraRetrievedMessagesOnShutdown()) .orElse(DEFAULT_SHOULD_PROCESS_EXTRA_MESSAGES_ON_SHUTDOWN); } /** * Similar to a {@link Runnable} but it allows for {@link InterruptedException}s to be thrown. */ @FunctionalInterface private interface BlockingRunnable { /** * Run the method. * * @throws InterruptedException if the thread was interrupted during execution */ void run() throws InterruptedException; } }
92432840f3726deef7291c02497c92f9b6d10106
3,553
java
Java
app/src/test/java/co/iyubinest/runtasticcodingcontest/GroupsInteractorTest.java
iyubinest/TrainingBuddies
cdc52534a94b626dde5e2e5184337baa4530d0ab
[ "Apache-2.0" ]
1
2017-07-28T17:24:17.000Z
2017-07-28T17:24:17.000Z
app/src/test/java/co/iyubinest/runtasticcodingcontest/GroupsInteractorTest.java
iyubinest/TrainingBuddies
cdc52534a94b626dde5e2e5184337baa4530d0ab
[ "Apache-2.0" ]
null
null
null
app/src/test/java/co/iyubinest/runtasticcodingcontest/GroupsInteractorTest.java
iyubinest/TrainingBuddies
cdc52534a94b626dde5e2e5184337baa4530d0ab
[ "Apache-2.0" ]
null
null
null
39.921348
99
0.750633
1,002,553
package co.iyubinest.runtasticcodingcontest; import co.iyubinest.runtasticcodingcontest.groups.Group; import co.iyubinest.runtasticcodingcontest.groups.GroupsInteractor; import co.iyubinest.runtasticcodingcontest.groups.HttpGroupsInteractor; import co.iyubinest.runtasticcodingcontest.members.Member; import co.iyubinest.runtasticcodingcontest.retrofit.AppRetrofit; import io.reactivex.subscribers.TestSubscriber; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.List; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import static org.hamcrest.core.Is.is; public class GroupsInteractorTest { private MockWebServer server; private MockResponse groupsResponse = new MockResponse().setBody(fromFile("groups.json")); private MockResponse error = new MockResponse().setHttp2ErrorCode(500); private TestSubscriber<List<Group>> subscriber = new TestSubscriber<>(); private GroupsInteractor interactor; private static String fromFile(String name) { try { InputStream resource = GroupsInteractorTest.class.getClassLoader().getResourceAsStream(name); BufferedReader reader = new BufferedReader(new InputStreamReader(resource)); StringBuilder result = new StringBuilder(); String partial = reader.readLine(); while (partial != null) { result.append(partial); partial = reader.readLine(); } return result.toString(); } catch (Exception ignored) { throw new IllegalArgumentException("File not found"); } } @Before public void setup() throws Exception { server = new MockWebServer(); interactor = new HttpGroupsInteractor(AppRetrofit.build(server.url("/").toString())); } @After public void tearDown() throws Exception { server.shutdown(); } @Test public void failOnError() throws Exception { server.enqueue(error); interactor.get().subscribe(subscriber); subscriber.assertError(Exception.class); } @Test public void biggestGroup() throws Exception { server.enqueue(groupsResponse); interactor.get().subscribe(subscriber); List<Group> groups = subscriber.values().get(0); Assert.assertThat(Group.biggestGroup(groups).name(), is("South Park")); Assert.assertThat(Group.biggestGroup(groups).members().size(), is(7)); } @Test public void fastestMember() throws Exception { server.enqueue(groupsResponse); interactor.get().subscribe(subscriber); List<Group> groups = subscriber.values().get(0); Assert.assertThat(Group.fastestMember(groups).id(), is(8)); } @Test public void trainingBuddies() throws Exception { server.enqueue(groupsResponse); interactor.get().subscribe(subscriber); List<Group> groups = subscriber.values().get(0); List<Member> simpsons = groups.get(0).members(); List<Member> futurama = groups.get(1).members(); List<Member> southPark = groups.get(2).members(); List<List<Member>> simpsonsTrainingBuddies = Group.trainingBuddies(simpsons); List<List<Member>> futuramaTrainingBuddies = Group.trainingBuddies(futurama); List<List<Member>> southParkTrainingBuddies = Group.trainingBuddies(southPark); Assert.assertThat(Group.secondQuestion(southParkTrainingBuddies), is(18)); Assert.assertThat(Group.secondQuestion(futuramaTrainingBuddies), is(-1)); Assert.assertThat(Group.secondQuestion(simpsonsTrainingBuddies), is(3)); } }
924328470833cfb5cc822cec85091b75e1fd25f6
2,650
java
Java
fdb-sql-layer-pg/src/main/java/com/foundationdb/sql/pg/PostgresDDLStatementGenerator.java
geophile/sql-layer
0eab8b596b729081b9265631230a6703b854a4ec
[ "MIT" ]
null
null
null
fdb-sql-layer-pg/src/main/java/com/foundationdb/sql/pg/PostgresDDLStatementGenerator.java
geophile/sql-layer
0eab8b596b729081b9265631230a6703b854a4ec
[ "MIT" ]
null
null
null
fdb-sql-layer-pg/src/main/java/com/foundationdb/sql/pg/PostgresDDLStatementGenerator.java
geophile/sql-layer
0eab8b596b729081b9265631230a6703b854a4ec
[ "MIT" ]
null
null
null
44.166667
118
0.719245
1,002,554
/** * The MIT License (MIT) * * Copyright (c) 2009-2015 FoundationDB, LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.foundationdb.sql.pg; import com.foundationdb.server.error.MissingDDLParametersException; import com.foundationdb.sql.parser.DDLStatementNode; import com.foundationdb.sql.parser.StatementNode; import com.foundationdb.sql.parser.ParameterNode; import com.foundationdb.sql.parser.CreateTableNode; import com.foundationdb.sql.parser.NodeTypes; import java.util.List; /** DDL statements executed against AIS. */ public class PostgresDDLStatementGenerator extends PostgresBaseStatementGenerator { public PostgresDDLStatementGenerator(PostgresServerSession server, PostgresOperatorCompiler compiler) { this.compiler = compiler; } @Override public PostgresStatement generateStub(PostgresServerSession server, String sql, StatementNode stmt, List<ParameterNode> params, int[] paramTypes) { if (!(stmt instanceof DDLStatementNode)) return null; PostgresOperatorStatement opstmt = null; if(stmt.getNodeType() == NodeTypes.CREATE_TABLE_NODE && ((CreateTableNode)stmt).getQueryExpression() != null){ opstmt = new PostgresOperatorStatement(compiler); } if ((params != null) && !params.isEmpty()) throw new MissingDDLParametersException (); return new PostgresDDLStatement((DDLStatementNode)stmt, sql, opstmt); } PostgresOperatorCompiler compiler; }
924328d5ad87fe953c2be3645a09479b77c82fb8
247
java
Java
src/main/java/cz/daiton/foodsquare/like/LikeService.java
itsDaiton/food-square-api
b8558a148f8c8b987c004c95fdd690cb04fc225c
[ "MIT" ]
null
null
null
src/main/java/cz/daiton/foodsquare/like/LikeService.java
itsDaiton/food-square-api
b8558a148f8c8b987c004c95fdd690cb04fc225c
[ "MIT" ]
2
2022-03-03T17:36:39.000Z
2022-03-10T16:22:05.000Z
src/main/java/cz/daiton/foodsquare/like/LikeService.java
itsDaiton/food-square-api
b8558a148f8c8b987c004c95fdd690cb04fc225c
[ "MIT" ]
null
null
null
13.722222
42
0.676113
1,002,555
package cz.daiton.foodsquare.like; import java.util.List; public interface LikeService { Like get(Long id); List<Like> getAll(); void add(LikeDto likeDto); void update(LikeDto likeDto, Long id); void delete(Long id); }
9243290618e1dee8a498d8d856aca26940f7da9c
10,803
java
Java
src/nl/leocms/content/ContentUtil.java
mmbase/natmm
e87fc70ddb29519478edc0829d29758582827629
[ "DOC", "Unlicense" ]
null
null
null
src/nl/leocms/content/ContentUtil.java
mmbase/natmm
e87fc70ddb29519478edc0829d29758582827629
[ "DOC", "Unlicense" ]
null
null
null
src/nl/leocms/content/ContentUtil.java
mmbase/natmm
e87fc70ddb29519478edc0829d29758582827629
[ "DOC", "Unlicense" ]
null
null
null
35.771523
145
0.648246
1,002,556
/* * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is LeoCMS. * * The Initial Developer of the Original Code is * 'De Gemeente Leeuwarden' (The dutch municipality Leeuwarden). * * See license.txt in the root of the LeoCMS directory for the full license. */ package nl.leocms.content; import java.util.List; import nl.leocms.authorization.AuthorizationHelper; import nl.leocms.util.ContentTypeHelper; import nl.leocms.util.RubriekHelper; import org.mmbase.bridge.*; import org.mmbase.util.logging.Logger; import org.mmbase.util.logging.Logging; /** * Various utilities for ContentElements * */ public class ContentUtil { /** MMbase logging system */ private static Logger log = Logging.getLoggerInstance(ContentUtil.class.getName()); private Cloud cloud; /** * @param mmbase */ public ContentUtil(Cloud cloud) { super(); this.cloud = cloud; } public void addSchrijver(Node content) { addSchrijver(content, cloud.getUser().getIdentifier()); } public void addSchrijver(Node content, String username) { log.debug("user " + username); AuthorizationHelper auth = new AuthorizationHelper(cloud); Node user = auth.getUserNode(username); RelationManager schrijver = cloud.getRelationManager("contentelement", "users", "schrijver"); content.deleteRelations("schrijver"); content.createRelation(user, schrijver).commit(); } /** * Create the relation to the creatierubriek. * * @param content - Node contentelement * @param rubrieknr - String rubrieknumber (nodenumber) */ public void addCreatieRubriek(Node content, String rubrieknr) { log.debug("Creatierubriek " + rubrieknr); Node rubriek = cloud.getNode(rubrieknr); RelationManager creatierubriek = cloud.getRelationManager("contentelement", "rubriek", "creatierubriek"); content.createRelation(rubriek, creatierubriek).commit(); } /** * Create a relation to the 'hoofdrubriek' of a content item. * * Bv. creatierubriek huren: path = root - Leeuwarden - Wonen - huren<BR> * Hoofdrubriek = Wonen<BR><BR> * * If the path is too short (eg. root - Leeuwarden), there is NO hoofdrubriek. * * @param content - content element * @param creatierubriek - creatierubriek. */ public void addHoofdRubriek(Node content, String creatierubriek) { RubriekHelper rubriekHelper = new RubriekHelper(cloud); List list = rubriekHelper.getPathToRoot( cloud.getNode(creatierubriek)); if (list.size() >= 3) { Node hoofdrubriek = (Node) list.get(2); log.debug("Hoofdrubriek "+hoofdrubriek); RelationManager man = cloud.getRelationManager("contentelement","rubriek","hoofdrubriek"); content.createRelation(hoofdrubriek,man).commit(); } } /** * Create a relation to the 'subsite' of a content item. * * Bv. creatierubriek huren: path = root - Leeuwarden - Wonen - huren<BR> * subsite = Leeuwarden<BR><BR> * * If the path is too short (eg. root), then root is the subsite. * * @param content - content element * @param creatierubriek - creatierubriek. */ public void addSubsite(Node content, String creatierubriek) { RubriekHelper rubriekHelper = new RubriekHelper(cloud); List list = rubriekHelper.getPathToRoot( cloud.getNode(creatierubriek)); if (!list.isEmpty()) { Node subsiteRubriek = null; RelationManager subsite = cloud.getRelationManager("contentelement","rubriek","subsite"); if (list.size() >= 2) { subsiteRubriek = (Node) list.get(1); } else { subsiteRubriek = (Node) list.get(0); } log.debug("subsite "+subsiteRubriek); content.createRelation(subsiteRubriek,subsite).commit(); } } /** * Check if a contentnode has a creatierubriek * * @param content - Content Node * @return true if the node has a related workflowitem */ public boolean hasCreatieRubriek(Node content) { NodeList list = null; if (ContentTypeHelper.PAGINA.equals(content.getNodeManager().getName())) { list = content.getRelatedNodes("rubriek", "posrel", "SOURCE"); } else { list = content.getRelatedNodes("rubriek", "creatierubriek", "DESTINATION"); } return !list.isEmpty(); } public Node getCreatieRubriek(Node content) { NodeList list = null; if (ContentTypeHelper.PAGINA.equals(content.getNodeManager().getName())) { list = content.getRelatedNodes("rubriek", "posrel", "SOURCE"); } else { list = content.getRelatedNodes("rubriek", "creatierubriek", "DESTINATION"); } return list.getNode(0); } /** * Check if a contentnode has a schrijver * * @param content - Content Node * @return true if the node has a related workflowitem */ public boolean hasSchrijver(Node content) { NodeList list = content.getRelatedNodes("users", "schrijver", "DESTINATION"); return !list.isEmpty(); } public Node getSchrijver(Node content) { return content.getRelatedNodes("users", "schrijver", "DESTINATION").getNode(0); } /** * pools are grouped in topics * each topic is related to rubriek * for all objects in a rubriek each pool an object is related to, should also be related to the topic of this rubriek * pre-condition: each rubriek has at most one related topic * * @param content - content element * @param creatierubriek - creatierubriek. */ public void updateTopics(Node content, String creatierubriek) { log.debug("trying to update topics"); Node rubriek = cloud.getNode(creatierubriek); NodeList nlTopics = rubriek.getRelatedNodes("topics","related",null); Node rubriekTopic = null; if(nlTopics.size()==0) { rubriekTopic = cloud.getNodeManager("topics").createNode(); rubriekTopic.setStringValue("title", rubriek.getStringValue("naam")); rubriekTopic.commit(); rubriek.createRelation(rubriekTopic,cloud.getRelationManager("related")).commit(); log.debug("created new topic and related it to rubriek " + rubriek.getStringValue("naam")); } if(nlTopics.size()>0) { rubriekTopic = nlTopics.getNode(0); } NodeList nlPools = content.getRelatedNodes("pools","posrel",null); int nlPoolsSize = nlPools.size(); for(int i=0; i < nlPoolsSize; i++) { Node pool = nlPools.getNode(i); pool = makeUnique(pool,"name"); // for doing anything, make sure this pool is unique log.debug("checking pool " + pool.getNumber()); nlTopics = cloud.getList( pool.getStringValue("number"), "pools,posrel,topics", "topics.number", "topics.number = '" + rubriekTopic.getNumber() + "'", null,null,null,false ); if(nlTopics.size()==0) { log.debug("create relation between pool " + pool.getNumber() + " and topic " + rubriekTopic.getNumber()); pool.createRelation(rubriekTopic,cloud.getRelationManager("posrel")).commit(); } } } /** * check if this node is unique on field (case-insensitive) * if it is the case then merge the node with its sibling * * @param node node to be checked * @param field field to should be a unique key (case-insensitive) */ public Node makeUnique(Node node, String field) { String sConstraint = "UPPER(" + field + ") = '" + node.getStringValue(field).toUpperCase() + "' AND number!='" + node.getNumber() + "'"; log.debug(sConstraint); NodeList nl = node.getNodeManager().getList(sConstraint,null,null); for (NodeIterator it = nl.nodeIterator(); it.hasNext();) { Node sibling = it.nextNode(); log.debug("nodes " + node.getNumber() + " and " + sibling.getNumber() + " have identical " + field + " " + node.getStringValue(field) ); if(sibling!=null && sibling.getNumber()!=node.getNumber()) { node = mergeNodes(node,sibling); } } return node; } /** * merges all relations from origin to target * and then deletes the origin * * @param origin * @param target */ public Node mergeNodes(Node origin, Node target) { log.debug("merging " + origin.getNumber() + " into " + target.getNumber()); RelationList rl = origin.getRelations(); for (RelationIterator it = rl.relationIterator(); it.hasNext();) { Relation rel = it.nextRelation(); Node rel_source = rel.getSource(); Node rel_destination = rel.getDestination(); if(rel_source.getNumber()==origin.getNumber()) { // origin is source, create a relation with the destination of the relation createRelation(target,rel_destination,rel.getRelationManager()); } else { // origin is target, create a relation with the source of the relation createRelation(rel_source,target,rel.getRelationManager()); } rel.delete(true); } try { origin.delete(); } catch (Exception e) { log.error("node " + origin.getNumber() + " still contains relations, so it can not be deleted"); } return target; } /** * create relation, but only if it does not already exist * * @param origin * @param target */ public void createRelation(Node source, Node destination, RelationManager rm) { if(!hasRelation(source,destination,rm)) { source.createRelation(destination,rm).commit(); } } /** * returns true if there exists a relation from source to destination of type rm * * @param source * @param destination * @param rm */ public boolean hasRelation(Node source, Node destination, RelationManager rm) { NodeList nl = source.getRelatedNodes(destination.getNodeManager(),rm.getName(),null); int dNumber = destination.getNumber(); for (NodeIterator it = nl.nodeIterator(); it.hasNext();) { if(it.nextNode().getNumber()==dNumber) { log.debug("the relation between " + source.getNumber() + " and " + dNumber + " exists"); return true; } } return false; } }
92432a032e8d79c14d4155f03b6aede50bcdcbd7
140
java
Java
common/src/main/java/com/library/common/callback/OnUiCallback.java
ydmmocoo/MGM
51d0822e9c378da1538847c6d5f01adf94524a4b
[ "Apache-2.0" ]
null
null
null
common/src/main/java/com/library/common/callback/OnUiCallback.java
ydmmocoo/MGM
51d0822e9c378da1538847c6d5f01adf94524a4b
[ "Apache-2.0" ]
null
null
null
common/src/main/java/com/library/common/callback/OnUiCallback.java
ydmmocoo/MGM
51d0822e9c378da1538847c6d5f01adf94524a4b
[ "Apache-2.0" ]
null
null
null
14
36
0.692857
1,002,557
package com.library.common.callback; /** * Created by WYiang on 2017/10/28. */ public interface OnUiCallback { void onUiThread(); }
92432a5e7fa8dfdd1526f1be5e6dfaad5ccca4c2
729
java
Java
api/src/test/java/fr/cesi/goodfood/domain/RestaurantTest.java
silas-riacourt/good-food
e01a8a4622e38bef96c82ac9b3de1ecd7f5a0310
[ "MIT" ]
null
null
null
api/src/test/java/fr/cesi/goodfood/domain/RestaurantTest.java
silas-riacourt/good-food
e01a8a4622e38bef96c82ac9b3de1ecd7f5a0310
[ "MIT" ]
null
null
null
api/src/test/java/fr/cesi/goodfood/domain/RestaurantTest.java
silas-riacourt/good-food
e01a8a4622e38bef96c82ac9b3de1ecd7f5a0310
[ "MIT" ]
null
null
null
30.375
58
0.709191
1,002,558
package fr.cesi.goodfood.domain; import static org.assertj.core.api.Assertions.assertThat; import fr.cesi.goodfood.web.rest.TestUtil; import org.junit.jupiter.api.Test; class RestaurantTest { @Test void equalsVerifier() throws Exception { TestUtil.equalsVerifier(Restaurant.class); Restaurant restaurant1 = new Restaurant(); restaurant1.setId(1L); Restaurant restaurant2 = new Restaurant(); restaurant2.setId(restaurant1.getId()); assertThat(restaurant1).isEqualTo(restaurant2); restaurant2.setId(2L); assertThat(restaurant1).isNotEqualTo(restaurant2); restaurant1.setId(null); assertThat(restaurant1).isNotEqualTo(restaurant2); } }
92432aae81db1d8f38c9daf2b0df8334d923e099
1,099
java
Java
models/src/test/java/vsr/cobalt/models/FunctionalityTest.java
ewie/cobalt
737e22a4e6bc46d2b90a5524cc8686ec3e37cfd4
[ "BSD-3-Clause" ]
null
null
null
models/src/test/java/vsr/cobalt/models/FunctionalityTest.java
ewie/cobalt
737e22a4e6bc46d2b90a5524cc8686ec3e37cfd4
[ "BSD-3-Clause" ]
null
null
null
models/src/test/java/vsr/cobalt/models/FunctionalityTest.java
ewie/cobalt
737e22a4e6bc46d2b90a5524cc8686ec3e37cfd4
[ "BSD-3-Clause" ]
null
null
null
23.891304
80
0.734304
1,002,559
/* * Copyright (c) 2014, Erik Wienhold * All rights reserved. * * Licensed under the BSD 3-Clause License. */ package vsr.cobalt.models; import org.testng.annotations.Test; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import static vsr.cobalt.models.makers.FunctionalityMaker.aMinimalFunctionality; import static vsr.cobalt.testing.Assert.assertSubClass; import static vsr.cobalt.testing.Utilities.make; @Test public class FunctionalityTest { @Test public void isAnIdentifiable() { assertSubClass(Functionality.class, Identifiable.class); } @Test public static class CanEqual { @Test public void returnTrueWhenCalledWitFunctionality() { final Functionality f1 = make(aMinimalFunctionality()); final Functionality f2 = make(aMinimalFunctionality()); assertTrue(f1.canEqual(f2)); } @Test public void returnFalseWhenCalledWithNonFunctionality() { final Functionality f = make(aMinimalFunctionality()); final Object x = new Object(); assertFalse(f.canEqual(x)); } } }
92432beffc10f94b3fbb40d1f72edaf64ce4eb83
2,285
java
Java
forest-core/src/main/java/com/dtflys/forest/utils/RequestNameValue.java
Zhongren233/forest
606694b2e6d78f851e91c024dfaca7fba0280d5e
[ "MIT" ]
471
2021-03-11T07:29:27.000Z
2022-03-31T09:35:49.000Z
forest-core/src/main/java/com/dtflys/forest/utils/RequestNameValue.java
Zhongren233/forest
606694b2e6d78f851e91c024dfaca7fba0280d5e
[ "MIT" ]
47
2021-03-12T02:02:12.000Z
2022-03-28T17:20:09.000Z
forest-core/src/main/java/com/dtflys/forest/utils/RequestNameValue.java
Zhongren233/forest
606694b2e6d78f851e91c024dfaca7fba0280d5e
[ "MIT" ]
79
2021-03-11T07:29:36.000Z
2022-03-19T07:50:56.000Z
20.401786
92
0.619256
1,002,560
package com.dtflys.forest.utils; import static com.dtflys.forest.mapping.MappingParameter.*; /** * 请求报文中键值对数据的封装 * * @author gongjun[[email protected]] * @since 2016-05-24 */ public class RequestNameValue { private String name; private Object value; private final int target; private String defaultValue; /** * 子项Content-Type */ private String partContentType; /** * 请求对象中键值对数据的封装 * * @param name 键值字符串 * @param target 在请求报文中的目标位置 */ public RequestNameValue(String name, int target) { this.name = name; this.target = target; } public RequestNameValue(String name, int target, String partContentType) { this.name = name; this.target = target; this.partContentType = partContentType; } public RequestNameValue(String name, Object value, int target) { this.name = name; this.value = value; this.target = target; } public RequestNameValue(String name, Object value, int target, String partContentType) { this.name = name; this.value = value; this.target = target; this.partContentType = partContentType; } public String getName() { return name; } public RequestNameValue setName(String name) { this.name = name; return this; } public Object getValue() { return value; } public RequestNameValue setValue(Object value) { this.value = value; return this; } public String getDefaultValue() { return defaultValue; } public RequestNameValue setDefaultValue(String defaultValue) { this.defaultValue = defaultValue; return this; } public boolean isInQuery() { return target == TARGET_QUERY; } public boolean isInBody() { return target == TARGET_BODY; } public boolean isInHeader() { return target == TARGET_HEADER; } public int getTarget() { return target; } public String getPartContentType() { return partContentType; } public RequestNameValue setPartContentType(String partContentType) { this.partContentType = partContentType; return this; } }
92432c4f22a58b79998f829b12b4afe617583a10
217
java
Java
src/main/java/org/stellar/sdk/StellarException.java
eschgi/java-stellar-sdk
c17fb8d344b0613a297c6c060c2580399d1632a2
[ "Apache-2.0" ]
null
null
null
src/main/java/org/stellar/sdk/StellarException.java
eschgi/java-stellar-sdk
c17fb8d344b0613a297c6c060c2580399d1632a2
[ "Apache-2.0" ]
null
null
null
src/main/java/org/stellar/sdk/StellarException.java
eschgi/java-stellar-sdk
c17fb8d344b0613a297c6c060c2580399d1632a2
[ "Apache-2.0" ]
null
null
null
18.083333
56
0.663594
1,002,561
package org.stellar.sdk; public class StellarException extends RuntimeException { public StellarException() { super(); } public StellarException(String message) { super(message); } }
92432cd7b61a8b85bdc5f1fa0fd334315f5336d3
927
java
Java
testSrc/com/intellij/plugins/haxe/lang/parser/statements/BreakTest.java
demurgos/intellij-haxe
f6d85d14a77c35f5b16b6cd2fcd53a97d00f2478
[ "Apache-2.0" ]
124
2017-01-04T14:02:38.000Z
2022-03-01T01:42:07.000Z
testSrc/com/intellij/plugins/haxe/lang/parser/statements/BreakTest.java
demurgos/intellij-haxe
f6d85d14a77c35f5b16b6cd2fcd53a97d00f2478
[ "Apache-2.0" ]
455
2017-01-10T03:44:40.000Z
2022-02-01T16:13:54.000Z
testSrc/com/intellij/plugins/haxe/lang/parser/statements/BreakTest.java
demurgos/intellij-haxe
f6d85d14a77c35f5b16b6cd2fcd53a97d00f2478
[ "Apache-2.0" ]
59
2017-01-20T07:46:49.000Z
2022-03-26T13:15:50.000Z
28.96875
75
0.729234
1,002,562
/* * Copyright 2000-2013 JetBrains s.r.o. * Copyright 2014-2014 AS3Boyan * Copyright 2014-2014 Elias Ku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.plugins.haxe.lang.parser.statements; /** * @author fedor.korotkov */ public class BreakTest extends StatementTestBase { public BreakTest() { super("break"); } public void testSimple() throws Throwable { doTest(true); } }
92432dc0c92d67bf1dd993b90d45316e198af6af
4,158
java
Java
org/apache/maven/configuration/internal/DefaultBeanConfigurator.java
CoOwner/VisualPvP
c92d1dcf40a812787e32e8a21d6462b57e755b99
[ "MIT" ]
null
null
null
org/apache/maven/configuration/internal/DefaultBeanConfigurator.java
CoOwner/VisualPvP
c92d1dcf40a812787e32e8a21d6462b57e755b99
[ "MIT" ]
null
null
null
org/apache/maven/configuration/internal/DefaultBeanConfigurator.java
CoOwner/VisualPvP
c92d1dcf40a812787e32e8a21d6462b57e755b99
[ "MIT" ]
null
null
null
27
129
0.733045
1,002,563
package org.apache.maven.configuration.internal; import java.io.File; import org.apache.maven.configuration.BeanConfigurationException; import org.apache.maven.configuration.BeanConfigurationPathTranslator; import org.apache.maven.configuration.BeanConfigurationRequest; import org.apache.maven.configuration.BeanConfigurationValuePreprocessor; import org.apache.maven.configuration.BeanConfigurator; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.converters.composite.ObjectWithFieldsConverter; import org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup; import org.codehaus.plexus.component.configurator.converters.lookup.DefaultConverterLookup; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; import org.codehaus.plexus.component.configurator.expression.TypeAwareExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration; import org.codehaus.plexus.util.xml.Xpp3Dom; @Component(role=BeanConfigurator.class) public class DefaultBeanConfigurator implements BeanConfigurator { private final ConverterLookup converterLookup; public DefaultBeanConfigurator() { converterLookup = new DefaultConverterLookup(); } public void configureBean(BeanConfigurationRequest request) throws BeanConfigurationException { if (request == null) { throw new IllegalArgumentException("bean configuration request not specified"); } if (request.getBean() == null) { throw new IllegalArgumentException("bean to be configured not specified"); } Object configuration = request.getConfiguration(); if (configuration == null) { return; } PlexusConfiguration plexusConfig = null; if ((configuration instanceof PlexusConfiguration)) { plexusConfig = (PlexusConfiguration)configuration; } else if ((configuration instanceof Xpp3Dom)) { plexusConfig = new XmlPlexusConfiguration((Xpp3Dom)configuration); } else { throw new BeanConfigurationException("unsupported bean configuration source (" + configuration.getClass().getName() + ")"); } ClassLoader classLoader = request.getClassLoader(); if (classLoader == null) { classLoader = request.getBean().getClass().getClassLoader(); } BeanExpressionEvaluator evaluator = new BeanExpressionEvaluator(request); ObjectWithFieldsConverter converter = new ObjectWithFieldsConverter(); try { converter.processConfiguration(converterLookup, request.getBean(), classLoader, plexusConfig, evaluator); } catch (ComponentConfigurationException e) { throw new BeanConfigurationException(e.getMessage(), e); } } static class BeanExpressionEvaluator implements TypeAwareExpressionEvaluator { private final BeanConfigurationValuePreprocessor preprocessor; private final BeanConfigurationPathTranslator translator; public BeanExpressionEvaluator(BeanConfigurationRequest request) { preprocessor = request.getValuePreprocessor(); translator = request.getPathTranslator(); } public Object evaluate(String expression, Class<?> type) throws ExpressionEvaluationException { if (preprocessor != null) { try { return preprocessor.preprocessValue(expression, type); } catch (BeanConfigurationException e) { throw new ExpressionEvaluationException(e.getMessage(), e); } } return expression; } public Object evaluate(String expression) throws ExpressionEvaluationException { return evaluate(expression, null); } public File alignToBaseDirectory(File file) { if (translator != null) { return translator.translatePath(file); } return file; } } }
92432e8999eed0a653f6f644268948307f771502
3,994
java
Java
app/src/main/java/home/MobilCraft/UnZipper.java
sergcomp/mobilecraft-v-1.0
b42d56cb0a24dabe32676a9b7c401b5e2ef1eaed
[ "Apache-2.0" ]
null
null
null
app/src/main/java/home/MobilCraft/UnZipper.java
sergcomp/mobilecraft-v-1.0
b42d56cb0a24dabe32676a9b7c401b5e2ef1eaed
[ "Apache-2.0" ]
null
null
null
app/src/main/java/home/MobilCraft/UnZipper.java
sergcomp/mobilecraft-v-1.0
b42d56cb0a24dabe32676a9b7c401b5e2ef1eaed
[ "Apache-2.0" ]
null
null
null
35.345133
110
0.55333
1,002,564
package home.MobilCraft; import android.app.IntentService; import android.app.Notification; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.util.Log; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; import com.MobileCraft.R; public class UnZipper extends IntentService { @Override protected void onHandleIntent(Intent intent) { mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Notification.Builder mBuilder = new Notification.Builder(this); mBuilder.setContentTitle(getString(R.string.notification_title)) .setContentText(getString(R.string.notification_description)).setSmallIcon(R.drawable.update); String[] file = intent.getStringArrayExtra(EXTRA_KEY_IN_FILE); String location = intent.getStringExtra(EXTRA_KEY_IN_LOCATION); mNotifyManager.notify(id, mBuilder.build()); int per = 0; int size = getSummarySize(file); for (String f : file) { try { try { FileInputStream fin = new FileInputStream(f); ZipInputStream zin = new ZipInputStream(fin); ZipEntry ze; while ((ze = zin.getNextEntry()) != null) { if (ze.isDirectory()) { per++; isDir(ze.getName(), location); } else { per++; int progress = 100 * per / size; publishProgress(progress); FileOutputStream f_out = new FileOutputStream(location + ze.getName()); byte[] buffer = new byte[8192]; int len; while ((len = zin.read(buffer)) != -1) { f_out.write(buffer, 0, len); } f_out.close(); zin.closeEntry(); f_out.close(); } } zin.close(); } catch (FileNotFoundException e) { Log.e(TAG, e.getMessage()); } } catch (IOException e) { Log.e(TAG, e.getLocalizedMessage()); } } } public UnZipper() { super("home.MobilCraft.UnZipper"); } private void isDir(String dir, String unDir) { File f = new File(unDir + dir); if (!f.isDirectory()) { f.mkdirs(); } } private void publishProgress(int progress) { Intent intentUpdate = new Intent(ACTION_UPDATE); intentUpdate.putExtra(ACTION_PROGRESS, progress); sendBroadcast(intentUpdate); } private int getSummarySize(String[] zips) { int size = 0; for (String z : zips) { try { ZipFile zipSize = new ZipFile(z); size += zipSize.size(); } catch (IOException e) { Log.e(TAG, e.getLocalizedMessage()); } } return size; } @Override public void onDestroy() { super.onDestroy(); mNotifyManager.cancel(id); publishProgress(-1); } public static final String ACTION_UPDATE = "home.MobilCraft.UPDATE"; public static final String EXTRA_KEY_IN_FILE = "file"; public static final String EXTRA_KEY_IN_LOCATION = "location"; public static final String ACTION_PROGRESS = "progress"; public final String TAG = UnZipper.class.getSimpleName(); private NotificationManager mNotifyManager; private int id = 1; }
92432e9656cb236487d10ebb969b6b98911f2c4b
488
java
Java
test/objects/TestRotatingTriangularPrism.java
Modiseus/TTC-Graph-Simulation
924f50d703591d97c2ed4aba5ac677612b0d6f2a
[ "MIT" ]
null
null
null
test/objects/TestRotatingTriangularPrism.java
Modiseus/TTC-Graph-Simulation
924f50d703591d97c2ed4aba5ac677612b0d6f2a
[ "MIT" ]
null
null
null
test/objects/TestRotatingTriangularPrism.java
Modiseus/TTC-Graph-Simulation
924f50d703591d97c2ed4aba5ac677612b0d6f2a
[ "MIT" ]
null
null
null
21.217391
91
0.754098
1,002,565
package objects; import objects.variables.ObjectData; public class TestRotatingTriangularPrism extends TestIRNGObject<RotatingTriangularPrism> { @Override protected RotatingTriangularPrism createRNGObject() { return new RotatingTriangularPrism(); } @Override protected ObjectData getDataForSimulation() { ObjectData data = ObjectData.create(); data.setValue(rngObject.varTimer, 19); data.setValue(rngObject.varTimerMax, 125); return data; } }
92432fc7e6a4b205fa902261524bcf8d3b4eff86
1,796
java
Java
app/src/main/java/com/mxt/anitrend/base/custom/view/text/PageIndicator.java
LDSpits/anitrend-app
e885a064412a9c1a354767c280e689f9476df730
[ "MIT" ]
null
null
null
app/src/main/java/com/mxt/anitrend/base/custom/view/text/PageIndicator.java
LDSpits/anitrend-app
e885a064412a9c1a354767c280e689f9476df730
[ "MIT" ]
null
null
null
app/src/main/java/com/mxt/anitrend/base/custom/view/text/PageIndicator.java
LDSpits/anitrend-app
e885a064412a9c1a354767c280e689f9476df730
[ "MIT" ]
null
null
null
25.657143
91
0.68931
1,002,566
package com.mxt.anitrend.base.custom.view.text; import android.content.Context; import android.graphics.Typeface; import android.support.annotation.Nullable; import android.support.v7.widget.AppCompatTextView; import android.util.AttributeSet; import android.util.TypedValue; import com.mxt.anitrend.R; import com.mxt.anitrend.base.interfaces.view.CustomView; import com.mxt.anitrend.util.CompatUtil; import java.util.Locale; /** * Created by max on 2017/11/25. */ public class PageIndicator extends AppCompatTextView implements CustomView { private int maximum; public PageIndicator(Context context) { super(context); onInit(); } public PageIndicator(Context context, @Nullable AttributeSet attrs) { super(context, attrs); onInit(); } public PageIndicator(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); onInit(); } /** * Optionally included when constructing custom views */ @Override public void onInit() { int padding = CompatUtil.dipToPx(8); setTextColor(CompatUtil.getColor(getContext(), R.color.colorTextLight)); setBackground(CompatUtil.getDrawable(getContext(), R.drawable.bubble_background)); setTextSize(TypedValue.COMPLEX_UNIT_SP, 10); setPadding(padding, padding, padding, padding); setTypeface(Typeface.DEFAULT_BOLD); } public void setMaximum(int maximum) { this.maximum = maximum; } public void setCurrentPosition(int index) { setText(String.format(Locale.getDefault(), "%d / %d", index, maximum)); } /** * Clean up any resources that won't be needed */ @Override public void onViewRecycled() { } }
9243304b91af6c55a66691cf71b55e4627d614c5
18,202
java
Java
spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerIntegrationTests.java
yangfancoming/spring-5.1.x
db4c2cbcaf8ba58f43463eff865d46bdbd742064
[ "Apache-2.0" ]
null
null
null
spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerIntegrationTests.java
yangfancoming/spring-5.1.x
db4c2cbcaf8ba58f43463eff865d46bdbd742064
[ "Apache-2.0" ]
null
null
null
spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerIntegrationTests.java
yangfancoming/spring-5.1.x
db4c2cbcaf8ba58f43463eff865d46bdbd742064
[ "Apache-2.0" ]
1
2021-06-05T07:25:05.000Z
2021-06-05T07:25:05.000Z
34.150094
119
0.77041
1,002,567
package org.springframework.messaging.simp.stomp; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.apache.activemq.broker.BrokerService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEventPublisher; import org.springframework.messaging.Message; import org.springframework.messaging.MessageDeliveryException; import org.springframework.messaging.MessageHandler; import org.springframework.messaging.MessagingException; import org.springframework.messaging.StubMessageChannel; import org.springframework.messaging.simp.SimpMessageHeaderAccessor; import org.springframework.messaging.simp.SimpMessageType; import org.springframework.messaging.simp.broker.BrokerAvailabilityEvent; import org.springframework.messaging.support.ExecutorSubscribableChannel; import org.springframework.messaging.support.MessageBuilder; import org.springframework.util.Assert; import org.springframework.util.SocketUtils; import static org.junit.Assert.*; /** * Integration tests for {@link StompBrokerRelayMessageHandler} running against ActiveMQ. * * */ public class StompBrokerRelayMessageHandlerIntegrationTests { @Rule public final TestName testName = new TestName(); private static final Log logger = LogFactory.getLog(StompBrokerRelayMessageHandlerIntegrationTests.class); private StompBrokerRelayMessageHandler relay; private BrokerService activeMQBroker; private ExecutorSubscribableChannel responseChannel; private TestMessageHandler responseHandler; private TestEventPublisher eventPublisher; private int port; @Before public void setup() throws Exception { logger.debug("Setting up before '" + this.testName.getMethodName() + "'"); this.port = SocketUtils.findAvailableTcpPort(61613); this.responseChannel = new ExecutorSubscribableChannel(); this.responseHandler = new TestMessageHandler(); this.responseChannel.subscribe(this.responseHandler); this.eventPublisher = new TestEventPublisher(); startActiveMqBroker(); createAndStartRelay(); } private void startActiveMqBroker() throws Exception { this.activeMQBroker = new BrokerService(); this.activeMQBroker.addConnector("stomp://localhost:" + this.port); this.activeMQBroker.setStartAsync(false); this.activeMQBroker.setPersistent(false); this.activeMQBroker.setUseJmx(false); this.activeMQBroker.getSystemUsage().getMemoryUsage().setLimit(1024 * 1024 * 5); this.activeMQBroker.getSystemUsage().getTempUsage().setLimit(1024 * 1024 * 5); this.activeMQBroker.start(); } private void createAndStartRelay() throws InterruptedException { StubMessageChannel channel = new StubMessageChannel(); List<String> prefixes = Arrays.asList("/queue/", "/topic/"); this.relay = new StompBrokerRelayMessageHandler(channel, this.responseChannel, channel, prefixes); this.relay.setRelayPort(this.port); this.relay.setApplicationEventPublisher(this.eventPublisher); this.relay.setSystemHeartbeatReceiveInterval(0); this.relay.setSystemHeartbeatSendInterval(0); this.relay.setPreservePublishOrder(true); this.relay.start(); this.eventPublisher.expectBrokerAvailabilityEvent(true); } @After public void stop() throws Exception { try { logger.debug("STOMP broker relay stats: " + this.relay.getStatsInfo()); this.relay.stop(); } finally { stopActiveMqBrokerAndAwait(); } } private void stopActiveMqBrokerAndAwait() throws Exception { logger.debug("Stopping ActiveMQ broker and will await shutdown"); if (!this.activeMQBroker.isStarted()) { logger.debug("Broker not running"); return; } final CountDownLatch latch = new CountDownLatch(1); this.activeMQBroker.addShutdownHook(new Runnable() { public void run() { latch.countDown(); } }); this.activeMQBroker.stop(); assertTrue("Broker did not stop", latch.await(5, TimeUnit.SECONDS)); logger.debug("Broker stopped"); } @Test public void publishSubscribe() throws Exception { logger.debug("Starting test publishSubscribe()"); String sess1 = "sess1"; String sess2 = "sess2"; String subs1 = "subs1"; String destination = "/topic/test"; MessageExchange conn1 = MessageExchangeBuilder.connect(sess1).build(); MessageExchange conn2 = MessageExchangeBuilder.connect(sess2).build(); this.relay.handleMessage(conn1.message); this.relay.handleMessage(conn2.message); this.responseHandler.expectMessages(conn1, conn2); MessageExchange subscribe = MessageExchangeBuilder.subscribeWithReceipt(sess1, subs1, destination, "r1").build(); this.relay.handleMessage(subscribe.message); this.responseHandler.expectMessages(subscribe); MessageExchange send = MessageExchangeBuilder.send(destination, "foo").andExpectMessage(sess1, subs1).build(); this.relay.handleMessage(send.message); this.responseHandler.expectMessages(send); } @Test(expected = MessageDeliveryException.class) public void messageDeliveryExceptionIfSystemSessionForwardFails() throws Exception { logger.debug("Starting test messageDeliveryExceptionIfSystemSessionForwardFails()"); stopActiveMqBrokerAndAwait(); this.eventPublisher.expectBrokerAvailabilityEvent(false); StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SEND); this.relay.handleMessage(MessageBuilder.createMessage("test".getBytes(), headers.getMessageHeaders())); } @Test public void brokerBecomingUnavailableTriggersErrorFrame() throws Exception { logger.debug("Starting test brokerBecomingUnavailableTriggersErrorFrame()"); String sess1 = "sess1"; MessageExchange connect = MessageExchangeBuilder.connect(sess1).build(); this.relay.handleMessage(connect.message); this.responseHandler.expectMessages(connect); MessageExchange error = MessageExchangeBuilder.error(sess1).build(); stopActiveMqBrokerAndAwait(); this.eventPublisher.expectBrokerAvailabilityEvent(false); this.responseHandler.expectMessages(error); } @Test public void brokerAvailabilityEventWhenStopped() throws Exception { logger.debug("Starting test brokerAvailabilityEventWhenStopped()"); stopActiveMqBrokerAndAwait(); this.eventPublisher.expectBrokerAvailabilityEvent(false); } @Test public void relayReconnectsIfBrokerComesBackUp() throws Exception { logger.debug("Starting test relayReconnectsIfBrokerComesBackUp()"); String sess1 = "sess1"; MessageExchange conn1 = MessageExchangeBuilder.connect(sess1).build(); this.relay.handleMessage(conn1.message); this.responseHandler.expectMessages(conn1); String subs1 = "subs1"; String destination = "/topic/test"; MessageExchange subscribe = MessageExchangeBuilder.subscribeWithReceipt(sess1, subs1, destination, "r1").build(); this.relay.handleMessage(subscribe.message); this.responseHandler.expectMessages(subscribe); MessageExchange error = MessageExchangeBuilder.error(sess1).build(); stopActiveMqBrokerAndAwait(); this.responseHandler.expectMessages(error); this.eventPublisher.expectBrokerAvailabilityEvent(false); startActiveMqBroker(); this.eventPublisher.expectBrokerAvailabilityEvent(true); } @Test public void disconnectWithReceipt() throws Exception { logger.debug("Starting test disconnectWithReceipt()"); MessageExchange connect = MessageExchangeBuilder.connect("sess1").build(); this.relay.handleMessage(connect.message); this.responseHandler.expectMessages(connect); MessageExchange disconnect = MessageExchangeBuilder.disconnectWithReceipt("sess1", "r123").build(); this.relay.handleMessage(disconnect.message); this.responseHandler.expectMessages(disconnect); } private static class TestEventPublisher implements ApplicationEventPublisher { private final BlockingQueue<BrokerAvailabilityEvent> eventQueue = new LinkedBlockingQueue<>(); @Override public void publishEvent(ApplicationEvent event) { publishEvent((Object) event); } @Override public void publishEvent(Object event) { logger.debug("Processing ApplicationEvent " + event); if (event instanceof BrokerAvailabilityEvent) { this.eventQueue.add((BrokerAvailabilityEvent) event); } } public void expectBrokerAvailabilityEvent(boolean isBrokerAvailable) throws InterruptedException { BrokerAvailabilityEvent event = this.eventQueue.poll(20000, TimeUnit.MILLISECONDS); assertNotNull("Times out waiting for BrokerAvailabilityEvent[" + isBrokerAvailable + "]", event); assertEquals(isBrokerAvailable, event.isBrokerAvailable()); } } private static class TestMessageHandler implements MessageHandler { private final BlockingQueue<Message<?>> queue = new LinkedBlockingQueue<>(); @Override public void handleMessage(Message<?> message) throws MessagingException { if (SimpMessageType.HEARTBEAT == SimpMessageHeaderAccessor.getMessageType(message.getHeaders())) { return; } this.queue.add(message); } public void expectMessages(MessageExchange... messageExchanges) throws InterruptedException { List<MessageExchange> expectedMessages = new ArrayList<>(Arrays.<MessageExchange>asList(messageExchanges)); while (expectedMessages.size() > 0) { Message<?> message = this.queue.poll(10000, TimeUnit.MILLISECONDS); assertNotNull("Timed out waiting for messages, expected [" + expectedMessages + "]", message); MessageExchange match = findMatch(expectedMessages, message); assertNotNull("Unexpected message=" + message + ", expected [" + expectedMessages + "]", match); expectedMessages.remove(match); } } private MessageExchange findMatch(List<MessageExchange> expectedMessages, Message<?> message) { for (MessageExchange exchange : expectedMessages) { if (exchange.matchMessage(message)) { return exchange; } } return null; } } /** * Holds a message as well as expected and actual messages matched against expectations. */ private static class MessageExchange { private final Message<?> message; private final MessageMatcher[] expected; private final Message<?>[] actual; public MessageExchange(Message<?> message, MessageMatcher... expected) { this.message = message; this.expected = expected; this.actual = new Message<?>[expected.length]; } public boolean matchMessage(Message<?> message) { for (int i = 0 ; i < this.expected.length; i++) { if (this.expected[i].match(message)) { this.actual[i] = message; return true; } } return false; } @Override public String toString() { return "Forwarded message:\n" + this.message + "\n" + "Should receive back:\n" + Arrays.toString(this.expected) + "\n" + "Actually received:\n" + Arrays.toString(this.actual) + "\n"; } } private static class MessageExchangeBuilder { private final Message<?> message; private final StompHeaderAccessor headers; private final List<MessageMatcher> expected = new ArrayList<>(); public MessageExchangeBuilder(Message<?> message) { this.message = message; this.headers = StompHeaderAccessor.wrap(message); } public static MessageExchangeBuilder error(String sessionId) { return new MessageExchangeBuilder(null).andExpectError(sessionId); } public static MessageExchangeBuilder connect(String sessionId) { StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECT); headers.setSessionId(sessionId); headers.setAcceptVersion("1.1,1.2"); headers.setHeartbeat(0, 0); Message<?> message = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders()); MessageExchangeBuilder builder = new MessageExchangeBuilder(message); builder.expected.add(new StompConnectedFrameMessageMatcher(sessionId)); return builder; } // TODO Determine why connectWithError() is unused. @SuppressWarnings("unused") public static MessageExchangeBuilder connectWithError(String sessionId) { StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECT); headers.setSessionId(sessionId); headers.setAcceptVersion("1.1,1.2"); Message<?> message = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders()); MessageExchangeBuilder builder = new MessageExchangeBuilder(message); return builder.andExpectError(); } public static MessageExchangeBuilder subscribeWithReceipt(String sessionId, String subscriptionId, String destination, String receiptId) { StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SUBSCRIBE); headers.setSessionId(sessionId); headers.setSubscriptionId(subscriptionId); headers.setDestination(destination); headers.setReceipt(receiptId); Message<?> message = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders()); MessageExchangeBuilder builder = new MessageExchangeBuilder(message); builder.expected.add(new StompReceiptFrameMessageMatcher(sessionId, receiptId)); return builder; } public static MessageExchangeBuilder send(String destination, String payload) { SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE); headers.setDestination(destination); Message<?> message = MessageBuilder.createMessage(payload.getBytes(StandardCharsets.UTF_8), headers.getMessageHeaders()); return new MessageExchangeBuilder(message); } public static MessageExchangeBuilder disconnectWithReceipt(String sessionId, String receiptId) { StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.DISCONNECT); headers.setSessionId(sessionId); headers.setReceipt(receiptId); Message<?> message = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders()); MessageExchangeBuilder builder = new MessageExchangeBuilder(message); builder.expected.add(new StompReceiptFrameMessageMatcher(sessionId, receiptId)); return builder; } public MessageExchangeBuilder andExpectMessage(String sessionId, String subscriptionId) { Assert.state(SimpMessageType.MESSAGE.equals(this.headers.getMessageType()), "MESSAGE type expected"); String destination = this.headers.getDestination(); Object payload = this.message.getPayload(); this.expected.add(new StompMessageFrameMessageMatcher(sessionId, subscriptionId, destination, payload)); return this; } public MessageExchangeBuilder andExpectError() { String sessionId = this.headers.getSessionId(); Assert.state(sessionId != null, "No sessionId to match the ERROR frame to"); return andExpectError(sessionId); } public MessageExchangeBuilder andExpectError(String sessionId) { this.expected.add(new StompFrameMessageMatcher(StompCommand.ERROR, sessionId)); return this; } public MessageExchange build() { return new MessageExchange(this.message, this.expected.toArray(new MessageMatcher[this.expected.size()])); } } private interface MessageMatcher { boolean match(Message<?> message); } private static class StompFrameMessageMatcher implements MessageMatcher { private final StompCommand command; private final String sessionId; public StompFrameMessageMatcher(StompCommand command, String sessionId) { this.command = command; this.sessionId = sessionId; } @Override public final boolean match(Message<?> message) { StompHeaderAccessor headers = StompHeaderAccessor.wrap(message); if (!this.command.equals(headers.getCommand()) || (this.sessionId != headers.getSessionId())) { return false; } return matchInternal(headers, message.getPayload()); } protected boolean matchInternal(StompHeaderAccessor headers, Object payload) { return true; } @Override public String toString() { return "command=" + this.command + ", session=\"" + this.sessionId + "\""; } } private static class StompReceiptFrameMessageMatcher extends StompFrameMessageMatcher { private final String receiptId; public StompReceiptFrameMessageMatcher(String sessionId, String receipt) { super(StompCommand.RECEIPT, sessionId); this.receiptId = receipt; } @Override protected boolean matchInternal(StompHeaderAccessor headers, Object payload) { return (this.receiptId.equals(headers.getReceiptId())); } @Override public String toString() { return super.toString() + ", receiptId=\"" + this.receiptId + "\""; } } private static class StompMessageFrameMessageMatcher extends StompFrameMessageMatcher { private final String subscriptionId; private final String destination; private final Object payload; public StompMessageFrameMessageMatcher(String sessionId, String subscriptionId, String destination, Object payload) { super(StompCommand.MESSAGE, sessionId); this.subscriptionId = subscriptionId; this.destination = destination; this.payload = payload; } @Override protected boolean matchInternal(StompHeaderAccessor headers, Object payload) { if (!this.subscriptionId.equals(headers.getSubscriptionId()) || !this.destination.equals(headers.getDestination())) { return false; } if (payload instanceof byte[] && this.payload instanceof byte[]) { return Arrays.equals((byte[]) payload, (byte[]) this.payload); } else { return this.payload.equals(payload); } } @Override public String toString() { return super.toString() + ", subscriptionId=\"" + this.subscriptionId + "\", destination=\"" + this.destination + "\", payload=\"" + getPayloadAsText() + "\""; } protected String getPayloadAsText() { return (this.payload instanceof byte[]) ? new String((byte[]) this.payload, StandardCharsets.UTF_8) : this.payload.toString(); } } private static class StompConnectedFrameMessageMatcher extends StompFrameMessageMatcher { public StompConnectedFrameMessageMatcher(String sessionId) { super(StompCommand.CONNECTED, sessionId); } } }
924330544675a8481b7ff07c7460ebc26cb1e0ce
1,293
java
Java
ontrack-web/src/main/java/net/ontrack/web/support/fm/FnSecSubscriber.java
joansmith2/ontrack
ef31174d0310a35cbb011a950e1a7d81552cf216
[ "MIT" ]
null
null
null
ontrack-web/src/main/java/net/ontrack/web/support/fm/FnSecSubscriber.java
joansmith2/ontrack
ef31174d0310a35cbb011a950e1a7d81552cf216
[ "MIT" ]
null
null
null
ontrack-web/src/main/java/net/ontrack/web/support/fm/FnSecSubscriber.java
joansmith2/ontrack
ef31174d0310a35cbb011a950e1a7d81552cf216
[ "MIT" ]
null
null
null
34.945946
98
0.723125
1,002,568
package net.ontrack.web.support.fm; import freemarker.template.TemplateMethodModel; import freemarker.template.TemplateModelException; import net.ontrack.core.model.Account; import net.ontrack.core.security.SecurityUtils; import net.ontrack.service.SubscriptionService; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import java.util.List; public class FnSecSubscriber implements TemplateMethodModel { private final SecurityUtils securityUtils; private final SubscriptionService subscriptionService; public FnSecSubscriber(SecurityUtils securityUtils, SubscriptionService subscriptionService) { this.securityUtils = securityUtils; this.subscriptionService = subscriptionService; } @Override public Object exec(List list) throws TemplateModelException { // Checks Validate.notNull(list, "List of arguments is required"); Validate.isTrue(list.size() == 0, "No argument is needed"); // Gets the current user Account account = securityUtils.getCurrentAccount(); // Test return account != null && account.getId() != 0 && StringUtils.isNotBlank(account.getEmail()) && subscriptionService.isEnabled(); } }
9243309a0ebf9b5eddbc61c871ee12c783e399d7
723
java
Java
cavy-manage/src/main/java/com/jh/cavy/manage/mapper/RoleMapper.java
jeffxjh/cavy-backend
ce12fa3fdfc8da3f336053c0dde5871c046d9c86
[ "Apache-2.0" ]
1
2021-09-11T02:58:42.000Z
2021-09-11T02:58:42.000Z
cavy-manage/src/main/java/com/jh/cavy/manage/mapper/RoleMapper.java
jeffxjh/cavy-backend
ce12fa3fdfc8da3f336053c0dde5871c046d9c86
[ "Apache-2.0" ]
null
null
null
cavy-manage/src/main/java/com/jh/cavy/manage/mapper/RoleMapper.java
jeffxjh/cavy-backend
ce12fa3fdfc8da3f336053c0dde5871c046d9c86
[ "Apache-2.0" ]
null
null
null
34.428571
250
0.781466
1,002,569
package com.jh.cavy.manage.mapper; import com.baomidou.mybatisplus.core.conditions.Wrapper;import com.baomidou.mybatisplus.core.toolkit.Constants;import com.jh.cavy.manage.domain.Role;import com.jh.cavy.manage.vo.RoleVO;import org.apache.ibatis.annotations.Param;import java.util.List; public interface RoleMapper { int deleteByPrimaryKey(Integer id); int insert(Role record); int insertSelective(Role record); Role selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(Role record); int updateByPrimaryKey(Role record); List<RoleVO> getRoleByUserId(@Param("userName") String userName); List<RoleVO> getRoleByMenuId(@Param(Constants.WRAPPER) Wrapper<Role> queryWrapper); }
924331572169ef5252ebdf1083b653989a02296f
281
java
Java
POC/atma/src/main/java/org/slc/sli/ingestion/streaming/ReferenceValidator.java
jstokes/secure-data-service
94ae9df1c2a46b3555cdee5779929f48405f788d
[ "Apache-2.0" ]
null
null
null
POC/atma/src/main/java/org/slc/sli/ingestion/streaming/ReferenceValidator.java
jstokes/secure-data-service
94ae9df1c2a46b3555cdee5779929f48405f788d
[ "Apache-2.0" ]
null
null
null
POC/atma/src/main/java/org/slc/sli/ingestion/streaming/ReferenceValidator.java
jstokes/secure-data-service
94ae9df1c2a46b3555cdee5779929f48405f788d
[ "Apache-2.0" ]
null
null
null
25.545455
67
0.786477
1,002,570
package org.slc.sli.ingestion.streaming; import java.util.Set; import org.apache.commons.lang3.tuple.Pair; public interface ReferenceValidator { public void addForValidation(String elementName, String value); public Set<Pair<String, String>> getRemainingReferences(); }
924331aab5376ba44151302f5f9dd5695ef027d3
185
java
Java
app/src/main/java/com/example/bozhilun/android/w30s/carema/OnAlbumItemClickListener.java
18271261642/RaceFitPro
8487da3a9cea4eefed27c727e02fc6786a91b603
[ "Apache-2.0" ]
1
2020-02-02T17:46:00.000Z
2020-02-02T17:46:00.000Z
app/src/main/java/com/example/bozhilun/android/w30s/carema/OnAlbumItemClickListener.java
18271261642/RaceFitPro
8487da3a9cea4eefed27c727e02fc6786a91b603
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/bozhilun/android/w30s/carema/OnAlbumItemClickListener.java
18271261642/RaceFitPro
8487da3a9cea4eefed27c727e02fc6786a91b603
[ "Apache-2.0" ]
2
2019-10-11T15:54:59.000Z
2021-05-13T03:01:23.000Z
16.818182
49
0.745946
1,002,571
package com.example.bozhilun.android.w30s.carema; /** * Created by Administrator on 2018/3/31. */ public interface OnAlbumItemClickListener { void doItemClick(int position); }
924331c93e2efa363a9b18244d6140346eb894c6
443
java
Java
legacy-core/src/main/java/de/ollie/archimedes/alexandrian/service/so/ColumnMetaInfo.java
greifentor/archimedes-legacy
32eac85cba6e82b2c2001b339cb6af20b11799b9
[ "Apache-2.0" ]
null
null
null
legacy-core/src/main/java/de/ollie/archimedes/alexandrian/service/so/ColumnMetaInfo.java
greifentor/archimedes-legacy
32eac85cba6e82b2c2001b339cb6af20b11799b9
[ "Apache-2.0" ]
27
2021-03-11T13:09:39.000Z
2021-11-19T07:14:13.000Z
legacy-core/src/main/java/de/ollie/archimedes/alexandrian/service/so/ColumnMetaInfo.java
greifentor/archimedes-legacy
32eac85cba6e82b2c2001b339cb6af20b11799b9
[ "Apache-2.0" ]
null
null
null
19.26087
73
0.717833
1,002,573
package de.ollie.archimedes.alexandrian.service.so; import java.util.ArrayList; import java.util.List; import lombok.Data; import lombok.Generated; import lombok.experimental.Accessors; /** * A container for table meta information like stereo types and options. * * @author ollie * */ @Accessors(chain = true) @Data @Generated public class ColumnMetaInfo { private List<OptionSO> options = new ArrayList<>(); }
924334f19a4f748e209bcdede48326fba317c6ce
1,492
java
Java
confectory-core/src/main/java/net/obvj/confectory/helper/NullConfigurationHelper.java
JaffarDev/confectory
8fae96dce6b538aa3c64830504a40383225bc26b
[ "Apache-2.0" ]
null
null
null
confectory-core/src/main/java/net/obvj/confectory/helper/NullConfigurationHelper.java
JaffarDev/confectory
8fae96dce6b538aa3c64830504a40383225bc26b
[ "Apache-2.0" ]
null
null
null
confectory-core/src/main/java/net/obvj/confectory/helper/NullConfigurationHelper.java
JaffarDev/confectory
8fae96dce6b538aa3c64830504a40383225bc26b
[ "Apache-2.0" ]
null
null
null
18.419753
87
0.575737
1,002,574
package net.obvj.confectory.helper; import java.util.Optional; /** * A "no-op" Configuration Helper object for situations where an optional configuration * object is not available. * * @param <T> the source type which configuration data is to be retrieved * * @author oswaldo.bapvic.jr (Oswaldo Junior) * @since 0.1.0 */ public class NullConfigurationHelper<T> implements ConfigurationHelper<T> { /** * @return {@link Optional#empty()}, always */ @Override public Optional<T> getBean() { return Optional.empty(); } /** * @return {@code false}, always */ @Override public boolean getBooleanProperty(String key) { return false; } /** * @return {@code 0}, always */ @Override public int getIntProperty(String key) { return 0; } /** * @return {@code 0L}, always */ @Override public long getLongProperty(String key) { return 0L; } /** * @return {@code 0D}, always */ @Override public double getDoubleProperty(String key) { return 0.0; } /** * @return an empty string ({@code ""}), always */ @Override public String getStringProperty(String key) { return ""; } /** * @return {@link Optional#empty()}, always */ @Override public Optional<String> getOptionalStringProperty(String key) { return Optional.empty(); } }
924335809d4466fa6d243c47a8cb4449f283026b
13,841
java
Java
MyCassandra-0.2.1/src/java/org/apache/cassandra/db/RowMutation.java
sunsuk7tp/MyCassandra
5da67c4ab57a0a581e2ce639fb512b144a4bb203
[ "Apache-2.0" ]
4
2015-01-10T01:49:23.000Z
2019-12-22T07:59:06.000Z
MyCassandra-0.2.1/src/java/org/apache/cassandra/db/RowMutation.java
sunsuk7tp/MyCassandra
5da67c4ab57a0a581e2ce639fb512b144a4bb203
[ "Apache-2.0" ]
null
null
null
MyCassandra-0.2.1/src/java/org/apache/cassandra/db/RowMutation.java
sunsuk7tp/MyCassandra
5da67c4ab57a0a581e2ce639fb512b144a4bb203
[ "Apache-2.0" ]
4
2015-09-30T23:00:33.000Z
2019-05-08T05:54:44.000Z
35.489744
136
0.625677
1,002,575
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.db; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.ExecutionException; import org.apache.commons.lang.StringUtils; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.db.filter.QueryPath; import org.apache.cassandra.io.ICompactSerializer; import org.apache.cassandra.io.util.DataOutputBuffer; import org.apache.cassandra.net.Message; import org.apache.cassandra.service.StorageService; import org.apache.cassandra.thrift.ColumnOrSuperColumn; import org.apache.cassandra.thrift.Deletion; import org.apache.cassandra.thrift.Mutation; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.FBUtilities; public class RowMutation { private static RowMutationSerializer serializer_ = new RowMutationSerializer(); public static final String HINT = "HINT"; public static final String FORWARD_HEADER = "FORWARD"; public static RowMutationSerializer serializer() { return serializer_; } private String table_; private ByteBuffer key_; // map of column family id to mutations for that column family. protected Map<Integer, ColumnFamily> modifications_ = new HashMap<Integer, ColumnFamily>(); public RowMutation(String table, ByteBuffer key) { table_ = table; key_ = key; } public RowMutation(String table, Row row) { table_ = table; key_ = row.key.key; add(row.cf); } protected RowMutation(String table, ByteBuffer key, Map<Integer, ColumnFamily> modifications) { table_ = table; key_ = key; modifications_ = modifications; } public String getTable() { return table_; } public ByteBuffer key() { return key_; } public Collection<ColumnFamily> getColumnFamilies() { return modifications_.values(); } void addHints(RowMutation rm) throws IOException { for (ColumnFamily cf : rm.getColumnFamilies()) { ByteBuffer combined = HintedHandOffManager.makeCombinedName(rm.getTable(), cf.metadata().cfName); QueryPath path = new QueryPath(HintedHandOffManager.HINTS_CF, rm.key(), combined); add(path, ByteBufferUtil.EMPTY_BYTE_BUFFER, System.currentTimeMillis(), cf.metadata().getGcGraceSeconds()); } } /* * Specify a column family name and the corresponding column * family object. * param @ cf - column family name * param @ columnFamily - the column family. */ public void add(ColumnFamily columnFamily) { assert columnFamily != null; ColumnFamily prev = modifications_.put(columnFamily.id(), columnFamily); if (prev != null) // developer error throw new IllegalArgumentException("ColumnFamily " + columnFamily + " already has modifications in this mutation: " + prev); } public boolean isEmpty() { return modifications_.isEmpty(); } /* * Specify a column name and a corresponding value for * the column. Column name is specified as <column family>:column. * This will result in a ColumnFamily associated with * <column family> as name and a Column with <column> * as name. The column can be further broken up * as super column name : columnname in case of super columns * * param @ cf - column name as <column family>:<column> * param @ value - value associated with the column * param @ timestamp - timestamp associated with this data. * param @ timeToLive - ttl for the column, 0 for standard (non expiring) columns */ public void add(QueryPath path, ByteBuffer value, long timestamp, int timeToLive) { Integer id = CFMetaData.getId(table_, path.columnFamilyName); ColumnFamily columnFamily = modifications_.get(id); if (columnFamily == null) { columnFamily = ColumnFamily.create(table_, path.columnFamilyName); modifications_.put(id, columnFamily); } columnFamily.addColumn(path, value, timestamp, timeToLive); } public void add(QueryPath path, ByteBuffer value, long timestamp) { add(path, value, timestamp, 0); } public void delete(QueryPath path, long timestamp) { Integer id = CFMetaData.getId(table_, path.columnFamilyName); int localDeleteTime = (int) (System.currentTimeMillis() / 1000); ColumnFamily columnFamily = modifications_.get(id); if (columnFamily == null) { columnFamily = ColumnFamily.create(table_, path.columnFamilyName); modifications_.put(id, columnFamily); } if (path.superColumnName == null && path.columnName == null) { columnFamily.delete(localDeleteTime, timestamp); } else if (path.columnName == null) { SuperColumn sc = new SuperColumn(path.superColumnName, columnFamily.getSubComparator()); sc.markForDeleteAt(localDeleteTime, timestamp); columnFamily.addColumn(sc); } else { columnFamily.addTombstone(path, localDeleteTime, timestamp); } } /* * This is equivalent to calling commit. Applies the changes to * to the table that is obtained by calling Table.open(). */ public void apply() throws IOException { if (DatabaseDescriptor.isBigtable(table_)) Table.open(table_).apply(this, getSerializedBuffer(), true); else applyUnsafe(); } /** * Apply without touching the commitlog. For testing. */ public void applyUnsafe() throws IOException { Table.open(table_).apply(this, getSerializedBuffer(), false); } /* * This is equivalent to calling commit. Applies the changes to * to the table that is obtained by calling Table.open(). */ void applyBinary() throws IOException, ExecutionException, InterruptedException { Table.open(table_).load(this); } public Message makeRowMutationMessage() throws IOException { return makeRowMutationMessage(StorageService.Verb.MUTATION); } public Message makeRowMutationMessage(StorageService.Verb verb) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); serializer().serialize(this, dos); return new Message(FBUtilities.getLocalAddress(), verb, bos.toByteArray()); } public static RowMutation getRowMutationFromMutations(String keyspace, ByteBuffer key, Map<String, List<Mutation>> cfmap) { RowMutation rm = new RowMutation(keyspace, key); for (Map.Entry<String, List<Mutation>> entry : cfmap.entrySet()) { String cfName = entry.getKey(); for (Mutation mutation : entry.getValue()) { if (mutation.deletion != null) { deleteColumnOrSuperColumnToRowMutation(rm, cfName, mutation.deletion); } else { addColumnOrSuperColumnToRowMutation(rm, cfName, mutation.column_or_supercolumn); } } } return rm; } public static RowMutation getRowMutation(String table, ByteBuffer key, Map<String, List<ColumnOrSuperColumn>> cfmap) { RowMutation rm = new RowMutation(table, key); for (Map.Entry<String, List<ColumnOrSuperColumn>> entry : cfmap.entrySet()) { String cfName = entry.getKey(); for (ColumnOrSuperColumn cosc : entry.getValue()) { if (cosc.column == null) { assert cosc.super_column != null; for (org.apache.cassandra.thrift.Column column : cosc.super_column.columns) { rm.add(new QueryPath(cfName, cosc.super_column.name, column.name), column.value, column.timestamp, column.ttl); } } else { assert cosc.super_column == null; rm.add(new QueryPath(cfName, null, cosc.column.name), cosc.column.value, cosc.column.timestamp, cosc.column.ttl); } } } return rm; } public DataOutputBuffer getSerializedBuffer() throws IOException { DataOutputBuffer buffer = new DataOutputBuffer(); RowMutation.serializer().serialize(this, buffer); return buffer; } public String toString() { return toString(false); } public String toString(boolean shallow) { StringBuilder buff = new StringBuilder("RowMutation("); buff.append("keyspace='").append(table_).append('\''); buff.append(", key='").append(ByteBufferUtil.bytesToHex(key_)).append('\''); buff.append(", modifications=["); if (shallow) { List<String> cfnames = new ArrayList<String>(); for (Integer cfid : modifications_.keySet()) { CFMetaData cfm = DatabaseDescriptor.getCFMetaData(cfid); cfnames.add(cfm == null ? "-dropped-" : cfm.cfName); } buff.append(StringUtils.join(cfnames, ", ")); } else buff.append(StringUtils.join(modifications_.values(), ", ")); return buff.append("])").toString(); } private static void addColumnOrSuperColumnToRowMutation(RowMutation rm, String cfName, ColumnOrSuperColumn cosc) { if (cosc.column == null) { for (org.apache.cassandra.thrift.Column column : cosc.super_column.columns) { rm.add(new QueryPath(cfName, cosc.super_column.name, column.name), column.value, column.timestamp, column.ttl); } } else { rm.add(new QueryPath(cfName, null, cosc.column.name), cosc.column.value, cosc.column.timestamp, cosc.column.ttl); } } private static void deleteColumnOrSuperColumnToRowMutation(RowMutation rm, String cfName, Deletion del) { if (del.predicate != null && del.predicate.column_names != null) { for(ByteBuffer c : del.predicate.column_names) { if (del.super_column == null && DatabaseDescriptor.getColumnFamilyType(rm.table_, cfName) == ColumnFamilyType.Super) rm.delete(new QueryPath(cfName, c), del.timestamp); else rm.delete(new QueryPath(cfName, del.super_column, c), del.timestamp); } } else { rm.delete(new QueryPath(cfName, del.super_column), del.timestamp); } } public RowMutation deepCopy() { RowMutation rm = new RowMutation(table_, ByteBufferUtil.clone(key_)); for (Map.Entry<Integer, ColumnFamily> e : modifications_.entrySet()) { ColumnFamily cf = e.getValue().cloneMeShallow(); for (Map.Entry<ByteBuffer, IColumn> ce : e.getValue().getColumnsMap().entrySet()) cf.addColumn(ce.getValue().deepCopy()); rm.modifications_.put(e.getKey(), cf); } return rm; } public static class RowMutationSerializer implements ICompactSerializer<RowMutation> { public void serialize(RowMutation rm, DataOutputStream dos) throws IOException { dos.writeUTF(rm.getTable()); ByteBufferUtil.writeWithShortLength(rm.key(), dos); /* serialize the modifications_ in the mutation */ int size = rm.modifications_.size(); dos.writeInt(size); if (size > 0) { for (Map.Entry<Integer,ColumnFamily> entry : rm.modifications_.entrySet()) { dos.writeInt(entry.getKey()); ColumnFamily.serializer().serialize(entry.getValue(), dos); } } } public RowMutation deserialize(DataInputStream dis) throws IOException { String table = dis.readUTF(); ByteBuffer key = ByteBufferUtil.readWithShortLength(dis); Map<Integer, ColumnFamily> modifications = new HashMap<Integer, ColumnFamily>(); int size = dis.readInt(); for (int i = 0; i < size; ++i) { Integer cfid = Integer.valueOf(dis.readInt()); ColumnFamily cf = ColumnFamily.serializer().deserialize(dis); modifications.put(cfid, cf); } return new RowMutation(table, key, modifications); } } }
924335b0293c43122acf8e0b80ac6154fe07f854
1,892
java
Java
Backend Units/clubzen/src/main/java/com/clubzen/models/porHolderModel.java
Shreyasi2002/CS253_Project
5076ae40fc6ee8ae78f24cbe5395523ccb8079b7
[ "MIT" ]
null
null
null
Backend Units/clubzen/src/main/java/com/clubzen/models/porHolderModel.java
Shreyasi2002/CS253_Project
5076ae40fc6ee8ae78f24cbe5395523ccb8079b7
[ "MIT" ]
3
2022-03-20T13:31:09.000Z
2022-03-30T09:38:54.000Z
Backend Units/clubzen/src/main/java/com/clubzen/models/porHolderModel.java
Shreyasi2002/CS253_Project
5076ae40fc6ee8ae78f24cbe5395523ccb8079b7
[ "MIT" ]
2
2022-03-20T12:40:42.000Z
2022-03-25T12:55:40.000Z
26.277778
101
0.7574
1,002,576
package com.clubzen.models; import javax.validation.constraints.NotBlank; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.FieldType; import org.springframework.data.mongodb.core.mapping.MongoId; @Document(collection = "porholdersdirectory") public class porHolderModel { public porHolderModel(String id, @NotBlank String councilFestName, @NotBlank String clubSectionName, @NotBlank String positionName, @NotBlank String username) { super(); this.id = id; this.councilFestName = councilFestName; this.clubSectionName = clubSectionName; this.positionName = positionName; this.username = username; } public void porHoldersModel() { } @MongoId(FieldType.OBJECT_ID) private String id; @NotBlank private String councilFestName; @NotBlank private String clubSectionName; @NotBlank private String positionName; @NotBlank private String username; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCouncilFestName() { return councilFestName; } public void setCouncilFestName(String councilFestName) { this.councilFestName = councilFestName; } public String getClubSectionName() { return clubSectionName; } public void setClubSectionName(String clubSectionName) { this.clubSectionName = clubSectionName; } public String getPositionName() { return positionName; } public void setPositionName(String positionName) { this.positionName = positionName; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Override public String toString() { return "porHolderModel [id=" + id + ", councilFestName=" + councilFestName + ", clubSectionName=" + clubSectionName + ", positionName=" + positionName + ", username=" + username + "]"; } }
924335bffd8c44199a56035cba394a5bf009fb01
7,661
java
Java
cpython/src/gen/java/org/bytedeco/cpython/PyASCIIObject.java
oxisto/javacpp-presets
a70841e089cbe4269cd3e1b1e6de2005c3b4aa16
[ "Apache-2.0" ]
2,132
2015-01-14T10:02:38.000Z
2022-03-31T07:51:08.000Z
cpython/src/gen/java/org/bytedeco/cpython/PyASCIIObject.java
oxisto/javacpp-presets
a70841e089cbe4269cd3e1b1e6de2005c3b4aa16
[ "Apache-2.0" ]
1,024
2015-01-11T18:35:03.000Z
2022-03-31T14:52:22.000Z
cpython/src/gen/java/org/bytedeco/cpython/PyASCIIObject.java
oxisto/javacpp-presets
a70841e089cbe4269cd3e1b1e6de2005c3b4aa16
[ "Apache-2.0" ]
759
2015-01-15T08:41:48.000Z
2022-03-29T17:05:57.000Z
45.064706
161
0.643389
1,002,577
// Targeted by JavaCPP version 1.5.7-SNAPSHOT: DO NOT EDIT THIS FILE package org.bytedeco.cpython; import java.nio.*; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.annotation.*; import static org.bytedeco.javacpp.presets.javacpp.*; import static org.bytedeco.cpython.global.python.*; /* --- Unicode Type ------------------------------------------------------- */ /* ASCII-only strings created through PyUnicode_New use the PyASCIIObject structure. state.ascii and state.compact are set, and the data immediately follow the structure. utf8_length and wstr_length can be found in the length field; the utf8 pointer is equal to the data pointer. */ @Properties(inherit = org.bytedeco.cpython.presets.python.class) public class PyASCIIObject extends Pointer { static { Loader.load(); } /** Default native constructor. */ public PyASCIIObject() { super((Pointer)null); allocate(); } /** Native array allocator. Access with {@link Pointer#position(long)}. */ public PyASCIIObject(long size) { super((Pointer)null); allocateArray(size); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public PyASCIIObject(Pointer p) { super(p); } private native void allocate(); private native void allocateArray(long size); @Override public PyASCIIObject position(long position) { return (PyASCIIObject)super.position(position); } @Override public PyASCIIObject getPointer(long i) { return new PyASCIIObject((Pointer)this).offsetAddress(i); } /* There are 4 forms of Unicode strings: - compact ascii: * structure = PyASCIIObject * test: PyUnicode_IS_COMPACT_ASCII(op) * kind = PyUnicode_1BYTE_KIND * compact = 1 * ascii = 1 * ready = 1 * (length is the length of the utf8 and wstr strings) * (data starts just after the structure) * (since ASCII is decoded from UTF-8, the utf8 string are the data) - compact: * structure = PyCompactUnicodeObject * test: PyUnicode_IS_COMPACT(op) && !PyUnicode_IS_ASCII(op) * kind = PyUnicode_1BYTE_KIND, PyUnicode_2BYTE_KIND or PyUnicode_4BYTE_KIND * compact = 1 * ready = 1 * ascii = 0 * utf8 is not shared with data * utf8_length = 0 if utf8 is NULL * wstr is shared with data and wstr_length=length if kind=PyUnicode_2BYTE_KIND and sizeof(wchar_t)=2 or if kind=PyUnicode_4BYTE_KIND and sizeof(wchar_t)=4 * wstr_length = 0 if wstr is NULL * (data starts just after the structure) - legacy string, not ready: * structure = PyUnicodeObject * test: kind == PyUnicode_WCHAR_KIND * length = 0 (use wstr_length) * hash = -1 * kind = PyUnicode_WCHAR_KIND * compact = 0 * ascii = 0 * ready = 0 * interned = SSTATE_NOT_INTERNED * wstr is not NULL * data.any is NULL * utf8 is NULL * utf8_length = 0 - legacy string, ready: * structure = PyUnicodeObject structure * test: !PyUnicode_IS_COMPACT(op) && kind != PyUnicode_WCHAR_KIND * kind = PyUnicode_1BYTE_KIND, PyUnicode_2BYTE_KIND or PyUnicode_4BYTE_KIND * compact = 0 * ready = 1 * data.any is not NULL * utf8 is shared and utf8_length = length with data.any if ascii = 1 * utf8_length = 0 if utf8 is NULL * wstr is shared with data.any and wstr_length = length if kind=PyUnicode_2BYTE_KIND and sizeof(wchar_t)=2 or if kind=PyUnicode_4BYTE_KIND and sizeof(wchar_4)=4 * wstr_length = 0 if wstr is NULL Compact strings use only one memory block (structure + characters), whereas legacy strings use one block for the structure and one block for characters. Legacy strings are created by PyUnicode_FromUnicode() and PyUnicode_FromStringAndSize(NULL, size) functions. They become ready when PyUnicode_READY() is called. See also _PyUnicode_CheckConsistency(). */ public native @ByRef PyObject ob_base(); public native PyASCIIObject ob_base(PyObject setter); public native @Cast("Py_ssize_t") long length(); public native PyASCIIObject length(long setter); /* Number of code points in the string */ public native @Cast("Py_hash_t") long hash(); public native PyASCIIObject hash(long setter); /* Hash value; -1 if not set */ /* SSTATE_NOT_INTERNED (0) SSTATE_INTERNED_MORTAL (1) SSTATE_INTERNED_IMMORTAL (2) If interned != SSTATE_NOT_INTERNED, the two references from the dictionary to this object are *not* counted in ob_refcnt. */ @Name("state.interned") public native @Cast("unsigned int") @NoOffset int state_interned(); public native PyASCIIObject state_interned(int setter); /* Character size: - PyUnicode_WCHAR_KIND (0): * character type = wchar_t (16 or 32 bits, depending on the platform) - PyUnicode_1BYTE_KIND (1): * character type = Py_UCS1 (8 bits, unsigned) * all characters are in the range U+0000-U+00FF (latin1) * if ascii is set, all characters are in the range U+0000-U+007F (ASCII), otherwise at least one character is in the range U+0080-U+00FF - PyUnicode_2BYTE_KIND (2): * character type = Py_UCS2 (16 bits, unsigned) * all characters are in the range U+0000-U+FFFF (BMP) * at least one character is in the range U+0100-U+FFFF - PyUnicode_4BYTE_KIND (4): * character type = Py_UCS4 (32 bits, unsigned) * all characters are in the range U+0000-U+10FFFF * at least one character is in the range U+10000-U+10FFFF */ @Name("state.kind") public native @Cast("unsigned int") @NoOffset int state_kind(); public native PyASCIIObject state_kind(int setter); /* Compact is with respect to the allocation scheme. Compact unicode objects only require one memory block while non-compact objects use one block for the PyUnicodeObject struct and another for its data buffer. */ @Name("state.compact") public native @Cast("unsigned int") @NoOffset int state_compact(); public native PyASCIIObject state_compact(int setter); /* The string only contains characters in the range U+0000-U+007F (ASCII) and the kind is PyUnicode_1BYTE_KIND. If ascii is set and compact is set, use the PyASCIIObject structure. */ @Name("state.ascii") public native @Cast("unsigned int") @NoOffset int state_ascii(); public native PyASCIIObject state_ascii(int setter); /* The ready flag indicates whether the object layout is initialized completely. This means that this is either a compact object, or the data pointer is filled out. The bit is redundant, and helps to minimize the test in PyUnicode_IS_READY(). */ @Name("state.ready") public native @Cast("unsigned int") @NoOffset int state_ready(); public native PyASCIIObject state_ready(int setter); /* Padding to ensure that PyUnicode_DATA() is always aligned to 4 bytes (see issue #19537 on m68k). */ public native @Cast("wchar_t*") Pointer wstr(); public native PyASCIIObject wstr(Pointer setter); /* wchar_t representation (null-terminated) */ }
9243370f3cffb5a63d66ce8ec68c763cf9dd9a3d
3,642
java
Java
qingyun-order/order-service/src/main/java/cn/wwtianmei/qingyun/order/service/impl/OmsOrderServiceImpl.java
javaDer/qingyuns
d3b6bbd0069619b1242860b63788d34dfed63ec7
[ "Apache-2.0" ]
null
null
null
qingyun-order/order-service/src/main/java/cn/wwtianmei/qingyun/order/service/impl/OmsOrderServiceImpl.java
javaDer/qingyuns
d3b6bbd0069619b1242860b63788d34dfed63ec7
[ "Apache-2.0" ]
null
null
null
qingyun-order/order-service/src/main/java/cn/wwtianmei/qingyun/order/service/impl/OmsOrderServiceImpl.java
javaDer/qingyuns
d3b6bbd0069619b1242860b63788d34dfed63ec7
[ "Apache-2.0" ]
null
null
null
39.586957
107
0.700439
1,002,578
package cn.wwtianmei.qingyun.order.service.impl; import cn.hutool.core.date.DateField; import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.IdUtil; import cn.wwtianmei.qingyun.order.api.Constants; import cn.wwtianmei.qingyun.order.api.entity.OmsOrderDto; import cn.wwtianmei.qingyun.order.entity.OmsOrder; import cn.wwtianmei.qingyun.order.entity.SendLog; import cn.wwtianmei.qingyun.order.mapper.OmsOrderMapper; import cn.wwtianmei.qingyun.order.query.OrderQuery; import cn.wwtianmei.qingyun.order.service.OmsOrderService; import cn.wwtianmei.qingyun.order.service.SendLogService; import cn.wwtianmei.qingyun.product.api.entity.PmsProductDto; import cn.wwtianmei.qingyun.product.api.service.ProductServiceApi; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import lombok.extern.slf4j.Slf4j; import org.apache.dubbo.config.annotation.Reference; import org.springframework.amqp.rabbit.connection.CorrelationData; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Date; /** * 订单表(OmsOrder)表服务实现类 * * @author makejava * @since 2020-03-05 00:08:39 */ @Slf4j @Service("omsOrderService") public class OmsOrderServiceImpl extends ServiceImpl<OmsOrderMapper, OmsOrder> implements OmsOrderService { @Autowired private RabbitTemplate rabbitTemplate; @Autowired private SendLogService logService; @Autowired private OmsOrderMapper orderMapper; @Reference ProductServiceApi productApi; @Override @Transactional(rollbackFor = Exception.class) public Boolean saveOrder(OrderQuery orderQuery) { //查看商品 PmsProductDto pmsProductDto = queryProduct(orderQuery.getProductId()); OmsOrder order = new OmsOrder(); BeanUtils.copyProperties(orderQuery, order); order.setCommentTime(new Date()); order.setCreateTime(new Date()); int insert = this.orderMapper.insert(order); if (insert > 0) { OmsOrder omsOrder = orderMapper.selectById(order.getId()); OmsOrderDto orderDto = new OmsOrderDto(); BeanUtils.copyProperties(omsOrder, orderDto); orderDto.setProductId(pmsProductDto.getId() + ""); log.info("omsOrder:{}", omsOrder); String msgId = IdUtil.fastSimpleUUID(); SendLog logs = SendLog.builder() .count(1) .createTime(new Date()) .msgId(msgId) .exchange(Constants.PMS_ORDER_EXCHANGE_NAME) .status(Constants.MSG_DELIVERING) .routeKey(Constants.PMS_ORDER_ROUTING_KEY_NAME) .orderId(orderDto.getId() + "") .tryTime(DateUtil.offset(new Date(), DateField.MINUTE, Constants.MSG_TIMEOUT)) .build(); this.logService.save(logs); rabbitTemplate.convertAndSend(Constants.PMS_ORDER_EXCHANGE_NAME, Constants.PMS_ORDER_ROUTING_KEY_NAME, orderDto, new CorrelationData(msgId)); log.info(order.toString()); return Boolean.TRUE; } return Boolean.FALSE; } @Override public OmsOrder selectByOrderId(Long id) { return this.orderMapper.selectById(id); } private PmsProductDto queryProduct(Long id) { PmsProductDto productDto = productApi.queryById(id); return productDto; } }