hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
|---|---|---|---|---|---|
dc2613a5a511645b9a93449d35a9aabc5c639dc2
| 486
|
package ShadowSiren.cards.abstractCards;
import IconsAddon.util.DamageModifierManager;
import ShadowSiren.damageModifiers.ElementallyInert;
public abstract class AbstractInertCard extends AbstractDynamicCard {
public AbstractInertCard(String id, String img, int cost, CardType type, CardColor color, CardRarity rarity, CardTarget target) {
super(id, img, cost, type, color, rarity, target);
DamageModifierManager.addModifier(this, new ElementallyInert());
}
}
| 40.5
| 133
| 0.786008
|
b272bea8ffa30035c5b89b3197619a4226a2cc76
| 1,585
|
package xdean.deannotation.checker.processor;
import java.util.Arrays;
import java.util.Set;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import com.google.auto.service.AutoService;
import xdean.annotation.processor.toolkit.AssertException;
import xdean.annotation.processor.toolkit.annotation.SupportedMetaAnnotation;
import xdean.deannotation.checker.CheckModifier;
import xdean.deannotation.checker.processor.common.CheckResult;
import xdean.deannotation.checker.processor.common.CheckResult.Builder;
import xdean.deannotation.checker.processor.common.Checker;
@AutoService(Processor.class)
@SupportedMetaAnnotation(CheckModifier.class)
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class ModifierChecker extends Checker<CheckModifier> {
@Override
public CheckResult check(RoundEnvironment env, CheckModifier cm, AnnotationMirror mid, Element element) throws AssertException {
Builder builder = CheckResult.Builder.create(element);
Set<Modifier> modifiers = element.getModifiers();
Arrays.stream(cm.require())
.forEach(m -> builder.addIf(!modifiers.contains(m), "Modifier required: " + m));
Arrays.stream(cm.forbid())
.forEach(m -> builder.addIf(modifiers.contains(m), "Modifier forbidden: " + m));
return builder.build(cm.message());
}
}
| 40.641026
| 130
| 0.80694
|
1763a722d24d5afa7b6d87f8d2ac2e207e9656be
| 195
|
package ro.adc.hra.employee;
public interface EmployeeServices {
FindEmployeesRs findEmployees(FindEmployeesRq request);
ModifyEmployeesRs modifyEmployees(ModifyEmployeesRq request);
}
| 24.375
| 65
| 0.820513
|
491069d38939f9f6275e200f642b53bb882521f3
| 2,467
|
// Copyright 2016 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.whois;
import static com.google.common.base.Preconditions.checkNotNull;
import static google.registry.model.EppResourceUtils.queryNotDeleted;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.net.InternetDomainName;
import google.registry.model.host.HostResource;
import google.registry.model.registry.Registries;
import java.net.InetAddress;
import org.joda.time.DateTime;
/**
* Represents a WHOIS lookup for a nameserver based on its IP.
*
* <p>Both IPv4 and IPv6 addresses are supported. Unlike other WHOIS commands, this is an eventually
* consistent query.
*
* <p><b>Note:</b> There may be multiple nameservers with the same IP.
*/
final class NameserverLookupByIpCommand implements WhoisCommand {
@VisibleForTesting
final InetAddress ipAddress;
NameserverLookupByIpCommand(InetAddress ipAddress) {
this.ipAddress = checkNotNull(ipAddress, "ipAddress");
}
@Override
public WhoisResponse executeQuery(DateTime now) throws WhoisException {
ImmutableList<HostResource> hosts = FluentIterable
.from(queryNotDeleted(HostResource.class, now, "inetAddresses", ipAddress))
.filter(new Predicate<HostResource>() {
@Override
public boolean apply(final HostResource host) {
return Registries
.findTldForName(InternetDomainName.from(host.getFullyQualifiedHostName()))
.isPresent();
}})
.toList();
if (hosts.isEmpty()) {
throw new WhoisException(now, SC_NOT_FOUND, "No nameservers found.");
}
return new NameserverWhoisResponse(hosts, now);
}
}
| 37.378788
| 100
| 0.748277
|
86a27c64cc67fd111c48e3ffd3562424f983f663
| 1,691
|
/*
* Copyright 2021 Voyta Krizek, https://github.com/NewTownData
*
* 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.newtowndata.maf.event.simple;
import com.newtowndata.maf.event.Event;
import com.newtowndata.maf.event.EventProducer;
import java.net.URI;
import java.time.Clock;
import java.util.UUID;
public class SimpleEventProducer implements EventProducer {
public static final String TYPE_START = "start";
public static final String TYPE_AGENT_REGISTERED = "agent_registered";
public static final String TYPE_ACK = "ack";
public static final String AGENT_URI_PREFIX = "agent:";
public static URI URI_ALL = URI.create("env:all");
public static URI URI_ENVIRONMENT = URI.create("env:env");
public static URI URI_RUNTIME = URI.create("env:runtime");
private final Clock clock;
public SimpleEventProducer(Clock clock) {
this.clock = clock;
}
@Override
public Event create(URI source, URI target, String type, Object data) {
return new Event(UUID.randomUUID().toString(), clock.millis(), source, target, type, data);
}
public static URI createAgentUri(String agentName) {
return URI.create(AGENT_URI_PREFIX + agentName);
}
}
| 33.82
| 100
| 0.749852
|
2048a664939c1c075bf3e18542a3920b2c0f88b5
| 1,821
|
package dto;
import java.math.BigDecimal;
public class UrunYorumSayimDto {
private Long id;
private String urunAdi;
private BigDecimal fiyat;
private Long yorumSayisi;
public UrunYorumSayimDto(Long id, String urunAdi, BigDecimal fiyat, Long yorumSayisi) {
this.id = id;
this.urunAdi = urunAdi;
this.fiyat = fiyat;
this.yorumSayisi = yorumSayisi;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUrunAdi() {
return urunAdi;
}
public void setUrunAdi(String urunAdi) {
this.urunAdi = urunAdi;
}
public BigDecimal getFiyat() {
return fiyat;
}
public void setFiyat(BigDecimal fiyat) {
this.fiyat = fiyat;
}
public Long getYorumSayisi() {
return yorumSayisi;
}
public void setYorumSayisi(Long yorumSayisi) {
this.yorumSayisi = yorumSayisi;
}
public String urunSayimKontrolandToString () {
if(yorumSayisi == 0) {
return "UrunYorumSayimDto{" +
"id=" + id +
", urunAdi='" + urunAdi + '\'' +
", fiyat=" + fiyat +
", yorumSayisi=" + " " +
'}';
}
return "UrunYorumSayimDto{" +
"id=" + id +
", urunAdi='" + urunAdi + '\'' +
", fiyat=" + fiyat +
", yorumSayisi=" + yorumSayisi +
'}';
}
@Override
public String toString() {
return "UrunYorumSayimDto{" +
"id=" + id +
", urunAdi='" + urunAdi + '\'' +
", fiyat=" + fiyat +
", yorumSayisi=" + yorumSayisi +
'}';
}
}
| 23.050633
| 91
| 0.489841
|
8ddb25073787d7347a4fcf133b914b599074914f
| 80
|
package ro.ase.cts.state.clase;
public class StareLibera implements Stare {
}
| 13.333333
| 43
| 0.775
|
35273328e303efe11c2790a835fe05f08fcf5d20
| 15,762
|
package gov.nasa.jpl.aerie.merlin.server.remotes.postgres;
import gov.nasa.jpl.aerie.json.Iso;
import gov.nasa.jpl.aerie.json.JsonParser;
import gov.nasa.jpl.aerie.merlin.driver.ActivityInstanceId;
import gov.nasa.jpl.aerie.merlin.protocol.types.SerializedValue;
import gov.nasa.jpl.aerie.merlin.server.exceptions.NoSuchPlanException;
import gov.nasa.jpl.aerie.merlin.server.http.InvalidEntityException;
import gov.nasa.jpl.aerie.merlin.server.http.InvalidJsonException;
import gov.nasa.jpl.aerie.merlin.server.models.ActivityInstance;
import gov.nasa.jpl.aerie.merlin.server.models.Constraint;
import gov.nasa.jpl.aerie.merlin.server.models.NewPlan;
import gov.nasa.jpl.aerie.merlin.server.models.Plan;
import gov.nasa.jpl.aerie.merlin.server.models.PlanId;
import gov.nasa.jpl.aerie.merlin.server.models.ProfileSet;
import gov.nasa.jpl.aerie.merlin.server.models.Timestamp;
import gov.nasa.jpl.aerie.merlin.server.remotes.MissionModelRepository.NoSuchMissionModelException;
import gov.nasa.jpl.aerie.merlin.server.remotes.PlanRepository;
import org.apache.commons.lang3.NotImplementedException;
import javax.json.Json;
import javax.json.stream.JsonParsingException;
import javax.sql.DataSource;
import java.io.StringReader;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static gov.nasa.jpl.aerie.json.BasicParsers.listP;
import static gov.nasa.jpl.aerie.json.BasicParsers.longP;
import static gov.nasa.jpl.aerie.json.BasicParsers.mapP;
import static gov.nasa.jpl.aerie.json.BasicParsers.productP;
import static gov.nasa.jpl.aerie.json.BasicParsers.stringP;
import static gov.nasa.jpl.aerie.json.Uncurry.tuple;
import static gov.nasa.jpl.aerie.json.Uncurry.untuple;
import static gov.nasa.jpl.aerie.merlin.server.http.MerlinParsers.activityInstanceIdP;
import static gov.nasa.jpl.aerie.merlin.server.http.SerializedValueJsonParser.serializedValueP;
public final class PostgresPlanRepository implements PlanRepository {
private final DataSource dataSource;
public PostgresPlanRepository(final DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public Map<PlanId, Plan> getAllPlans() {
try (final var connection = this.dataSource.getConnection()) {
try (final var getAllPlansAction = new GetAllPlansAction(connection)) {
return getAllPlansAction.get();
}
} catch (final SQLException ex) {
throw new DatabaseException("Failed to get all plans", ex);
}
}
@Override
public Plan getPlan(final PlanId planId) throws NoSuchPlanException {
try (final var connection = this.dataSource.getConnection()) {
try (
final var getSimulationAction = new GetSimulationAction(connection);
final var getSimulationTemplateAction = new GetSimulationTemplateAction(connection);
) {
final var planRecord = getPlanRecord(connection, planId);
final Map<String, SerializedValue> arguments = new HashMap<>();
final var simRecord$ = getSimulationAction.get(planId);
if (simRecord$.isPresent()) {
final var simRecord = simRecord$.get();
final var templateId$ = simRecord.simulationTemplateId();
// Apply template arguments followed by simulation arguments.
// Overwriting of template arguments with sim. arguments is intentional here,
// and the resulting set of arguments is assumed to be complete
if (templateId$.isPresent()) {
getSimulationTemplateAction.get(templateId$.get()).ifPresent(simTemplateRecord -> {
arguments.putAll(simTemplateRecord.arguments());
});
}
arguments.putAll(simRecord.arguments());
}
return new Plan(
planRecord.name(),
Long.toString(planRecord.missionModelId()),
planRecord.startTime(),
planRecord.endTime(),
planRecord.activities(),
arguments
);
}
} catch (final SQLException ex) {
throw new DatabaseException("Failed to get plan", ex);
}
}
@Override
public long getPlanRevision(final PlanId planId) throws NoSuchPlanException {
try (final var connection = this.dataSource.getConnection()) {
try (final var getPlanRevisionAction = new GetPlanRevisionAction(connection)) {
return getPlanRevisionAction.get(planId);
}
} catch (final SQLException ex) {
throw new DatabaseException("Failed to get plan revision", ex);
}
}
@Override
public PostgresPlanRevisionData getPlanRevisionData(final PlanId planId) throws NoSuchPlanException {
try (final var connection = this.dataSource.getConnection()) {
try (final var getPlanRevisionDataAction = new GetPlanRevisionDataAction(connection)) {
return getPlanRevisionDataAction.get(planId)
.orElseThrow(() -> new NoSuchPlanException(planId));
}
} catch (final SQLException ex) {
throw new DatabaseException("Failed to get plan revision data", ex);
}
}
@Override
public Map<ActivityInstanceId, ActivityInstance> getAllActivitiesInPlan(final PlanId planId) throws NoSuchPlanException {
try (final var connection = this.dataSource.getConnection()) {
try (final var getActivitiesAction = new GetActivitiesAction(connection)) {
return getActivitiesAction.get(planId);
}
} catch (final SQLException ex) {
throw new DatabaseException("Failed to get all activities from plan", ex);
}
}
@Override
public CreatedPlan createPlan(final NewPlan plan) throws NoSuchMissionModelException, IntegrationFailureException {
try (
final var connection = this.dataSource.getConnection();
// Rollback the transaction if we throw out of this method.
final var transactionContext = new TransactionContext(connection);
) {
try (
final var createPlanAction = new CreatePlanAction(connection);
final var createActivityAction = new CreateActivityAction(connection);
final var setActivityArgumentsAction = new CreateActivityArgumentsAction(connection)
) {
final PlanId planId = createPlanAction.apply(
plan.name,
toMissionModelId(plan.missionModelId),
plan.startTimestamp,
plan.endTimestamp);
final List<ActivityInstanceId> activityIds;
if (plan.activityInstances == null) {
activityIds = new ArrayList<>();
} else {
activityIds = new ArrayList<>(plan.activityInstances.size());
for (final var activity : plan.activityInstances) {
final var activityId = createActivityAction.apply(
planId,
plan.startTimestamp,
activity.startTimestamp,
activity.type);
for (final var argument : activity.arguments.entrySet()) {
// Add this argument to the staged batch of arguments.
setActivityArgumentsAction.add(activityId, argument.getKey(), argument.getValue());
}
activityIds.add(new ActivityInstanceId(activityId));
}
// Insert all the accumulated arguments for all activities at once.
setActivityArgumentsAction.apply();
}
// Commit our changes so that they become visible to other agents.
transactionContext.commit();
return new CreatedPlan(planId, activityIds);
}
} catch (final SQLException ex) {
throw new DatabaseException("Failed to create a plan", ex);
}
}
@Override
public PlanTransaction updatePlan(final PlanId planId) throws NoSuchPlanException {
return new PostgresPlanTransaction(this.dataSource, planId);
}
@Override
public void deletePlan(final PlanId planId) {
throw new NotImplementedException("If this is needed on the Postgres repository then implement it");
}
@Override
public ActivityInstanceId createActivity(final PlanId planId, final ActivityInstance activity) {
throw new NotImplementedException("If this is needed on the Postgres repository then implement it");
}
@Override
public void deleteAllActivities(final PlanId planId) {
throw new NotImplementedException("If this is needed on the Postgres repository then implement it");
}
@Override
public Map<String, Constraint> getAllConstraintsInPlan(final PlanId planId) throws NoSuchPlanException {
try (final var connection = this.dataSource.getConnection()) {
try (final var getPlanConstraintsAction = new GetPlanConstraintsAction(connection)) {
return getPlanConstraintsAction.get(planId);
}
} catch (final SQLException ex) {
throw new DatabaseException(
"Failed to retrieve constraints for plan with id `%s`".formatted(planId), ex);
}
}
@Override
public long addExternalDataset(
final PlanId planId,
final Timestamp datasetStart,
final ProfileSet profileSet
) throws NoSuchPlanException {
try (final var connection = this.dataSource.getConnection()) {
final var plan = getPlanRecord(connection, planId);
final var planDataset = createPlanDataset(connection, planId, plan.startTime(), datasetStart);
ProfileRepository.postResourceProfiles(
connection,
planDataset.datasetId(),
profileSet,
datasetStart
);
return planDataset.datasetId();
} catch (final SQLException ex) {
throw new DatabaseException(
"Failed to add external dataset to plan with id `%s`".formatted(planId), ex);
}
}
private PlanRecord getPlanRecord(
final Connection connection,
final PlanId planId
) throws SQLException, NoSuchPlanException {
try (final var getPlanAction = new GetPlanAction(connection)) {
return getPlanAction.get(planId);
}
}
// TODO: This functionality is not required for the use-case
// we are addressing at the time of creation, but it
// will be necessary for our future use-cases of associating
// multiple plans with an external dataset. At that time,
// this function should be lifted to the PlanRepository interface
// and hooked up to the merlin bindings
private static void useExternalDataset(
final Connection connection,
final PlanRecord plan,
final long datasetId
) throws SQLException {
associatePlanWithDataset(connection, plan.id(), datasetId, plan.startTime());
}
private static long toMissionModelId(final String modelId)
throws NoSuchMissionModelException
{
try {
return Long.parseLong(modelId, 10);
} catch (final NumberFormatException ex) {
throw new NoSuchMissionModelException();
}
}
private static PlanDatasetRecord createPlanDataset(
final Connection connection,
final PlanId planId,
final Timestamp planStart,
final Timestamp datasetStart
) throws SQLException {
try (final var createPlanDatasetAction = new CreatePlanDatasetAction(connection)) {
return createPlanDatasetAction.apply(planId, planStart, datasetStart);
}
}
private static PlanDatasetRecord associatePlanWithDataset(
final Connection connection,
final PlanId planId,
final long datasetId,
final Timestamp planStart
) throws SQLException {
try (final var associatePlanDatasetAction = new AssociatePlanDatasetAction(connection)) {
return associatePlanDatasetAction.apply(planId, datasetId, planStart);
}
}
/*package-local*/ static Map<ActivityInstanceId, ActivityInstance> parseActivitiesJson(final String json, final Timestamp planStartTime) {
try {
final var activityRowP =
productP
.field("id", activityInstanceIdP)
.field("start_offset_in_micros", longP)
.field("type", stringP)
.field("arguments", mapP(serializedValueP))
.map(Iso.of(
untuple((actId, startOffsetInMicros, type, arguments) ->
tuple(
actId,
new ActivityInstance(type,
planStartTime.plusMicros(startOffsetInMicros),
arguments))),
untuple((ActivityInstanceId actId, ActivityInstance $) ->
tuple(actId, planStartTime.microsUntil($.startTimestamp), $.type, $.arguments))));
final var activities = new HashMap<ActivityInstanceId, ActivityInstance>();
for (final var entry : parseJson(json, listP(activityRowP))) {
activities.put(entry.getKey(), entry.getValue());
}
return activities;
} catch (final InvalidJsonException ex) {
throw new UnexpectedJsonException("The JSON returned from the database has an unexpected structure", ex);
} catch (final InvalidEntityException ex) {
throw new UnexpectedJsonException("The JSON returned from the database is syntactically invalid", ex);
}
}
private static <T> T parseJson(final String subject, final JsonParser<T> parser)
throws InvalidJsonException, InvalidEntityException
{
try {
final var requestJson = Json.createReader(new StringReader(subject)).readValue();
final var result = parser.parse(requestJson);
return result.getSuccessOrThrow($ -> new InvalidEntityException(List.of($)));
} catch (final JsonParsingException ex) {
throw new InvalidJsonException(ex);
}
}
/*package-local*/ static Map<String, SerializedValue> parseActivityArgumentsJson(final String json) {
try {
return parseJson(json, mapP(serializedValueP));
} catch (final InvalidJsonException ex) {
throw new UnexpectedJsonException("The JSON returned from the database has an unexpected structure", ex);
} catch (final InvalidEntityException ex) {
throw new UnexpectedJsonException("The JSON returned from the database is syntactically invalid", ex);
}
}
private static final class PostgresPlanTransaction implements PlanTransaction {
private final DataSource dataSource;
private final PlanId planId;
private Optional<String> name = Optional.empty();
private Optional<Timestamp> startTime = Optional.empty();
private Optional<Timestamp> endTime = Optional.empty();
public PostgresPlanTransaction(final DataSource dataSource, final PlanId planId) {
this.dataSource = dataSource;
this.planId = planId;
}
@Override
public void commit() throws NoSuchPlanException {
try (final var connection = this.dataSource.getConnection()) {
try (final var updatePlanAction = new UpdatePlanAction(connection)) {
updatePlanAction.apply(
this.planId,
this.name.orElse(null),
this.startTime.orElse(null),
this.endTime.orElse(null));
}
} catch (final SQLException ex) {
throw new DatabaseException("Failed to update a plan", ex);
}
}
@Override
public PlanTransaction setName(final String name) {
this.name = Optional.of(name);
return this;
}
@Override
public PlanTransaction setStartTimestamp(final Timestamp timestamp) {
this.startTime = Optional.of(timestamp);
return this;
}
@Override
public PlanTransaction setEndTimestamp(final Timestamp timestamp) {
this.endTime = Optional.of(timestamp);
return this;
}
@Override
public PlanTransaction setConfiguration(final Map<String, SerializedValue> configuration) {
return this;
}
}
}
| 39.014851
| 140
| 0.694645
|
ffed5732558078319db66be363b75bd012b834ff
| 1,951
|
package dangod.themis.controller;
import dangod.themis.controller.base.BaseController;
import dangod.themis.controller.base.annotation.Authorization;
import dangod.themis.core.result.Result;
import dangod.themis.model.vo.MenuVo;
import dangod.themis.service.core.AuthorityService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import static dangod.themis.controller.base.constant.Message.MENU_SUCCESS_MESSAGE;
import static dangod.themis.controller.base.constant.Message.TOKEN_INVAILD_MESSAGE;
import static dangod.themis.controller.base.constant.Status.SUCCESS;
import static dangod.themis.controller.base.constant.Status.UNAUTHORIZED;
import static dangod.themis.controller.base.constant.AnnotationConstant.AUTHORIZATION;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
@CrossOrigin
@RestController
@RequestMapping(value = "/menu")
public class MenuController extends BaseController {
@Autowired
private AuthorityService authorityService;
@RequestMapping(method = GET)
@ApiOperation(value = "获取菜单")
@Authorization
public String listMenu(HttpServletRequest request, HttpServletResponse response,
@RequestHeader(AUTHORIZATION)String token){
long userId=getUserId(request);
List<MenuVo> list = authorityService.getMenuByUserId(userId);
if(list != null)
return Result.send(SUCCESS, list, MENU_SUCCESS_MESSAGE);
else
return Result.send(UNAUTHORIZED, null, TOKEN_INVAILD_MESSAGE);
}
}
| 39.816327
| 86
| 0.798052
|
943a654b7574e968258ab979e0d8f7a8181c0974
| 714
|
package familiar.api.character;
import familiar.service.character.domain.witcher.WitcherCharacter;
import familiar.service.character.service.WitcherCharacterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class CharacterController {
@Autowired
WitcherCharacterService witcherCharacterService;
@GetMapping("/characters")
public WitcherCharacter getCharacters() {
return witcherCharacterService.findWitcherCharacterById(2);
}
}
| 32.454545
| 67
| 0.822129
|
d1c5f15bb74af5e84bdb3f40ac6f52235b6bd1be
| 3,109
|
package xyz.filipfloreani.overlapr.utils;
import android.animation.ArgbEvaluator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.view.View;
import com.github.mikephil.charting.data.Entry;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import io.realm.RealmList;
import xyz.filipfloreani.overlapr.model.RealmChartModel;
import xyz.filipfloreani.overlapr.model.RealmPointModel;
/**
* Created by filipfloreani on 30/03/2017.
*/
public final class GeneralUtils {
private static final SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy 'at' hh:mm:ss 'UTC'");
public static AlertDialog.Builder buildWatchOutDialog(Context context) {
AlertDialog.Builder adBuilder = new AlertDialog.Builder(context);
adBuilder.setTitle("Watch out")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
return adBuilder;
}
public static Date dateFromTimestamp(long seconds) {
if (seconds == -1) {
return null;
}
return new Date(seconds * 1000);
}
public static long toTimestamp(Date date) {
if (date == null) {
return 0;
}
return date.getTime() / 1000;
}
public static Date getUTCNow() {
Calendar calendar = Calendar.getInstance();
int localOffset = TimeZone.getDefault().getOffset(
calendar.getTimeInMillis());
calendar.add(Calendar.MILLISECOND, -localOffset);
return calendar.getTime();
}
public static String formatDate(@NonNull Date date) {
return sdf.format(date);
}
public static long getUTCNowAsTimestamp() {
return toTimestamp(getUTCNow());
}
public static RealmList<RealmPointModel> entriesToChartPoints(List<Entry> dataSet, RealmChartModel chart) {
RealmList<RealmPointModel> realmPoints = new RealmList<>();
for (Entry entry : dataSet) {
RealmPointModel realmPoint = new RealmPointModel(entry.getX(), entry.getY(), chart);
realmPoints.add(realmPoint);
}
return realmPoints;
}
public static void animateBackgroundColorChange(final View view, int colorFrom, int colorTo) {
ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
colorAnimation.setDuration(150);
colorAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
view.setBackgroundColor((int) animation.getAnimatedValue());
}
});
colorAnimation.start();
}
}
| 32.051546
| 111
| 0.673528
|
20349a8668d1abb08def41281f75d60bfb67311b
| 7,965
|
package de.uni_hildesheim.sse.monitoring.runtime.boot;
/**
* Helper class to transfer the values of a monitoring group (also compiled in
* instrumented code) to the recorder. Be careful: Due to the JVM init and load
* process, neither annotation instances nor the global configuration may be
* used here.
*
* @author Holger Eichelberger
* @since 1.00
* @version 1.20
*/
public class MonitoringGroupSettings {
/**
* Stores instances of this class for reuse. As class loading usually
* happens not in parallel, not many instances will be stored here.
*/
private static final ArrayList<MonitoringGroupSettings> POOL
= new ArrayList<MonitoringGroupSettings>(5);
/**
* Contains arbitrary ids for monitoring and grouping.
*
* @since 1.00
*/
private String[] id;
/**
* Returns a combination of debug states for additional information to
* be emitted during monitoring.
*
* @since 1.00
*/
private DebugState[] debugStates;
/**
* Stores the group accounting to be applied. By default this value is set
* to {@link GroupAccountingType#DEFAULT} and, therefore, taken from the
* global configuration.
*
* @since 1.00
*/
private GroupAccountingType gType;
/**
* Stores the resources to be accounted. By default, all resources defined
* in {@link ResourceType} are accounted.
*
* @since 1.00
*/
private ResourceType[] resources;
/**
* Stores the instance identifier kind.
*
* @since 1.20
*/
private InstanceIdentifierKind instanceIdentifierKind;
/**
* Stores whether values in multi groups should be distributed evenly to
* the contained values or whether the entire value should be added to each
* group.
*
* @since 1.00
*/
private BooleanValue distributeValues;
/**
* Stores whether accountable resources of the multi monitoring group
* is authoritative or weather the contained groups should be considered.
*
* @since 1.00
*/
private BooleanValue considerContained;
/**
* Creates a new instance. Prevents creation from outside in order to enable
* pooling.
*
* @since 1.00
*/
private MonitoringGroupSettings() {
clear();
}
/**
* Creates a further instance of this instances (intended as factory method
* to be executed on a prototypical instance).
*
* @return the created instance
*
* @since 1.00
*/
public MonitoringGroupSettings create() {
return new MonitoringGroupSettings();
}
/**
* Cleans the attributes of this instance.
*
* @since 1.00
*/
public void clear() {
id = null;
debugStates = DebugState.DEFAULT;
gType = GroupAccountingType.DEFAULT;
resources = ResourceType.SET_DEFAULT;
distributeValues = BooleanValue.DEFAULT;
considerContained = BooleanValue.DEFAULT;
instanceIdentifierKind = InstanceIdentifierKind.NONE;
}
/**
* Sets the basic values needed for monitoring.
*
* @param id the recorder ids
* @param debugStates the intended debugging flags
* @param gType the group accounting type
* @param resources the accountable resources
* @param instanceIdentifierKind the instance identifier kind
*
* @since 1.20
*/
public void setBasics(String[] id, DebugState[] debugStates,
GroupAccountingType gType, ResourceType[] resources, InstanceIdentifierKind instanceIdentifierKind) {
this.id = id;
this.debugStates = debugStates;
this.gType = gType;
this.resources = resources;
this.instanceIdentifierKind = instanceIdentifierKind;
}
/**
* Sets advanced values for multi monitoring groups.
*
* @param distributeValues whether values should be distributed evenly
* @param considerContained whether accountable resources of contained
* groups should be considered or whether the group is authoritive
*
* @since 1.00
*/
public void setMulti(BooleanValue distributeValues,
BooleanValue considerContained) {
this.distributeValues = distributeValues;
this.considerContained = considerContained;
}
/**
* Contains arbitrary ids for monitoring and grouping.
*
* @return the ids
*
* @since 1.00
*/
public String[] getId() {
return id;
}
/**
* Returns a combination of debug states for additional information to
* be emitted during monitoring.
*
* @return the debugging states
*
* @since 1.00
*/
public DebugState[] getDebugStates() {
return debugStates;
}
/**
* Returns the group accounting to be applied. By default this value is set
* to {@link GroupAccountingType#DEFAULT} and, therefore, taken from the
* global configuration.
*
* @return the accounting type
*
* @since 1.00
*/
public GroupAccountingType getAccountingType() {
return gType;
}
/**
* Returns the resources to be accounted. By default, all resources defined
* in {@link ResourceType} are accounted.
*
* @return the accountable resources
*
* @since 1.00
*/
public ResourceType[] getResources() {
return resources;
}
/**
* Returns the instance identifier kind.
*
* @return the instance identifier kind
*
* @since 1.20
*/
public InstanceIdentifierKind getInstanceIdentifierKind() {
return instanceIdentifierKind;
}
/**
* Returns whether values in multi groups should be distributed evenly to
* the contained values or whether the entire value should be added to each
* group.
*
* @return <code>true</code> if values should be distributed,
* <code>false</code> if not
*
* @since 1.00
*/
public BooleanValue getDistributeValues() {
return distributeValues;
}
/**
* Returns whether accountable resources of the multi monitoring group
* is authoritative or weather the contained groups should be considered.
*
* @return <code>true</code> if the contained groups values should be
* considered, <code>false</code> if the multi group is authoritative
*
* @since 1.00
*/
public BooleanValue getConsiderContained() {
return considerContained;
}
/**
* Returns an instance from the shared pool. This explicit method is needed
* due to problems with javassist and Android.
*
* @return the instance from the pool. This instance has
* to be released by {@link #release(MonitoringGroupSettings)}.
*
* @since SugiBib 1.20
*/
public static final MonitoringGroupSettings getFromPool() {
int size = POOL.size();
MonitoringGroupSettings result;
if (0 == size) {
result = new MonitoringGroupSettings();
} else {
result = POOL.remove(size - 1);
}
return result;
}
/**
* Releases and clears the specified instance
* to the shared pool. This explicit method is needed due to problems
* with javassist and Android.
*
* @param instance the instance to be released (must not be <b>null</b>)
*/
public static final void release(MonitoringGroupSettings instance) {
instance.clear();
POOL.add(instance);
}
}
| 29.609665
| 110
| 0.604394
|
dca31273a2b40d23f77f8131209e8fda81ca2882
| 730
|
package com.nepxion.discovery.plugin.framework.event;
/**
* <p>Title: Nepxion Discovery</p>
* <p>Description: Nepxion Discovery</p>
* <p>Copyright: Copyright (c) 2017-2050</p>
* <p>Company: Nepxion</p>
* @author Haojun Ren
* @version 1.0
*/
import java.io.Serializable;
import com.nepxion.discovery.common.entity.ParameterEntity;
public class ParameterChangeEvent implements Serializable {
private static final long serialVersionUID = 7843872188960155327L;
private ParameterEntity parameterEntity;
public ParameterChangeEvent(ParameterEntity parameterEntity) {
this.parameterEntity = parameterEntity;
}
public ParameterEntity getParameterEntity() {
return parameterEntity;
}
}
| 26.071429
| 70
| 0.741096
|
9ed3ca3777892790981429de71d97a0be99a78ef
| 12,354
|
package com.gempukku.libgdx.graph.shader.field;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.g3d.utils.TextureDescriptor;
import com.badlogic.gdx.utils.JsonValue;
import com.gempukku.libgdx.graph.shader.BasicShader;
import com.gempukku.libgdx.graph.shader.ShaderContext;
import com.gempukku.libgdx.graph.shader.UniformRegistry;
import com.gempukku.libgdx.graph.shader.builder.CommonShaderBuilder;
import com.gempukku.libgdx.graph.shader.builder.FragmentShaderBuilder;
import com.gempukku.libgdx.graph.shader.builder.VertexShaderBuilder;
import com.gempukku.libgdx.graph.shader.node.DefaultFieldOutput;
import com.gempukku.libgdx.graph.shader.node.GraphShaderNodeBuilder;
import com.gempukku.libgdx.graph.shader.property.PropertySource;
public class TextureRegionShaderFieldType implements ShaderFieldType {
@Override
public boolean accepts(Object value) {
return value instanceof com.badlogic.gdx.graphics.g2d.TextureRegion;
}
@Override
public String getShaderType() {
return "vec4";
}
@Override
public Object convert(Object value) {
return value;
}
@Override
public String getName() {
return "TextureRegion";
}
@Override
public boolean isTexture() {
return true;
}
@Override
public GraphShaderNodeBuilder.FieldOutput addAsGlobalUniform(CommonShaderBuilder commonShaderBuilder, JsonValue data, final PropertySource propertySource) {
final String name = propertySource.getPropertyName();
final TextureDescriptor<Texture> textureDescriptor = new TextureDescriptor<>();
if (data.has("minFilter"))
textureDescriptor.minFilter = Texture.TextureFilter.valueOf(data.getString("minFilter"));
if (data.has("magFilter"))
textureDescriptor.magFilter = Texture.TextureFilter.valueOf(data.getString("magFilter"));
if (data.has("uWrap"))
textureDescriptor.uWrap = Texture.TextureWrap.valueOf(data.getString("uWrap"));
if (data.has("vWrap"))
textureDescriptor.vWrap = Texture.TextureWrap.valueOf(data.getString("vWrap"));
String textureVariableName = "u_property_" + propertySource.getPropertyIndex();
String uvTransformVariableName = "u_uvTransform_" + propertySource.getPropertyIndex();
commonShaderBuilder.addUniformVariable(textureVariableName, "sampler2D", true,
new UniformRegistry.UniformSetter() {
@Override
public void set(BasicShader shader, int location, ShaderContext shaderContext) {
Object value = shaderContext.getGlobalProperty(name);
value = propertySource.getValueToUse(value);
if (value == null)
value = new TextureRegion(shader.getDefaultTexture());
textureDescriptor.texture = ((TextureRegion) value).getTexture();
shader.setUniform(location, textureDescriptor);
}
}, "Texture property - " + name);
commonShaderBuilder.addUniformVariable(uvTransformVariableName, "vec4", true,
new UniformRegistry.UniformSetter() {
@Override
public void set(BasicShader shader, int location, ShaderContext shaderContext) {
Object value = shaderContext.getGlobalProperty(name);
value = propertySource.getValueToUse(value);
if (value == null)
value = new TextureRegion(shader.getDefaultTexture());
TextureRegion region = (TextureRegion) value;
shader.setUniform(location,
region.getU(), region.getV(),
region.getU2() - region.getU(),
region.getV2() - region.getV());
}
}, "Texture UV property - " + name);
return new DefaultFieldOutput(getName(), uvTransformVariableName, textureVariableName);
}
@Override
public GraphShaderNodeBuilder.FieldOutput addAsLocalUniform(CommonShaderBuilder commonShaderBuilder, JsonValue data, final PropertySource propertySource) {
final String name = propertySource.getPropertyName();
final TextureDescriptor<Texture> textureDescriptor = new TextureDescriptor<>();
if (data.has("minFilter"))
textureDescriptor.minFilter = Texture.TextureFilter.valueOf(data.getString("minFilter"));
if (data.has("magFilter"))
textureDescriptor.magFilter = Texture.TextureFilter.valueOf(data.getString("magFilter"));
if (data.has("uWrap"))
textureDescriptor.uWrap = Texture.TextureWrap.valueOf(data.getString("uWrap"));
if (data.has("vWrap"))
textureDescriptor.vWrap = Texture.TextureWrap.valueOf(data.getString("vWrap"));
String textureVariableName = "u_property_" + propertySource.getPropertyIndex();
String uvTransformVariableName = "u_uvTransform_" + propertySource.getPropertyIndex();
commonShaderBuilder.addUniformVariable(textureVariableName, "sampler2D", false,
new UniformRegistry.UniformSetter() {
@Override
public void set(BasicShader shader, int location, ShaderContext shaderContext) {
Object value = shaderContext.getLocalProperty(name);
value = propertySource.getValueToUse(value);
if (value == null)
value = new TextureRegion(shader.getDefaultTexture());
textureDescriptor.texture = ((TextureRegion) value).getTexture();
shader.setUniform(location, textureDescriptor);
}
}, "Texture property - " + name);
commonShaderBuilder.addUniformVariable(uvTransformVariableName, "vec4", false,
new UniformRegistry.UniformSetter() {
@Override
public void set(BasicShader shader, int location, ShaderContext shaderContext) {
Object value = shaderContext.getLocalProperty(name);
value = propertySource.getValueToUse(value);
if (value == null)
value = new TextureRegion(shader.getDefaultTexture());
TextureRegion region = (TextureRegion) value;
shader.setUniform(location,
region.getU(), region.getV(),
region.getU2() - region.getU(),
region.getV2() - region.getV());
}
}, "Texture UV property - " + name);
return new DefaultFieldOutput(getName(), uvTransformVariableName, textureVariableName);
}
@Override
public GraphShaderNodeBuilder.FieldOutput addAsVertexAttribute(VertexShaderBuilder vertexShaderBuilder, JsonValue data, final PropertySource propertySource) {
final TextureDescriptor<Texture> textureDescriptor = new TextureDescriptor<>();
if (data.has("minFilter"))
textureDescriptor.minFilter = Texture.TextureFilter.valueOf(data.getString("minFilter"));
if (data.has("magFilter"))
textureDescriptor.magFilter = Texture.TextureFilter.valueOf(data.getString("magFilter"));
if (data.has("uWrap"))
textureDescriptor.uWrap = Texture.TextureWrap.valueOf(data.getString("uWrap"));
if (data.has("vWrap"))
textureDescriptor.vWrap = Texture.TextureWrap.valueOf(data.getString("vWrap"));
String textureVariableName = "u_property_" + propertySource.getPropertyIndex();
String uvTransformAttributeName = "a_property_" + propertySource.getPropertyIndex();
vertexShaderBuilder.addUniformVariable(textureVariableName, "sampler2D", false,
new UniformRegistry.UniformSetter() {
@Override
public void set(BasicShader shader, int location, ShaderContext shaderContext) {
Object value = propertySource.getPropertyName();
value = propertySource.getValueToUse(value);
if (value == null)
value = new TextureRegion(shader.getDefaultTexture());
textureDescriptor.texture = ((TextureRegion) value).getTexture();
shader.setUniform(location, textureDescriptor);
}
}, "Texture property - " + propertySource.getPropertyName());
vertexShaderBuilder.addAttributeVariable(new VertexAttribute(1024, 4, uvTransformAttributeName), "vec4", "TextureUV property - " + propertySource.getPropertyName());
return new DefaultFieldOutput(ShaderFieldType.TextureRegion, uvTransformAttributeName, textureVariableName);
}
@Override
public GraphShaderNodeBuilder.FieldOutput addAsFragmentAttribute(VertexShaderBuilder vertexShaderBuilder, FragmentShaderBuilder fragmentShaderBuilder, JsonValue data, final PropertySource propertySource) {
final TextureDescriptor<Texture> textureDescriptor = new TextureDescriptor<>();
if (data.has("minFilter"))
textureDescriptor.minFilter = Texture.TextureFilter.valueOf(data.getString("minFilter"));
if (data.has("magFilter"))
textureDescriptor.magFilter = Texture.TextureFilter.valueOf(data.getString("magFilter"));
if (data.has("uWrap"))
textureDescriptor.uWrap = Texture.TextureWrap.valueOf(data.getString("uWrap"));
if (data.has("vWrap"))
textureDescriptor.vWrap = Texture.TextureWrap.valueOf(data.getString("vWrap"));
String textureVariableName = "u_property_" + propertySource.getPropertyIndex();
String uvTransformAttributeName = "a_property_" + propertySource.getPropertyIndex();
String uvTransformVariableName = "v_property_" + propertySource.getPropertyIndex();
fragmentShaderBuilder.addUniformVariable(textureVariableName, "sampler2D", false,
new UniformRegistry.UniformSetter() {
@Override
public void set(BasicShader shader, int location, ShaderContext shaderContext) {
Object value = shaderContext.getLocalProperty(propertySource.getPropertyName());
value = propertySource.getValueToUse(value);
if (value == null)
value = new TextureRegion(shader.getDefaultTexture());
textureDescriptor.texture = ((TextureRegion) value).getTexture();
shader.setUniform(location, textureDescriptor);
}
}, "Texture property - " + propertySource.getPropertyName());
vertexShaderBuilder.addAttributeVariable(new VertexAttribute(1024, 4, uvTransformAttributeName), "vec4", "TextureUV property - " + propertySource.getPropertyName());
if (!vertexShaderBuilder.hasVaryingVariable(uvTransformVariableName)) {
vertexShaderBuilder.addVaryingVariable(uvTransformVariableName, "vec4");
vertexShaderBuilder.addMainLine(uvTransformVariableName + " = " + uvTransformAttributeName + ";");
fragmentShaderBuilder.addVaryingVariable(uvTransformVariableName, "vec4");
}
return new DefaultFieldOutput(ShaderFieldType.TextureRegion, uvTransformVariableName, textureVariableName);
}
@Override
public void setValueInAttributesArray(float[] vertices, int startIndex, Object value) {
TextureRegion region = (TextureRegion) value;
vertices[startIndex + 0] = region.getU();
vertices[startIndex + 1] = region.getV();
vertices[startIndex + 2] = region.getU2() - region.getU();
vertices[startIndex + 3] = region.getV2() - region.getV();
}
@Override
public Object convertFromJson(JsonValue data) {
if (data == null)
return null;
return data.getString("previewPath", null);
}
}
| 55.900452
| 209
| 0.647644
|
bd23267e494f8d29cdf0518dee688deb5c8d60ee
| 267
|
package com.minkov.springbootintro.services.services;
import com.minkov.springbootintro.services.models.BeerServiceModel;
import java.util.List;
public interface BeersService {
List<BeerServiceModel> getBeers();
void createBeer(String name);
}
| 22.25
| 68
| 0.764045
|
5229969dd0476459711ede80c98bed97ceb3edf0
| 189
|
package pay.src.homeclean;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface PaymentRepository extends PagingAndSortingRepository<Payment, Long>{
}
| 23.625
| 85
| 0.857143
|
7000dea904ee65b72d4f7c7b4033d678f7fc2502
| 359
|
package lk.ijse.dep.web.lms.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Embeddable;
@Data @AllArgsConstructor @NoArgsConstructor
@Embeddable
public class Address {
private String no;
private String addressLine1;
private String addressLine2;
private String city;
}
| 21.117647
| 44
| 0.791086
|
05933645bfb31089102f13542da853e91a41a28e
| 1,315
|
package openblocks.Battle;
import java.util.ArrayList;
import java.util.Iterator;
import openblocks.common.entity.math.EntityStats;
import openblocks.common.entity.math.MobStats;
import openblocks.common.entity.math.PlayerStats;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.entity.player.EntityPlayer;
/**
* @author NuenoB
*
*/
public class BattleThread implements Runnable {
PlayerStats player;
MobStats mob;
ArrayList<EntityStats> battlers;
Minecraft minecraft = Minecraft.getMinecraft();
/* (non-Javadoc)
* @see java.lang.Runnable#run()
* Llama continuamente al controlador de la batalla
*/
public boolean initBattle(Entity entity){
if (entity instanceof EntityMob){
this.mob= new MobStats(entity);
battlers.add(player);
battlers.add(this.mob);
run();
}
return false;
}
/**
* Runs the current battle in the new thread making a new instance of Battle.
* Calls update method of class Battle.
*/
@Override
public synchronized void run() {
Battle battle= new Battle(battlers, minecraft);
while (minecraft.running){
battle.update();
try {
Thread.sleep(500);
} catch (InterruptedException e) {}
}
}
}
| 23.070175
| 78
| 0.739924
|
8ef7006fd5a740de13f6cfb850e6adfa3ef123f4
| 1,195
|
package com.microsoft.xrm.sdk.Messages;
import android.support.annotation.Nullable;
import com.microsoft.xrm.sdk.EntityReference;
import com.microsoft.xrm.sdk.OrganizationRequest;
public final class AssignRequest extends OrganizationRequest {
public AssignRequest() {
this.setRequestName("Assign");
this.setResponseType(new AssignResponse());
}
@Nullable
public EntityReference getAssignee() {
if (this.getParameters().containsKey("Assignee")) {
return (EntityReference) this.getParameters().get("Assignee");
}
return null;
}
public void setAssignee(EntityReference value) {
this.set("Assignee", value);
}
@Nullable
public EntityReference getTarget() {
if (this.getParameters().containsKey("Target")) {
return (EntityReference) this.getParameters().get("Target");
}
return null;
}
public void setTarget(EntityReference value) {
this.set("Target", value);
}
@Override
public String getRequestBody() {
this.set("Assignee", getAssignee());
this.set("Target", getTarget());
return getSoapBody();
}
}
| 24.895833
| 74
| 0.646025
|
55e480f06abc81ca95848260d5250ab18c194b74
| 7,376
|
// This file was generated by Mendix Studio Pro.
//
// WARNING: Code you write here will be lost the next time you deploy the project.
package test.proxies;
public class Credential
{
private final com.mendix.systemwideinterfaces.core.IMendixObject credentialMendixObject;
private final com.mendix.systemwideinterfaces.core.IContext context;
/**
* Internal name of this entity
*/
public static final java.lang.String entityName = "Test.Credential";
/**
* Enum describing members of this entity
*/
public enum MemberNames
{
User("User"),
ga_SecretKey("ga_SecretKey");
private java.lang.String metaName;
MemberNames(java.lang.String s)
{
metaName = s;
}
@java.lang.Override
public java.lang.String toString()
{
return metaName;
}
}
public Credential(com.mendix.systemwideinterfaces.core.IContext context)
{
this(context, com.mendix.core.Core.instantiate(context, "Test.Credential"));
}
protected Credential(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixObject credentialMendixObject)
{
if (credentialMendixObject == null)
throw new java.lang.IllegalArgumentException("The given object cannot be null.");
if (!com.mendix.core.Core.isSubClassOf("Test.Credential", credentialMendixObject.getType()))
throw new java.lang.IllegalArgumentException("The given object is not a Test.Credential");
this.credentialMendixObject = credentialMendixObject;
this.context = context;
}
/**
* @deprecated Use 'Credential.load(IContext, IMendixIdentifier)' instead.
*/
@java.lang.Deprecated
public static test.proxies.Credential initialize(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixIdentifier mendixIdentifier) throws com.mendix.core.CoreException
{
return test.proxies.Credential.load(context, mendixIdentifier);
}
/**
* Initialize a proxy using context (recommended). This context will be used for security checking when the get- and set-methods without context parameters are called.
* The get- and set-methods with context parameter should be used when for instance sudo access is necessary (IContext.createSudoClone() can be used to obtain sudo access).
*/
public static test.proxies.Credential initialize(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixObject mendixObject)
{
return new test.proxies.Credential(context, mendixObject);
}
public static test.proxies.Credential load(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixIdentifier mendixIdentifier) throws com.mendix.core.CoreException
{
com.mendix.systemwideinterfaces.core.IMendixObject mendixObject = com.mendix.core.Core.retrieveId(context, mendixIdentifier);
return test.proxies.Credential.initialize(context, mendixObject);
}
public static java.util.List<test.proxies.Credential> load(com.mendix.systemwideinterfaces.core.IContext context, java.lang.String xpathConstraint) throws com.mendix.core.CoreException
{
java.util.List<test.proxies.Credential> result = new java.util.ArrayList<test.proxies.Credential>();
for (com.mendix.systemwideinterfaces.core.IMendixObject obj : com.mendix.core.Core.retrieveXPathQuery(context, "//Test.Credential" + xpathConstraint))
result.add(test.proxies.Credential.initialize(context, obj));
return result;
}
/**
* Commit the changes made on this proxy object.
*/
public final void commit() throws com.mendix.core.CoreException
{
com.mendix.core.Core.commit(context, getMendixObject());
}
/**
* Commit the changes made on this proxy object using the specified context.
*/
public final void commit(com.mendix.systemwideinterfaces.core.IContext context) throws com.mendix.core.CoreException
{
com.mendix.core.Core.commit(context, getMendixObject());
}
/**
* Delete the object.
*/
public final void delete()
{
com.mendix.core.Core.delete(context, getMendixObject());
}
/**
* Delete the object using the specified context.
*/
public final void delete(com.mendix.systemwideinterfaces.core.IContext context)
{
com.mendix.core.Core.delete(context, getMendixObject());
}
/**
* @return value of User
*/
public final java.lang.String getUser()
{
return getUser(getContext());
}
/**
* @param context
* @return value of User
*/
public final java.lang.String getUser(com.mendix.systemwideinterfaces.core.IContext context)
{
return (java.lang.String) getMendixObject().getValue(context, MemberNames.User.toString());
}
/**
* Set value of User
* @param user
*/
public final void setUser(java.lang.String user)
{
setUser(getContext(), user);
}
/**
* Set value of User
* @param context
* @param user
*/
public final void setUser(com.mendix.systemwideinterfaces.core.IContext context, java.lang.String user)
{
getMendixObject().setValue(context, MemberNames.User.toString(), user);
}
/**
* @return value of ga_SecretKey
*/
public final java.lang.String getga_SecretKey()
{
return getga_SecretKey(getContext());
}
/**
* @param context
* @return value of ga_SecretKey
*/
public final java.lang.String getga_SecretKey(com.mendix.systemwideinterfaces.core.IContext context)
{
return (java.lang.String) getMendixObject().getValue(context, MemberNames.ga_SecretKey.toString());
}
/**
* Set value of ga_SecretKey
* @param ga_secretkey
*/
public final void setga_SecretKey(java.lang.String ga_secretkey)
{
setga_SecretKey(getContext(), ga_secretkey);
}
/**
* Set value of ga_SecretKey
* @param context
* @param ga_secretkey
*/
public final void setga_SecretKey(com.mendix.systemwideinterfaces.core.IContext context, java.lang.String ga_secretkey)
{
getMendixObject().setValue(context, MemberNames.ga_SecretKey.toString(), ga_secretkey);
}
/**
* @return the IMendixObject instance of this proxy for use in the Core interface.
*/
public final com.mendix.systemwideinterfaces.core.IMendixObject getMendixObject()
{
return credentialMendixObject;
}
/**
* @return the IContext instance of this proxy, or null if no IContext instance was specified at initialization.
*/
public final com.mendix.systemwideinterfaces.core.IContext getContext()
{
return context;
}
@java.lang.Override
public boolean equals(Object obj)
{
if (obj == this)
return true;
if (obj != null && getClass().equals(obj.getClass()))
{
final test.proxies.Credential that = (test.proxies.Credential) obj;
return getMendixObject().equals(that.getMendixObject());
}
return false;
}
@java.lang.Override
public int hashCode()
{
return getMendixObject().hashCode();
}
/**
* @return String name of this class
*/
public static java.lang.String getType()
{
return "Test.Credential";
}
/**
* @return String GUID from this object, format: ID_0000000000
* @deprecated Use getMendixObject().getId().toLong() to get a unique identifier for this object.
*/
@java.lang.Deprecated
public java.lang.String getGUID()
{
return "ID_" + getMendixObject().getId().toLong();
}
}
| 30.106122
| 215
| 0.722885
|
3f15f08fc96e56c6188d61c2803e295f2cc8db15
| 348
|
class MnistManager {
/**
* Reads the current label.
*
* @return int
* @throws java.io.IOException
*/
public int readLabel() throws IOException {
if (labels == null) {
throw new IllegalStateException("labels file not initialized.");
}
return labels.readLabel();
}
private MnistLabelFile labels;
}
| 18.315789
| 69
| 0.623563
|
7c8d43d39a2fe89c479d7c9574ceabf52c9e6a18
| 395
|
package SDA;
import SDA.Flights.FlightService;
import SDA.Pogoda.Pogoda;
import java.io.IOException;
import java.time.Month;
public class TesterStrumieni {
public static void main(String[] args) throws IOException {
Strumienie a = new Strumienie();
Pogoda w = new Pogoda();
FlightService loty = new FlightService();
loty.generateRaport();
}
}
| 15.192308
| 63
| 0.673418
|
b36d62514594f5ae4615ed71cbc7a3311abcb309
| 105
|
package io.craftgate.model;
public enum CardType {
CREDIT_CARD,
DEBIT_CARD,
PREPAID_CARD
}
| 11.666667
| 27
| 0.704762
|
db77143464875f00671f9e0c057d72d795115c06
| 7,987
|
package de.iisys.pippa.system.pippa;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Logger;
import java.util.Set;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import de.iisys.pippa.core.dispatcher.Dispatcher;
import de.iisys.pippa.core.executor.Executor;
import de.iisys.pippa.core.message_processor.AMessageProcessor;
import de.iisys.pippa.core.pippa_service.PippaService;
import de.iisys.pippa.core.resolver.Resolver;
import de.iisys.pippa.core.skill.Skill;
import de.iisys.pippa.core.skill_registry.SkillRegistry;
public class Pippa {
private static final Logger log = Logger.getLogger(Pippa.class.getName());
private Map<String, AMessageProcessor> systemComponents = new LinkedHashMap<String, AMessageProcessor>();
private List<Skill> skills = new ArrayList<Skill>();
private List<PippaService> pippaServices = new ArrayList<PippaService>();
private BundleContext context = null;
protected Pippa(BundleContext context) {
this.context = context;
systemComponents.put("SpeechRecognizer", null);
systemComponents.put("SpeechAnalyser", null);
systemComponents.put("AudioStorage", null);
systemComponents.put("Dispatcher", null);
systemComponents.put("SkillRegistry", null);
systemComponents.put("Resolver", null);
systemComponents.put("Scheduler", null);
systemComponents.put("Executor", null);
systemComponents.put("MessageStorage", null);
}
public void startPippa() {
log.info("starting Pippa");
this.loadSystemServices();
this.chainSystemServices();
this.threadSystemServices();
this.loadSkillServices();
this.chainSkillServices();
this.threadSkillServices();
// TODO rename
this.loadPippaServices();
this.threadPippaServices();
this.showAllThreads();
log.info("Pippa started");
}
private void loadSystemServices() {
log.info("loading system services: " + systemComponents.keySet());
Collection<ServiceReference<AMessageProcessor>> serviceReferences = null;
for (String serviceName : systemComponents.keySet()) {
try {
// get all service references registered under the given name (which should be
// 1)
serviceReferences = context.getServiceReferences(AMessageProcessor.class, "(name=" + serviceName + ")");
// get actual object from reference
AMessageProcessor service = context
.getService(((List<ServiceReference<AMessageProcessor>>) serviceReferences).get(0));
// store object with service name (class-name)
systemComponents.put(serviceName, service);
} catch (InvalidSyntaxException e) {
log.info("Error loading Service " + serviceName + ": " + e);
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void chainSystemServices() {
log.info("chaining system services");
systemComponents.get("SpeechRecognizer")
.setOutgoingQueue(systemComponents.get("SpeechAnalyser").getIncomingQueue());
systemComponents.get("SpeechAnalyser")
.setOutgoingQueue(systemComponents.get("AudioStorage").getIncomingQueue());
systemComponents.get("AudioStorage").setOutgoingQueue(systemComponents.get("Dispatcher").getIncomingQueue());
systemComponents.get("Dispatcher").setOutgoingQueue(systemComponents.get("SkillRegistry").getIncomingQueue());
Resolver resolver = (Resolver) systemComponents.get("Resolver");
resolver.setDispatcherQueue(systemComponents.get("Dispatcher").getIncomingQueue());
resolver.setExecutorQueue(systemComponents.get("Executor").getIncomingQueue());
resolver.setSkillRegistryQueue(systemComponents.get("SkillRegistry").getIncomingQueue());
resolver.setSchedulerQueue(systemComponents.get("Scheduler").getIncomingQueue());
systemComponents.get("Scheduler").setOutgoingQueue(systemComponents.get("Resolver").getIncomingQueue());
systemComponents.get("Executor").setOutgoingQueue(systemComponents.get("MessageStorage").getIncomingQueue());
Executor executor = (Executor)systemComponents.get("Executor");
executor.setSkillRegistryQueue(systemComponents.get("SkillRegistry").getIncomingQueue());
}
private void threadSystemServices() {
log.info("threading system services");
for (Entry<String, AMessageProcessor> chainLink : systemComponents.entrySet()) {
Thread t = new Thread((Runnable) chainLink.getValue(), "--- " + chainLink.getKey());
t.start();
}
}
private void loadSkillServices() {
log.info("loading skill services");
Collection<ServiceReference<Skill>> serviceReferences = null;
Skill skill = null;
try {
// get all service references
serviceReferences = context.getServiceReferences(Skill.class, null);
for (ServiceReference<Skill> serviceReference : serviceReferences) {
// get actual object from reference
skill = context.getService(serviceReference);
// store object
skills.add(skill);
// register skill within registry
this.registerSkill(skill);
// register skills regexes within dispatcher
this.registerRegex(skill);
}
} catch (InvalidSyntaxException e) {
log.info("Error loading Service " + skill.getClass().getSimpleName() + ": " + e);
// TODO Auto-generated catch block
}
}
private void chainSkillServices() {
log.info("chaining skill services");
// link all outgoing queues of skills to the resolvers incoming queue for
for (Skill skill : this.skills) {
((AMessageProcessor) skill).setOutgoingQueue(systemComponents.get("Resolver").getIncomingQueue());
}
}
private void threadSkillServices() {
log.info("threading skill services");
for (Skill skill : skills) {
Thread t = new Thread((Runnable) skill, "+++ " + skill.getClass().getSimpleName());
t.start();
}
}
private void loadPippaServices() {
log.info("loading pippa_service services");
Collection<ServiceReference<PippaService>> serviceReferences = null;
PippaService service = null;
try {
// get all service references
serviceReferences = context.getServiceReferences(PippaService.class, null);
for (ServiceReference<PippaService> serviceReference : serviceReferences) {
// get actual object from reference
service = context.getService(serviceReference);
this.pippaServices.add(service);
}
} catch (InvalidSyntaxException e) {
log.info("Error loading service " + service.getClass().getSimpleName() + ": " + e);
// TODO Auto-generated catch block
}
}
private void threadPippaServices() {
log.info("threading pippa_service services");
for (PippaService service : this.pippaServices) {
if (service instanceof Runnable) {
Thread t = new Thread((Runnable) service, "~~~ " + service.getClass().getSimpleName());
t.start();
}
}
}
private void registerSkill(Skill skill) {
((SkillRegistry) this.systemComponents.get("SkillRegistry")).registerSkill(skill);
}
private void registerRegex(Skill skill) {
((Dispatcher) this.systemComponents.get("Dispatcher")).registerRegexes(skill);
}
private void deregisterSkill(Skill skill) {
// TODO
}
private void deregisterRegex(Skill skill) {
// TODO
}
private void showAllThreads() {
System.out.println(" ");
System.out.println("*****THREADS******");
System.out.println("** --- Pippa-System");
System.out.println("** ~~~ Pippa-Services");
System.out.println("** +++ Skills");
System.out.println("******************");
System.out.println(" ");
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
for (Thread t : threadSet) {
System.out.println(t.getName());
}
}
}
| 29.043636
| 113
| 0.70477
|
00f3bfc5378d9b79c7aced5ee2a9a7f0e6648770
| 3,006
|
package com.googlecode.jedis;
import static com.google.common.base.Charsets.UTF_8;
import static com.googlecode.jedis.PairImpl.newPair;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
/**
* Decodes single lines to a proper return type.
*
* TODO: pipelined mode!
*
* @author Moritz Heuser
*
*/
final class ResponseDecoder extends SimpleChannelUpstreamHandler {
private static Logger log = LoggerFactory.getLogger("org.googlecode.jedis");
private static final byte[] NULL = { '-', '1' };
private int multiBulkArgs;
private boolean multiBulkMode = false;
private List<byte[]> multiBulkStore;
private final BlockingQueue<Pair<ResponseType, List<byte[]>>> queue;
public ResponseDecoder(
final BlockingQueue<Pair<ResponseType, List<byte[]>>> queue) {
this.queue = queue;
}
@Override
public void messageReceived(final ChannelHandlerContext ctx,
final MessageEvent e) throws Exception {
super.messageReceived(ctx, e);
@SuppressWarnings("unchecked")
final Pair<ResponseType, byte[]> responseLine = (Pair<ResponseType, byte[]>) e
.getMessage();
final ResponseType responseType = responseLine.getFirst();
byte[] line = responseLine.getSecond();
switch (responseType) {
case MultiBulk:
multiBulkArgs = Integer.valueOf(new String(line, UTF_8));
if (multiBulkArgs <= 0) {
// empty multibulk response, blpop and brpop are returning -1
final List<byte[]> response = ImmutableList.of();
toQueue(newPair(ResponseType.MultiBulk, response));
} else {
multiBulkMode = true;
multiBulkStore = Lists.newArrayListWithCapacity(multiBulkArgs);
}
break;
case Bulk:
if (Arrays.equals(line, NULL)) {
line = null;
}
if (multiBulkMode) {
multiBulkArgs--;
multiBulkStore.add(line);
if (multiBulkArgs == 0) {
// can't use guava's immutable list because of null values
final List<byte[]> result = Lists
.newArrayList(multiBulkStore);
multiBulkStore.clear();
multiBulkMode = false;
toQueue(newPair(ResponseType.MultiBulk, result));
}
} else {
// can't use guava's immutable list because of possible null
// values
toQueue(newPair(responseType, Collections.singletonList(line)));
}
break;
default:
toQueue(newPair(responseType, (List<byte[]>) ImmutableList.of(line)));
}
}
private void toQueue(final Pair<ResponseType, List<byte[]>> next) {
try {
queue.offer(next, 1, TimeUnit.MINUTES);
} catch (final InterruptedException e) {
log.error("Could not put a Response to the queue!", e);
}
}
}
| 28.628571
| 80
| 0.71324
|
14f3263d0ef0d9f2870193a8d99a7e1e6a82a099
| 2,092
|
package com.hyh.android_animation;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import com.hyh.android_animation.fragment.FragmentRepotity;
import com.hyh.base_lib.BaseFragment;
import com.hyh.base_lib.BaseFragmentFactory;
import com.hyh.base_lib.adapter.DataListAdapter;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final RecyclerView rvList = findViewById(R.id.rv_list);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
rvList.setLayoutManager(layoutManager);
DataListAdapter dataListAdapter = new DataListAdapter(this, new DataListAdapter.OnClickCallBack() {
@Override
public void onClick(BaseFragmentFactory baseFragmentFactory) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
BaseFragment fragment = baseFragmentFactory.createFragment();
fragment.setOnDestroyCallBack(new BaseFragment.OnDestroyCallBack() {
@Override
public void onDestroy() {
rvList.setVisibility(View.VISIBLE);
}
});
transaction.replace(R.id.fl_fragment_container, fragment);
//添加到返回栈中,使得点击返回键会回到当前activity
transaction.addToBackStack(null);
transaction.commit();
Log.d("hyh", "MainActivity: onClick ");
rvList.setVisibility(View.GONE);
}
}, FragmentRepotity.sDataList);
rvList.setAdapter(dataListAdapter);
}
}
| 42.693878
| 107
| 0.688337
|
5f767047c98572087fff6e0005d45eec91327466
| 5,592
|
/*
* Copyright 2012-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.zhongshi.gateway.config;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.jboss.logging.MDC;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.http.MediaType;
import org.springframework.http.codec.HttpMessageReader;
import org.springframework.http.codec.HttpMessageWriter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.Assert;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.reactive.result.view.ViewResolver;
import org.springframework.web.server.ServerWebExchange;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.zhongshi.factory.BaseResultFactory;
import com.zhongshi.factory.result.AbstractBaseResult;
import com.zhongshi.gateway.config.tool.RequestTool;
import com.zhongshi.tool.ApplicationEnvironmentConfig;
import reactor.core.publisher.Mono;
/**
*
* 功能说明:网关错误映射器
*
* 功能作者:彭晋龙 ( 联系方式QQ/微信:1095071913 )
*
* 创建日期:2019-10-31 :20:16:00
*
* 版权归属:蓝河团队
*
* 协议说明:Apache2.0( 文件顶端 )
*
*/
public class GatewayExceptionHandler extends BaseResultFactory implements ErrorWebExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GatewayExceptionHandler.class);
private List<HttpMessageReader<?>> messageReaders = Collections.emptyList();
private List<HttpMessageWriter<?>> messageWriters = Collections.emptyList();
private List<ViewResolver> viewResolvers = Collections.emptyList();
private ThreadLocal<AbstractBaseResult> exceptionHandlerResult = new ThreadLocal<>();
public void setMessageReaders(List<HttpMessageReader<?>> messageReaders) {
Assert.notNull(messageReaders, "'messageReaders' must not be null");
this.messageReaders = messageReaders;
}
public void setViewResolvers(List<ViewResolver> viewResolvers) {
this.viewResolvers = viewResolvers;
}
public void setMessageWriters(List<HttpMessageWriter<?>> messageWriters) {
Assert.notNull(messageWriters, "'messageWriters' must not be null");
this.messageWriters = messageWriters;
}
protected Mono<ServerResponse> renderErrorResponse(ServerRequest request) {
AbstractBaseResult result = exceptionHandlerResult.get();
return ServerResponse.status(result.getHttpCode()).contentType(MediaType.APPLICATION_JSON_UTF8)
.body(BodyInserters.fromObject(result));
}
private Mono<? extends Void> write(ServerWebExchange exchange, ServerResponse response) {
exchange.getResponse().getHeaders().setContentType(response.headers().getContentType());
return response.writeTo(exchange, new ResponseContext());
}
private class ResponseContext implements ServerResponse.Context {
@Override
public List<HttpMessageWriter<?>> messageWriters() {
return GatewayExceptionHandler.this.messageWriters;
}
@Override
public List<ViewResolver> viewResolvers() {
return GatewayExceptionHandler.this.viewResolvers;
}
}
@Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable e) {
AbstractBaseResult result = null;
ServerHttpRequest request = exchange.getRequest();
MDC.put("tid",exchange.getAttributes().get("TID"));
MDC.put("applicationName", ApplicationEnvironmentConfig.applicationName);
Map<String,String> logs = new LinkedHashMap<String, String>();
logs.put("reqType", "gateway");
logs.put("reqIp", RequestTool.getIpAddress(request)+" net");
logs.put("reqUrl", request.getURI().toString());
logs.put("reqMethod", request.getMethod().toString());
logs.put("errorDesc", e.getLocalizedMessage());
log.error(getStackTrace(e));
if (e instanceof NotFoundException) {
result = error(code(404),404);
}else if(BlockException.isBlockException(e)){
result =error(code(601),500);
}else {
result = error(code(500),500);
}
logs.put("respData", result.toString());
log.error(BaseResultFactory.appendLog(logs).toString());
if (exchange.getResponse().isCommitted()) {
return Mono.error(e);
}
MDC.clear();
exceptionHandlerResult.set(result);
ServerRequest newRequest = ServerRequest.create(exchange, this.messageReaders);
return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse).route(newRequest)
.switchIfEmpty(Mono.error(e)).flatMap((handler) -> handler.handle(newRequest))
.flatMap((response) -> write(exchange, response));
}
}
| 34.732919
| 100
| 0.773069
|
7993e03f1f26b40723b710e6640338f0a97240f7
| 238
|
package org.trvedata.sgm;
public enum Operation {
MESSAGE("message"),
ADD("add"),
REMOVE("remove"),
UPDATE("update");
public final String opcode;
Operation(String opcode) {
this.opcode = opcode;
}
}
| 15.866667
| 31
| 0.605042
|
e66a77caba301c8d081f0ccbe6037aaddfa7a7a9
| 639
|
package it.unitn.ds1.resources;
public class Resource implements Cloneable {
private Integer value;
private Integer version;
public Resource(Integer value, Integer version) {
this.value = value;
this.version = version;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
@Override
public Object clone() {
return new Resource(value, version);
}
}
| 19.363636
| 53
| 0.616588
|
5d7101d085031c6120935ddfb45a324041b5d8b4
| 722
|
package code.assignment.model;
import java.math.BigDecimal;
/**
* Model class used to create Product object.
*/
public class Product {
private final long id;
private final String name;
private final BigDecimal price;
private final Promotion promotion;
public Product(long id, String name, BigDecimal price, Promotion promotion) {
this.id = id;
this.name = name;
this.price = price;
this.promotion = promotion;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public BigDecimal getPrice() {
return price;
}
public Promotion getPromotion() {
return promotion;
}
}
| 18.512821
| 81
| 0.619114
|
b0d8c00febb768aef1559cc4a3df0c3105315688
| 34,088
|
package com.system.dao;
import com.system.Logs.Log;
import com.system.Message.Messages;
import com.system.Queries.Query;
import com.system.dao.Interfaces.IProductManagement;
import com.system.models.Products;
import com.system.models.Recipie;
import com.system.models.Supplier;
import com.system.services.SqlConnectionServices;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
public class ProductManagementDao implements IProductManagement {
public static void getLogInfo (String message){
try {
Log log = Log.getInstance();
log.logger.info(message);
}catch (Exception exp){
exp.printStackTrace();
}
}
public static void getLogWarning (String message){
try {
Log log = Log.getInstance();
log.logger.warning(message);
}catch (Exception exp){
exp.printStackTrace();
}
}
//to close the open sql connections
public void closeSqlConnection(Connection connection){
if(connection != null){
SqlConnectionServices.closeConnection(connection);
}
}
@Override
public ObservableList<String> getAllCategoryNames() {
ObservableList<String> list = FXCollections.observableArrayList();
Connection connection = SqlConnectionServices.getConnection();
try{
PreparedStatement preparedStatement = SqlConnectionServices.prepareAStatement(connection, Query.categoryNames,null);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet != null){
while (resultSet.next()){
list.add(resultSet.getString(1));
}
}
}catch (SQLException exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
return list;
}
@Override
public ObservableList<String> getSuppliearNames() {
ObservableList<String> list = FXCollections.observableArrayList();
Connection connection = SqlConnectionServices.getConnection();
try{
PreparedStatement preparedStatement = SqlConnectionServices.prepareAStatement(connection, Query.supplierNames,null);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet != null){
while (resultSet.next()){
list.add(resultSet.getString(1));
}
}
}catch (SQLException exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
return list;
}
@Override
public int getSupplierId(String supplierName) {
int id = 0;
Connection connection = SqlConnectionServices.getConnection();
HashMap<Integer , Object> params = new HashMap<>();
params.put(1,supplierName);
try {
PreparedStatement preparedStatement = SqlConnectionServices.prepareAStatement(connection,Query.supplierId,params);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet != null){
while (resultSet.next()){
id = resultSet.getInt(1);
}
}
}catch (SQLException exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
return id;
}
@Override
public int getCategoryId(String categoryName) {
int id = 0;
Connection connection = SqlConnectionServices.getConnection();
HashMap<Integer , Object> params = new HashMap<>();
params.put(1,categoryName);
try {
PreparedStatement preparedStatement = SqlConnectionServices.prepareAStatement(connection,Query.categoryId,params);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet != null){
while (resultSet.next()){
id = resultSet.getInt(1);
}
}
}catch (SQLException exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
return id;
}
@Override
public ObservableList<String> getAllProductsNames() {
ObservableList<String> list = FXCollections.observableArrayList();
Connection connection = SqlConnectionServices.getConnection();
try{
PreparedStatement preparedStatement = SqlConnectionServices.prepareAStatement(connection, Query.allProductsNames,null);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet != null){
while (resultSet.next()){
list.add(resultSet.getString(1));
}
}
}catch (SQLException exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
return list;
}
@Override
public int getProductId(String productName) {
int id = 0;
Connection connection = SqlConnectionServices.getConnection();
HashMap<Integer , Object> params = new HashMap<>();
params.put(1,productName);
try {
PreparedStatement preparedStatement = SqlConnectionServices.prepareAStatement(connection,Query.productId,params);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet != null){
while (resultSet.next()){
id = resultSet.getInt(1);
}
}
}catch (SQLException exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
return id;
}
@Override
public void addSellPrice(Products product, String date) {
int productId = getProductId(product.getProductName());
Connection connection = SqlConnectionServices.getConnection();
HashMap<Integer , Object> params = new HashMap<>();
params.put(1,productId);
params.put(2,product.getSellPrice());
params.put(3,date);
try{
int affectedRows = SqlConnectionServices.prepareAStatement(connection,Query.addSellHistory,params).executeUpdate();
if(affectedRows == 0){
getLogInfo("sell price not successfully added");
System.out.println("sell price not inserted");
}else {
getLogInfo("sell price add successfully");
System.out.println("selling history inserted");
}
}catch (Exception exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
}
@Override
public void addNewProduct(Products product, String categoryName, String supplierName) {
int categoryId = getCategoryId(categoryName);
int suppliearId = getSupplierId(supplierName);
Connection connection = SqlConnectionServices.getConnection();
HashMap<Integer , Object> params = new HashMap<>();
params.put(1,categoryId);
params.put(2,suppliearId);
params.put(3,product.getProductName());
try{
int affectedRows = SqlConnectionServices.prepareAStatement(connection,Query.addNewProductQuery,params).executeUpdate();
if(affectedRows == 0){
getLogInfo("new product added successfully");
Messages.getWarning("Data is not Inserted");
}else {
getLogInfo("new product not added successfully");
Messages.getAlert("Data Inserted SuccessFully");
}
}catch (Exception exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
}
@Override
public float getCurrentPrice(String ProductName) {
float currentProductPrice = 0;
int productId = getProductId(ProductName);
Connection connection = SqlConnectionServices.getConnection();
HashMap<Integer , Object> params = new HashMap<>();
params.put(1,productId);
try{
PreparedStatement preparedStatement = SqlConnectionServices.prepareAStatement(connection,Query.currentSellingPrice,params);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet != null){
while (resultSet.next()){
currentProductPrice = resultSet.getFloat(1);
}
}
}catch (Exception exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
return currentProductPrice;
}
@Override
public void setNewSellPrice(Products product) {
int productId = getProductId(product.getProductName());
Connection connection = SqlConnectionServices.getConnection();
HashMap<Integer , Object> params = new HashMap<>();
params.put(1 , productId);
params.put(2 , product.getSellPrice());
params.put(3 , product.getDate());
try{
int affectedRows = SqlConnectionServices.prepareAStatement(connection,Query.updateSellingPrice,params).executeUpdate();
if(affectedRows == 0){
getLogInfo("new Price is not Updated try again");
Messages.getWarning("new Price is not Updated try again");
}else {
getLogInfo("new Price is successfully updated");
Messages.getAlert("new Price is successfully updated");
}
}catch (Exception exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
}
@Override
public void addNewCategory(Products product) {
Connection connection = SqlConnectionServices.getConnection();
HashMap<Integer , Object> params = new HashMap<>();
params.put(1,product.getCategoryName());
try{
int affectedRows = SqlConnectionServices.prepareAStatement(connection,Query.newCategoryName,params).executeUpdate();
if(affectedRows == 0){
getLogInfo("Category is not added in sucessfully");
Messages.getWarning("Category is not added in sucessfully");
}else{
getLogInfo("Category is Successfully Added");
Messages.getAlert("Category is Successfully Added");
}
}catch (Exception exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
}
@Override
public void addNewSupplier(Supplier supplier) {
Connection connection = SqlConnectionServices.getConnection();
HashMap<Integer , Object> params = new HashMap<>();
params.put(1 , supplier.getSupplierName());
params.put(2 , supplier.getPhoneNumber());
params.put(3 , supplier.getAddress());
params.put(4 , supplier.getEmail());
try {
int affcctedRows = SqlConnectionServices.prepareAStatement(connection,Query.newSupplier,params).executeUpdate();
if(affcctedRows == 0){
getLogInfo("Suppliear is not Entered ");
Messages.getWarning("Suppliear is not Entered ");
}else {
getLogInfo("Suppliear is Successfully entered.");
Messages.getAlert("Suppliear is Successfully entered.");
}
}catch (Exception exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
}
@Override
public ObservableList<String> getSuppliearPhno() {
ObservableList<String> list = FXCollections.observableArrayList();
Connection connection = SqlConnectionServices.getConnection();
try{
PreparedStatement preparedStatement = SqlConnectionServices.prepareAStatement(connection, Query.supplierPhNo,null);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet != null){
while (resultSet.next()){
list.add(resultSet.getString(1));
}
}
}catch (SQLException exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
return list;
}
@Override
public ObservableList<String> getSuppliearInfo(Supplier supplier) {
ObservableList<String> list = FXCollections.observableArrayList();
Connection connection = SqlConnectionServices.getConnection();
HashMap<Integer ,Object> params = new HashMap<>();
params.put(1,supplier.getSupplierName());
try{
PreparedStatement preparedStatement = SqlConnectionServices.prepareAStatement(connection,Query.supplierInfo,params);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet != null){
while (resultSet.next()){
for(int i = 1 ; i <= 5 ; i++) {
list.add(resultSet.getString(i));
}
}
}
}catch (Exception exp){
getLogWarning(exp.getMessage());
System.out.println("eror comming check it later");
}finally {
this.closeSqlConnection(connection);
}
return list;
}
@Override
public ObservableList<String> getRecipieCategorys() {
ObservableList<String> list = FXCollections.observableArrayList();
Connection connection = SqlConnectionServices.getConnection();
try{
PreparedStatement preparedStatement = SqlConnectionServices.prepareAStatement(connection, Query.recpieCategoryNames,null);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet != null){
while (resultSet.next()){
list.add(resultSet.getString(1));
}
}
}catch (SQLException exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
return list;
}
@Override
public void addNewRecipieCategory(String name) {
Connection connection = SqlConnectionServices.getConnection();
HashMap<Integer , Object> params = new HashMap<>();
params.put(1,name);
try{
int affectedRows = SqlConnectionServices.prepareAStatement(connection,Query.newRecipieCategory,params).executeUpdate();
if(affectedRows == 0){
getLogInfo("recipie category not added successfully");
Messages.getWarning("Category is not added in sucessfully");
}else{
getLogInfo("recipie category added succeddfully");
Messages.getAlert("Category is Successfully Added");
}
}catch (Exception exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
}
@Override
public ObservableList<String> getRecipieNames() {
ObservableList<String> list = FXCollections.observableArrayList();
Connection connection = SqlConnectionServices.getConnection();
try{
PreparedStatement preparedStatement = SqlConnectionServices.prepareAStatement(connection, Query.recipieNames,null);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet != null){
while (resultSet.next()){
list.add(resultSet.getString(1));
}
}
}catch (SQLException exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
return list;
}
@Override
public int getRecipieCatId(String catName) {
int id = 0;
Connection connection = SqlConnectionServices.getConnection();
HashMap<Integer , Object> params = new HashMap<>();
params.put(1,catName);
try {
PreparedStatement preparedStatement = SqlConnectionServices.prepareAStatement(connection,Query.recipieCatId,params);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet != null){
while (resultSet.next()){
id = resultSet.getInt(1);
}
}
}catch (SQLException exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
return id;
}
@Override
public void addNewRecipieName(String name,String recipieName) {
int catId = getRecipieCatId(name);
Connection connection = SqlConnectionServices.getConnection();
HashMap<Integer , Object> params = new HashMap<>();
params.put(1 , catId);
params.put(2 , recipieName);
try{
int affectedRows = SqlConnectionServices.prepareAStatement(connection,Query.addRecipeName,params).executeUpdate();
if(affectedRows == 0){
getLogInfo("new recipie not added successfull");
System.out.println("new name is not Updated try again");
}else {
getLogInfo("new recipie added successfull");
System.out.println("new name is successfully updated");
}
}catch (Exception exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
}
@Override
public int getRecipieId(String name) {
int id = 0;
Connection connection = SqlConnectionServices.getConnection();
HashMap<Integer , Object> params = new HashMap<>();
params.put(1,name);
try {
PreparedStatement preparedStatement = SqlConnectionServices.prepareAStatement(connection,Query.recipieProductId,params);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet != null){
while (resultSet.next()){
id = resultSet.getInt(1);
}
}
}catch (SQLException exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
return id;
}
@Override
public void addRecipieSellPrice(float sellPrice, String date,String recipieName) {
int recipieId = getRecipieId(recipieName);
Connection connection = SqlConnectionServices.getConnection();
HashMap<Integer , Object> params = new HashMap<>();
params.put(1 , recipieId);
params.put(2 , sellPrice);
params.put(3 , date);
try{
int affectedRows = SqlConnectionServices.prepareAStatement(connection,Query.recipeSellPrice,params).executeUpdate();
if(affectedRows == 0){
getLogInfo("new recipie sell price is not added");
Messages.getWarning("new sellPrice is not Updated try again");
}else {
getLogInfo("new recipie sell price is added");
Messages.getAlert("new sellPrice is successfully updated");
}
}catch (Exception exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
}
@Override
public void addRecipeIngredents(Recipie recipie) {
int recipieId = getRecipieId(recipie.getRecipieName());
int productId = getProductId(recipie.getProductName());
Connection connection = SqlConnectionServices.getConnection();
HashMap<Integer , Object> params = new HashMap<>();
params.put(1 , recipieId);
params.put(2 , productId);
params.put(3 , recipie.getQuantity());
params.put(4 , recipie.getDate());
try{
int affectedRows = SqlConnectionServices.prepareAStatement(connection,Query.addRecipieIngredents,params).executeUpdate();
if(affectedRows == 0){
getLogInfo("new Ingredents not Added try again");
System.out.println("new Ingredents not Added try again");
}else {
getLogInfo("new Ingredents Added ");
System.out.println("new Ingredents Added");
}
}catch (Exception exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
}
@Override
public ObservableList<Integer> getRecipieId() {
ObservableList<Integer> list = FXCollections.observableArrayList();
Connection connection = SqlConnectionServices.getConnection();
try{
PreparedStatement preparedStatement = SqlConnectionServices.prepareAStatement(connection, Query.recipeNameId,null);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet != null){
while (resultSet.next()){
list.add(resultSet.getInt(1));
}
}
}catch (SQLException exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
return list;
}
@Override
public float getRecipeCurrentPrice(Recipie recipie) {
float currentPrice = 0;
int recipieId = getRecipieId(recipie.getRecipieName());
Connection connection = SqlConnectionServices.getConnection();
HashMap<Integer , Object> params = new HashMap<>();
params.put(1 , recipieId);
try {
PreparedStatement preparedStatement = SqlConnectionServices.prepareAStatement(connection,Query.recipieCurrentPrice,params);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet != null){
while (resultSet.next()){
currentPrice = resultSet.getInt(1);
}
}
}catch (SQLException exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
return currentPrice;
}
@Override
public void setNewRecipieSellPrice(Recipie recipie) {
int productId = getRecipieId(recipie.getRecipieName());
Connection connection = SqlConnectionServices.getConnection();
HashMap<Integer , Object> params = new HashMap<>();
params.put(1 , productId);
params.put(2 , recipie.getPrice());
params.put(3 , recipie.getDate());
try{
int affectedRows = SqlConnectionServices.prepareAStatement(connection,Query.newRecipieSellPrice,params).executeUpdate();
if(affectedRows == 0){
getLogInfo("new recipie sell price is not updated");
Messages.getWarning("new Price is not Updated try again");
}else {
getLogInfo("new recipie sell price is added");
Messages.getAlert("new Price is successfully updated");
}
}catch (Exception exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
}
@Override
public float getLatestPurchasePrice(String name) {
float currentPrice = 0;
int recipieId = getProductId(name);
Connection connection = SqlConnectionServices.getConnection();
HashMap<Integer , Object> params = new HashMap<>();
params.put(1 , recipieId);
try {
PreparedStatement preparedStatement = SqlConnectionServices.prepareAStatement(connection,Query.getLatestPurchasePrice,params);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet != null){
while (resultSet.next()){
currentPrice = resultSet.getInt(1);
}
}
}catch (SQLException exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
return currentPrice;
}
@Override
public void addnewRecipiePurchase(Recipie recipie) {
int productId = getRecipieId(recipie.getRecipieName());
Connection connection = SqlConnectionServices.getConnection();
HashMap<Integer , Object> params = new HashMap<>();
params.put(1,productId);
params.put(2,recipie.getPurPrice());
params.put(3,recipie.getDate());
try{
int affectedRows = SqlConnectionServices.prepareAStatement(connection,Query.insertRecipiePurchase,params).executeUpdate();
if(affectedRows == 0){
getLogInfo("recipie purchase is not inserted");
Messages.getWarning("Data is not Inserted");
}else {
getLogInfo("recipie purchase inserted");
Messages.getAlert("Data inserted successfully");
}
}catch (Exception exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
}
public float getRecipiePurchasePrice(String recipieName){
int id = getRecipieId(recipieName);
float price = 0;
Connection connection = SqlConnectionServices.getConnection();
HashMap<Integer , Object> params = new HashMap<>();
params.put(1,id);
try {
PreparedStatement preparedStatement = SqlConnectionServices.prepareAStatement(connection,Query.getRecipePurchasePrice,params);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet != null){
while (resultSet.next()){
price = resultSet.getFloat(1);
}
}
}catch (SQLException exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
return price;
}
public void insertTemp(int orderId,float price ,String date){
Connection connection = SqlConnectionServices.getConnection();
HashMap<Integer , Object> params = new HashMap<>();
params.put(1,orderId);
params.put(2,price);
params.put(3,date);
try{
int affectedRows = SqlConnectionServices.prepareAStatement(connection,Query.insertTemp,params).executeUpdate();
if(affectedRows == 0){
getLogInfo("temp data is not inserted");
System.out.println("Data is not Inserted");
}else {
getLogInfo("temp data inserted");
System.out.println("Data Inserted SuccessFully");
}
}catch (Exception exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
}
public ObservableList<Recipie> getRecipieDetails(int id){
ObservableList<Recipie> list = FXCollections.observableArrayList();
Connection connection = SqlConnectionServices.getConnection();
HashMap<Integer , Object> params = new HashMap<>();
params.put(1,id);
try{
PreparedStatement preparedStatement = SqlConnectionServices.prepareAStatement(connection, Query.getRecipieData,params);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet != null){
while (resultSet.next()){
list.add(new Recipie(resultSet.getInt(1),resultSet.getString(2),resultSet.getFloat(3)));
}
}
}catch (SQLException exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
return list;
}
public void delRecipieIngreidents(String recipieName){
int id = getRecipieId(recipieName);
Connection connection = SqlConnectionServices.getConnection();
HashMap<Integer , Object> params = new HashMap<>();
params.put(1,id);
try{
int affectedRows = SqlConnectionServices.prepareAStatement(connection,Query.deleteRecipieIngridents,params).executeUpdate();
if(affectedRows == 0){
getLogInfo("Ingriedents data is not deleted");
System.out.println("Data is not Inserted");
}else {
getLogInfo("Ingriedents data delete SuccessFully");
System.out.println("Ingriedents data SuccessFully");
}
}catch (Exception exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
}
public void delRecipiePurchase(String recipieName){
int id = getRecipieId(recipieName);
Connection connection = SqlConnectionServices.getConnection();
HashMap<Integer , Object> params = new HashMap<>();
params.put(1,id);
try{
int affectedRows = SqlConnectionServices.prepareAStatement(connection,Query.deleteRecPur,params).executeUpdate();
if(affectedRows == 0){
getLogInfo("rcipie purchase data is not deleted");
System.out.println("Data is not Inserted");
}else {
getLogInfo("Recipie purchase data deleted");
System.out.println("Ingriedents data SuccessFully");
}
}catch (Exception exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
}
public void delRecipieSell(String recipieName){
int id = getRecipieId(recipieName);
Connection connection = SqlConnectionServices.getConnection();
HashMap<Integer , Object> params = new HashMap<>();
params.put(1,id);
try{
int affectedRows = SqlConnectionServices.prepareAStatement(connection,Query.deleteRecSell,params).executeUpdate();
if(affectedRows == 0){
getLogInfo("recipie sell data is not deleted");
System.out.println("Data is not Inserted");
}else {
getLogInfo("recipie sell data deleted");
System.out.println("Ingriedents data SuccessFully");
}
}catch (Exception exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
}
public void delRecipieProduct(String recipieName){
int id = getRecipieId(recipieName);
ObservableList<Recipie> list = FXCollections.observableArrayList();
Connection connection = SqlConnectionServices.getConnection();
HashMap<Integer , Object> params = new HashMap<>();
params.put(1,id);
try{
int affectedRows = SqlConnectionServices.prepareAStatement(connection,Query.deleteRcipeName,params).executeUpdate();
if(affectedRows == 0){
getLogInfo("recipie product data is not deleted");
System.out.println("Data is not Inserted");
}else {
getLogInfo("recipie product data is deleted");
System.out.println("Ingriedents data SuccessFully");
}
}catch (Exception exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
}
public ObservableList<Integer> getIngredentsProductId(){
ObservableList<Integer> list = FXCollections.observableArrayList();
Connection connection = SqlConnectionServices.getConnection();
try{
PreparedStatement preparedStatement = SqlConnectionServices.prepareAStatement(connection, Query.getIngriedentsProductId,null);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet != null){
while (resultSet.next()){
list.add(resultSet.getInt(1));
}
}
}catch (SQLException exp){
getLogWarning(exp.getMessage());
exp.printStackTrace();
}finally {
this.closeSqlConnection(connection);
}
return list;
}
}
| 30.70991
| 138
| 0.597307
|
85f7e0ab0220a4afa8d568175b85beca9270cc4c
| 9,848
|
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.explorer.client.parameter.schema;
import com.google.api.explorer.client.base.ApiMethod;
import com.google.api.explorer.client.base.ApiMethod.HttpMethod;
import com.google.api.explorer.client.base.ApiService;
import com.google.api.explorer.client.base.Schema;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.json.client.JSONBoolean;
import com.google.gwt.json.client.JSONException;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.SimpleCheckBox;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
/**
* UI for constructing a request body based on the schema of the expected
* request.
*
* @author jasonhall@google.com (Jason Hall)
*/
public class SchemaForm extends Composite {
interface SchemaFormUiBinder extends UiBinder<Widget, SchemaForm> {
}
public @UiField HTMLPanel root;
private SchemaEditor editor;
private ApiMethod method;
public SchemaForm(UiBinder<Widget, SchemaForm> uiBinder) {
initWidget(uiBinder.createAndBindUi(this));
}
public SchemaForm() {
this((SchemaFormUiBinder) GWT.create(SchemaFormUiBinder.class));
}
/**
* Returns the JSON string value of the current state of the object shown in
* this form.
*/
public String getStringValue() {
if (editor == null) {
return "";
}
StringBuilder builder = new StringBuilder();
editor.prettyPrint(builder, 0);
return builder.toString();
}
/**
* Returns the JSON format of the current state of the object.
*/
public JSONObject getJSONObject() {
return editor.getJSONValue().isObject();
}
/**
* Set the value of the base editor to the JSON value recursively.
*
* @throws JSONException if the JSON can not be applied to the editor cleanly.
*/
public void setJSONValue(JSONValue value) {
// May not yet be initialized with a schema.
if (editor != null) {
editor.setJSONValue(value);
}
}
/** Sets the {@link Schema} to be displayed in this form. */
public void setSchema(ApiService service, ApiMethod method, Schema schema) {
this.method = method;
this.editor = getSchemaEditorForSchema(service, schema,
/* This is the root element and descendats should be nullable, if also patch. */ true);
root.clear();
root.add(editor.render(schema));
}
private boolean methodIsPatch() {
return method.getHttpMethod().equals(HttpMethod.PATCH);
}
/** Returns the SchemaEditor for the given Property value. */
SchemaEditor getSchemaEditorForSchema(
ApiService service, Schema schema, boolean descendantsNullable) {
Schema dereferenced = schema;
if (schema.getRef() != null) {
// Properties of this object are defined elsewhere.
dereferenced = service.getSchemas().get(schema.getRef());
}
SchemaEditor editor;
if (dereferenced.getType() != null) {
switch (dereferenced.getType()) {
case OBJECT:
editor = new ObjectSchemaEditor(this,
method.getId(),
service,
dereferenced.getProperties(),
dereferenced.getAdditionalProperties(),
methodIsPatch() && descendantsNullable);
break;
case ARRAY:
editor = new ArraySchemaEditor(service, this, dereferenced.getItems());
break;
case BOOLEAN:
editor = new BooleanSchemaEditor();
break;
case INTEGER:
case NUMBER:
editor = new NumberSchemaEditor();
break;
case ANY:
case STRING:
default:
editor = new StringSchemaEditor();
}
} else {
editor = new StringSchemaEditor();
}
return editor;
}
/** Base interface for all schema-based editors. */
interface SchemaEditor {
static final String INDENTATION = " ";
/** Returns a widget displaying the UI for the user to fill in. */
Widget render(Schema property);
/**
* Returns the JSON value of the single property defined displayed by this
* editor.
*/
JSONValue getJSONValue();
/**
* Recursively bind the JSON provided to the editors.
*
* @throws JSONException if the JSON can not be applied to the editor cleanly.
*/
void setJSONValue(JSONValue value);
/**
* Add results from our calculation on to the existing results.
*/
void prettyPrint(StringBuilder resultSoFar, int indentation);
/**
* Returns whether or not this schema editor is composed of other schema editors.
*/
boolean isComposite();
}
/** Editor for string values. */
static class StringSchemaEditor implements SchemaEditor {
private HasText hasText;
@Override
public Widget render(Schema property) {
HTMLPanel panel = new HTMLPanel("");
panel.getElement().getStyle().setDisplay(Display.INLINE);
panel.add(new InlineLabel("\""));
if (property.locked()) {
InlineLabel label = new InlineLabel();
panel.add(label);
hasText = label;
} else {
TextArea editor = new TextArea();
panel.add(editor);
hasText = editor;
}
panel.add(new InlineLabel("\""));
if (property.getDefault() != null) {
hasText.setText(property.getDefault());
}
return panel;
}
@Override
public JSONValue getJSONValue() {
return new JSONString(hasText.getText());
}
@Override
public void setJSONValue(JSONValue value) {
JSONString stringVal = value.isString();
if (stringVal != null) {
hasText.setText(stringVal.stringValue());
} else {
throw new JSONException("Not a valid JSON string: " + value.toString());
}
}
@Override
public void prettyPrint(StringBuilder resultSoFar, int indentation) {
resultSoFar.append(getJSONValue().toString());
}
@Override
public boolean isComposite() {
return false;
}
}
/** Editor for numerical values. */
static class NumberSchemaEditor implements SchemaEditor {
private TextBox textbox;
@Override
public Widget render(Schema property) {
textbox = new TextBox();
if (property.getDefault() != null) {
textbox.setValue(property.getDefault());
}
return textbox;
}
@Override
public JSONValue getJSONValue() {
// Try to parse the value as a number.
double val;
try {
val = Double.valueOf(textbox.getValue());
} catch (NumberFormatException nfe) {
// If the value is not a number, pass it as a string.
return new JSONString(textbox.getValue());
}
return new JSONNumber(val);
}
@Override
public void setJSONValue(JSONValue value) {
JSONNumber numberVal = value.isNumber();
JSONString stringVal = value.isString();
if (numberVal != null) {
textbox.setValue(String.valueOf(numberVal.doubleValue()));
} else if (stringVal != null){
textbox.setValue(stringVal.stringValue());
} else {
throw new JSONException("Not a valid JSON number: " + value.toString());
}
}
@Override
public void prettyPrint(StringBuilder resultSoFar, int indentation) {
resultSoFar.append(getJSONValue().toString());
}
@Override
public boolean isComposite() {
return false;
}
}
/** Editor for boolean values. */
static class BooleanSchemaEditor implements SchemaEditor {
private SimpleCheckBox checkbox;
@Override
public Widget render(Schema property) {
checkbox = new SimpleCheckBox();
// Set it to true if that is the default.
checkbox.setValue("true".equals(property.getDefault()));
// If this property is locked, disable the checkbox
if (property.locked()) {
checkbox.setEnabled(false);
}
return checkbox;
}
@Override
public JSONValue getJSONValue() {
return JSONBoolean.getInstance(checkbox.getValue());
}
@Override
public void setJSONValue(JSONValue value) {
JSONBoolean boolVal = value.isBoolean();
JSONString stringVal = value.isString();
if (boolVal != null) {
checkbox.setValue(boolVal.booleanValue());
} else if (stringVal != null) {
checkbox.setValue(Boolean.parseBoolean(stringVal.stringValue()));
} else {
throw new JSONException("Not a valid JSON boolean: " + value.toString());
}
}
@Override
public void prettyPrint(StringBuilder resultSoFar, int indentation) {
resultSoFar.append(getJSONValue().toString());
}
@Override
public boolean isComposite() {
return false;
}
}
}
| 28.544928
| 95
| 0.662571
|
f017ab9f3deb2bacc3f758811c6495cad214f226
| 1,276
|
/*
* Copyright 2012 - 2016 Manuel Laggner
*
* 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.tinymediamanager.scraper;
import org.tinymediamanager.scraper.entities.MediaType;
/**
* The UnsupportedMediaTypeException is used to indicate that the given media type cannot be used for the chosen meta data provider
*
* @author Manuel Laggner
* @since 1.0
*/
public class UnsupportedMediaTypeException extends Exception {
private static final long serialVersionUID = 2860692702692312793L;
private MediaType type;
public UnsupportedMediaTypeException(MediaType type) {
this.type = type;
}
@Override
public String toString() {
return "The media type " + type.name() + " is not supported by this meta data provider";
}
}
| 32.717949
| 131
| 0.742163
|
6859b61cba7e8874ae0d630eaad2fd04c50240a7
| 5,207
|
package dev.mieser.tsa.web.controller;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.jupiter.params.provider.Arguments.arguments;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.springframework.http.HttpHeaders.CONTENT_TYPE;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import java.io.InputStream;
import java.util.Arrays;
import java.util.stream.Stream;
import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import dev.mieser.tsa.domain.TimeStampResponseData;
import dev.mieser.tsa.integration.api.IssueTimeStampService;
import dev.mieser.tsa.signing.api.exception.InvalidTspRequestException;
import dev.mieser.tsa.signing.api.exception.TspResponseException;
import dev.mieser.tsa.signing.api.exception.UnknownHashAlgorithmException;
@WebMvcTest
@ContextConfiguration(classes = TimeStampAuthorityController.class)
class TimeStampAuthorityControllerTest {
private static final String REQUEST_CONTENT_TYPE = "application/timestamp-query";
private static final String REPLY_CONTENT_TYPE = "application/timestamp-reply";
private final MockMvc mockMvc;
@MockBean
private IssueTimeStampService issueTimeStampServiceMock;
@Autowired
TimeStampAuthorityControllerTest(MockMvc mockMvc) {
this.mockMvc = mockMvc;
}
@Test
void doesNotAcceptOtherContentTypes() throws Exception {
// given / when / then
mockMvc.perform(post("/").contentType(APPLICATION_JSON))
.andExpect(status().isUnsupportedMediaType());
}
@Test
void setsExpectedResponseContentType() throws Exception {
// given
byte[] requestContent = "TSP request".getBytes(UTF_8);
byte[] responseContent = "TSP response".getBytes(UTF_8);
TimeStampResponseData issuedResponse = TimeStampResponseData.builder()
.asnEncoded(responseContent)
.build();
given(issueTimeStampServiceMock.signTimestampRequest(any())).willReturn(issuedResponse);
// when / then
mockMvc.perform(post("/")
.content(requestContent)
.contentType(REQUEST_CONTENT_TYPE)
.accept(REPLY_CONTENT_TYPE))
.andExpect(status().isOk())
.andExpect(header().stringValues(CONTENT_TYPE, REPLY_CONTENT_TYPE));
}
@Test
void returnsAsnEncodedTspResponseInBody() throws Exception {
// given
byte[] requestContent = "TSP request".getBytes(UTF_8);
byte[] responseContent = "TSP response".getBytes(UTF_8);
TimeStampResponseData issuedResponse = TimeStampResponseData.builder()
.asnEncoded(responseContent)
.build();
given(issueTimeStampServiceMock.signTimestampRequest(any())).willAnswer(invocation -> {
InputStream actualStream = invocation.getArgument(0);
byte[] actualContent = IOUtils.toByteArray(actualStream);
return Arrays.equals(actualContent, requestContent) ? issuedResponse : null;
});
// when / then
mockMvc.perform(post("/")
.content(requestContent)
.contentType(REQUEST_CONTENT_TYPE)
.accept(REPLY_CONTENT_TYPE))
.andExpect(status().isOk())
.andExpect(content().bytes(responseContent));
}
@ParameterizedTest
@MethodSource("exceptionToStatusCodeProvider")
void mapsExceptionToExpectedStatusCode(RuntimeException exception, HttpStatus expectedStatus) throws Exception {
// given
byte[] requestContent = "TSP request".getBytes(UTF_8);
given(issueTimeStampServiceMock.signTimestampRequest(any())).willThrow(exception);
// when / then
mockMvc.perform(post("/")
.content(requestContent)
.contentType(REQUEST_CONTENT_TYPE)
.accept(REPLY_CONTENT_TYPE))
.andExpect(status().is(expectedStatus.value()));
}
static Stream<Arguments> exceptionToStatusCodeProvider() {
return Stream.of(
arguments(new InvalidTspRequestException("Test", new IllegalStateException()), BAD_REQUEST),
arguments(new UnknownHashAlgorithmException("Test"), BAD_REQUEST),
arguments(new TspResponseException("Test", new IllegalStateException()), INTERNAL_SERVER_ERROR));
}
}
| 39.748092
| 116
| 0.732476
|
2a002f0e81f468c6839ceccf7fc4811967a568d7
| 11,983
|
/*
* 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.
*
* Modifications copyright (c) 2017 Lambda^3
* 07.02.2017 - Modified/repacked version from Apache Jena.
*
*/
package net.stargraph;
/*-
* ==========================License-Start=============================
* stargraph-model
* --------------------------------------------------------------------
* Copyright (C) 2017 Lambda^3
* --------------------------------------------------------------------
* 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.
* ==========================License-End===============================
*/
/**
* Code to split an URI or IRI into prefix and local part.
* Historically, 'prefix' is referred to as 'namespace'
* reflecting RDF/XML history.
* <p>
* For display, use {@link #localname} and {@link #namespace}.
* This follows Turtle, adds some pragmatic rulesm but does not escape
* any characters. A URI is split never split before the last {@code /}
* or last {@code #}, if present.
* See {@link #splitpoint} for more details.
* <p>
*/
final class SplitIRI {
/**
* Return the 'namespace' (prefix) for a URI string.
* Use with {@link #localname}
*/
public static String namespace(String string) {
int i = splitpoint(string);
if (i < 0)
return string;
return string.substring(0, i);
}
/**
* Calculate a localname - do not escape PN_LOCAL_ESC.
* This is not guaranteed to be legal Turtle.
* Use with {@link #namespace}
*/
public static String localname(String string) {
int i = splitpoint(string);
if (i < 0)
return "";
return string.substring(i);
}
/**
* Return the 'namespace' (prefix) for a URI string,
* legal for Turtle and goes with {@link #localnameTTL}
*/
public static String namespaceTTL(String string) {
return namespace(string);
}
/**
* Calculate a localname - enforce legal Turle
* escape PN_LOCAL_ESC, check for final '.'
* Use with {@link #namespaceTTL}
*/
public static String localnameTTL(String string) {
String x = localname(string);
if (x.isEmpty())
return x;
return escape_PN_LOCAL_ESC(x);
}
private static String escape_PN_LOCAL_ESC(String x) {
// Assume that escapes are rare so scan once to make sure there
// is work to do then scan again doing the work.
//'\' ('_' | '~' | '.' | '-' | '!' | '$' | '&' | "'" | '(' | ')' | '*' | '+' | ',' | ';' | '=' | '/' | '?' | '#' | '@' | '%')
int N = x.length();
boolean escchar = false;
for (int i = 0; i < N; i++) {
char ch = x.charAt(i);
if (needsEscape(ch, (i == N - 1))) {
escchar = true;
break;
}
}
if (!escchar)
return x;
StringBuilder sb = new StringBuilder(N + 10);
for (int i = 0; i < N; i++) {
char ch = x.charAt(i);
// DOT only needs escaping at the end
if (needsEscape(ch, (i == N - 1)))
sb.append('\\');
sb.append(ch);
}
return sb.toString();
}
private static boolean needsEscape(char ch, boolean finalChar) {
if (ch == '.')
return finalChar;
return isPN_LOCAL_ESC(ch);
}
// @formatter:off
/* From the RDF 1.1 Turtle specification:
[136s] PrefixedName ::= PNAME_LN | PNAME_NS
Productions for terminals
[163s] PN_CHARS_BASE ::= [A-Z] | [a-z] | [#x00C0-#x00D6] | [#x00D8-#x00F6] | [#x00F8-#x02FF] | [#x0370-#x037D] | [#x037F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
[164s] PN_CHARS_U ::= PN_CHARS_BASE | '_'
[166s] PN_CHARS ::= PN_CHARS_U | '-' | [0-9] | #x00B7 | [#x0300-#x036F] | [#x203F-#x2040]
[167s] PN_PREFIX ::= PN_CHARS_BASE ((PN_CHARS | '.')* PN_CHARS)?
[168s] PN_LOCAL ::= (PN_CHARS_U | ':' | [0-9] | PLX) ((PN_CHARS | '.' | ':' | PLX)* (PN_CHARS | ':' | PLX))?
[169s] PLX ::= PERCENT | PN_LOCAL_ESC
[170s] PERCENT ::= '%' HEX HEX
[171s] HEX ::= [0-9] | [A-F] | [a-f]
[172s] PN_LOCAL_ESC ::= '\' ('_' | '~' | '.' | '-' | '!' | '$' | '&' | "'" | '(' | ')' | '*' | '+' | ',' | ';' | '=' | '/' | '?' | '#' | '@' | '%')
*/
// @formatter:on
/**
* Find the URI split point, return the index into the string that is the
* first character of a legal Turtle local name.
* <p>
* This is a pragmatic choice, not just finding the maximal point.
* For example, with escaping '/' can be included but that means
* {@code http://example/path/abc} could split to give {@code http://example/}
* and {@code path/abc} .
* <p>
* Split URN's after ':'.
*
* @param uri URI string
* @return The split point, or -1 for "not found".
*/
public static int splitpoint(String uri) {
boolean isURN = uri.startsWith("urn:");
// Fast track. Still need to check validity of the prefix part.
int idx1 = uri.lastIndexOf('#');
// Not so simple - \/ in local names
int idx2 = isURN ? uri.lastIndexOf(':') : uri.lastIndexOf('/');
// If absolute.
int idx3 = uri.indexOf(':');
// Note: local names can't end in "." in Turtle.
// This is handled by escape_PN_LOCAL_ESC which will escape it as "\."
// Test the discovered local part.
// Limit is exclusive.
int limit = Math.max(idx1, idx2);
limit = Math.max(limit, idx3);
limit = Math.max(-1, limit);
int splitPoint = -1;
// Work backwards, checking for
// ((PN_CHARS | '.' | ':' | PLX)*
for (int i = uri.length() - 1; i > limit; i--) {
char ch = uri.charAt(i);
if ( /*RiotChars.*/isPNChars_U_N(ch) || /*RiotChars.*/isPN_LOCAL_ESC(ch) || ch == ':' || ch == '-' || ch == '.')
continue;
splitPoint = i + 1;
break;
}
// limit was at the end. No split point (we could escape the limit point)
if (splitPoint == -1)
splitPoint = limit + 1;
// No split point.
if (splitPoint >= uri.length())
return -1;
// Check the first character of the local name.
// All character are legal localname name characters but may not satisfy the additional
// first character rule. Move forward to first legal first character.
int ch = uri.charAt(splitPoint);
while (ch == '.' || ch == '-') {
splitPoint++;
if (splitPoint >= uri.length())
return -1;
ch = uri.charAt(splitPoint);
}
// Checking the final '.' is done when checking for escapes.
return splitPoint;
}
private static boolean checkhex(String uri, int i) {
return /*RiotChars.*/isHexChar(uri.charAt(i));
}
// Extracted from RiotChars
// When/if RIOT becomes accessible to this code, then refactor
private static boolean /*RiotChars.*/isPN_LOCAL_ESC(char ch) {
switch (ch) {
case '\\':
case '_':
case '~':
case '.':
case '-':
case '!':
case '$':
case '&':
case '\'':
case '(':
case ')':
case '*':
case '+':
case ',':
case ';':
case '=':
case '/':
case '?':
case '#':
case '@':
case '%':
return true;
default:
return false;
}
}
/**
* ASCII 0-9
*/
private static boolean isDigit(int ch) {
return range(ch, '0', '9');
}
private static boolean isPNCharsBase(int ch) {
// PN_CHARS_BASE ::= [A-Z] | [a-z] | [#x00C0-#x00D6] | [#x00D8-#x00F6] | [#x00F8-#x02FF] |
// [#x0370-#x037D] | [#x037F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] |
// [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] |
// [#x10000-#xEFFFF]
return
r(ch, 'a', 'z') || r(ch, 'A', 'Z') || r(ch, 0x00C0, 0x00D6) || r(ch, 0x00D8, 0x00F6) || r(ch, 0x00F8, 0x02FF) ||
r(ch, 0x0370, 0x037D) || r(ch, 0x037F, 0x1FFF) || r(ch, 0x200C, 0x200D) || r(ch, 0x2070, 0x218F) ||
r(ch, 0x2C00, 0x2FEF) || r(ch, 0x3001, 0xD7FF) ||
// Surrogate pairs
r(ch, 0xD800, 0xDFFF) ||
r(ch, 0xF900, 0xFDCF) || r(ch, 0xFDF0, 0xFFFD) ||
r(ch, 0x10000, 0xEFFFF); // Outside the basic plain.
}
private static boolean isPNChars_U(int ch) {
//PN_CHARS_BASE | '_'
return isPNCharsBase(ch) || (ch == '_');
}
private static boolean isPNChars_U_N(int ch) {
// PN_CHARS_U | [0-9]
return isPNCharsBase(ch) || (ch == '_') || isDigit(ch);
}
private static boolean isPNChars(int ch) {
// PN_CHARS ::= PN_CHARS_U | '-' | [0-9] | #x00B7 | [#x0300-#x036F] | [#x203F-#x2040]
return isPNChars_U(ch) || isDigit(ch) || (ch == '-') || ch == 0x00B7 || r(ch, 0x300, 0x036F) || r(ch, 0x203F, 0x2040);
}
/**
* Hexadecimal character
*/
private static boolean isHexChar(int ch) {
return range(ch, '0', '9') || range(ch, 'a', 'f') || range(ch, 'A', 'F');
}
private static int valHexChar(int ch) {
if (range(ch, '0', '9'))
return ch - '0';
if (range(ch, 'a', 'f'))
return ch - 'a' + 10;
if (range(ch, 'A', 'F'))
return ch - 'A' + 10;
return -1;
}
private static boolean r(int ch, int a, int b) {
return (ch >= a && ch <= b);
}
private static boolean range(int ch, char a, char b) {
return (ch >= a && ch <= b);
}
}
| 36.64526
| 271
| 0.524159
|
bc5a232fe1e6c3d111729a70065e95e7ba472c4c
| 934
|
package fr.itris.glips.library.geom.path.segment;
import java.awt.geom.*;
import org.apache.batik.ext.awt.geom.*;
/**
* the class that handles close path instructions
* @author ITRIS, Jordi SUC
*/
public class ClosePathSegment extends Segment{
/**
* a constructor of the class
* @param previousSegment the segment that lies just before this segment
*/
public ClosePathSegment(Segment previousSegment){
super(previousSegment);
initialize();
}
@Override
public void initialize() {
this.absoluteCmdName="Z";
this.relativeCmdName="z";
}
@Override
public void storeValues() {}
@Override
public void fillPath(ExtendedGeneralPath path) {
path.closePath();
super.fillPath(path);
}
@Override
public void applyTransform(AffineTransform transform) {}
@Override
public void modifyPoint(Point2D point, int index) {}
@Override
public String toString() {
return absoluteCmdName;
}
}
| 17.961538
| 73
| 0.720557
|
322eb84efcd406515a44f4a70f3605d5fc4e65c8
| 560
|
/*
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.stetho.websocket;
/**
* Close codes as defined by RFC6455.
*/
public interface CloseCodes {
int NORMAL_CLOSURE = 1000;
int PROTOCOL_ERROR = 1002;
int CLOSED_ABNORMALLY = 1006;
int UNEXPECTED_CONDITION = 1011;
}
| 26.666667
| 78
| 0.723214
|
1c8f50bb9421187ca9ecf6a0590440eecc898599
| 1,115
|
package com.gmail.andersoninfonet.dsmovie.entities;
import java.io.Serializable;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name = "tb_score")
public class Score implements Serializable {
@EmbeddedId
private ScorePK id = new ScorePK();
private Double value;
/**
*
*/
public Score() {
}
/**
* @param movie the movie to set
*/
public void setMovie(final Movie movie) {
id.setMovie(movie);
}
/**
* @param user the user to set
*/
public void setUser(final User user) {
id.setUser(user);
}
/**
* @return the id
*/
public ScorePK getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(final ScorePK id) {
this.id = id;
}
/**
* @return the value
*/
public Double getValue() {
return value;
}
/**
* @param value the value to set
*/
public void setValue(final Double value) {
this.value = value;
}
}
| 16.893939
| 51
| 0.559641
|
ba4a337ff32ec3443572deda7a72812c4c634f98
| 7,078
|
package github.algmaknick.Heart_Sound_Stethoscope_for_android;
import android.graphics.Canvas;
import android.graphics.Paint;
class AxisTickLabels {
private static final String[] axisNames = {"Hz", "dB", "Sec", "Hz", "Pitch"}; // See GridLabel.Type
// Draw ticks and labels for a axisMap.
// labelPaint should use fixed width font
static void draw(Canvas c, ScreenPhysicalMapping axisMap, GridLabel gridLabel,
float axisBeginX, float axisBeginY, int directionI, int labelSide,
Paint labelPaint, Paint gridPaint, Paint rulerBrightPaint) {
String axisName = axisNames[gridLabel.getGridType().getValue()];
float textHeight = labelPaint.getFontMetrics(null);
float labelLargeLen = 0.7f * textHeight;
float labelSmallLen = 0.6f * labelLargeLen;
// directionI: 0:+x, 1:+y, 2:-x, 3:-y
// labelSide: 1: label at positive side of axis, -1: otherwise
boolean drawOnXAxis = directionI % 2 == 0;
int directionSign = directionI <=1 ? 1 : -1;
// Plot axis marks
float posAlongAxis;
for (int k = 0; k < 2; k ++) {
float labelLen = (k == 0 ? labelSmallLen : labelLargeLen) * labelSide;
Paint tickPainter = k == 0 ? gridPaint : rulerBrightPaint;
double[] values = k == 0 ? gridLabel.ticks : gridLabel.values;
for (int i = 0; i < values.length; i++) {
posAlongAxis = (float)axisMap.pixelFromV(values[i]) * directionSign;
if (drawOnXAxis) {
c.drawLine(axisBeginX + posAlongAxis, axisBeginY,
axisBeginX + posAlongAxis, axisBeginY + labelLen, tickPainter);
} else {
c.drawLine(axisBeginX, axisBeginY + posAlongAxis,
axisBeginX + labelLen, axisBeginY + posAlongAxis, tickPainter);
}
}
}
// Straight line
if (drawOnXAxis) {
c.drawLine(axisBeginX, axisBeginY, axisBeginX + (float)axisMap.nCanvasPixel * (1-directionI), axisBeginY, labelPaint);
} else {
c.drawLine(axisBeginX, axisBeginY, axisBeginX, axisBeginY + (float)axisMap.nCanvasPixel * (2-directionI), labelPaint);
}
// Plot labels
float widthDigit = labelPaint.measureText("0");
float widthAxisName = widthDigit * axisName.length();
float widthAxisNameExt = widthAxisName +.5f*widthDigit; // with a safe boundary
// For drawOnXAxis == true
float axisNamePosX = directionSign==1
? - widthAxisNameExt + (float)axisMap.nCanvasPixel
: - widthAxisNameExt;
// For drawOnXAxis == false
// always show y-axis name at the smaller (in pixel) position.
float axisNamePosY = directionSign==1
? textHeight
: textHeight - (float)axisMap.nCanvasPixel;
if (gridLabel.getGridType() == GridLabel.Type.DB) {
// For dB axis, show axis name far from 0dB (directionSign==1)
axisNamePosY = (float)axisMap.nCanvasPixel - 0.8f*widthDigit;
}
float labelPosY = axisBeginY + ( labelSide == 1 ? 0.1f*labelLargeLen + textHeight : -0.3f*labelLargeLen);
float labelPosX;
int notShowNextLabel = 0;
for(int i = 0; i < gridLabel.strings.length; i++) {
posAlongAxis = (float)axisMap.pixelFromV(gridLabel.values[i]) * directionSign;
float thisDigitWidth = drawOnXAxis ? widthDigit*gridLabel.strings[i].length() + 0.3f*widthDigit
: -textHeight;
float axisNamePos = drawOnXAxis ? axisNamePosX
: axisNamePosY;
float axisNameLen = drawOnXAxis ? widthAxisNameExt
: -textHeight;
// Avoid label overlap:
// (1) No overlap to axis name like "Hz";
// (2) If no (1), no overlap to important label 1, 10, 100, 1000, 10000, 1k, 10k;
// (3) If no (1) and (2), no overlap to previous label.
if (isIntvOverlap(posAlongAxis, thisDigitWidth,
axisNamePos, axisNameLen)) {
continue; // case (1)
}
if (notShowNextLabel > 0) {
notShowNextLabel--;
continue; // case (3)
}
int j = i+1;
while (j < gridLabel.strings.length) {
float nextDigitPos = (float)axisMap.pixelFromV(gridLabel.values[j]) * directionSign;
float nextDigitWidth = drawOnXAxis ? widthDigit*gridLabel.strings[j].length() + 0.3f*widthDigit
: -textHeight;
if (! isIntvOverlap(posAlongAxis, thisDigitWidth,
nextDigitPos, nextDigitWidth)) {
break; // no overlap of case (3)
}
notShowNextLabel++;
if (gridLabel.isImportantLabel(j)) {
// do not show label i (case (2))
// but also check case (1) for label j
if (! isIntvOverlap(nextDigitPos, nextDigitWidth,
axisNamePos, axisNameLen)) {
notShowNextLabel = -1;
break;
}
}
j++;
}
if (notShowNextLabel == -1) {
notShowNextLabel = j - i - 1; // show the label in case (2)
continue;
}
// Now safe to draw label
if (drawOnXAxis) {
c.drawText(gridLabel.chars[i], 0, gridLabel.strings[i].length(),
axisBeginX + posAlongAxis, labelPosY, labelPaint);
} else {
labelPosX = labelSide == -1
? axisBeginX - 0.5f * labelLargeLen - widthDigit * gridLabel.strings[i].length()
: axisBeginX + 0.5f * labelLargeLen;
c.drawText(gridLabel.chars[i], 0, gridLabel.strings[i].length(),
labelPosX, axisBeginY + posAlongAxis, labelPaint);
}
}
if (drawOnXAxis) {
c.drawText(axisName, axisBeginX + axisNamePosX, labelPosY, labelPaint);
} else {
labelPosX = labelSide == -1
? axisBeginX - 0.5f * labelLargeLen - widthAxisName
: axisBeginX + 0.5f * labelLargeLen;
c.drawText(axisName, labelPosX, axisBeginY + axisNamePosY, labelPaint);
}
}
// Return true if two intervals [pos1, pos1+len1] [pos2, pos2+len2] overlaps.
private static boolean isIntvOverlap(float pos1, float len1, float pos2, float len2) {
if (len1 < 0) { pos1 -= len1; len1 = -len1; }
if (len2 < 0) { pos2 -= len2; len2 = -len2; }
return pos1 <= pos2 && pos2 <= pos1+len1 || pos2 <= pos1 && pos1 <= pos2+len2;
}
}
| 47.503356
| 130
| 0.539983
|
b39b0a792c06b28dce88a7275a348d6e2fc627c2
| 5,044
|
package bgp.utils;
/**
* Builds IPv4 packets.
* @author Niko
*
*/
public class PacketEngine {
private static final int HEADER_LENGTH = 20;
/**
* Only IPv4 is supported in this simulation
*/
private static final byte VERSION = 4;
/**
* No IPv4 packet options are supported => IHL = 5 always
*/
private static final byte IHL = 5;
/**
* Only the default type of service is supported
*/
private static final byte DSCP = 0;
/**
* Explicit Congestion Notification is not implemented.
*/
private static final byte ECN = 0;
/**
* Start all packets with TTL 255;
*/
private static final byte DEFAULT_TTL = (byte) 255;
/**
* Since there is no difference in implementation, mark all packets as UDP.
*/
private static final byte DEFAULT_PROTOCOL = (byte) 17;
public static byte[] buildPacket(Address from, Address to, byte[] payload) {
return buildPacket(from.address, to.address, payload);
}
public static byte[] buildPacket(long from, long to, byte[] payload) {
int totalLen = HEADER_LENGTH + payload.length;
byte[] result = new byte[totalLen];
result[0] = (VERSION << 4) + IHL;
result[1] = (DSCP << 2) + ECN;
result[2] = (byte) (totalLen >> 8);
result[3] = (byte) (totalLen);
// No fragmentation necessary, ID can be 0
result[4] = 0;
result[5] = 0;
// 0: Reserved, must be zero, 1: Don't fragment, 0: More fragments
result[6] = (0b010 << 5) + 0;
result[7] = 0;
result[8] = DEFAULT_TTL;
result[9] = DEFAULT_PROTOCOL;
// Checksum is calculated after all values are in place
result[12] = (byte) (from >> 24);
result[13] = (byte) (from >> 16);
result[14] = (byte) (from >> 8);
result[15] = (byte) (from);
result[16] = (byte) (to >> 24);
result[17] = (byte) (to >> 16);
result[18] = (byte) (to >> 8);
result[19] = (byte) (to);
long checksum = calculateChecksum(result);
result[10] = (byte) (checksum >> 8);
result[11] = (byte) (checksum);
System.arraycopy(payload, 0, result, HEADER_LENGTH, payload.length);
return result;
}
/**
* Decrements the TTL counter in the packet by one and recalculates the checksum.
* </br><b>PASSED PARAMETER ARRAY IS MUTATED!</b>
*
* @param packet
* @throws IllegalArgumentException Exception is thrown if TTL is 0
*/
public static void decrementTTL(byte[] packet) throws IllegalArgumentException {
if (packet[8] == 0) {
throw new IllegalArgumentException("TTL is already zero");
}
packet[8] = (byte) ((packet[8] - 1)&0xFF);
// Reset the values to avoid affecting the checcksum
packet[10] = 0;
packet[11] = 0;
long checksum = calculateChecksum(packet);
packet[10] = (byte) ((checksum >>> 8)&0xFF);
packet[11] = (byte) (checksum&0xFF);
}
public static long calculateChecksum(byte[] packet) {
// AND operations with 0xFF's are in place to avoid type casting to int
long calculatedChecksum = 0;
for (int i = 0; i < HEADER_LENGTH; i += 2) {
calculatedChecksum = (calculatedChecksum | (((packet[i] << 8)&0xFF00) | (packet[i+1]&0x00FF)))
&0xFFFFFFFF;
}
while ((calculatedChecksum&0xFFFFFFFF) > 0xFFFF) {
calculatedChecksum = (((calculatedChecksum&0xFFFF0000) >>> 16)
| (calculatedChecksum&0x0000FFFF))&0xFFFFFFFF;
}
return (~calculatedChecksum) & 0xFFFF;
}
/**
* Validates the packet header by checking packet length, header checksum, IP version and header length
* @param packet
* @return true if packet header is correct, false otherwise
*/
public static boolean validatePacketHeader(byte[] packet) {
if (packet.length < 20) {
// Received packet is not long enough to hold header
return false;
}
if (!verifyChecksum(packet)) {
// Invalid checksum
return false;
}
if (((packet[0]&0xF0)>>>4) != VERSION) {
// Invalid IP version
return false;
}
if ((packet[0]&0x0F) < 5) {
// IHL is less than 5
return false;
}
if (((packet[0]&0x0F) << 2) > (((packet[2]&0xFF) << 8)&0xFF00) + (packet[3]&0xFF)) {
// Datagram is too short to contain header
return false;
}
return true;
}
public static boolean verifyChecksum(byte[] packet) {
return calculateChecksum(packet) == 0;
}
public static byte[] extractBody(byte[] packet) {
int headerOctets = (packet[0]&0x0F) << 2;
int totalOctets = (((packet[2]&0xFF) << 8)&0xFF00) + (packet[3]&0xFF);
int bodyOctets = totalOctets - headerOctets;
byte[] result = new byte[bodyOctets];
System.arraycopy(packet, headerOctets, result, 0, bodyOctets);
return result;
}
public static long extractSender(byte[] packet) {
return (((packet[12] << 24)&0xFF000000)
| ((packet[13] << 16)&0x00FF0000)
| ((packet[14] << 8)&0x0000FF00)
| ((packet[15])&0x000000FF))&0xFFFFFFFFL;
}
public static long extractRecipient(byte[] packet) {
return (((packet[16] << 24)&0xFF000000L)
| ((packet[17] << 16)&0x00FF0000L)
| ((packet[18] << 8)&0x0000FF00L)
| ((packet[19])&0x000000FFL))&0xFFFFFFFFL;
}
public static int extractTTL(byte[] packet) {
return packet[8]&0xFF;
}
}
| 27.714286
| 104
| 0.644726
|
5c9f13a336a748705da36327deb197d7c235c355
| 2,285
|
package br.jus.trf2.balcaojus;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import com.crivano.swaggerservlet.SwaggerCall;
import com.crivano.swaggerservlet.SwaggerCallParameters;
import com.crivano.swaggerservlet.SwaggerMultipleCallResult;
import br.jus.trf2.balcaojus.AutenticarPost.Usuario;
import br.jus.trf2.balcaojus.IBalcaojus.IPeticaoIntercorrenteListarGet;
import br.jus.trf2.balcaojus.IBalcaojus.PeticaoIntercorrenteResumo;
import br.jus.trf2.sistemaprocessual.ISistemaProcessual.IUsuarioUsernamePeticaoIntercorrenteListarGet;
import br.jus.trf2.sistemaprocessual.ISistemaProcessual.PeticaoIntercorrente;
public class PeticaoIntercorrenteListarGet implements IPeticaoIntercorrenteListarGet {
@Override
public void run(Request req, Response resp, BalcaojusContext ctx) throws Exception {
Usuario u = BalcaojusServlet.getPrincipal();
Map<String, SwaggerCallParameters> mapp = new HashMap<>();
IUsuarioUsernamePeticaoIntercorrenteListarGet.Request q = new IUsuarioUsernamePeticaoIntercorrenteListarGet.Request();
q.data = req.data;
for (String system : Utils.getSystems()) {
mapp.put(system,
new SwaggerCallParameters(system + " - obter resumos de petições intercorrentes",
Utils.getApiPassword(system), "GET",
Utils.getApiUrl(system) + "/usuario/" + u.usuario + "/peticao-intercorrente/listar", q,
IUsuarioUsernamePeticaoIntercorrenteListarGet.Response.class));
}
SwaggerMultipleCallResult mcr = SwaggerCall.callMultiple(mapp, BalcaojusServlet.TIMEOUT_MILLISECONDS);
resp.status = Utils.getStatus(mcr);
resp.list = new ArrayList<>();
for (String system : mcr.responses.keySet()) {
IUsuarioUsernamePeticaoIntercorrenteListarGet.Response r = (IUsuarioUsernamePeticaoIntercorrenteListarGet.Response) mcr.responses
.get(system);
if (r.list != null)
for (PeticaoIntercorrente i : r.list) {
PeticaoIntercorrenteResumo t = new PeticaoIntercorrenteResumo();
t.processo = i.processo;
t.protocolo = i.protocolo;
t.dataprotocolo = i.dataprotocolo;
t.classe = i.classe;
t.sistema = system;
t.unidade = i.unidade;
resp.list.add(t);
}
}
}
@Override
public String getContext() {
return "obter resumo de petições intercorrentes";
}
}
| 37.459016
| 132
| 0.774179
|
60c6f62c98de1781db61283743ffd6a186b4adef
| 2,615
|
/**
* Copyright 2005-2016 Red Hat, Inc.
*
* Red Hat 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 io.fabric8.itests.common;
import io.fabric8.api.FabricService;
import io.fabric8.api.ZooKeeperClusterBootstrap;
import io.fabric8.api.gravia.ServiceLocator;
import io.fabric8.itests.support.CommandSupport;
import java.io.InputStream;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.osgi.StartLevelAware;
import org.jboss.osgi.metadata.OSGiManifestBuilder;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.Asset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Test basic {@link ZooKeeperClusterBootstrap} functionality
*
* @since 27-Jan-2014
*/
@RunWith(Arquillian.class)
public class BootstrapServiceTest {
@Deployment
@StartLevelAware(autostart = true)
public static Archive<?> deployment() {
final JavaArchive archive = ShrinkWrap.create(JavaArchive.class, "bootstrap-service-test.jar");
archive.addPackage(CommandSupport.class.getPackage());
archive.setManifest(new Asset() {
@Override
public InputStream openStream() {
OSGiManifestBuilder builder = OSGiManifestBuilder.newInstance();
builder.addBundleManifestVersion(2);
builder.addBundleSymbolicName(archive.getName());
builder.addBundleVersion("1.0.0");
builder.addImportPackages(ServiceLocator.class, FabricService.class);
return builder.openStream();
}
});
return archive;
}
@Test
public void testZooKeeperClusterBootstrapAvailable() throws Exception {
ZooKeeperClusterBootstrap bootstrap = ServiceLocator.getRequiredService(ZooKeeperClusterBootstrap.class);
Assert.assertNotNull("ZooKeeperClusterBootstrap not null", bootstrap);
}
}
| 37.357143
| 113
| 0.728107
|
cc706916380099ab9a83c29429bbeea33d874062
| 6,064
|
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The contents of this file are subject to the terms of either the Universal Permissive License
* v 1.0 as shown at http://oss.oracle.com/licenses/upl
*
* or the following license:
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions
* and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmc.rjmx.internal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.openjdk.jmc.common.io.IOToolkit;
import org.openjdk.jmc.rjmx.ConnectionException;
import org.openjdk.jmc.rjmx.IConnectionDescriptor;
import org.openjdk.jmc.rjmx.IConnectionHandle;
import org.openjdk.jmc.rjmx.IConnectionListener;
import org.openjdk.jmc.rjmx.IServerDescriptor;
import org.openjdk.jmc.rjmx.IServerHandle;
public final class ServerHandle implements IServerHandle {
private final List<DefaultConnectionHandle> connectionHandles = new ArrayList<>();
private final RJMXConnection connection;
private final Runnable observer;
private Boolean disposedGracefully; // null if not yet disposed
private final Runnable connectionListener = new Runnable() {
@Override
public void run() {
disconnect();
}
};
private final IConnectionListener connectionHandleListener = new IConnectionListener() {
@Override
public void onConnectionChange(IConnectionHandle handle) {
if (!handle.isConnected() && removeConnectionHandle(handle)) {
nofifyObserver();
}
}
};
public ServerHandle(IConnectionDescriptor descriptor) {
this(new ServerDescriptor(), descriptor, null);
}
public ServerHandle(IServerDescriptor server, IConnectionDescriptor descriptor, Runnable observer) {
this.observer = observer;
connection = new RJMXConnection(descriptor, server, connectionListener);
}
public IConnectionDescriptor getConnectionDescriptor() {
return connection.getConnectionDescriptor();
}
@Override
public IServerDescriptor getServerDescriptor() {
return connection.getServerDescriptor();
}
public synchronized IConnectionHandle[] getConnectionHandles() {
IConnectionHandle[] handles = new IConnectionHandle[connectionHandles.size()];
Iterator<DefaultConnectionHandle> it = connectionHandles.iterator();
for (int i = 0; i < handles.length; i++) {
handles[i] = it.next();
}
return handles;
}
@Override
public IConnectionHandle connect(String usage) throws ConnectionException {
IConnectionListener[] listeners = new IConnectionListener[] {connectionHandleListener};
return doConnect(usage, listeners);
}
@Override
public IConnectionHandle connect(String usage, IConnectionListener listener) throws ConnectionException {
IConnectionListener[] listeners = new IConnectionListener[] {listener, connectionHandleListener};
return doConnect(usage, listeners);
}
private IConnectionHandle doConnect(String usage, IConnectionListener[] listeners) throws ConnectionException {
boolean performedConnect;
DefaultConnectionHandle newConnectionHandle;
synchronized (this) {
if (isDisposed()) {
throw new ConnectionException("Server handle is disposed"); //$NON-NLS-1$
}
performedConnect = connection.connect();
newConnectionHandle = new DefaultConnectionHandle(connection, usage, listeners);
connectionHandles.add(newConnectionHandle);
}
if (performedConnect) {
nofifyObserver();
}
return newConnectionHandle;
}
public void dispose(boolean gracefully) {
synchronized (this) {
if (!isDisposed()) {
disposedGracefully = gracefully;
}
}
disconnect();
}
@Override
public void dispose() {
dispose(true);
}
private synchronized boolean isDisposed() {
return disposedGracefully != null;
}
private synchronized boolean removeConnectionHandle(IConnectionHandle handle) {
connectionHandles.remove(handle);
if (connectionHandles.size() == 0) {
connection.close();
return true;
}
return false;
}
@Override
public void close() {
disconnect();
}
private void disconnect() {
for (IConnectionHandle handle : getConnectionHandles()) {
IOToolkit.closeSilently(handle);
}
}
@Override
public String toString() {
return connection.toString();
}
private void nofifyObserver() {
if (observer != null) {
observer.run();
}
}
@Override
public synchronized State getState() {
if (isDisposed()) {
return disposedGracefully ? State.DISPOSED : State.FAILED;
} else {
return connection.isConnected() ? State.CONNECTED : State.DISCONNECTED;
}
}
@Override
protected void finalize() throws Throwable {
disconnect();
super.finalize();
}
}
| 31.915789
| 112
| 0.759894
|
e6fa4fbaccd01ea0a268e54424390de8b5157214
| 2,165
|
package com.am.bp.alf.innovations;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.kafka.config.KafkaListenerEndpointRegistry;
import org.springframework.kafka.listener.MessageListenerContainer;
import org.springframework.kafka.test.rule.KafkaEmbedded;
import org.springframework.kafka.test.utils.ContainerTestUtils;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { ListenerConfig.class, KafkaListenerEndpointRegistry.class,
ListenerService.class }, webEnvironment = WebEnvironment.NONE)
@ActiveProfiles("junittest")
@ComponentScan("com.am.bp.alf.innovations")
// @EntityScan("com.am.bp.alf.innovations")
public class SenderServiceTest {
private static final Logger LOGGER = LoggerFactory.getLogger(SenderServiceTest.class);
private static String BATCH_TOPIC = "junittest.user.activity.logs.t";
@Autowired
private SenderService senderService;
@Autowired
private ListenerService listenerService;
@Autowired
private KafkaListenerEndpointRegistry kafkaListenerEndpointRegistry;
@ClassRule
public static KafkaEmbedded embeddedKafka = new KafkaEmbedded(1, true, BATCH_TOPIC);
@Before
public void setUp() throws Exception {
for (MessageListenerContainer messageListenerContainer : kafkaListenerEndpointRegistry
.getListenerContainers()) {
ContainerTestUtils.waitForAssignment(messageListenerContainer, embeddedKafka.getPartitionsPerTopic());
}
}
@Test
public void testReceive() throws Exception {
for (int i = 0; i < 100; i++) {
senderService.send(BATCH_TOPIC, "message " + i);
}
}
}
| 35.491803
| 114
| 0.776443
|
10ae07510ca77abb19a3eb9f496248b5b519768b
| 1,314
|
// SPDX-License-Identifier: MIT
package com.mercedesbenz.sechub.domain.authorization.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mercedesbenz.sechub.domain.authorization.AuthUser;
import com.mercedesbenz.sechub.domain.authorization.AuthUserRepository;
import com.mercedesbenz.sechub.sharedkernel.Step;
import com.mercedesbenz.sechub.sharedkernel.usecases.user.UseCaseUserClicksLinkToGetNewAPIToken;
import com.mercedesbenz.sechub.sharedkernel.validation.UserInputAssertion;
@Service
public class AuthUpdateUserApiTokenService {
private static final Logger LOG = LoggerFactory.getLogger(AuthUpdateUserApiTokenService.class);
@Autowired
AuthUserRepository userRepo;
@Autowired
UserInputAssertion assertion;
@UseCaseUserClicksLinkToGetNewAPIToken(@Step(number = 3, next = { Step.NO_NEXT_STEP }, name = "Update auth data"))
public void updateAPIToken(String userId, String hashedApiToken) {
assertion.assertIsValidUserId(userId);
AuthUser user = userRepo.findOrFail(userId);
user.setHashedApiToken(hashedApiToken);
userRepo.save(user);
LOG.debug("API token for user:{} updated", userId);
}
}
| 33.692308
| 118
| 0.789193
|
b082432de1ea96224a6ba6eccca640e022555c20
| 3,197
|
/*
* 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 org.zols.links.web;
import java.util.List;
import org.slf4j.Logger;
import static org.slf4j.LoggerFactory.getLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import static org.springframework.web.bind.annotation.RequestMethod.DELETE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
import static org.springframework.web.bind.annotation.RequestMethod.PUT;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.zols.datatore.exception.DataStoreException;
import org.zols.links.domain.LinkGroup;
import org.zols.links.domain.Link;
import org.zols.links.service.LinkGroupService;
@RestController
@RequestMapping(value="/api/link_groups")
public class LinkGroupController {
private static final Logger LOGGER = getLogger(LinkGroupController.class);
@Autowired
private LinkGroupService linkGroupService;
@RequestMapping(method = POST)
public LinkGroup create(@RequestBody LinkGroup group) throws DataStoreException {
LOGGER.info("Creating new categories {}", group);
return linkGroupService.create(group);
}
@RequestMapping(value = "/{name}", method = GET)
public LinkGroup read(@PathVariable(value = "name") String name) throws DataStoreException {
LOGGER.info("Getting group ", name);
return linkGroupService.read(name);
}
@RequestMapping(value = "/{name}", method = PUT)
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void update(@PathVariable(value = "name") String name,
@RequestBody LinkGroup group) throws DataStoreException {
if (name.equals(group.getName())) {
LOGGER.info("Updating categories with id {} with {}", name, group);
linkGroupService.update(group);
}
}
@RequestMapping(value = "/{name}", method = DELETE)
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void delete(@PathVariable(value = "name") String name) throws DataStoreException {
LOGGER.info("Deleting categories with id {}", name);
linkGroupService.delete(name);
}
@RequestMapping(method = GET)
public List<LinkGroup> list() throws DataStoreException {
LOGGER.info("Getting categories ");
return linkGroupService.list();
}
@RequestMapping(value = "/{name}/first_level_links", method = GET)
public List<Link> listFirstLevelLinks(@PathVariable(value = "name") String name) throws DataStoreException {
LOGGER.info("Getting first level links of group {} ",name);
return linkGroupService.getFirstLevelLinks(name);
}
}
| 41.519481
| 112
| 0.732562
|
c0d3aa27e65d238a9bc678dc7887e0bc626383f0
| 5,211
|
/*
* Criteo API Transition Swagger
* This is used to help Criteo clients transition from MAPI to Criteo API
*
* The version of the OpenAPI document: 1.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.criteo.marketing.model;
import java.util.Objects;
import java.util.Arrays;
import com.criteo.marketing.model.AdSetTargeting;
import com.criteo.marketing.model.PatchAdSetBidding;
import com.criteo.marketing.model.PatchAdSetBudget;
import com.criteo.marketing.model.PatchAdSetScheduling;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
/**
* ad set patch model
*/
@ApiModel(description = "ad set patch model")
public class PatchAdSet {
public static final String SERIALIZED_NAME_NAME = "name";
@SerializedName(SERIALIZED_NAME_NAME)
private String name;
public static final String SERIALIZED_NAME_SCHEDULING = "scheduling";
@SerializedName(SERIALIZED_NAME_SCHEDULING)
private PatchAdSetScheduling scheduling;
public static final String SERIALIZED_NAME_BIDDING = "bidding";
@SerializedName(SERIALIZED_NAME_BIDDING)
private PatchAdSetBidding bidding;
public static final String SERIALIZED_NAME_TARGETING = "targeting";
@SerializedName(SERIALIZED_NAME_TARGETING)
private AdSetTargeting targeting;
public static final String SERIALIZED_NAME_BUDGET = "budget";
@SerializedName(SERIALIZED_NAME_BUDGET)
private PatchAdSetBudget budget;
public PatchAdSet name(String name) {
this.name = name;
return this;
}
/**
* Name of the ad set
* @return name
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "Name of the ad set")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public PatchAdSet scheduling(PatchAdSetScheduling scheduling) {
this.scheduling = scheduling;
return this;
}
/**
* Get scheduling
* @return scheduling
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public PatchAdSetScheduling getScheduling() {
return scheduling;
}
public void setScheduling(PatchAdSetScheduling scheduling) {
this.scheduling = scheduling;
}
public PatchAdSet bidding(PatchAdSetBidding bidding) {
this.bidding = bidding;
return this;
}
/**
* Get bidding
* @return bidding
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public PatchAdSetBidding getBidding() {
return bidding;
}
public void setBidding(PatchAdSetBidding bidding) {
this.bidding = bidding;
}
public PatchAdSet targeting(AdSetTargeting targeting) {
this.targeting = targeting;
return this;
}
/**
* Get targeting
* @return targeting
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public AdSetTargeting getTargeting() {
return targeting;
}
public void setTargeting(AdSetTargeting targeting) {
this.targeting = targeting;
}
public PatchAdSet budget(PatchAdSetBudget budget) {
this.budget = budget;
return this;
}
/**
* Get budget
* @return budget
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public PatchAdSetBudget getBudget() {
return budget;
}
public void setBudget(PatchAdSetBudget budget) {
this.budget = budget;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PatchAdSet patchAdSet = (PatchAdSet) o;
return Objects.equals(this.name, patchAdSet.name) &&
Objects.equals(this.scheduling, patchAdSet.scheduling) &&
Objects.equals(this.bidding, patchAdSet.bidding) &&
Objects.equals(this.targeting, patchAdSet.targeting) &&
Objects.equals(this.budget, patchAdSet.budget);
}
@Override
public int hashCode() {
return Objects.hash(name, scheduling, bidding, targeting, budget);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PatchAdSet {\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" scheduling: ").append(toIndentedString(scheduling)).append("\n");
sb.append(" bidding: ").append(toIndentedString(bidding)).append("\n");
sb.append(" targeting: ").append(toIndentedString(targeting)).append("\n");
sb.append(" budget: ").append(toIndentedString(budget)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 23.057522
| 92
| 0.696603
|
ee7bae7769a29f921915148b7b2ea56e9267c27e
| 7,422
|
package org.metaborg.spoofax.core;
import org.metaborg.core.MetaBorgGeneric;
import org.metaborg.core.MetaborgException;
import org.metaborg.core.plugin.IModulePluginLoader;
import org.metaborg.spoofax.core.analysis.ISpoofaxAnalysisService;
import org.metaborg.spoofax.core.build.ISpoofaxBuilder;
import org.metaborg.spoofax.core.completion.ISpoofaxCompletionService;
import org.metaborg.spoofax.core.outline.ISpoofaxOutlineService;
import org.metaborg.spoofax.core.processing.ISpoofaxProcessorRunner;
import org.metaborg.spoofax.core.processing.analyze.ISpoofaxAnalysisResultProcessor;
import org.metaborg.spoofax.core.processing.parse.ISpoofaxParseResultProcessor;
import org.metaborg.spoofax.core.stratego.IStrategoCommon;
import org.metaborg.spoofax.core.stratego.IStrategoRuntimeService;
import org.metaborg.spoofax.core.style.ISpoofaxCategorizerService;
import org.metaborg.spoofax.core.style.ISpoofaxStylerService;
import org.metaborg.spoofax.core.syntax.ISpoofaxSyntaxService;
import org.metaborg.spoofax.core.terms.ITermFactoryService;
import org.metaborg.spoofax.core.tracing.ISpoofaxHoverService;
import org.metaborg.spoofax.core.tracing.ISpoofaxResolverService;
import org.metaborg.spoofax.core.tracing.ISpoofaxTracingService;
import org.metaborg.spoofax.core.transform.ISpoofaxTransformService;
import org.metaborg.spoofax.core.unit.ISpoofaxAnalyzeUnit;
import org.metaborg.spoofax.core.unit.ISpoofaxAnalyzeUnitUpdate;
import org.metaborg.spoofax.core.unit.ISpoofaxInputUnit;
import org.metaborg.spoofax.core.unit.ISpoofaxParseUnit;
import org.metaborg.spoofax.core.unit.ISpoofaxTransformUnit;
import org.metaborg.spoofax.core.unit.ISpoofaxUnitService;
import org.spoofax.interpreter.terms.IStrategoTerm;
import com.google.inject.Module;
import com.google.inject.util.Types;
/**
* Facade for instantiating and accessing the Metaborg API, instantiated with the Spoofax implementation.
*/
@SuppressWarnings("hiding")
public class Spoofax extends
MetaBorgGeneric<ISpoofaxInputUnit, ISpoofaxParseUnit, ISpoofaxAnalyzeUnit, ISpoofaxAnalyzeUnitUpdate, ISpoofaxTransformUnit<?>, ISpoofaxTransformUnit<ISpoofaxParseUnit>, ISpoofaxTransformUnit<ISpoofaxAnalyzeUnit>, IStrategoTerm> {
public final ISpoofaxUnitService unitService;
public final ISpoofaxSyntaxService syntaxService;
public final ISpoofaxAnalysisService analysisService;
public final ISpoofaxTransformService transformService;
public final ISpoofaxBuilder builder;
public final ISpoofaxProcessorRunner processorRunner;
public final ISpoofaxParseResultProcessor parseResultProcessor;
public final ISpoofaxAnalysisResultProcessor analysisResultProcessor;
public final ISpoofaxTracingService tracingService;
public final ISpoofaxCategorizerService categorizerService;
public final ISpoofaxStylerService stylerService;
public final ISpoofaxHoverService hoverService;
public final ISpoofaxResolverService resolverService;
public final ISpoofaxOutlineService outlineService;
public final ISpoofaxCompletionService completionService;
public final ITermFactoryService termFactoryService;
public final IStrategoRuntimeService strategoRuntimeService;
public final IStrategoCommon strategoCommon;
/**
* Instantiate the MetaBorg API with a Spoofax implementation.
*
* @param loader
* Module plugin loader to use.
* @param module
* Spoofax module to use.
* @param additionalModules
* Additional modules to use.
*
* @throws MetaborgException
* When loading plugins or dependency injection fails.
*/
public Spoofax(IModulePluginLoader loader, SpoofaxModule module, Module... additionalModules)
throws MetaborgException {
super(ISpoofaxInputUnit.class, ISpoofaxParseUnit.class, ISpoofaxAnalyzeUnit.class,
ISpoofaxAnalyzeUnitUpdate.class,
Types.newParameterizedType(ISpoofaxTransformUnit.class, Types.subtypeOf(Object.class)),
Types.newParameterizedType(ISpoofaxTransformUnit.class, ISpoofaxParseUnit.class),
Types.newParameterizedType(ISpoofaxTransformUnit.class, ISpoofaxAnalyzeUnit.class), IStrategoTerm.class,
loader, module, additionalModules);
this.unitService = injector.getInstance(ISpoofaxUnitService.class);
this.syntaxService = injector.getInstance(ISpoofaxSyntaxService.class);
this.analysisService = injector.getInstance(ISpoofaxAnalysisService.class);
this.transformService = injector.getInstance(ISpoofaxTransformService.class);
this.builder = injector.getInstance(ISpoofaxBuilder.class);
this.processorRunner = injector.getInstance(ISpoofaxProcessorRunner.class);
this.parseResultProcessor = injector.getInstance(ISpoofaxParseResultProcessor.class);
this.analysisResultProcessor = injector.getInstance(ISpoofaxAnalysisResultProcessor.class);
this.tracingService = injector.getInstance(ISpoofaxTracingService.class);
this.categorizerService = injector.getInstance(ISpoofaxCategorizerService.class);
this.stylerService = injector.getInstance(ISpoofaxStylerService.class);
this.hoverService = injector.getInstance(ISpoofaxHoverService.class);
this.resolverService = injector.getInstance(ISpoofaxResolverService.class);
this.outlineService = injector.getInstance(ISpoofaxOutlineService.class);
this.completionService = injector.getInstance(ISpoofaxCompletionService.class);
this.termFactoryService = injector.getInstance(ITermFactoryService.class);
this.strategoRuntimeService = injector.getInstance(IStrategoRuntimeService.class);
this.strategoCommon = injector.getInstance(IStrategoCommon.class);
}
/**
* Instantiate the MetaBorg API with a Spoofax implementation.
*
* @param module
* Spoofax module to use.
* @param additionalModules
* Additional modules to use.
*
* @throws MetaborgException
* When loading plugins or dependency injection fails.
*/
public Spoofax(SpoofaxModule module, Module... additionalModules) throws MetaborgException {
this(defaultPluginLoader(), module, additionalModules);
}
/**
* Instantiate the MetaBorg API with a Spoofax implementation.
*
* @param loader
* Module plugin loader to use.
* @param additionalModules
* Additional modules to use.
*
* @throws MetaborgException
* When loading plugins or dependency injection fails.
*/
public Spoofax(IModulePluginLoader loader, Module... additionalModules) throws MetaborgException {
this(loader, defaultModule(), additionalModules);
}
/**
* Instantiate the MetaBorg API with a Spoofax implementation.
*
* @param additionalModules
* Additional modules to use.
*
* @throws MetaborgException
* When loading plugins or dependency injection fails.
*/
public Spoofax(Module... additionalModules) throws MetaborgException {
this(defaultPluginLoader(), defaultModule(), additionalModules);
}
protected static SpoofaxModule defaultModule() {
return new SpoofaxModule();
}
}
| 45.814815
| 234
| 0.758151
|
8833f849c80d22d99169b4da21f68fe4c6bf5e64
| 5,563
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.test.txtimer.ejb;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.util.Collection;
import java.util.Iterator;
import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.ejb.TimedObject;
import javax.ejb.Timer;
import org.jboss.logging.Logger;
/**
* TxTimer test bean
*
* @author Dimitris.Andreadis@jboss.org
* @version $Revision: 57211 $
*/
public class TimerTestBean implements SessionBean, TimedObject
{
private Logger log = Logger.getLogger(TimerTestBean.class.getName());
private SessionContext context;
public TimerTestBean()
{
// empty
}
public void setSessionContext(SessionContext newContext) throws EJBException
{
context = newContext;
}
public void ejbCreate() throws CreateException {}
public void ejbRemove() throws EJBException, RemoteException {}
public void ejbActivate() throws EJBException, RemoteException {}
public void ejbPassivate() throws EJBException, RemoteException {}
public void ejbTimeout(Timer timer)
{
log.info("ejbTimeout: " + timer);
}
// Business Interface --------------------------------------------
/**
* @ejb.interface-method
* @ejb.transaction type = "Required"
* @throws EJBException Thrown if method fails due to system-level error.
*/
public void startTimerInTxRequired() throws EJBException
{
startTimer("Required");
}
/**
* @ejb.interface-method
* @ejb.transaction type = "RequiresNew"
* @throws EJBException Thrown if method fails due to system-level error.
*/
public void startTimerInTxRequiresNew() throws EJBException
{
startTimer("RequiresNew");
}
/**
* @ejb.interface-method
* @ejb.transaction type = "Never"
* @throws EJBException Thrown if method fails due to system-level error.
*/
public void startTimerInTxNever() throws EJBException
{
startTimer("Never");
}
/**
* @ejb.interface-method
* @ejb.transaction type = "NotSupported"
* @throws EJBException Thrown if method fails due to system-level error.
*/
public void startTimerInTxNotSupported() throws EJBException
{
startTimer("NotSupported");
}
/**
* @ejb.interface-method
*/
public int listAllTimers()
{
Collection timers = context.getTimerService().getTimers();
String s = "Timers: ";
for (Iterator it = timers.iterator();it.hasNext();)
{
Timer t = (Timer)it.next();
s = s + t.toString() + " ";
try
{
s += t.getInfo();
}
catch (Exception ignore)
{
// empty
}
s += "\n";
}
log.info(s);
return timers.size();
}
/**
* @ejb.interface-method
* @ejb.transaction type = "Required"
* @throws EJBException Thrown if method fails due to system-level error.
*/
public void cancelTimerInTxRequired() throws EJBException
{
cancelTimers();
}
/**
* @ejb.interface-method
* @ejb.transaction type = "RequiresNew"
* @throws EJBException Thrown if method fails due to system-level error.
*/
public void cancelTimerInTxRequiresNew() throws EJBException
{
cancelTimers();
}
/**
* @ejb.interface-method
* @ejb.transaction type = "Never"
* @throws EJBException Thrown if method fails due to system-level error.
*/
public void cancelTimerInTxNever() throws EJBException
{
cancelTimers();
}
/**
* @ejb.interface-method
* @ejb.transaction type = "NotSupported"
* @throws EJBException Thrown if method fails due to system-level error.
*/
public void cancelTimerInTxNotSupported() throws EJBException
{
cancelTimers();
}
// Private -------------------------------------------------------
private void startTimer(Serializable info)
{
log.info("Starting timer, info=" + info);
context.getTimerService().createTimer(10000, info);
}
private void cancelTimers()
{
Collection timers = context.getTimerService().getTimers();
for (Iterator it = timers.iterator(); it.hasNext(); )
{
Timer t = (Timer)it.next();
log.info("Cancelling timer " + t + " " + t.getInfo());
t.cancel();
log.info("Timer is now " + t);
}
}
}
| 28.09596
| 79
| 0.637606
|
8877564ffcee851c479a8659e88ae8a93bb92d23
| 6,803
|
/*
* Copyright (c) 2014.
* Mikol Faro <mikol.faro@gmail.com>
* Simone Mangano <simone.mangano@ieee.org>
* Mattia Tortorelli <mattia.tortorelli@gmail.com>
*
* 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 org.biokoframework.system.services.authentication.simple.impl;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.biokoframework.system.ConfigurationEnum;
import org.biokoframework.system.entity.login.Login;
import org.biokoframework.system.entity.login.LoginBuilder;
import org.biokoframework.system.exceptions.CommandExceptionsFactory;
import org.biokoframework.system.repository.memory.InMemoryRepository;
import org.biokoframework.system.repository.service.IRepositoryService;
import org.biokoframework.system.services.authentication.AuthResponse;
import org.biokoframework.system.services.authentication.AuthenticationFailureException;
import org.biokoframework.system.services.entity.EntityModule;
import org.biokoframework.system.services.entity.IEntityBuilderService;
import org.biokoframework.system.services.repository.RepositoryModule;
import org.biokoframework.utils.domain.EntityBuilder;
import org.biokoframework.utils.exception.ValidationException;
import org.biokoframework.utils.fields.Fields;
import org.biokoframework.utils.repository.Repository;
import org.biokoframework.utils.repository.RepositoryException;
import org.biokoframework.utils.validation.ValidationModule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.util.Collections;
import static org.biokoframework.utils.matcher.Matchers.error;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
/**
* @author Mikol Faro <mikol.faro@gmail.com>
* @date 2014-03-12
*/
public class SimpleAuthenticationServiceTest {
private Injector fInjector;
private Repository<Login> fLoginRepo;
private EntityBuilder<Login> fLoginBuilder;
private IEntityBuilderService fEntitiesBuilder;
@Rule
public ExpectedException expected = ExpectedException.none();
@Before
public void createInjector() {
fInjector = Guice.createInjector(
new EntityModule(),
new ValidationModule(),
new RepositoryModule(ConfigurationEnum.DEV) {
@Override
protected void configureForDev() {
bindRepositoryTo(InMemoryRepository.class);
}
@Override
protected void configureForDemo() {}
@Override
protected void configureForProd() {}
}
);
fLoginRepo = fInjector.getInstance(IRepositoryService.class).getRepository(Login.class);
fLoginBuilder = fInjector.getInstance(LoginBuilder.class);
fEntitiesBuilder = fInjector.getInstance(IEntityBuilderService.class);
}
@Test
public void simpleAuthenticationTest() throws AuthenticationFailureException, ValidationException, RepositoryException {
Login login = fLoginBuilder.loadDefaultExample().build(false);
login = fLoginRepo.save(login);
SimpleAuthenticationService authenticationService = fInjector.getInstance(SimpleAuthenticationService.class);
Fields fields = new Fields(
Login.USER_EMAIL, login.get(Login.USER_EMAIL),
Login.PASSWORD, login.get(Login.PASSWORD));
AuthResponse response = authenticationService.authenticate(fields, Collections.<String>emptyList());
assertThat(response, is(notNullValue()));
assertThat((String) response.getMergeFields().get("authLoginId"), is(equalTo(login.getId())));
}
@Test
public void failBecauseUserDoesNotExist() throws AuthenticationFailureException {
Login login = fLoginBuilder.loadDefaultExample().build(false);
SimpleAuthenticationService authenticationService = fInjector.getInstance(SimpleAuthenticationService.class);
Fields fields = new Fields(
Login.USER_EMAIL, login.get(Login.USER_EMAIL),
Login.PASSWORD, login.get(Login.PASSWORD));
expected.expect(AuthenticationFailureException.class);
expected.expect(error(CommandExceptionsFactory.createInvalidLoginException().getErrors().get(0)));
authenticationService.authenticate(fields, Collections.<String>emptyList());
}
@Test
public void failBecauseBadPassword() throws ValidationException, RepositoryException, AuthenticationFailureException {
Login login = fLoginBuilder.loadDefaultExample().build(false);
login = fLoginRepo.save(login);
SimpleAuthenticationService authenticationService = fInjector.getInstance(SimpleAuthenticationService.class);
Fields fields = new Fields(
Login.USER_EMAIL, login.get(Login.USER_EMAIL),
Login.PASSWORD, "A Wrong Password");
expected.expect(AuthenticationFailureException.class);
expected.expect(error(CommandExceptionsFactory.createInvalidLoginException().getErrors().get(0)));
authenticationService.authenticate(fields, Collections.<String>emptyList());
}
@Test
public void failBecauseAuthInfosAreNotFound() throws AuthenticationFailureException {
SimpleAuthenticationService authenticationService = fInjector.getInstance(SimpleAuthenticationService.class);
Fields fields = new Fields();
expected.expect(AuthenticationFailureException.class);
expected.expect(error(CommandExceptionsFactory.createUnauthorisedAccessException().getErrors().get(0)));
authenticationService.authenticate(fields, Collections.<String>emptyList());
}
}
| 44.175325
| 124
| 0.744083
|
30fa2ef74b6d2d3be735109d26ea6bdf7ccafd11
| 939
|
package org.ingrahamrobotics.robot2013.commands;
/**
*
*/
public class FrisbeeHolderSolenoidsExtend extends CommandBase {
private boolean isFinished;
/**
* Default Constructor
*/
public FrisbeeHolderSolenoidsExtend() {
requires(frisbeeHolderSolenoids);
}
/**
* Initializes this command. (Preparation for execute())
*/
protected void initialize() {
isFinished = false;
}
/**
* Execute this command. (Called multiple times through execution)
*/
protected void execute() {
frisbeeHolderSolenoids.extend();
frisbeeHolderSolenoids.outputStatus();
isFinished = true;
}
/**
* @return whether or not this command is finished.
*/
protected boolean isFinished() {
return isFinished;
}
/**
* Ends this command (Called after isFinished returns true)
*/
protected void end() {
}
}
| 20.413043
| 70
| 0.617678
|
13fd3b1e191b6f2f65326f7d5af03cbc83d99e5e
| 1,983
|
package views.editor.toolbox;
import java.awt.*;
import javax.swing.*;
import misc.SelectorComponent;
import models.ToolModel;
import models.tikz.TikzComponent;
import controllers.editor.toolbox.SelectorController;
/**
* Implementation of the View (from the MVC architectural pattern) for the
* Selector. The Selector is part of the toolbox used to choose which component
* is selected.
*/
public class SelectorView extends JPanel implements SelectorComponent.SelectorComponentListener {
private final JScrollPane scrollzone;
private final JPanel options;
private final SelectorController controller;
private final ToolView parentView;
/**
* Constructs a new view for the Selector with a given ToolModel
*
* @param parentView
* @param model
*/
public SelectorView(ToolView parentView, ToolModel model) {
this.parentView = parentView;
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
options = new JPanel(new GridLayout(1, 0));
scrollzone = new JScrollPane(options);
this.add(scrollzone);
controller = new SelectorController(this, model);
}
/**
* Adds a SelectorComponent (tikz element) to this view
*
* @param comp
* The component
*/
protected void addComponent(SelectorComponent comp) {
options.add(comp);
}
/**
* Set the number of components contained in the view
*
* @param nbr
* The number of components
*/
public void setComponentNbr(int nbr) {
((GridLayout) options.getLayout()).setRows(nbr);
}
/**
* Informs the controller which component is being selected
*
* @param component
* The selected component
*/
@Override
public void componentSelected(TikzComponent component) {
controller.itemSelected(component);
}
public ToolView getParentView() {
return parentView;
}
}
| 27.164384
| 97
| 0.663641
|
9bf45e9a23d186e0052dd60f63d5bfb59e2b6b76
| 3,255
|
/*
* 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 za.co.trojanc.ups.gui.service;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.networkupstools.jnut.Client;
import org.networkupstools.jnut.Device;
import org.networkupstools.jnut.NutException;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import za.co.trojanc.ups.gui.entity.UPSConfig;
/**
*
* @author charl
*/
public class UpsService {
private List<UPSConfig> configs = new ArrayList<>();
private static final UpsService singleton = new UpsService();
private UpsService(){}
public static UpsService get(){
return singleton;
}
public void init(){
System.out.println("Home" + System.getProperty("user.home"));
loadConfigurationFile();
}
private void loadConfigurationFile(){
try{
Path upsClientHome = Paths.get(System.getProperty("user.home"), ".ups-client");
// If the file doesnt exist, we create one
if(!Files.exists(upsClientHome)){
Files.createDirectories(upsClientHome);
}
Path upsInstanceConfiguration = upsClientHome.resolve("instances.json");
if(!Files.exists(upsInstanceConfiguration)){
Files.createFile(upsInstanceConfiguration);
}
loadInstances(upsInstanceConfiguration);
}catch(IOException ioe){
ioe.printStackTrace();
}
}
private void loadInstances(Path filePath){
JSONArray instances = readJson(filePath);
int size = instances.size();
for(int idx = 0 ; idx < size ; idx++){
JSONObject jo = instances.getJSONObject(0);
UPSConfig config = (UPSConfig)JSONObject.toBean(jo, UPSConfig.class);
configs.add(config);
}
}
private void writeJson(JSON json, Path filePath){
Charset charset = Charset.forName("UTF-8");
String s = json.toString(4);
try (BufferedWriter writer = Files.newBufferedWriter(filePath, charset)) {
writer.write(s, 0, s.length());
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
}
private JSONArray readJson(Path instanceConfig){
Charset charset = Charset.forName("UTF-8");
StringBuilder sb = new StringBuilder();
try (BufferedReader reader = Files.newBufferedReader(instanceConfig, charset)) {
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
String data = sb.toString();
if(data.length() <2){
return null;
}
return JSONArray.fromObject(data);
}
public Device getClient(int upsId){
try {UPSConfig config = configs.get(upsId);
Client client = new Client(config.getHost(), config.getPort(), config.getLogin(), config.getPasswd());
return client.getDevice(config.getUpsName());
} catch (IOException | NutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public void addUps(UPSConfig config){
}
}
| 26.04
| 104
| 0.718587
|
abb4b952082c5e3655e267e1eb32042949a66a9c
| 218
|
package com.jesen.customglide.loaddata;
import android.content.Context;
/**
* 加载外部资源
*/
public interface ILoadData {
void loadResource(String path, LoadResponseListener responseListener, Context context);
}
| 16.769231
| 92
| 0.766055
|
c44dab65ea77162f82e2fa5a935d90726d29778a
| 2,565
|
/*
* Copyright 2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package bingo.odata;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class ODataUrlInfo {
private final String serviceRootUri;
private final ODataResourcePath resourcePath;
private final String resourceUri;
private final ODataQueryOptions queryOptions;
private final Map<String, String> pathParameters = new HashMap<String, String>();
public ODataUrlInfo(String serviceRootUri, String resourcePath, String queryString) {
super();
this.serviceRootUri = serviceRootUri;
this.resourcePath = new ODataResourcePath(resourcePath);
this.resourceUri = serviceRootUri + resourcePath.substring(1);
this.queryOptions = new ODataQueryOptions(queryString);
}
public ODataUrlInfo(String serviceRootUri, String resourcePath, Map<String, String> queryOptions) {
super();
this.serviceRootUri = serviceRootUri;
this.resourcePath = new ODataResourcePath(resourcePath);
this.resourceUri = serviceRootUri + resourcePath.substring(1);
this.queryOptions = new ODataQueryOptions(queryOptions);
}
public String getServiceRootUri() {
return serviceRootUri;
}
public ODataResourcePath getResourcePath() {
return resourcePath;
}
public String getResourceUri() {
return resourceUri;
}
public ODataQueryOptions getQueryOptions(){
return queryOptions;
}
public Set<String> getPathParameterNames(){
return pathParameters.keySet();
}
public String getPathParameter(String name){
return pathParameters.get(name);
}
public Map<String,String> getPathParametersMap(){
return pathParameters;
}
public void setPathParameter(String name,String value){
pathParameters.put(name, value);
}
public void setPathParameters(Map<String, String> params){
pathParameters.clear();
pathParameters.putAll(params);
}
}
| 31.280488
| 101
| 0.716179
|
a1e13ddc14ee9e6f715c9f5dc8689cc0c55d12dd
| 3,241
|
package com.weichu.mdesigner.api.vo;
import java.math.BigDecimal;
/**
* 消费满多少规则1
* @author Administrator
*
*/
public class MerchantGoodsSubtractVo {
private Integer id;
private Integer merchantId;
private Integer constraintType;
private Integer type;
private BigDecimal consumePrice;
private BigDecimal amount1;
private BigDecimal amount2;
private BigDecimal discount;
private String constraintTimeStart;
private String constraintTimeEnd;
private String description;
private String enabled;
private String effectiveTime;
private String effectiveStatus;
private String expiredTime;
private String expiredStatus;
private String remark;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getMerchantId() {
return merchantId;
}
public void setMerchantId(Integer merchantId) {
this.merchantId = merchantId;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public BigDecimal getConsumePrice() {
return consumePrice;
}
public void setConsumePrice(BigDecimal consumePrice) {
this.consumePrice = consumePrice;
}
public BigDecimal getAmount1() {
return amount1;
}
public void setAmount1(BigDecimal amount1) {
this.amount1 = amount1;
}
public BigDecimal getAmount2() {
return amount2;
}
public void setAmount2(BigDecimal amount2) {
this.amount2 = amount2;
}
public BigDecimal getDiscount() {
return discount;
}
public void setDiscount(BigDecimal discount) {
this.discount = discount;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getEnabled() {
return enabled;
}
public void setEnabled(String enabled) {
this.enabled = enabled;
}
public String getEffectiveTime() {
return effectiveTime;
}
public void setEffectiveTime(String effectiveTime) {
this.effectiveTime = effectiveTime;
}
public String getEffectiveStatus() {
return effectiveStatus;
}
public void setEffectiveStatus(String effectiveStatus) {
this.effectiveStatus = effectiveStatus;
}
public String getExpiredTime() {
return expiredTime;
}
public void setExpiredTime(String expiredTime) {
this.expiredTime = expiredTime;
}
public String getExpiredStatus() {
return expiredStatus;
}
public void setExpiredStatus(String expiredStatus) {
this.expiredStatus = expiredStatus;
}
public String getConstraintTimeStart() {
return constraintTimeStart;
}
public void setConstraintTimeStart(String constraintTimeStart) {
this.constraintTimeStart = constraintTimeStart;
}
public String getConstraintTimeEnd() {
return constraintTimeEnd;
}
public void setConstraintTimeEnd(String constraintTimeEnd) {
this.constraintTimeEnd = constraintTimeEnd;
}
public Integer getConstraintType() {
return constraintType;
}
public void setConstraintType(Integer constraintType) {
this.constraintType = constraintType;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
}
| 17.710383
| 65
| 0.733107
|
03246d2cc37b99e6c1fa5c0675d14cb9f1f6b435
| 59,445
|
/*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.cloudcontrolapi;
import org.w3c.dom.*;
import java.net.*;
import java.util.*;
import javax.annotation.Generated;
import org.apache.commons.logging.*;
import com.amazonaws.*;
import com.amazonaws.annotation.SdkInternalApi;
import com.amazonaws.auth.*;
import com.amazonaws.handlers.*;
import com.amazonaws.http.*;
import com.amazonaws.internal.*;
import com.amazonaws.internal.auth.*;
import com.amazonaws.metrics.*;
import com.amazonaws.regions.*;
import com.amazonaws.transform.*;
import com.amazonaws.util.*;
import com.amazonaws.protocol.json.*;
import com.amazonaws.util.AWSRequestMetrics.Field;
import com.amazonaws.annotation.ThreadSafe;
import com.amazonaws.client.AwsSyncClientParams;
import com.amazonaws.client.builder.AdvancedConfig;
import com.amazonaws.services.cloudcontrolapi.AWSCloudControlApiClientBuilder;
import com.amazonaws.services.cloudcontrolapi.waiters.AWSCloudControlApiWaiters;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.cloudcontrolapi.model.*;
import com.amazonaws.services.cloudcontrolapi.model.transform.*;
/**
* Client for accessing CloudControlApi. All service calls made using this client are blocking, and will not return
* until the service call completes.
* <p>
* <p>
* Use Amazon Web Services Cloud Control API to create, read, update, delete, and list (CRUD-L) your cloud resources
* that belong to a wide range of services--both Amazon Web Services and third-party. With the Cloud Control API
* standardized set of application programming interfaces (APIs), you can perform CRUD-L operations on any supported
* resources in your Amazon Web Services account. Using Cloud Control API, you won't have to generate code or scripts
* specific to each individual service responsible for those resources.
* </p>
* <p>
* For more information about Amazon Web Services Cloud Control API, see the <a
* href="https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/what-is-cloudcontrolapi.html">Amazon Web Services
* Cloud Control API User Guide</a>.
* </p>
*/
@ThreadSafe
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AWSCloudControlApiClient extends AmazonWebServiceClient implements AWSCloudControlApi {
/** Provider for AWS credentials. */
private final AWSCredentialsProvider awsCredentialsProvider;
private static final Log log = LogFactory.getLog(AWSCloudControlApi.class);
/** Default signing name for the service. */
private static final String DEFAULT_SIGNING_NAME = "cloudcontrolapi";
private volatile AWSCloudControlApiWaiters waiters;
/** Client configuration factory providing ClientConfigurations tailored to this client */
protected static final ClientConfigurationFactory configFactory = new ClientConfigurationFactory();
private final AdvancedConfig advancedConfig;
private static final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory = new com.amazonaws.protocol.json.SdkJsonProtocolFactory(
new JsonClientMetadata()
.withProtocolVersion("1.0")
.withSupportsCbor(false)
.withSupportsIon(false)
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("ConcurrentModificationException").withExceptionUnmarshaller(
com.amazonaws.services.cloudcontrolapi.model.transform.ConcurrentModificationExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("HandlerFailureException").withExceptionUnmarshaller(
com.amazonaws.services.cloudcontrolapi.model.transform.HandlerFailureExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("HandlerInternalFailureException").withExceptionUnmarshaller(
com.amazonaws.services.cloudcontrolapi.model.transform.HandlerInternalFailureExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("ServiceLimitExceededException").withExceptionUnmarshaller(
com.amazonaws.services.cloudcontrolapi.model.transform.ServiceLimitExceededExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("ServiceInternalErrorException").withExceptionUnmarshaller(
com.amazonaws.services.cloudcontrolapi.model.transform.ServiceInternalErrorExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("PrivateTypeException").withExceptionUnmarshaller(
com.amazonaws.services.cloudcontrolapi.model.transform.PrivateTypeExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("RequestTokenNotFoundException").withExceptionUnmarshaller(
com.amazonaws.services.cloudcontrolapi.model.transform.RequestTokenNotFoundExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("ClientTokenConflictException").withExceptionUnmarshaller(
com.amazonaws.services.cloudcontrolapi.model.transform.ClientTokenConflictExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("InvalidRequestException").withExceptionUnmarshaller(
com.amazonaws.services.cloudcontrolapi.model.transform.InvalidRequestExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("NetworkFailureException").withExceptionUnmarshaller(
com.amazonaws.services.cloudcontrolapi.model.transform.NetworkFailureExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("ResourceNotFoundException").withExceptionUnmarshaller(
com.amazonaws.services.cloudcontrolapi.model.transform.ResourceNotFoundExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("AlreadyExistsException").withExceptionUnmarshaller(
com.amazonaws.services.cloudcontrolapi.model.transform.AlreadyExistsExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("ConcurrentOperationException").withExceptionUnmarshaller(
com.amazonaws.services.cloudcontrolapi.model.transform.ConcurrentOperationExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("UnsupportedActionException").withExceptionUnmarshaller(
com.amazonaws.services.cloudcontrolapi.model.transform.UnsupportedActionExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("NotStabilizedException").withExceptionUnmarshaller(
com.amazonaws.services.cloudcontrolapi.model.transform.NotStabilizedExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("ResourceConflictException").withExceptionUnmarshaller(
com.amazonaws.services.cloudcontrolapi.model.transform.ResourceConflictExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("InvalidCredentialsException").withExceptionUnmarshaller(
com.amazonaws.services.cloudcontrolapi.model.transform.InvalidCredentialsExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("TypeNotFoundException").withExceptionUnmarshaller(
com.amazonaws.services.cloudcontrolapi.model.transform.TypeNotFoundExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("GeneralServiceException").withExceptionUnmarshaller(
com.amazonaws.services.cloudcontrolapi.model.transform.GeneralServiceExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("ThrottlingException").withExceptionUnmarshaller(
com.amazonaws.services.cloudcontrolapi.model.transform.ThrottlingExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("NotUpdatableException").withExceptionUnmarshaller(
com.amazonaws.services.cloudcontrolapi.model.transform.NotUpdatableExceptionUnmarshaller.getInstance()))
.withBaseServiceExceptionClass(com.amazonaws.services.cloudcontrolapi.model.AWSCloudControlApiException.class));
public static AWSCloudControlApiClientBuilder builder() {
return AWSCloudControlApiClientBuilder.standard();
}
/**
* Constructs a new client to invoke service methods on CloudControlApi using the specified parameters.
*
* <p>
* All service calls made using this new client object are blocking, and will not return until the service call
* completes.
*
* @param clientParams
* Object providing client parameters.
*/
AWSCloudControlApiClient(AwsSyncClientParams clientParams) {
this(clientParams, false);
}
/**
* Constructs a new client to invoke service methods on CloudControlApi using the specified parameters.
*
* <p>
* All service calls made using this new client object are blocking, and will not return until the service call
* completes.
*
* @param clientParams
* Object providing client parameters.
*/
AWSCloudControlApiClient(AwsSyncClientParams clientParams, boolean endpointDiscoveryEnabled) {
super(clientParams);
this.awsCredentialsProvider = clientParams.getCredentialsProvider();
this.advancedConfig = clientParams.getAdvancedConfig();
init();
}
private void init() {
setServiceNameIntern(DEFAULT_SIGNING_NAME);
setEndpointPrefix(ENDPOINT_PREFIX);
// calling this.setEndPoint(...) will also modify the signer accordingly
setEndpoint("cloudcontrolapi.us-east-1.amazonaws.com");
HandlerChainFactory chainFactory = new HandlerChainFactory();
requestHandler2s.addAll(chainFactory.newRequestHandlerChain("/com/amazonaws/services/cloudcontrolapi/request.handlers"));
requestHandler2s.addAll(chainFactory.newRequestHandler2Chain("/com/amazonaws/services/cloudcontrolapi/request.handler2s"));
requestHandler2s.addAll(chainFactory.getGlobalHandlers());
}
/**
* <p>
* Cancels the specified resource operation request. For more information, see <a href=
* "https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-operations-manage-requests.html#resource-operations-manage-requests-cancel"
* >Canceling resource operation requests</a> in the <i>Amazon Web Services Cloud Control API User Guide</i>.
* </p>
* <p>
* Only resource operations requests with a status of <code>PENDING</code> or <code>IN_PROGRESS</code> can be
* cancelled.
* </p>
*
* @param cancelResourceRequestRequest
* @return Result of the CancelResourceRequest operation returned by the service.
* @throws RequestTokenNotFoundException
* A resource operation with the specified request token cannot be found.
* @throws ConcurrentModificationException
* The resource is currently being modified by another operation.
* @sample AWSCloudControlApi.CancelResourceRequest
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cloudcontrol-2021-09-30/CancelResourceRequest"
* target="_top">AWS API Documentation</a>
*/
@Override
public CancelResourceRequestResult cancelResourceRequest(CancelResourceRequestRequest request) {
request = beforeClientExecution(request);
return executeCancelResourceRequest(request);
}
@SdkInternalApi
final CancelResourceRequestResult executeCancelResourceRequest(CancelResourceRequestRequest cancelResourceRequestRequest) {
ExecutionContext executionContext = createExecutionContext(cancelResourceRequestRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<CancelResourceRequestRequest> request = null;
Response<CancelResourceRequestResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new CancelResourceRequestRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(cancelResourceRequestRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.CLIENT_ENDPOINT, endpoint);
request.addHandlerContext(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "CloudControl");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "CancelResourceRequest");
request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
HttpResponseHandler<AmazonWebServiceResponse<CancelResourceRequestResult>> responseHandler = protocolFactory
.createResponseHandler(new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false),
new CancelResourceRequestResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Creates the specified resource. For more information, see <a
* href="https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-operations-create.html">Creating a
* resource</a> in the <i>Amazon Web Services Cloud Control API User Guide</i>.
* </p>
* <p>
* After you have initiated a resource creation request, you can monitor the progress of your request by calling <a
* href="https://docs.aws.amazon.com/cloudcontrolapi/latest/APIReference/API_GetResourceRequestStatus.html">
* GetResourceRequestStatus</a> using the <code>RequestToken</code> of the <code>ProgressEvent</code> type returned
* by <code>CreateResource</code>.
* </p>
*
* @param createResourceRequest
* @return Result of the CreateResource operation returned by the service.
* @throws ConcurrentOperationException
* Another resource operation is currently being performed on this resource.
* @throws ClientTokenConflictException
* The specified client token has already been used in another resource request.</p>
* <p>
* It is best practice for client tokens to be unique for each resource operation request. However, client
* token expire after 36 hours.
* @throws UnsupportedActionException
* The specified resource does not support this resource operation.
* @throws TypeNotFoundException
* The specified extension does not exist in the CloudFormation registry.
* @throws AlreadyExistsException
* The resource with the name requested already exists.
* @throws GeneralServiceException
* The resource handler has returned that the downstream service generated an error that does not map to any
* other handler error code.
* @throws HandlerInternalFailureException
* The resource handler has returned that an unexpected error occurred within the resource handler.
* @throws InvalidCredentialsException
* The resource handler has returned that the credentials provided by the user are invalid.
* @throws InvalidRequestException
* The resource handler has returned that invalid input from the user has generated a generic exception.
* @throws NetworkFailureException
* The resource handler has returned that the request could not be completed due to networking issues, such
* as a failure to receive a response from the server.
* @throws ResourceNotFoundException
* A resource with the specified identifier cannot be found.
* @throws NotStabilizedException
* The resource handler has returned that the downstream resource failed to complete all of its ready-state
* checks.
* @throws NotUpdatableException
* One or more properties included in this resource operation are defined as create-only, and therefore
* cannot be updated.
* @throws ResourceConflictException
* The resource is temporarily unavailable to be acted upon. For example, if the resource is currently
* undergoing an operation and cannot be acted upon until that operation is finished.
* @throws ServiceInternalErrorException
* The resource handler has returned that the downstream service returned an internal error, typically with
* a <code>5XX HTTP</code> status code.
* @throws ServiceLimitExceededException
* The resource handler has returned that a non-transient resource limit was reached on the service side.
* @throws ThrottlingException
* The request was denied due to request throttling.
* @throws PrivateTypeException
* Cloud Control API has not received a valid response from the resource handler, due to a configuration
* error. This includes issues such as the resource handler returning an invalid response, or timing out.
* @throws HandlerFailureException
* The resource handler has failed without a returning a more specific error code. This can include
* timeouts.
* @sample AWSCloudControlApi.CreateResource
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cloudcontrol-2021-09-30/CreateResource" target="_top">AWS
* API Documentation</a>
*/
@Override
public CreateResourceResult createResource(CreateResourceRequest request) {
request = beforeClientExecution(request);
return executeCreateResource(request);
}
@SdkInternalApi
final CreateResourceResult executeCreateResource(CreateResourceRequest createResourceRequest) {
ExecutionContext executionContext = createExecutionContext(createResourceRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<CreateResourceRequest> request = null;
Response<CreateResourceResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new CreateResourceRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(createResourceRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.CLIENT_ENDPOINT, endpoint);
request.addHandlerContext(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "CloudControl");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "CreateResource");
request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
HttpResponseHandler<AmazonWebServiceResponse<CreateResourceResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new CreateResourceResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Deletes the specified resource. For details, see <a
* href="https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-operations-delete.html">Deleting a
* resource</a> in the <i>Amazon Web Services Cloud Control API User Guide</i>.
* </p>
* <p>
* After you have initiated a resource deletion request, you can monitor the progress of your request by calling <a
* href="https://docs.aws.amazon.com/cloudcontrolapi/latest/APIReference/API_GetResourceRequestStatus.html">
* GetResourceRequestStatus</a> using the <code>RequestToken</code> of the <code>ProgressEvent</code> returned by
* <code>DeleteResource</code>.
* </p>
*
* @param deleteResourceRequest
* @return Result of the DeleteResource operation returned by the service.
* @throws ConcurrentOperationException
* Another resource operation is currently being performed on this resource.
* @throws ClientTokenConflictException
* The specified client token has already been used in another resource request.</p>
* <p>
* It is best practice for client tokens to be unique for each resource operation request. However, client
* token expire after 36 hours.
* @throws UnsupportedActionException
* The specified resource does not support this resource operation.
* @throws TypeNotFoundException
* The specified extension does not exist in the CloudFormation registry.
* @throws AlreadyExistsException
* The resource with the name requested already exists.
* @throws GeneralServiceException
* The resource handler has returned that the downstream service generated an error that does not map to any
* other handler error code.
* @throws HandlerInternalFailureException
* The resource handler has returned that an unexpected error occurred within the resource handler.
* @throws InvalidCredentialsException
* The resource handler has returned that the credentials provided by the user are invalid.
* @throws InvalidRequestException
* The resource handler has returned that invalid input from the user has generated a generic exception.
* @throws NetworkFailureException
* The resource handler has returned that the request could not be completed due to networking issues, such
* as a failure to receive a response from the server.
* @throws ResourceNotFoundException
* A resource with the specified identifier cannot be found.
* @throws NotStabilizedException
* The resource handler has returned that the downstream resource failed to complete all of its ready-state
* checks.
* @throws NotUpdatableException
* One or more properties included in this resource operation are defined as create-only, and therefore
* cannot be updated.
* @throws ResourceConflictException
* The resource is temporarily unavailable to be acted upon. For example, if the resource is currently
* undergoing an operation and cannot be acted upon until that operation is finished.
* @throws ServiceInternalErrorException
* The resource handler has returned that the downstream service returned an internal error, typically with
* a <code>5XX HTTP</code> status code.
* @throws ServiceLimitExceededException
* The resource handler has returned that a non-transient resource limit was reached on the service side.
* @throws ThrottlingException
* The request was denied due to request throttling.
* @throws PrivateTypeException
* Cloud Control API has not received a valid response from the resource handler, due to a configuration
* error. This includes issues such as the resource handler returning an invalid response, or timing out.
* @throws HandlerFailureException
* The resource handler has failed without a returning a more specific error code. This can include
* timeouts.
* @sample AWSCloudControlApi.DeleteResource
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cloudcontrol-2021-09-30/DeleteResource" target="_top">AWS
* API Documentation</a>
*/
@Override
public DeleteResourceResult deleteResource(DeleteResourceRequest request) {
request = beforeClientExecution(request);
return executeDeleteResource(request);
}
@SdkInternalApi
final DeleteResourceResult executeDeleteResource(DeleteResourceRequest deleteResourceRequest) {
ExecutionContext executionContext = createExecutionContext(deleteResourceRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<DeleteResourceRequest> request = null;
Response<DeleteResourceResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new DeleteResourceRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(deleteResourceRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.CLIENT_ENDPOINT, endpoint);
request.addHandlerContext(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "CloudControl");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "DeleteResource");
request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
HttpResponseHandler<AmazonWebServiceResponse<DeleteResourceResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new DeleteResourceResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Returns information about the current state of the specified resource. For details, see <a
* href="https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-operations-read.html">Reading a
* resource's current state</a>.
* </p>
* <p>
* You can use this action to return information about an existing resource in your account and Amazon Web Services
* Region, whether or not those resources were provisioned using Cloud Control API.
* </p>
*
* @param getResourceRequest
* @return Result of the GetResource operation returned by the service.
* @throws UnsupportedActionException
* The specified resource does not support this resource operation.
* @throws TypeNotFoundException
* The specified extension does not exist in the CloudFormation registry.
* @throws AlreadyExistsException
* The resource with the name requested already exists.
* @throws GeneralServiceException
* The resource handler has returned that the downstream service generated an error that does not map to any
* other handler error code.
* @throws HandlerInternalFailureException
* The resource handler has returned that an unexpected error occurred within the resource handler.
* @throws InvalidCredentialsException
* The resource handler has returned that the credentials provided by the user are invalid.
* @throws InvalidRequestException
* The resource handler has returned that invalid input from the user has generated a generic exception.
* @throws NetworkFailureException
* The resource handler has returned that the request could not be completed due to networking issues, such
* as a failure to receive a response from the server.
* @throws ResourceNotFoundException
* A resource with the specified identifier cannot be found.
* @throws NotStabilizedException
* The resource handler has returned that the downstream resource failed to complete all of its ready-state
* checks.
* @throws NotUpdatableException
* One or more properties included in this resource operation are defined as create-only, and therefore
* cannot be updated.
* @throws ResourceConflictException
* The resource is temporarily unavailable to be acted upon. For example, if the resource is currently
* undergoing an operation and cannot be acted upon until that operation is finished.
* @throws ServiceInternalErrorException
* The resource handler has returned that the downstream service returned an internal error, typically with
* a <code>5XX HTTP</code> status code.
* @throws ServiceLimitExceededException
* The resource handler has returned that a non-transient resource limit was reached on the service side.
* @throws ThrottlingException
* The request was denied due to request throttling.
* @throws PrivateTypeException
* Cloud Control API has not received a valid response from the resource handler, due to a configuration
* error. This includes issues such as the resource handler returning an invalid response, or timing out.
* @throws HandlerFailureException
* The resource handler has failed without a returning a more specific error code. This can include
* timeouts.
* @sample AWSCloudControlApi.GetResource
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cloudcontrol-2021-09-30/GetResource" target="_top">AWS API
* Documentation</a>
*/
@Override
public GetResourceResult getResource(GetResourceRequest request) {
request = beforeClientExecution(request);
return executeGetResource(request);
}
@SdkInternalApi
final GetResourceResult executeGetResource(GetResourceRequest getResourceRequest) {
ExecutionContext executionContext = createExecutionContext(getResourceRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<GetResourceRequest> request = null;
Response<GetResourceResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new GetResourceRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(getResourceRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.CLIENT_ENDPOINT, endpoint);
request.addHandlerContext(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "CloudControl");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "GetResource");
request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
HttpResponseHandler<AmazonWebServiceResponse<GetResourceResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new GetResourceResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Returns the current status of a resource operation request. For more information, see <a href=
* "https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-operations-manage-requests.html#resource-operations-manage-requests-track"
* >Tracking the progress of resource operation requests</a> in the <i>Amazon Web Services Cloud Control API User
* Guide</i>.
* </p>
*
* @param getResourceRequestStatusRequest
* @return Result of the GetResourceRequestStatus operation returned by the service.
* @throws RequestTokenNotFoundException
* A resource operation with the specified request token cannot be found.
* @sample AWSCloudControlApi.GetResourceRequestStatus
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cloudcontrol-2021-09-30/GetResourceRequestStatus"
* target="_top">AWS API Documentation</a>
*/
@Override
public GetResourceRequestStatusResult getResourceRequestStatus(GetResourceRequestStatusRequest request) {
request = beforeClientExecution(request);
return executeGetResourceRequestStatus(request);
}
@SdkInternalApi
final GetResourceRequestStatusResult executeGetResourceRequestStatus(GetResourceRequestStatusRequest getResourceRequestStatusRequest) {
ExecutionContext executionContext = createExecutionContext(getResourceRequestStatusRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<GetResourceRequestStatusRequest> request = null;
Response<GetResourceRequestStatusResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new GetResourceRequestStatusRequestProtocolMarshaller(protocolFactory).marshall(super
.beforeMarshalling(getResourceRequestStatusRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.CLIENT_ENDPOINT, endpoint);
request.addHandlerContext(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "CloudControl");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "GetResourceRequestStatus");
request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
HttpResponseHandler<AmazonWebServiceResponse<GetResourceRequestStatusResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false),
new GetResourceRequestStatusResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Returns existing resource operation requests. This includes requests of all status types. For more information,
* see <a href=
* "https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-operations-manage-requests.html#resource-operations-manage-requests-list"
* >Listing active resource operation requests</a> in the <i>Amazon Web Services Cloud Control API User Guide</i>.
* </p>
* <note>
* <p>
* Resource operation requests expire after seven days.
* </p>
* </note>
*
* @param listResourceRequestsRequest
* @return Result of the ListResourceRequests operation returned by the service.
* @sample AWSCloudControlApi.ListResourceRequests
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cloudcontrol-2021-09-30/ListResourceRequests"
* target="_top">AWS API Documentation</a>
*/
@Override
public ListResourceRequestsResult listResourceRequests(ListResourceRequestsRequest request) {
request = beforeClientExecution(request);
return executeListResourceRequests(request);
}
@SdkInternalApi
final ListResourceRequestsResult executeListResourceRequests(ListResourceRequestsRequest listResourceRequestsRequest) {
ExecutionContext executionContext = createExecutionContext(listResourceRequestsRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<ListResourceRequestsRequest> request = null;
Response<ListResourceRequestsResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new ListResourceRequestsRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(listResourceRequestsRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.CLIENT_ENDPOINT, endpoint);
request.addHandlerContext(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "CloudControl");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "ListResourceRequests");
request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
HttpResponseHandler<AmazonWebServiceResponse<ListResourceRequestsResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new ListResourceRequestsResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Returns information about the specified resources. For more information, see <a
* href="cloudcontrolapi/latest/userguide/resource-operations-list.html">Discovering resources</a> in the <i>Amazon
* Web Services Cloud Control API User Guide</i>.
* </p>
* <p>
* You can use this action to return information about existing resources in your account and Amazon Web Services
* Region, whether or not those resources were provisioned using Cloud Control API.
* </p>
*
* @param listResourcesRequest
* @return Result of the ListResources operation returned by the service.
* @throws UnsupportedActionException
* The specified resource does not support this resource operation.
* @throws TypeNotFoundException
* The specified extension does not exist in the CloudFormation registry.
* @throws AlreadyExistsException
* The resource with the name requested already exists.
* @throws GeneralServiceException
* The resource handler has returned that the downstream service generated an error that does not map to any
* other handler error code.
* @throws HandlerInternalFailureException
* The resource handler has returned that an unexpected error occurred within the resource handler.
* @throws InvalidCredentialsException
* The resource handler has returned that the credentials provided by the user are invalid.
* @throws InvalidRequestException
* The resource handler has returned that invalid input from the user has generated a generic exception.
* @throws NetworkFailureException
* The resource handler has returned that the request could not be completed due to networking issues, such
* as a failure to receive a response from the server.
* @throws ResourceNotFoundException
* A resource with the specified identifier cannot be found.
* @throws NotStabilizedException
* The resource handler has returned that the downstream resource failed to complete all of its ready-state
* checks.
* @throws NotUpdatableException
* One or more properties included in this resource operation are defined as create-only, and therefore
* cannot be updated.
* @throws ResourceConflictException
* The resource is temporarily unavailable to be acted upon. For example, if the resource is currently
* undergoing an operation and cannot be acted upon until that operation is finished.
* @throws ServiceInternalErrorException
* The resource handler has returned that the downstream service returned an internal error, typically with
* a <code>5XX HTTP</code> status code.
* @throws ServiceLimitExceededException
* The resource handler has returned that a non-transient resource limit was reached on the service side.
* @throws ThrottlingException
* The request was denied due to request throttling.
* @throws PrivateTypeException
* Cloud Control API has not received a valid response from the resource handler, due to a configuration
* error. This includes issues such as the resource handler returning an invalid response, or timing out.
* @throws HandlerFailureException
* The resource handler has failed without a returning a more specific error code. This can include
* timeouts.
* @sample AWSCloudControlApi.ListResources
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cloudcontrol-2021-09-30/ListResources" target="_top">AWS API
* Documentation</a>
*/
@Override
public ListResourcesResult listResources(ListResourcesRequest request) {
request = beforeClientExecution(request);
return executeListResources(request);
}
@SdkInternalApi
final ListResourcesResult executeListResources(ListResourcesRequest listResourcesRequest) {
ExecutionContext executionContext = createExecutionContext(listResourcesRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<ListResourcesRequest> request = null;
Response<ListResourcesResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new ListResourcesRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(listResourcesRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.CLIENT_ENDPOINT, endpoint);
request.addHandlerContext(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "CloudControl");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "ListResources");
request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
HttpResponseHandler<AmazonWebServiceResponse<ListResourcesResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new ListResourcesResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Updates the specified property values in the resource.
* </p>
* <p>
* You specify your resource property updates as a list of patch operations contained in a JSON patch document that
* adheres to the <a href="https://datatracker.ietf.org/doc/html/rfc6902"> <i>RFC 6902 - JavaScript Object Notation
* (JSON) Patch</i> </a> standard.
* </p>
* <p>
* For details on how Cloud Control API performs resource update operations, see <a
* href="https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-operations-update.html">Updating a
* resource</a> in the <i>Amazon Web Services Cloud Control API User Guide</i>.
* </p>
* <p>
* After you have initiated a resource update request, you can monitor the progress of your request by calling <a
* href="https://docs.aws.amazon.com/cloudcontrolapi/latest/APIReference/API_GetResourceRequestStatus.html">
* GetResourceRequestStatus</a> using the <code>RequestToken</code> of the <code>ProgressEvent</code> returned by
* <code>UpdateResource</code>.
* </p>
* <p>
* For more information about the properties of a specific resource, refer to the related topic for the resource in
* the <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html">
* Resource and property types reference</a> in the <i>Amazon Web Services CloudFormation Users Guide</i>.
* </p>
*
* @param updateResourceRequest
* @return Result of the UpdateResource operation returned by the service.
* @throws ConcurrentOperationException
* Another resource operation is currently being performed on this resource.
* @throws ClientTokenConflictException
* The specified client token has already been used in another resource request.</p>
* <p>
* It is best practice for client tokens to be unique for each resource operation request. However, client
* token expire after 36 hours.
* @throws UnsupportedActionException
* The specified resource does not support this resource operation.
* @throws TypeNotFoundException
* The specified extension does not exist in the CloudFormation registry.
* @throws AlreadyExistsException
* The resource with the name requested already exists.
* @throws GeneralServiceException
* The resource handler has returned that the downstream service generated an error that does not map to any
* other handler error code.
* @throws HandlerInternalFailureException
* The resource handler has returned that an unexpected error occurred within the resource handler.
* @throws InvalidCredentialsException
* The resource handler has returned that the credentials provided by the user are invalid.
* @throws InvalidRequestException
* The resource handler has returned that invalid input from the user has generated a generic exception.
* @throws NetworkFailureException
* The resource handler has returned that the request could not be completed due to networking issues, such
* as a failure to receive a response from the server.
* @throws ResourceNotFoundException
* A resource with the specified identifier cannot be found.
* @throws NotStabilizedException
* The resource handler has returned that the downstream resource failed to complete all of its ready-state
* checks.
* @throws NotUpdatableException
* One or more properties included in this resource operation are defined as create-only, and therefore
* cannot be updated.
* @throws ResourceConflictException
* The resource is temporarily unavailable to be acted upon. For example, if the resource is currently
* undergoing an operation and cannot be acted upon until that operation is finished.
* @throws ServiceInternalErrorException
* The resource handler has returned that the downstream service returned an internal error, typically with
* a <code>5XX HTTP</code> status code.
* @throws ServiceLimitExceededException
* The resource handler has returned that a non-transient resource limit was reached on the service side.
* @throws ThrottlingException
* The request was denied due to request throttling.
* @throws PrivateTypeException
* Cloud Control API has not received a valid response from the resource handler, due to a configuration
* error. This includes issues such as the resource handler returning an invalid response, or timing out.
* @throws HandlerFailureException
* The resource handler has failed without a returning a more specific error code. This can include
* timeouts.
* @sample AWSCloudControlApi.UpdateResource
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cloudcontrol-2021-09-30/UpdateResource" target="_top">AWS
* API Documentation</a>
*/
@Override
public UpdateResourceResult updateResource(UpdateResourceRequest request) {
request = beforeClientExecution(request);
return executeUpdateResource(request);
}
@SdkInternalApi
final UpdateResourceResult executeUpdateResource(UpdateResourceRequest updateResourceRequest) {
ExecutionContext executionContext = createExecutionContext(updateResourceRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<UpdateResourceRequest> request = null;
Response<UpdateResourceResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new UpdateResourceRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(updateResourceRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.CLIENT_ENDPOINT, endpoint);
request.addHandlerContext(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "CloudControl");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "UpdateResource");
request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
HttpResponseHandler<AmazonWebServiceResponse<UpdateResourceResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new UpdateResourceResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* Returns additional metadata for a previously executed successful, request, typically used for debugging issues
* where a service isn't acting as expected. This data isn't considered part of the result data returned by an
* operation, so it's available through this separate, diagnostic interface.
* <p>
* Response metadata is only cached for a limited period of time, so if you need to access this extra diagnostic
* information for an executed request, you should use this method to retrieve it as soon as possible after
* executing the request.
*
* @param request
* The originally executed request
*
* @return The response metadata for the specified request, or null if none is available.
*/
public ResponseMetadata getCachedResponseMetadata(AmazonWebServiceRequest request) {
return client.getResponseMetadataForRequest(request);
}
/**
* Normal invoke with authentication. Credentials are required and may be overriden at the request level.
**/
private <X, Y extends AmazonWebServiceRequest> Response<X> invoke(Request<Y> request, HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler,
ExecutionContext executionContext) {
return invoke(request, responseHandler, executionContext, null, null);
}
/**
* Normal invoke with authentication. Credentials are required and may be overriden at the request level.
**/
private <X, Y extends AmazonWebServiceRequest> Response<X> invoke(Request<Y> request, HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler,
ExecutionContext executionContext, URI cachedEndpoint, URI uriFromEndpointTrait) {
executionContext.setCredentialsProvider(CredentialUtils.getCredentialsProvider(request.getOriginalRequest(), awsCredentialsProvider));
return doInvoke(request, responseHandler, executionContext, cachedEndpoint, uriFromEndpointTrait);
}
/**
* Invoke with no authentication. Credentials are not required and any credentials set on the client or request will
* be ignored for this operation.
**/
private <X, Y extends AmazonWebServiceRequest> Response<X> anonymousInvoke(Request<Y> request,
HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler, ExecutionContext executionContext) {
return doInvoke(request, responseHandler, executionContext, null, null);
}
/**
* Invoke the request using the http client. Assumes credentials (or lack thereof) have been configured in the
* ExecutionContext beforehand.
**/
private <X, Y extends AmazonWebServiceRequest> Response<X> doInvoke(Request<Y> request, HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler,
ExecutionContext executionContext, URI discoveredEndpoint, URI uriFromEndpointTrait) {
if (discoveredEndpoint != null) {
request.setEndpoint(discoveredEndpoint);
request.getOriginalRequest().getRequestClientOptions().appendUserAgent("endpoint-discovery");
} else if (uriFromEndpointTrait != null) {
request.setEndpoint(uriFromEndpointTrait);
} else {
request.setEndpoint(endpoint);
}
request.setTimeOffset(timeOffset);
HttpResponseHandler<AmazonServiceException> errorResponseHandler = protocolFactory.createErrorResponseHandler(new JsonErrorResponseMetadata());
return client.execute(request, responseHandler, errorResponseHandler, executionContext);
}
@com.amazonaws.annotation.SdkInternalApi
static com.amazonaws.protocol.json.SdkJsonProtocolFactory getProtocolFactory() {
return protocolFactory;
}
@Override
public AWSCloudControlApiWaiters waiters() {
if (waiters == null) {
synchronized (this) {
if (waiters == null) {
waiters = new AWSCloudControlApiWaiters(this);
}
}
}
return waiters;
}
@Override
public void shutdown() {
super.shutdown();
if (waiters != null) {
waiters.shutdown();
}
}
}
| 56.885167
| 160
| 0.703659
|
5fdbc7605fe08ba0635e9f36d958afe5eecf980b
| 806
|
package chessboard;
/*
Вывести шахматную доску с заданными размерами высоты и ширины, по принципу:
* * * * * *
* * * * * *
* * * * * *
* * * * * *
Программа запускается через вызов главного класса с параметрами.
*/
public class Chess {
public static void main(String[] args) {
if(args.length == 0) {
Display.showProgramInfo();
}
else if (args.length == 2) {
Chess.ourProgramRun(args);
}else {
Display.showErrorMessage();
}
}
public static void ourProgramRun(String[] args){
if(ValidateData.checkParameters(args)){
ChessBoard chessBoard = new ChessBoard(Integer.parseInt(args[0]), Integer.parseInt(args[1]), '*');
StringBuilder chessBordObject = chessBoard.createChessBoard();
Display.showChessBoard(chessBordObject);
}else{
Display.showMessage();
}
}
}
| 21.783784
| 101
| 0.669975
|
60b7ad1a4463c57474fd9fa5e4be6c17910464d4
| 2,938
|
package com.blankj.androidutilcode.feature.core.fragment;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.TextView;
import com.blankj.androidutilcode.R;
import com.blankj.androidutilcode.base.BaseFragment;
import com.blankj.utilcode.util.FragmentUtils;
import com.blankj.utilcode.util.LogUtils;
import java.util.Random;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 17/02/02
* desc :
* </pre>
*/
public class ChildFragment extends BaseFragment
implements FragmentUtils.OnBackClickListener {
private TextView tvAboutFragment;
public static ChildFragment newInstance() {
Bundle args = new Bundle();
ChildFragment fragment = new ChildFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void initData(@Nullable Bundle bundle) {
}
@Override
public int bindLayout() {
return R.layout.fragment_child;
}
@Override
public void initView(Bundle savedInstanceState, View contentView) {
Random random = new Random();
FragmentUtils.setBackgroundColor(this, Color.rgb(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
findViewById(R.id.btn_show_about_fragment).setOnClickListener(this);
findViewById(R.id.btn_pop).setOnClickListener(this);
tvAboutFragment = findViewById(R.id.tv_about_fragment);
}
@Override
public void doBusiness() {
}
@Override
public void onWidgetClick(View view) {
tvAboutFragment.setText("");
switch (view.getId()) {
case R.id.btn_show_about_fragment:
tvAboutFragment.setText("top: " + FragmentUtils.getSimpleName(FragmentUtils.getTop(getFragmentManager()))
+ "\ntopInStack: " + FragmentUtils.getSimpleName(FragmentUtils.getTopInStack(getFragmentManager()))
+ "\ntopShow: " + FragmentUtils.getSimpleName(FragmentUtils.getTopShow(getFragmentManager()))
+ "\ntopShowInStack: " + FragmentUtils.getSimpleName(FragmentUtils.getTopShowInStack(getFragmentManager()))
+ "\n---all of fragments---\n"
+ FragmentUtils.getAllFragments(getFragmentManager()).toString()
+ "\n----------------------\n\n"
+ "---stack top---\n"
+ FragmentUtils.getAllFragmentsInStack(getFragmentManager()).toString()
+ "\n---stack bottom---\n\n"
);
break;
// case R.id.btn_pop:
// FragmentUtils.popFragment(getFragmentManager());
// break;
}
}
@Override
public boolean onBackClick() {
LogUtils.d("demo2 onBackClick");
return false;
}
}
| 33.011236
| 131
| 0.624575
|
c81fb1d5034cd334d512011c6e7e5b92907b1506
| 10,984
|
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.internal.ws.api.wsdl;
import com.sun.tools.internal.ws.wsdl.document.WSDLConstants;
import org.w3c.dom.Element;
/**
* JAXWS WSDL parser {@link com.sun.tools.internal.ws.wsdl.parser.WSDLParser} will call an {@link TWSDLExtensionHandler} registered
* with it for the WSDL extensibility elements thats not already defined in the WSDL 1.1 spec, such as SOAP or MIME.
*
* @author Vivek Pandey
* @deprecated This class is deprecated, will be removed in JAX-WS 2.2 RI.
*/
public abstract class TWSDLExtensionHandler {
/**
* Gives the namespace of an extensibility element.
* <p/>
* For example a soap 1.1 XXExtensionHandler would return <code>""http://schemas.xmlsoap.org/wsdl/soap/"</code>
*/
public String getNamespaceURI() {
return null;
}
/**
* This interface is called during WSDL parsing on detecting any wsdl extension.
*
* @param context Parser context that will be passed on by the wsdl parser
* @param parent The Parent element within which the extensibility element is defined
* @param e The extensibility elemenet
* @return false if there was some error during the extension handling otherwise returns true. If returned false
* then the WSDL parser can abort if the wsdl extensibility element had <code>required</code> attribute set to true
*/
public boolean doHandleExtension(TWSDLParserContext context, TWSDLExtensible parent, Element e) {
if (parent.getWSDLElementName().equals(WSDLConstants.QNAME_DEFINITIONS)) {
return handleDefinitionsExtension(context, parent, e);
} else if (parent.getWSDLElementName().equals(WSDLConstants.QNAME_TYPES)) {
return handleTypesExtension(context, parent, e);
} else if (parent.getWSDLElementName().equals(WSDLConstants.QNAME_PORT_TYPE)) {
return handlePortTypeExtension(context, parent, e);
} else if (
parent.getWSDLElementName().equals(WSDLConstants.QNAME_BINDING)) {
return handleBindingExtension(context, parent, e);
} else if (
parent.getWSDLElementName().equals(WSDLConstants.QNAME_OPERATION)) {
return handleOperationExtension(context, parent, e);
} else if (parent.getWSDLElementName().equals(WSDLConstants.QNAME_INPUT)) {
return handleInputExtension(context, parent, e);
} else if (
parent.getWSDLElementName().equals(WSDLConstants.QNAME_OUTPUT)) {
return handleOutputExtension(context, parent, e);
} else if (parent.getWSDLElementName().equals(WSDLConstants.QNAME_FAULT)) {
return handleFaultExtension(context, parent, e);
} else if (
parent.getWSDLElementName().equals(WSDLConstants.QNAME_SERVICE)) {
return handleServiceExtension(context, parent, e);
} else if (parent.getWSDLElementName().equals(WSDLConstants.QNAME_PORT)) {
return handlePortExtension(context, parent, e);
} else {
return false;
}
}
/**
* Callback for <code>wsdl:portType</code>
*
* @param context Parser context that will be passed on by the wsdl parser
* @param parent The Parent element within which the extensibility element is defined
* @param e The extensibility elemenet
* @return false if there was some error during the extension handling otherwise returns true. If returned false
* then the WSDL parser can abort if the wsdl extensibility element had <code>required</code> attribute set to true
*/
public boolean handlePortTypeExtension(TWSDLParserContext context, TWSDLExtensible parent, Element e) {
return false;
}
/**
* Callback for <code>wsdl:definitions</code>
*
* @param context Parser context that will be passed on by the wsdl parser
* @param parent The Parent element within which the extensibility element is defined
* @param e The extensibility elemenet
* @return false if there was some error during the extension handling otherwise returns true. If returned false
* then the WSDL parser can abort if the wsdl extensibility element had <code>required</code> attribute set to true
*/
public boolean handleDefinitionsExtension(TWSDLParserContext context, TWSDLExtensible parent, Element e) {
return false;
}
/**
* Callback for <code>wsdl:type</code>
*
* @param context Parser context that will be passed on by the wsdl parser
* @param parent The Parent element within which the extensibility element is defined
* @param e The extensibility elemenet
* @return false if there was some error during the extension handling otherwise returns true. If returned false
* then the WSDL parser can abort if the wsdl extensibility element had <code>required</code> attribute set to true
*/
public boolean handleTypesExtension(TWSDLParserContext context, TWSDLExtensible parent, Element e) {
return false;
}
/**
* Callback for <code>wsdl:binding</code>
*
* @param context Parser context that will be passed on by the wsdl parser
* @param parent The Parent element within which the extensibility element is defined
* @param e The extensibility elemenet
* @return false if there was some error during the extension handling otherwise returns true. If returned false
* then the WSDL parser can abort if the wsdl extensibility element had <code>required</code> attribute set to true
*/
public boolean handleBindingExtension(TWSDLParserContext context, TWSDLExtensible parent, Element e) {
return false;
}
/**
* Callback for <code>wsdl:portType/wsdl:operation</code>.
*
* @param context Parser context that will be passed on by the wsdl parser
* @param parent The Parent element within which the extensibility element is defined
* @param e The extensibility elemenet
* @return false if there was some error during the extension handling otherwise returns true. If returned false
* then the WSDL parser can abort if the wsdl extensibility element had <code>required</code> attribute set to true
*/
public boolean handleOperationExtension(TWSDLParserContext context, TWSDLExtensible parent, Element e) {
return false;
}
/**
* Callback for <code>wsdl:input</code>
*
* @param context Parser context that will be passed on by the wsdl parser
* @param parent The Parent element within which the extensibility element is defined
* @param e The extensibility elemenet
* @return false if there was some error during the extension handling otherwise returns true. If returned false
* then the WSDL parser can abort if the wsdl extensibility element had <code>required</code> attribute set to true
*/
public boolean handleInputExtension(TWSDLParserContext context, TWSDLExtensible parent, Element e) {
return false;
}
/**
* Callback for <code>wsdl:output</code>
*
* @param context Parser context that will be passed on by the wsdl parser
* @param parent The Parent element within which the extensibility element is defined
* @param e The extensibility elemenet
* @return false if there was some error during the extension handling otherwise returns true. If returned false
* then the WSDL parser can abort if the wsdl extensibility element had <code>required</code> attribute set to true
*/
public boolean handleOutputExtension(TWSDLParserContext context, TWSDLExtensible parent, Element e) {
return false;
}
/**
* Callback for <code>wsdl:fault</code>
*
* @param context Parser context that will be passed on by the wsdl parser
* @param parent The Parent element within which the extensibility element is defined
* @param e The extensibility elemenet
* @return false if there was some error during the extension handling otherwise returns true. If returned false
* then the WSDL parser can abort if the wsdl extensibility element had <code>required</code> attribute set to true
*/
public boolean handleFaultExtension(TWSDLParserContext context, TWSDLExtensible parent, Element e) {
return false;
}
/**
* Callback for <code>wsdl:service</code>
*
* @param context Parser context that will be passed on by the wsdl parser
* @param parent The Parent element within which the extensibility element is defined
* @param e The extensibility elemenet
* @return false if there was some error during the extension handling otherwise returns true. If returned false
* then the WSDL parser can abort if the wsdl extensibility element had <code>required</code> attribute set to true
*/
public boolean handleServiceExtension(TWSDLParserContext context, TWSDLExtensible parent, Element e) {
return false;
}
/**
* Callback for <code>wsdl:port</code>
*
* @param context Parser context that will be passed on by the wsdl parser
* @param parent The Parent element within which the extensibility element is defined
* @param e The extensibility elemenet
* @return false if there was some error during the extension handling otherwise returns true. If returned false
* then the WSDL parser can abort if the wsdl extensibility element had <code>required</code> attribute set to true
*/
public boolean handlePortExtension(TWSDLParserContext context, TWSDLExtensible parent, Element e) {
return false;
}
}
| 50.617512
| 131
| 0.703933
|
726c614a57ab4ae2a2beded185c27883c0ccd122
| 1,854
|
package org.apache.http.spring.boot.client.handler;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.StatusLine;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import org.apache.http.spring.boot.client.exception.HttpResponseException;
/**
*
* @className: XMLResponseHandler
* @description: http请求响应处理:返回org.w3c.dom.Document对象
* @author : hiwepy
* @date : 下午01:43:19 2015-7-14
* @modify by:
* @modify date :
* @modify description :
*/
public class XMLResponseHandler implements ResponseHandler<Document> {
private DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
@Override
public void handleClient(HttpClient httpclient) {
}
@Override
public Document handleResponse(HttpMethodBase httpMethod) throws IOException {
StatusLine statusLine = httpMethod.getStatusLine();
int status = statusLine.getStatusCode();
if (status >= HttpStatus.SC_OK && status < HttpStatus.SC_MULTIPLE_CHOICES) {
try {
DocumentBuilder docBuilder = factory.newDocumentBuilder();
return docBuilder.parse(httpMethod.getResponseBodyAsString());
} catch (ParserConfigurationException ex) {
throw new IllegalStateException(ex);
} catch (SAXException ex) {
throw new HttpResponseException("Malformed XML document", ex);
} finally {
}
} else {
throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
}
}
}
| 31.965517
| 94
| 0.721683
|
8273f39bcf88a9e7ec1bf8e2bcec4d76da2d7aa2
| 2,153
|
package com.packtpublishing.tddjava.alexandria;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import java.util.ArrayList;
import java.util.List;
@XmlRootElement
public class Book {
private final String title;
private final String author;
@XmlTransient
private ArrayList<States> status;
private int id;
public Book(String title, String author, States status) {
this.title = title;
this.author = author;
this.status = new ArrayList<>();
this.status.add(status);
}
public String getTitle() {
return title;
}
public States getStatus() {
return status.get(status.size() - 1);
}
public String getAuthor() {
return author;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
@XmlElement(name = "status")
public int getStatusAsInteger(){
return getStatus().getValue();
}
public void rent() {
status.add(States.RENTED);
}
public void returnBook() {
status.add(States.AVAILABLE);
}
public void censor() {
status.add(States.CENSORED);
}
public void uncensor() {
status.add(States.AVAILABLE);
}
public void prepare() {
status.add(States.AVAILABLE);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Book book = (Book) o;
if (id != book.id) return false;
if (!author.equals(book.author)) return false;
if (!status.equals(book.status)) return false;
if (!title.equals(book.title)) return false;
return true;
}
@Override
public int hashCode() {
int result = title.hashCode();
result = 31 * result + author.hashCode();
result = 31 * result + status.hashCode();
result = 31 * result + id;
return result;
}
public List<States> anyState() {
return status;
}
}
| 21.747475
| 66
| 0.594055
|
0222af2c6a1f4ae8ad08af880c5a8bf8b7942d47
| 907
|
package au.edu.unsw.soacourse.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection {
private static final String DB_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_CONNECTION = "jdbc:mysql://localhost:3306/licencedb?autoReconnect=true&useSSL=false";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "root";
/**
* Get a connetion to the database
* @return Connection to the database
* @throws ClassNotFoundException ..
* @throws SQLException If a database error occurs
*/
public static Connection getConnection() throws ClassNotFoundException, SQLException {
Connection dbConnection = null;
Class.forName(DB_DRIVER);
dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
return dbConnection;
}
}
| 32.392857
| 118
| 0.753032
|
50b9d26af46abd4330e70d21c5a41144827d746c
| 283
|
package com.icode.componentservicerepository.understanding;
import org.springframework.stereotype.Repository;
@Repository
public class GirlRepositoryImpl implements GirlRepository {
@Override
public Girl getGirlByName(String name) {
return new Girl(name);
}
}
| 21.769231
| 59
| 0.773852
|
34180d9cdb6315f6bcca0193ac3d06308209f9c7
| 7,725
|
package com.bwyap.network.server;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import com.bwyap.network.ConnectionState;
import com.bwyap.network.authenticator.ServerAuthenticator;
import com.bwyap.network.interpreter.ConsoleServerInterpreter;
import com.bwyap.network.interpreter.ServerInterpreter;
import com.bwyap.utility.interpreter.InterpreterInterface;
/**
* An abstract class representing a server bound to a specified port.
* If no port is specified, the default port (8080) is used.
* When the server is run,
* it will create a {@code ServerSocket} that listens to the specified port for incoming connections on a new thread.
* Every new connection, once authenticated, will be added to a list of clients as a {@code ClientConnection} object.
* Each connection starts a new thread to listen to any incoming messages and TODO to send messages.
* <p>
* A separate thread is also started to poll all connected clients.
* The polling method for clients should be defined in a concrete implementation.
*
* @author bwyap
*
*/
public abstract class Server implements Runnable {
public static final String VERSION = "0.8a";
public static final boolean DEV_DEBUG = false;
//TODO change this to use properties file
protected static final int DEFAULT_PORT = 8080;
protected final int MAX_CLIENTS;
protected final UUID SERVERID;
protected int port;
protected ServerSocket serverSocket;
protected ServerAuthenticator authenticator;
protected ServerLogger logger;
protected List<ClientConnection> clients =
Collections.synchronizedList(new ArrayList<ClientConnection>());
protected InterpreterInterface interpreter;
protected volatile boolean listening = false;
protected volatile boolean polling = false;
protected Thread listenThread;
protected Thread pollThread;
protected Thread interpreterThread;
/**
* Create a Server on the default port
*/
public Server(String name, final int maxConnections, ServerAuthenticator authenticator) {
if (DEV_DEBUG) System.out.println("SERVER version " + VERSION);
this.SERVERID = UUID.randomUUID();
this.port = DEFAULT_PORT;
this.authenticator = authenticator;
this.authenticator.setUUID(SERVERID);
this.MAX_CLIENTS = maxConnections;
this.logger = new ServerLogger(name, System.out);
logger.pushInfo("Server [" + name + "] created on port " + this.port + " (default).");
logger.pushInfo("ID: " + this.SERVERID);
}
/**
* Create a server on the specified port.
* @param port
*/
public Server(String name, int port, final int maxConnections, ServerAuthenticator authenticator) {
System.out.println("SERVER version " + VERSION);
this.SERVERID = UUID.randomUUID();
this.port = port;
this.authenticator = authenticator;
this.MAX_CLIENTS = maxConnections;
this.logger = new ServerLogger(name, System.out);
logger.pushInfo("Server [" + name + "] created on port " + this.port + ".");
logger.pushInfo("ID: " + this.SERVERID);
}
@Override
public void run() {
if (Server.DEV_DEBUG) logger.pushInfo("Starting server...");
// Open the socket on the specified port
if (!createSocket()) {
logger.pushError("Error opening port.");
return;
}
else if (Server.DEV_DEBUG) logger.pushInfo("Server bound to port.");
// Start a new thread to listen for new clients
listening = true;
listenThread = new Thread(new ServerListener(), "listen");
listenThread.start();
// Start a new thread to poll all existing client connections
polling = true;
pollThread = new Thread(new ClientConnectionPoller(), "poll");
pollThread.start();
//Start a new thread to listen to user commands
interpreter = new ConsoleServerInterpreter(this);
interpreterThread = new Thread((ServerInterpreter) interpreter, "interpret");
interpreterThread.start();
}
/**
* Tries to open a socket on the port the server has been assigned to
* @return true if binding is successful
*/
private boolean createSocket() {
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* Handler for when a client is polled
* @param client
*/
protected abstract void pollClient(ClientConnection client);
/**
* Listens to the server's assigned port for any new connections from clients.
* Client connections are added to the server's client list.
* @author Benjamin
*
*/
private class ServerListener implements Runnable {
@Override
public void run() {
while (listening) {
try {
if (DEV_DEBUG) logger.pushInfo("Listening for clients...");
serverSocket.setSoTimeout(5000);
Socket socket = serverSocket.accept();
ClientConnection client = createClientConnection(SERVERID, socket, logger, authenticator, interpreter);
// Check if exceeding connected clients
if (clients.size() >= MAX_CLIENTS) {
logger.pushCon("Client tried to connect: " + socket.getInetAddress() + ":" + socket.getPort());
logger.pushCon("SERVER FULL: " + socket.getInetAddress() + ":" + socket.getPort() + " kicked");
client.sendToClient(authenticator.generateServerFullMessage());
client.state = ConnectionState.DISCONNECTING;
}
else {
// Add client to connected clients
clients.add(client);
logger.pushCon("New connection from " + socket.getInetAddress() + ":" + socket.getPort());
}
client.start();
}
catch (SocketTimeoutException e) {
//Socket timeout is expected.
}
catch (IOException e) {
e.printStackTrace();
}
}
//Listening thread exiting
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Create a new ClientConnection object.
* This method should be used to instantiate subclasses of ClientConnection.
* @param SERVERID
* @param socket
* @param logger
* @param authenticator
* @return
*/
protected abstract ClientConnection createClientConnection(UUID serverID, Socket socket, ServerLogger logger, ServerAuthenticator authenticator, InterpreterInterface interpreter);
/**
* Polls all existing client connections for their state
* @author Benjamin
*
*/
private class ClientConnectionPoller implements Runnable {
@Override
public void run() {
while (polling) {
for (int i = 0; i < clients.size(); i++) {
synchronized (clients) {
pollClient(clients.get(i));
}
}
}
}
}
/**
* Safely disconnects all clients and the server down
*/
public synchronized void shutdown() {
//TODO
//Save stuff
//
for (ClientConnection c : clients) {
c.kick("Server shutting down.");
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
listening = false;
polling = false;
interpreter.stop();
logger.pushInfo("Server shutting down.");
}
/**
* Get the ID of the server
* @return
*/
public UUID getID() {
return SERVERID;
}
/**
* Get the port the server is listening on
* @return
*/
public int getPort() {
return port;
}
/**
* Gets the ServerInterpreter for this client.
* @return
*/
public ServerInterpreter getInterpreter() {
return (ServerInterpreter) interpreter;
}
/**
* Get the list of clients connected to the server.
* @return
*/
public List<ClientConnection> getClients() {
return clients;
}
public boolean isRunning() {
return listening && polling && interpreter.isRunning();
}
}
| 26.455479
| 180
| 0.700453
|
15560041db7ccd3c48fa443c1271db82b839e2e4
| 4,680
|
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.greglturnquist.learningspringboot;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.*;
import static org.mockito.Mockito.mock;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.repository.config.EnableReactiveMongoRepositories;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.FileSystemUtils;
/**
* @author Greg Turnquist
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ImageServiceTests.TestConfig.class)
@DataMongoTest
public class ImageServiceTests {
@Autowired
ImageRepository repository;
@Autowired
ImageService imageService;
@Autowired
MongoOperations operations;
@Before
public void setUp() throws IOException {
operations.dropCollection(Image.class);
operations.insert(new Image("1",
"learning-spring-boot-cover.jpg"));
operations.insert(new Image("2",
"learning-spring-boot-2nd-edition-cover.jpg"));
operations.insert(new Image("3",
"bazinga.png"));
FileSystemUtils.deleteRecursively(new File(ImageService.UPLOAD_ROOT));
Files.createDirectory(Paths.get(ImageService.UPLOAD_ROOT));
FileCopyUtils.copy("Test file",
new FileWriter(ImageService.UPLOAD_ROOT +
"/learning-spring-boot-cover.jpg"));
FileCopyUtils.copy("Test file2",
new FileWriter(ImageService.UPLOAD_ROOT +
"/learning-spring-boot-2nd-edition-cover.jpg"));
FileCopyUtils.copy("Test file3",
new FileWriter(ImageService.UPLOAD_ROOT + "/bazinga.png"));
}
@Test
public void findAllImages() {
List<Image> images = imageService
.findAllImages()
.collectList()
.block(Duration.ofSeconds(30));
assertThat(images)
.hasSize(3)
.extracting("name").contains(
"learning-spring-boot-cover.jpg",
"bazinga.png",
"learning-spring-boot-2nd-edition-cover.jpg");
}
@Test
public void findOneImage() {
Resource resource = imageService.findOneImage("learning-spring-boot-cover.jpg").block(Duration.ofSeconds(30));
assertThat(resource.exists()).isTrue();
}
@Test
public void deleteImage() {
imageService.deleteImage("learning-spring-boot-cover.jpg").block(Duration.ofSeconds(30));
}
@Test
public void createImages() {
Image alphaImage = new Image("1", "alpha.jpg");
Image bravoImage = new Image("2", "bravo.jpg");
FilePart file1 = mock(FilePart.class);
given(file1.filename()).willReturn(alphaImage.getName());
given(file1.transferTo(any())).willReturn(Mono.empty());
FilePart file2 = mock(FilePart.class);
given(file2.filename()).willReturn(bravoImage.getName());
given(file2.transferTo(any())).willReturn(Mono.empty());
List<Image> images = imageService
.createImage(Flux.just(file1, file2))
.then(imageService.findAllImages().collectList())
.block(Duration.ofSeconds(30));
assertThat(images).hasSize(5);
}
@Configuration
@EnableReactiveMongoRepositories(basePackageClasses = ImageRepository.class)
static class TestConfig {
@Bean
public ImageService imageService(ResourceLoader resourceLoader, ImageRepository imageRepository) {
return new ImageService(resourceLoader, imageRepository);
}
}
}
| 31.2
| 112
| 0.768162
|
57903c1a0c51016ce5e3d0a2cb855729a28c7394
| 639
|
package wt.app.website.controllers;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import wt.app.website.models.Location;
import wt.app.website.services.LocationService;
@RestController
public class LocationController {
@Autowired
LocationService locationService;
@GetMapping("api/location")
public List<Location> location() {
return locationService.getLocations();
}
}
| 24.576923
| 62
| 0.804382
|
ed721382512e55fa52632a0bfea7a59b57fb4365
| 4,088
|
package com.lhsang.dashboard.model;
import java.text.NumberFormat;
import java.util.List;
import java.util.Locale;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.lhsang.dashboard.utils.FormatUnit;
@Entity(name="products")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Product {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
private String img;
private double quantity;
private String unit;
private int price;
@Column(name="promotion_id")
private int promotionId;
private double remain;
private String notes;
private String description;
@OneToOne(fetch = FetchType.LAZY, mappedBy = "product", cascade = CascadeType.ALL)
@JsonManagedReference
ProductManage productManage;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="category_id")
@JsonBackReference
private Category category;
@OneToMany(mappedBy="product")
@JsonManagedReference
private List<OrderDetail> orderDetails;
@OneToMany(mappedBy="product",cascade=CascadeType.ALL)
@JsonManagedReference
List<Images> listImg;
public List<OrderDetail> getOrderDetails() {
return orderDetails;
}
public void setOrderDetails(List<OrderDetail> orderDetails) {
this.orderDetails = orderDetails;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public double getQuantity() {
return quantity;
}
public void setQuantity(double quantity) {
this.quantity = quantity;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getPromotionId() {
return promotionId;
}
public void setPromotionId(int promotionId) {
this.promotionId = promotionId;
}
public double getRemain() {
return remain;
}
public void setRemain(double remain) {
this.remain = remain;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public ProductManage getProductManage() {
return productManage;
}
public void setProductManage(ProductManage productManage) {
this.productManage = productManage;
}
// only test
public int getReviewTotal() {
int random = (int)(Math.random() * 20 + 1);
return random;
}
public String getRating() {
String rating="<span class=\"fa fa-star checked\"></span>";
String notRating="<span class=\"fa fa-star \"></span>";
int random = (int)(Math.random() * 5 + 2);
String ans="";
for(int i=1;i<=5;i++) {
if(i<=random)
ans+=rating;
else ans+=notRating;
}
return ans;
}
public String formatMoney() {
return FormatUnit.formatMoneyToVND(price);
}
public String getNameLimitCharacter(int num) {
num=num<=name.length()? num:name.length();
return FormatUnit.nearestWord(num, name);
}
public List<Images> getListImg() {
return listImg;
}
public void setListImg(List<Images> listImg) {
this.listImg = listImg;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
| 19.283019
| 83
| 0.728963
|
39c0d62360956dfa830812240dc2bacedc21353f
| 164
|
package space.nyuki.questionnaire.exception;
public class CollectionEmptyException extends RuntimeException {
public CollectionEmptyException() {
super();
}
}
| 20.5
| 64
| 0.804878
|
8b78cd54e52d72176b5e4b12111c301a3edb89ce
| 3,037
|
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.spellchecker.quickfixes;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Iconable;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.SmartPointerManager;
import com.intellij.psi.SmartPsiElementPointer;
import com.intellij.psi.util.PsiUtilBase;
import com.intellij.spellchecker.util.SpellCheckerBundle;
import consulo.annotation.access.RequiredReadAction;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
public class ChangeTo extends ShowSuggestions implements LocalQuickFix, Iconable
{
private final TextRange myRange;
private final SmartPsiElementPointer<PsiElement> myElementPointer;
public ChangeTo(String wordWithTypo, PsiElement element, TextRange range)
{
super(wordWithTypo);
myRange = range;
myElementPointer = SmartPointerManager.createPointer(element);
}
@Nonnull
public String getName()
{
return SpellCheckerBundle.message("change.to");
}
@Nonnull
public String getFamilyName()
{
return SpellCheckerBundle.message("change.to");
}
@Override
@RequiredReadAction
public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor)
{
PsiElement element = myElementPointer.getElement();
if(element == null)
{
return;
}
Editor editor = PsiUtilBase.findEditor(element);
if(editor == null)
{
return;
}
TextRange textRange = myRange;
editor.getSelectionModel().setSelection(textRange.getStartOffset(), textRange.getEndOffset());
String word = editor.getSelectionModel().getSelectedText();
if(word == null || StringUtil.isEmpty(word))
{
return;
}
List<LookupElement> lookupItems = new ArrayList<>();
for(String variant : getSuggestions(project))
{
lookupItems.add(LookupElementBuilder.create(variant));
}
LookupElement[] items = new LookupElement[lookupItems.size()];
items = lookupItems.toArray(items);
LookupManager lookupManager = LookupManager.getInstance(project);
lookupManager.showLookup(editor, items);
}
}
| 30.676768
| 96
| 0.780375
|
6b8670650573aac222001b29e252a001098c8360
| 2,075
|
package org.bricolages.streaming.stream.processor;
import org.bricolages.streaming.exception.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.Map;
import java.io.IOException;
import lombok.*;
public class ObjectColumnProcessor extends SingleColumnProcessor {
static public ObjectColumnProcessor build(ProcessorParams params, ProcessorContext ctx) {
val lenObj = params.getLength();
if (lenObj == null) {
throw new ConfigError("length is required: " + params.getName());
}
val len = (int)lenObj;
if (len <= 0) {
throw new ConfigError("object params requires positive length: " + params.getName());
}
return new ObjectColumnProcessor(params, len);
}
final int length;
public ObjectColumnProcessor(ProcessorParams params, int length) {
super(params);
this.length = length;
}
static final ObjectMapper MAPPER = new ObjectMapper();
@Override
public Object processValue(Object value) throws ProcessorException {
if (value == null) return null;
if (value instanceof String && ((String)value).startsWith("{")) {
try {
value = MAPPER.readValue((String)value, new TypeReference<Map<Object, Object>>() {});
}
catch (IOException ex) {
throw new ProcessorException("JSON parse error: " + ex.getMessage());
}
}
checkJSONObject(value);
return value;
}
void checkJSONObject(Object obj) throws ProcessorException {
try {
val json = MAPPER.writeValueAsString(obj);
if (json.length() > this.length) {
throw new ProcessorException("object too long: length=" + json.length());
}
}
catch (JsonProcessingException ex) {
throw new ProcessorException("JSON serialize error: " + ex.getMessage());
}
}
}
| 35.169492
| 101
| 0.634217
|
5904b4e82f012f7e2800635b18b95f68ae3cda34
| 10,279
|
package laine.com.timepicker.fragment;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import laine.com.timepicker.base.BaseFragmentActivity;
import laine.com.timepicker.base.BaseFragmentListener;
import laine.com.timepicker.third.spinnerwheel.AbstractWheel;
import laine.com.timepicker.third.spinnerwheel.AbstractWheelTextAdapter;
public class YearSpinnerWheelFragment extends Fragment {
private Context context;
private View view;
private BaseFragmentListener listener;
private TextView titleTv;
private String mTitle;
private int date_length = 10;
private int month_length = 12;
public String tag = "";
private Calendar startC;
private boolean isShowTime = true;
public YearSpinnerWheelFragment() {
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = activity;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if (bundle != null) {
tag = bundle.getString("tag");
}
}
public void addListener(BaseFragmentListener listener) {
this.listener = listener;
}
public void setDateLength(int length) {
this.date_length = length;
}
public void setShowTime(boolean isShowTime) {
this.isShowTime = isShowTime;
}
public void setDate(String start, int dateLength, boolean time) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(
time ? "yyyy-MM-dd HH:mm:ss" : "yyyy-MM-dd");
Date s = sdf.parse(start);
startC = Calendar.getInstance();
startC.setTime(s);
this.date_length = dateLength;
} catch (ParseException e) {
e.printStackTrace();
}
}
public void setDate(String start, String end, boolean time) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(
time ? "yyyy-MM-dd HH:mm:ss" : "yyyy-MM-dd");
Date s = sdf.parse(start);
Date e = sdf.parse(end);
Date c = new Date();
startC = Calendar.getInstance();
startC.setTime(s.after(c) ? s : c);
Calendar ec = Calendar.getInstance();
ec.setTime(e);
int sd = startC.get(Calendar.DAY_OF_YEAR);
int ed = ec.get(Calendar.DAY_OF_YEAR);
this.date_length = Math.abs(ed - sd) + 1;
} catch (ParseException e) {
e.printStackTrace();
}
}
public void setTitle(String title) {
mTitle = title;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(getResId("fragment_date_spinner_wheel_layout"),
null);
initView();
return view;
}
private int getResId(String resourceName){
Resources resources = getResources();
int resId = resources.getIdentifier(resourceName,"layout",context.getPackageName());
return resId;
}
private int getId(String idName){
Resources resources = getResources();
int resId = resources.getIdentifier(idName, "id", context.getPackageName());
return resId;
}
private void onCallBack(Date date) {
if (listener != null) {
listener.onCallBack(date);
}
}
private void initView() {
titleTv = (TextView) view.findViewById(getId("title_text"));
titleTv.setText(mTitle);
final AbstractWheel day = (AbstractWheel) view.findViewById(getId("date"));
final DayArrayAdapter dayAdapter = new DayArrayAdapter(context);
day.setViewAdapter(dayAdapter);
day.setCurrentItem(0);
day.setVisibleItems(5);
if (!isShowTime) {
view.findViewById(getId("time")).setVisibility(View.GONE);
}
final AbstractWheel time = (AbstractWheel) view.findViewById(getId("time"));
final TimeArrayAdapter timeAdapter = new TimeArrayAdapter(context);
time.setViewAdapter(timeAdapter);
time.setCurrentItem(40);
time.setVisibleItems(5);
time.setCyclic(true);
view.findViewById(getId("cancel")).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
if (context instanceof BaseFragmentActivity) {
((BaseFragmentActivity) context).displayFragment(
false, "single_spinner", null, listener);
}
}
});
view.findViewById(getId("complete")).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
if (context instanceof BaseFragmentActivity) {
((BaseFragmentActivity) context).displayFragment(
false, tag, null, listener);
}
Date year = dayAdapter.getItemTime(day.getCurrentItem());
Date month = timeAdapter.getItemTime(time.getCurrentItem());
onCallBack(parserDate(year, month));
}
});
view.findViewById(getId("mark_layout")).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
if (context instanceof BaseFragmentActivity) {
((BaseFragmentActivity) context).displayFragment(
false, tag, null, listener);
}
}
});
}
private Date parserDate(Date year, Date month) {
Calendar y = Calendar.getInstance(Locale.getDefault());
Calendar m = Calendar.getInstance(Locale.getDefault());
Calendar c = Calendar.getInstance(Locale.getDefault());
y.setTime(year);
m.setTime(month);
c.set(y.get(Calendar.YEAR), m.get(Calendar.MONTH), 1);
return c.getTime();
}
/**
* Day adapter
*/
private class DayArrayAdapter extends AbstractWheelTextAdapter {
private Calendar calendar;
private SparseArray<Date> timeMap;
private SimpleDateFormat sformat = new SimpleDateFormat("yyyy年");
protected DayArrayAdapter(Context context) {
super(context, getResId("time_picker_custom_time"), getId("time_value"));
this.calendar = startC == null ? Calendar.getInstance() : startC;
timeMap = new SparseArray<Date>(date_length);
}
@Override
public View getItem(int index, View cachedView, ViewGroup parent) {
View view = super.getItem(index, cachedView, parent);
TextView date = (TextView) view.findViewById(getId("time_value"));
Date d = null;
int i = timeMap.indexOfKey(index);
if (i >= 0) {
d = timeMap.get(index);
} else {
Calendar calendar_ = (Calendar) calendar.clone();
calendar_.add(Calendar.YEAR, index);
d = calendar_.getTime();
timeMap.put(index, d);
}
date.setText(sformat.format(d));
return view;
}
@Override
public int getItemsCount() {
return date_length;
}
public Date getItemTime(int index) {
if (timeMap.indexOfKey(index) >= 0) {
return timeMap.get(index);
}
return new Date();
}
@Override
protected CharSequence getItemText(int index) {
return "";
}
}
/**
* Day adapter
*/
private class TimeArrayAdapter extends AbstractWheelTextAdapter {
private Calendar calendar;
private SparseArray<Date> timeMap;
private SimpleDateFormat sformat = new SimpleDateFormat("MM月");
protected TimeArrayAdapter(Context context) {
super(context, getResId("time_picker_custom_time"), getId("time_value"));
this.calendar = startC == null ? Calendar.getInstance() : startC;
timeMap = new SparseArray<Date>(month_length);
}
@Override
public View getItem(int index, View cachedView, ViewGroup parent) {
View view = super.getItem(index, cachedView, parent);
TextView date = (TextView) view.findViewById(getId("time_value"));
Date d = null;
int i = timeMap.indexOfKey(index);
if (i >= 0) {
d = timeMap.get(index);
} else {
Calendar calendar_ = (Calendar) calendar.clone();
calendar_.add(Calendar.MONTH, index);
d = calendar_.getTime();
timeMap.put(index, d);
}
date.setText(sformat.format(d));
return view;
}
public Date getItemTime(int index) {
if (timeMap.indexOfKey(index) >= 0) {
return timeMap.get(index);
}
return new Date();
}
@Override
public int getItemsCount() {
return month_length;
}
@Override
protected CharSequence getItemText(int index) {
// Date d = timeMap.get(index);
return "";
}
}
}
| 32.021807
| 92
| 0.575932
|
6e84d08b17d0425fe64bbb00ab60ffbada8bca54
| 1,491
|
/*
* Copyright 2016-2019 52°North Initiative for Geospatial Open Source
* Software GmbH
*
* 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.n52.javaps.service.kvp;
import org.n52.janmayen.http.MediaTypes;
import org.n52.shetland.ogc.wps.WPS200Constants;
import org.n52.shetland.ogc.wps.WPSConstants;
import org.n52.shetland.ogc.wps.request.GetStatusRequest;
import org.n52.svalbard.decode.OperationDecoderKey;
/**
* TODO JavaDoc
*
* @author Christian Autermann
*/
public class GetStatusKvpDecoder extends AbstractJobIdKvpDecoder<GetStatusRequest> {
public GetStatusKvpDecoder() {
super(GetStatusRequest::new, new OperationDecoderKey(WPSConstants.SERVICE, WPS200Constants.VERSION,
WPSConstants.Operations.GetStatus.name(), MediaTypes.APPLICATION_KVP), new OperationDecoderKey(
WPSConstants.SERVICE, null, WPSConstants.Operations.GetStatus.name(),
MediaTypes.APPLICATION_KVP));
}
}
| 37.275
| 111
| 0.743796
|
a9320acf4b15e981efc3949b0fc264cc33db5c47
| 1,027
|
package com.bakdata.commons.serialization;
import java.io.Serializable;
/**
* <p> Interface to take care of serializing and deserializing objects of class {@code T} from and
* to {@code byte[]}. </p>
*
* <p>It is recommended to implement the {@code equals()} method.</p>
*
* @param <T> Class which can be serialized and deserialized by this class
*/
public interface Serializer<T> extends Serializable {
/**
* Deserializes an object of class {@code T} from a {@code byte[]}
*
* @param bytes raw bytes representing an object of class {@code T}
* @return deserialized object
* @throws SerializationException if deserialization fails
*/
T deserialize(byte[] bytes) throws SerializationException;
/**
* Serialize an object of class {@code T} to a {@code byte[]}
*
* @param t object of class {@code T} to be serialized
* @return raw bytes representing @{code t}
* @throws SerializationException if serialization fails
*/
byte[] serialize(T t) throws SerializationException;
}
| 30.205882
| 98
| 0.695229
|
189687de237b7a9d2ab9d1eb2fedd5559a74e068
| 3,572
|
package me.zhengjie.modules.Archivesmouthsmanagement.service.impl;
import me.zhengjie.modules.Archivesmouthsmanagement.domain.Archivesmouthsmanagement;
import me.zhengjie.modules.Archivesmouthsmanagement.repository.ArchivesmouthsmanagementRepository;
import me.zhengjie.modules.Archivesmouthsmanagement.service.ArchivesmouthsmanagementService;
import me.zhengjie.modules.Archivesmouthsmanagement.service.dto.ArchivesmouthsmanagementDTO;
import me.zhengjie.modules.Archivesmouthsmanagement.service.dto.ArchivesmouthsmanagementQueryCriteria;
import me.zhengjie.modules.Archivesmouthsmanagement.service.mapper.ArchivesmouthsmanagementMapper;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.ValidationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class ArchivesmouthsmanagementServicelmpl implements ArchivesmouthsmanagementService {
@Autowired
private ArchivesmouthsmanagementRepository archivesmouthsmanagementRepository;
@Autowired
private ArchivesmouthsmanagementMapper archivesmouthsmanagementMapper;
@Override
public Object queryAll(ArchivesmouthsmanagementQueryCriteria criteria, Pageable pageable){
Page<Archivesmouthsmanagement> page = archivesmouthsmanagementRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
return PageUtil.toPage(page.map(archivesmouthsmanagementMapper::toDto));
}
@Override
public Object queryAll(ArchivesmouthsmanagementQueryCriteria criteria){
return archivesmouthsmanagementMapper.toDto(archivesmouthsmanagementRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
}
@Override
public ArchivesmouthsmanagementDTO findById(Integer id) {
Optional<Archivesmouthsmanagement> tenantinformation = archivesmouthsmanagementRepository.findById(id);
ValidationUtil.isNull(tenantinformation,"Archivesmouthsmanagement","id",id);
return archivesmouthsmanagementMapper.toDto(tenantinformation.get());
}
@Override
@Transactional(rollbackFor = Exception.class)
public ArchivesmouthsmanagementDTO create(Archivesmouthsmanagement resources) {
return archivesmouthsmanagementMapper.toDto(archivesmouthsmanagementRepository.save(resources));
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(Archivesmouthsmanagement resources) {
Optional<Archivesmouthsmanagement> optionalTenantinformation = archivesmouthsmanagementRepository.findById(resources.getId());
ValidationUtil.isNull( optionalTenantinformation,"Archivesmouthsmanagement","id",resources.getId());
Archivesmouthsmanagement archivesmouthsmanagement = optionalTenantinformation.get();
archivesmouthsmanagement.copy(resources);
archivesmouthsmanagementRepository.save(archivesmouthsmanagement);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Integer id) {
archivesmouthsmanagementRepository.deleteById(id);
}
}
| 49.611111
| 195
| 0.821669
|
a0ece21c68492f7dadcc3140cbdb5a5681a8203d
| 3,808
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.rhhs.frc.commands;
import edu.rhhs.frc.subsystems.PneumaticSubsystem;
import edu.rhhs.frc.subsystems.Winch;
/**
* @author rhhs
*/
public class WinchSetPositionShortShot extends ExtraThreeTimeoutCommandBase {
private static final double WINCH_ENGAGE_TIMEOUT = 0.1;
private static final double WINCH_BRAKE_EXTEND_TIMEOUT = 0.1;
private static final double WINCH_FREE_TIMEOUT = 0.1;
private boolean m_winchEngaged;
private boolean m_brakeExtended;
private boolean m_winchFree;
private double m_deltaDistance;
public WinchSetPositionShortShot(double deltaDistance) {
m_deltaDistance = deltaDistance;
requires(getWinch());
setInterruptible(false);
}
// Called just before this Command runs the first time
protected void initialize() {
m_winchEngaged = false;
m_brakeExtended = false;
m_winchFree = false;
resetTimer1();
resetTimer2();
resetTimer3();
// Check if we are already at the short shot position
// if (getWinch().getWinchPosition() == Winch.WINCH_AT_SHORT_SHOT) {
// startExtraTimeout3(0);
// return;
// }
System.out.println("Winch retract started Distance = " + m_deltaDistance);
getWinch().resetZeroPosition();
getWinch().setDeviceZeroPositionOffset(0);
getWinch().setShiftPosition(PneumaticSubsystem.EXTEND);
getWinch().setWinchSpeed(Winch.WINCH_RELEASE_SPEED);
startExtraTimeout1(WINCH_ENGAGE_TIMEOUT);
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
if (!m_winchEngaged && isExtraTimedOut1()) {
System.out.println("Winch retract brake retracted");
getWinch().setWinchSpeed(Winch.WINCH_RETRACT_SPEED);
getWinch().setBrakePosition(PneumaticSubsystem.RETRACT);
m_winchEngaged = true;
}
else if (!m_brakeExtended && m_winchEngaged && (m_deltaDistance - getWinch().getDevicePosition()) > 0) {
System.out.println("Winch retract brake extended. Current = " + getWinch().getDevicePosition());
getWinch().setWinchSpeed(Winch.WINCH_HOLD_SPEED);
getWinch().setBrakePosition(PneumaticSubsystem.EXTEND);
startExtraTimeout2(WINCH_BRAKE_EXTEND_TIMEOUT);
m_brakeExtended = true;
}
else if (!m_winchFree && isExtraTimedOut2()) {
getWinch().setBrakePosition(PneumaticSubsystem.EXTEND);
getWinch().setShiftPosition(PneumaticSubsystem.RETRACT);
getWinch().setWinchSpeed(-0.2);
startExtraTimeout3(WINCH_FREE_TIMEOUT);
m_winchFree = true;
}
System.out.println("Position = " + getWinch().getDevicePosition() + ", Delta distance = " + (m_deltaDistance - getWinch().getDevicePosition()));
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
if (isExtraTimedOut3()) {
System.out.println("Winch free finished");
}
return isExtraTimedOut3();
}
// Called once after isFinished returns true
protected void end() {
getWinch().setBrakePosition(PneumaticSubsystem.EXTEND);
getWinch().setShiftPosition(PneumaticSubsystem.RETRACT);
getWinch().stopWinch();
getWinch().setWinchPosition(Winch.WINCH_AT_SHORT_SHOT);
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
System.out.println("Winch retract Interrupted");
end();
}
}
| 38.08
| 152
| 0.660714
|
63ff0691528423a6510b01390ca9195a14115a2a
| 763
|
package xyz.sanshan.main.service.convent;
import org.modelmapper.ModelMapper;
import xyz.sanshan.main.pojo.dto.recommend.RecommendDTO;
import xyz.sanshan.main.pojo.entity.recommend.RecommendDO;
import java.util.Objects;
public class RecommendConvert {
private static final ModelMapper MODEL_MAPPER = new ModelMapper();
public static RecommendDTO doToDto(RecommendDO recommendDO){
if (Objects.isNull(recommendDO)) {
return null;
}
return MODEL_MAPPER.map(recommendDO,RecommendDTO.class);
}
public static RecommendDO dtoToDo(RecommendDTO recommendDTO){
if (Objects.isNull(recommendDTO)) {
return null;
}
return MODEL_MAPPER.map(recommendDTO,RecommendDO.class);
}
}
| 26.310345
| 70
| 0.714286
|
8123785d56006f8b76644d639dde003a8a6eaf5d
| 1,271
|
package model;
import java.io.Serializable;
public class City implements Serializable, Comparable<City> {
private static final long serialVersionUID = 1;
//---------------------------- Attributes of the City class ----------------------------\\
private int codeCi;
private String nameCi;
private int refCi;
//-------------------------- Constructor, getter and setter class --------------------------\\
/**
* City class constructor
* @param codeCi object's code
* @param nameCi object's name
* @param refCi object's reference
*/
public City(int codeCi, String nameCi, int refCi) {
this.codeCi = codeCi;
this.nameCi = nameCi;
this.refCi = refCi;
}
public int getCodeCi() {
return codeCi;
}
public void setCodeCi(int codeCi) {
this.codeCi = codeCi;
}
public String getNameCi() {
return nameCi;
}
public void setNameCi(String nameCi) {
this.nameCi = nameCi;
}
public int getRefCi() {
return refCi;
}
public void setRefCi(int refCi) {
this.refCi = refCi;
}
@Override
public int compareTo(City o) {
return this.getNameCi().compareToIgnoreCase(o.getNameCi());
}
}
| 22.696429
| 98
| 0.556255
|
1fa8b6d4d15fe34199905ada212083729f41bb50
| 2,134
|
/*
* Copyright 2019 Institut Laue–Langevin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.ill.puma.persistence.service.document;
import eu.ill.puma.persistence.PumaTest;
import eu.ill.puma.persistence.domain.document.Formula;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
public class FormulaServiceTest extends PumaTest {
private static final Logger log = LoggerFactory.getLogger(FormulaServiceTest.class);
@Autowired
private FormulaService formulaService;
@Test
public void contextLoads() throws Exception {
Assert.assertNotNull(this.formulaService);
}
@Test
public void createAndRetrieve() {
Formula formula = new Formula();
formula.setCode("abcdef");
formulaService.save(formula);
Assert.assertNotNull(formula.getId());
Formula result = formulaService.getById(formula.getId());
Assert.assertEquals("abcdef", result.getCode());
List<Formula> formulas = formulaService.getAll();
Assert.assertTrue(formulas.size() > 0);
}
@Test
public void testSingleCreation() {
String code = "abcdef";
Formula formula1 = new Formula();
formula1.setCode(code);
formula1 = formulaService.save(formula1);
Assert.assertNotNull(formula1.getId());
Long formula1Id = formula1.getId();
Formula formula2 = new Formula();
formula2.setCode(code);
formula2 = formulaService.save(formula2);
Assert.assertNotNull(formula2.getId());
Long formula2Id = formula2.getId();
Assert.assertEquals(formula1Id, formula2Id);
}
}
| 27.012658
| 85
| 0.754452
|
6216e6170579c300bf1ae8bc7802f4867ef077a1
| 1,576
|
package storm.mesos.logviewer;
import java.net.InetAddress;
import java.net.Socket;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import com.google.common.base.Optional;
public class SocketUrlDetection implements IUrlDetection {
public static final int DEFAULT_PORT = 8000;
protected Optional<Integer> port;
private static final Logger LOG = Logger.getLogger(SocketUrlDetection.class);
public SocketUrlDetection() {
setPort(Optional.of(DEFAULT_PORT));
}
public SocketUrlDetection(int port) {
setPort(Optional.of(port));
}
public SocketUrlDetection(Optional<Integer> port) {
setPort(port);
}
@Override
public boolean isReachable() {
Socket socket = null;
boolean reachable = false;
try {
if (LOG.isDebugEnabled()) {
LOG.debug("Checking host " + InetAddress.getLocalHost() + " and port " + getPort());
}
if (port.isPresent()) {
socket = new Socket(InetAddress.getLocalHost(), getPort().get());
reachable = true;
}
} catch (Exception e) {
// don't care.
} finally {
IOUtils.closeQuietly(socket);
}
return reachable;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void setPort(Optional port) {
this.port = (Optional<Integer>) port;
}
@Override
public Optional<Integer> getPort() {
return port;
}
}
| 26.266667
| 100
| 0.593909
|
d169658aff085671a62ba27367dc84171cc009e8
| 1,456
|
/*******************************************************************************
* Copyright (c) Microsoft Open Technologies, Inc.
* All Rights Reserved
* See License.txt in the project root for license information.
******************************************************************************/
package com.microsoft.directoryservices;
/**
* The type License Units Detail.
*/
public class LicenseUnitsDetail extends ODataBaseEntity {
public LicenseUnitsDetail(){
setODataType("#Microsoft.DirectoryServices.LicenseUnitsDetail");
}
private Integer enabled;
/**
* Gets the enabled.
*
* @return the Integer
*/
public Integer getenabled() {
return this.enabled;
}
/**
* Sets the enabled.
*
* @param value the Integer
*/
public void setenabled(Integer value) {
this.enabled = value;
}
private Integer suspended;
/**
* Gets the suspended.
*
* @return the Integer
*/
public Integer getsuspended() {
return this.suspended;
}
/**
* Sets the suspended.
*
* @param value the Integer
*/
public void setsuspended(Integer value) {
this.suspended = value;
}
private Integer warning;
/**
* Gets the warning.
*
* @return the Integer
*/
public Integer getwarning() {
return this.warning;
}
/**
* Sets the warning.
*
* @param value the Integer
*/
public void setwarning(Integer value) {
this.warning = value;
}
}
| 18.909091
| 81
| 0.570055
|
fd6d57d203170b61ed0110d654a5c799139b8d04
| 2,741
|
package org.LeetcodeSolution.BranchAndBound;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Problem
* 77.Combinations
* https://leetcode.com/problems/combinations/
* Grade of difficulty
* Medium
* Related topics
* @author cartoon
* @version 1.0
*/
public class Solution77 {
private List<List<Integer>> res;
public List<List<Integer>> combine(int n, int k) {
if(n==0||k==0){
return Collections.emptyList();
}
res=new ArrayList<>();
List<Integer> list=new ArrayList<>();
combineByBranch(1,n,k,list);
return res;
}
/**
* 1.About Complexity
* 1.1 Time Complexity is O(n^2)
* 1.2 Space Complexity is O(n)
* 2.how I solve
* 2.1 this solution is base on branch and bound
* 2.2 circulate 1 to n-(k-list.size())+1 and backtracking i+1 at the same time
* 2.3 if k=list.size(),end recursion,and put current list to result list
* 3.About submit record
* 3.1 6ms and 49.4MB memory in LeetCode China
* 3.2 2ms and 39.3MB memory in LeetCode
* 4.Q&A
* 4.1 Q:Why is the time complexity of the two algorithms so different?
* A:I think it is about circulation times,this solution is wipe some useless recursion
* @param current
* @param n
* @param k
* @param list
*/
private void combineByBranch(int current,int n,int k,List<Integer> list){
if(k==list.size()){
res.add(new ArrayList<>(list));
}
else{
for(int i=current;i<=n-(k-list.size())+1;i++){
list.add(i);
combineByBranch(i+1,n,k,list);
list.remove(list.size()-1);
}
}
}
/**
* 1.About Complexity
* 1.1 Time Complexity is O(n^2)
* 1.2 Space Complexity is O(n)
* 2.how I solve
* 2.1 this solution is base on backTracking
* 2.2 circulate 1 to n and backtracking i+1 and k-1 at the same time
* 2.3 if k=0,end recursion,and put current list to result list
* 3.About submit record
* 3.1 36ms and 39MB memory in LeetCode China
* 3.2 19ms and 41.8MB memory in LeetCode
* 4.Q&A
* @param current
* @param n
* @param k
* @param list
*/
private void combineByBackTracking(int current,int n,int k,List<Integer> list){
if(k==0){
res.add(new ArrayList<>(list));
}
else{
for(int i=current;i<=n;i++){
list.add(i);
combineByBackTracking(i+1,n,k-1,list);
list.remove(list.size()-1);
}
}
}
}
| 29.473118
| 99
| 0.554907
|
68aea035e79067e39c354d68328e3d9f163ef71a
| 473
|
package com.qiuxs.cuteframework.web.action.cache;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import com.qiuxs.cuteframework.core.basic.utils.TimeUtils;
@Retention(RUNTIME)
@Target(METHOD)
public @interface ActionCache {
/** 缓存Keys */
String[] keys();
/** 有效时间 */
long expiresIn() default TimeUtils.SECONDS * 30;
}
| 21.5
| 59
| 0.773784
|
1efa7d5fe7ac00ba4d5d3165d3c42c47e575008c
| 1,272
|
package com.infusion.mongoutils;
import com.mongodb.BasicDBObject;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
/**
* When invoked, this goal connects to the mongo instance and clones the specified database from the source instance using
* <a href="https://docs.mongodb.org/manual/reference/command/clone/">clone</a>.
*/
@Mojo(name = "clone", defaultPhase = LifecyclePhase.PRE_INTEGRATION_TEST)
public class CloneMojo extends AbstractCommandMojo {
/**
* The database to clone.
*/
@Parameter(required = true)
private String database;
/**
* The source instance host in format: host[:port].
*/
@Parameter(required = true)
private String clone;
@Override
protected BasicDBObject getCommand() throws MojoExecutionException {
return new BasicDBObject("clone", clone);
}
@Override
protected String getDatabaseName() throws MojoExecutionException {
return database;
}
public CloneMojo() {}
CloneMojo(String database, String clone) {
this.database = database;
this.clone = clone;
}
}
| 28.909091
| 122
| 0.71305
|
93a50cd3b67463e43cdbc251700f0d4245702190
| 1,477
|
/*<license>
Copyright 2004-2005, PeopleWare n.v.
NO RIGHTS ARE GRANTED FOR THE USE OF THIS SOFTWARE, EXCEPT, IN WRITING,
TO SELECTED PARTIES.
</license>*/
package be.peopleware.persistence_II.ramstorage;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Emulation of a database in RAM.
*
* @author Jan Dockx
* @author Peopleware n.v.
*/
public class RamStorage {
/*<section name="Meta Information">*/
//------------------------------------------------------------------
/** {@value} */
public static final String CVS_REVISION = "$Revision$"; //$NON-NLS-1$
/** {@value} */
public static final String CVS_DATE = "$Date$"; //$NON-NLS-1$
/** {@value} */
public static final String CVS_STATE = "$State$"; //$NON-NLS-1$
/** {@value} */
public static final String CVS_TAG = "$Name$"; //$NON-NLS-1$
/*</section>*/
/**
* Map with all the {@link RamStorageMap} instances.
* The key is the type of the map.
*/
private HashMap $pbMaps = new HashMap();
/**
* @mudo missing specification
*/
public synchronized RamStorageMap getMap(final Class beanType) {
assert beanType != null;
RamStorageMap skpbm =
(RamStorageMap)$pbMaps.get(beanType);
if (skpbm == null) {
skpbm = new RamStorageMap(beanType);
$pbMaps.put(beanType, skpbm);
}
return skpbm;
}
public synchronized Map getRamStorageMaps() {
return Collections.unmodifiableMap($pbMaps);
}
}
| 25.033898
| 73
| 0.620176
|
dfed54fcde885a76ec872c89a4420ac969a4ff48
| 1,570
|
package run.nya.petbbs.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 全局Spring MVC设置
*
* 2021/02/18
*/
@Configuration
public class GlobalWebMvcConfigurer implements WebMvcConfigurer {
/**
* 跨域
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedHeaders("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.maxAge(3600);
}
/**
* 跨域过滤器
*/
@Bean
public CorsFilter corsFilter() {
CorsConfiguration configuration = new CorsConfiguration();
// 允许所有域名跨域
configuration.addAllowedOrigin("*");
// 允许全部原始头
configuration.addAllowedHeader("*");
// 允许所有请求方法跨域
configuration.addAllowedMethod("*");
// 允许跨域发送Cookie
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return new CorsFilter(source);
}
}
| 30.192308
| 87
| 0.671975
|
a58814fd317fb8ef4920b5bfc5db41162588da6b
| 1,524
|
package com.android.settings.rr.util;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
import com.android.settings.util.CMDProcessor;
public class OnBoot extends BroadcastReceiver {
Context settingsContext = null;
private static final String TAG = "RR_onboot";
Boolean mSetupRunning = false;
@Override
public void onReceive(Context context, Intent intent) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
for(int i = 0; i < procInfos.size(); i++)
{
if(procInfos.get(i).processName.equals("com.google.android.setupwizard")) {
mSetupRunning = true;
}
}
if(!mSetupRunning) {
SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(context);
if(sharedpreferences.getBoolean("selinux", true)) {
CMDProcessor.runSuCommand("setenforce 1");
} else if (!sharedpreferences.getBoolean("selinux", true)) {
CMDProcessor.runSuCommand("setenforce 0");
}
}
}
}
| 35.44186
| 111
| 0.698819
|
aefd3186d2c9acd4d27f5f3bb20c0368111fc586
| 1,956
|
/**
* Copyright (c) 2019,sunnybs.
* All Rights Reserved.
*
* Project Name:ad-search
* Package Name:com.imooc.ad.controller
* File Name:SearchController.java
* Date:2019年5月4日 下午5:07:23
*
*/
package com.imooc.ad.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.JSON;
import com.imooc.ad.annotation.IgnoreResponseAdvice;
import com.imooc.ad.client.SponsorClient;
import com.imooc.ad.client.vo.AdPlan;
import com.imooc.ad.client.vo.AdPlanGetRequest;
import com.imooc.ad.vo.CommonResponse;
import lombok.extern.slf4j.Slf4j;
/**
* ClassName: SearchController <br/>
* Description: TODO <br/>
* Date: 2019年5月4日 下午5:07:23 <br/>
* <br/>
*
* @author jiang(邮箱)
*
* 修改记录
* @version 产品版本信息 yyyy-mm-dd 姓名(邮箱) 修改信息<br/>
*
*/
@Slf4j
@RestController
public class SearchController {
@Autowired
private RestTemplate restTemplate;
@Autowired
private SponsorClient sponsorClient;
@PostMapping("/getAdPlans")
@IgnoreResponseAdvice
public CommonResponse<List<AdPlan>> getAd(@RequestBody AdPlanGetRequest request) {
log.info("ad-search: getAdPlansByRibbon -> {}", JSON.toJSON(request));
return sponsorClient.getAdPlans(request);
}
@PostMapping("/getByRibbon")
@IgnoreResponseAdvice
@SuppressWarnings("unchecked")
public CommonResponse<List<AdPlan>> getAdPlans(@RequestBody AdPlanGetRequest request) {
log.info("ad-search: getAdPlansByRibbon -> {}", JSON.toJSON(request));
return restTemplate
.postForEntity("http://eurela-client-ad-sponsor/ad-sponsor/get/adPlan", request, CommonResponse.class)
.getBody();
}
}
| 28.764706
| 118
| 0.724438
|
b2ef4b6aee4e546e8663522aa526c1553d320797
| 1,674
|
package com.wingplus.coomohome.activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.wingplus.coomohome.R;
import com.wingplus.coomohome.config.RuntimeConfig;
import com.wingplus.coomohome.util.GlideUtil;
/**
* 二维码页面
*
* @author leaffun.
* Create on 2017/9/10.
*/
public class QRcodeActivity extends BaseActivity implements View.OnClickListener {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qrcode);
initView();
}
private void initView() {
ImageView back = findViewById(R.id.back);
ImageView qrCode = findViewById(R.id.qrCode);
TextView des = findViewById(R.id.des);
// des.setText("二维码描述");
GlideUtil.GlideWithPlaceHolder(QRcodeActivity.this, RuntimeConfig.user.getQrCode()).into(qrCode);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.back:
finish();
overridePendingTransition(R.anim.close_x_enter, R.anim.close_x_exit);
break;
default:
break;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
finish();
overridePendingTransition(R.anim.close_x_enter, R.anim.close_x_exit);
return true;
}
return super.onKeyDown(keyCode, event);
}
}
| 28.372881
| 105
| 0.653524
|
865b1500fbfd6281bf2c25bf2b79b44275a97afc
| 11,466
|
/*
* Copyright 2021 The caver-java Authors
*
* Licensed under the Apache License, Version 2.0 (the “License”);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.klaytn.caver.abi.wrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.klaytn.caver.abi.ABI;
import com.klaytn.caver.abi.EventValues;
import com.klaytn.caver.abi.datatypes.Type;
import com.klaytn.caver.contract.ContractEvent;
import com.klaytn.caver.contract.ContractIOType;
import com.klaytn.caver.contract.ContractMethod;
import com.klaytn.caver.utils.Utils;
import org.web3j.protocol.ObjectMapperFactory;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
/**
* Representing an ABIWrapper which wraps all of static methods of ABI
*/
public class ABIWrapper {
/**
* Creates an ABIWrapper instance
*/
public ABIWrapper() {
}
/**
* Encodes a function call.
* @param method A ContractMethod instance.
* @param params A List of method parameter.
* @return String
*/
public String encodeFunctionCall(ContractMethod method, List<Object> params) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
return ABI.encodeFunctionCall(method, params);
}
/**
* Encodes a function call.
* @param functionSig A function signature string.
* @param params A List of method parameter.
* @return String
*/
public String encodeFunctionCall(String functionSig, List<String> solTypeList, List<Object> params) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
return ABI.encodeFunctionCall(functionSig, solTypeList, params);
}
/**
* Encodes a function call
* @param method A ContractMethod instance.
* @param params A List of method parameter wrapped solidity wrapper class.
* @return String
*/
public String encodeFunctionCallWithSolidityWrapper(ContractMethod method, List<Type> params) {
return ABI.encodeFunctionCallWithSolidityWrapper(method, params);
}
/**
* Encodes a function signature.
* @param method A ContractMethod instance.
* @return String
*/
public String encodeFunctionSignature(ContractMethod method) {
return ABI.encodeFunctionSignature(method);
}
/**
* Encodes a function signature.
* @param functionName A function name string.
* @return String
*/
public String encodeFunctionSignature(String functionName) {
return ABI.encodeFunctionSignature(functionName);
}
/**
* Encodes a data related contract deployment.
* @param constructor A ContractMethod instance that contains constructor info.
* @param byteCode A smart contract bytecode.
* @param constructorParams A list of parameter that need to execute Constructor
* @return String
* @throws ClassNotFoundException
* @throws NoSuchMethodException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public String encodeContractDeploy(ContractMethod constructor, String byteCode, List<Object> constructorParams) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
return ABI.encodeContractDeploy(constructor, byteCode, constructorParams);
}
/**
* Build a function name string.
* @param method A ContractMethod instance.
* @return String
*/
public String buildFunctionString(ContractMethod method) {
return ABI.buildFunctionString(method);
}
/**
* Encodes a event signature.
* @param event A ContractEvent instance.
* @return String
*/
public String encodeEventSignature(ContractEvent event) {
return ABI.encodeEventSignature(event);
}
/**
* Encodes a event signature.
* @param eventName A event signature.
* @return String
*/
public String encodeEventSignature(String eventName) {
return ABI.encodeEventSignature(eventName);
}
/**
* Build a event name string.
* @param event A ContractEvent instance
* @return String
*/
public String buildEventString(ContractEvent event) {
return ABI.buildEventString(event);
}
/**
* Encodes a parameter based on its type to its ABI representation.
* @param solidityType A solidity type to encode.
* @param value A value to encode
* @return String
* @throws ClassNotFoundException
* @throws NoSuchMethodException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public String encodeParameter(String solidityType, Object value) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
return ABI.encodeParameter(solidityType, value);
}
/**
* Encodes a parameters based on its type to its ABI representation.
* @param method A ContractMethod instance that contains to solidity type
* @param values A List of value to encode
* @return String
* @throws ClassNotFoundException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws InstantiationException
* @throws IllegalAccessException
*/
public String encodeParameters(ContractMethod method, List<Object> values) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
return ABI.encodeParameters(method, values);
}
/**
* Encodes a parameters based on its type to its ABI representation.
* @param solidityTypes A list of solidity type to encode
* @param values A List of value to encode
* @return String
* @throws ClassNotFoundException
* @throws NoSuchMethodException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public String encodeParameters(List<String> solidityTypes, List<Object> values) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
return ABI.encodeParameters(solidityTypes, values);
}
/**
* Encodes a parameter based on its type to its ABI representation.
* @param parameter A parameter that wrapped solidity type wrapper.
* @return String
*/
public String encodeParameter(Type parameter) {
return ABI.encodeParameter(parameter);
}
/**
* Encodes a parameter based on its type to its ABI representation.
* @param parameters A List of parameters that wrappped solidity type wrapper
* @return String
*/
public String encodeParameters(List<Type> parameters) {
return ABI.encodeParameters(parameters);
}
/**
* Decodes a ABI encoded parameter.
* @param solidityType A solidity type string.
* @param encoded The ABI byte code to decode
* @return Type
* @throws ClassNotFoundException
*/
public Type decodeParameter(String solidityType, String encoded) throws ClassNotFoundException {
return ABI.decodeParameter(solidityType, encoded);
}
/**
* Decodes a ABI encoded parameters.
* @param solidityTypeList A List of solidity type string.
* @param encoded The ABI byte code to decode
* @return List
* @throws ClassNotFoundException
*/
public List<Type> decodeParameters(List<String> solidityTypeList, String encoded) throws ClassNotFoundException {
return ABI.decodeParameters(solidityTypeList, encoded);
}
/**
* Decodes a ABI encoded parameters.
* @param method A ContractMethod instance.
* @param encoded The ABI byte code to decoed
* @return List
* @throws ClassNotFoundException
*/
public List<Type> decodeParameters(ContractMethod method, String encoded) throws ClassNotFoundException {
return ABI.decodeParameters(method, encoded);
}
/**
* Decodes a ABI-encoded log data and indexed topic data
* @param inputs A list of ContractIOType instance.
* @param data An ABI-encoded in the data field of a log
* @param topics A list of indexed parameter topics of the log.
* @return EventValues
* @throws ClassNotFoundException
*/
public EventValues decodeLog(List<ContractIOType> inputs, String data, List<String> topics) throws ClassNotFoundException {
return ABI.decodeLog(inputs, data, topics);
}
/**
* Decodes a function call data that composed of function selector and encoded input argument.
* <pre>Example :
* {@code
* String encodedData = "0x24ee0.....";
* String abi = "{\n" +
* " \"name\":\"myMethod\",\n" +
* " \"type\":\"function\",\n" +
* " \"inputs\":[\n" +
* " {\n" +
* " \"type\":\"uint256\",\n" +
* " \"name\":\"myNumber\"\n" +
* " },\n" +
* " {\n" +
* " \"type\":\"string\",\n" +
* " \"name\":\"mystring\"\n" +
* " }\n" +
* " ]\n" +
* "}";
*
* List<Type> params = caver.abi.decodeFunctionCall(abi, encoded);
* }
* </pre>
* @param functionAbi The abi json string of a function.
* @param encodedString The encode function call data string.
* @return List<Type>
* @throws ClassNotFoundException
*/
public List<Type> decodeFunctionCall(String functionAbi, String encodedString) throws ClassNotFoundException {
return ABI.decodeFunctionCall(functionAbi, encodedString);
}
/**
* Decodes a function call data that composed of function selector and encoded input argument.
* <pre>Example :
* {@code
* String contractABI = "...";
* Contract contract = caver.contract.create(contractABI);
* ContractMethod method = contract.getMethod("myFunction");
*
* List<Type> result = caver.abi.decodeFunctionCall(method, "0x{ABI-encoded string}");
* }</pre>
* @param method The ContractMethod instance to decode ABI-encoded string.
* @param encodedString The encode function call data string.
* @return List<Type>
* @throws ClassNotFoundException
*/
public List<Type> decodeFunctionCall(ContractMethod method, String encodedString) throws ClassNotFoundException {
return ABI.decodeFunctionCall(method, encodedString);
}
}
| 37.593443
| 245
| 0.677743
|
8b46c9d81e8e3610f92b28ca85d94bbe3de18f50
| 370
|
package br.com.zup.zupacademy.daniel.mercadolivre.produto.opiniaoProduto;
import br.com.zup.zupacademy.daniel.mercadolivre.produto.Produto;
import org.springframework.data.repository.CrudRepository;
import java.util.Set;
public interface OpiniaoProdutoRepository extends CrudRepository<OpiniaoProduto,Long> {
Set<OpiniaoProduto> findByProduto(Produto produto);
}
| 33.636364
| 87
| 0.840541
|
98325ecd9dc432008d24662d35b7a716efa56f20
| 4,382
|
/*
* SkipQueueTest.java
* JUnit based test
*
* Created on March 9, 2007, 11:45 PM
*/
package tamp.ch15.priority.priority;
import junit.framework.TestCase;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author mph
*/
public class SkipQueueTest extends TestCase {
static final int LOG_RANGE = 5;
static final int TEST_SIZE = 128;
static final int RANGE = 32;
private final static int THREADS = 8;
private final static int PER_THREAD = TEST_SIZE / THREADS;
static Random random = new Random();
SkipQueue<Integer> instance;
Thread[] thread = new Thread[THREADS];
Map<Integer, Integer> log = new ConcurrentHashMap<Integer, Integer>();
public SkipQueueTest(String testName) {
super(testName);
}
protected void setUp() throws Exception {
}
protected void tearDown() throws Exception {
}
/**
* Test of add method, of class priority.SkipQueue.
*/
public void testAdd() {
System.out.println("add");
Map<Integer, Integer> log = new HashMap<Integer, Integer>();
int key, value;
SkipQueue<Integer> instance = new SkipQueue<Integer>();
int range = (1 << LOG_RANGE);
for (int i = 0; i < TEST_SIZE; i++) {
key = random.nextInt(range);
value = random.nextInt();
log.put(value, key);
instance.add(value, key);
}
// validate
int oldKey = -1;
for (int i = 0; i < TEST_SIZE; i++) {
Integer v = instance.removeMin();
if (v != null) {
value = v;
key = log.get(value);
if (oldKey > key) {
fail("non-ascending keys!");
}
}
}
System.out.println("OK.");
}
/**
* Parallel adds, sequential removeMin
*
* @throws java.lang.Exception
*/
public void testParallelAdd() throws Exception {
System.out.println("testParallelAdd");
int key, value;
instance = new SkipQueue<Integer>();
for (int i = 0; i < THREADS; i++) {
thread[i] = new AddThread(i * PER_THREAD);
}
for (int i = 0; i < THREADS; i++) {
thread[i].start();
}
for (int i = 0; i < THREADS; i++) {
thread[i].join();
}
int oldKey = -1;
for (int i = 0; i < TEST_SIZE; i++) {
value = instance.removeMin();
key = log.get(value);
if (oldKey > key) {
fail("non-ascending keys!");
}
oldKey = key;
}
System.out.println("OK.");
}
/**
* Parallel adds, sequential removeMin
*
* @throws java.lang.Exception
*/
public void testParallelBoth() throws Exception {
System.out.println("testParallelBoth");
int key, value;
instance = new SkipQueue<Integer>();
for (int i = 0; i < THREADS; i++) {
thread[i] = new AddThread(i * PER_THREAD);
}
for (int i = 0; i < THREADS; i++) {
thread[i].start();
}
for (int i = 0; i < THREADS; i++) {
thread[i].join();
}
for (int i = 0; i < THREADS; i++) {
thread[i] = new RemoveMinThread();
}
for (int i = 0; i < THREADS; i++) {
thread[i].start();
}
for (int i = 0; i < THREADS; i++) {
thread[i].join();
}
System.out.println("OK.");
}
class AddThread extends Thread {
int base;
AddThread(int i) {
base = i;
}
public void run() {
for (int i = 0; i < PER_THREAD; i++) {
int x = base + i;
log.put(x, x);
instance.add(x, x);
}
}
}
class RemoveMinThread extends Thread {
int last;
RemoveMinThread() {
last = Integer.MIN_VALUE;
}
public void run() {
for (int i = 0; i < PER_THREAD; i++) {
int x = instance.removeMin();
if (x < last) {
fail("non-ascending priorities: " + last + ", " + x);
}
last = x;
}
}
}
}
| 25.928994
| 74
| 0.488361
|
0b2443071879552c29fd3037d40955eed5ecfec7
| 2,822
|
package de.fau.cs.mad.smile.android.encryption;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.security.KeyPairGeneratorSpec;
import android.util.Log;
import net.danlew.android.joda.JodaTimeAndroid;
import java.io.File;
import java.math.BigInteger;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.security.auth.x500.X500Principal;
public class App extends Application {
private static Context mContext;
@Override
public void onCreate() {
super.onCreate();
mContext = this;
JodaTimeAndroid.init(this);
generateKeyPair();
}
public static Context getContext() {
return mContext;
}
public static SharedPreferences getPreferences() {
final Context context = getContext().getApplicationContext();
final String preferenceFileName = context.getPackageName() + "_preferences";
SharedPreferences preferences = context.getSharedPreferences(preferenceFileName, Context.MODE_MULTI_PROCESS);
return preferences;
}
public static File getCertificateDirectory() {
Context appContext = App.getContext().getApplicationContext();
return appContext.getDir("smime-certificates", Context.MODE_PRIVATE);
}
private void generateKeyPair() {
/* When app starts first, create certificate for PasswordEncryption. */
String passwordEncryptionCertificateAlias = getResources().getString(R.string.smile_save_passphrases_certificate_alias);
try {
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
if (keyStore.containsAlias(passwordEncryptionCertificateAlias)) {
return;
}
Calendar start = new GregorianCalendar();
Calendar end = new GregorianCalendar();
end.add(Calendar.YEAR, 5);
final KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(mContext)
.setAlias(passwordEncryptionCertificateAlias)
.setSubject(new X500Principal("CN=SMile-crypto-Password-Encrypt"))
.setSerialNumber(BigInteger.ONE)
.setStartDate(start.getTime())
.setEndDate(end.getTime())
.build();
final KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
gen.initialize(spec);
gen.generateKeyPair();
} catch (Exception e) {
if(SMileCrypto.isDEBUG()) {
Log.e(SMileCrypto.LOG_TAG, "ERROR: " + e.getMessage());
}
e.printStackTrace();
}
}
}
| 34.414634
| 128
| 0.663714
|
f5c4421eff0bf64942e0b416963c611bf438254e
| 664
|
package application.persistence.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "link")
public class LinkEntity {
@Id
@Column
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String link;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public LinkEntity() {
super();
}
}
| 15.090909
| 52
| 0.72741
|
2e0ae51fe56338e8cc70fc3bf41812b1d762b740
| 733
|
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
public class FlyBoss extends Actor
{
public int movemult = 1;
public void act()
{
if(this.isAtEdge()){
movemult*=-1;
move();
}else{
move();
int rand = Greenfoot.getRandomNumber(50);
if (isTouching(Ship.class)){
getWorld().addObject(new GameOver(),300,400);
removeTouching(Ship.class);
}
else if(rand == 20){
getWorld().addObject(new Spittle(),getX(),getY()+100);
}
}
}
public void move(){
setLocation(getX()+(22*movemult), getY()+1);
}
}
| 28.192308
| 79
| 0.492497
|
629164527d4d5bc675789214b8345003b6e9e709
| 8,509
|
/**
* cc-dbp-dataset
*
* Copyright (c) 2017 IBM
*
* The author 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.ibm.research.ai.ki.kbp;
import it.unimi.dsi.fastutil.objects.*;
import java.io.*;
import java.util.*;
import com.ibm.reseach.ai.ki.nlp.*;
import com.ibm.reseach.ai.ki.nlp.types.*;
import com.ibm.research.ai.ki.formats.*;
import com.ibm.research.ai.ki.kbp.embeddings.*;
import com.ibm.research.ai.ki.nlp.parse.*;
import com.ibm.research.ai.ki.util.*;
/**
* useful to gather the vocab on a RelexMention tsv dataset with or without Spark.
* @author mrglass
*
*/
public class RelexVocab implements Serializable {
private static final long serialVersionUID = 1L;
Object2IntOpenHashMap<String> word2count = new Object2IntOpenHashMap<String>();
ObjectSet<String> types = new ObjectOpenHashSet<String>();
ObjectSet<String> relations = new ObjectOpenHashSet<String>();
public RelexVocab() {
//empty constructor
}
public RelexVocab(IRelexMention m, Annotator tokenizer) {
this.add(m, tokenizer);
}
public static String toDigitSequence(String d) {
return Lang.LPAD("", '#', d.length());
}
public void add(IRelexMention m, Annotator tokenizer) {
for (String t : m.getTypes())
types.add(t);
for (String r : m.getRelations())
relations.add(r);
for (String tok : m.getTokens(tokenizer)) {
word2count.addTo(normalized(tok), 1);
//if it is a number we also view it as a digit sequence of a certain length
if (Lang.isInteger(tok)) {
word2count.addTo(toDigitSequence(tok), 1);
}
}
}
//use this method to convert from RDD<Indices> -> RDDPair<String,Integer>
// then reduceByKey
// then filter while count is too high
// then we'll need to collect
public Object2IntMap.FastEntrySet<String> getWordCounts() {
return word2count.object2IntEntrySet();
}
//use this method to collect the set of types and relations
public RelexVocab mergeTypesAndRelations(RelexVocab other) {
this.types.addAll(other.types);
this.relations.addAll(other.relations);
return this;
}
//for single threaded case
public void merge(RelexVocab other, int vocabLimit) {
this.types.addAll(other.types);
this.relations.addAll(other.relations);
for (Object2IntMap.Entry<String> e : other.word2count.object2IntEntrySet()) {
this.word2count.addTo(e.getKey(), e.getIntValue());
}
//reduce to vocabLimit, increasing minCount until done
double minCount = 2;
while (this.word2count.size() > vocabLimit) {
this.removeBelowMinCount((int)Math.ceil(minCount));
minCount *= 1.5;
}
}
public void removeBelowMinCount(int minCount) {
List<String> toRemove = new ArrayList<>();
for (Object2IntMap.Entry<String> e : this.word2count.object2IntEntrySet()) {
if (e.getIntValue() < minCount) {
toRemove.add(e.getKey());
}
}
for (String w : toRemove)
this.word2count.removeInt(w);
}
/**
*
* @param minCount
* @param vocabLimit
* @return the minCount required to achieve both minCount and vocabLimit
*/
public int limitVocab(int removeBelowCount, int vocabLimit) {
double minCount = removeBelowCount / 1.5;
int nextRemoveBelow = removeBelowCount;
while (this.word2count.size() > vocabLimit) {
minCount *= 1.5;
nextRemoveBelow = (int)Math.ceil(minCount);
this.removeBelowMinCount(nextRemoveBelow);
}
return nextRemoveBelow;
}
public int vocabSize() {
return this.word2count.size();
}
public Collection<String> getTypes() {
return types;
}
public Collection<String> getRelations() {
return relations;
}
//CONSIDER put the normalization after the PairRDD, just before the reducebykey
public static String normalized(String tstr) {
return tstr.toLowerCase().replaceAll("\\s+", " ");
}
//this will still be done in a single process, even on spark.
//we'll just collect the vocab set
public static void writeVocab(File initialEmbeddings, File finalEmbeddings, Collection<String> thevocab, String[] specialWords) {
EmbeddingFormat ef = new EmbeddingFormat(initialEmbeddings);
for (int i = 0; i < ef.items.length; ++i)
ef.items[i] = normalized(ef.items[i]);
Map<String,Integer> efwordNdx = ef.getItem2Ndx();
int vlen = ef.itemSize;
Random rand = new Random();
String[] words = new String[thevocab.size()+specialWords.length];
float[][] vectors = new float[words.length][];
int wndx = 0;
for (wndx = 0; wndx < specialWords.length; ++wndx) {
words[wndx] = specialWords[wndx];
vectors[wndx] = DenseVectors.sphericallyRandomFloatVector(vlen, rand);
}
//report stuff about the vocab
int oovWords = 0;
RandomUtil.Sample<String> oovs = new RandomUtil.Sample<>(20);
for (String v : thevocab) {
Integer ndx = efwordNdx.get(v);
if (ndx == null) {
++oovWords;
oovs.maybeSave(v);
}
words[wndx] = v;
vectors[wndx] = ndx != null ? ef.vectors[ndx] : DenseVectors.sphericallyRandomFloatVector(vlen, rand);
++wndx;
}
System.out.println("OOV "+oovWords+" out of "+thevocab.size());
System.out.println("OOV Sample:\n "+Lang.stringList(oovs, "\n "));
ef = new EmbeddingFormat();
ef.shapes = new int[1][1];
ef.itemSize = vectors[0].length;
ef.shapes[0][0] = ef.itemSize;
ef.hyperparameters = new Properties();
ef.name = ef.hyperparameters.getProperty("name", "Relex Vectors");
ef.items = words;
ef.vectors = vectors;
ef.write(finalEmbeddings);
}
/**
* puts the collection into a sorted array
* @param strs
* @return
*/
public static String[] toArray(Collection<String> strs) {
List<String> strList = new ArrayList<>(strs);
Collections.sort(strList);
return strList.toArray(new String[strList.size()]);
}
/**
* Loads the vocabulary of the EmbeddingFormat file.
* @param f
* @return
*/
public static Map<String,Integer> getWordNdx(File f) {
return new EmbeddingFormat(f, true).getItem2Ndx();
}
/**
* Load the map from entity-id to type vector, used when we have vector valued types rather than discrete types with embeddings.
* @param typeVector
* @return
*/
public static Map<String,float[]> readTypeVectors(File typeVector) {
Map<String,float[]> id2TypeVector = new HashMap<>();
for (File f : new FileUtil.FileIterable(typeVector))
for (String[] parts : new SimpleTsvIterable(f)) {
if (parts.length != 2) {
throw new Error("bad line in "+f.getAbsolutePath()+": "+Lang.stringList(parts, "\t"));
}
id2TypeVector.put(parts[0], DenseVectors.toFloatArray(DenseVectors.fromString(parts[1])));
}
return id2TypeVector;
}
/**
* Example Args:
/baseDir/simpleFormatTsvDir
/baseDir/fromWord2VecConverter/wordVectors.ef
/baseDir/tensorDir
* @param args
*/
public static void main(String[] args) {
String tsvDir = args[0];
String initialEmbeddings = args[1];
String outDir = args[2];
//TODO: get from RelexConfig
int vocabLimit = 100000;
int minCount = 2;
Pipeline tokenize = new Pipeline(new ClearNLPTokenize());
tokenize.initialize(new Properties());
RelexVocab total = new RelexVocab();
for (File f : new FileUtil.FileIterable(new File(tsvDir))) {
for (RelexMention m : RelexMentionReader.getReader(f, RelexMention.class)) {
RelexVocab v = new RelexVocab(m, tokenize);
total.merge(v, vocabLimit);
}
}
total.removeBelowMinCount(minCount);
RelexVocab.writeVocab(
new File(initialEmbeddings),
new File(outDir, RelexDatasetFiles.wordVectors),
total.word2count.keySet(),
new String[0]);
RelexConfig config = new RelexConfig();
config.entityTypes = toArray(total.getTypes());
config.relationTypes = toArray(total.getRelations());
config.vocabMinCount = minCount;
config.vocabLimit = total.word2count.size();
FileUtil.writeFileAsString(new File(outDir, "relexConfig.properties"), config.toString());
}
}
| 31.168498
| 130
| 0.687507
|
292c4f2d782f23d945bd4c30e5686396251868a8
| 1,768
|
/*
* Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.test.internal.io;
import java.io.File;
import java.io.IOException;
import org.testng.annotations.Test;
import com.orientechnologies.common.test.SpeedTestMonoThread;
import com.orientechnologies.orient.core.storage.fs.OFileMMap;
@Test(enabled = false)
public class OMMapOpenCloseTest extends SpeedTestMonoThread {
protected static final String FILE_NAME = "C:/temp/orient-test.file";
private static final int NUMS = 1000000;
private static final int START_SIZE = 500000000;
private OFileMMap file;
public OMMapOpenCloseTest() {
super(NUMS);
}
@Override
public void init() throws IOException {
System.out.println("Testing opening and closing of a " + START_SIZE / 1000000 + "MB files for " + NUMS + " times...");
file = new OFileMMap(FILE_NAME, "rw");
// DELETE THE TEST FILE EVERY TIME
File f = new File(FILE_NAME);
if (!f.exists())
file.create(START_SIZE);
else
file.open();
}
@Override
public void cycle() throws IOException {
// file.tryUnmap();
// file.tryMap();
}
}
| 29.466667
| 121
| 0.70362
|
b9b6f52e1aed50912107529a54b74fe1a9009d41
| 478
|
package com.zengs.cloud.eureka;
import org.springframework.boot.SpringApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
import org.springframework.context.annotation.ComponentScan;
@EnableEurekaServer
@SpringCloudApplication
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class,args);
}
}
| 28.117647
| 74
| 0.820084
|
01430566e3c9ae9b377e24ac26801ba2b2b4e8a4
| 6,813
|
/*
* 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.river.test.spec.jeri.basicinvocationhandler;
import org.apache.river.qa.harness.QATestEnvironment;
import org.apache.river.qa.harness.QAConfig;
import org.apache.river.qa.harness.Test;
import net.jini.jeri.BasicInvocationHandler;
import net.jini.jeri.ObjectEndpoint;
import org.apache.river.test.spec.jeri.util.FakeObjectEndpoint;
import org.apache.river.test.spec.jeri.util.FakeMethodConstraints;
import java.util.logging.Level;
/**
* <pre>
* Purpose
* This test verifies the behavior of the BasicInvocationHandler
* during normal and exceptional constructor calls.
*
* This test verifies the behavior of the
* BasicInvocationHandler.getObjectEndpoint,
* BasicInvocationHandler.getClientConstraints, and
* BasicInvocationHandler.getServerConstraints methods.
*
* Test Cases
* This test contains these test cases:
* 1) new BasicInvocationHandler((BasicInvocationHandler)null,*)
* 2) new BasicInvocationHandler((ObjectEndpoint)null,*)
* 3) new BasicInvocationHandler(BasicInvocationHandler,MethodConstraints)
* 4) new BasicInvocationHandler(BasicInvocationHandler,null)
* 5) new BasicInvocationHandler(ObjectEndpoint,MethodConstraints)
* 6) new BasicInvocationHandler(ObjectEndpoint,null)
*
* Infrastructure
* This test requires the following infrastructure:
* 1) FakeObjectEndpoint
* -newCall method throws AssertionError (should never be called)
* -executeCall method throws AssertionError (should never be called)
* 2) FakeMethodConstraints
* -getConstraints method returns InvocationConstraints created
* from InvocationConstraint[] passed to constructor or, if null,
* InvocationConstraints.EMPTY
* -possibleConstraints method returns an iterator over
* return value of getConstraints
*
* Actions
* The test performs the following steps:
* 1) construct a BasicInvocationHandler, passing in null as the
* BasicInvocationHandler
* 2) verify NullPointerException is thrown
* 3) construct a BasicInvocationHandler, passing in null as the
* ObjectEndpoint
* 4) verify NullPointerException is thrown
* 5) construct a BasicInvocationHandler, passing in an instance of
* a FakeObjectEndpoint and FakeMethodConstraints
* 6) verify the get method return the appropriate values
* 7) construct a BasicInvocationHandler, passing in an instance of
* a FakeObjectEndpoint and null MethodConstraints
* 8) verify the get method return the appropriate values
* 9) construct a BasicInvocationHandler, passing in the instance of
* a BasicInvocationHandler created above and FakeMethodConstraints
* 10) verify the get method return the appropriate values
* 11) construct a BasicInvocationHandler, passing in the instance of
* a BasicInvocationHandler created above and null MethodConstraints
* 12) verify the get method return the appropriate values
* </pre>
*/
public class ConstructorAccessorTest extends QATestEnvironment implements Test {
// inherit javadoc
public Test construct(QAConfig sysConfig) throws Exception {
return this;
}
// inherit javadoc
public void run() throws Exception {
BasicInvocationHandler handler;
BasicInvocationHandler handler2;
FakeMethodConstraints clientConstraints =
new FakeMethodConstraints(null);
FakeMethodConstraints serverConstraints =
new FakeMethodConstraints(null);
FakeObjectEndpoint oe = new FakeObjectEndpoint();
logger.log(Level.FINE,"=================================");
logger.log(Level.FINE,"test case 1: null constructor args");
logger.log(Level.FINE,"");
try {
handler = new BasicInvocationHandler(
(BasicInvocationHandler)null,clientConstraints);
assertion(false);
} catch (NullPointerException ignore) {
}
try {
handler = new BasicInvocationHandler(
(ObjectEndpoint)null,serverConstraints);
assertion(false);
} catch (NullPointerException ignore) {
}
logger.log(Level.FINE,"=================================");
logger.log(Level.FINE,"test case 2: "
+ "accessor methods returns constructor args");
logger.log(Level.FINE,"");
handler = new BasicInvocationHandler(oe,serverConstraints);
assertion(handler.getObjectEndpoint() == oe);
assertion(handler.getClientConstraints() == null);
assertion(handler.getServerConstraints() == serverConstraints);
handler2 = new BasicInvocationHandler(handler,clientConstraints);
assertion(handler2.getObjectEndpoint() == oe);
assertion(handler2.getClientConstraints() == clientConstraints);
assertion(handler2.getServerConstraints() == serverConstraints);
handler2 = new BasicInvocationHandler(handler,null);
assertion(handler2.getObjectEndpoint() == oe);
assertion(handler2.getClientConstraints() == null);
assertion(handler2.getServerConstraints() == serverConstraints);
handler = new BasicInvocationHandler(oe,null);
assertion(handler.getObjectEndpoint() == oe);
assertion(handler.getClientConstraints() == null);
assertion(handler.getServerConstraints() == null);
handler2 = new BasicInvocationHandler(handler,clientConstraints);
assertion(handler2.getObjectEndpoint() == oe);
assertion(handler2.getClientConstraints() == clientConstraints);
assertion(handler2.getServerConstraints() == null);
handler2 = new BasicInvocationHandler(handler,null);
assertion(handler2.getObjectEndpoint() == oe);
assertion(handler2.getClientConstraints() == null);
assertion(handler2.getServerConstraints() == null);
}
// inherit javadoc
public void tearDown() {
}
}
| 41.797546
| 80
| 0.705269
|
735390c176f42ba8693c5ef5dcb8fa14637cd61f
| 1,110
|
package za.co.wstoop.jatalog;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Basic unit tests.
*/
public class JatalogTest {
@Test
public void testEquals() {
/* Truth be told the only reason I need Jatalog.equals() to work
* is so that I can test Jatalog.toString() */
try {
Jatalog thisJatalog = TestUtils.createDatabase();
Jatalog thatJatalog = TestUtils.createDatabase();
assertTrue(thisJatalog != thatJatalog);
assertTrue(thisJatalog.equals(thatJatalog));
thatJatalog.fact("foo", "bar");
assertFalse(thisJatalog.equals(thatJatalog));
} catch (DatalogException e) {
e.printStackTrace();
}
}
@Test
public void testToString() {
try {
Jatalog thisJatalog = TestUtils.createDatabase();
String string = thisJatalog.toString();
Jatalog thatJatalog = new Jatalog();
thatJatalog.executeAll(string);
assertTrue(thisJatalog != thatJatalog);
assertTrue(thisJatalog.equals(thatJatalog));
} catch (DatalogException e) {
e.printStackTrace();
}
}
}
| 22.2
| 66
| 0.694595
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.