repo_name
stringlengths 7
70
| file_path
stringlengths 9
215
| context
list | import_statement
stringlengths 47
10.3k
| token_num
int64 643
100k
| cropped_code
stringlengths 62
180k
| all_code
stringlengths 62
224k
| next_line
stringlengths 9
1.07k
| gold_snippet_index
int64 0
117
| created_at
stringlengths 25
25
| level
stringclasses 9
values |
---|---|---|---|---|---|---|---|---|---|---|
hmcts/opal-fines-service | src/main/java/uk/gov/hmcts/opal/service/PartyServiceInterface.java | [
{
"identifier": "AccountSearchDto",
"path": "src/main/java/uk/gov/hmcts/opal/dto/AccountSearchDto.java",
"snippet": "@Data\n@Builder\npublic class AccountSearchDto implements ToJsonString {\n /** The court (CT) or MET (metropolitan area). */\n private String court;\n /** Defendant Surname, Company Name or A/C number. */\n private String surname;\n /** Can be either Defendant, Minor Creditor or Company. */\n private String searchType;\n /** Defendant Forenames. */\n private String forename;\n /** Defendant Initials. */\n private String initials;\n /** Defendant Date of Birth. */\n private DateDto dateOfBirth;\n /** Defendant Address, typically just first line. */\n private String addressLineOne;\n /** National Insurance Number. */\n private String niNumber;\n /** Prosecutor Case Reference. */\n private String pcr;\n /** Major Creditor account selection. */\n private String majorCreditor;\n /** Unsure. */\n private String tillNumber;\n}"
},
{
"identifier": "PartyDto",
"path": "src/main/java/uk/gov/hmcts/opal/dto/PartyDto.java",
"snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\n@Jacksonized\npublic class PartyDto implements ToJsonString {\n private Long partyId;\n private boolean organisation;\n private String organisationName;\n private String surname;\n private String forenames;\n private String initials;\n private String title;\n private String addressLine1;\n private String addressLine2;\n private String addressLine3;\n private String addressLine4;\n private String addressLine5;\n private String postcode;\n private String accountType;\n private LocalDate dateOfBirth;\n private Short age;\n private String niNumber;\n private LocalDateTime lastChangedDate;\n private String accountNo;\n private BigDecimal amountImposed;\n}"
},
{
"identifier": "PartyEntity",
"path": "src/main/java/uk/gov/hmcts/opal/entity/PartyEntity.java",
"snippet": "@Entity\n@Data\n@Table(name = \"parties\")\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\npublic class PartyEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = \"party_id_seq\")\n @SequenceGenerator(name = \"party_id_seq\", sequenceName = \"party_id_seq\", allocationSize = 1)\n @Column(name = \"party_id\")\n private Long partyId;\n\n @Column(name = \"organisation\")\n private boolean organisation;\n\n @Column(name = \"organisation_name\", length = 80)\n private String organisationName;\n\n @Column(name = \"surname\", length = 50)\n private String surname;\n\n @Column(name = \"forenames\", length = 50)\n private String forenames;\n\n @Column(name = \"initials\", length = 2)\n private String initials;\n\n @Column(name = \"title\", length = 20)\n private String title;\n\n @Column(name = \"address_line_1\", length = 35)\n private String addressLine1;\n\n @Column(name = \"address_line_2\", length = 35)\n private String addressLine2;\n\n @Column(name = \"address_line_3\", length = 35)\n private String addressLine3;\n\n @Column(name = \"address_line_4\", length = 35)\n private String addressLine4;\n\n @Column(name = \"address_line_5\", length = 35)\n private String addressLine5;\n\n @Column(name = \"postcode\", length = 10)\n private String postcode;\n\n @Column(name = \"account_type\", length = 20)\n private String accountType;\n\n @Column(name = \"birth_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate dateOfBirth;\n\n @Column(name = \"age\")\n private Short age;\n\n @Column(name = \"national_insurance_number\", length = 20)\n private String niNumber;\n\n @Column(name = \"last_changed_date\")\n @Temporal(TemporalType.TIMESTAMP)\n private LocalDateTime lastChangedDate;\n\n @OneToMany(mappedBy = \"party\", cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n private List<DefendantAccountPartiesEntity> defendantAccounts;\n}"
},
{
"identifier": "PartySummary",
"path": "src/main/java/uk/gov/hmcts/opal/entity/PartySummary.java",
"snippet": "public interface PartySummary {\n\n String getTitle();\n\n String getForenames();\n\n String getSurname();\n\n /**\n * The name of the defendant, being an aggregation of surname, firstnames and title.\n */\n default String getName() {\n return getTitle().concat(\" \").concat(getForenames()).concat(\" \").concat(getSurname());\n }\n\n /**\n * The date of birth of the defendant.\n */\n LocalDate getDateOfBirth();\n\n /**\n * First line of the defendant's address.\n */\n String getAddressLine1();\n\n Set<DefendantAccountLink> getDefendantAccounts();\n\n interface DefendantAccountLink {\n DefendantAccountPartySummary getDefendantAccount();\n }\n\n interface DefendantAccountPartySummary {\n\n /**\n * The defendant account number.\n */\n String getAccountNumber();\n\n /**\n * The balance on the defendant account.\n */\n BigDecimal getAccountBalance();\n\n /**\n * The Court (traditionally abbreviated to CT) 'Accounting Division' or 'Metropolitan Area' (MET).\n */\n String getImposingCourtId();\n\n }\n}"
}
] | import uk.gov.hmcts.opal.dto.AccountSearchDto;
import uk.gov.hmcts.opal.dto.PartyDto;
import uk.gov.hmcts.opal.entity.PartyEntity;
import uk.gov.hmcts.opal.entity.PartySummary;
import java.util.List; | 1,426 | package uk.gov.hmcts.opal.service;
public interface PartyServiceInterface {
PartyDto getParty(long partyId);
PartyDto saveParty(PartyDto party);
| package uk.gov.hmcts.opal.service;
public interface PartyServiceInterface {
PartyDto getParty(long partyId);
PartyDto saveParty(PartyDto party);
| public List<PartySummary> searchForParty(AccountSearchDto accountSearchDto); | 0 | 2023-10-23 14:12:11+00:00 | 2k |
IronRiders/MockSeason23-24 | src/main/java/org/ironriders/subsystems/VisionSubsystem.java | [
{
"identifier": "Game",
"path": "src/main/java/org/ironriders/constants/Game.java",
"snippet": "public class Game {\n public static class Field {\n public enum AprilTagLocation {\n EXCHANGE(1, 2),\n PORTAL(3, 4, 5, 6),\n SWITCH(7, 8, 9, 10, 11, 12, 13, 14);\n\n final int[] ids;\n\n AprilTagLocation(int... ids) {\n this.ids = ids;\n }\n\n public boolean has(int id) {\n return Arrays.stream(ids).anyMatch(i -> i == id);\n }\n\n public int[] getIds() {\n return ids;\n }\n }\n\n public static class Dimensions {\n /**\n * In FT.\n */\n public static final int FIELD_LENGTH = 54;\n /**\n * In FT.\n */\n public static final int FIELD_WIDTH = 27;\n }\n\n public static class Switch {\n /**\n * In IN.\n */\n public static final double SWITCH_WALL_HEIGHT = 18.75;\n /**\n * In FT.\n */\n public static final int SWITCH_PLATE_LENGTH = 3;\n /**\n * In FT.\n */\n public static final int SWITCH_PLATE_WIDTH = 4;\n /**\n * In IN.\n */\n public static final double SWITCH_FENCE_TO_PLATE_GAP = 1.5;\n }\n\n public static class Portal {\n /**\n * In IN, from the ground to the lowest point.\n */\n public static final int PORTAL_HEIGHT_OFF_GROUND = 20;\n /**\n * In IN.\n */\n public static final int PORTAL_HEIGHT = 14;\n /**\n * In IN.\n */\n public static final int PORTAL_WIDTH = 14;\n }\n\n public static class Exchange {\n /**\n * In IN.\n */\n public static final double EXCHANGE_HEIGHT = 16.25;\n /**\n * In IN.\n */\n public static final double EXCHANGE_WIDTH = 21;\n /**\n * In IN.\n */\n public static final double EXCHANGE_RAMP_HEIGHT = 1.75;\n /**\n * In IN.\n */\n public static final double EXCHANGE_RAMP_LENGTH = 6.5;\n /**\n * In IN.\n */\n public static final int EXCHANGE_RAMP_WIDTH = -1;\n }\n }\n\n public static class GamePieces {\n /**\n * In pounds.\n */\n public static final double POWER_CUBE_WEIGHT = 3.25;\n\n public static class Dimensions {\n /**\n * In IN.\n */\n public static final int POWER_CUBE_HEIGHT = 11;\n /**\n * In IN.\n */\n public static final int POWER_CUBE_LENGTH = 13;\n /**\n * In IN.\n */\n public static final int POWER_CUBE_WIDTH = 13;\n }\n }\n}"
},
{
"identifier": "LIMELIGHT_POSITION",
"path": "src/main/java/org/ironriders/constants/Robot.java",
"snippet": "public static final Transform3d LIMELIGHT_POSITION =\n new Transform3d(Units.inchesToMeters(15.5), 0, Units.inchesToMeters(13.5), new Rotation3d());"
},
{
"identifier": "Vision",
"path": "src/main/java/org/ironriders/constants/Vision.java",
"snippet": "public class Vision {\n public static final String CAMERA = \"LIMELIGHT\";\n public static final String APRIL_TAG_FIELD_LAYOUT_LOCATION = \"/apriltags/2018-powerup.json\";\n public static final double WAIT_TIME = 0.3;\n\n public enum VisionPipeline {\n APRIL_TAGS(0),\n CUBES(1);\n\n final int index;\n\n VisionPipeline(int index) {\n this.index = index;\n }\n\n public static VisionPipeline fromIndex(int index) {\n for (VisionPipeline pipeline : VisionPipeline.values()) {\n if (pipeline.index == index) {\n return pipeline;\n }\n }\n return null;\n }\n\n public int getIndex() {\n return index;\n }\n }\n}"
}
] | import edu.wpi.first.apriltag.AprilTagFieldLayout;
import edu.wpi.first.math.geometry.Pose3d;
import edu.wpi.first.wpilibj.Filesystem;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import org.ironriders.constants.Game;
import org.photonvision.EstimatedRobotPose;
import org.photonvision.PhotonCamera;
import org.photonvision.PhotonPoseEstimator;
import org.photonvision.common.hardware.VisionLEDMode;
import org.photonvision.targeting.PhotonPipelineResult;
import java.io.IOException;
import java.util.Optional;
import static org.ironriders.constants.Robot.LIMELIGHT_POSITION;
import static org.ironriders.constants.Vision.*;
import static org.ironriders.constants.Vision.VisionPipeline.APRIL_TAGS;
import static org.photonvision.PhotonPoseEstimator.PoseStrategy.LOWEST_AMBIGUITY; | 1,343 | package org.ironriders.subsystems;
public class VisionSubsystem extends SubsystemBase {
private final PhotonCamera camera = new PhotonCamera(CAMERA);
private final PhotonPoseEstimator estimator;
private final AprilTagFieldLayout tagLayout;
private boolean useVisionForEstimation = false;
public VisionSubsystem() {
try {
tagLayout = new AprilTagFieldLayout(
Filesystem.getDeployDirectory() + APRIL_TAG_FIELD_LAYOUT_LOCATION
);
} catch (IOException e) {
throw new RuntimeException(e);
}
| package org.ironriders.subsystems;
public class VisionSubsystem extends SubsystemBase {
private final PhotonCamera camera = new PhotonCamera(CAMERA);
private final PhotonPoseEstimator estimator;
private final AprilTagFieldLayout tagLayout;
private boolean useVisionForEstimation = false;
public VisionSubsystem() {
try {
tagLayout = new AprilTagFieldLayout(
Filesystem.getDeployDirectory() + APRIL_TAG_FIELD_LAYOUT_LOCATION
);
} catch (IOException e) {
throw new RuntimeException(e);
}
| estimator = new PhotonPoseEstimator(tagLayout, LOWEST_AMBIGUITY, camera, LIMELIGHT_POSITION); | 1 | 2023-10-23 20:31:46+00:00 | 2k |
ChrisGenti/DiscordTickets | src/main/java/com/github/chrisgenti/discordtickets/tools/utils/files/FileUtil.java | [
{
"identifier": "DiscordDataDeserializer",
"path": "src/main/java/com/github/chrisgenti/discordtickets/io/DiscordDataDeserializer.java",
"snippet": "public class DiscordDataDeserializer extends StdDeserializer<DiscordData> {\n public DiscordDataDeserializer() {\n super(DiscordData.class);\n }\n\n @Override\n public DiscordData deserialize(JsonParser parser, DeserializationContext deserializationContext) throws IOException {\n ObjectCodec codec = parser.getCodec();\n JsonNode node = codec.readTree(parser);\n\n JsonNode discordNode = node.get(\"discord\");\n String discordToken = discordNode.get(\"token\").asText(\"\");\n\n JsonNode mongoNode = node.get(\"mongo\");\n String mongoHostname = mongoNode.get(\"hostname\").asText(\"\");\n String mongoUsername = mongoNode.get(\"username\").asText(\"\");\n String mongoPassword = mongoNode.get(\"password\").asText(\"\");\n\n return new DiscordData(new DiscordData.Discord(discordToken), new DiscordData.Mongo(mongoHostname, mongoUsername, mongoPassword));\n }\n}"
},
{
"identifier": "DiscordDataSerializer",
"path": "src/main/java/com/github/chrisgenti/discordtickets/io/DiscordDataSerializer.java",
"snippet": "public class DiscordDataSerializer extends StdSerializer<DiscordData> {\n public DiscordDataSerializer() {\n super(DiscordData.class);\n }\n\n @Override\n public void serialize(DiscordData var, JsonGenerator generator, SerializerProvider serializerProvider) throws IOException {\n DiscordData.Discord discordData = var.discord(); DiscordData.Mongo mongoData = var.mongo();\n\n generator.writeStartObject();\n generator.writeObjectFieldStart(\"discord\");\n generator.writeStringField(\"token\", \"\");\n generator.writeEndObject();\n\n generator.writeObjectFieldStart(\"mongo\");\n generator.writeStringField(\"hostname\", \"\");\n generator.writeStringField(\"username\", \"\");\n generator.writeStringField(\"password\", \"\");\n\n generator.writeEndObject();\n }\n}"
},
{
"identifier": "ObjectTriple",
"path": "src/main/java/com/github/chrisgenti/discordtickets/tools/ObjectTriple.java",
"snippet": "public class ObjectTriple<LEFT, MID, RIGHT> {\n private LEFT left;\n private MID mid;\n private RIGHT right;\n\n private ObjectTriple(@Nullable LEFT left, @Nullable MID mid, @Nullable RIGHT right) {\n this.left = left; this.mid = mid; this.right = right;\n }\n\n @SuppressWarnings(\"InstantiationOfUtilityClass\")\n public static <LEFT, MID, RIGHT> ObjectTriple<LEFT, MID, RIGHT> of(\n @Nullable LEFT left, @Nullable MID mid, @Nullable RIGHT right\n ) {\n return new ObjectTriple<>(left, mid, right);\n }\n\n public LEFT left() {\n return left;\n }\n\n public MID mid() {\n return mid;\n }\n\n public RIGHT right() {\n return right;\n }\n}"
},
{
"identifier": "FileResult",
"path": "src/main/java/com/github/chrisgenti/discordtickets/tools/enums/files/FileResult.java",
"snippet": "public enum FileResult {\n EXISTING(\"loaded from existing file\"),\n CREATED(\"missing file, created a new one\"),\n MALFORMED(\"\");\n\n private final String reason;\n FileResult(String reason) {\n this.reason = reason;\n }\n\n public String reason() {\n return reason;\n }\n}"
}
] | import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.github.chrisgenti.discordtickets.DiscordData;
import com.github.chrisgenti.discordtickets.io.DiscordDataDeserializer;
import com.github.chrisgenti.discordtickets.io.DiscordDataSerializer;
import com.github.chrisgenti.discordtickets.tools.ObjectTriple;
import com.github.chrisgenti.discordtickets.tools.enums.files.FileResult;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path; | 991 | package com.github.chrisgenti.discordtickets.tools.utils.files;
public class FileUtil {
private FileUtil() {}
public static @NotNull ObjectTriple<FileResult, DiscordData, Exception> loadData(@NotNull Path path) {
File var = path.toFile();
ObjectMapper mapper = new ObjectMapper(); | package com.github.chrisgenti.discordtickets.tools.utils.files;
public class FileUtil {
private FileUtil() {}
public static @NotNull ObjectTriple<FileResult, DiscordData, Exception> loadData(@NotNull Path path) {
File var = path.toFile();
ObjectMapper mapper = new ObjectMapper(); | SimpleModule module = new SimpleModule("DiscordDataSerializer"); | 1 | 2023-10-23 13:24:05+00:00 | 2k |
moonstoneid/aero-cast | apps/feed-publisher/src/main/java/com/moonstoneid/aerocast/publisher/service/ArticleService.java | [
{
"identifier": "Article",
"path": "apps/feed-publisher/src/main/java/com/moonstoneid/aerocast/publisher/model/Article.java",
"snippet": "@Data\n@Entity\n@Table(name = \"article\")\npublic class Article {\n\n @Id\n @GeneratedValue(strategy = GenerationType.SEQUENCE)\n @Column(name = \"id\", nullable = false)\n private Integer id;\n\n @Column(name = \"title\", length = 200, nullable = false)\n private String title;\n\n @Column(name = \"summary\", length = 2000, nullable = false)\n private String summary;\n\n @Column(name = \"content\", length = 10000, nullable = false)\n private String content;\n\n @Column(name = \"date\", nullable = false)\n private OffsetDateTime date;\n\n}"
},
{
"identifier": "AppProperties",
"path": "apps/feed-publisher/src/main/java/com/moonstoneid/aerocast/publisher/config/AppProperties.java",
"snippet": "@ConfigurationProperties(prefix = \"app\")\n@Data\npublic class AppProperties {\n private String baseUrl;\n private String title;\n private String subTitle;\n private String iconPath;\n}"
},
{
"identifier": "EthPublisherAdapter",
"path": "apps/feed-publisher/src/main/java/com/moonstoneid/aerocast/publisher/eth/EthPublisherAdapter.java",
"snippet": "@Service\npublic class EthPublisherAdapter extends BaseEthAdapter {\n\n private final Credentials pubCredentials;\n private final String pubContractAddr;\n\n public EthPublisherAdapter(Web3j web3j, EthPublisherProperties ethPublisherProperties) {\n super(web3j);\n this.pubCredentials = Credentials.create(ethPublisherProperties.getPrivateKey());\n this.pubContractAddr = ethPublisherProperties.getContractAddress();\n }\n\n public void publish(String link) {\n FeedPublisher contract = createPublisherContract(pubContractAddr, pubCredentials);\n try {\n contract.publish(link).sendAsync().get();\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n}"
},
{
"identifier": "ArticleRepo",
"path": "apps/feed-publisher/src/main/java/com/moonstoneid/aerocast/publisher/repo/ArticleRepo.java",
"snippet": "@Repository\npublic interface ArticleRepo extends JpaRepository<Article, String> {\n\n}"
}
] | import java.util.List;
import com.moonstoneid.aerocast.publisher.model.Article;
import com.moonstoneid.aerocast.publisher.config.AppProperties;
import com.moonstoneid.aerocast.publisher.eth.EthPublisherAdapter;
import com.moonstoneid.aerocast.publisher.repo.ArticleRepo;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert; | 651 | package com.moonstoneid.aerocast.publisher.service;
@Service
public class ArticleService {
private final String baseUrl;
private final ArticleRepo articleRepo;
private final EthPublisherAdapter ethPublisherAdapter;
| package com.moonstoneid.aerocast.publisher.service;
@Service
public class ArticleService {
private final String baseUrl;
private final ArticleRepo articleRepo;
private final EthPublisherAdapter ethPublisherAdapter;
| public ArticleService(AppProperties appProperties, ArticleRepo articleRepo, | 1 | 2023-10-23 20:33:07+00:00 | 2k |
UnityFoundation-io/Libre311 | app/src/test/java/app/util/MockStorageService.java | [
{
"identifier": "PhotoUploadDTO",
"path": "app/src/main/java/app/dto/storage/PhotoUploadDTO.java",
"snippet": "@Introspected\npublic class PhotoUploadDTO {\n\n @NotBlank\n private String image;\n\n @NotBlank\n @JsonProperty(\"g_recaptcha_response\")\n private String gRecaptchaResponse;\n\n\n public String getgRecaptchaResponse() {\n return gRecaptchaResponse;\n }\n\n public void setgRecaptchaResponse(String gRecaptchaResponse) {\n this.gRecaptchaResponse = gRecaptchaResponse;\n }\n\n public String getImage() {\n return image;\n }\n\n public void setImage(String image) {\n this.image = image;\n }\n}"
},
{
"identifier": "StorageService",
"path": "app/src/main/java/app/service/storage/StorageService.java",
"snippet": "@Singleton\npublic class StorageService {\n private static final Logger LOG = LoggerFactory.getLogger(StorageService.class);\n private final ObjectStorageOperations<?, ?, ?> objectStorage;\n private final ReCaptchaService reCaptchaService;\n private final GoogleImageSafeSearchService googleImageClassificationService;\n private final StorageUrlUtil storageUrlUtil;\n\n public StorageService(ObjectStorageOperations<?, ?, ?> objectStorage, ReCaptchaService reCaptchaService, GoogleImageSafeSearchService googleImageClassificationService, StorageUrlUtil storageUrlUtil) {\n this.objectStorage = objectStorage;\n this.reCaptchaService = reCaptchaService;\n this.googleImageClassificationService = googleImageClassificationService;\n this.storageUrlUtil = storageUrlUtil;\n }\n\n public StorageService() {\n this.storageUrlUtil = null;\n this.objectStorage = null;\n this.reCaptchaService = null;\n this.googleImageClassificationService = null;\n }\n\n public String upload(@Valid PhotoUploadDTO photoUploadDTO) {\n if (photoUploadDTO.getgRecaptchaResponse() == null || !reCaptchaService.verifyReCaptcha(photoUploadDTO.getgRecaptchaResponse())) {\n LOG.error(\"ReCaptcha verification failed.\");\n return null;\n }\n\n String base64Image = photoUploadDTO.getImage();\n String dataUri = base64Image.split(\",\")[0];\n MediaType mediaType = MediaType.of(dataUri.substring(dataUri.indexOf(\":\")+1, dataUri.indexOf(\";\")));\n\n if (mediaType != MediaType.IMAGE_JPEG_TYPE && mediaType != MediaType.IMAGE_PNG_TYPE) {\n LOG.error(\"File must be jpeg or png.\");\n return null;\n }\n String extension = mediaType.getExtension();\n\n String image = base64Image.split(\",\")[1];\n\n if (googleImageClassificationService.imageIsExplicit(image)) {\n LOG.error(\"Image does not meet SafeSearch criteria.\");\n return null;\n }\n\n byte[] bytes = Base64.getDecoder().decode(image);\n UploadRequest request = UploadRequest.fromBytes(bytes, UUID.randomUUID()+\".\"+extension);\n UploadResponse<?> response = objectStorage.upload(request);\n\n return storageUrlUtil.getObjectUrlString(response.getKey());\n }\n}"
}
] | import app.dto.storage.PhotoUploadDTO;
import app.service.storage.StorageService;
import io.micronaut.context.annotation.Replaces;
import io.micronaut.http.MediaType;
import io.micronaut.objectstorage.request.UploadRequest;
import jakarta.inject.Singleton;
import javax.validation.Valid;
import java.util.Base64;
import java.util.UUID; | 945 | // Copyright 2023 Libre311 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 app.util;
@Singleton
@Replaces(StorageService.class)
public class MockStorageService extends StorageService {
public MockStorageService() {
super();
}
| // Copyright 2023 Libre311 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 app.util;
@Singleton
@Replaces(StorageService.class)
public class MockStorageService extends StorageService {
public MockStorageService() {
super();
}
| public String upload(@Valid PhotoUploadDTO photoUploadDTO) { | 0 | 2023-10-18 15:37:36+00:00 | 2k |
logicaalternativa/algebraictypes | src/test/java/com/logicaalternativa/algebraictypes/examples/ExampleTryTest.java | [
{
"identifier": "valueOf",
"path": "src/main/java/com/logicaalternativa/algebraictypes/dsl/AlgebraSyntax.java",
"snippet": "public static AlgebraWrapper valueOf( Integer val ) {\n return new AlgebraWrapper( new AlgebraDsl.Number( val ) ); \n}"
},
{
"identifier": "AlgebraDsl",
"path": "src/main/java/com/logicaalternativa/algebraictypes/dsl/AlgebraDsl.java",
"snippet": "public sealed interface AlgebraDsl extends Serializable {\n \n record Number( int value ) implements AlgebraDsl{} \n \n record Addition( AlgebraDsl sumand1, AlgebraDsl summand2 ) implements AlgebraDsl{}\n \n record Negative( AlgebraDsl alg ) implements AlgebraDsl{} \n \n record Subtraction( AlgebraDsl minuend, AlgebraDsl subtrahend ) implements AlgebraDsl{} \n \n record Multiplication( AlgebraDsl one, AlgebraDsl other ) implements AlgebraDsl{} \n\n}"
},
{
"identifier": "Try",
"path": "src/main/java/com/logicaalternativa/algebraictypes/sideeffects/Try.java",
"snippet": "public sealed interface Try<A> {\n\n record Success<A>(A value) implements Try<A>{}\n\n record Failure <A>( Throwable error ) implements Try<A> {}\n\n}"
},
{
"identifier": "Trys",
"path": "src/main/java/com/logicaalternativa/algebraictypes/sideeffects/Trys.java",
"snippet": "public class Trys {\n \n private Trys() {}\n \n public static <T> Try<T> of( final Supplier<T> s ) {\n \n try {\n final var value = s.get();\n return new Try.Success<>( value ) ;\n } catch ( Throwable e) {\n return new Try.Failure<>( e );\n }\n }\n \n public static <T> Try<T> failed( final Throwable error ) {\n return new Try.Failure<>( error ) ;\n } \n \n public static <T,U> Try<U> flatMap( \n Try<T> from, \n Function<? super T, ? extends Try<U>> f ) {\n \n return switch( from ) {\n case Try.Success<T>( var value ) -> executeF( f, value );\n case Try.Failure<T>( var e ) -> failed( e ) ;\n };\n }\n \n public static <T> Try<T> recoverWith( \n Try<T> from, \n Function<? super Throwable, ? extends Try<T>> f ) {\n \n return switch( from ) {\n case Try.Success<T> s -> s;\n case Try.Failure<T>( var e ) -> executeF( f, e ) ;\n };\n }\n \n public static <T,U> Try<U> map( \n Try<T> from, \n Function<? super T, ? extends U> f ) {\n \n return flatMap(from, s -> of( () -> f.apply(s) ) );\n }\n \n public static <T> Try<T> recover( \n Try<T> from, \n Function<? super Throwable, ? extends T> f ) {\n return recoverWith( from, e -> of( () -> f.apply(e) ) );\n }\n \n private static <T,U> Try<U> executeF( \n final Function<? super T, ? extends Try<U>> f, \n final T value) {\n try {\n return f.apply( value);\n } catch (Throwable e) {\n return failed( e ); \n }\n }\n \n public static <T> TryWrap<T> wrap(Try<T> tryValue) {\n return new TryWrap<>( tryValue );\n } \n \n public static class TryWrap<T> {\n \n private final Try<T> tryValue;\n \n private TryWrap( final Try<T> tryValue ) {\n this.tryValue = tryValue;\n }\n \n public Try<T> get() {\n return tryValue;\n }\n \n public <U> TryWrap<U> flatMap( \n Function<? super T, ? extends Try<U>> f ) {\n return new TryWrap<>( Trys.flatMap( tryValue, f ) );\n }\n \n public <U> TryWrap<U> map( \n Function<? super T, ? extends U> f ) {\n return new TryWrap<>( Trys.map( tryValue, f ) );\n }\n \n public TryWrap<T> recoverWith( \n Function<? super Throwable, ? extends Try<T>> f ) {\n return new TryWrap<>( Trys.recoverWith( tryValue, f ) );\n }\n \n public TryWrap<T> recover( \n Function<? super Throwable, ? extends T> f ) {\n return new TryWrap<>( Trys.recover( tryValue, f ) );\n }\n\n }\n\n}"
}
] | import static com.logicaalternativa.algebraictypes.dsl.AlgebraSyntax.valueOf;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.platform.commons.logging.Logger;
import org.junit.platform.commons.logging.LoggerFactory;
import com.logicaalternativa.algebraictypes.dsl.AlgebraDsl;
import com.logicaalternativa.algebraictypes.sideeffects.Try;
import com.logicaalternativa.algebraictypes.sideeffects.Trys; | 1,279 | package com.logicaalternativa.algebraictypes.examples;
public class ExampleTryTest {
final Logger log = LoggerFactory.getLogger(getClass());
@Test
@DisplayName("Test try OK")
void test01() {
| package com.logicaalternativa.algebraictypes.examples;
public class ExampleTryTest {
final Logger log = LoggerFactory.getLogger(getClass());
@Test
@DisplayName("Test try OK")
void test01() {
| final var tryOk = Trys.of( () -> 10 /5 ); | 3 | 2023-10-21 20:03:49+00:00 | 2k |
Radekyspec/TasksMaster | src/test/java/entities/project/CommonProjectTest.java | [
{
"identifier": "CommonMessageBoardFactory",
"path": "src/main/java/entities/message_board/CommonMessageBoardFactory.java",
"snippet": "public class CommonMessageBoardFactory {\n /**\n * create a new MessageBoard which containing many massage\n *\n * @param ID the ID of the messageBoard\n * @return return a new messageBoard that we build\n */\n public static CommonMessageBoard create(long ID) {\n return new CommonMessageBoard(ID);\n }\n}"
},
{
"identifier": "MessageBoard",
"path": "src/main/java/entities/message_board/MessageBoard.java",
"snippet": "public interface MessageBoard {\n /**\n * Return the ID of the MessageBoard\n *\n * @return its ID\n */\n long getID();\n\n /**\n * Return all the message in the MessageBoard\n *\n * @return its messages\n */\n Map<Long, Message> getMessage();\n\n /**\n * add the new message into our MessageBoard\n *\n * @param message a new message object\n */\n void setMessage(Message message);\n}"
},
{
"identifier": "CommonScheduleFactory",
"path": "src/main/java/entities/schedule/CommonScheduleFactory.java",
"snippet": "public class CommonScheduleFactory {\n /**\n * build up a new schedule\n *\n * @param id the id of the schedule\n */\n public static CommonSchedule create(long id) {\n return new CommonSchedule(id);\n }\n}"
},
{
"identifier": "Schedule",
"path": "src/main/java/entities/schedule/Schedule.java",
"snippet": "public interface Schedule {\n /**\n * return the ID of the schedule\n *\n * @return the ID of the schedule\n */\n long getId();\n\n /**\n * return the events of the schedule\n *\n * @return the events of the schedule\n */\n List<Event> getEvents();\n\n /**\n * add a new event to the schedule\n *\n * @param event the new event.\n */\n void addEvent(Event event);\n}"
},
{
"identifier": "CommonToDoPanelFactory",
"path": "src/main/java/entities/todo_panel/CommonToDoPanelFactory.java",
"snippet": "public class CommonToDoPanelFactory {\n /**\n * create a CommonToDoPanel class that contains things as followed.\n *\n * @param ID the identification of this To_DoPanel\n * @return a CommonToDoPanel class\n */\n public static CommonToDoPanel create(long ID) {\n return new CommonToDoPanel(ID);\n }\n}"
},
{
"identifier": "ToDoPanel",
"path": "src/main/java/entities/todo_panel/ToDoPanel.java",
"snippet": "public interface ToDoPanel {\n /**\n * Returns ID of this obj.\n *\n * @return its ID.\n */\n long getId();\n\n /**\n * Returns lists of this obj.\n *\n * @return all the TO_DOList managed by this panel.\n */\n Map<Long, ToDoList> getLists();\n}"
},
{
"identifier": "CommonUserFactory",
"path": "src/main/java/entities/user/CommonUserFactory.java",
"snippet": "public class CommonUserFactory {\n private CommonUserFactory() {\n }\n\n /**\n * Create a new user\n *\n * @param ID the unique ID of user\n * @param name the name of user\n * @param password the password of user\n * @param createDateTime the time when user account created\n * @param email the email user used to sign up account\n * @return a new user object\n */\n public static User create(long ID, String name, String password, LocalDateTime createDateTime, String email) {\n return new CommonUser(ID, name, password, createDateTime, email);\n }\n}"
},
{
"identifier": "User",
"path": "src/main/java/entities/user/User.java",
"snippet": "public interface User {\n /**\n * Return the ID of the User\n *\n * @return its ID\n */\n long getID();\n\n /**\n * Return the organization that User is in\n *\n * @return its organization\n */\n Organization getOrganization();\n\n /**\n * Return the name of the User\n *\n * @return its name\n */\n String getName();\n\n /**\n * Return the password of the User\n *\n * @return its password\n */\n String getPassword();\n\n /**\n * Return the created time of the User\n *\n * @return its creation_time\n */\n LocalDateTime getCreationTime();\n\n /**\n * Return the email of the User\n *\n * @return its email\n */\n String getEmail();\n\n Rule getRule();\n\n /**\n * set and get the rule of the User, including Boss, Leader and Member\n */\n\n void setRule(Rule rule);\n\n /**\n * let user join a organization\n *\n * @param organization an organization that user want to join\n */\n void joinOrganization(Organization organization);\n\n}"
}
] | import entities.message_board.CommonMessageBoardFactory;
import entities.message_board.MessageBoard;
import entities.schedule.CommonScheduleFactory;
import entities.schedule.Schedule;
import entities.todo_panel.CommonToDoPanelFactory;
import entities.todo_panel.ToDoPanel;
import entities.user.CommonUserFactory;
import entities.user.User;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.LocalDateTime;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull; | 1,266 | package entities.project;
class CommonProjectTest {
private User user1;
private User user2;
private Project project; | package entities.project;
class CommonProjectTest {
private User user1;
private User user2;
private Project project; | private ToDoPanel toDoPanel; | 5 | 2023-10-23 15:17:21+00:00 | 2k |
denis-vp/toy-language-interpreter | src/main/java/model/expression/HeapReadExpression.java | [
{
"identifier": "IDictionary",
"path": "src/main/java/adt/IDictionary.java",
"snippet": "public interface IDictionary<K, V> {\n void add(K key, V value);\n\n void remove(K key);\n\n V get(K key);\n\n void update(K key, V value);\n\n boolean search(K key);\n\n int size();\n\n boolean isEmpty();\n\n Collection<Map.Entry<K, V>> entrySet();\n\n Set<K> keys();\n\n Collection<V> values();\n\n IDictionary<K, V> deepCopy();\n}"
},
{
"identifier": "IHeap",
"path": "src/main/java/adt/IHeap.java",
"snippet": "public interface IHeap {\n int add(Value value);\n\n void remove(Integer key);\n\n Value get(Integer key);\n\n void update(Integer key, Value value);\n\n boolean search(Integer key);\n\n int size();\n\n boolean isEmpty();\n\n Map<Integer, Value> getContent();\n\n void setContent(Map<Integer, Value> heap);\n\n Set<Integer> keys();\n\n Collection<Value> values();\n}"
},
{
"identifier": "ExpressionException",
"path": "src/main/java/exception/ExpressionException.java",
"snippet": "public class ExpressionException extends InterpreterException {\n public ExpressionException(String message) {\n super(message);\n }\n}"
},
{
"identifier": "ReferenceType",
"path": "src/main/java/model/type/ReferenceType.java",
"snippet": "public class ReferenceType implements Type {\n private final Type inner;\n\n public ReferenceType(Type inner) {\n this.inner = inner;\n }\n\n public Type getInner() {\n return this.inner;\n }\n\n public boolean equals(Object another) {\n if (another == null) {\n return false;\n } else if (another == this) {\n return true;\n }\n\n return another instanceof ReferenceType;\n }\n\n @Override\n public Value defaultValue() {\n return new ReferenceValue(0, this.inner);\n }\n\n @Override\n public Type deepCopy() {\n return new ReferenceType(this.inner.deepCopy());\n }\n\n public String toString() {\n return \"ref (\" + this.inner + \")\";\n }\n}"
},
{
"identifier": "Type",
"path": "src/main/java/model/type/Type.java",
"snippet": "public interface Type {\n Value defaultValue();\n\n Type deepCopy();\n}"
},
{
"identifier": "ReferenceValue",
"path": "src/main/java/model/value/ReferenceValue.java",
"snippet": "public class ReferenceValue implements Value {\n private final int address;\n private final Type locationType;\n\n public ReferenceValue(int address, Type locationType) {\n this.address = address;\n this.locationType = locationType;\n }\n\n public int getAddress() {\n return this.address;\n }\n\n public Type getLocationType() {\n return this.locationType;\n }\n\n public boolean equals(Object another) {\n if (another == null) {\n return false;\n } else if (another == this) {\n return true;\n }\n\n if (another instanceof ReferenceValue) {\n return this.address == ((ReferenceValue) another).getAddress() &&\n this.locationType.equals(((ReferenceValue) another).getLocationType());\n }\n return false;\n }\n\n @Override\n public Type getType() {\n return new ReferenceType(this.locationType);\n }\n\n @Override\n public Value deepCopy() {\n return new ReferenceValue(this.address, this.locationType.deepCopy());\n }\n\n public String toString() {\n return \"(\" + this.address + \", \" + this.locationType + \")\";\n }\n}"
},
{
"identifier": "Value",
"path": "src/main/java/model/value/Value.java",
"snippet": "public interface Value {\n Type getType();\n\n Value deepCopy();\n}"
}
] | import adt.IDictionary;
import adt.IHeap;
import exception.ExpressionException;
import model.type.ReferenceType;
import model.type.Type;
import model.value.ReferenceValue;
import model.value.Value; | 954 | package model.expression;
public class HeapReadExpression implements Expression {
private final Expression expression;
public HeapReadExpression(Expression expression) {
this.expression = expression;
}
@Override | package model.expression;
public class HeapReadExpression implements Expression {
private final Expression expression;
public HeapReadExpression(Expression expression) {
this.expression = expression;
}
@Override | public Value eval(IDictionary<String, Value> symbolTable, IHeap heap) throws ExpressionException { | 0 | 2023-10-21 18:08:59+00:00 | 2k |
PrzemyslawMusial242473/GreenGame | src/main/java/org/io/GreenGame/user/service/implementation/AuthServiceImplementation.java | [
{
"identifier": "SecurityConfig",
"path": "src/main/java/org/io/GreenGame/config/SecurityConfig.java",
"snippet": "@Configuration\n@EnableWebSecurity\npublic class SecurityConfig {\n\n @Autowired\n private UserDetailsService userDetailsService;\n\n @Bean\n public static PasswordEncoder passwordEncoder() {\n return new BCryptPasswordEncoder();\n }\n\n @Bean\n public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {\n http.userDetailsService(userDetailsService)\n .csrf(AbstractHttpConfigurer::disable)\n .cors(AbstractHttpConfigurer::disable)\n .authorizeHttpRequests(request -> {\n request.requestMatchers(\"/\").permitAll();\n request.requestMatchers(\"/register\").permitAll();\n request.requestMatchers(\"/login\").permitAll();\n request.requestMatchers(\"/deleteUser\").permitAll();\n request.requestMatchers(\"/secured/**\")\n .authenticated();\n request.requestMatchers(\"/secured/**\")\n .hasRole(\"USER\");\n }).formLogin(form -> form\n .loginPage(\"/login\")\n .loginProcessingUrl(\"/login\")\n .permitAll().defaultSuccessUrl(\"/secured/hello\", true).failureUrl(\"/login\"))\n .logout(logout -> logout\n .logoutRequestMatcher(new AntPathRequestMatcher(\"/logout\"))\n .permitAll()\n );\n return http.build();\n }\n\n @Autowired\n public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {\n auth\n .userDetailsService(userDetailsService)\n .passwordEncoder(passwordEncoder());\n }\n}"
},
{
"identifier": "GreenGameUser",
"path": "src/main/java/org/io/GreenGame/user/model/GreenGameUser.java",
"snippet": "@Entity\n@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\n@Table(name=\"Users\")\npublic class GreenGameUser {\n\n @Id\n @GeneratedValue\n private Long id;\n\n private String Username;\n\n private String Email;\n\n private LocalDateTime CreationDate;\n\n private LocalDateTime ChangeDate;\n\n @ManyToMany(fetch = FetchType.EAGER, cascade=CascadeType.ALL)\n @JoinTable(\n name=\"users_roles\",\n joinColumns={@JoinColumn(name=\"USER_ID\", referencedColumnName=\"ID\")},\n inverseJoinColumns={@JoinColumn(name=\"ROLE_ID\", referencedColumnName=\"ID\")})\n private List<Role> roles = new ArrayList<>();\n @Embedded\n private Security SecurityData;\n\n\n @Override\n public String toString() {\n return \"GreenGameUser{\" +\n \"id=\" + id +\n \", Username='\" + Username + '\\'' +\n \", Email='\" + Email + '\\'' +\n \", CreationDate=\" + CreationDate +\n \", ChangeDate=\" + ChangeDate +\n \", roles=\" + roles +\n \", SecurityData=\" + SecurityData +\n \", passwdhash=\" + SecurityData.getPasswordHash() +\n '}';\n }\n}"
},
{
"identifier": "Role",
"path": "src/main/java/org/io/GreenGame/user/model/Role.java",
"snippet": "@Setter\n@Getter\n@NoArgsConstructor\n@AllArgsConstructor\n@Entity\n@Table(name=\"roles\")\npublic class Role\n{\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(nullable=false, unique=true)\n private String name;\n\n @ManyToMany(mappedBy=\"roles\")\n private List<GreenGameUser> users;\n}"
},
{
"identifier": "Security",
"path": "src/main/java/org/io/GreenGame/user/model/Security.java",
"snippet": "@Setter\n@Getter\n@NoArgsConstructor\n@AllArgsConstructor\n@Embeddable\npublic class Security {\n\n private LocalDateTime SecurityChangeDate;\n\n private LocalDateTime SecurityLastLoginDate;\n\n private String PasswordHash;\n\n}"
},
{
"identifier": "UserRegisterForm",
"path": "src/main/java/org/io/GreenGame/user/model/UserRegisterForm.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class UserRegisterForm {\n\n String username;\n String email;\n String password;\n String repeatedPassword;\n}"
},
{
"identifier": "RoleRepository",
"path": "src/main/java/org/io/GreenGame/user/repository/RoleRepository.java",
"snippet": "@Repository\npublic interface RoleRepository extends JpaRepository<Role, Long> {\n Role findByName(String name);\n}"
},
{
"identifier": "UserRepository",
"path": "src/main/java/org/io/GreenGame/user/repository/UserRepository.java",
"snippet": "@Repository\npublic interface UserRepository extends JpaRepository<GreenGameUser, Long> {\n\n @Query(\"SELECT COUNT(user.id) FROM GreenGameUser user WHERE user.id = :id\")\n Long checkIfIdIsInDatabase(Long id);\n\n @Query(\"SELECT COUNT(user.Username) FROM GreenGameUser user WHERE user.Username = :username\")\n Long checkIfUsernameIsInDatabase(String username);\n\n @Query(\"SELECT COUNT(user.Email) FROM GreenGameUser user WHERE user.Email = :email\")\n Long checkIfEmailIsInDatabase(String email);\n\n @Query(\"SELECT user FROM GreenGameUser user WHERE user.Email = :email\")\n GreenGameUser findUserByEmail(String email);\n}"
},
{
"identifier": "AuthService",
"path": "src/main/java/org/io/GreenGame/user/service/AuthService.java",
"snippet": "public interface AuthService {\n Boolean registerUser(UserRegisterForm userRegisterForm);\n Boolean deleteUser(GreenGameUser greenGameUser);\n Boolean changePassword(GreenGameUser greenGameUser, String oldPassword, String newPassword);\n GreenGameUser getUserFromSession();\n}"
}
] | import org.io.GreenGame.config.SecurityConfig;
import org.io.GreenGame.user.model.GreenGameUser;
import org.io.GreenGame.user.model.Role;
import org.io.GreenGame.user.model.Security;
import org.io.GreenGame.user.model.UserRegisterForm;
import org.io.GreenGame.user.repository.RoleRepository;
import org.io.GreenGame.user.repository.UserRepository;
import org.io.GreenGame.user.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Objects;
import java.util.Random; | 1,400 | package org.io.GreenGame.user.service.implementation;
@Service
@ComponentScan
public class AuthServiceImplementation implements AuthService {
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Override | package org.io.GreenGame.user.service.implementation;
@Service
@ComponentScan
public class AuthServiceImplementation implements AuthService {
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Override | public Boolean registerUser(UserRegisterForm userRegisterForm) { | 4 | 2023-10-23 09:21:30+00:00 | 2k |
NewStudyGround/NewStudyGround | server/src/main/java/com/codestates/server/domain/bookmark/service/BookmarkService.java | [
{
"identifier": "Bookmark",
"path": "server/src/main/java/com/codestates/server/domain/bookmark/entity/Bookmark.java",
"snippet": "@Entity\n@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Bookmark {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @OneToOne\n private LicenseInfo licenseInfo;\n\n @ManyToOne\n @JoinColumn(name = \"member_id\")\n @JsonIgnore\n private Member member;\n}"
},
{
"identifier": "BookmarkRepository",
"path": "server/src/main/java/com/codestates/server/domain/bookmark/repository/BookmarkRepository.java",
"snippet": "public interface BookmarkRepository extends JpaRepository<Bookmark, Long> {\n\n public boolean existsBookmarkByLicenseInfoAndMember(LicenseInfo licenseInfo, Member member);\n\n public Bookmark findBookmarkByLicenseInfoAndMember(LicenseInfo licenseInfo, Member member);\n\n}"
},
{
"identifier": "LicenseInfo",
"path": "server/src/main/java/com/codestates/server/domain/license/licenseinfo/entity/LicenseInfo.java",
"snippet": "@Entity\n@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class LicenseInfo {\n\n @Id\n private Long code;\n\n @Column\n private String name;\n\n// @ColumnDefault(\"0\") //default 값을 0으로 준다. 하지만 이 엔티티에서 실제 값의 주입은 batchConfig에서 일어난다.\n @Column\n private Long markCount;\n\n @OneToMany(mappedBy = \"licenseInfo\")\n private List<LicenseDate> licenses;\n\n}"
},
{
"identifier": "LicenseInfoRepository",
"path": "server/src/main/java/com/codestates/server/domain/license/licenseinfo/repository/LicenseInfoRepository.java",
"snippet": "@Repository\npublic interface LicenseInfoRepository extends JpaRepository<LicenseInfo,Long> {\n\n /**\n * 이름으로 LicenseInfo 조회\n * @param name\n * @return\n */\n public LicenseInfo findByName(String name);\n\n /**\n * 북마크수 기준으로 상위 5개를 뽑아낸다.\n * @return\n */\n public List<LicenseInfo> findTop5ByOrderByMarkCountDesc();\n\n public List<LicenseInfo> findByNameContaining(String keyword);\n\n}"
},
{
"identifier": "Member",
"path": "server/src/main/java/com/codestates/server/domain/member/entity/Member.java",
"snippet": "@Getter\n@Setter\n@RequiredArgsConstructor\n@Entity\npublic class Member {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long memberId;\n\n private String email;\n\n private String name; // 닉네임\n\n private String phone;\n\n private String password;\n\n private String profileImage;\n\n // 멤버 당 하나의 권한을 가지기 때문에 즉시 로딩 괜찮음 (즉시로딩 N : 1은 괜찮으나 1:N은 안됨)\n // 사용자 등록 시 사용자의 권한 등록을 위해 권한 테이블 생성\n @ElementCollection(fetch = FetchType.EAGER)\n private List<String> roles = new ArrayList<>();\n\n @JsonIgnore\n @OneToMany(mappedBy = \"member\", cascade = CascadeType.ALL)\n private List<Board> boards;\n\n @JsonIgnore\n @OneToMany(mappedBy = \"member\", cascade = CascadeType.ALL)\n private List<Answer> answers;\n\n @JsonIgnore\n @OneToMany(mappedBy = \"member\", cascade = CascadeType.ALL)\n private List<Comment> comments;\n\n @JsonIgnore\n @OneToMany(mappedBy = \"member\", cascade = CascadeType.ALL)\n private List<Bookmark> Bookmarks;\n\n}"
},
{
"identifier": "BusinessLogicException",
"path": "server/src/main/java/com/codestates/server/global/exception/BusinessLogicException.java",
"snippet": "public class BusinessLogicException extends RuntimeException {\n @Getter\n private ExceptionCode exceptionCode;\n\n public BusinessLogicException(ExceptionCode exceptionCode) {\n super(exceptionCode.getMessage());\n this.exceptionCode = exceptionCode;\n }\n}"
},
{
"identifier": "ExceptionCode",
"path": "server/src/main/java/com/codestates/server/global/exception/ExceptionCode.java",
"snippet": "public enum ExceptionCode {\n //User not in database\n USER_NOT_FOUND(404, \"User not found\"),\n //User exists\n USER_EXISTS(409, \"User exists\"),\n //Unauthorized user\n UNAUTHORIZED_USER(401, \"Unauthorized user\"),\n // answer not in database\n ANSWER_NOT_FOUND(404, \"Answer not found\"),\n // comment not in database\n COMMENT_NOT_FOUND(404, \"Comment not found\"),\n // Board not in database\n BOARD_NOT_FOUND(404, \"Board not found\"),\n //Bookmark exists\n BOOKMARK_EXISTS(409, \"bookmark exists\"),\n //Bookmark Not in database\n BOOKMARK_NOT_FOUND(404,\"Bookmark not found\"),\n //LicenseInfo Not in database\n LICENSE_NOT_FOUND(404,\"License not found\"),\n // kakako 로부터 유효한 정보 받지 못함\n UNAUTHORIZED_KAKAO(401, \"카카오로부터 유효한 사용자 정보를 받지 못했습니다.\"),\n // 이메일이 없는 사용자는 가입할 수 없습니다.\n UNAUTHORIZED_EMAIL_KAKAO(401, \"이메일이 없는 사용자는 가입할 수 없습니다.\");\n\n\n @Getter\n private int status;\n\n @Getter\n private String message;\n\n ExceptionCode(int code, String message) {\n this.status = code;\n this.message = message;\n }\n}"
}
] | import com.codestates.server.domain.bookmark.entity.Bookmark;
import com.codestates.server.domain.bookmark.repository.BookmarkRepository;
import com.codestates.server.domain.license.licenseinfo.entity.LicenseInfo;
import com.codestates.server.domain.license.licenseinfo.repository.LicenseInfoRepository;
import com.codestates.server.domain.member.entity.Member;
import com.codestates.server.global.exception.BusinessLogicException;
import com.codestates.server.global.exception.ExceptionCode;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service; | 1,510 | package com.codestates.server.domain.bookmark.service;
@Service
@RequiredArgsConstructor
public class BookmarkService {
private final BookmarkRepository bookmarkRepository;
private final LicenseInfoRepository licenseInfoRepository;
| package com.codestates.server.domain.bookmark.service;
@Service
@RequiredArgsConstructor
public class BookmarkService {
private final BookmarkRepository bookmarkRepository;
private final LicenseInfoRepository licenseInfoRepository;
| public void saveBookmark(Member member, LicenseInfo licenseInfo){ | 4 | 2023-10-23 09:41:00+00:00 | 2k |
metacosm/quarkus-power | deployment/src/main/java/io/quarkiverse/power/deployment/PowerProcessor.java | [
{
"identifier": "PowerCommands",
"path": "deployment/src/main/java/io/quarkiverse/power/deployment/devui/commands/PowerCommands.java",
"snippet": "@GroupCommandDefinition(name = \"power\", description = \"Power consumption commands\", generateHelp = true)\n@SuppressWarnings(\"rawtypes\")\npublic class PowerCommands implements GroupCommand {\n private final PowerMeasurer<? extends SensorMeasure> sensor;\n\n public PowerCommands(PowerMeasurer<? extends SensorMeasure> sensor) {\n this.sensor = sensor;\n }\n\n @Override\n public List<Command> getCommands() {\n return List.of(new StartCommand(sensor), new StopCommand(sensor));\n }\n\n @Override\n public CommandResult execute(CommandInvocation commandInvocation) throws CommandException, InterruptedException {\n commandInvocation.println(commandInvocation.getHelpInfo());\n return CommandResult.SUCCESS;\n }\n}"
},
{
"identifier": "PowerMeasurer",
"path": "runtime/src/main/java/io/quarkiverse/power/runtime/PowerMeasurer.java",
"snippet": "public class PowerMeasurer<M extends SensorMeasure> {\n private static final OperatingSystemMXBean osBean;\n\n static {\n osBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();\n // take two measures to avoid initial zero values\n osBean.getProcessCpuLoad();\n osBean.getCpuLoad();\n osBean.getProcessCpuLoad();\n osBean.getCpuLoad();\n }\n\n private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();\n private ScheduledFuture<?> scheduled;\n private final PowerSensor<M> sensor;\n private OngoingPowerMeasure measure;\n\n private Consumer<PowerMeasure> completed;\n private BiConsumer<Integer, PowerMeasure> sampled;\n private Consumer<Exception> errorHandler;\n\n private final static PowerMeasurer<? extends SensorMeasure> instance = new PowerMeasurer<>(\n PowerSensorProducer.determinePowerSensor());\n\n public static PowerMeasurer<? extends SensorMeasure> instance() {\n return instance;\n }\n\n public PowerMeasurer(PowerSensor<M> sensor) {\n this.sensor = sensor;\n this.onError(null);\n }\n\n public double cpuShareOfJVMProcess() {\n final var processCpuLoad = osBean.getProcessCpuLoad();\n final var cpuLoad = osBean.getCpuLoad();\n return (processCpuLoad < 0 || cpuLoad <= 0) ? 0 : processCpuLoad / cpuLoad;\n }\n\n public void onCompleted(Consumer<PowerMeasure> completed) {\n this.completed = completed;\n }\n\n public void onSampled(BiConsumer<Integer, PowerMeasure> sampled) {\n this.sampled = sampled;\n }\n\n public void onError(Consumer<Exception> errorHandler) {\n this.errorHandler = errorHandler != null ? errorHandler : (exception) -> {\n throw new RuntimeException(exception);\n };\n }\n\n public Optional<String> additionalSensorInfo() {\n return Optional.ofNullable(measure).flatMap(sensor::additionalInfo);\n }\n\n public boolean isRunning() {\n return measure != null;\n }\n\n public void start(long durationInSeconds, long frequencyInMilliseconds)\n throws Exception {\n try {\n measure = sensor.start(durationInSeconds, frequencyInMilliseconds);\n\n if (durationInSeconds > 0) {\n executor.schedule(this::stop, durationInSeconds, TimeUnit.SECONDS);\n }\n\n scheduled = executor.scheduleAtFixedRate(this::update, 0, frequencyInMilliseconds, TimeUnit.MILLISECONDS);\n } catch (Exception e) {\n handleError(e);\n }\n }\n\n private void update() {\n try {\n sensor.update(measure);\n if (this.sampled != null) {\n sampled.accept(measure.numberOfSamples(), measure);\n }\n } catch (Exception e) {\n handleError(e);\n }\n }\n\n private void handleError(Exception e) {\n errorHandler.accept(e);\n try {\n if (scheduled != null) {\n scheduled.cancel(true);\n }\n if (sensor != null) {\n sensor.stop();\n }\n } catch (Exception ex) {\n // ignore shutting down exceptions\n }\n }\n\n public void stop() {\n try {\n if (isRunning()) {\n sensor.stop();\n scheduled.cancel(true);\n // record the result\n final var measured = new StoppedPowerMeasure(measure);\n // then set the measure to null to mark that we're ready for a new measure\n measure = null;\n // and finally, but only then, run the completion handler\n completed.accept(measured);\n }\n } catch (Exception e) {\n handleError(e);\n }\n }\n}"
}
] | import io.quarkiverse.power.deployment.devui.commands.PowerCommands;
import io.quarkiverse.power.runtime.PowerMeasurer;
import io.quarkus.deployment.IsDevelopment;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.ConsoleCommandBuildItem;
import io.quarkus.deployment.builditem.FeatureBuildItem; | 1,270 | package io.quarkiverse.power.deployment;
class PowerProcessor {
private static final String FEATURE = "power";
@BuildStep
FeatureBuildItem feature() {
return new FeatureBuildItem(FEATURE);
}
@BuildStep(onlyIf = IsDevelopment.class)
void addConsoleCommands(BuildProducer<ConsoleCommandBuildItem> commands) {
// register dev console commands | package io.quarkiverse.power.deployment;
class PowerProcessor {
private static final String FEATURE = "power";
@BuildStep
FeatureBuildItem feature() {
return new FeatureBuildItem(FEATURE);
}
@BuildStep(onlyIf = IsDevelopment.class)
void addConsoleCommands(BuildProducer<ConsoleCommandBuildItem> commands) {
// register dev console commands | commands.produce(new ConsoleCommandBuildItem(new PowerCommands(PowerMeasurer.instance()))); | 1 | 2023-10-23 16:44:57+00:00 | 2k |
LeGhast/Miniaturise | src/main/java/de/leghast/miniaturise/command/AdjustCommand.java | [
{
"identifier": "Miniaturise",
"path": "src/main/java/de/leghast/miniaturise/Miniaturise.java",
"snippet": "public final class Miniaturise extends JavaPlugin {\n\n private MiniatureManager miniatureManager;\n private RegionManager regionManager;\n private SettingsManager settingsManager;\n\n @Override\n public void onEnable() {\n ConfigManager.setupConfig(this);\n initialiseManagers();\n registerListeners();\n setCommands();\n setTabCompleters();\n }\n\n @Override\n public void onDisable() {\n saveConfig();\n }\n\n private void initialiseManagers(){\n miniatureManager = new MiniatureManager(this);\n regionManager = new RegionManager(this);\n settingsManager = new SettingsManager(this);\n }\n\n private void registerListeners(){\n Bukkit.getPluginManager().registerEvents(new PlayerInteractListener(this), this);\n Bukkit.getPluginManager().registerEvents(new PlayerQuitListener(this), this);\n Bukkit.getPluginManager().registerEvents(new InventoryClickListener(this), this);\n }\n\n private void setCommands(){\n getCommand(\"select\").setExecutor(new SelectCommand(this));\n getCommand(\"scale\").setExecutor(new ScaleCommand(this));\n getCommand(\"cut\").setExecutor(new CutCommand(this));\n getCommand(\"tools\").setExecutor(new ToolsCommand(this));\n getCommand(\"paste\").setExecutor(new PasteCommand(this));\n getCommand(\"tool\").setExecutor(new ToolCommand(this));\n getCommand(\"delete\").setExecutor(new DeleteCommand(this));\n getCommand(\"copy\").setExecutor(new CopyCommand(this));\n getCommand(\"position\").setExecutor(new PositionCommand(this));\n getCommand(\"clear\").setExecutor(new ClearCommand(this));\n getCommand(\"adjust\").setExecutor(new AdjustCommand(this));\n getCommand(\"rotate\").setExecutor(new RotateCommand(this));\n }\n\n public void setTabCompleters(){\n getCommand(\"position\").setTabCompleter(new PositionTabCompleter());\n getCommand(\"scale\").setTabCompleter(new ScaleTabCompleter());\n getCommand(\"tool\").setTabCompleter(new ToolTabCompleter());\n getCommand(\"rotate\").setTabCompleter(new RotateTabCompleter());\n }\n\n /**\n * @return The MiniatureManager instance\n */\n public MiniatureManager getMiniatureManager(){\n return miniatureManager;\n }\n\n /**\n * @return The RegionManager instance\n */\n public RegionManager getRegionManager(){\n return regionManager;\n }\n\n public SettingsManager getSettingsManager(){\n return settingsManager;\n }\n\n}"
},
{
"identifier": "UserInterface",
"path": "src/main/java/de/leghast/miniaturise/ui/UserInterface.java",
"snippet": "public class UserInterface {\n\n public UserInterface(Miniaturise main, Player player, Page page){\n Inventory inv = Bukkit.createInventory(null, 45, page.getTitle());\n switch (page){\n case POSITION -> {\n inv.setContents(PositionPage.getPositionPage(main, player));\n }\n case SIZE -> {\n inv.setContents(SizePage.getSizePage(main, player));\n }\n case ROTATION -> {\n inv.setContents(RotationPage.getRotationPage(main, player));\n }\n }\n player.openInventory(inv);\n }\n\n}"
}
] | import de.leghast.miniaturise.Miniaturise;
import de.leghast.miniaturise.ui.UserInterface;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull; | 960 | package de.leghast.miniaturise.command;
public class AdjustCommand implements CommandExecutor {
private Miniaturise main;
public AdjustCommand(Miniaturise main){
this.main = main;
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String s, @NotNull String[] args) {
if(sender instanceof Player player){
if(player.hasPermission("miniaturise.use")) {
if (!main.getSettingsManager().hasAdjusterSettings(player.getUniqueId())) {
main.getSettingsManager().addAdjusterSettings(player.getUniqueId());
} | package de.leghast.miniaturise.command;
public class AdjustCommand implements CommandExecutor {
private Miniaturise main;
public AdjustCommand(Miniaturise main){
this.main = main;
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String s, @NotNull String[] args) {
if(sender instanceof Player player){
if(player.hasPermission("miniaturise.use")) {
if (!main.getSettingsManager().hasAdjusterSettings(player.getUniqueId())) {
main.getSettingsManager().addAdjusterSettings(player.getUniqueId());
} | new UserInterface(main, player, main.getSettingsManager().getAdjusterSettings(player.getUniqueId()).getPage()); | 1 | 2023-10-15 09:08:33+00:00 | 2k |
HenryAWE/tcreate | src/main/java/henryawe/tcreate/register/TCreatePotatoCannonProjectileTypes.java | [
{
"identifier": "SharedSecrets",
"path": "src/main/java/henryawe/tcreate/SharedSecrets.java",
"snippet": "public final class SharedSecrets {\n private SharedSecrets() {\n }\n\n private static final StackWalker STACK_WALKER = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);\n\n private static final HashSet<Class<?>> PERMITTED_CLASSES = new HashSet<>(List.of(\n SharedSecrets.class,\n TCreate.class,\n TCreateFluids.class,\n TCreateItems.class,\n TCreateTabs.class,\n TCreateRecipeTypes.class,\n TCreatePotatoCannonProjectileTypes.class,\n ProcessingTypes.class,\n SkySlimeType.class,\n SkySlimeRecipe.class,\n BaseEffect.class,\n ColdEffect.class\n ));\n\n public static ResourceLocation asResource(String name) {\n final var caller = STACK_WALKER.getCallerClass();\n if (!PERMITTED_CLASSES.contains(caller))\n throw new SecurityException(\"Caller \" + caller + \" is not permitted to access SharedSecrets.\");\n return new ResourceLocation(MODID, name);\n }\n\n /**\n * Convert the color to int.\n * <p/>\n * result = r << 16 | g << 8 | b\n *\n * @param color the color.\n * @return int represents the color.\n */\n public static int getColor(@NotNull Color color) {\n final var caller = STACK_WALKER.getCallerClass();\n if (!PERMITTED_CLASSES.contains(caller))\n throw new SecurityException(\"Caller \" + caller + \" is not permitted to access SharedSecrets.\");\n return color.getRed() << 16 | color.getGreen() << 8 | color.getBlue();\n }\n}"
},
{
"identifier": "EflnEffects",
"path": "src/main/java/henryawe/tcreate/create/potatocannon/EflnEffects.java",
"snippet": "public final class EflnEffects {\n public static boolean onBlockHit(@NotNull LevelAccessor l, @NotNull BlockHitResult result) {\n if (!l.isClientSide() && l instanceof Level worldIn) {\n final BlockPos pos = result.getBlockPos();\n final var explosion = new EFLNExplosion(\n worldIn,\n null, null, null,\n pos.getX(), pos.getY(), pos.getZ(),\n 6f, true, Explosion.BlockInteraction.DESTROY\n );\n if (!ForgeEventFactory.onExplosionStart(worldIn, explosion)) {\n explosion.explode();\n explosion.finalizeExplosion(true);\n }\n }\n return true;\n }\n}"
}
] | import com.simibubi.create.content.equipment.potatoCannon.PotatoCannonProjectileType;
import henryawe.tcreate.SharedSecrets;
import henryawe.tcreate.create.potatocannon.EflnEffects;
import org.jetbrains.annotations.NotNull;
import static com.simibubi.create.content.equipment.potatoCannon.PotatoCannonProjectileType.Builder;
import static slimeknights.tconstruct.gadgets.TinkerGadgets.efln; | 739 | package henryawe.tcreate.register;
public final class TCreatePotatoCannonProjectileTypes {
@NotNull
private static Builder create(@NotNull String name) { | package henryawe.tcreate.register;
public final class TCreatePotatoCannonProjectileTypes {
@NotNull
private static Builder create(@NotNull String name) { | return new Builder(SharedSecrets.asResource(name)); | 0 | 2023-10-16 14:42:49+00:00 | 2k |
sudo-selfdestruction/WarehouseAccountingSystem | src/main/java/by/bsu/rfict/WarehouseAccountingSystem/mapper/ItemMapper.java | [
{
"identifier": "ItemDto",
"path": "src/main/java/by/bsu/rfict/WarehouseAccountingSystem/dto/ItemDto.java",
"snippet": "@Data\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class ItemDto {\n private String name;\n private String description;\n private String manufacturingCountry;\n private int cost;\n private double weight;\n\n}"
},
{
"identifier": "OrderDto",
"path": "src/main/java/by/bsu/rfict/WarehouseAccountingSystem/dto/OrderDto.java",
"snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class OrderDto {\n private List<ItemDto> itemDtoList;\n private Double cost;\n private String description;\n}"
},
{
"identifier": "Item",
"path": "src/main/java/by/bsu/rfict/WarehouseAccountingSystem/entity/Item.java",
"snippet": "@Entity\n@Table(name = \"items\")\n@Data\npublic class Item {\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n @Column(name = \"id\")\n private Long id;\n\n @Column(name = \"name\")\n private String name;\n\n @Column(name = \"description\", columnDefinition = \"text\")\n private String description;\n\n @Column(name = \"manufacturing_country\")\n private String manufacturingCountry;\n\n @Column(name = \"cost\")\n private int cost;\n\n @Column(name = \"weight\")\n private double weight;\n\n @JsonIgnore\n @ManyToMany(mappedBy = \"itemList\", fetch = FetchType.LAZY)\n private List<Order> orderList;\n}"
},
{
"identifier": "ItemService",
"path": "src/main/java/by/bsu/rfict/WarehouseAccountingSystem/service/ItemService.java",
"snippet": "@Service\n@AllArgsConstructor\n@Slf4j\npublic class ItemService {\n @Autowired\n private ItemRepository itemRepository;\n\n public Item findById(Long itemId) {\n Item item = itemRepository.findById(itemId).orElse(null);\n\n if (item == null) {\n log.info(\"findById - item with id {} didn't find\", itemId);\n\n return null;\n }\n log.info(\"findById - item with id {} successfully found\", itemId);\n\n return item;\n }\n\n public Item findByName(String itemName) {\n Item item = itemRepository.findItemByName(itemName);\n\n if (item == null) {\n log.info(\"findById - item with name {} didn't find\", itemName);\n\n return null;\n }\n log.info(\"findById - item with name {} successfully found\", itemName);\n\n return item;\n }\n\n public List<Item> findAll() {\n List<Item> itemList = itemRepository.findAll();\n log.info(\"findAll - found {} items\", itemList.size());\n\n return itemList;\n }\n\n public Item addItem(Item item) {\n Item newItem = itemRepository.save(item);\n log.info(\"addItem - item : {} successfully saved\", item);\n\n return newItem;\n }\n\n public Item updateItem(Item item, Item updatedItem) {\n BeanUtils.copyProperties(updatedItem, item, \"id\");\n itemRepository.save(item);\n log.info(\"updateItem - item : {} successfully updated\", item);\n\n return item;\n }\n\n public void deleteItem(Item item) {\n if (item == null) {\n log.info(\"deleteItem - item doesn't exist\");\n }\n\n itemRepository.delete(item);\n log.info(\"deleteItem - item : {} successfully deleted\", item);\n }\n}"
},
{
"identifier": "OrderService",
"path": "src/main/java/by/bsu/rfict/WarehouseAccountingSystem/service/OrderService.java",
"snippet": "@Service\n@AllArgsConstructor\n@Slf4j\npublic class OrderService {\n @Autowired\n private OrderRepository orderRepository;\n private UserService userService;\n\n public Order findById(Long orderId) {\n Order order = orderRepository.findById(orderId).orElse(null);\n\n if (order == null) {\n log.warn(\"findById - order : didn't found\");\n }\n log.info(\"findById - order : {} successfully found\", order);\n\n return order;\n }\n\n public List<Order> findAll() {\n List<Order> orderList = orderRepository.findAll();\n log.info(\"findAll - found {} orders\", orderList.size());\n\n return orderList;\n }\n\n public Order addOrder(Order order) {\n User user = userService.getUserByLogin();\n order.setUser(user);\n order = orderRepository.save(order);\n log.info(\"addOrder - order : {} successfully saved\");\n\n return order;\n }\n\n public void deleteOrder(Order order) {\n if (order == null) {\n log.info(\"deleteOrder - item doesn't exist\");\n }\n\n orderRepository.delete(order);\n log.info(\"deleteOrder - order : {} successfully deleted\", order);\n }\n\n public Order updateOrder(Order order, Order updatedOrder) {\n BeanUtils.copyProperties(updatedOrder, order, \"id\");\n orderRepository.save(order);\n log.info(\"updateOrder - order : {} successfully updated\", order);\n\n return order;\n }\n\n public double calcWeight(List<Item> itemList) {\n double orderWeight = 0;\n for (Item item : itemList) {\n orderWeight += item.getWeight();\n }\n return orderWeight;\n }\n\n public double calcCost(List<Item> itemList) {\n int orderCost = 0;\n for (Item item : itemList) {\n orderCost += item.getCost();\n }\n return orderCost;\n }\n}"
}
] | import by.bsu.rfict.WarehouseAccountingSystem.dto.ItemDto;
import by.bsu.rfict.WarehouseAccountingSystem.dto.OrderDto;
import by.bsu.rfict.WarehouseAccountingSystem.entity.Item;
import by.bsu.rfict.WarehouseAccountingSystem.service.ItemService;
import by.bsu.rfict.WarehouseAccountingSystem.service.OrderService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List; | 1,457 | package by.bsu.rfict.WarehouseAccountingSystem.mapper;
@Component
@AllArgsConstructor
public class ItemMapper {
@Autowired | package by.bsu.rfict.WarehouseAccountingSystem.mapper;
@Component
@AllArgsConstructor
public class ItemMapper {
@Autowired | private OrderService orderService; | 4 | 2023-10-20 07:50:29+00:00 | 2k |
RamirJunior/schedule-project | src/main/java/ramir/com/schedule/api/controller/UserController.java | [
{
"identifier": "UserRequestDto",
"path": "src/main/java/ramir/com/schedule/api/dto/user/UserRequestDto.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class UserRequestDto {\n\n @NotBlank(message = \"Name is required.\")\n private String name;\n\n @NotBlank(message = \"Lastname is required.\")\n private String lastname;\n\n @NotBlank(message = \"Email is required.\")\n @Email\n private String email;\n private String phone;\n}"
},
{
"identifier": "UserResponseDto",
"path": "src/main/java/ramir/com/schedule/api/dto/user/UserResponseDto.java",
"snippet": "@Data\npublic class UserResponseDto {\n private UUID id;\n private String name;\n private String lastname;\n private String email;\n private String phone;\n}"
},
{
"identifier": "UserMapper",
"path": "src/main/java/ramir/com/schedule/api/mapper/UserMapper.java",
"snippet": "@Component\n@RequiredArgsConstructor\npublic class UserMapper {\n\n private final ModelMapper mapper;\n\n public User toUser(UserRequestDto request) {\n return mapper.map(request, User.class);\n }\n\n public UserResponseDto toUserResponse(User user) {\n return mapper.map(user, UserResponseDto.class);\n }\n\n public List<UserResponseDto> toUserResponseList(List<User> users) {\n return users.stream()\n .map(this::toUserResponse)\n .collect(Collectors.toList());\n }\n}"
},
{
"identifier": "User",
"path": "src/main/java/ramir/com/schedule/domain/entity/User.java",
"snippet": "@Data\n@Entity(name = \"users\")\npublic class User {\n\n @Id\n @GeneratedValue(strategy = GenerationType.UUID)\n private UUID id;\n private String name;\n private String lastname;\n @Email\n private String email;\n private String phone;\n\n}"
},
{
"identifier": "UserService",
"path": "src/main/java/ramir/com/schedule/domain/service/UserService.java",
"snippet": "@Service\n@Transactional\n@RequiredArgsConstructor\npublic class UserService {\n\n private final UserRepository userRepository;\n\n public Optional<User> saveUser(User user) {\n if (isRegisteredEmail(user.getEmail()))\n return Optional.empty();\n\n return Optional.of(userRepository.save(user));\n }\n\n private boolean isRegisteredEmail(String email) {\n var emailFound = userRepository.findByEmail(email);\n return emailFound.isPresent();\n }\n\n public List<User> getUsers() {\n return userRepository.findAll();\n }\n\n public Optional<User> getUser(UUID id) {\n return userRepository.findById(id);\n }\n\n public Optional<User> updateUser(User userReceived, UUID id) {\n Optional<User> userFound = userRepository.findById(id);\n if (userFound.isEmpty())\n return userFound;\n\n copyValidAttributes(userReceived, userFound.get());\n var userUpdated = userRepository.save(userFound.get());\n return Optional.of(userUpdated);\n }\n\n private static void copyValidAttributes(User userSource, User userDestination) {\n if (userSource.getName() != null)\n userDestination.setName(userSource.getName());\n if (userSource.getLastname() != null)\n userDestination.setLastname(userSource.getLastname());\n if (userSource.getEmail() != null)\n userDestination.setEmail(userSource.getEmail());\n if (userSource.getPhone() != null)\n userDestination.setPhone(userSource.getPhone());\n }\n\n public Optional<User> deleteUser(UUID id) {\n Optional<User> userFound = userRepository.findById(id);\n if (userFound.isEmpty())\n return Optional.empty();\n\n userRepository.deleteById(id);\n return userFound;\n }\n}"
}
] | import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ramir.com.schedule.api.dto.user.UserRequestDto;
import ramir.com.schedule.api.dto.user.UserResponseDto;
import ramir.com.schedule.api.mapper.UserMapper;
import ramir.com.schedule.domain.entity.User;
import ramir.com.schedule.domain.service.UserService;
import java.util.List;
import java.util.Optional;
import java.util.UUID; | 981 | package ramir.com.schedule.api.controller;
@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
public class UserController {
private final UserService userService;
private final UserMapper userMapper;
@PostMapping | package ramir.com.schedule.api.controller;
@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
public class UserController {
private final UserService userService;
private final UserMapper userMapper;
@PostMapping | public ResponseEntity<UserResponseDto> save(@Valid @RequestBody UserRequestDto userRequest) { | 0 | 2023-10-19 13:34:10+00:00 | 2k |
zendo-games/zenlib | src/test/java/zendo/games/zenlib/ZenlibMainTest.java | [
{
"identifier": "ZenScreen",
"path": "src/main/java/zendo/games/zenlib/screens/ZenScreen.java",
"snippet": "public abstract class ZenScreen implements Disposable {\n\n public final SpriteBatch batch;\n public final TweenManager tween;\n public final OrthographicCamera windowCamera;\n public final Vector3 pointerPos;\n\n protected OrthographicCamera worldCamera;\n protected Viewport viewport;\n protected Stage uiStage;\n protected Skin skin;\n protected boolean exitingScreen;\n\n public ZenScreen() {\n var main = ZenMain.instance;\n\n this.batch = main.assets.batch;\n this.tween = main.tween;\n this.windowCamera = main.windowCamera;\n this.pointerPos = new Vector3();\n this.worldCamera = new OrthographicCamera();\n this.viewport = new ScreenViewport(worldCamera);\n this.viewport.update(main.config.window.width, main.config.window.height, true);\n this.exitingScreen = false;\n\n initializeUI();\n }\n\n @Override\n public void dispose() {}\n\n public void resize(int width, int height) {\n viewport.update(width, height, true);\n }\n\n /**\n * Update something in the screen even when\n * {@code Time.pause_for()} is being processed\n * @param dt the time in seconds since the last frame\n */\n public void alwaysUpdate(float dt) {}\n\n public void update(float dt) {\n windowCamera.update();\n worldCamera.update();\n uiStage.act(dt);\n }\n\n public void renderFrameBuffers(SpriteBatch batch) {}\n\n public abstract void render(SpriteBatch batch);\n\n protected void initializeUI() {\n skin = VisUI.getSkin();\n\n var viewport = new ScreenViewport(windowCamera);\n uiStage = new Stage(viewport, batch);\n\n // extend and setup any per-screen ui widgets in here...\n }\n}"
},
{
"identifier": "ZenTextButton",
"path": "src/main/java/zendo/games/zenlib/ui/ZenTextButton.java",
"snippet": "public class ZenTextButton extends VisTextButton {\n public TextButtonStyle style;\n\n public ZenTextButton(String text) {\n super(text);\n setFocusBorderEnabled(false);\n style = new TextButtonStyle(getStyle());\n style.up = ZenPatch.glass.ninePatchDrawable;\n style.over = ZenPatch.glass_active.ninePatchDrawable;\n style.down = ZenPatch.glass_dim.ninePatchDrawable;\n setStyle(style);\n }\n\n public ZenTextButton(float x, float y, String text) {\n this(text);\n setPosition(x, y);\n }\n\n public ZenTextButton(float x, float y, float width, float height, String text) {\n this(x, y, text);\n setSize(width, height);\n }\n}"
},
{
"identifier": "ZenWindow",
"path": "src/main/java/zendo/games/zenlib/ui/ZenWindow.java",
"snippet": "public class ZenWindow extends VisWindow {\n public WindowStyle style;\n\n /**\n * Creates a window that is not movable or resizable.\n */\n public ZenWindow() {\n super(\"\");\n setMovable(false);\n setResizable(false);\n setModal(true);\n style = new WindowStyle(getStyle());\n style.background = ZenPatch.glass_red.ninePatchDrawable;\n setStyle(style);\n }\n\n /**\n * Creates a window with width and height. Set position to center of parent.\n */\n public ZenWindow(float width, float height) {\n this();\n setSize(width, height);\n setCenterOnAdd(true);\n }\n\n /**\n * Creates a window with width and height. Set position to x, y.\n */\n public ZenWindow(float x, float y, float width, float height) {\n this();\n setSize(width, height);\n setPosition(x, y);\n }\n}"
}
] | import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ScreenUtils;
import com.badlogic.gdx.utils.viewport.StretchViewport;
import space.earlygrey.shapedrawer.ShapeDrawer;
import zendo.games.zenlib.physics.*;
import zendo.games.zenlib.screens.ZenScreen;
import zendo.games.zenlib.ui.ZenTextButton;
import zendo.games.zenlib.ui.ZenWindow; | 1,378 | package zendo.games.zenlib;
public class ZenlibMainTest extends ZenMain<ZenlibMainTest.Assets> {
public static final ZenConfig config = new ZenConfig();
public static ZenlibMainTest game;
public ZenlibMainTest() {
super(config);
ZenlibMainTest.game = this;
}
@Override
public Assets createAssets() {
return new Assets();
}
@Override
public ZenScreen createStartScreen() {
return new TestScreen1();
}
// ------------------------------------------------------------------------
// Test Assets (from src/test/resources)
// ------------------------------------------------------------------------
public static class Assets extends ZenAssets {
Texture gdx;
@Override
public void loadManagerAssets() {
mgr.load("libgdx.png", Texture.class);
}
@Override
public void initCachedAssets() {
gdx = mgr.get("libgdx.png", Texture.class);
}
}
// ------------------------------------------------------------------------
// Test Screen
// ------------------------------------------------------------------------
public static class TestScreen1 extends ZenScreen {
public TestScreen1() {
// override the default 'ScreenViewport'
int screenWidth = config.window.width / 2;
int screenHeight = config.window.height / 2;
this.viewport = new StretchViewport(screenWidth, screenHeight, worldCamera);
this.viewport.apply(true);
Gdx.input.setInputProcessor(uiStage);
}
@Override
protected void initializeUI() {
super.initializeUI();
| package zendo.games.zenlib;
public class ZenlibMainTest extends ZenMain<ZenlibMainTest.Assets> {
public static final ZenConfig config = new ZenConfig();
public static ZenlibMainTest game;
public ZenlibMainTest() {
super(config);
ZenlibMainTest.game = this;
}
@Override
public Assets createAssets() {
return new Assets();
}
@Override
public ZenScreen createStartScreen() {
return new TestScreen1();
}
// ------------------------------------------------------------------------
// Test Assets (from src/test/resources)
// ------------------------------------------------------------------------
public static class Assets extends ZenAssets {
Texture gdx;
@Override
public void loadManagerAssets() {
mgr.load("libgdx.png", Texture.class);
}
@Override
public void initCachedAssets() {
gdx = mgr.get("libgdx.png", Texture.class);
}
}
// ------------------------------------------------------------------------
// Test Screen
// ------------------------------------------------------------------------
public static class TestScreen1 extends ZenScreen {
public TestScreen1() {
// override the default 'ScreenViewport'
int screenWidth = config.window.width / 2;
int screenHeight = config.window.height / 2;
this.viewport = new StretchViewport(screenWidth, screenHeight, worldCamera);
this.viewport.apply(true);
Gdx.input.setInputProcessor(uiStage);
}
@Override
protected void initializeUI() {
super.initializeUI();
| var window = new ZenWindow(300f, 400f); | 2 | 2023-10-21 19:36:50+00:00 | 2k |
tuna-pizza/GraphXings | src/GraphXings/Game/GameState.java | [
{
"identifier": "Coordinate",
"path": "src/GraphXings/Data/Coordinate.java",
"snippet": "public class Coordinate\r\n{\r\n private int x;\r\n private int y;\r\n /**\r\n * Constructs an integer Coordinate object\r\n * @param x The x-coordinate.\r\n * @param y The y-coordinate.\r\n */\r\n public Coordinate(int x, int y)\r\n {\r\n this.x = x;\r\n this.y = y;\r\n }\r\n\r\n /**\r\n * Returns the x-coordinate.\r\n * @return The x-coordinate.\r\n */\r\n public int getX()\r\n {\r\n return x;\r\n }\r\n\r\n /**\r\n * Returns the y-coordinate.\r\n * @return The y-coordinate.\r\n */\r\n public int getY()\r\n {\r\n return y;\r\n }\r\n\r\n /**\r\n * Decides whether this and the Coordinate other are the same.\r\n * @param other Another coordinate.\r\n * @return True, if this equals other, false otherwise.\r\n */\r\n public boolean equals (Coordinate other)\r\n {\r\n return ((this.x == other.x) && (this.y == other.y));\r\n }\r\n}\r"
},
{
"identifier": "Graph",
"path": "src/GraphXings/Data/Graph.java",
"snippet": "public class Graph\r\n{\r\n /**\r\n * The vertex set.\r\n */\r\n private HashSet<Vertex> vertices;\r\n /**\r\n * The edge set.\r\n */\r\n private HashSet<Edge> edges;\r\n /**\r\n * The adjacency list representation.\r\n */\r\n private HashMap<Vertex,HashSet<Edge>> adjacentEdges;\r\n /**\r\n * The number of vertices.\r\n */\r\n private int n;\r\n /**\r\n * The number of edges.\r\n */\r\n private int m;\r\n\r\n /**\r\n * Initializes an empty graph.\r\n */\r\n public Graph()\r\n {\r\n vertices = new HashSet<>();\r\n edges = new HashSet<>();\r\n adjacentEdges = new HashMap<>();\r\n n = 0;\r\n m = 0;\r\n }\r\n\r\n /**\r\n * Adds a vertex to the graph.\r\n * @param v The vertex to be added.\r\n */\r\n public void addVertex(Vertex v)\r\n {\r\n if (!vertices.contains(v))\r\n {\r\n vertices.add(v);\r\n adjacentEdges.put(v,new HashSet<>());\r\n n++;\r\n }\r\n }\r\n\r\n /**\r\n * Add an edge to the graph.\r\n * @param e The edge to be added.\r\n * @return True, if the edge was successfully added, false otherwise.\r\n */\r\n public boolean addEdge(Edge e)\r\n {\r\n if (vertices.contains(e.getS())&&vertices.contains(e.getT()))\r\n {\r\n if (!adjacentEdges.get(e.getS()).contains(e))\r\n {\r\n adjacentEdges.get(e.getS()).add(e);\r\n adjacentEdges.get(e.getT()).add(e);\r\n edges.add(e);\r\n m++;\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * Gets the vertex set.\r\n * @return An Iterable over the vertex set.\r\n */\r\n public Iterable<Vertex> getVertices()\r\n {\r\n return vertices;\r\n }\r\n\r\n /**\r\n * Returns the edges incident to a specified vertex.\r\n * @param v The vertex whose adjacent edges are queried.\r\n * @return An Iterable over the edges incident to Vertex v.\r\n */\r\n public Iterable<Edge> getIncidentEdges(Vertex v)\r\n {\r\n if (!vertices.contains(v))\r\n {\r\n return null;\r\n }\r\n return adjacentEdges.get(v);\r\n }\r\n\r\n /**\r\n * Returns the edges of the graph.\r\n * @return An Iterable over the edge set.\r\n */\r\n public Iterable<Edge> getEdges()\r\n {\r\n return edges;\r\n }\r\n\r\n /**\r\n * Get the number of vertices.\r\n * @return The number of vertices.\r\n */\r\n public int getN()\r\n {\r\n return n;\r\n }\r\n\r\n /**\r\n * Gets the number of edges.\r\n * @return The number of edges.\r\n */\r\n public int getM()\r\n {\r\n return m;\r\n }\r\n\r\n /**\r\n * Creates a functionally equivalent copy of the graph that uses different references.\r\n * @return A Graph object containing a copy of the graph.\r\n */\r\n public Graph copy()\r\n {\r\n Graph copy = new Graph();\r\n for (Vertex v : vertices)\r\n {\r\n copy.addVertex(v);\r\n }\r\n for (Edge e : edges)\r\n {\r\n copy.addEdge(e);\r\n }\r\n return copy;\r\n }\r\n\r\n /**\r\n * Shuffles the order of vertices in the vertex set.\r\n */\r\n public void shuffleIndices()\r\n {\r\n List<Vertex> toBeShuffled = new ArrayList<>(vertices);\r\n Collections.shuffle(toBeShuffled);\r\n vertices = new HashSet<>(toBeShuffled);\r\n }\r\n\r\n /**\r\n * Provides the adjacency list representation of the graph.\r\n * @return The adjacency list representation.\r\n */\r\n @Override\r\n public String toString()\r\n {\r\n String out = \"\";\r\n for (Vertex v : vertices)\r\n {\r\n out += v.getId() + \": [\";\r\n for (Edge e: adjacentEdges.get(v))\r\n {\r\n out += \"(\" + e.getS().getId() +\",\" + e.getT().getId() +\"),\";\r\n }\r\n out += \"]\\n\";\r\n }\r\n return out;\r\n }\r\n}\r"
},
{
"identifier": "Vertex",
"path": "src/GraphXings/Data/Vertex.java",
"snippet": "public class Vertex\r\n{\r\n /**\r\n * The ID of the vertex.\r\n */\r\n private String id;\r\n\r\n /**\r\n * Creates a vertex with a given ID.\r\n * @param id The provided ID.\r\n */\r\n public Vertex(String id)\r\n {\r\n this.id = id;\r\n }\r\n\r\n /**\r\n * Gets the ID of the vertex.\r\n * @return The ID of the vertex.\r\n */\r\n public String getId()\r\n {\r\n return id;\r\n }\r\n}\r"
}
] | import GraphXings.Data.Coordinate;
import GraphXings.Data.Graph;
import GraphXings.Data.Vertex;
import java.util.HashMap;
import java.util.HashSet; | 1,500 | package GraphXings.Game;
/**
* A class describing the current state of the game.
*/
public class GameState
{
/**
* The set of vertices contained in the graph.
*/ | package GraphXings.Game;
/**
* A class describing the current state of the game.
*/
public class GameState
{
/**
* The set of vertices contained in the graph.
*/ | private HashSet<Vertex> vertices; | 2 | 2023-10-18 12:11:38+00:00 | 2k |
rafaelmachadobr/LivrariaDigital | src/main/java/br/com/rafael/livrariadigital/service/UsuarioService.java | [
{
"identifier": "BusinessException",
"path": "src/main/java/br/com/rafael/livrariadigital/handler/BusinessException.java",
"snippet": "public class BusinessException extends RuntimeException {\n public BusinessException(String mensagem) {\n super(mensagem);\n }\n public BusinessException(String mensagem, Object... params) {\n super(String.format(mensagem, params));\n }\n}"
},
{
"identifier": "Endereco",
"path": "src/main/java/br/com/rafael/livrariadigital/model/Endereco.java",
"snippet": "@Table(name = \"endereco\")\n@Entity\n@Data\npublic class Endereco {\n @Id\n private String cep;\n private String logradouro;\n private String complemento;\n private String bairro;\n private String localidade;\n private String uf;\n private String ibge;\n private String gia;\n private String ddd;\n private String siafi;\n}"
},
{
"identifier": "Usuario",
"path": "src/main/java/br/com/rafael/livrariadigital/model/Usuario.java",
"snippet": "@Entity\n@Data\npublic class Usuario {\n @Id\n @GeneratedValue(strategy = GenerationType.UUID)\n private UUID id;\n\n @Column(nullable = false)\n @NotBlank(message = \"O nome do usuário é obrigatório\")\n private String nome;\n\n @Column(nullable = false, unique = true)\n @NotBlank(message = \"O email do usuário é obrigatório\")\n @Pattern(regexp = \"[a-z0-9._%+-]+@[a-z0-9.-]+\\\\.[a-z]{2,4}\", message = \"O email deve estar no formato adequado\")\n private String email;\n\n @Column(nullable = false, unique = true)\n @NotBlank(message = \"O telefone do usuário é obrigatório\")\n @Pattern(regexp = \"\\\\([0-9]{2}\\\\) [0-9]{4,5}-[0-9]{4}\", message = \"O telefone deve estar no formato (99) 99999-9999\")\n private String telefone;\n\n @Column(nullable = false)\n @NotBlank(message = \"A senha do usuário é obrigatória\")\n @Size(min = 8, message = \"A senha deve conter pelo menos 8 caracteres (excluindo espaços em branco)\")\n @Pattern(regexp = \"^\\\\S{8,}$\", message = \"A senha não pode conter espaços em branco\")\n private String senha;\n\n @Column(nullable = false)\n @NotNull(message = \"A data de nascimento do usuário é obrigatória\")\n private Date dataNascimento;\n\n @ManyToOne\n @JoinColumn(nullable = false)\n @NotNull(message = \"O endereço do usuário é obrigatório\")\n private Endereco endereco;\n}"
},
{
"identifier": "EnderecoRepository",
"path": "src/main/java/br/com/rafael/livrariadigital/repository/EnderecoRepository.java",
"snippet": "public interface EnderecoRepository extends JpaRepository<Endereco, String> {\n}"
},
{
"identifier": "UsuarioRepository",
"path": "src/main/java/br/com/rafael/livrariadigital/repository/UsuarioRepository.java",
"snippet": "public interface UsuarioRepository extends JpaRepository<Usuario, UUID> {\n}"
}
] | import br.com.rafael.livrariadigital.handler.BusinessException;
import br.com.rafael.livrariadigital.model.Endereco;
import br.com.rafael.livrariadigital.model.Usuario;
import br.com.rafael.livrariadigital.repository.EnderecoRepository;
import br.com.rafael.livrariadigital.repository.UsuarioRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.UUID; | 937 | package br.com.rafael.livrariadigital.service;
@Service
public class UsuarioService {
private final UsuarioRepository usuarioRepository;
private final EnderecoRepository enderecoRepository;
private final ViaCepService viaCepService;
@Autowired
public UsuarioService(UsuarioRepository usuarioRepository, EnderecoRepository enderecoRepository, ViaCepService viaCepService) {
this.usuarioRepository = usuarioRepository;
this.enderecoRepository = enderecoRepository;
this.viaCepService = viaCepService;
}
| package br.com.rafael.livrariadigital.service;
@Service
public class UsuarioService {
private final UsuarioRepository usuarioRepository;
private final EnderecoRepository enderecoRepository;
private final ViaCepService viaCepService;
@Autowired
public UsuarioService(UsuarioRepository usuarioRepository, EnderecoRepository enderecoRepository, ViaCepService viaCepService) {
this.usuarioRepository = usuarioRepository;
this.enderecoRepository = enderecoRepository;
this.viaCepService = viaCepService;
}
| public List<Usuario> buscarTodos() { | 2 | 2023-10-18 22:34:45+00:00 | 2k |
Primogem-Craft-Development/Primogem-Craft-Fabric | src/main/java/com/primogemstudio/primogemcraft/items/instances/materials/vajrada/OnArmorTick.java | [
{
"identifier": "PrimogemCraftMobEffects",
"path": "src/main/java/com/primogemstudio/primogemcraft/effects/PrimogemCraftMobEffects.java",
"snippet": "public class PrimogemCraftMobEffects {\n public static final AbnormalDiseaseMobEffect ABNORMAL_DISEASE = register(\"abnormal_disease\", new AbnormalDiseaseMobEffect());\n public static final PastMobEffect PAST = register(\"past\", new PastMobEffect());\n public static final AmulateMobEffect AMULATE = register(\"amulate\", new AmulateMobEffect());\n public static final AThousandNightsDawnsongMobEffect DAWNSONG = register(\"a_thousand_nights_dawnsong\", new AThousandNightsDawnsongMobEffect());\n public static final AThousandNightsDawnsongCooldownMobEffect DAWNSONG_COOLDOWN = register(\"a_thousand_nights_dawnsong_cooldown\", new AThousandNightsDawnsongCooldownMobEffect());\n public static final FlyingMobEffect FLYING = register(\"flying\", new FlyingMobEffect());\n public static final BurnMobEffect BURN = register(\"burn\", new BurnMobEffect());\n public static void init() {\n }\n\n public static <T extends MobEffect> T register(String id, T effect) {\n return Registry.register(BuiltInRegistries.MOB_EFFECT, new ResourceLocation(MOD_ID, id), effect);\n }\n}"
},
{
"identifier": "ArmorHelper",
"path": "src/main/java/com/primogemstudio/primogemcraft/items/instances/materials/common/ArmorHelper.java",
"snippet": "public class ArmorHelper {\n public static double getArmorValue(LivingEntity entity, ItemStack itemstack) {\n setArmorValue(itemstack);\n return entity.getItemBySlot(EquipmentSlot.FEET).getOrCreateTag().getDouble(\"armor_value\") + entity.getItemBySlot(EquipmentSlot.LEGS).getOrCreateTag().getDouble(\"armor_value\") + entity.getItemBySlot(EquipmentSlot.CHEST).getOrCreateTag().getDouble(\"armor_value\") + entity.getItemBySlot(EquipmentSlot.HEAD).getOrCreateTag().getDouble(\"armor_value\");\n }\n\n public static void setArmorValue(ItemStack itemstack) {\n if (!itemstack.getOrCreateTag().getBoolean(\"armor_value\")) {\n if (itemstack.is(ELEMENT_IRON)) itemstack.getOrCreateTag().putDouble(\"armor_value\", 0.5);\n if (itemstack.is(ELEMENT_DIAMOND)) itemstack.getOrCreateTag().putDouble(\"armor_value\", 1);\n if (itemstack.is(ELEMENT_NETHERITE)) itemstack.getOrCreateTag().putDouble(\"armor_value\", 2);\n }\n }\n}"
}
] | import com.primogemstudio.primogemcraft.effects.PrimogemCraftMobEffects;
import com.primogemstudio.primogemcraft.items.instances.materials.common.ArmorHelper;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.LevelAccessor; | 791 | package com.primogemstudio.primogemcraft.items.instances.materials.vajrada;
public class OnArmorTick {
public static void execute(LevelAccessor world, Entity entity, ItemStack itemstack) {
if (!entity.level().isClientSide) {
var le = (LivingEntity) entity;
var armor_value = ArmorHelper.getArmorValue(le, itemstack); | package com.primogemstudio.primogemcraft.items.instances.materials.vajrada;
public class OnArmorTick {
public static void execute(LevelAccessor world, Entity entity, ItemStack itemstack) {
if (!entity.level().isClientSide) {
var le = (LivingEntity) entity;
var armor_value = ArmorHelper.getArmorValue(le, itemstack); | if (le.hasEffect(PrimogemCraftMobEffects.AMULATE) && armor_value >= 2) { | 0 | 2023-10-15 08:07:06+00:00 | 2k |
turtleisaac/PokEditor | src/main/java/io/github/turtleisaac/pokeditor/gui/sheets/tables/FrozenColumnTable.java | [
{
"identifier": "DefaultSheetCellRenderer",
"path": "src/main/java/io/github/turtleisaac/pokeditor/gui/sheets/tables/cells/renderers/DefaultSheetCellRenderer.java",
"snippet": "public class DefaultSheetCellRenderer extends DefaultTableCellRenderer\n{\n public DefaultSheetCellRenderer()\n {\n super();\n }\n\n @Override\n public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)\n {\n super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);\n\n if (isSelected || table.getSelectedRow() == row) {\n Border border = UIManager.getBorder(\"Table.focusCellHighlightBorder\");\n setBorder(border);\n if (!isSelected)\n {\n setBackground(UIManager.getColor(\"Table.selectionInactiveBackground\"));\n }\n else\n {\n setBackground(UIManager.getColor(\"Component.custom.borderColor\"));\n }\n\n }\n else {\n if (row % 2 == 0)\n setBackground(table.getBackground());\n else\n setBackground(UIManager.getColor(\"TableHeader.pressedBackground\"));\n }\n\n// if (isSelected || table.getSelectedRow() == row) {\n// setBackground(table.getSelectionBackground());\n// } else {\n// setForeground(getForeground());\n\n// }\n// setBorder(BorderFactory.createCompoundBorder());\n\n return this;\n }\n}"
},
{
"identifier": "MultiLineTableHeaderRenderer",
"path": "src/main/java/io/github/turtleisaac/pokeditor/gui/sheets/tables/cells/renderers/MultiLineTableHeaderRenderer.java",
"snippet": "public class MultiLineTableHeaderRenderer extends JTextArea implements TableCellRenderer\n{\n public MultiLineTableHeaderRenderer()\n {\n setEditable(false);\n setLineWrap(true);\n setOpaque(false);\n setFocusable(false);\n setWrapStyleWord(true);\n LookAndFeel.installBorder(this, \"TableHeader.cellBorder\");\n }\n\n @Override\n public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)\n {\n int width = table.getColumnModel().getColumn(column).getWidth();\n setText(String.valueOf(value));\n setSize(width, getPreferredSize().height);\n if (table.getSelectedColumn() == column)\n {\n setForeground(UIManager.getColor(\"Component.custom.borderColor\"));\n }\n else {\n setForeground(UIManager.getColor(\"TableHeader.foreground\"));\n }\n return this;\n }\n}"
}
] | import io.github.turtleisaac.pokeditor.formats.GenericFileData;
import io.github.turtleisaac.pokeditor.gui.sheets.tables.cells.renderers.DefaultSheetCellRenderer;
import io.github.turtleisaac.pokeditor.gui.sheets.tables.cells.renderers.MultiLineTableHeaderRenderer;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import java.awt.*;
import java.util.Enumeration; | 866 | package io.github.turtleisaac.pokeditor.gui.sheets.tables;
public class FrozenColumnTable<E extends GenericFileData> extends JTable
{
public FrozenColumnTable(TableModel model)
{
super(model);
setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
setRowMargin(1);
getColumnModel().setColumnMargin(1);
setShowGrid(true);
setGridColor(Color.black);
setShowHorizontalLines(true);
setShowVerticalLines(true);
TableColumn col = getColumnModel().getColumn(0);
col.setWidth(35);
col.setPreferredWidth(35);
// for (int i = 0; i < getColumnCount(); i++)
// {
// CellTypes c = cellTypes[i];
// TableColumn col = getColumnModel().getColumn(i);
// col.setWidth(widths[i]);
// col.setPreferredWidth(widths[i]);
// }
| package io.github.turtleisaac.pokeditor.gui.sheets.tables;
public class FrozenColumnTable<E extends GenericFileData> extends JTable
{
public FrozenColumnTable(TableModel model)
{
super(model);
setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
setRowMargin(1);
getColumnModel().setColumnMargin(1);
setShowGrid(true);
setGridColor(Color.black);
setShowHorizontalLines(true);
setShowVerticalLines(true);
TableColumn col = getColumnModel().getColumn(0);
col.setWidth(35);
col.setPreferredWidth(35);
// for (int i = 0; i < getColumnCount(); i++)
// {
// CellTypes c = cellTypes[i];
// TableColumn col = getColumnModel().getColumn(i);
// col.setWidth(widths[i]);
// col.setPreferredWidth(widths[i]);
// }
| MultiLineTableHeaderRenderer renderer = new MultiLineTableHeaderRenderer(); | 1 | 2023-10-15 05:00:57+00:00 | 2k |
dashorst/funwithflags | src/main/java/fwf/turn/Turn.java | [
{
"identifier": "Game",
"path": "src/main/java/fwf/game/Game.java",
"snippet": "@Dependent\npublic class Game {\n @Inject\n Instance<Turn> turnFactory;\n\n @Inject\n Event<GameFinished> gameFinished;\n\n @Inject\n Event<TurnStarted> turnStarted;\n\n @Inject\n Event<TurnSwitched> turnSwitched;\n\n @Inject\n Event<TurnFinished> turnFinished;\n\n @Inject\n CountryRepository countryRepository;\n\n private List<Player> players = Collections.emptyList();\n private List<Turn> turns = new ArrayList<>();\n\n private String playerNames;\n \n private int secondsPerResult;\n\n private boolean gameOver = false;\n\n private Turn currentTurn = null;\n\n public Game() {\n }\n\n public void init(List<Player> playersInLobby, int numberOfTurns, int secondsPerTurn, int secondsPerResult) {\n this.players = playersInLobby;\n this.playerNames = players.stream().map(Player::name).toList().toString();\n this.secondsPerResult = secondsPerResult;\n\n var countries = new ArrayList<>(countryRepository.countries());\n Collections.shuffle(countries);\n\n for (int i = 0; i < numberOfTurns; i++) {\n var turn = turnFactory.get();\n\n turn.init(this, i + 1, countries.get(i), secondsPerTurn, secondsPerResult);\n turns.add(turn);\n }\n currentTurn = turns.get(0);\n turnStarted.fire(new TurnStarted(this, currentTurn));\n }\n\n public List<Turn> turns() {\n return turns;\n }\n\n public boolean isGameOver() {\n return gameOver;\n }\n\n public int numberOfTurns() {\n return turns.size();\n }\n\n public int turnNumber() {\n if (currentTurn == null)\n return numberOfTurns();\n return turns.indexOf(currentTurn) + 1;\n }\n\n public Collection<Player> players() {\n return Collections.unmodifiableCollection(players);\n }\n\n public List<Score> scores() {\n var scores = new ArrayList<Score>();\n for (Player player : players) {\n int score = 0;\n for (Turn turn : turns) {\n score += turn.scoreForPlayer(player);\n }\n scores.add(new Score(this, player, score));\n }\n Collections.sort(scores, Comparator.comparing(Score::score, Comparator.reverseOrder()));\n return scores;\n }\n\n public Optional<Turn> currentTurn() {\n return Optional.ofNullable(currentTurn);\n }\n\n // todo observe ClockTick event\n public void onTick() {\n if (gameOver)\n return;\n\n if (currentTurn == null)\n return;\n\n if (currentTurn.isDone()) {\n if (!currentTurn.isResultDone()) {\n // fire turn finished only once\n if (currentTurn.resultsSecondsLeft() == secondsPerResult)\n turnFinished.fire(new TurnFinished(this, currentTurn));\n\n currentTurn.tick();\n Log.debugf(\"Game ticked: %s, turn: #%d, results left: %ds\",\n players().stream().map(Player::name).toList(), turnNumber(), currentTurn.resultsSecondsLeft());\n } else {\n var previousTurn = currentTurn;\n var nextTurn = turns.stream().filter(t -> !t.isDone()).findFirst();\n if (nextTurn.isPresent()) {\n currentTurn = nextTurn.get();\n turnSwitched.fire(new TurnSwitched(this, previousTurn, currentTurn));\n turnStarted.fire(new TurnStarted(this, currentTurn));\n } else {\n gameOver = true;\n gameFinished.fire(new GameFinished(this, \"Game over\"));\n }\n }\n } else {\n Log.debugf(\"Game ticked: %s, turn: #%d, seconds left: %ds\", players().stream().map(Player::name).toList(),\n turnNumber(), currentTurn.secondsLeft());\n currentTurn.tick();\n }\n }\n\n void onPlayerUnregistered(@Observes PlayerUnregistered event) {\n var playerToRemove = event.player();\n if (players.remove(playerToRemove)) {\n if (players.size() <= 1) {\n gameOver = true;\n // fire game over\n gameFinished.fire(new GameFinished(this, \"Last player standing\"));\n }\n }\n }\n\n void onGameDestroyed(@Observes GameDestroyed event) {\n for (Turn turn : event.game().turns) {\n turnFactory.destroy(turn);\n }\n event.game().turns.clear();\n }\n\n @Override\n public String toString() {\n return playerNames + \", turn \" + turnNumber();\n }\n}"
},
{
"identifier": "Player",
"path": "src/main/java/fwf/player/Player.java",
"snippet": "@Dependent\npublic class Player {\n private String id;\n private Session session;\n private String name;\n\n public void init(Session session, String name) {\n this.session = session;\n this.name = name;\n this.id = session.getId() + \"|\" + name;\n }\n\n public Session session() {\n return session;\n }\n\n public String name() {\n return name;\n }\n\n @Override\n public String toString() {\n return id;\n }\n\n @Override\n public int hashCode() {\n return Objects.hashCode(session);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj instanceof Player other) {\n return Objects.equals(this.session(), other.session());\n }\n return false;\n }\n}"
}
] | import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import fwf.country.Country;
import fwf.game.Game;
import fwf.guess.Guess;
import fwf.player.Player;
import fwf.player.PlayerGuessed;
import io.quarkus.logging.Log;
import jakarta.enterprise.event.Event;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject; | 1,493 | package fwf.turn;
public class Turn {
@Inject
Event<TurnClockTicked> clockTicked;
@Inject
Event<TurnGuessRecorded> guessRecorded;
| package fwf.turn;
public class Turn {
@Inject
Event<TurnClockTicked> clockTicked;
@Inject
Event<TurnGuessRecorded> guessRecorded;
| private Game game; | 0 | 2023-10-17 19:10:37+00:00 | 2k |
Amanastel/Hotel-Management-Microservices | hotelServices/src/main/java/com/lcwd/hotel/service/Impl/hotelServiceImpl.java | [
{
"identifier": "Hotel",
"path": "hotelServices/src/main/java/com/lcwd/hotel/entities/Hotel.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\n@Entity\n@Table(name = \"HOTELS\")\npublic class Hotel {\n @Id\n private String id;\n private String name;\n private String location;\n private String about;\n @OneToMany(mappedBy = \"hotel\", cascade = CascadeType.ALL)\n private List<Room> rooms;\n @OneToMany(mappedBy = \"hotel\", cascade = CascadeType.ALL)\n private List<Booking> bookings;\n\n}"
},
{
"identifier": "Room",
"path": "hotelServices/src/main/java/com/lcwd/hotel/entities/Room.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\n@Entity\npublic class Room {\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private Integer roomId;\n private String roomType;\n private String roomNumber;\n private Integer roomPrice;\n private Status Status;\n private String roomDescription;\n @ManyToOne\n @JsonIgnore\n private Hotel hotel;\n\n}"
},
{
"identifier": "Status",
"path": "hotelServices/src/main/java/com/lcwd/hotel/entities/Status.java",
"snippet": "public enum Status {\n AVAILABLE, BOOKED\n}"
},
{
"identifier": "NotFoundException",
"path": "hotelServices/src/main/java/com/lcwd/hotel/exception/NotFoundException.java",
"snippet": "public class NotFoundException extends RuntimeException{\r\n\t\r\n\tpublic NotFoundException(String str){\r\n\t\tsuper(str) ;\r\n\t}\r\n\r\n}\r"
},
{
"identifier": "BookingRepository",
"path": "hotelServices/src/main/java/com/lcwd/hotel/repository/BookingRepository.java",
"snippet": "@Repository\npublic interface BookingRepository extends JpaRepository<Booking, String> {\n\n}"
},
{
"identifier": "HotelRepository",
"path": "hotelServices/src/main/java/com/lcwd/hotel/repository/HotelRepository.java",
"snippet": "@Repository\npublic interface HotelRepository extends JpaRepository<Hotel, String> {\n public List<Hotel> findByLocation(String location);\n public Hotel findByName(String name);\n}"
},
{
"identifier": "RoomRepository",
"path": "hotelServices/src/main/java/com/lcwd/hotel/repository/RoomRepository.java",
"snippet": "public interface RoomRepository extends JpaRepository<Room, String> {\n}"
},
{
"identifier": "hotelService",
"path": "hotelServices/src/main/java/com/lcwd/hotel/service/hotelService.java",
"snippet": "public interface hotelService {\n public Hotel addHotel(Hotel hotel);\n public Hotel getHotelById(String hotelId);\n public List<Hotel> getAllHotels();\n public Hotel deleteHotelById(String hotelId);\n public Room addRoom(String hotelId, Room room);\n public Room getRoomById(String roomId);\n public List<Room> getAllAvailableRoom(String hotelId);\n public List<Room> getAllBookedRoom(String hotelId);\n public List<Room> getAllRooms(String hotelId);\n public Room deleteRoomById(String roomId);\n public List<Hotel> getHotelByLocation(String location);\n public Hotel getHotelByName(String name);\n\n\n}"
}
] | import com.lcwd.hotel.entities.Hotel;
import com.lcwd.hotel.entities.Room;
import com.lcwd.hotel.entities.Status;
import com.lcwd.hotel.exception.NotFoundException;
import com.lcwd.hotel.repository.BookingRepository;
import com.lcwd.hotel.repository.HotelRepository;
import com.lcwd.hotel.repository.RoomRepository;
import com.lcwd.hotel.service.hotelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID; | 827 | package com.lcwd.hotel.service.Impl;
@Service
@Slf4j
public class hotelServiceImpl implements hotelService {
@Autowired
private HotelRepository hotelRepository;
@Autowired
private RoomRepository roomRepository;
@Autowired | package com.lcwd.hotel.service.Impl;
@Service
@Slf4j
public class hotelServiceImpl implements hotelService {
@Autowired
private HotelRepository hotelRepository;
@Autowired
private RoomRepository roomRepository;
@Autowired | private BookingRepository bookingRepository; | 4 | 2023-10-17 19:25:18+00:00 | 2k |
xiezhihui98/GAT1400 | src/main/java/com/cz/viid/be/service/VIIDNotificationService.java | [
{
"identifier": "ResponseStatusObject",
"path": "src/main/java/com/cz/viid/framework/domain/dto/ResponseStatusObject.java",
"snippet": "@Data\npublic class ResponseStatusObject {\n\n @JsonProperty(\"Id\")\n private String id;\n @JsonProperty(\"RequestURL\")\n private String requestUrl;\n @JsonProperty(\"StatusCode\")\n private String statusCode;\n @JsonProperty(\"StatusString\")\n private String statusString;\n @JsonProperty(\"LocalTime\")\n private String localTime;\n\n public ResponseStatusObject() {\n }\n\n public ResponseStatusObject(String requestUrl, String statusCode, String statusString) {\n this(null, requestUrl, statusCode, statusString);\n }\n\n public ResponseStatusObject(String id, String requestUrl, String statusCode, String statusString) {\n this.id = id;\n this.requestUrl = requestUrl;\n this.statusCode = statusCode;\n this.statusString = statusString;\n this.localTime = DateFormatUtils.format(new Date(), \"yyyyMMddHHmmss\");\n }\n\n}"
},
{
"identifier": "SubscribeNotificationObject",
"path": "src/main/java/com/cz/viid/framework/domain/dto/SubscribeNotificationObject.java",
"snippet": "@Data\npublic class SubscribeNotificationObject {\n\n @JsonProperty(\"ExecuteOperation\")\n private String ExecuteOperation;\n @JsonProperty(\"NotificationID\")\n private String NotificationID;\n @JsonProperty(\"SubscribeID\")\n private String SubscribeID;\n @JsonProperty(\"Title\")\n private String Title;\n @JsonProperty(\"TriggerTime\")\n private String TriggerTime;\n @JsonProperty(\"InfoIDs\")\n private String InfoIDs;\n\n //自动采集的车辆信息订阅接受对象\n @JsonProperty(\"MotorVehicleObjectList\")\n private MotorVehicleObjects MotorVehicleObjectList;\n //自动采集的非机动车辆信息订阅接收对象\n @JsonProperty(\"NonMotorVehicleObjectList\")\n private NonMotorVehicleList NonMotorVehicleObjectList;\n //视频卡口目录订阅接受对象\n @JsonProperty(\"TollgateObjectList\")\n private TollgateObjectList TollgateObjectList;\n //采集设备订阅接受对象 人脸设备\n @JsonProperty(\"DeviceList\")\n private DeviceObjectList DeviceList;\n //人脸抓拍数据订阅接受对象\n @JsonProperty(\"FaceObjectList\")\n private FaceObjectList FaceObjectList;\n //自动采集的人员信息订阅接收对象\n @JsonProperty(\"PersonObjectList\")\n private PersonList PersonObjectList;\n}"
},
{
"identifier": "VIIDSubscribe",
"path": "src/main/java/com/cz/viid/framework/domain/entity/VIIDSubscribe.java",
"snippet": "@Data\n@EqualsAndHashCode\n@ToString\n@TableName(value = \"viid_subscrube\", autoResultMap = true)\npublic class VIIDSubscribe {\n\n @ApiModelProperty(\"订阅标识符\")\n @TableId(value = \"subscribe_id\", type = IdType.NONE)\n private String subscribeId;\n @ApiModelProperty(\"订阅标题\")\n @TableField(\"title\")\n private String title;\n @ApiModelProperty(\"订阅类型,7=视频卡口设备,13=车辆信息(卡口过车记录)\")\n @TableField(\"subscribe_detail\")\n private String subscribeDetail;\n @ApiModelProperty(\"资源ID(卡口ID)\")\n @TableField(value = \"resource_uri\", typeHandler = StringToArrayTypeHandler.class, jdbcType = JdbcType.ARRAY)\n private String resourceUri;\n @ApiModelProperty(\"申请人\")\n @TableField(\"application_name\")\n private String applicationName;\n @ApiModelProperty(\"申请单位\")\n @TableField(\"application_org\")\n private String applicationOrg;\n @ApiModelProperty(\"开始时间\")\n @JsonFormat(pattern = \"yyyyMMddHHmmss\")\n @TableField(\"begin_time\")\n private Date beginTime;\n @ApiModelProperty(\"结束时间\")\n @JsonFormat(pattern = \"yyyyMMddHHmmss\")\n @TableField(\"end_time\")\n private Date endTime;\n @ApiModelProperty(\"订阅回调地址\")\n @TableField(\"receive_addr\")\n private String receiveAddr;\n @ApiModelProperty(\"数据上报间隔\")\n @TableField(\"report_interval\")\n private Integer reportInterval;\n @ApiModelProperty(\"理由\")\n @TableField(\"reason\")\n private String reason;\n @ApiModelProperty(\"操作类型(0=订阅,1=取消订阅)\")\n @TableField(\"operate_type\")\n private Integer operateType;\n @ApiModelProperty(\"订阅状态(0=订阅中,1=已取消订阅,2=订阅到期,9=未订阅)\")\n @TableField(\"subscribe_status\")\n private Integer subscribeStatus;\n @TableField(\"resource_class\")\n private Integer resourceClass;\n @JsonIgnore\n @TableField(\"result_image_declare\")\n private String resultImageDeclare;\n @JsonIgnore\n @TableField(\"result_feature_declare\")\n private Integer resultFeatureDeclare;\n @TableField(\"server_id\")\n private String serverId;\n @TableField(\"create_time\")\n private Date createTime = new Date();\n}"
}
] | import com.cz.viid.framework.domain.dto.ResponseStatusObject;
import com.cz.viid.framework.domain.dto.SubscribeNotificationObject;
import com.cz.viid.framework.domain.entity.VIIDSubscribe; | 1,318 | package com.cz.viid.be.service;
public interface VIIDNotificationService {
VIIDSubscribe getSubscribeById(String subscribeId);
| package com.cz.viid.be.service;
public interface VIIDNotificationService {
VIIDSubscribe getSubscribeById(String subscribeId);
| ResponseStatusObject motorVehicleHandler(SubscribeNotificationObject notificationObject, VIIDSubscribe subscribe); | 0 | 2023-10-23 11:25:43+00:00 | 2k |
leforero4-ui/unico_proyecto_con_todos_los_patrones_de_diseno_en_java | src/main/application/driver/adapter/usecase/mission/MiddleMission.java | [
{
"identifier": "BoardCollection",
"path": "src/main/application/driver/port/usecase/iterator/BoardCollection.java",
"snippet": "public interface BoardCollection<T> {\n int getRows();\n int getColumns();\n Enemy getEnemy(int row, int column);\n\tvoid deleteEnemy(int row, int column);\n\tString getAvatarSquare(int row, int column);\n\tPatternsIterator<T> getIterator();\n}"
},
{
"identifier": "Enemy",
"path": "src/main/domain/model/Enemy.java",
"snippet": "public abstract class Enemy implements Protective {\n\tprotected int life;\n\tprotected int attackLevel;\n\tprotected final Skillfull skill;\n\tprotected Status status;\n\t\n\tpublic Enemy(int life, int attackLevel, Skillfull skill) {\n\t\tthis.life = life;\n\t\tthis.attackLevel = attackLevel;\n\t\tthis.skill = skill;\n\t\tthis.status = new Asleep();\n\t}\n\n\tpublic int getLife() {\n\t\treturn this.life;\n\t}\n\t\n\tpublic int getAttackLevel(boolean isAttacking) {\n\t\treturn this.skill.getEnhancedAttackLevel(this.attackLevel, isAttacking);\n\t}\n\t\n\tpublic int getCounterAttackLevel(final int attackLevelReceived) {\n\t\treturn this.status.getAttackLevel(attackLevelReceived, this);\n\t}\n\t\n\tpublic void setStatus(final Status status) {\n\t\tthis.status = status;\n\t}\n\t\n\t@Override\n\tpublic void protect(final Supreme theProtected) {\n\t\tthis.receiveAttack(1);\n\t\tif (this.getLife() <= 0) {\n\t\t\ttheProtected.removeProtector(this);\n\t\t}\n\t}\n\n\tpublic abstract void receiveAttack(final int attack);\n\t\n\tpublic abstract String getAvatar(final String prefix);\n\t\n\tpublic abstract void acceptVisit(Visitor visitor);\n}"
},
{
"identifier": "Mission",
"path": "src/main/domain/model/Mission.java",
"snippet": "public abstract class Mission {\n\tprotected final BoardCollection<Enemy> board;\n\tprotected final PatternsIterator<Enemy> enemyIterator;\n\t\n\tpublic Mission(BoardCollection<Enemy> board) {\n\t\tthis.board = board;\n\t\tthis.enemyIterator = this.board.getIterator();\n\t}\n\t\n\tpublic boolean isMissionComplete() {\n\t\treturn this.isMainObjectiveComplete()\n\t\t\t\t&& this.isSecondaryObjectiveComplete()\n\t\t\t\t&& this.isTertiaryObjectiveComplete();\n\t}\n\n\tprotected abstract boolean isMainObjectiveComplete();\n\tprotected abstract boolean isSecondaryObjectiveComplete();\n\t\n\tprotected boolean isTertiaryObjectiveComplete() {\n\t\tboolean isSoldierAlive = false;\n\t\t\n\t\twhile (this.enemyIterator.hasNext()) {\n\t\t\tfinal Enemy enemy = this.enemyIterator.getNext();\n\t\t\tif(enemy instanceof SoldierAir || enemy instanceof SoldierNaval) {\n\t\t\t\tisSoldierAlive = true;\n\t\t\t\tbreak;\n\t\t\t}\n }\n\t\tthis.enemyIterator.reset();\n\t\t\n\t\treturn isSoldierAlive;\n\t}\n\n}"
},
{
"identifier": "SquadronAir",
"path": "src/main/domain/model/SquadronAir.java",
"snippet": "public class SquadronAir extends Squadron {\n\t\n\tpublic SquadronAir(final List<Enemy> squadronList, final Skillfull skill) {\n\t\tsuper(squadronList, skill);\n\t}\n\n\t@Override\n\tpublic String getAvatar(final String prefix) {\n\t\tStringBuilder avatarTemp = new StringBuilder();\n\t\tfor (Enemy enemy : this.squadronList) {\n\t\t\tavatarTemp.append(enemy.getAvatar(prefix + this.skill.getIdentifier() + \"EA\"));\n\t\t}\n\t\treturn avatarTemp.toString();\n\t}\n\n}"
},
{
"identifier": "SquadronNaval",
"path": "src/main/domain/model/SquadronNaval.java",
"snippet": "public class SquadronNaval extends Squadron {\n\t\n\tpublic SquadronNaval(final List<Enemy> squadronList, final Skillfull skill) {\n\t\tsuper(squadronList, skill);\n\t}\n\n\t@Override\n\tpublic String getAvatar(final String prefix) {\n\t\tStringBuilder avatarTemp = new StringBuilder();\n\t\tfor (Enemy enemy : this.squadronList) {\n\t\t\tavatarTemp.append(enemy.getAvatar(prefix + this.skill.getIdentifier() + \"EN\"));\n\t\t}\n\t\treturn avatarTemp.toString();\n\t}\n\n}"
},
{
"identifier": "SupremeAir",
"path": "src/main/domain/model/SupremeAir.java",
"snippet": "public class SupremeAir extends Supreme {\n\t\n\tprivate static SupremeAir instance;\n\t\n\tprivate SupremeAir() {\n\t\tsuper(200, 15, new MultipleShots(3));\n\t}\n\t\n\tpublic static SupremeAir getInstance() {\n\t\tif(instance == null) {\n\t\t\tinstance = new SupremeAir();\n\t\t}\n\t\t\n\t\treturn instance;\n\t}\n\n\t@Override\n\tpublic String getAvatar(final String prefix) {\n\t\treturn prefix + this.skill.getIdentifier() + \"JA|\";\n\t}\n\n}"
},
{
"identifier": "SupremeNaval",
"path": "src/main/domain/model/SupremeNaval.java",
"snippet": "public class SupremeNaval extends Supreme {\n\t\n\tprivate static SupremeNaval instance;\n\t\n\tprivate SupremeNaval() {\n\t\tsuper(200, 15, new Bang(10));\n\t}\n\t\n\tpublic static SupremeNaval getInstance() {\n\t\tif(instance == null) {\n\t\t\tinstance = new SupremeNaval();\n\t\t}\n\t\t\n\t\treturn instance;\n\t}\n\n\t@Override\n\tpublic String getAvatar(final String prefix) {\n\t\treturn prefix + this.skill.getIdentifier() + \"JN|\";\n\t}\n\n}"
}
] | import main.application.driver.port.usecase.iterator.BoardCollection;
import main.domain.model.Enemy;
import main.domain.model.Mission;
import main.domain.model.SquadronAir;
import main.domain.model.SquadronNaval;
import main.domain.model.SupremeAir;
import main.domain.model.SupremeNaval; | 1,459 | package main.application.driver.adapter.usecase.mission;
public class MiddleMission extends Mission {
public MiddleMission(BoardCollection<Enemy> board) {
super(board);
}
@Override
protected boolean isMainObjectiveComplete() {
boolean isWeakened = true;
while (this.enemyIterator.hasNext()) {
final Enemy enemy = this.enemyIterator.getNext();
if(enemy instanceof SupremeAir || enemy instanceof SupremeNaval) {
isWeakened = enemy.getLife() < 80;
break;
}
}
this.enemyIterator.reset();
return isWeakened;
}
@Override
protected boolean isSecondaryObjectiveComplete() {
int squadronsAlive = 0;
while (this.enemyIterator.hasNext()) {
final Enemy enemy = this.enemyIterator.getNext(); | package main.application.driver.adapter.usecase.mission;
public class MiddleMission extends Mission {
public MiddleMission(BoardCollection<Enemy> board) {
super(board);
}
@Override
protected boolean isMainObjectiveComplete() {
boolean isWeakened = true;
while (this.enemyIterator.hasNext()) {
final Enemy enemy = this.enemyIterator.getNext();
if(enemy instanceof SupremeAir || enemy instanceof SupremeNaval) {
isWeakened = enemy.getLife() < 80;
break;
}
}
this.enemyIterator.reset();
return isWeakened;
}
@Override
protected boolean isSecondaryObjectiveComplete() {
int squadronsAlive = 0;
while (this.enemyIterator.hasNext()) {
final Enemy enemy = this.enemyIterator.getNext(); | if(enemy instanceof SquadronAir || enemy instanceof SquadronNaval) { | 4 | 2023-10-20 18:36:47+00:00 | 2k |
Squawkykaka/when_pigs_fly | src/main/java/com/squawkykaka/when_pigs_fly/commands/Menu.java | [
{
"identifier": "WhenPigsFly",
"path": "src/main/java/com/squawkykaka/when_pigs_fly/WhenPigsFly.java",
"snippet": "public final class WhenPigsFly extends JavaPlugin {\n\n private static WhenPigsFly instance;\n\n @Override\n public void onEnable() {\n instance = this; // Set the instance to the current plugin\n saveDefaultConfig();\n getLogger().info(\"------------------------\");\n getLogger().info(\"---- Plugin Loading ----\");\n\n EventUtil.register(new AxolotlThrowListener(this));\n EventUtil.register(new PluginEvents());\n new Heal_Feed();\n new Spawn(this);\n new Menu(this);\n Metrics metrics = new Metrics(this, 20271);\n getLogger().info(\"------------------------\");\n getLogger().info(\"---- Plugin enabled ----\");\n getLogger().info(\"------------------------\");\n }\n\n @Override\n public void onDisable() {\n getLogger().info(\"Plugin disabled.\");\n }\n\n // Create a method to obtain the plugin instance\n public static WhenPigsFly getInstance() {\n return instance;\n }\n}"
},
{
"identifier": "CommandBase",
"path": "src/main/java/com/squawkykaka/when_pigs_fly/util/CommandBase.java",
"snippet": "public abstract class CommandBase extends BukkitCommand implements CommandExecutor {\n private List<String> delayedPlayers = null;\n private int delay = 0;\n private final int minArguments;\n private final int maxArguments;\n private final boolean playerOnly;\n public CommandBase(String command) {\n this(command, 0);\n }\n\n public CommandBase(String command, boolean playerOnly) {\n this(command, 0, playerOnly);\n }\n\n public CommandBase(String command, int requiredArguments) {\n this(command, requiredArguments, requiredArguments);\n }\n\n public CommandBase(String command, int minArguments, int maxArguments) {\n this(command, minArguments, maxArguments, false);\n }\n\n public CommandBase(String command, int requiredArguments, boolean playerOnly) {\n this(command, requiredArguments, requiredArguments, playerOnly);\n }\n\n public CommandBase(String command, int minArguments, int maxArguments, boolean playerOnly) {\n super(command);\n\n this.minArguments = minArguments;\n this.maxArguments = maxArguments;\n this.playerOnly = playerOnly;\n\n CommandMap commandMap = getCommandMap();\n if (command != null) {\n commandMap.register(command, this);\n }\n }\n\n public CommandMap getCommandMap() {\n try {\n if (Bukkit.getPluginManager() instanceof SimplePluginManager) {\n Field field = SimplePluginManager.class.getDeclaredField(\"commandMap\");\n field.setAccessible(true);\n\n return (CommandMap) field.get(Bukkit.getPluginManager());\n }\n } catch (NoSuchFieldException | IllegalAccessException e) {\n e.printStackTrace();\n }\n return null;\n }\n\n public CommandBase enableDelay(int delay) {\n this.delay = delay;\n this.delayedPlayers = new ArrayList<>();\n return this;\n }\n\n public void removeDelay(Player player) {\n this.delayedPlayers.remove(player.getName());\n }\n\n public void sendUsage(CommandSender sender) {\n Msg.send(sender, getUsage());\n }\n\n public boolean execute(CommandSender sender, String alias, String [] arguments) {\n if (arguments.length < minArguments || (arguments.length > maxArguments && maxArguments != -1)) {\n sendUsage(sender);\n return true;\n }\n\n if (playerOnly && !(sender instanceof Player)) {\n Msg.send(sender,\"&cOnly players can use this command.\");\n return true;\n }\n\n String permission = getPermission();\n if (permission != null && !sender.hasPermission(permission)) {\n Msg.send(sender, \"&cYou do not have permission to use this command.\");\n return true;\n }\n\n if (delayedPlayers != null && sender instanceof Player) {\n Player player = (Player) sender;\n if (delayedPlayers.contains(player.getName())) {\n Msg.send(player, \"&cPlease wait \" + delay + \" seconds before using this command again.\");\n return true;\n }\n\n delayedPlayers.add(player.getName());\n Bukkit.getScheduler().scheduleSyncDelayedTask(WhenPigsFly.getInstance(), () -> {\n delayedPlayers.remove(player.getName());\n }, 20L * delay);\n }\n\n if (!onCommand(sender, arguments))\n sendUsage(sender);\n\n return true;\n }\n\n public boolean onCommand(CommandSender sender, Command command, String alias, String [] arguments) {\n return this.onCommand(sender, arguments);\n }\n\n public abstract boolean onCommand(CommandSender sender, String [] arguments);\n\n public abstract String getUsage();\n}"
},
{
"identifier": "Msg",
"path": "src/main/java/com/squawkykaka/when_pigs_fly/util/Msg.java",
"snippet": "public class Msg {\n public static void send(CommandSender sender, String message) {\n send(sender, message, \"&a\");\n }\n\n public static void send(CommandSender sender, String message, String prefix) {\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&', prefix + message));\n }\n}"
}
] | import com.squawkykaka.when_pigs_fly.WhenPigsFly;
import com.squawkykaka.when_pigs_fly.util.CommandBase;
import com.squawkykaka.when_pigs_fly.util.Msg;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
import java.util.List; | 1,439 | package com.squawkykaka.when_pigs_fly.commands;
public class Menu implements Listener {
private final String invName = "When pigs fly! Menu";
| package com.squawkykaka.when_pigs_fly.commands;
public class Menu implements Listener {
private final String invName = "When pigs fly! Menu";
| public Menu(WhenPigsFly plugin) { | 0 | 2023-10-17 02:07:39+00:00 | 2k |
greatwqs/finance-manager | src/test/java/com/github/greatwqs/app/BaseSpringServiceTest.java | [
{
"identifier": "RequestComponent",
"path": "src/main/java/com/github/greatwqs/app/component/RequestComponent.java",
"snippet": "@Slf4j\n@Component\npublic class RequestComponent {\n\n public HttpServletRequest getRequest() {\n if (getRequestAttributes() != null) {\n return getRequestAttributes().getRequest();\n } else {\n return null;\n }\n }\n\n public String getRequestUri() {\n HttpServletRequest request = getRequest();\n if (request == null) {\n return \"unkonw uri\";\n } else {\n return request.getRequestURI();\n }\n }\n\n public String getRequestUrl() {\n HttpServletRequest request = getRequest();\n if (request == null) {\n return \"unkonw url\";\n } else {\n return request.getRequestURL().toString();\n }\n }\n\n public HttpServletResponse getResponse() {\n return getRequestAttributes().getResponse();\n }\n\n public ServletRequestAttributes getRequestAttributes() {\n return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());\n }\n\n /***\n * getExecuteIp\n * @return\n */\n public String getClientIp() {\n HttpServletRequest request = getRequest();\n if (request == null) {\n return \"\";\n }\n String ip = request.getHeader(\"x-forwarded-for\");\n if (StringUtils.isBlank(ip) || \"unknown\".equalsIgnoreCase(ip)) {\n ip = request.getHeader(\"Proxy-Client-IP\");\n }\n if (StringUtils.isBlank(ip) || \"unknown\".equalsIgnoreCase(ip)) {\n ip = request.getHeader(\"WL-Proxy-Client-IP\");\n }\n if (StringUtils.isBlank(ip) || \"unknown\".equalsIgnoreCase(ip)) {\n ip = request.getRemoteAddr();\n }\n if (StringUtils.isBlank(ip) || \"unknown\".equalsIgnoreCase(ip)) {\n ip = request.getHeader(\"X-Real-IP\");\n }\n if (ip != null && ip.trim().length() > 0) {\n int index = ip.indexOf(',');\n return (index != -1) ? ip.substring(0, index) : ip;\n }\n return ip;\n }\n\n /***\n * default zh_CN\n * @return\n */\n public Locale getLocale() {\n return AppConstants.LOCALE;\n }\n\n /***\n * get locale\n * @return\n */\n private Locale getRequestLocale() {\n HttpServletRequest request = getRequest();\n final String APP_LOCALE = \"app_locale\";\n final Cookie cookie = WebUtils.getCookie(request, APP_LOCALE);\n if (cookie != null && StringUtils.isNotEmpty(cookie.getValue())) {\n return org.springframework.util.StringUtils.parseLocaleString(cookie.getValue());\n }\n\n /**\n * based on the Accept-Language header. If the client request\n * doesn't provide an Accept-Language header, this method returns the\n * default locale for the server.\n */\n return request.getLocale();\n }\n\n public void setParam(String key, Object value) {\n RequestContextHolder.currentRequestAttributes()\n .setAttribute(key, value, RequestAttributes.SCOPE_REQUEST);\n }\n\n public Object getParam(String key) {\n return RequestContextHolder.currentRequestAttributes()\n .getAttribute(key, RequestAttributes.SCOPE_REQUEST);\n }\n\n public UserPo getLoginUser() {\n return (UserPo) RequestContextHolder.currentRequestAttributes()\n .getAttribute(AppConstants.REQUEST_USER, RequestAttributes.SCOPE_REQUEST);\n }\n\n public String getLoginToken() {\n return (String) RequestContextHolder.currentRequestAttributes()\n .getAttribute(AppConstants.REQUEST_USER_TOKEN, RequestAttributes.SCOPE_REQUEST);\n }\n}"
},
{
"identifier": "SmsComponent",
"path": "src/main/java/com/github/greatwqs/app/component/SmsComponent.java",
"snippet": "@Slf4j\n@Component\npublic class SmsComponent {\n\n\t@Async\n\tpublic void sendSms(String phoneNo, String smsCode) {\n\t\tlog.warn(\"phoneNo: \" + phoneNo + \", smsCode: \" + smsCode);\n\t}\n}"
}
] | import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import com.github.greatwqs.app.component.RequestComponent;
import com.github.greatwqs.app.component.SmsComponent; | 1,064 | package com.github.greatwqs.app;
/**
*
* BaseServiceTest @MockBean for third part!
*
* @author greatwqs
* Create on 2020/6/25
*/
public abstract class BaseSpringServiceTest extends BaseSpringTest {
@MockBean
@Autowired
protected SmsComponent smsComponent;
@MockBean
@Autowired | package com.github.greatwqs.app;
/**
*
* BaseServiceTest @MockBean for third part!
*
* @author greatwqs
* Create on 2020/6/25
*/
public abstract class BaseSpringServiceTest extends BaseSpringTest {
@MockBean
@Autowired
protected SmsComponent smsComponent;
@MockBean
@Autowired | private RequestComponent requestComponent; | 0 | 2023-10-16 12:45:57+00:00 | 2k |
Wind-Gone/Vodka | code/src/main/java/utils/jdbc/ExecJDBC.java | [
{
"identifier": "SQLExceptionInfo",
"path": "code/src/main/java/utils/exception/SQLExceptionInfo.java",
"snippet": "public class SQLExceptionInfo {\n public static String getSQLExceptionInfo(SQLException se) {\n return \", sql state: \" + se.getSQLState() +\n \", error code: \" + se.getErrorCode() +\n \", message: \" + se.getMessage() +\n \", cause: \" + se.getCause();\n }\n\n public static String getIOExceptionInfo(IOException ie) {\n return \", message: \" + ie.getMessage() +\n \", cause: \" + ie.getCause();\n }\n}"
},
{
"identifier": "jTPCCUtil",
"path": "code/src/main/java/utils/common/jTPCCUtil.java",
"snippet": "public class jTPCCUtil implements CommonConfig {\n private static Connection dbConn = null;\n private static PreparedStatement stmtGetConfig = null;\n\n public static String getSysProp(String inSysProperty, String defaultValue) {\n String outPropertyValue = null;\n try {\n outPropertyValue = System.getProperty(inSysProperty, defaultValue);\n } catch (Exception e) {\n System.err.println(\"Error Reading Required System Property '\" + inSysProperty + \"'\");\n }\n return (outPropertyValue);\n\n } // end getSysProp\n\n\n public static String randomStr(long strLen) {\n char freshChar;\n StringBuilder freshString;\n freshString = new StringBuilder();\n while (freshString.length() < (strLen - 1)) {\n freshChar = (char) (Math.random() * 128);\n if (Character.isLetter(freshChar)) {\n freshString.append(freshChar);\n }\n }\n\n return (freshString.toString());\n\n } // end randomStr\n\n\n public static String getCurrentTime() {\n return dateFormat.format(new java.util.Date());\n }\n\n public static String formattedDouble(double d) {\n String dS = \"\" + d;\n return dS.length() > 6 ? dS.substring(0, 6) : dS;\n }\n\n public static String getConfig(String db, Properties dbProps, String option)\n throws Exception {\n ResultSet rs;\n String value;\n\n if (dbConn == null) {\n dbConn = DriverManager.getConnection(db, dbProps);\n stmtGetConfig = dbConn.prepareStatement(\"SELECT cfg_value FROM vodka_config \" + \" WHERE cfg_name = ?\");\n }\n stmtGetConfig.setString(1, option);\n rs = stmtGetConfig.executeQuery();\n if (!rs.next())\n throw new Exception(\"DB Load configuration parameter '\" +\n option + \"' not found\");\n value = rs.getString(\"cfg_value\");\n rs.close();\n return value;\n }\n\n} // end jTPCCUtil"
}
] | import java.io.*;
import java.sql.*;
import java.util.*;
import utils.exception.SQLExceptionInfo;
import org.apache.log4j.Logger;
import utils.common.jTPCCUtil; | 1,473 | package utils.jdbc;/*
* ExecJDBC - Command line program to process SQL DDL statements, from
* a text input file, to any JDBC Data Source
*
*/
public class ExecJDBC {
private static final Logger log = Logger.getLogger(ExecJDBC.class);
public static void main(String[] args) {
Connection conn = null;
Statement stmt;
String rLine;
String sLine = null;
StringBuilder sql = new StringBuilder();
try {
Properties ini = new Properties();
ini.load(new FileInputStream(System.getProperty("prop")));
Class.forName(ini.getProperty("driver")); // Register jdbcDriver
conn = DriverManager.getConnection(ini.getProperty("conn"),
ini.getProperty("user"), ini.getProperty("password")); // make connection
conn.setAutoCommit(true);
String dbType = ini.getProperty("db"); // Retrieve datbase type
boolean ora_ready_to_execute = false; // For oracle : Boolean that indicates whether or not there is a entity.statement ready to be executed.
stmt = conn.createStatement(); // Create Statement
BufferedReader in = new BufferedReader(new FileReader(
jTPCCUtil.getSysProp("commandFile", null))); // Open inputFile
while ((rLine = in.readLine()) != null) { // loop thru input file and concatenate SQL entity.statement fragments
if (ora_ready_to_execute) {
String query = sql.toString();
execJDBC(stmt, query);
sql = new StringBuilder();
ora_ready_to_execute = false;
}
String line = rLine.trim();
if (line.length() != 0) {
if (line.startsWith("--") && !line.startsWith("-- {")) {
System.out.println(rLine); // print comment line
} else {
if (line.equals("$$")) {
sql.append(rLine);
sql.append("\n");
while ((rLine = in.readLine()) != null) {
line = rLine.trim();
sql.append(rLine);
sql.append("\n");
if (line.equals("$$")) {
break;
}
}
continue;
}
if (line.startsWith("-- {")) {
sql.append(rLine);
sql.append("\n");
while ((rLine = in.readLine()) != null) {
line = rLine.trim();
sql.append(rLine);
sql.append("\n");
if (line.startsWith("-- }")) {
ora_ready_to_execute = true;
break;
}
}
continue;
}
if (line.endsWith("\\;")) {
sql.append(rLine.replaceAll("\\\\;", ";"));
sql.append("\n");
} else {
sql.append(line.replaceAll("\\\\;", ";"));
if (line.endsWith(";")) {
String query = sql.toString();
execJDBC(stmt, query.substring(0, query.length() - 1));
sql = new StringBuilder();
} else {
sql.append("\n");
}
}
}
} //end if
} //end while
in.close();
} catch (IOException | SQLException ie) {
System.out.println(ie.getMessage());
} catch (Exception e) {
e.printStackTrace();
//exit Cleanly
} finally {
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} // end finally
} // end try
} // end main
static void execJDBC(Statement stmt, String query) {
int retryCount = 1; // retry times
int retryThreshold = 6;
while (true) {
try {
System.out.println(query + ";");
stmt.execute(query);
break;
} catch (SQLException se) {
if (retryCount > retryThreshold) { | package utils.jdbc;/*
* ExecJDBC - Command line program to process SQL DDL statements, from
* a text input file, to any JDBC Data Source
*
*/
public class ExecJDBC {
private static final Logger log = Logger.getLogger(ExecJDBC.class);
public static void main(String[] args) {
Connection conn = null;
Statement stmt;
String rLine;
String sLine = null;
StringBuilder sql = new StringBuilder();
try {
Properties ini = new Properties();
ini.load(new FileInputStream(System.getProperty("prop")));
Class.forName(ini.getProperty("driver")); // Register jdbcDriver
conn = DriverManager.getConnection(ini.getProperty("conn"),
ini.getProperty("user"), ini.getProperty("password")); // make connection
conn.setAutoCommit(true);
String dbType = ini.getProperty("db"); // Retrieve datbase type
boolean ora_ready_to_execute = false; // For oracle : Boolean that indicates whether or not there is a entity.statement ready to be executed.
stmt = conn.createStatement(); // Create Statement
BufferedReader in = new BufferedReader(new FileReader(
jTPCCUtil.getSysProp("commandFile", null))); // Open inputFile
while ((rLine = in.readLine()) != null) { // loop thru input file and concatenate SQL entity.statement fragments
if (ora_ready_to_execute) {
String query = sql.toString();
execJDBC(stmt, query);
sql = new StringBuilder();
ora_ready_to_execute = false;
}
String line = rLine.trim();
if (line.length() != 0) {
if (line.startsWith("--") && !line.startsWith("-- {")) {
System.out.println(rLine); // print comment line
} else {
if (line.equals("$$")) {
sql.append(rLine);
sql.append("\n");
while ((rLine = in.readLine()) != null) {
line = rLine.trim();
sql.append(rLine);
sql.append("\n");
if (line.equals("$$")) {
break;
}
}
continue;
}
if (line.startsWith("-- {")) {
sql.append(rLine);
sql.append("\n");
while ((rLine = in.readLine()) != null) {
line = rLine.trim();
sql.append(rLine);
sql.append("\n");
if (line.startsWith("-- }")) {
ora_ready_to_execute = true;
break;
}
}
continue;
}
if (line.endsWith("\\;")) {
sql.append(rLine.replaceAll("\\\\;", ";"));
sql.append("\n");
} else {
sql.append(line.replaceAll("\\\\;", ";"));
if (line.endsWith(";")) {
String query = sql.toString();
execJDBC(stmt, query.substring(0, query.length() - 1));
sql = new StringBuilder();
} else {
sql.append("\n");
}
}
}
} //end if
} //end while
in.close();
} catch (IOException | SQLException ie) {
System.out.println(ie.getMessage());
} catch (Exception e) {
e.printStackTrace();
//exit Cleanly
} finally {
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} // end finally
} // end try
} // end main
static void execJDBC(Statement stmt, String query) {
int retryCount = 1; // retry times
int retryThreshold = 6;
while (true) {
try {
System.out.println(query + ";");
stmt.execute(query);
break;
} catch (SQLException se) {
if (retryCount > retryThreshold) { | log.error("Fail to execute sql entity.statement after assigned trys, " + query + ",\n" + SQLExceptionInfo.getSQLExceptionInfo(se)); | 0 | 2023-10-22 11:22:32+00:00 | 2k |
Onuraktasj/stock-tracking-system | src/main/java/com/onuraktas/stocktrackingsystem/mapper/CategoryMapper.java | [
{
"identifier": "CategoryDto",
"path": "src/main/java/com/onuraktas/stocktrackingsystem/dto/entity/CategoryDto.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor(access = AccessLevel.PRIVATE)\n@ToString\n@EqualsAndHashCode\n@Builder\npublic class CategoryDto implements Serializable {\n\n private UUID categoryId;\n private String categoryName;\n private Boolean isActive;\n}"
},
{
"identifier": "ProductDto",
"path": "src/main/java/com/onuraktas/stocktrackingsystem/dto/entity/ProductDto.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor(access = AccessLevel.PRIVATE)\n@ToString\n@EqualsAndHashCode\n@Builder\npublic class ProductDto {\n\n private UUID productId;\n private String productName;\n private String description;\n private Integer amount;\n private Boolean isActive;\n}"
},
{
"identifier": "CreateCategoryRequest",
"path": "src/main/java/com/onuraktas/stocktrackingsystem/dto/request/CreateCategoryRequest.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor(access = AccessLevel.PRIVATE)\n@ToString\n@EqualsAndHashCode\n@Builder\npublic class CreateCategoryRequest {\n\n private String categoryName;\n}"
},
{
"identifier": "CreateCategoryResponse",
"path": "src/main/java/com/onuraktas/stocktrackingsystem/dto/response/CreateCategoryResponse.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor(access = AccessLevel.PRIVATE)\n@ToString\n@EqualsAndHashCode\n@SuperBuilder\npublic class CreateCategoryResponse {\n\n private String status;\n\n private UUID categoryId;\n\n\n}"
},
{
"identifier": "Category",
"path": "src/main/java/com/onuraktas/stocktrackingsystem/entity/Category.java",
"snippet": "@AllArgsConstructor\n@NoArgsConstructor\n@Getter\n@Setter\n@EqualsAndHashCode\n@ToString\n@Builder\n@Entity\npublic class Category {\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private UUID categoryId;\n private String categoryName;\n @Builder.Default\n private Boolean isActive = true;\n}"
},
{
"identifier": "Product",
"path": "src/main/java/com/onuraktas/stocktrackingsystem/entity/Product.java",
"snippet": "@Getter\n@Setter\n@AllArgsConstructor\n@NoArgsConstructor\n@EqualsAndHashCode\n@Builder\n@ToString\n@Entity\npublic class Product {\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private UUID productId;\n private String productName;\n private String description;\n private Integer amount;\n @Builder.Default\n private Boolean isActive = true;\n}"
}
] | import com.onuraktas.stocktrackingsystem.dto.entity.CategoryDto;
import com.onuraktas.stocktrackingsystem.dto.entity.ProductDto;
import com.onuraktas.stocktrackingsystem.dto.request.CreateCategoryRequest;
import com.onuraktas.stocktrackingsystem.dto.response.CreateCategoryResponse;
import com.onuraktas.stocktrackingsystem.entity.Category;
import com.onuraktas.stocktrackingsystem.entity.Product;
import java.util.List;
import java.util.Objects; | 908 | package com.onuraktas.stocktrackingsystem.mapper;
public class CategoryMapper {
public static CategoryDto toDto(Category category){
if (Objects.isNull(category))
return null;
return CategoryDto.builder()
.categoryId(category.getCategoryId())
.categoryName(category.getCategoryName())
.isActive(category.getIsActive())
.build();
}
public static CategoryDto toEntity(Category category){
if (Objects.isNull(category))
return null;
return CategoryDto.builder()
.categoryId(category.getCategoryId())
.categoryName(category.getCategoryName())
.isActive(category.getIsActive())
.build();
}
public static Category toEntity(CategoryDto categoryDto){
if (Objects.isNull(categoryDto))
return null;
return Category.builder()
.categoryName(categoryDto.getCategoryName())
.build();
}
public static Category toEntity(CreateCategoryRequest categoryRequest){
if (Objects.isNull(categoryRequest))
return null;
return Category.builder()
.categoryName(categoryRequest.getCategoryName())
.build();
}
| package com.onuraktas.stocktrackingsystem.mapper;
public class CategoryMapper {
public static CategoryDto toDto(Category category){
if (Objects.isNull(category))
return null;
return CategoryDto.builder()
.categoryId(category.getCategoryId())
.categoryName(category.getCategoryName())
.isActive(category.getIsActive())
.build();
}
public static CategoryDto toEntity(Category category){
if (Objects.isNull(category))
return null;
return CategoryDto.builder()
.categoryId(category.getCategoryId())
.categoryName(category.getCategoryName())
.isActive(category.getIsActive())
.build();
}
public static Category toEntity(CategoryDto categoryDto){
if (Objects.isNull(categoryDto))
return null;
return Category.builder()
.categoryName(categoryDto.getCategoryName())
.build();
}
public static Category toEntity(CreateCategoryRequest categoryRequest){
if (Objects.isNull(categoryRequest))
return null;
return Category.builder()
.categoryName(categoryRequest.getCategoryName())
.build();
}
| public static CreateCategoryResponse toCreateCategoryResponse(Category category){ | 3 | 2023-10-23 19:00:09+00:00 | 2k |
ushh789/FinancialCalculator | src/main/java/com/netrunners/financialcalculator/StartMenu.java | [
{
"identifier": "LogHelper",
"path": "src/main/java/com/netrunners/financialcalculator/LogicalInstrumnts/FileInstruments/LogHelper.java",
"snippet": "public class LogHelper {\n\n // Додаємо об'єкт логування\n private static final Logger logger = Logger.getLogger(LogHelper.class.getName());\n\n static {\n try {\n // Налаштовуємо об'єкт логування для запису в файл \"log.txt\"\n FileHandler fileHandler = new FileHandler(\"logs/log\"+ LocalDateTime.now().format(DateTimeFormatter.ofPattern(\"dd-MM-yyyy_HH-mm-ss\"))+\".log\");\n SimpleFormatter formatter = new SimpleFormatter();\n fileHandler.setFormatter(formatter);\n logger.addHandler(fileHandler);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n // Метод для логування повідомлень\n public static void log(Level level, String message, Throwable throwable) {\n logger.log(level, message, throwable);\n }\n}"
},
{
"identifier": "LanguageManager",
"path": "src/main/java/com/netrunners/financialcalculator/VisualInstruments/MenuActions/LanguageManager.java",
"snippet": "public class LanguageManager {\n private static LanguageManager instance;\n private ObservableResourceFactory resourceFactory;\n private Properties properties;\n private static final String PROPERTIES_FILE = \"config.properties\";\n\n\n private LanguageManager() {\n resourceFactory = new ObservableResourceFactory();\n properties = new Properties();\n loadLanguage();\n }\n public Locale getLocale() {\n return resourceFactory.getResources().getLocale();\n }\n\n public static LanguageManager getInstance() {\n if (instance == null) {\n instance = new LanguageManager();\n }\n return instance;\n }\n private void loadLanguage() {\n try (InputStream input = new FileInputStream(PROPERTIES_FILE)) {\n properties.load(input);\n if (properties.getProperty(\"language\") != null) {\n resourceFactory.setResources(ResourceBundle.getBundle(\"com/netrunners/financialcalculator/assets/messages\", new Locale(properties.getProperty(\"language\"))));\n } else {\n resourceFactory.setResources(ResourceBundle.getBundle(\"com/netrunners/financialcalculator/assets/messages\", new Locale(\"en\")));\n }\n } catch (IOException ex) {\n ex.printStackTrace();\n }\n }\n\n public void saveLanguage() {\n try (OutputStream output = new FileOutputStream(PROPERTIES_FILE)) {\n properties.setProperty(\"language\", resourceFactory.getResources().getLocale().getLanguage());\n properties.store(output, null);\n } catch (IOException ex) {\n ex.printStackTrace();\n }\n }\n\n public void changeLanguage(Locale locale) {\n resourceFactory.setResources(ResourceBundle.getBundle(\"com/netrunners/financialcalculator/assets/messages\", locale));\n }\n\n public StringBinding getStringBinding(String key) {\n return resourceFactory.getStringBinding(key);\n }\n\n public static int checkOption(String chosenOption){\n LanguageManager languageManager = LanguageManager.getInstance();\n String option1 = languageManager.getStringBinding(\"Option1\").get();\n String option2 = languageManager.getStringBinding(\"Option2\").get();\n String option3 = languageManager.getStringBinding(\"Option3\").get();\n String option4 = languageManager.getStringBinding(\"Option4\").get();\n\n if (chosenOption.equals(option1)) {\n return 1;\n } else if (chosenOption.equals(option2)) {\n return 2;\n } else if (chosenOption.equals(option3)) {\n return 3;\n } else if (chosenOption.equals(option4)) {\n return 4;\n } else {\n return -1000;\n }\n }\n}"
}
] | import com.netrunners.financialcalculator.LogicalInstrumnts.FileInstruments.LogHelper;
import com.netrunners.financialcalculator.VisualInstruments.MenuActions.LanguageManager;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.fxml.FXMLLoader;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level; | 1,046 | package com.netrunners.financialcalculator;
public class StartMenu extends Application {
public static Scene startMenuScene;
public static List<Scene> openScenes = new ArrayList<>();
public static String currentTheme = "file:src/main/resources/com/netrunners/financialcalculator/assets/lightTheme.css";
@Override
public void start(Stage primaryStage) {
try {
FXMLLoader fxmlLoader = new FXMLLoader(StartMenu.class.getResource("StartMenu.fxml")); | package com.netrunners.financialcalculator;
public class StartMenu extends Application {
public static Scene startMenuScene;
public static List<Scene> openScenes = new ArrayList<>();
public static String currentTheme = "file:src/main/resources/com/netrunners/financialcalculator/assets/lightTheme.css";
@Override
public void start(Stage primaryStage) {
try {
FXMLLoader fxmlLoader = new FXMLLoader(StartMenu.class.getResource("StartMenu.fxml")); | primaryStage.titleProperty().bind(LanguageManager.getInstance().getStringBinding("CalcLabel")); | 1 | 2023-10-18 16:03:09+00:00 | 2k |
bowbahdoe/java-audio-stack | jlayer-player/src/main/java/dev/mccue/jlayer/player/advanced/AdvancedPlayer.java | [
{
"identifier": "AudioDevice",
"path": "jlayer-player/src/main/java/dev/mccue/jlayer/player/AudioDevice.java",
"snippet": "public interface AudioDevice\r\n{\r\n\t/**\r\n\t * Prepares the AudioDevice for playback of audio samples. \r\n\t * @param decoder\tThe decoder that will be providing the audio\r\n\t *\t\t\t\t\tsamples. \r\n\t * \r\n\t * If the audio device is already open, this method returns silently. \r\n\t * \r\n\t */\r\n\tpublic void open(Decoder decoder) throws JavaLayerException;\r\n\t\t\r\n\t/**\r\n\t * Retrieves the open state of this audio device. \r\n\t * \r\n\t * @return <code>true</code> if this audio device is open and playing\r\n\t *\t\t\taudio samples, or <code>false</code> otherwise. \r\n\t */\r\n\tpublic boolean isOpen();\r\n\t\r\n\t/**\r\n\t * Writes a number of samples to this <code>AudioDevice</code>. \r\n\t * \r\n\t * @param samples\tThe array of signed 16-bit samples to write\r\n\t *\t\t\t\t\tto the audio device. \r\n\t * @param offs\t\tThe offset of the first sample.\r\n\t * @param len\t\tThe number of samples to write. \r\n\t * \r\n\t * This method may return prior to the samples actually being played \r\n\t * by the audio device. \r\n\t */\r\n\tpublic void write(short[] samples, int offs, int len) throws JavaLayerException;\r\n\t\t\r\n\t\r\n\t/**\r\n\t * Closes this audio device. Any currently playing audio is stopped \r\n\t * as soon as possible. Any previously written audio data that has not been heard\r\n\t * is discarded. \r\n\t * \r\n\t * The implementation should ensure that any threads currently blocking\r\n\t * on the device (e.g. during a <code>write</code> or <code>flush</code>\r\n\t * operation should be unblocked by this method. \r\n\t */\r\n\tpublic void close();\r\n\t\r\n\t\r\n\t/**\r\n\t * Blocks until all audio samples previously written to this audio device have\r\n\t * been heard. \r\n\t */\r\n\tpublic void flush();\r\n\t\t\t\r\n\t/**\r\n\t * Retrieves the current playback position in milliseconds. \r\n\t */\r\n\tpublic int getPosition();\r\n}\r"
},
{
"identifier": "FactoryRegistry",
"path": "jlayer-player/src/main/java/dev/mccue/jlayer/player/FactoryRegistry.java",
"snippet": "public class FactoryRegistry extends AudioDeviceFactory\r\n{\r\n\tstatic private FactoryRegistry instance = null;\r\n\t\r\n\tstatic synchronized public FactoryRegistry systemRegistry()\r\n\t{\r\n\t\tif (instance==null)\r\n\t\t{\r\n\t\t\tinstance = new FactoryRegistry();\r\n\t\t\tinstance.registerDefaultFactories();\r\n\t\t}\r\n\t\treturn instance;\r\n\t}\r\n\r\n\t\r\n\tprotected final Hashtable<Class<? extends AudioDeviceFactory>, AudioDeviceFactory> factories\r\n\t\t\t= new Hashtable<>();\r\n\t\r\n\t/**\r\n\t * Registers an <code>AudioDeviceFactory</code> instance\r\n\t * with this registry. \r\n\t */\r\n\tpublic void addFactory(AudioDeviceFactory factory)\r\n\t{\t\r\n\t\tfactories.put(factory.getClass(), factory);\t\t\t\t\t\t \r\n\t}\r\n\t\r\n\tpublic void removeFactoryType(Class<? extends AudioDeviceFactory> cls)\r\n\t{\r\n\t\tfactories.remove(cls);\r\n\t}\r\n\t\r\n\tpublic void removeFactory(AudioDeviceFactory factory)\r\n\t{\r\n\t\tfactories.remove(factory.getClass());\t\r\n\t}\r\n\t\r\n\tpublic AudioDevice createAudioDevice() throws JavaLayerException\r\n\t{\r\n\t\tAudioDevice device = null;\r\n\t\tAudioDeviceFactory[] factories = getFactoriesPriority();\r\n\t\t\r\n\t\tif (factories==null)\r\n\t\t\tthrow new JavaLayerException(this + \": no factories registered\");\r\n\t\t\r\n\t\tJavaLayerException lastEx = null;\r\n\t\tfor (int i=0; (device==null) && (i<factories.length); i++)\r\n\t\t{\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\tdevice = factories[i].createAudioDevice();\r\n\t\t\t}\r\n\t\t\tcatch (JavaLayerException ex)\r\n\t\t\t{\r\n\t\t\t\tlastEx = ex;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tif (device==null && lastEx!=null)\r\n\t\t{\r\n\t\t\tthrow new JavaLayerException(\"Cannot create AudioDevice\", lastEx);\r\n\t\t}\r\n\t\t\r\n\t\treturn device;\r\n\t}\r\n\t\r\n\t\r\n\tprotected AudioDeviceFactory[] getFactoriesPriority()\r\n\t{\r\n\t\tAudioDeviceFactory[] fa = null;\r\n\t\tsynchronized (factories)\r\n\t\t{\r\n\t\t\tint size = factories.size();\r\n\t\t\tif (size!=0)\r\n\t\t\t{\r\n\t\t\t\tfa = new AudioDeviceFactory[size];\r\n\t\t\t\tint idx = 0;\r\n\t\t\t\tEnumeration<AudioDeviceFactory> e = factories.elements();\r\n\t\t\t\twhile (e.hasMoreElements())\r\n\t\t\t\t{\r\n\t\t\t\t\tAudioDeviceFactory factory = e.nextElement();\r\n\t\t\t\t\tfa[idx++] = factory;\t\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn fa;\r\n\t}\r\n\r\n\tprotected void registerDefaultFactories()\r\n\t{\r\n\t\taddFactory(new JavaSoundAudioDeviceFactory());\r\n\t}\r\n}\r"
}
] | import java.io.InputStream;
import dev.mccue.jlayer.decoder.*;
import dev.mccue.jlayer.player.AudioDevice;
import dev.mccue.jlayer.player.FactoryRegistry;
| 1,522 | /*
* 11/19/04 1.0 moved to LGPL.
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package dev.mccue.jlayer.player.advanced;
/**
* a hybrid of javazoom.jl.player.Player tweeked to include <code>play(startFrame, endFrame)</code>
* hopefully this will be included in the api
*/
public class AdvancedPlayer
{
/** The MPEG audio bitstream.*/
private Bitstream bitstream;
/** The MPEG audio decoder. */
private Decoder decoder;
/** The AudioDevice the audio samples are written to. */
| /*
* 11/19/04 1.0 moved to LGPL.
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package dev.mccue.jlayer.player.advanced;
/**
* a hybrid of javazoom.jl.player.Player tweeked to include <code>play(startFrame, endFrame)</code>
* hopefully this will be included in the api
*/
public class AdvancedPlayer
{
/** The MPEG audio bitstream.*/
private Bitstream bitstream;
/** The MPEG audio decoder. */
private Decoder decoder;
/** The AudioDevice the audio samples are written to. */
| private AudioDevice audio;
| 0 | 2023-10-19 14:09:37+00:00 | 2k |
dvillavicencio/Riven-of-a-Thousand-Servers | src/main/java/com/danielvm/destiny2bot/factory/UserCharacterMessageCreator.java | [
{
"identifier": "Choice",
"path": "src/main/java/com/danielvm/destiny2bot/dto/discord/Choice.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Choice {\n\n /**\n * Name of the choice\n */\n private String name;\n\n /**\n * Value of the choice\n */\n private Object value;\n}"
},
{
"identifier": "Interaction",
"path": "src/main/java/com/danielvm/destiny2bot/dto/discord/Interaction.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Interaction implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 315485352844067387L;\n\n /**\n * The Id of the interaction\n */\n private Object id;\n\n /**\n * The Id of the application\n */\n @JsonAlias(\"application_id\")\n private Object applicationId;\n\n /**\n * The type of the interaction (see {@link com.danielvm.destiny2bot.enums.InteractionType})\n */\n private Integer type;\n\n /**\n * Additional data of the interaction, will be attached to all interactions besides PING\n */\n private InteractionData data;\n\n /**\n * Member Data of the user that invoked the command\n */\n private Member member;\n\n}"
},
{
"identifier": "InteractionResponse",
"path": "src/main/java/com/danielvm/destiny2bot/dto/discord/InteractionResponse.java",
"snippet": "@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\npublic class InteractionResponse {\n\n /**\n * The type of the InteractionResponse\n * <br>\n * {@see {@link com.danielvm.destiny2bot.enums.InteractionResponse }}\n */\n private Integer type;\n /**\n * Data attached to the Interaction Response\n */\n private InteractionResponseData data;\n\n /**\n * Creates the default response for a PING request\n *\n * @return InteractionResponse with null data and type 1\n */\n public static Mono<InteractionResponse> PING() {\n return Mono.just(new InteractionResponse(1, null));\n }\n}"
},
{
"identifier": "InteractionResponseData",
"path": "src/main/java/com/danielvm/destiny2bot/dto/discord/InteractionResponseData.java",
"snippet": "@Data\n@Builder\npublic class InteractionResponseData {\n\n /**\n * The message content of the InteractionResponse\n */\n private String content;\n\n /**\n * List of embeds{@link }\n */\n private List<Embedded> embeds;\n\n /**\n * List of choices for autocomplete interactions\n */\n private List<Choice> choices;\n}"
},
{
"identifier": "DestinyCharacterService",
"path": "src/main/java/com/danielvm/destiny2bot/service/DestinyCharacterService.java",
"snippet": "@Service\n@Slf4j\npublic class DestinyCharacterService {\n\n private final BungieClient bungieClient;\n private final UserDetailsReactiveDao userDetailsReactiveDao;\n private final BungieMembershipService bungieMembershipService;\n\n public DestinyCharacterService(\n BungieClient bungieClient,\n UserDetailsReactiveDao userDetailsReactiveDao,\n BungieMembershipService bungieMembershipService) {\n this.bungieClient = bungieClient;\n this.userDetailsReactiveDao = userDetailsReactiveDao;\n this.bungieMembershipService = bungieMembershipService;\n }\n\n /**\n * Retrieves all the characters for a Destiny user\n *\n * @param userId the user's discordId to retrieve the access token\n * @return Flux of {@link DestinyCharacter}s\n */\n public Flux<DestinyCharacter> getCharactersForUser(String userId) {\n return Mono.just(userId)\n .filterWhen(userDetailsReactiveDao::existsByDiscordId)\n .flatMap(userDetailsReactiveDao::getByDiscordId)\n .map(userDetails -> OAuth2Util.formatBearerToken(userDetails.getAccessToken()))\n .flatMap(bungieMembershipService::getUserMembershipInformation)\n .flatMap(membershipResponse -> {\n String membershipId = MembershipUtil.extractMembershipId(membershipResponse);\n Integer membershipType = MembershipUtil.extractMembershipType(membershipResponse);\n return bungieClient.getUserCharacters(membershipType, membershipId);\n })\n .flatMapIterable(characters ->\n characters.getResponse().getCharacters().getData().entrySet())\n .switchIfEmpty(Mono.error(\n new ResourceNotFoundException(\"No characters found for user [%s]\".formatted(userId))))\n .map(entry -> {\n String characterId = entry.getKey();\n String characterClass = DestinyClass.findByCode(entry.getValue().getClassType())\n .getName();\n String characterRace = DestinyRace.findByCode(entry.getValue().getRaceType()).getName();\n Integer lightLevel = entry.getValue().getLight();\n\n return new DestinyCharacter(characterId, characterClass, lightLevel, characterRace);\n });\n }\n}"
}
] | import com.danielvm.destiny2bot.dto.discord.Choice;
import com.danielvm.destiny2bot.dto.discord.Interaction;
import com.danielvm.destiny2bot.dto.discord.InteractionResponse;
import com.danielvm.destiny2bot.dto.discord.InteractionResponseData;
import com.danielvm.destiny2bot.service.DestinyCharacterService;
import java.util.Collections;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono; | 1,375 | package com.danielvm.destiny2bot.factory;
@Component
public class UserCharacterMessageCreator implements AuthorizedMessageFactory {
private static final String CHOICE_FORMAT = "[%s] %s - %s";
private final DestinyCharacterService destinyCharacterService;
public UserCharacterMessageCreator(
DestinyCharacterService destinyCharacterService) {
this.destinyCharacterService = destinyCharacterService;
}
@Override
public Mono<InteractionResponse> createResponse(String userId) {
return destinyCharacterService.getCharactersForUser(userId) | package com.danielvm.destiny2bot.factory;
@Component
public class UserCharacterMessageCreator implements AuthorizedMessageFactory {
private static final String CHOICE_FORMAT = "[%s] %s - %s";
private final DestinyCharacterService destinyCharacterService;
public UserCharacterMessageCreator(
DestinyCharacterService destinyCharacterService) {
this.destinyCharacterService = destinyCharacterService;
}
@Override
public Mono<InteractionResponse> createResponse(String userId) {
return destinyCharacterService.getCharactersForUser(userId) | .map(character -> new Choice(CHOICE_FORMAT.formatted( | 0 | 2023-10-20 05:53:03+00:00 | 2k |
MinecraftForge/ModLauncher | src/main/java/cpw/mods/modlauncher/TransformationServiceDecorator.java | [
{
"identifier": "LabelType",
"path": "src/main/java/cpw/mods/modlauncher/TransformTargetLabel.java",
"snippet": "public enum LabelType {\n FIELD(FieldNode.class),\n METHOD(MethodNode.class),\n CLASS(ClassNode.class),\n PRE_CLASS(ClassNode.class);\n\n private final Class<?> nodeType;\n\n LabelType(Class<?> nodeType) {\n this.nodeType = nodeType;\n }\n\n public Class<?> getNodeType() {\n return nodeType;\n }\n\n @SuppressWarnings(\"unchecked\")\n public <V> TransformList<V> getFromMap(EnumMap<LabelType, TransformList<?>> transformers) {\n return get(transformers, (Class<V>) this.nodeType);\n }\n\n @SuppressWarnings(\"unchecked\")\n private <V> TransformList<V> get(EnumMap<LabelType, TransformList<?>> transformers, Class<V> type) {\n return (TransformList<V>) transformers.get(this);\n }\n\n @SuppressWarnings(\"unchecked\")\n public <T> Supplier<TransformList<T>> mapSupplier(EnumMap<LabelType, TransformList<?>> transformers) {\n return () -> (TransformList<T>) transformers.get(this);\n }\n\n}"
},
{
"identifier": "LogMarkers",
"path": "src/main/java/cpw/mods/modlauncher/LogMarkers.java",
"snippet": "class LogMarkers {\n static final Marker MODLAUNCHER = MarkerManager.getMarker(\"MODLAUNCHER\");\n static final Marker CLASSLOADING = MarkerManager.getMarker(\"CLASSLOADING\").addParents(MODLAUNCHER);\n static final Marker LAUNCHPLUGIN = MarkerManager.getMarker(\"LAUNCHPLUGIN\").addParents(MODLAUNCHER);\n}"
}
] | import cpw.mods.modlauncher.TransformTargetLabel.LabelType;
import cpw.mods.modlauncher.api.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.lang.reflect.Type;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import static cpw.mods.modlauncher.LogMarkers.*; | 923 | /*
* Copyright (c) Forge Development LLC
* SPDX-License-Identifier: LGPL-3.0-only
*/
package cpw.mods.modlauncher;
/**
* Decorates {@link cpw.mods.modlauncher.api.ITransformationService} to track state and other runtime metadata.
*/
public class TransformationServiceDecorator {
private static final Logger LOGGER = LogManager.getLogger();
private final ITransformationService service;
private boolean isValid;
TransformationServiceDecorator(ITransformationService service) {
this.service = service;
}
void onLoad(IEnvironment env, Set<String> otherServices) {
try {
LOGGER.debug(MODLAUNCHER,"Loading service {}", this.service::name);
this.service.onLoad(env, otherServices);
this.isValid = true;
LOGGER.debug(MODLAUNCHER,"Loaded service {}", this.service::name);
} catch (IncompatibleEnvironmentException e) {
LOGGER.error(MODLAUNCHER,"Service failed to load {}", this.service.name(), e);
this.isValid = false;
}
}
boolean isValid() {
return isValid;
}
void onInitialize(IEnvironment environment) {
LOGGER.debug(MODLAUNCHER,"Initializing transformation service {}", this.service::name);
this.service.initialize(environment);
LOGGER.debug(MODLAUNCHER,"Initialized transformation service {}", this.service::name);
}
public void gatherTransformers(TransformStore transformStore) {
LOGGER.debug(MODLAUNCHER, "Initializing transformers for transformation service {}", this.service::name);
var transformers = this.service.transformers();
Objects.requireNonNull(transformers, "The transformers list should not be null");
for (ITransformer<?> transformer : transformers) {
Type type = null;
var genericInterfaces = transformer.getClass().getGenericInterfaces();
for (var typ : genericInterfaces) {
if (typ instanceof ParameterizedType pt && pt.getRawType().equals(ITransformer.class)) {
type = pt.getActualTypeArguments()[0];
break;
}
}
if (type == null) {
LOGGER.error(MODLAUNCHER, "Invalid Transformer, could not determine generic type {}", transformer.getClass().getSimpleName());
throw new IllegalArgumentException("Invalid Transformer, could not determine generic type " + transformer.getClass().getSimpleName());
}
| /*
* Copyright (c) Forge Development LLC
* SPDX-License-Identifier: LGPL-3.0-only
*/
package cpw.mods.modlauncher;
/**
* Decorates {@link cpw.mods.modlauncher.api.ITransformationService} to track state and other runtime metadata.
*/
public class TransformationServiceDecorator {
private static final Logger LOGGER = LogManager.getLogger();
private final ITransformationService service;
private boolean isValid;
TransformationServiceDecorator(ITransformationService service) {
this.service = service;
}
void onLoad(IEnvironment env, Set<String> otherServices) {
try {
LOGGER.debug(MODLAUNCHER,"Loading service {}", this.service::name);
this.service.onLoad(env, otherServices);
this.isValid = true;
LOGGER.debug(MODLAUNCHER,"Loaded service {}", this.service::name);
} catch (IncompatibleEnvironmentException e) {
LOGGER.error(MODLAUNCHER,"Service failed to load {}", this.service.name(), e);
this.isValid = false;
}
}
boolean isValid() {
return isValid;
}
void onInitialize(IEnvironment environment) {
LOGGER.debug(MODLAUNCHER,"Initializing transformation service {}", this.service::name);
this.service.initialize(environment);
LOGGER.debug(MODLAUNCHER,"Initialized transformation service {}", this.service::name);
}
public void gatherTransformers(TransformStore transformStore) {
LOGGER.debug(MODLAUNCHER, "Initializing transformers for transformation service {}", this.service::name);
var transformers = this.service.transformers();
Objects.requireNonNull(transformers, "The transformers list should not be null");
for (ITransformer<?> transformer : transformers) {
Type type = null;
var genericInterfaces = transformer.getClass().getGenericInterfaces();
for (var typ : genericInterfaces) {
if (typ instanceof ParameterizedType pt && pt.getRawType().equals(ITransformer.class)) {
type = pt.getActualTypeArguments()[0];
break;
}
}
if (type == null) {
LOGGER.error(MODLAUNCHER, "Invalid Transformer, could not determine generic type {}", transformer.getClass().getSimpleName());
throw new IllegalArgumentException("Invalid Transformer, could not determine generic type " + transformer.getClass().getSimpleName());
}
| LabelType seen = null; | 0 | 2023-10-18 17:56:01+00:00 | 2k |
Kyrotechnic/KyroClient | Client/src/main/java/me/kyroclient/modules/player/ServerRotations.java | [
{
"identifier": "Module",
"path": "Client/src/main/java/me/kyroclient/modules/Module.java",
"snippet": "public class Module {\n @Expose\n @SerializedName(\"name\")\n public String name;\n @Expose\n @SerializedName(\"toggled\")\n private boolean toggled;\n @Expose\n @SerializedName(\"keyCode\")\n private int keycode;\n private final Category category;\n public boolean extended;\n @Expose\n @SerializedName(\"settings\")\n public ConfigManager.ConfigSetting[] cfgSettings;\n private boolean devOnly;\n public final MilliTimer toggledTime;\n public final List<Setting> settings;\n\n public Module(final String name, final int keycode, final Category category) {\n this.toggledTime = new MilliTimer();\n this.settings = new ArrayList<Setting>();\n this.name = name;\n this.keycode = keycode;\n this.category = category;\n }\n\n public Module(final String name, final Category category) {\n this(name, 0, category);\n }\n\n public boolean isToggled() {\n return this.toggled;\n }\n\n public void toggle() {\n this.setToggled(!this.toggled);\n }\n\n public void onEnable() {\n }\n public void assign()\n {\n\n }\n\n public void onSave() {\n }\n\n public String getSuffix()\n {\n return null;\n }\n\n public void addSetting(final Setting setting) {\n this.getSettings().add(setting);\n }\n\n public void addSettings(final Setting... settings) {\n for (final Setting setting : settings) {\n this.addSetting(setting);\n }\n }\n\n public Category getCategory() {\n return this.category;\n }\n\n public String getName() {\n return this.name;\n }\n\n public boolean isPressed() {\n return this.keycode != 0 && Keyboard.isKeyDown(this.keycode);\n }\n\n public int getKeycode() {\n return this.keycode;\n }\n\n public void setKeycode(final int keycode) {\n this.keycode = keycode;\n }\n\n public List<Setting> getSettings() {\n return this.settings;\n }\n\n public static List<Module> getModulesByCategory(final Category c) {\n return (List<Module>) KyroClient.moduleManager.getModules().stream().filter(module -> module.category == c).collect(Collectors.toList());\n }\n\n /*public static <T> T getModule(final Class<T> module) {\n for (final Module m : KyroClient.modules) {\n if (m.getClass().equals(module)) {\n return (T)m;\n }\n }\n return null;\n }\n\n public static Module getModule(final Predicate<Module> predicate) {\n for (final Module m : KyroClient.modules) {\n if (predicate.test(m)) {\n return m;\n }\n }\n return null;\n }\n\n public static Module getModule(final String string) {\n for (final Module m : KyroClient.modules) {\n if (m.getName().equalsIgnoreCase(string)) {\n return m;\n }\n }\n return null;\n }*/\n\n public void setToggled(final boolean toggled) {\n if (this.toggled != toggled) {\n this.toggled = toggled;\n this.toggledTime.reset();\n if (toggled) {\n this.onEnable();\n }\n else {\n this.onDisable();\n }\n }\n }\n\n public String suffix()\n {\n return \"\";\n }\n\n public void onDisable() {\n }\n\n public void setDevOnly(final boolean devOnly) {\n this.devOnly = devOnly;\n }\n\n public boolean isDevOnly() {\n return this.devOnly;\n }\n\n protected static void sendMessage(final String message) {\n KyroClient.mc.thePlayer.addChatMessage(new ChatComponentText(message));\n }\n\n public enum Category\n {\n CRIMSONISLE(\"Crimson Isle\"),\n GARDEN(\"Garden\"),\n RIFT(\"Rift\"),\n DUNGEONS(\"Dungeons\"),\n PLAYER(\"Player\"),\n RENDER(\"Render\"),\n COMBAT(\"Combat\"),\n MISC(\"Misc\"),\n DIANA(\"Diana\"),\n MINING(\"Mining\"),\n CLIENT(\"Client\");\n\n public String name;\n\n private Category(final String name) {\n this.name = name;\n }\n }\n}"
},
{
"identifier": "BooleanSetting",
"path": "Client/src/main/java/me/kyroclient/settings/BooleanSetting.java",
"snippet": "public class BooleanSetting extends Setting\n{\n @Expose\n @SerializedName(\"value\")\n private boolean enabled;\n\n public BooleanSetting(final String name, final boolean enabled) {\n super(name);\n this.enabled = enabled;\n }\n\n public BooleanSetting(final String name, final boolean enabled, final Predicate<Boolean> isHidden) {\n super(name, isHidden);\n this.enabled = enabled;\n }\n\n public boolean isEnabled() {\n return this.enabled;\n }\n\n public void setEnabled(final boolean enabled) {\n this.enabled = enabled;\n }\n\n public void toggle() {\n this.setEnabled(!this.isEnabled());\n }\n}"
}
] | import me.kyroclient.modules.Module;
import me.kyroclient.settings.BooleanSetting; | 1,337 | package me.kyroclient.modules.player;
public class ServerRotations extends Module
{
private static ServerRotations instance; | package me.kyroclient.modules.player;
public class ServerRotations extends Module
{
private static ServerRotations instance; | public BooleanSetting onlyKillAura; | 1 | 2023-10-15 16:24:51+00:00 | 2k |
LucidDaddyYT/mystical-ash-mod | src/main/java/com/luciddemon/mysticalash/MysticalAsh.java | [
{
"identifier": "ModEntityTypes",
"path": "src/main/java/com/luciddemon/mysticalash/entity/ModEntityTypes.java",
"snippet": "public class ModEntityTypes {\n public static final DeferredRegister<EntityType<?>> ENTITY_TYPES =\n DeferredRegister.create(ForgeRegistries.ENTITIES, MysticalAsh.MODID);\n\n public static final RegistryObject<EntityType<QuadwingEntity>> QUADWING =\n ENTITY_TYPES.register(\"quadwing\",\n () -> EntityType.Builder.of(QuadwingEntity::new, MobCategory.CREATURE)\n .sized(0.8f, 0.6f)\n .build(new ResourceLocation(MysticalAsh.MODID, \"quadwing\").toString()));\n\n\n public static void register(IEventBus eventBus) {\n ENTITY_TYPES.register(eventBus);\n }\n}"
},
{
"identifier": "QuadwingRenderer",
"path": "src/main/java/com/luciddemon/mysticalash/entity/client/QuadwingRenderer.java",
"snippet": "public class QuadwingRenderer extends GeoEntityRenderer<QuadwingEntity> {\n public QuadwingRenderer(EntityRendererProvider.Context renderManager) {\n super(renderManager, new QuadwingModel());\n this.shadowRadius = 2.0f;\n }\n\n @Override\n public ResourceLocation getTextureLocation(QuadwingEntity instance) {\n return new ResourceLocation(MysticalAsh.MODID, \"textures/entity/quadwing.png\");\n }\n}"
},
{
"identifier": "ModItems",
"path": "src/main/java/com/luciddemon/mysticalash/item/ModItems.java",
"snippet": "public class ModItems {\n public static final DeferredRegister<Item> ITEMS =\n DeferredRegister.create(ForgeRegistries.ITEMS, MysticalAsh.MODID);\n\n public static final RegistryObject<Item> OBSIDIAN_SHARD = ITEMS.register(\"obsidian_shard\",\n () -> new Item(new Item.Properties().tab(ModCreativeModeTab.MYSTICAL_ASH)));\n\n public static final RegistryObject<Item> QUADWING_SPAWN_EGG = ITEMS.register(\"quadwing_spawn_egg\",\n () -> new ForgeSpawnEggItem(ModEntityTypes.QUADWING,0x948e8d, 0x3b3635,\n new Item.Properties().tab(ModCreativeModeTab.MYSTICAL_ASH)));\n\n\n\n public static void register(IEventBus eventBus) {\n ITEMS.register(eventBus);\n }\n}"
}
] | import com.luciddemon.mysticalash.entity.ModEntityTypes;
import com.luciddemon.mysticalash.entity.client.QuadwingRenderer;
import com.luciddemon.mysticalash.item.ModItems;
import com.mojang.logging.LogUtils;
import net.minecraft.client.renderer.entity.EntityRenderers;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.InterModComms;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.event.lifecycle.InterModEnqueueEvent;
import net.minecraftforge.fml.event.lifecycle.InterModProcessEvent;
import net.minecraftforge.event.server.ServerStartingEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.slf4j.Logger;
import software.bernie.geckolib3.GeckoLib;
import java.util.stream.Collectors; | 915 | package com.luciddemon.mysticalash;
// The value here should match an entry in the META-INF/mods.toml file
@Mod(MysticalAsh.MODID)
public class MysticalAsh
{
public static final String MODID = "mysticalash";
// Directly reference a slf4j logger
private static final Logger LOGGER = LogUtils.getLogger();
public MysticalAsh()
{
//Get EventBus
IEventBus eventBus = FMLJavaModLoadingContext.get().getModEventBus();
// Register the setup method for modloading
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);
//Register ModItems | package com.luciddemon.mysticalash;
// The value here should match an entry in the META-INF/mods.toml file
@Mod(MysticalAsh.MODID)
public class MysticalAsh
{
public static final String MODID = "mysticalash";
// Directly reference a slf4j logger
private static final Logger LOGGER = LogUtils.getLogger();
public MysticalAsh()
{
//Get EventBus
IEventBus eventBus = FMLJavaModLoadingContext.get().getModEventBus();
// Register the setup method for modloading
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);
//Register ModItems | ModItems.register(eventBus); | 2 | 2023-10-18 15:57:40+00:00 | 2k |
ssap-rainbow/SSAP-BackEnd | src/main/java/ssap/ssap/controller/ErrandDetailedController.java | [
{
"identifier": "Task",
"path": "src/main/java/ssap/ssap/domain/Task.java",
"snippet": "@Getter\n@Setter\n@ToString\n@NoArgsConstructor\n@Entity\n@Table(name = \"tasks\")\npublic class Task {\n //ToDo: 테이블 필드 검증 추가 필요\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column\n private Long id;\n\n @Column\n private String title;\n\n @Column\n private String description;\n\n// @Column\n// private String location;\n\n @Column\n private String roadAddress;\n\n @Column\n private String jibunAddress;\n\n @Column\n private String detailedAddress;\n\n @Column\n private String preferredGender;\n\n @Column\n private String startTime;\n\n @Column\n private String endTime;\n\n @Column\n private String fee;\n\n @Column\n private Boolean auctionStatus;\n\n @Column\n private Boolean termsAgreed;\n\n @Column\n private String auctionStartTime;\n\n @Column\n private String auctionEndTime;\n\n @Column\n private String status;\n\n @ManyToOne(fetch = FetchType.LAZY)\n @JoinColumn(name = \"user_id\")\n private User user;\n\n @ManyToOne(fetch = FetchType.LAZY)\n @JoinColumn(name = \"helper_id\")\n private User helper;\n\n @ManyToOne(fetch = FetchType.LAZY)\n @JoinColumn(name = \"category_id\")\n private Category category;\n\n @ManyToOne(fetch = FetchType.LAZY)\n @JoinColumn(name = \"detailed_item_id\")\n private DetailedItem detailedItem;\n\n @ManyToOne(fetch = FetchType.LAZY)\n @JoinColumn(name = \"auction_id\")\n private Auction auction;\n\n @OneToMany(mappedBy = \"task\", cascade = CascadeType.ALL)\n private List<TaskAttachment> attachments; // Task와 ThumbNailEntity의 연관 관계 설정\n}"
},
{
"identifier": "ErrandDetailedService",
"path": "src/main/java/ssap/ssap/service/ErrandDetailedService.java",
"snippet": "@Service\npublic class ErrandDetailedService {\n\n private final TaskRepository taskRepository;\n private final UserRepository userRepository;\n\n private final AuctionRepository auctionRepository;\n\n @Autowired\n public ErrandDetailedService(TaskRepository taskRepository, UserRepository userRepository, AuctionRepository auctionRepository) {\n this.taskRepository = taskRepository;\n this.userRepository = userRepository;\n this.auctionRepository = auctionRepository;\n }\n\n // taskId를 받아 심부름 상세 정보를 조회\n public Map<String, Object> getErrandDetails(Long taskId) {\n // Task 객체를 찾으며, 찾을 수 없다면 예외를 발생\n Task task = taskRepository.findById(taskId)\n .orElseThrow(() -> new EntityNotFoundException(\"taskId 을 찾을 수 없습니다.: \" + taskId));\n\n // User 객체를 찾으며, 찾을 수 없다면 예외를 발생\n User requester = userRepository.findById(task.getUser().getUserId())\n .orElseThrow(() -> new EntityNotFoundException(\"userId 을 찾을 수 없습니다.: \" + task.getUser().getUserId()));\n\n // Auction 객체를 찾으며, 존재하지 않는 경우에 대한 처리를 추가\n Optional<Auction> auction = auctionRepository.findByTaskId(task.getId());\n\n // 조회된 정보를 바탕으로 Map을 생성하여 반환\n Map<String, Object> details = new HashMap<>();\n\n // 각 필드에 대한 정보를 Map에 저장\n details.put(\"categoryTag\", task.getCategory().getCategoryName());\n details.put(\"detailitem\", task.getDetailedItem().getDetailedItemName());\n details.put(\"title\", task.getTitle());\n details.put(\"description\", task.getDescription());\n details.put(\"fee\", task.getFee());\n details.put(\"auctionStartTime\", task.getAuctionStartTime());\n details.put(\"auctionEndTime\", task.getAuctionEndTime());\n details.put(\"StartTime\", task.getStartTime());\n details.put(\"EndTime\", task.getEndTime());\n details.put(\"roadAddress\", task.getRoadAddress());\n details.put(\"jibunAddress\", task.getJibunAddress());\n details.put(\"detailedAddress\", task.getDetailedAddress());\n details.put(\"name\", task.getUser().getName());\n details.put(\"ageRange\", task.getUser().getAgeRange());\n details.put(\"gender\", task.getUser().getGender());\n details.put(\"profileImageUrl\", task.getUser().getProfileImageUrl());\n // Auction 객체가 존재하는 경우 해당 ID를 저장, 존재하지 않는 경우 null 저장\n details.put(\"auctionId\", auction.map(Auction::getId).orElse(null));\n\n return details;\n }\n}"
},
{
"identifier": "OAuthService",
"path": "src/main/java/ssap/ssap/service/OAuthService.java",
"snippet": "public interface OAuthService {\n LoginResponseDto kakaoLogin(String provider, String code, HttpServletResponse response);\n\n boolean isAccessTokenValid(String accessToken);\n\n String refreshAccessToken(String refreshToken);\n\n void logout(String provider, String accessToken);\n}"
}
] | import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.persistence.EntityNotFoundException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ssap.ssap.domain.Task;
import ssap.ssap.service.ErrandDetailedService;
import ssap.ssap.service.OAuthService;
import java.util.Map; | 1,395 | package ssap.ssap.controller;
@RestController
@Slf4j
@CrossOrigin(origins = "*")
@RequestMapping("api/errands")
@Tag(name = "심부름 상세 페이지", description = "심부름 상세 페이지 관련 API")
public class ErrandDetailedController {
private final ErrandDetailedService errandDetailedService; | package ssap.ssap.controller;
@RestController
@Slf4j
@CrossOrigin(origins = "*")
@RequestMapping("api/errands")
@Tag(name = "심부름 상세 페이지", description = "심부름 상세 페이지 관련 API")
public class ErrandDetailedController {
private final ErrandDetailedService errandDetailedService; | private final OAuthService oAuthService; | 2 | 2023-10-17 08:45:39+00:00 | 2k |
aws-samples/transactional-outbox-pattern | outboxApp/src/main/java/com/amazonaws/samples/controller/FlightController.java | [
{
"identifier": "Flight",
"path": "outboxApp/src/main/java/com/amazonaws/samples/model/Flight.java",
"snippet": "@Entity\n@Table(name = \"flights\")\n@EntityListeners(AuditingEntityListener.class)\n@Getter\n@Setter\n@NoArgsConstructor(force = true)\npublic class Flight {\n @Id\n @GeneratedValue\n private Long id;\n\n @NotBlank(message = \"Departure airport cannot be blank\")\n @NotNull\n private String departureAirport;\n\n @NotBlank(message = \"Destination airport cannot be blank\")\n @NotNull\n private String arrivalAirport;\n\n @NotNull\n @Temporal(TemporalType.TIMESTAMP)\n private Date departureDateTime;\n\n @NotNull\n @Temporal(TemporalType.TIMESTAMP)\n private Date arrivalDateTime;\n\n}"
},
{
"identifier": "FlightOutbox",
"path": "outboxApp/src/main/java/com/amazonaws/samples/model/FlightOutbox.java",
"snippet": "@Entity\n@Table(name = \"flightsOutbox\")\n@EntityListeners(AuditingEntityListener.class)\n@RequiredArgsConstructor\n@NoArgsConstructor(force = true)\n@Getter\n@Setter\npublic class FlightOutbox {\n\n public enum EventType {\n FLIGHT_BOOKED\n }\n\n @Id\n @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = \"outbox_seq\")\n private Long id;\n\n private final String aggregateId;\n\n @Enumerated(EnumType.STRING)\n private final EventType eventType;\n\n @Column(columnDefinition = \"json\")\n @JdbcTypeCode(SqlTypes.JSON)\n private final JsonNode payload;\n}"
},
{
"identifier": "FlightRepository",
"path": "outboxApp/src/main/java/com/amazonaws/samples/repository/FlightRepository.java",
"snippet": "@Repository\npublic interface FlightRepository extends JpaRepository<Flight, Long> {\n\n}"
},
{
"identifier": "OutboxRepository",
"path": "outboxApp/src/main/java/com/amazonaws/samples/repository/OutboxRepository.java",
"snippet": "@Repository\npublic interface OutboxRepository extends JpaRepository<FlightOutbox, Long> {\n @Lock(LockModeType.PESSIMISTIC_WRITE)\n Page<FlightOutbox> findAllByOrderByIdAsc(Pageable pageable);\n}"
}
] | import com.amazonaws.samples.model.Flight;
import com.amazonaws.samples.model.FlightOutbox;
import com.amazonaws.samples.repository.FlightRepository;
import com.amazonaws.samples.repository.OutboxRepository;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import java.util.List; | 704 | package com.amazonaws.samples.controller;
@RestController
@RequestMapping("/api")
@AllArgsConstructor
public class FlightController {
final FlightRepository flightRepository;
final OutboxRepository outboxRepository;
final ObjectMapper objectMapper;
@GetMapping("/flights")
public List<Flight> getAllFlights() {
return flightRepository.findAll();
}
@PostMapping("/flights")
@Transactional
public Flight createFlight(@Valid @RequestBody Flight flight) {
Flight savedFlight = flightRepository.save(flight);
JsonNode flightPayload = objectMapper.convertValue(flight, JsonNode.class); | package com.amazonaws.samples.controller;
@RestController
@RequestMapping("/api")
@AllArgsConstructor
public class FlightController {
final FlightRepository flightRepository;
final OutboxRepository outboxRepository;
final ObjectMapper objectMapper;
@GetMapping("/flights")
public List<Flight> getAllFlights() {
return flightRepository.findAll();
}
@PostMapping("/flights")
@Transactional
public Flight createFlight(@Valid @RequestBody Flight flight) {
Flight savedFlight = flightRepository.save(flight);
JsonNode flightPayload = objectMapper.convertValue(flight, JsonNode.class); | FlightOutbox outboxEvent = new FlightOutbox(flight.getId().toString(), FlightOutbox.EventType.FLIGHT_BOOKED, | 1 | 2023-10-19 07:09:48+00:00 | 2k |
easy1staking-com/jpgstore-java-client | src/test/java/com/easy1staking/jpgstore/jpgstorejavaclient/service/JpgstorePurchaseServiceTest.java | [
{
"identifier": "AccountConfig",
"path": "src/main/java/com/easy1staking/jpgstore/jpgstorejavaclient/config/AccountConfig.java",
"snippet": "@Configuration\npublic class AccountConfig {\n\n @Bean\n public Account account(@Value(\"${wallet.mnemonic}\") String mnemonic) {\n return new Account(mnemonic);\n }\n\n\n}"
},
{
"identifier": "BlockfrostConfig",
"path": "src/main/java/com/easy1staking/jpgstore/jpgstorejavaclient/config/BlockfrostConfig.java",
"snippet": "@Configuration\npublic class BlockfrostConfig {\n\n @Value(\"${blockfrost.url}\")\n private String blockfrostUrl;\n\n @Value(\"${blockfrost.key}\")\n private String blockfrostKey;\n\n @Bean\n public AddressService addressService() {\n return new AddressServiceImpl(blockfrostUrl, \"\");\n }\n\n @Bean\n public TransactionService transactionService() {\n return new TransactionServiceImpl(blockfrostUrl, \"\");\n }\n\n @Bean\n public MetadataService metadataService() {\n return new MetadataServiceImpl(blockfrostUrl, \"\");\n }\n\n @Bean\n public BFBackendService bfBackendService() {\n return new BFBackendService(Constants.BLOCKFROST_MAINNET_URL, blockfrostKey);\n }\n\n}"
},
{
"identifier": "JacksonConfig",
"path": "src/main/java/com/easy1staking/jpgstore/jpgstorejavaclient/config/JacksonConfig.java",
"snippet": "@Configuration\npublic class JacksonConfig {\n\n @Bean\n public ObjectMapper objectMapper() {\n ObjectMapper objectMapper = new ObjectMapper();\n SimpleModule module = new SimpleModule();\n module.addSerializer(ConstrPlutusData.class, new ConstrDataJsonSerializer());\n module.addSerializer(BigIntPlutusData.class,new BigIntDataJsonSerializer());\n module.addSerializer(BytesPlutusData.class,new BytesDataJsonSerializer());\n module.addSerializer(ListPlutusData.class,new ListDataJsonSerializer());\n module.addSerializer(MapPlutusData.class,new MapDataJsonSerializer());\n objectMapper.registerModule(module);\n return objectMapper;\n }\n\n\n}"
},
{
"identifier": "Constants",
"path": "src/main/java/com/easy1staking/jpgstore/jpgstorejavaclient/model/Constants.java",
"snippet": "public class Constants {\n\n public static final String JPG_CONTRACT_ADDRESS = \"addr1zxgx3far7qygq0k6epa0zcvcvrevmn0ypsnfsue94nsn3tvpw288a4x0xf8pxgcntelxmyclq83s0ykeehchz2wtspks905plm\";\n\n}"
}
] | import com.bloxbean.cardano.client.api.exception.ApiException;
import com.bloxbean.cardano.client.api.model.Result;
import com.bloxbean.cardano.client.api.model.Utxo;
import com.bloxbean.cardano.client.backend.blockfrost.service.BFBackendService;
import com.bloxbean.cardano.client.plutus.spec.PlutusData;
import com.easy1staking.jpgstore.jpgstorejavaclient.config.AccountConfig;
import com.easy1staking.jpgstore.jpgstorejavaclient.config.BlockfrostConfig;
import com.easy1staking.jpgstore.jpgstorejavaclient.config.JacksonConfig;
import com.easy1staking.jpgstore.jpgstorejavaclient.model.Constants;
import com.easy1staking.jpgstore.jpgstorejavaclient.model.ListingDetails;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertTrue; | 946 | package com.easy1staking.jpgstore.jpgstorejavaclient.service;
@SpringBootTest(classes = {AccountConfig.class, BlockfrostConfig.class, JacksonConfig.class, JpgstorePurchaseService.class, ListingDatumService.class})
class JpgstorePurchaseServiceTest {
@Autowired
private JpgstorePurchaseService jpgstorePurchaseService;
@Autowired
private BFBackendService bfBackendService;
@Autowired
private ListingDatumService listingDatumService;
/**
* Fully working code to puchase an NFT from jpg.store
* @throws ApiException
*/
@Test
public void purchaseNft() throws ApiException {
| package com.easy1staking.jpgstore.jpgstorejavaclient.service;
@SpringBootTest(classes = {AccountConfig.class, BlockfrostConfig.class, JacksonConfig.class, JpgstorePurchaseService.class, ListingDatumService.class})
class JpgstorePurchaseServiceTest {
@Autowired
private JpgstorePurchaseService jpgstorePurchaseService;
@Autowired
private BFBackendService bfBackendService;
@Autowired
private ListingDatumService listingDatumService;
/**
* Fully working code to puchase an NFT from jpg.store
* @throws ApiException
*/
@Test
public void purchaseNft() throws ApiException {
| Result<List<Utxo>> utxos = bfBackendService.getUtxoService().getUtxos(Constants.JPG_CONTRACT_ADDRESS, | 3 | 2023-10-23 13:49:15+00:00 | 2k |
LuckPerms/rest-api-java-client | src/main/java/net/luckperms/rest/service/TrackService.java | [
{
"identifier": "CreateTrackRequest",
"path": "src/main/java/net/luckperms/rest/model/CreateTrackRequest.java",
"snippet": "public class CreateTrackRequest extends AbstractModel {\n private final String name;\n\n public CreateTrackRequest(String name) {\n this.name = name;\n }\n\n public String name() {\n return this.name;\n }\n}"
},
{
"identifier": "Track",
"path": "src/main/java/net/luckperms/rest/model/Track.java",
"snippet": "public class Track extends AbstractModel {\n private final String name;\n private final List<String> groups;\n\n public Track(String name, List<String> groups) {\n this.name = name;\n this.groups = groups;\n }\n\n public String name() {\n return this.name;\n }\n\n public List<String> groups() {\n return this.groups;\n }\n}"
},
{
"identifier": "UpdateTrackRequest",
"path": "src/main/java/net/luckperms/rest/model/UpdateTrackRequest.java",
"snippet": "public class UpdateTrackRequest extends AbstractModel {\n private final List<String> groups;\n\n public UpdateTrackRequest(List<String> groups) {\n this.groups = groups;\n }\n\n public List<String> username() {\n return this.groups;\n }\n}"
}
] | import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.PATCH;
import retrofit2.http.POST;
import retrofit2.http.Path;
import java.util.Set;
import net.luckperms.rest.model.CreateTrackRequest;
import net.luckperms.rest.model.Track;
import net.luckperms.rest.model.UpdateTrackRequest;
import retrofit2.Call;
import retrofit2.http.Body; | 679 | /*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.luckperms.rest.service;
public interface TrackService {
@GET("/track")
Call<Set<String>> list();
@POST("/track") | /*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.luckperms.rest.service;
public interface TrackService {
@GET("/track")
Call<Set<String>> list();
@POST("/track") | Call<Track> create(@Body CreateTrackRequest req); | 1 | 2023-10-22 16:07:30+00:00 | 2k |
mervekeser/tobeto.intro | oopWithNLayeredApp/src/main/java/org/example/Main.java | [
{
"identifier": "ProductManager",
"path": "oopWithNLayeredApp/src/main/java/org/example/business/ProductManager.java",
"snippet": "public class ProductManager {\n private ProductDao productDao;\n private Logger[] loggers;\n public ProductManager(ProductDao productDao, Logger[] loggers) {\n this.productDao = productDao;\n this.loggers = loggers;\n }\n\n public void add(Product product1) throws Exception{\n //iş kuralları buraya yazılıyor\n if(product1.getUnitPrice()<10){\n throw new Exception(\"Ürün fiyatı 10'dan küçük olamaz\");\n }\n\n //ProductDao productDao = new JdbcProductDao(); //Buraya JdbcProductDao yazsak onuda kabul eder\n productDao.add(product1); //bir katman başka bir katmanın classını kullanıyorken\n\n for (Logger logger: loggers) { //[db, file, mail]\n logger.log(product1.getName());\n } // sadece interface'inden erişim kurmalıdır\n }\n}"
},
{
"identifier": "DatabaseLogger",
"path": "oopWithNLayeredApp/src/main/java/org/example/core/logging/DatabaseLogger.java",
"snippet": "public class DatabaseLogger implements Logger{\n @Override\n public void log(String data) {\n System.out.println(\"Veritabanına loglandı: \" + data);\n }\n}"
},
{
"identifier": "FileLogger",
"path": "oopWithNLayeredApp/src/main/java/org/example/core/logging/FileLogger.java",
"snippet": "public class FileLogger implements Logger{\n\n @Override\n public void log(String data) {\n System.out.println(\"Dosyaya loglandı: \" + data);\n }\n}"
},
{
"identifier": "Logger",
"path": "oopWithNLayeredApp/src/main/java/org/example/core/logging/Logger.java",
"snippet": "public interface Logger {\n void log(String data);\n}"
},
{
"identifier": "MailLogger",
"path": "oopWithNLayeredApp/src/main/java/org/example/core/logging/MailLogger.java",
"snippet": "public class MailLogger implements Logger{\n @Override\n public void log(String data) {\n System.out.println(\"Mail gönderildi: \" + data);\n }\n}"
},
{
"identifier": "HibernateProductDao",
"path": "oopWithNLayeredApp/src/main/java/org/example/dataAccess/HibernateProductDao.java",
"snippet": "public class HibernateProductDao implements ProductDao{\n public void add(Product product){\n //sadece db erişim kodları buraya yazılır... SQL\n System.out.println(\"Hibernate ile veritabanına eklendi\");\n }\n\n}"
},
{
"identifier": "JdbcProductDao",
"path": "oopWithNLayeredApp/src/main/java/org/example/dataAccess/JdbcProductDao.java",
"snippet": "public class JdbcProductDao implements ProductDao{\n public void add(Product product){\n //sadece db erişim kodları buraya yazılır... SQL\n System.out.println(\"JDBC ile veritabanına eklendi\");\n }\n}"
},
{
"identifier": "Product",
"path": "oopWithNLayeredApp/src/main/java/org/example/entities/Product.java",
"snippet": "public class Product {\n private int id;\n private String name;\n private double unitPrice;\n\n public Product() {\n\n }\n\n public Product(int id, String name, double unitPrice) {\n this.id = id;\n this.name = name;\n this.unitPrice = unitPrice;\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public double getUnitPrice() {\n return unitPrice;\n }\n\n public void setUnitPrice(double unitPrice) {\n this.unitPrice = unitPrice;\n }\n}"
}
] | import org.example.business.ProductManager;
import org.example.core.logging.DatabaseLogger;
import org.example.core.logging.FileLogger;
import org.example.core.logging.Logger;
import org.example.core.logging.MailLogger;
import org.example.dataAccess.HibernateProductDao;
import org.example.dataAccess.JdbcProductDao;
import org.example.entities.Product;
import java.util.List; | 1,027 | package org.example;
public class Main {
public static void main(String[] args) throws Exception {
Product product1 = new Product(1, "IPhone Xr", 10000);
Logger[] loggers = {new DatabaseLogger(), new FileLogger(), new MailLogger()};
| package org.example;
public class Main {
public static void main(String[] args) throws Exception {
Product product1 = new Product(1, "IPhone Xr", 10000);
Logger[] loggers = {new DatabaseLogger(), new FileLogger(), new MailLogger()};
| ProductManager productManager = new ProductManager(new HibernateProductDao(), loggers); | 5 | 2023-10-23 14:56:19+00:00 | 2k |
EvanAatrox/hubbo | hubbo-service-facade/src/main/java/cn/hubbo/service/impl/RoleServiceImpl.java | [
{
"identifier": "RoleDao",
"path": "hubbo-dao/src/main/java/cn/hubbo/dao/RoleDao.java",
"snippet": "@Repository\npublic interface RoleDao extends JpaRepository<Role, Integer> {\n\n\n}"
},
{
"identifier": "UserDao",
"path": "hubbo-dao/src/main/java/cn/hubbo/dao/UserDao.java",
"snippet": "public interface UserDao extends JpaRepository<User, Integer> {\n\n\n User queryByUsernameEquals(String username);\n\n\n}"
},
{
"identifier": "Role",
"path": "hubbo-domain/src/main/java/cn/hubbo/domain/dos/Role.java",
"snippet": "@Data\n@ToString(exclude = {\"users\"})\n@Accessors(chain = true)\n@Entity(name = \"t_role\")\n@Table(indexes = {@Index(name = \"role_name_index\", columnList = \"role_name\", unique = true), @Index(name = \"permission_code_index\", columnList = \"permission_code\", unique = true)})\npublic class Role {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"role_id\", columnDefinition = \"smallint\")\n @Comment(\"角色ID\")\n private Integer roleId;\n\n\n @Column(name = \"role_name\", columnDefinition = \"varchar(60)\", nullable = false)\n @Comment(\"角色名\")\n private String roleName;\n\n\n @Column(name = \"permission_code\", columnDefinition = \"varchar(60)\", nullable = false)\n @Comment(\"角色拥有的权限字符串,系统的权限字符由三部分组成,一级资源分类.具体资源名.要进行的操作 三部分组成\")\n private String permissionCode;\n\n @Column(name = \"role_status\", columnDefinition = \"bit(1) default 1\")\n @Comment(\"角色状态,1启用,0禁用\")\n private boolean roleStatus;\n\n\n @Column(name = \"delete_flag\", columnDefinition = \"bit(1) default 0\", nullable = false)\n @Comment(\"逻辑删除的标志位,0未删除,1删除\")\n private boolean deleteFlag;\n\n\n @Column(name = \"creator_code\", columnDefinition = \"integer\", nullable = false, updatable = false)\n @Comment(\"创建者编号\")\n private Integer creatorCode;\n\n @Column(name = \"create_time\", columnDefinition = \"timestamp default current_timestamp()\", updatable = false)\n @Comment(\"角色的创建时间\")\n private Date creatTime;\n\n\n @Column(name = \"update_time\", columnDefinition = \"timestamp\")\n @Comment(\"最近一次的更新时间\")\n private Date updateTime;\n\n\n @Column(name = \"delete_time\", columnDefinition = \"timestamp\", updatable = false)\n @Comment(\"删除时间\")\n private Date deleteTime;\n\n @ManyToMany(mappedBy = \"roles\", fetch = FetchType.EAGER)\n private List<User> users;\n\n @ManyToMany(fetch = FetchType.EAGER)\n @JoinTable(name = \"t_role_menu\", joinColumns = {@JoinColumn(name = \"role_id\", nullable = false)}, inverseJoinColumns = {@JoinColumn(name = \"menu_id\", nullable = false)})\n private List<Menu> menus;\n\n}"
},
{
"identifier": "IRoleService",
"path": "hubbo-service/src/main/java/cn/hubbo/service/IRoleService.java",
"snippet": "public interface IRoleService {\n\n /**\n * @param role 角色信息\n *\n * @return 保存的角色信息\n */\n\n Role save(Role role);\n\n\n /**\n * 根据编号查询角色信息\n *\n * @param id 角色id\n *\n * @return role信息\n */\n Optional<Role> queryById(Integer id);\n \n\n}"
}
] | import cn.hubbo.dao.RoleDao;
import cn.hubbo.dao.UserDao;
import cn.hubbo.domain.dos.Role;
import cn.hubbo.service.IRoleService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Optional; | 1,036 | package cn.hubbo.service.impl;
/**
* @author 张晓华
* @version V1.0
* @Package cn.hubbo.service.impl
* @date 2023/10/22 12:17
* @Copyright © 2023-2025 版权所有,未经授权均为剽窃,作者保留一切权利
*/
@Service
@AllArgsConstructor
public class RoleServiceImpl implements IRoleService {
| package cn.hubbo.service.impl;
/**
* @author 张晓华
* @version V1.0
* @Package cn.hubbo.service.impl
* @date 2023/10/22 12:17
* @Copyright © 2023-2025 版权所有,未经授权均为剽窃,作者保留一切权利
*/
@Service
@AllArgsConstructor
public class RoleServiceImpl implements IRoleService {
| private RoleDao roleDao; | 0 | 2023-10-18 09:38:29+00:00 | 2k |
Xernas78/menu-lib | src/main/java/dev/xernas/menulib/Menu.java | [
{
"identifier": "InventorySize",
"path": "src/main/java/dev/xernas/menulib/utils/InventorySize.java",
"snippet": "public enum InventorySize {\n\n SMALLEST(9),\n SMALL(18),\n NORMAL(27),\n LARGE(36),\n LARGER(45),\n LARGEST(54);\n\n private final int size;\n\n InventorySize(int size) {\n this.size = size;\n }\n\n public int getSize() {\n return size;\n }\n}"
},
{
"identifier": "ItemUtils",
"path": "src/main/java/dev/xernas/menulib/utils/ItemUtils.java",
"snippet": "public class ItemUtils {\n\n public static ItemStack createItem(String name, Material material) {\n ItemStack itemStack = new ItemStack(material);\n ItemMeta meta = itemStack.getItemMeta();\n meta.setDisplayName(name);\n itemStack.setItemMeta(meta);\n return itemStack;\n }\n\n public final boolean isItem(ItemStack item, String itemId) {\n PersistentDataContainer dataContainer = Objects.requireNonNull(item.getItemMeta()).getPersistentDataContainer();\n if (dataContainer.has(MenuLib.getItemIdKey(), PersistentDataType.STRING)) {\n return Objects.equals(dataContainer.get(MenuLib.getItemIdKey(), PersistentDataType.STRING), itemId);\n }\n return false;\n }\n\n}"
}
] | import dev.xernas.menulib.utils.InventorySize;
import dev.xernas.menulib.utils.ItemUtils;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataContainer;
import org.bukkit.persistence.PersistentDataType;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects; | 657 | package dev.xernas.menulib;
public abstract class Menu implements InventoryHolder {
private final Player owner;
public Menu(Player owner) {
this.owner = owner;
}
@NotNull
public abstract String getName();
@NotNull
public abstract InventorySize getInventorySize();
public String getPermission() {
return null;
}
public String getNoPermissionMessage() {
return "";
}
public abstract void onInventoryClick(InventoryClickEvent e);
@NotNull
public abstract Map<Integer, ItemStack> getContent();
public final void open() {
if (getPermission() != null && !getPermission().isEmpty()) {
if (!owner.hasPermission(getPermission())) {
owner.sendMessage(getNoPermissionMessage());
return;
}
}
Inventory inventory = getInventory();
getContent().forEach(inventory::setItem);
owner.openInventory(inventory);
}
public final Map<Integer, ItemStack> fill(Material material) {
Map<Integer, ItemStack> map = new HashMap<>();
for (int i = 0; i < getInventorySize().getSize(); i++) { | package dev.xernas.menulib;
public abstract class Menu implements InventoryHolder {
private final Player owner;
public Menu(Player owner) {
this.owner = owner;
}
@NotNull
public abstract String getName();
@NotNull
public abstract InventorySize getInventorySize();
public String getPermission() {
return null;
}
public String getNoPermissionMessage() {
return "";
}
public abstract void onInventoryClick(InventoryClickEvent e);
@NotNull
public abstract Map<Integer, ItemStack> getContent();
public final void open() {
if (getPermission() != null && !getPermission().isEmpty()) {
if (!owner.hasPermission(getPermission())) {
owner.sendMessage(getNoPermissionMessage());
return;
}
}
Inventory inventory = getInventory();
getContent().forEach(inventory::setItem);
owner.openInventory(inventory);
}
public final Map<Integer, ItemStack> fill(Material material) {
Map<Integer, ItemStack> map = new HashMap<>();
for (int i = 0; i < getInventorySize().getSize(); i++) { | ItemStack filler = ItemUtils.createItem(" ", material); | 1 | 2023-10-23 16:02:26+00:00 | 2k |
USSEndeavour/UniversityGradeTracker | src/universitymanagement/models/Student.java | [
{
"identifier": "NoSubjectsException",
"path": "src/universitymanagement/exceptions/NoSubjectsException.java",
"snippet": "public class NoSubjectsException extends Exception {\n public NoSubjectsException() {\n }\n\n public NoSubjectsException(String message) {\n super(message);\n }\n\n public NoSubjectsException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public NoSubjectsException(Throwable cause) {\n super(cause);\n }\n}"
},
{
"identifier": "InvalidSubjectException",
"path": "src/universitymanagement/exceptions/InvalidSubjectException.java",
"snippet": "public class InvalidSubjectException extends Exception {\n public InvalidSubjectException() {\n }\n\n public InvalidSubjectException(String message){\n super(message);\n }\n\n public InvalidSubjectException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public InvalidSubjectException(Throwable cause) {\n super(cause);\n }\n}"
},
{
"identifier": "InvalidGradeException",
"path": "src/universitymanagement/exceptions/InvalidGradeException.java",
"snippet": "public class InvalidGradeException extends Exception {\n public InvalidGradeException() {\n }\n\n public InvalidGradeException(String message){\n super(message);\n }\n\n public InvalidGradeException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public InvalidGradeException(Throwable cause) {\n super(cause);\n }\n}"
},
{
"identifier": "ExistingSubjectException",
"path": "src/universitymanagement/exceptions/ExistingSubjectException.java",
"snippet": "public class ExistingSubjectException extends Exception {\n public ExistingSubjectException() {\n }\n\n public ExistingSubjectException(String message){\n super(message);\n }\n\n public ExistingSubjectException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public ExistingSubjectException(Throwable cause) {\n super(cause);\n }\n}"
}
] | import java.util.ArrayList;
import universitymanagement.exceptions.NoSubjectsException;
import universitymanagement.exceptions.InvalidSubjectException;
import universitymanagement.exceptions.InvalidGradeException;
import universitymanagement.exceptions.ExistingSubjectException; | 761 | package universitymanagement.models;
public class Student {
private String name;
private final ArrayList<Subject> subjects;
// Constructor to initialize a Student with a name and an empty list of subjects.
public Student(String name) {
this.name = name;
this.subjects = new ArrayList<>();
}
// Getter method to retrieve the name of the student.
public String getName() {
return name;
}
// Method to add a subject to the student's list of subjects.
// Throws ExistingSubjectException if the subject with the same name already exists in the list.
public void addSubject(Subject subject) throws ExistingSubjectException {
boolean flag = false;
for (Subject s: subjects) {
if (s.getName().equals(subject.getName())) {
flag = true;
break;
}
}
if (flag)
throw new ExistingSubjectException(name + " is already enrolled in the " + subject.getName() + " course!");
subjects.add(subject);
}
// Method to remove a subject from the student's list of subjects.
public void removeSubject(Subject subject) {
subjects.remove(subject);
}
// Getter method to retrieve the list of subjects that the student is enrolled in.
public ArrayList<Subject> getSubjects() {
return subjects;
}
// Method to get a specific subject by its name.
// Throws InvalidSubjectException if the subject with the given name is not found. | package universitymanagement.models;
public class Student {
private String name;
private final ArrayList<Subject> subjects;
// Constructor to initialize a Student with a name and an empty list of subjects.
public Student(String name) {
this.name = name;
this.subjects = new ArrayList<>();
}
// Getter method to retrieve the name of the student.
public String getName() {
return name;
}
// Method to add a subject to the student's list of subjects.
// Throws ExistingSubjectException if the subject with the same name already exists in the list.
public void addSubject(Subject subject) throws ExistingSubjectException {
boolean flag = false;
for (Subject s: subjects) {
if (s.getName().equals(subject.getName())) {
flag = true;
break;
}
}
if (flag)
throw new ExistingSubjectException(name + " is already enrolled in the " + subject.getName() + " course!");
subjects.add(subject);
}
// Method to remove a subject from the student's list of subjects.
public void removeSubject(Subject subject) {
subjects.remove(subject);
}
// Getter method to retrieve the list of subjects that the student is enrolled in.
public ArrayList<Subject> getSubjects() {
return subjects;
}
// Method to get a specific subject by its name.
// Throws InvalidSubjectException if the subject with the given name is not found. | public Subject getSubject(Subjects subjectName) throws InvalidSubjectException, InvalidGradeException { | 1 | 2023-10-18 05:33:31+00:00 | 2k |
samdsk/lab-sweng | e03-2023giu/src/test/java/it/unimi/di/sweng/esame/model/ModelTest.java | [
{
"identifier": "Observable",
"path": "e01-2023gen/src/main/java/it/unimi/di/sweng/esame/Observable.java",
"snippet": "public interface Observable<T> {\n\tvoid addObserver(@NotNull Observer<@NotNull T> observer);\n\tvoid removeObserver(@NotNull Observer<@NotNull T> observer);\n\t@NotNull T getState();\n\n\tvoid notifyObservers();\n}"
},
{
"identifier": "Observer",
"path": "e01-2023gen/src/main/java/it/unimi/di/sweng/esame/Observer.java",
"snippet": "public interface Observer<T> {\n\tvoid update(@NotNull Observable<T> observable, @NotNull T state);\n}"
},
{
"identifier": "DisplayPresenter",
"path": "e02-2023feb/src/main/java/it/unimi/di/sweng/esame/presenters/DisplayPresenter.java",
"snippet": "public class DisplayPresenter implements Observer<List<Canzone>> {\n\tprivate final Observable<List<Canzone>> model;\n\tprivate final DisplayView view;\n\tprivate int offset = 0;\n\tprivate int limit = Main.PANEL_SIZE;\n\tprivate @NotNull PrintStrategy printStrategy = new ClassificaPrintStrategy();\n\tprivate @NotNull OrderStrategy orderStrategy = new ClassificaOrder();\n\n\tpublic DisplayPresenter(@NotNull Observable<List<Canzone>> model,@NotNull DisplayView view) {\n\t\tthis.model = model;\n\t\tthis.view = view;\n\t\tmodel.addObserver(this);\n\t}\n\n\tpublic DisplayPresenter(@NotNull Observable<List<Canzone>> model, @NotNull DisplayView view, int offset) {\n\t\tthis(model,view);\n\t\tthis.offset = offset;\n\t}\n\n\tpublic DisplayPresenter(@NotNull Observable<List<Canzone>> model, @NotNull DisplayView view, int offset, int limit) {\n\t\tthis(model,view,offset);\n\t\tthis.limit = limit;\n\t}\n\n\t@Override\n\tpublic void update(@NotNull Observable<List<Canzone>> observable, @NotNull List<Canzone> state) {\n\t\torderStrategy.sort(state);\n\n\t\tfor (int i = 0; i < limit && i+offset < state.size(); i++) {\n\t\t\tview.set(i,printStrategy.format(state.get(i+offset)));\n\t\t}\n\t}\n\n\tpublic @NotNull DisplayPresenter setPrintStrategy(@NotNull PrintStrategy printStrategy) {\n\t\tthis.printStrategy = printStrategy;\n\t\treturn this;\n\t}\n\n\tpublic DisplayPresenter setOrderStrategy(OrderStrategy orderStrategy) {\n\t\tthis.orderStrategy = orderStrategy;\n\t\treturn this;\n\t}\n}"
}
] | import it.unimi.di.sweng.esame.Observable;
import it.unimi.di.sweng.esame.Observer;
import it.unimi.di.sweng.esame.presenters.DisplayPresenter;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.*; | 1,397 | package it.unimi.di.sweng.esame.model;
public class ModelTest {
@Test
void testSegnalzione() {
String tratto = "A4";
int posizione = 4;
Segnalazione SUT = new Segnalazione(new Posizione(tratto,posizione),"incidente");
assertThat(SUT.formatDisplay()).isEqualTo("incidente sulla A4 al Km 4");
}
@Test
void testSegnalzionePosizioneMustBePositive() {
String tratto = "A4";
int posizione = -4;
assertThatThrownBy(()->new Segnalazione(new Posizione(tratto,posizione),"incidente"))
.isInstanceOf(IllegalArgumentException.class).hasMessage("Posizione deve essere positiva");
}
@Test
void testSegnalaRisolto() {
Segnalazione SUT = new Segnalazione(new Posizione("A4",45),"incidente");
assertThat(SUT.segnalaComeRisolto().isRisolto()).isTrue();
assertThat(SUT.isRisolto()).isFalse();
}
@Test
void testPosizione() {
Posizione SUT = new Posizione("A4",45);
assertThat(SUT.formatDisplay()).isEqualTo("A4 al Km 45");
}
@Test
void testModel() {
Model SUT = new Model();
Segnalazione segnalazione = mock(Segnalazione.class);
Posizione posizione = new Posizione("A4",45);
when(segnalazione.getPosizione()).thenReturn(posizione);
SUT.addSegnalazione(segnalazione);
assertThat(SUT.contains(posizione)).isTrue();
}
@Test
void testModelDuplicates() {
Model SUT = new Model();
Segnalazione segnalazione = mock(Segnalazione.class);
Posizione posizione = new Posizione("A4",45);
when(segnalazione.getPosizione()).thenReturn(posizione);
SUT.addSegnalazione(segnalazione);
assertThatThrownBy(()-> SUT.addSegnalazione(segnalazione))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("altra segnalazione già presente per questo tratto");
}
@Test
void testContaSegnalazioniNonRisolti() {
Model SUT = new Model();
Posizione p1 = new Posizione("A3",45);
Segnalazione s1 = createMockedSegnalzione(p1,false);
Posizione p2 = new Posizione("A4",45);
Segnalazione s2 = createMockedSegnalzione(p2,false);
SUT.addSegnalazione(s1);
SUT.addSegnalazione(s2);
assertThat(SUT.segnalazioniAperti()).isEqualTo(2);
SUT.risolvi(p2);
assertThat(SUT.segnalazioniAperti()).isEqualTo(1);
}
public static Segnalazione createMockedSegnalzione(@NotNull Posizione p, boolean risolto){
Segnalazione s = mock(Segnalazione.class);
when(s.getPosizione()).thenReturn(p);
when(s.isRisolto()).thenReturn(risolto);
when(s.formatDisplay()).thenReturn(String.format("incidente sulla %s",p.formatDisplay()));
return s;
}
@Test
void testObserver() {
Observable<List<Segnalazione>> SUT = new ObservableModel(); | package it.unimi.di.sweng.esame.model;
public class ModelTest {
@Test
void testSegnalzione() {
String tratto = "A4";
int posizione = 4;
Segnalazione SUT = new Segnalazione(new Posizione(tratto,posizione),"incidente");
assertThat(SUT.formatDisplay()).isEqualTo("incidente sulla A4 al Km 4");
}
@Test
void testSegnalzionePosizioneMustBePositive() {
String tratto = "A4";
int posizione = -4;
assertThatThrownBy(()->new Segnalazione(new Posizione(tratto,posizione),"incidente"))
.isInstanceOf(IllegalArgumentException.class).hasMessage("Posizione deve essere positiva");
}
@Test
void testSegnalaRisolto() {
Segnalazione SUT = new Segnalazione(new Posizione("A4",45),"incidente");
assertThat(SUT.segnalaComeRisolto().isRisolto()).isTrue();
assertThat(SUT.isRisolto()).isFalse();
}
@Test
void testPosizione() {
Posizione SUT = new Posizione("A4",45);
assertThat(SUT.formatDisplay()).isEqualTo("A4 al Km 45");
}
@Test
void testModel() {
Model SUT = new Model();
Segnalazione segnalazione = mock(Segnalazione.class);
Posizione posizione = new Posizione("A4",45);
when(segnalazione.getPosizione()).thenReturn(posizione);
SUT.addSegnalazione(segnalazione);
assertThat(SUT.contains(posizione)).isTrue();
}
@Test
void testModelDuplicates() {
Model SUT = new Model();
Segnalazione segnalazione = mock(Segnalazione.class);
Posizione posizione = new Posizione("A4",45);
when(segnalazione.getPosizione()).thenReturn(posizione);
SUT.addSegnalazione(segnalazione);
assertThatThrownBy(()-> SUT.addSegnalazione(segnalazione))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("altra segnalazione già presente per questo tratto");
}
@Test
void testContaSegnalazioniNonRisolti() {
Model SUT = new Model();
Posizione p1 = new Posizione("A3",45);
Segnalazione s1 = createMockedSegnalzione(p1,false);
Posizione p2 = new Posizione("A4",45);
Segnalazione s2 = createMockedSegnalzione(p2,false);
SUT.addSegnalazione(s1);
SUT.addSegnalazione(s2);
assertThat(SUT.segnalazioniAperti()).isEqualTo(2);
SUT.risolvi(p2);
assertThat(SUT.segnalazioniAperti()).isEqualTo(1);
}
public static Segnalazione createMockedSegnalzione(@NotNull Posizione p, boolean risolto){
Segnalazione s = mock(Segnalazione.class);
when(s.getPosizione()).thenReturn(p);
when(s.isRisolto()).thenReturn(risolto);
when(s.formatDisplay()).thenReturn(String.format("incidente sulla %s",p.formatDisplay()));
return s;
}
@Test
void testObserver() {
Observable<List<Segnalazione>> SUT = new ObservableModel(); | Observer<List<Segnalazione>> presenter = mock(DisplayPresenter.class); | 1 | 2023-10-19 06:28:13+00:00 | 2k |
RoessinghResearch/senseeact | SenSeeActServiceLib/src/main/java/nl/rrd/senseeact/service/FileServer.java | [
{
"identifier": "BadRequestException",
"path": "SenSeeActServiceLib/src/main/java/nl/rrd/senseeact/service/exception/BadRequestException.java",
"snippet": "@ResponseStatus(value=HttpStatus.BAD_REQUEST)\npublic class BadRequestException extends HttpException {\n\tprivate static final long serialVersionUID = 1L;\n\t\n\tpublic BadRequestException() {\n\t\tsuper(\"Bad Request\");\n\t}\n\n\tpublic BadRequestException(String message) {\n\t\tsuper(message);\n\t}\n\t\n\tpublic BadRequestException(String code, String message) {\n\t\tsuper(code, message);\n\t}\n\t\n\tpublic BadRequestException(HttpError error) {\n\t\tsuper(error);\n\t}\n\t\n\tpublic BadRequestException appendInvalidInput(BadRequestException other) {\n\t\tList<HttpFieldError> errors = new ArrayList<>();\n\t\tfor (HttpFieldError error : getError().getFieldErrors()) {\n\t\t\terrors.add(error);\n\t\t}\n\t\tfor (HttpFieldError error : other.getError().getFieldErrors()) {\n\t\t\terrors.add(error);\n\t\t}\n\t\treturn withInvalidInput(errors);\n\t}\n\t\n\tpublic BadRequestException appendInvalidInput(\n\t\t\tHttpFieldError... fieldErrors) {\n\t\treturn appendInvalidInput(Arrays.asList(fieldErrors));\n\t}\n\t\n\tpublic BadRequestException appendInvalidInput(\n\t\t\tList<HttpFieldError> fieldErrors) {\n\t\tList<HttpFieldError> newErrors = new ArrayList<>();\n\t\tfor (HttpFieldError error : getError().getFieldErrors()) {\n\t\t\tnewErrors.add(error);\n\t\t}\n\t\tfor (HttpFieldError error : fieldErrors) {\n\t\t\tnewErrors.add(error);\n\t\t}\n\t\treturn withInvalidInput(newErrors);\n\t}\n\t\n\tpublic static BadRequestException withInvalidInput(\n\t\t\tHttpFieldError... fieldErrors) {\n\t\treturn withInvalidInput(Arrays.asList(fieldErrors));\n\t}\n\n\tpublic static BadRequestException withInvalidInput(\n\t\t\tList<HttpFieldError> fieldErrors) {\n\t\tStringBuffer errorMsg = new StringBuffer();\n\t\tString newline = System.getProperty(\"line.separator\");\n\t\tfor (HttpFieldError fieldError : fieldErrors) {\n\t\t\tif (errorMsg.length() > 0)\n\t\t\t\terrorMsg.append(newline);\n\t\t\terrorMsg.append(fieldError.getMessage());\n\t\t}\n\t\tHttpError error = new HttpError(ErrorCode.INVALID_INPUT,\n\t\t\t\terrorMsg.toString());\n\t\tfor (HttpFieldError fieldError : fieldErrors) {\n\t\t\terror.addFieldError(fieldError);\n\t\t}\n\t\treturn new BadRequestException(error);\n\t}\n}"
},
{
"identifier": "HttpException",
"path": "SenSeeActServiceLib/src/main/java/nl/rrd/senseeact/service/exception/HttpException.java",
"snippet": "public abstract class HttpException extends Exception {\n\tprivate static final long serialVersionUID = 1L;\n\t\n\tprivate HttpError error;\n\n\t/**\n\t * Constructs a new HTTP exception with default error code 0.\n\t * \n\t * @param message the error message\n\t */\n\tpublic HttpException(String message) {\n\t\tsuper(message);\n\t\terror = new HttpError(null, message);\n\t}\n\t\n\t/**\n\t * Constructs a new HTTP exception.\n\t * \n\t * @param code the error code (default null)\n\t * @param message the error message\n\t */\n\tpublic HttpException(String code, String message) {\n\t\tsuper(message);\n\t\terror = new HttpError(code, message);\n\t}\n\t\n\t/**\n\t * Constructs a new HTTP exception with the specified error.\n\t * \n\t * @param error the error\n\t */\n\tpublic HttpException(HttpError error) {\n\t\tsuper(error.getMessage());\n\t\tthis.error = error;\n\t}\n\n\t/**\n\t * Returns the error details.\n\t * \n\t * @return the error details\n\t */\n\tpublic HttpError getError() {\n\t\treturn error;\n\t}\n\t\n\t/**\n\t * Returns the HTTP exception for the specified HTTP status code.\n\t * Unsupported status codes will be mapped to an {@link\n\t * InternalServerErrorException InternalServerErrorException}.\n\t * \n\t * @param statusCode the HTTP status code\n\t * @param error the error details\n\t * @return the HTTP exception\n\t */\n\tpublic static HttpException forStatus(int statusCode, HttpError error) {\n\t\tswitch (statusCode) {\n\t\tcase 400:\n\t\t\treturn new BadRequestException(error);\n\t\tcase 401:\n\t\t\treturn new UnauthorizedException(error);\n\t\tcase 403:\n\t\t\treturn new ForbiddenException(error);\n\t\tcase 404:\n\t\t\treturn new NotFoundException(error);\n\t\tcase 501:\n\t\t\treturn new NotImplementedException(error);\n\t\tdefault:\n\t\t\treturn new InternalServerErrorException(error);\n\t\t}\n\t}\n}"
}
] | import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import nl.rrd.utils.exception.ParseException;
import nl.rrd.utils.http.HttpRange;
import nl.rrd.senseeact.service.exception.BadRequestException;
import nl.rrd.senseeact.service.exception.HttpException;
import java.io.*; | 1,192 | package nl.rrd.senseeact.service;
public class FileServer {
public static void readFile(HttpServletRequest request,
HttpServletResponse response, File file, String contentType) | package nl.rrd.senseeact.service;
public class FileServer {
public static void readFile(HttpServletRequest request,
HttpServletResponse response, File file, String contentType) | throws HttpException, IOException { | 1 | 2023-10-24 09:36:50+00:00 | 2k |
Kipp-ie/LunarisMC | LunarisMC-Plugin/src/main/java/dev/kippenboutske/lunarismcplugin.java | [
{
"identifier": "joinListener",
"path": "LunarisMC-Plugin/src/main/java/dev/kippenboutske/listeners/joinListener.java",
"snippet": "public class joinListener implements Listener {\n @EventHandler\n public void onJoin(PlayerJoinEvent e) {\n Player player = e.getPlayer();\n MiniMessage mm = MiniMessage.miniMessage();\n final Component name = mm.deserialize(\"<blue>Welcome in <bold>testing</bold></blue>\");\n final BossBar bossbar = BossBar.bossBar( name, 1, BossBar.Color.BLUE, BossBar.Overlay.NOTCHED_20);\n player.showBossBar(bossbar);\n player.sendMessage(\"Hello \" + PlainTextComponentSerializer.plainText().serialize(player.displayName()) + \"! Welcome in LunarisMC !\");\n player.sendMessage(\"Your current ping is: \" + player.getPing() + \"MS!\");\n e.joinMessage(mm.deserialize(\"<gray>[ų] \" + PlainTextComponentSerializer.plainText().serialize(player.displayName())+ \"</gray>\"));\n final Component header = mm.deserialize(\"<blue>\\n Welcome in \\n </blue>\" + \"<bold>testing</bold>\");\n final Component footer = mm.deserialize(\"<blue>Have a great time!</blue>\" + \"\\n\" + \"<aqua>Cheese</aqua>\");\n player.sendPlayerListHeaderAndFooter( header, footer);\n\n }\n}"
},
{
"identifier": "leaveListener",
"path": "LunarisMC-Plugin/src/main/java/dev/kippenboutske/listeners/leaveListener.java",
"snippet": "public class leaveListener implements Listener {\n @EventHandler\n public void onLeave(PlayerQuitEvent e) {\n Player player = e.getPlayer();\n MiniMessage mm = MiniMessage.miniMessage();\n e.quitMessage(mm.deserialize(\"<gray>[ť] \" + PlainTextComponentSerializer.plainText().serialize(player.displayName()) + \"</gray>\"));\n\n }\n}"
}
] | import dev.kippenboutske.listeners.joinListener;
import dev.kippenboutske.listeners.leaveListener;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin; | 880 | package dev.kippenboutske;
public final class lunarismcplugin extends JavaPlugin {
@Override
public void onEnable() {
Bukkit.getLogger().info("██╗░░░░░██╗░░░██╗███╗░░██╗░█████╗░██████╗░██╗░██████╗███╗░░░███╗░█████╗░");
Bukkit.getLogger().info("██║░░░░░██║░░░██║████╗░██║██╔══██╗██╔══██╗██║██╔════╝████╗░████║██╔══██╗");
Bukkit.getLogger().info("██║░░░░░██║░░░██║██╔██╗██║███████║██████╔╝██║╚█████╗░██╔████╔██║██║░░╚═╝");
Bukkit.getLogger().info("██║░░░░░██║░░░██║██║╚████║██╔══██║██╔══██╗██║░╚═══██╗██║╚██╔╝██║██║░░██╗");
Bukkit.getLogger().info("███████╗╚██████╔╝██║░╚███║██║░░██║██║░░██║██║██████╔╝██║░╚═╝░██║╚█████╔╝");
Bukkit.getLogger().info("╚══════╝░╚═════╝░╚═╝░░╚══╝╚═╝░░╚═╝╚═╝░░╚═╝╚═╝╚═════╝░╚═╝░░░░░╚═╝░╚════╝░"); | package dev.kippenboutske;
public final class lunarismcplugin extends JavaPlugin {
@Override
public void onEnable() {
Bukkit.getLogger().info("██╗░░░░░██╗░░░██╗███╗░░██╗░█████╗░██████╗░██╗░██████╗███╗░░░███╗░█████╗░");
Bukkit.getLogger().info("██║░░░░░██║░░░██║████╗░██║██╔══██╗██╔══██╗██║██╔════╝████╗░████║██╔══██╗");
Bukkit.getLogger().info("██║░░░░░██║░░░██║██╔██╗██║███████║██████╔╝██║╚█████╗░██╔████╔██║██║░░╚═╝");
Bukkit.getLogger().info("██║░░░░░██║░░░██║██║╚████║██╔══██║██╔══██╗██║░╚═══██╗██║╚██╔╝██║██║░░██╗");
Bukkit.getLogger().info("███████╗╚██████╔╝██║░╚███║██║░░██║██║░░██║██║██████╔╝██║░╚═╝░██║╚█████╔╝");
Bukkit.getLogger().info("╚══════╝░╚═════╝░╚═╝░░╚══╝╚═╝░░╚═╝╚═╝░░╚═╝╚═╝╚═════╝░╚═╝░░░░░╚═╝░╚════╝░"); | Bukkit.getPluginManager().registerEvents(new joinListener(), this); | 0 | 2023-10-21 22:13:29+00:00 | 2k |
imart302/DulceNectar-BE | src/main/java/com/dulcenectar/java/services/interfaces/InboxService.java | [
{
"identifier": "CreateInboxRequestDto",
"path": "src/main/java/com/dulcenectar/java/dtos/inbox/CreateInboxRequestDto.java",
"snippet": "public class CreateInboxRequestDto implements RequestDto<Inbox> {\n\t\n\tprivate String name;\n\tprivate String message;\n\tprivate String senderEmail;\n\tprivate Long phoneNumber;\n\n\tpublic CreateInboxRequestDto(String name, String message, String senderEmail, Long phoneNumber) {\n\t\tsuper();\n\t\tthis.name = name;\n\t\tthis.message = message;\n\t\tthis.senderEmail = senderEmail;\n\t\tthis.phoneNumber = phoneNumber;\n\t}\n\n\tpublic CreateInboxRequestDto() {\n\t\tsuper();\n\t}\n\n\t@Override\n\tpublic Inbox toEntity() {\n\t\tInbox inbox = new Inbox();\n\t\tinbox.setMessage(this.message);\n\t\tinbox.setSenderEmail(this.senderEmail);\n\t\tinbox.setName(this.name);\n\t\tinbox.setPhoneNumber(this.phoneNumber.toString());\n\t\t\n\t\treturn inbox;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getMessage() {\n\t\treturn message;\n\t}\n\n\tpublic void setMessage(String message) {\n\t\tthis.message = message;\n\t}\n\n\tpublic String getSenderEmail() {\n\t\treturn senderEmail;\n\t}\n\n\tpublic void setSenderEmail(String senderEmail) {\n\t\tthis.senderEmail = senderEmail;\n\t}\n\n\tpublic Long getPhoneNumber() {\n\t\treturn phoneNumber;\n\t}\n\n\tpublic void setPhoneNumber(Long phoneNumber) {\n\t\tthis.phoneNumber = phoneNumber;\n\t}\n\t\n}"
},
{
"identifier": "Inbox",
"path": "src/main/java/com/dulcenectar/java/models/Inbox.java",
"snippet": "@Entity\n@Table(name = \"inbox\")\npublic class Inbox {\n \n\t@Id\n\t@GeneratedValue(strategy=GenerationType.IDENTITY)\n\tprivate Integer id;\n\tprivate String message;\n\tprivate String senderEmail;\n\tprivate String phoneNumber;\n\tprivate String name;\n \n\t@CreationTimestamp\n\tprivate LocalDateTime createdAt;\n \n\tpublic Inbox(Integer id, String message, String senderEmail, String phoneNumber, String name,\n\t\t\tLocalDateTime createdAt) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.message = message;\n\t\tthis.senderEmail = senderEmail;\n\t\tthis.phoneNumber = phoneNumber;\n\t\tthis.name = name;\n\t\tthis.createdAt = createdAt;\n\t}\n \n\tpublic Inbox(Integer id) {\n\t\tsuper();\n\t\tthis.id = id;\n\t}\n \n\tpublic Inbox() {\n\t\tsuper();\n\t}\n \n\tpublic long getId() {\n\t\treturn id;\n\t}\n \n\tpublic void setId(Integer id) {\n\t\tthis.id = id;\n\t}\n \n\tpublic String getMessage() {\n\t\treturn message;\n\t}\n \n\tpublic void setMessage(String message) {\n\t\tthis.message = message;\n\t}\n \n\tpublic String getSenderEmail() {\n\t\treturn senderEmail;\n\t}\n \n\tpublic void setSenderEmail(String senderEmail) {\n\t\tthis.senderEmail = senderEmail;\n\t}\n \n\tpublic String getPhoneNumber() {\n\t\treturn phoneNumber;\n\t}\n \n\tpublic void setPhoneNumber(String phoneNumber) {\n\t\tthis.phoneNumber = phoneNumber;\n\t}\n \n\tpublic String getName() {\n\t\treturn name;\n\t}\n \n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n \n\tpublic LocalDateTime getCreatedAt() {\n\t\treturn createdAt;\n\t}\n \n\tpublic void setCreatedAt(LocalDateTime createdAt) {\n\t\tthis.createdAt = createdAt;\n\t}\n}"
}
] | import java.util.List;
import com.dulcenectar.java.dtos.inbox.CreateInboxRequestDto;
import com.dulcenectar.java.models.Inbox; | 949 | package com.dulcenectar.java.services.interfaces;
public interface InboxService {
public String createInbox(CreateInboxRequestDto inbox); | package com.dulcenectar.java.services.interfaces;
public interface InboxService {
public String createInbox(CreateInboxRequestDto inbox); | public List<Inbox> getAllInbox(); | 1 | 2023-10-24 00:07:39+00:00 | 2k |
hendisantika/spring-boot-event-sourcing | stock-management-eventstore/src/main/java/com/hendisantika/stockmanagementeventstore/controller/StockController.java | [
{
"identifier": "Stock",
"path": "stock-management-eventstore/src/main/java/com/hendisantika/stockmanagementeventstore/dto/Stock.java",
"snippet": "@Data\npublic class Stock {\n\n private String name;\n\n private int quantity;\n\n private String user;\n}"
},
{
"identifier": "StockAddedEvent",
"path": "stock-management-eventstore/src/main/java/com/hendisantika/stockmanagementeventstore/dto/StockAddedEvent.java",
"snippet": "@Builder\n@Data\npublic class StockAddedEvent implements StockEvent {\n private Stock stockDetails;\n}"
},
{
"identifier": "StockRemovedEvent",
"path": "stock-management-eventstore/src/main/java/com/hendisantika/stockmanagementeventstore/dto/StockRemovedEvent.java",
"snippet": "@Builder\n@Data\npublic class StockRemovedEvent implements StockEvent {\n private Stock stockDetails;\n}"
},
{
"identifier": "EventStore",
"path": "stock-management-eventstore/src/main/java/com/hendisantika/stockmanagementeventstore/entity/EventStore.java",
"snippet": "@Entity\n@Data\npublic class EventStore {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private long eventId;\n\n private String eventType;\n\n private String entityId;\n\n private String eventData;\n\n private LocalDateTime eventTime;\n}"
},
{
"identifier": "EventService",
"path": "stock-management-eventstore/src/main/java/com/hendisantika/stockmanagementeventstore/service/EventService.java",
"snippet": "@Service\n@RequiredArgsConstructor\n@Slf4j\npublic class EventService {\n\n private final EventRepository eventRepository;\n\n public EventStore addEvent(StockAddedEvent event) throws JsonProcessingException {\n\n EventStore eventStore = new EventStore();\n\n eventStore.setEventData(new ObjectMapper().writeValueAsString(event.getStockDetails()));\n\n eventStore.setEventType(\"STOCK_ADDED\");\n\n eventStore.setEntityId(event.getStockDetails().getName());\n\n eventStore.setEventTime(LocalDateTime.now());\n\n return eventRepository.save(eventStore);\n }\n\n public EventStore removeStockEvent(StockRemovedEvent event) throws JsonProcessingException {\n\n EventStore eventStore = new EventStore();\n\n eventStore.setEventData(new ObjectMapper().writeValueAsString(event.getStockDetails()));\n\n eventStore.setEventType(\"STOCK_REMOVED\");\n eventStore.setEntityId(event.getStockDetails().getName());\n\n eventStore.setEventTime(LocalDateTime.now());\n\n return eventRepository.save(eventStore);\n }\n\n public Iterable<EventStore> fetchAllEvents(String name) {\n return eventRepository.findByEntityId(name);\n }\n\n public Iterable<EventStore> fetchAllEventsTillDate(String name, LocalDateTime date) {\n return eventRepository.findByEntityIdAndEventTimeLessThanEqual(name, date);\n }\n}"
}
] | import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.gson.Gson;
import com.hendisantika.stockmanagementeventstore.dto.Stock;
import com.hendisantika.stockmanagementeventstore.dto.StockAddedEvent;
import com.hendisantika.stockmanagementeventstore.dto.StockRemovedEvent;
import com.hendisantika.stockmanagementeventstore.entity.EventStore;
import com.hendisantika.stockmanagementeventstore.service.EventService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.time.LocalDateTime; | 906 | package com.hendisantika.stockmanagementeventstore.controller;
/**
* Created by IntelliJ IDEA.
* Project : spring-boot-event-sourcing
* User: hendi
* Email: hendisantika@gmail.com
* Telegram : @hendisantika34
* Link : s.id/hendisantika
* Date: 10/16/2023
* Time: 11:19 AM
* To change this template use File | Settings | File Templates.
*/
@RestController
@RequiredArgsConstructor
@Slf4j
@RequestMapping("/stocks")
public class StockController {
private final EventService eventService;
@PostMapping | package com.hendisantika.stockmanagementeventstore.controller;
/**
* Created by IntelliJ IDEA.
* Project : spring-boot-event-sourcing
* User: hendi
* Email: hendisantika@gmail.com
* Telegram : @hendisantika34
* Link : s.id/hendisantika
* Date: 10/16/2023
* Time: 11:19 AM
* To change this template use File | Settings | File Templates.
*/
@RestController
@RequiredArgsConstructor
@Slf4j
@RequestMapping("/stocks")
public class StockController {
private final EventService eventService;
@PostMapping | public EventStore addStock(@RequestBody Stock stockRequest) throws JsonProcessingException { | 3 | 2023-10-16 03:37:14+00:00 | 2k |
DaveScott99/ToyStore-JSP | src/main/java/br/com/toyStore/dao/UserDAO.java | [
{
"identifier": "DbException",
"path": "src/main/java/br/com/toyStore/exception/DbException.java",
"snippet": "public class DbException extends RuntimeException {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic DbException(String msg) {\n\t\tsuper(msg);\n\t}\n\t\n}"
},
{
"identifier": "Product",
"path": "src/main/java/br/com/toyStore/model/Product.java",
"snippet": "public class Product implements Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\t\n\tprivate Long id;\n\tprivate String name;\n\tprivate Double price;\n\tprivate String imageName;\n\tprivate String brand;\n\tprivate String description;\n\t\n\tprivate Category category;\n\t\n\tpublic Product() {\n\t}\n\n\tpublic Product(Long id, String name, Double price, String imageName, String brand, String description,\n\t\t\tCategory category) {\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t\tthis.price = price;\n\t\tthis.imageName = imageName;\n\t\tthis.brand = brand;\n\t\tthis.description = description;\n\t\tthis.category = category;\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic Double getPrice() {\n\t\treturn price;\n\t}\n\n\tpublic void setPrice(Double price) {\n\t\tthis.price = price;\n\t}\n\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\n\tpublic void setDescription(String description) {\n\t\tthis.description = description;\n\t}\n\n\tpublic Category getCategory() {\n\t\treturn category;\n\t}\n\n\tpublic void setCategory(Category category) {\n\t\tthis.category = category;\n\t}\n\n\tpublic String getImageName() {\n\t\treturn imageName;\n\t}\n\n\tpublic void setImageName(String imageName) {\n\t\tthis.imageName = imageName;\n\t}\n\n\tpublic String getBrand() {\n\t\treturn brand;\n\t}\n\n\tpublic void setBrand(String brand) {\n\t\tthis.brand = brand;\n\t}\n\t\n}"
},
{
"identifier": "User",
"path": "src/main/java/br/com/toyStore/model/User.java",
"snippet": "public class User {\n\n\tprivate int id;\n\tprivate String username;\n\tprivate String password;\n\t\n\tpublic User() {\n\t}\n\t\n\tpublic User(int id, String username, String password) {\n\t\tthis.id = id;\n\t\tthis.username = username;\n\t\tthis.password = password;\n\t}\n\n\tpublic int getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(int id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getUsername() {\n\t\treturn username;\n\t}\n\n\tpublic void setUsername(String username) {\n\t\tthis.username = username;\n\t}\n\n\tpublic String getPassword() {\n\t\treturn password;\n\t}\n\n\tpublic void setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\t\n\t\n}"
},
{
"identifier": "ConnectionFactory",
"path": "src/main/java/br/com/toyStore/util/ConnectionFactory.java",
"snippet": "public class ConnectionFactory {\n\nprivate static Connection conn = null;\n\t\n\tpublic static Connection getConnection() {\n\t\tif (conn == null) {\n\t\t\ttry {\n\t\t\t\t\n\t\t\t\tClass.forName(\"com.mysql.jdbc.Driver\");\n\t\t\t\t\n\t\t\t\tString login = \"root\";\n\t\t\t\tString senha = \"1305\";\n\t\t\t\tString url = \"jdbc:mysql://localhost:3306/TOY_STORE?useUnicode=true&characterEncoding=UTF-8\";\n\t\t\t\tconn = DriverManager.getConnection(url,login,senha);\n\t\t\t}\n\t\t\tcatch(SQLException e) {\n\t\t\t\tthrow new DbException(e.getMessage());\n\t\t\t} \n\t\t\tcatch (ClassNotFoundException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\treturn conn;\n\t}\n\t\n\tpublic static void closeConnection() {\n\t\tif (conn != null) {\n\t\t\ttry {\n\t\t\t\tconn.close();\n\t\t\t}\n\t\t\tcatch (SQLException e) {\n\t\t\t\tthrow new DbException(e.getMessage());\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static void closeStatement(Statement st) {\n\t\tif (st != null) {\n\t\t\ttry {\n\t\t\t\tst.close();\n\t\t\t} catch (SQLException e) {\n\t\t\t\tthrow new DbException(e.getMessage());\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static void closeResultSet(ResultSet rs) {\n\t\tif (rs != null) {\n\t\t\ttry {\n\t\t\t\trs.close();\n\t\t\t} catch (SQLException e) {\n\t\t\t\tthrow new DbException(e.getMessage());\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void closeConnection(Connection conn, Statement stmt,\n\t\t\tResultSet rs) throws Exception {\n\t\tclose(conn, stmt, rs);\n\t}\n\n\tpublic static void closeConnection(Connection conn, Statement stmt)\n\t\t\tthrows Exception {\n\t\tclose(conn, stmt, null);\n\t}\n\n\tpublic static void closeConnection(Connection conn) throws Exception {\n\t\tclose(conn, null, null);\n\t}\n\n\tprivate static void close(Connection conn, Statement stmt, ResultSet rs)\n\t\t\tthrows Exception {\n\t\ttry {\n\t\t\tif (rs != null)\n\t\t\t\trs.close();\n\t\t\tif (stmt != null)\n\t\t\t\tstmt.close();\n\t\t\tif (conn != null)\n\t\t\t\tconn.close();\n\t\t} catch (Exception e) {\n\t\t\tthrow new Exception(e.getMessage());\n\t\t}\n\t}\n\t\n}"
}
] | import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import br.com.toyStore.exception.DbException;
import br.com.toyStore.model.Product;
import br.com.toyStore.model.User;
import br.com.toyStore.util.ConnectionFactory; | 1,537 | package br.com.toyStore.dao;
public class UserDAO {
private Connection conn;
private PreparedStatement ps;
private ResultSet rs;
private User user;
public UserDAO(Connection conn) {
this.conn = conn;
}
public void insert(User user) {
try {
if (user != null) {
String SQL = "INSERT INTO TOY_STORE.USER (USERNAME_USER, PASSWORD_USER) values "
+ "(?, ?)";
ps = conn.prepareStatement(SQL);
ps.setString(1, user.getUsername());
ps.setString(2, user.getPassword());
ps.executeUpdate();
}
} catch (SQLException sqle) { | package br.com.toyStore.dao;
public class UserDAO {
private Connection conn;
private PreparedStatement ps;
private ResultSet rs;
private User user;
public UserDAO(Connection conn) {
this.conn = conn;
}
public void insert(User user) {
try {
if (user != null) {
String SQL = "INSERT INTO TOY_STORE.USER (USERNAME_USER, PASSWORD_USER) values "
+ "(?, ?)";
ps = conn.prepareStatement(SQL);
ps.setString(1, user.getUsername());
ps.setString(2, user.getPassword());
ps.executeUpdate();
}
} catch (SQLException sqle) { | throw new DbException("Erro ao inserir dados " + sqle); | 0 | 2023-10-20 02:51:14+00:00 | 2k |
Lewoaragao/filetransfer | src/main/java/com/filetransfer/controller/FileController.java | [
{
"identifier": "FileResponse",
"path": "src/main/java/com/filetransfer/response/FileResponse.java",
"snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class FileResponse {\n\n\tprivate Integer index;\n\tprivate String message;\n\tprivate String fileName;\n\n\tpublic FileResponse(String message) {\n\t\tthis.message = message;\n\t}\n}"
},
{
"identifier": "FilesResponse",
"path": "src/main/java/com/filetransfer/response/FilesResponse.java",
"snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class FilesResponse {\n\n\tprivate String message;\n\tprivate List<String> fileNames;\n\tprivate List<FileVO> files;\n\n\tpublic FilesResponse(String message) {\n\t\tthis.message = message;\n\t}\n}"
},
{
"identifier": "FileService",
"path": "src/main/java/com/filetransfer/service/FileService.java",
"snippet": "@Service\npublic class FileService {\n\n\tpublic static final String uploadDir = \"src/main/resources/static/uploads\";\n\n\tpublic String saveFile(MultipartFile file, Integer index) throws IOException {\n\t\tLocalDateTime currentTime = LocalDateTime.now();\n\t\tDateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"yyyyMMddHHmmss\");\n\t\tString formattedDateTime = currentTime.format(formatter);\n\n\t\t// Obtenha o nome original do arquivo\n\t\tString fileExtension = this.getFileExtension(file);\n\n\t\t// Remova espaços e substitua por underline\n\t\tString sanitizedFileName = this.getSanitizedFileName(file);\n\n\t\t// Combine o nome sanitizado com a data/hora formatada e a extensão do arquivo\n\t\tString fileName = sanitizedFileName + \"_\" + formattedDateTime + index + fileExtension;\n\n\t\tPath uploadPath = Paths.get(uploadDir);\n\t\tFiles.createDirectories(uploadPath);\n\t\tPath destinationPath = uploadPath.resolve(fileName);\n\n\t\tFiles.copy(file.getInputStream(), destinationPath, StandardCopyOption.REPLACE_EXISTING);\n\n\t\treturn fileName;\n\t}\n\n\tpublic String getFileNameWithoutExtension(MultipartFile file) {\n\t\t// Obtenha o nome original do arquivo\n\t\tString originalFileName = file.getOriginalFilename();\n\n\t\t// Verifique se o nome original do arquivo contém uma extensão\n\t\tint lastIndex = originalFileName.lastIndexOf('.');\n\n\t\tif (lastIndex >= 0) {\n\t\t\t// Remova a extensão do nome original\n\t\t\treturn originalFileName.substring(0, lastIndex);\n\t\t} else {\n\t\t\t// Se não houver extensão, retorne o nome original completo\n\t\t\treturn originalFileName;\n\t\t}\n\t}\n\n\tpublic String getSanitizedFileName(MultipartFile file) {\n\t\t// Obtenha o nome original do arquivo\n\t\tString originalFileName = this.getFileNameWithoutExtension(file);\n\n\t\t// Remova a acentuação substituindo caracteres acentuados por não acentuados\n\t\toriginalFileName = removeAccents(originalFileName);\n\t\t\n\t\t// Remove todos os pontos de interrogação por underline, \n\t\t// geralmente ocorre por erro de encoding, por isso vem esses\n\t\t// pontos de interrogação\n\t\toriginalFileName = originalFileName.replace(\"?\", \"_\");\n\n\t\t// Substitua espaços por underscores\n\t\tString sanitizedFileName = originalFileName.replaceAll(\" \", \"_\");\n\n\t\treturn sanitizedFileName;\n\t}\n\n\tprivate String removeAccents(String input) {\n\t\t// Use Normalizer para remover a acentuação\n\t\tString normalizedString = Normalizer.normalize(input, Normalizer.Form.NFD);\n\t\t// Substitua caracteres acentuados por não acentuados\n\t\treturn normalizedString.replaceAll(\"[^\\\\p{ASCII}]\", \"\");\n\t}\n\n\tpublic String getFileExtension(MultipartFile file) {\n\t\t// Obtenha o nome original do arquivo\n\t\tString originalFileName = file.getOriginalFilename();\n\n\t\t// Obtenha a extensão do arquivo\n\t\tString fileExtension = originalFileName.substring(originalFileName.lastIndexOf(\".\"));\n\n\t\treturn fileExtension;\n\t}\n\n}"
},
{
"identifier": "Util",
"path": "src/main/java/com/filetransfer/util/Util.java",
"snippet": "public class Util {\n\n\tpublic static MediaType getMediaTypeForFile(String filename) {\n\t\tString extension = filename.substring(filename.lastIndexOf(\".\")).toLowerCase();\n\t\textension = extension.replace(\".\", \"\");\n\n\t\tswitch (extension) {\n\n\t\tcase \"pdf\":\n\t\t\treturn MediaType.APPLICATION_PDF;\n\t\tcase \"jpg\":\n\t\tcase \"jpeg\":\n\t\t\treturn MediaType.IMAGE_JPEG;\n\t\tcase \"png\":\n\t\t\treturn MediaType.IMAGE_PNG;\n\t\tcase \"gif\":\n\t\t\treturn MediaType.IMAGE_GIF;\n\t\tcase \"bmp\":\n\t\t\treturn MediaType.valueOf(\"image/bmp\");\n\t\tcase \"svg\":\n\t\t\treturn MediaType.valueOf(\"image/svg+xml\");\n\t\tcase \"webp\":\n\t\t\treturn MediaType.valueOf(\"image/webp\");\n\t\tcase \"mp3\":\n\t\t\treturn MediaType.valueOf(\"audio/mpeg\");\n\t\tcase \"wav\":\n\t\t\treturn MediaType.valueOf(\"audio/wav\");\n\t\tcase \"ogg\":\n\t\t\treturn MediaType.valueOf(\"audio/ogg\");\n\t\tcase \"flac\":\n\t\t\treturn MediaType.valueOf(\"audio/flac\");\n\t\tdefault:\n\t\t\treturn MediaType.APPLICATION_OCTET_STREAM;\n\t\t}\n\t}\n\t\n}"
},
{
"identifier": "FileVO",
"path": "src/main/java/com/filetransfer/vo/FileVO.java",
"snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class FileVO {\n\n\tprivate Integer index;\n\tprivate String originalFilename;\n\tprivate String downloadFilename;\n\tprivate String filename;\n\tprivate String extension;\n\n}"
}
] | import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.filetransfer.response.FileResponse;
import com.filetransfer.response.FilesResponse;
import com.filetransfer.service.FileService;
import com.filetransfer.util.Util;
import com.filetransfer.vo.FileVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor; | 1,533 | package com.filetransfer.controller;
@RestController
@CrossOrigin("*")
@RequestMapping("/api/file")
@RequiredArgsConstructor
@Api(tags = "Operações com arquivo do tipo File")
public class FileController {
@Autowired | package com.filetransfer.controller;
@RestController
@CrossOrigin("*")
@RequestMapping("/api/file")
@RequiredArgsConstructor
@Api(tags = "Operações com arquivo do tipo File")
public class FileController {
@Autowired | FileService service; | 2 | 2023-10-24 11:43:46+00:00 | 2k |
StarDevelopmentLLC/StarLib | src/main/java/com/stardevllc/starlib/observable/collections/impl/set/AbstractObservableSet.java | [
{
"identifier": "ObservableSet",
"path": "src/main/java/com/stardevllc/starlib/observable/collections/ObservableSet.java",
"snippet": "public interface ObservableSet<T> extends Set<T> {\n void addChangeListener(SetChangeListener<T> listener);\n}"
},
{
"identifier": "SetChangeListener",
"path": "src/main/java/com/stardevllc/starlib/observable/collections/listeners/SetChangeListener.java",
"snippet": "@FunctionalInterface\npublic interface SetChangeListener<T> {\n void onChange(SetChangeListener.Change<T> change);\n\n class Change<T> {\n protected final ObservableSet<T> set;\n protected List<T> added = new ArrayList<>();\n protected List<T> removed = new ArrayList<>();\n\n public Change(ObservableSet<T> set) {\n this.set = set;\n }\n\n public ObservableSet<T> getSet() {\n return set;\n }\n\n public List<T> getAdded() {\n return added;\n }\n\n public List<T> getRemoved() {\n return removed;\n }\n }\n}"
},
{
"identifier": "Change",
"path": "src/main/java/com/stardevllc/starlib/observable/collections/listeners/SetChangeListener.java",
"snippet": "class Change<T> {\n protected final ObservableSet<T> set;\n protected List<T> added = new ArrayList<>();\n protected List<T> removed = new ArrayList<>();\n\n public Change(ObservableSet<T> set) {\n this.set = set;\n }\n\n public ObservableSet<T> getSet() {\n return set;\n }\n\n public List<T> getAdded() {\n return added;\n }\n\n public List<T> getRemoved() {\n return removed;\n }\n}"
}
] | import com.stardevllc.starlib.observable.collections.ObservableSet;
import com.stardevllc.starlib.observable.collections.listeners.SetChangeListener;
import com.stardevllc.starlib.observable.collections.listeners.SetChangeListener.Change;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import java.util.stream.Stream; | 688 | package com.stardevllc.starlib.observable.collections.impl.set;
public abstract class AbstractObservableSet<T> implements ObservableSet<T> {
protected Set<T> value;
protected ArrayList<SetChangeListener<T>> changeListeners = new ArrayList<>();
public AbstractObservableSet(Set<T> value) {
this.value = value;
}
@Override
public void addChangeListener(SetChangeListener<T> listener) {
this.changeListeners.add(listener);
}
@Override
public int size() {
return value.size();
}
@Override
public boolean isEmpty() {
return value.isEmpty();
}
@Override
public boolean contains(Object o) {
return value.contains(o);
}
@Override
public Object[] toArray() {
return value.toArray();
}
@Override
public <T1> T1[] toArray(T1[] a) {
return value.toArray(a);
}
@Override
public boolean add(T t) {
boolean result = value.add(t);
if (result) { | package com.stardevllc.starlib.observable.collections.impl.set;
public abstract class AbstractObservableSet<T> implements ObservableSet<T> {
protected Set<T> value;
protected ArrayList<SetChangeListener<T>> changeListeners = new ArrayList<>();
public AbstractObservableSet(Set<T> value) {
this.value = value;
}
@Override
public void addChangeListener(SetChangeListener<T> listener) {
this.changeListeners.add(listener);
}
@Override
public int size() {
return value.size();
}
@Override
public boolean isEmpty() {
return value.isEmpty();
}
@Override
public boolean contains(Object o) {
return value.contains(o);
}
@Override
public Object[] toArray() {
return value.toArray();
}
@Override
public <T1> T1[] toArray(T1[] a) {
return value.toArray(a);
}
@Override
public boolean add(T t) {
boolean result = value.add(t);
if (result) { | Change<T> change = new Change<>(this); | 2 | 2023-10-23 17:28:03+00:00 | 2k |
yallerocha/Estruturas-de-Dados-e-Algoritmos | src/test/java/dataStructures/queue/StudentQueueTest.java | [
{
"identifier": "Queue",
"path": "src/main/java/com/dataStructures/queue/Queue.java",
"snippet": "public interface Queue<T> {\n\n\t/**\n\t * Inserts a new element in the queue or returns an exception if the queue\n\t * is full. Null elements are not allowed (the queue remains unchanged).\n\t * \n\t * @param element\n\t * @throws QueueOverflowException\n\t */\n\tpublic void enqueue(T element) throws QueueOverflowException;\n\n\t/**\n\t * If the queue has elements, it removes the oldest of the queue and returns\n\t * it; otherwise, it throws an exception.\n\t * \n\t * @return\n\t * @throws QueueUnderflowException\n\t */\n\tpublic T dequeue() throws QueueUnderflowException;\n\n\t/**\n\t * Returns (without removing) the oldest element of the queue; or \n\t * null if the queue is empty.\n\t * \n\t * @return\n\t */\n\tpublic T head();\n\n\t/**\n\t * Returns true if the queue is empty; or false, otherwise.\n\t * \n\t * @return\n\t */\n\tpublic boolean isEmpty();\n\n\t/**\n\t * Returns true if the queue is full; or false, otherwise.\n\t * \n\t * @return\n\t */\n\tpublic boolean isFull();\n\n}"
},
{
"identifier": "QueueOverflowException",
"path": "src/main/java/com/dataStructures/queue/exceptions/QueueOverflowException.java",
"snippet": "public class QueueOverflowException extends Exception {\n\n\tpublic QueueOverflowException() {\n\t\tsuper(\"Fila cheia\");\n\t}\n\n}"
},
{
"identifier": "QueueUnderflowException",
"path": "src/main/java/com/dataStructures/queue/exceptions/QueueUnderflowException.java",
"snippet": "public class QueueUnderflowException extends Exception {\n\n\tpublic QueueUnderflowException() {\n\t\tsuper(\"Fila vazia\");\n\t}\n\n}"
},
{
"identifier": "CircularQueue",
"path": "src/main/java/com/dataStructures/queue/variationsOfQueue/CircularQueue.java",
"snippet": "public class CircularQueue<T> implements Queue<T> {\n\n\tprivate T[] array;\n\tprivate int tail;\n\tprivate int head;\n\tprivate int elements;\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic CircularQueue(int size) {\n\t\tarray = (T[]) new Object[size];\n\t\thead = -1;\n\t\ttail = -1;\n\t\telements = 0;\n\t}\n\n\t@Override\n\tpublic void enqueue(T element) throws QueueOverflowException {\n\t\tif (!isFull()) {\n\t\t\tif (isEmpty()) {\n\t\t\t\thead = 0;\n\t\t\t}\n\t\t\ttail++;\n\t\t\tarray[tail] = element;\n\t\t\telements++;\n\n\t\t} else {\n\t\t\tthrow new QueueOverflowException();\n\t\t}\n\t}\n\n\t@Override\n\tpublic T dequeue() throws QueueUnderflowException {\n\t\tif (!isEmpty()) {\n\t\t\tT removedElement = array[head];\n\t\t\t\n\t\t\tarray[head] = null;\n\t\t\thead++;\n\t\t\telements--;\n\n\t\t\tif (isEmpty()) {\n\t\t\t\thead = -1;\n\t\t\t\ttail = -1;\n\t\t\t}\n\t\t\treturn removedElement;\n\t\t\t\n\t\t} else {\n\t\t\tthrow new QueueUnderflowException();\n\t\t}\n\t}\n\n\t@Override\n\tpublic T head() {\n\t\tif(head != -1) {\n\t\t\treturn array[head];\n\t\t}\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic boolean isEmpty() {\n\t\treturn elements == 0;\n\t}\n\n\t@Override\n\tpublic boolean isFull() {\n\t\treturn elements == array.length;\n\t}\n}"
}
] | import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import com.dataStructures.queue.Queue;
import com.dataStructures.queue.exceptions.QueueOverflowException;
import com.dataStructures.queue.exceptions.QueueUnderflowException;
import com.dataStructures.queue.variationsOfQueue.CircularQueue; | 1,304 | package dataStructures.queue;
public class StudentQueueTest {
public Queue<Integer> queue1;
public Queue<Integer> queue2;
public Queue<Integer> queue3;
@Before
public void setUp() throws QueueOverflowException {
getImplementations();
// Fila com 3 elementos não cheia.
queue1.enqueue(1);
queue1.enqueue(2);
queue1.enqueue(3);
// Fila com 2 elementos de tamanho 2. Fila cheia.
queue2.enqueue(1);
queue2.enqueue(2);
}
private void getImplementations() {
// TODO O aluno deve ajustar aqui para instanciar sua implementação
queue1 = new CircularQueue<Integer>(10);
queue2 = new CircularQueue<Integer>(2);
queue3 = new CircularQueue<Integer>(5);
}
// MÉTODOS DE TESTE
@Test
public void testHead() {
assertEquals(new Integer(1), queue1.head());
}
@Test
public void testIsEmpty() {
assertFalse(queue1.isEmpty());
assertTrue(queue3.isEmpty());
}
@Test
public void testIsFull() {
assertFalse(queue1.isFull());
}
@Test
public void testEnqueue() {
try {
queue1.enqueue(new Integer(5));
} catch (QueueOverflowException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test(expected = QueueOverflowException.class)
public void testEnqueueComErro() throws QueueOverflowException {
queue2.enqueue(new Integer(5)); // vai depender do tamanho que a fila
// foi iniciada!!!
}
@Test
public void testDequeue() {
try {
assertEquals(new Integer(1), queue1.dequeue()); | package dataStructures.queue;
public class StudentQueueTest {
public Queue<Integer> queue1;
public Queue<Integer> queue2;
public Queue<Integer> queue3;
@Before
public void setUp() throws QueueOverflowException {
getImplementations();
// Fila com 3 elementos não cheia.
queue1.enqueue(1);
queue1.enqueue(2);
queue1.enqueue(3);
// Fila com 2 elementos de tamanho 2. Fila cheia.
queue2.enqueue(1);
queue2.enqueue(2);
}
private void getImplementations() {
// TODO O aluno deve ajustar aqui para instanciar sua implementação
queue1 = new CircularQueue<Integer>(10);
queue2 = new CircularQueue<Integer>(2);
queue3 = new CircularQueue<Integer>(5);
}
// MÉTODOS DE TESTE
@Test
public void testHead() {
assertEquals(new Integer(1), queue1.head());
}
@Test
public void testIsEmpty() {
assertFalse(queue1.isEmpty());
assertTrue(queue3.isEmpty());
}
@Test
public void testIsFull() {
assertFalse(queue1.isFull());
}
@Test
public void testEnqueue() {
try {
queue1.enqueue(new Integer(5));
} catch (QueueOverflowException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test(expected = QueueOverflowException.class)
public void testEnqueueComErro() throws QueueOverflowException {
queue2.enqueue(new Integer(5)); // vai depender do tamanho que a fila
// foi iniciada!!!
}
@Test
public void testDequeue() {
try {
assertEquals(new Integer(1), queue1.dequeue()); | } catch (QueueUnderflowException e) { | 2 | 2023-10-21 21:39:25+00:00 | 2k |
MYSTD/BigDataApiTest | data-governance-assessment/src/main/java/com/std/dga/assessor/calc/NoAccessAssessor.java | [
{
"identifier": "Assessor",
"path": "data-governance-assessment/src/main/java/com/std/dga/assessor/Assessor.java",
"snippet": "public abstract class Assessor {\n\n public final GovernanceAssessDetail doAssessor(AssessParam assessParam){\n\n// System.out.println(\"Assessor 管理流程\");\n GovernanceAssessDetail governanceAssessDetail = new GovernanceAssessDetail();\n governanceAssessDetail.setAssessDate(assessParam.getAssessDate());\n governanceAssessDetail.setMetricId(assessParam.getTableMetaInfo().getId()+\"\");\n governanceAssessDetail.setTableName(assessParam.getTableMetaInfo().getTableName());\n governanceAssessDetail.setSchemaName(assessParam.getTableMetaInfo().getSchemaName());\n governanceAssessDetail.setMetricName(assessParam.getGovernanceMetric().getMetricName());\n governanceAssessDetail.setGovernanceType(assessParam.getGovernanceMetric().getGovernanceType());\n governanceAssessDetail.setTecOwner(assessParam.getTableMetaInfo().getTableMetaInfoExtra().getTecOwnerUserName());\n governanceAssessDetail.setCreateTime(new Date());\n //默认先给满分, 在考评器查找问题的过程中,如果有问题,再按照指标的要求重新给分。\n governanceAssessDetail.setAssessScore(BigDecimal.TEN);\n\n try {\n checkProblem(governanceAssessDetail, assessParam);\n }catch (Exception e) {\n governanceAssessDetail.setAssessScore(BigDecimal.ZERO);\n governanceAssessDetail.setIsAssessException(\"1\");\n //记录异常信息\n //简单记录\n //governanceAssessDetail.setAssessExceptionMsg( e.getMessage());\n\n //详细记录\n StringWriter stringWriter = new StringWriter() ;\n PrintWriter msgPrintWriter = new PrintWriter(stringWriter) ;\n e.printStackTrace( msgPrintWriter);\n governanceAssessDetail.setAssessExceptionMsg( stringWriter.toString().substring( 0, Math.min( 2000 , stringWriter.toString().length())) );\n }\n\n return governanceAssessDetail;\n }\n\n public abstract void checkProblem(GovernanceAssessDetail governanceAssessDetail , AssessParam assessParam) throws Exception;\n}"
},
{
"identifier": "AssessParam",
"path": "data-governance-assessment/src/main/java/com/std/dga/governance/bean/AssessParam.java",
"snippet": "@Data\npublic class AssessParam {\n\n private String assessDate ;\n private TableMetaInfo tableMetaInfo ;\n private GovernanceMetric governanceMetric ;\n\n private Map<String ,TableMetaInfo> tableMetaInfoMap ; // 所有表\n\n private TDsTaskDefinition tDsTaskDefinition ; // 该指标需要的任务定义\n\n private TDsTaskInstance tDsTaskInstance ; // 该指标需要的任务状态信息(当日)\n\n}"
},
{
"identifier": "GovernanceAssessDetail",
"path": "data-governance-assessment/src/main/java/com/std/dga/governance/bean/GovernanceAssessDetail.java",
"snippet": "@Data\n@TableName(\"governance_assess_detail\")\npublic class GovernanceAssessDetail implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * id\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 考评日期\n */\n private String assessDate;\n\n /**\n * 表名\n */\n private String tableName;\n\n /**\n * 库名\n */\n private String schemaName;\n\n /**\n * 指标项id\n */\n private String metricId;\n\n /**\n * 指标项名称\n */\n private String metricName;\n\n /**\n * 治理类型\n */\n private String governanceType;\n\n /**\n * 技术负责人\n */\n private String tecOwner;\n\n /**\n * 考评得分\n */\n private BigDecimal assessScore;\n\n /**\n * 考评问题项\n */\n private String assessProblem;\n\n /**\n * 考评备注\n */\n private String assessComment;\n\n /**\n * 考评是否异常\n */\n private String isAssessException;\n\n /**\n * 异常信息\n */\n private String assessExceptionMsg;\n\n /**\n * 治理处理路径\n */\n private String governanceUrl;\n\n /**\n * 创建日期\n */\n private Date createTime;\n}"
}
] | import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.std.dga.assessor.Assessor;
import com.std.dga.governance.bean.AssessParam;
import com.std.dga.governance.bean.GovernanceAssessDetail;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.ivy.util.DateUtil;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit; | 1,260 | package com.std.dga.assessor.calc;
@Component("NO_ACCESS")
public class NoAccessAssessor extends Assessor {
@Override | package com.std.dga.assessor.calc;
@Component("NO_ACCESS")
public class NoAccessAssessor extends Assessor {
@Override | public void checkProblem(GovernanceAssessDetail governanceAssessDetail, AssessParam assessParam) throws Exception { | 1 | 2023-10-20 10:13:43+00:00 | 2k |
RaulGB88/MOD-034-Microservicios-con-Java | REM20231023/catalogo/src/main/java/com/example/domains/core/contracts/services/DomainService.java | [
{
"identifier": "DuplicateKeyException",
"path": "REM20231023/catalogo/src/main/java/com/example/exceptions/DuplicateKeyException.java",
"snippet": "public class DuplicateKeyException extends Exception {\n\tprivate static final long serialVersionUID = 1L;\n\tprivate final static String MESSAGE_STRING = \"Duplicate key\";\n\t\n\tpublic DuplicateKeyException() {\n\t\tthis(MESSAGE_STRING);\n\t}\n\n\tpublic DuplicateKeyException(String message) {\n\t\tsuper(message);\n\t}\n\n\tpublic DuplicateKeyException(Throwable cause) {\n\t\tthis(MESSAGE_STRING, cause);\n\t}\n\n\tpublic DuplicateKeyException(String message, Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n\n\tpublic DuplicateKeyException(String message, Throwable cause, boolean enableSuppression,\n\t\t\tboolean writableStackTrace) {\n\t\tsuper(message, cause, enableSuppression, writableStackTrace);\n\t}\n\n}"
},
{
"identifier": "InvalidDataException",
"path": "REM20231023/catalogo/src/main/java/com/example/exceptions/InvalidDataException.java",
"snippet": "public class InvalidDataException extends Exception {\n\tprivate static final long serialVersionUID = 1L;\n\tprivate final static String MESSAGE_STRING = \"Invalid data\";\n\tprivate Map<String, String> errors = null;\n\t\n\tpublic InvalidDataException() {\n\t\tthis(MESSAGE_STRING);\n\t}\n\n\tpublic InvalidDataException(String message) {\n\t\tsuper(message);\n\t}\n\n\tpublic InvalidDataException(Map<String, String> errors) {\n\t\tthis(MESSAGE_STRING, errors);\n\t}\n\n\tpublic InvalidDataException(String message, Map<String, String> errors) {\n\t\tsuper(message);\n\t\tthis.errors = errors;\n\t}\n\n\tpublic InvalidDataException(Throwable cause) {\n\t\tthis(MESSAGE_STRING, cause);\n\t}\n\n\tpublic InvalidDataException(String message, Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n\n\tpublic InvalidDataException(String message, Throwable cause, boolean enableSuppression,\n\t\t\tboolean writableStackTrace) {\n\t\tsuper(message, cause, enableSuppression, writableStackTrace);\n\t}\n\n\tpublic InvalidDataException(Throwable cause, Map<String, String> errors) {\n\t\tthis(MESSAGE_STRING, cause, errors);\n\t}\n\n\tpublic InvalidDataException(String message, Throwable cause, Map<String, String> errors) {\n\t\tsuper(message, cause);\n\t\tthis.errors = errors;\n\t}\n\n\tpublic InvalidDataException(String message, Throwable cause, Map<String, String> errors, boolean enableSuppression,\n\t\t\tboolean writableStackTrace) {\n\t\tsuper(message, cause, enableSuppression, writableStackTrace);\n\t\tthis.errors = errors;\n\t}\n\n\tpublic boolean hasErrors() { return errors != null; }\n\tpublic Map<String, String> getErrors() { return errors; }\n\t\n\t\n}"
},
{
"identifier": "NotFoundException",
"path": "REM20231023/catalogo/src/main/java/com/example/exceptions/NotFoundException.java",
"snippet": "public class NotFoundException extends Exception {\n\tprivate static final long serialVersionUID = 1L;\n\tprivate final static String MESSAGE_STRING = \"Not found\";\n\t\n\tpublic NotFoundException() {\n\t\tthis(MESSAGE_STRING);\n\t}\n\n\tpublic NotFoundException(String message) {\n\t\tsuper(message);\n\t}\n\n\tpublic NotFoundException(Throwable cause) {\n\t\tthis(MESSAGE_STRING, cause);\n\t}\n\n\tpublic NotFoundException(String message, Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n\n\tpublic NotFoundException(String message, Throwable cause, boolean enableSuppression,\n\t\t\tboolean writableStackTrace) {\n\t\tsuper(message, cause, enableSuppression, writableStackTrace);\n\t}\n}"
}
] | import java.util.List;
import java.util.Optional;
import com.example.exceptions.DuplicateKeyException;
import com.example.exceptions.InvalidDataException;
import com.example.exceptions.NotFoundException; | 910 | package com.example.domains.core.contracts.services;
public interface DomainService<E, K> {
List<E> getAll();
Optional<E> getOne(K id);
| package com.example.domains.core.contracts.services;
public interface DomainService<E, K> {
List<E> getAll();
Optional<E> getOne(K id);
| E add(E item) throws DuplicateKeyException, InvalidDataException; | 1 | 2023-10-24 14:35:15+00:00 | 2k |
Amir-UL-Islam/eTBManager3-Backend | src/main/java/org/msh/etbm/db/entities/ExamMicroscopy.java | [
{
"identifier": "Operation",
"path": "src/main/java/org/msh/etbm/commons/entities/cmdlog/Operation.java",
"snippet": "public enum Operation { NEW, EDIT, DELETE, ALL }"
},
{
"identifier": "MicroscopyResult",
"path": "src/main/java/org/msh/etbm/db/enums/MicroscopyResult.java",
"snippet": "public enum MicroscopyResult implements MessageKey {\n\n NEGATIVE('-'),\n POSITIVE('+'),\n PLUS('+'),\n PLUS2('+'),\n PLUS3('+'),\n PLUS4('+'),\n NOTDONE('0');\n\n private char result;\n\n MicroscopyResult(char result) {\n this.result = result;\n }\n\n @Override\n public String getMessageKey() {\n return getClass().getSimpleName().concat(\".\" + name());\n }\n\n\n /**\n * Check if the value is positive result\n *\n * @return true if it's a positive result\n */\n public boolean isPositive() {\n return (result == '+');\n }\n\n\n /**\n * Check if the value is a negative result\n *\n * @return true if it's a negative result\n */\n public boolean isNegative() {\n return (result == '-');\n }\n\n\n /**\n * Return the list of values that are positive\n *\n * @return Enum list\n */\n static public MicroscopyResult[] getPositiveResults() {\n int num = 0;\n for (MicroscopyResult res : values()) {\n if (res.isPositive()) {\n num++;\n }\n }\n\n MicroscopyResult[] lst = new MicroscopyResult[num];\n int i = 0;\n for (MicroscopyResult res : values()) {\n if (res.isPositive()) {\n lst[i] = res;\n i++;\n }\n }\n return lst;\n }\n\n\n /**\n * Return the list of values that are negative\n *\n * @return Enum list\n */\n static public MicroscopyResult[] getNegativeResults() {\n int num = 0;\n for (MicroscopyResult res : values()) {\n if (res.isNegative()) {\n num++;\n }\n }\n\n MicroscopyResult[] lst = new MicroscopyResult[num];\n int i = 0;\n for (MicroscopyResult res : values()) {\n if (res.isNegative()) {\n lst[i] = res;\n i++;\n }\n }\n return lst;\n }\n}"
},
{
"identifier": "SampleType",
"path": "src/main/java/org/msh/etbm/db/enums/SampleType.java",
"snippet": "public enum SampleType implements MessageKey {\n\n SPUTUM,\n OTHER,\n\n //Cambodia\n PUS,\n CSF,\n URINE,\n STOOL,\n TISSUE;\n\n @Override\n public String getMessageKey() {\n return getClass().getSimpleName().concat(\".\" + name());\n }\n}"
},
{
"identifier": "VisualAppearance",
"path": "src/main/java/org/msh/etbm/db/enums/VisualAppearance.java",
"snippet": "public enum VisualAppearance implements MessageKey {\n BLOOD_STAINED,\n MUCOPURULENT,\n SALIVA;\n\n /**\n * Return the key string in the list of the messages to display the correct status in the selected language\n *\n * @return\n */\n @Override\n public String getMessageKey() {\n return getClass().getSimpleName().concat(\".\" + name());\n }\n}"
}
] | import org.msh.etbm.commons.entities.cmdlog.Operation;
import org.msh.etbm.commons.entities.cmdlog.PropertyLog;
import org.msh.etbm.db.enums.MicroscopyResult;
import org.msh.etbm.db.enums.SampleType;
import org.msh.etbm.db.enums.VisualAppearance;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table; | 946 | package org.msh.etbm.db.entities;
@Entity
@Table(name = "exammicroscopy")
public class ExamMicroscopy extends LaboratoryExam {
| package org.msh.etbm.db.entities;
@Entity
@Table(name = "exammicroscopy")
public class ExamMicroscopy extends LaboratoryExam {
| @PropertyLog(operations = {Operation.NEW, Operation.DELETE}) | 0 | 2023-10-23 13:47:54+00:00 | 2k |
2357457057/qy-rpc | src/main/java/top/yqingyu/rpc/consumer/ConsumerHolderContext.java | [
{
"identifier": "Constants",
"path": "src/main/java/top/yqingyu/rpc/Constants.java",
"snippet": "public interface Constants {\n String method = \"@\";\n String param = \"#\";\n String parameterList = \"parameterList\";\n String invokeSuccess = \"0\";\n String invokeNoSuch = \"1\";\n String invokeThrowError = \"2\";\n String invokeResult = \"invokeResult\";\n String invokeErrorClass = \"invokeErrorClass\";\n String invokeErrorMessage = \"invokeErrorMessage\";\n String serviceIdentifierTag = \"serviceIdentifierTag\";\n //ms\n long authenticationWaitTime = 3000;\n String SpringCGLib = \"$$SpringCGLIB$$\";\n String JDK_PROXY = \"jdk.proxy\";\n String SpringCGLibRegx = \"[$]{2}SpringCGLIB[$]{2}\";\n\n List<String> specialMethod = Arrays.asList(\"toString\", \"hashcode\", \"equals\");\n\n String linkId = \"RPC_LINK_ID\";\n}"
},
{
"identifier": "NoSuchHolderException",
"path": "src/main/java/top/yqingyu/rpc/exception/NoSuchHolderException.java",
"snippet": "public class NoSuchHolderException extends QyRuntimeException {\n\n public NoSuchHolderException() {\n }\n\n public NoSuchHolderException(String message, Object... o) {\n super(message, o);\n }\n\n public NoSuchHolderException(Throwable cause, String message, Object... o) {\n super(cause, message, o);\n }\n\n public NoSuchHolderException(Throwable cause) {\n super(cause);\n }\n\n public NoSuchHolderException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, Object... o) {\n super(message, cause, enableSuppression, writableStackTrace, o);\n }\n}"
},
{
"identifier": "RpcUtil",
"path": "src/main/java/top/yqingyu/rpc/util/RpcUtil.java",
"snippet": "public class RpcUtil {\n /**\n * 倘若该类实现的接口实现了某些接口,类名会选取与该对象全限定名最接近的接口的全限定名\n */\n public static String getClassName(Class<?> aClass) {\n String className = aClass.getName();\n if (aClass.isInterface()) {\n return className;\n }\n\n Class<?>[] interfaces = aClass.getInterfaces();\n Class<?> interface$ = null;\n String[] classNameS = className.split(\"[.]\");\n int sameMax = 0;\n\n for (Class<?> anInterface : interfaces) {\n String name = anInterface.getName();\n String[] split = name.split(\"[.]\");\n int min = Math.min(classNameS.length, split.length);\n for (int i = 0; i < min; i++) {\n if (!split[i].equals(classNameS[i])) {\n break;\n }\n if (i > sameMax) {\n sameMax = i;\n interface$ = anInterface;\n }\n }\n }\n if (interface$ != null) {\n className = interface$.getName();\n }\n return className;\n }\n\n public static ClassLoader getClassLoader(Class<?> c) {\n ClassLoader cl = c.getClassLoader();\n if (cl == null) {\n cl = DuplicatesPredicate.class.getClassLoader();\n }\n if (cl == null) {\n cl = Thread.currentThread().getContextClassLoader();\n }\n return cl;\n }\n}"
}
] | import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.yqingyu.common.cglib.core.ClassLoaderAwareGeneratorStrategy;
import top.yqingyu.common.cglib.core.QyNamingPolicy;
import top.yqingyu.common.cglib.proxy.Enhancer;
import top.yqingyu.qymsg.DataType;
import top.yqingyu.qymsg.MsgHelper;
import top.yqingyu.qymsg.MsgType;
import top.yqingyu.qymsg.QyMsg;
import top.yqingyu.qymsg.netty.Connection;
import top.yqingyu.rpc.Constants;
import top.yqingyu.rpc.exception.NoSuchHolderException;
import top.yqingyu.rpc.util.RpcUtil;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap; | 1,103 | package top.yqingyu.rpc.consumer;
public class ConsumerHolderContext {
private static final Logger logger = LoggerFactory.getLogger(ConsumerHolderContext.class);
final ConcurrentHashMap<Class<?>, Object> ProxyClassCache = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, ConsumerHolder> CONSUMER_MAP = new ConcurrentHashMap<>();
final RpcLinkId rpcLinkId;
volatile MethodExecuteInterceptor methodExecuteInterceptor = new MethodExecuteInterceptor() {
};
public ConsumerHolderContext() {
this.rpcLinkId = new RpcLinkId();
}
void addConsumer(Consumer consumer) throws Exception {
Connection connection = consumer.getClient().getConnection();
String name = consumer.getName();
QyMsg qyMsg = new QyMsg(MsgType.AC, DataType.OBJECT); | package top.yqingyu.rpc.consumer;
public class ConsumerHolderContext {
private static final Logger logger = LoggerFactory.getLogger(ConsumerHolderContext.class);
final ConcurrentHashMap<Class<?>, Object> ProxyClassCache = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, ConsumerHolder> CONSUMER_MAP = new ConcurrentHashMap<>();
final RpcLinkId rpcLinkId;
volatile MethodExecuteInterceptor methodExecuteInterceptor = new MethodExecuteInterceptor() {
};
public ConsumerHolderContext() {
this.rpcLinkId = new RpcLinkId();
}
void addConsumer(Consumer consumer) throws Exception {
Connection connection = consumer.getClient().getConnection();
String name = consumer.getName();
QyMsg qyMsg = new QyMsg(MsgType.AC, DataType.OBJECT); | QyMsg back = connection.get(qyMsg, Constants.authenticationWaitTime); | 0 | 2023-10-18 11:03:57+00:00 | 2k |
ghillert/pof-gradle-demo-multi-project | app/src/main/java/com/hillert/coherence/pof/app/App.java | [
{
"identifier": "LinkedList",
"path": "list/src/main/java/com/hillert/coherence/pof/list/LinkedList.java",
"snippet": "public class LinkedList {\n private Node head;\n\n public void add(String element) {\n Node newNode = new Node(element);\n\n Node it = tail(head);\n if (it == null) {\n head = newNode;\n } else {\n it.next = newNode;\n }\n }\n\n private static Node tail(Node head) {\n Node it;\n\n for (it = head; it != null && it.next != null; it = it.next) {}\n\n return it;\n }\n\n public boolean remove(String element) {\n boolean result = false;\n Node previousIt = null;\n Node it = null;\n for (it = head; !result && it != null; previousIt = it, it = it.next) {\n if (0 == element.compareTo(it.data)) {\n result = true;\n unlink(previousIt, it);\n break;\n }\n }\n\n return result;\n }\n\n private void unlink(Node previousIt, Node currentIt) {\n if (currentIt == head) {\n head = currentIt.next;\n } else {\n previousIt.next = currentIt.next;\n }\n }\n\n public int size() {\n int size = 0;\n\n for (Node it = head; it != null; ++size, it = it.next) {}\n\n return size;\n }\n\n public String get(int index) {\n Node it = head;\n while (index > 0 && it != null) {\n it = it.next;\n index--;\n }\n\n if (it == null) {\n throw new IndexOutOfBoundsException(\"Index is out of range\");\n }\n\n return it.data;\n }\n\n private static class Node {\n final String data;\n Node next;\n\n Node(String data) {\n this.data = data;\n }\n }\n}"
},
{
"identifier": "join",
"path": "utilities/src/main/java/com/hillert/coherence/pof/utilities/StringUtils.java",
"snippet": "public static String join(LinkedList source) {\n return JoinUtils.join(source);\n}"
},
{
"identifier": "split",
"path": "utilities/src/main/java/com/hillert/coherence/pof/utilities/StringUtils.java",
"snippet": "public static LinkedList split(String source) {\n return SplitUtils.split(source);\n}"
},
{
"identifier": "getMessage",
"path": "app/src/main/java/com/hillert/coherence/pof/app/MessageUtils.java",
"snippet": "public static String getMessage() {\n return \"Hello World!\";\n}"
}
] | import com.hillert.coherence.pof.list.LinkedList;
import static com.hillert.coherence.pof.utilities.StringUtils.join;
import static com.hillert.coherence.pof.utilities.StringUtils.split;
import static com.hillert.coherence.pof.app.MessageUtils.getMessage;
import org.apache.commons.text.WordUtils; | 729 | /*
* This Java source file was generated by the Gradle 'init' task.
*/
package com.hillert.coherence.pof.app;
public class App {
public static void main(String[] args) { | /*
* This Java source file was generated by the Gradle 'init' task.
*/
package com.hillert.coherence.pof.app;
public class App {
public static void main(String[] args) { | LinkedList tokens; | 0 | 2023-10-24 20:23:49+00:00 | 2k |
SuelytonThiago/anime-server | src/main/java/com/example/animeserver/rest/services/AnimeService.java | [
{
"identifier": "Anime",
"path": "src/main/java/com/example/animeserver/domain/entities/Anime.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Entity\n@Table(name = \"tb_animes\")\npublic class Anime {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n private String name;\n private String synopsis;\n private LocalDate date;\n\n @ManyToMany\n @JoinTable(name = \"tb_anime_categories\",\n joinColumns = @JoinColumn(name = \"anime_id\"),\n inverseJoinColumns = @JoinColumn(name = \"category_id\"))\n private List<Category> categories = new ArrayList<>();\n\n @OneToMany(mappedBy = \"likeAnime\",cascade = CascadeType.REMOVE)\n private List<Like> animeLikes = new ArrayList<>();\n\n @OneToMany(mappedBy = \"episodeAnime\",cascade = CascadeType.REMOVE)\n private Set<Episode> episodes = new HashSet<>();\n\n @OneToMany(mappedBy = \"commentAnime\",cascade = CascadeType.REMOVE)\n private Set<Comment> animeComments = new HashSet<>();\n\n public Anime(Long id, String name, String synopsis) {\n this.id = id;\n this.name = name;\n this.synopsis = synopsis;\n this.date = LocalDate.now();\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (!(o instanceof Anime anime)) return false;\n return getId().equals(anime.getId());\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(getId());\n }\n}"
},
{
"identifier": "Category",
"path": "src/main/java/com/example/animeserver/domain/entities/Category.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\n@Entity\n@Table(name = \"tb_categories\")\npublic class Category {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n private String name;\n\n public Category( String name) {\n this.id = id;\n this.name = name;\n }\n\n public static Category of(CategoryRequest request){\n return Category.builder().name(request.getName()).build();\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (!(o instanceof Category category)) return false;\n return getId().equals(category.getId());\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(getId());\n }\n}"
},
{
"identifier": "AnimeRepository",
"path": "src/main/java/com/example/animeserver/domain/repositories/AnimeRepository.java",
"snippet": "public interface AnimeRepository extends JpaRepository<Anime,Long> {\n\n @Query(value = \"select * from tb_animes c where c.date > :date \",nativeQuery = true)\n List<Anime> findByRecentlyAdded(@Param(\"date\") LocalDate date);\n\n Optional<Anime> findByName(String name);\n\n List<Anime> findByCategories(Category category);\n\n\n\n\n}"
},
{
"identifier": "CustomException",
"path": "src/main/java/com/example/animeserver/rest/services/exceptions/CustomException.java",
"snippet": "public class CustomException extends BaseBusinessException {\n\n public CustomException(String message) {\n super(message);\n }\n\n @Override\n public HttpStatus getStatusCode() {\n return HttpStatus.BAD_REQUEST;\n }\n}"
},
{
"identifier": "ObjectNotFoundException",
"path": "src/main/java/com/example/animeserver/rest/services/exceptions/ObjectNotFoundException.java",
"snippet": "public class ObjectNotFoundException extends BaseBusinessException{\n\n public ObjectNotFoundException(String message) {\n super(message);\n }\n\n @Override\n public HttpStatus getStatusCode() {\n return HttpStatus.NOT_FOUND;\n }\n}"
}
] | import com.example.animeserver.domain.entities.Anime;
import com.example.animeserver.domain.entities.Category;
import com.example.animeserver.domain.repositories.AnimeRepository;
import com.example.animeserver.rest.dto.*;
import com.example.animeserver.rest.services.exceptions.CustomException;
import com.example.animeserver.rest.services.exceptions.ObjectNotFoundException;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors; | 1,064 | package com.example.animeserver.rest.services;
@Service
public class AnimeService {
@Autowired
private AnimeRepository animeRepository;
@Autowired
private CategoryService categoryService;
@Autowired
private CommentService commentService;
@Autowired
private LikeService likeService;
@Autowired
private EpisodeService episodeService;
@Transactional
public void create(AnimeRequest request){ | package com.example.animeserver.rest.services;
@Service
public class AnimeService {
@Autowired
private AnimeRepository animeRepository;
@Autowired
private CategoryService categoryService;
@Autowired
private CommentService commentService;
@Autowired
private LikeService likeService;
@Autowired
private EpisodeService episodeService;
@Transactional
public void create(AnimeRequest request){ | var anime = new Anime(null, request.getName(), request.getSynopsis()); | 0 | 2023-10-22 21:55:02+00:00 | 2k |
exagonsoft/drones-management-board-backend | src/test/java/exagonsoft/drones/controller/DroneControllerTest.java | [
{
"identifier": "BatteryLevelDto",
"path": "src/main/java/exagonsoft/drones/dto/BatteryLevelDto.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class BatteryLevelDto {\n private int batteryLevel;\n}"
},
{
"identifier": "DroneDto",
"path": "src/main/java/exagonsoft/drones/dto/DroneDto.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class DroneDto {\n private Long id;\n private String serial_number;\n private ModelType model;\n private Integer max_weight;\n private Integer battery_capacity;\n private StateType state;\n}"
},
{
"identifier": "MedicationDto",
"path": "src/main/java/exagonsoft/drones/dto/MedicationDto.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class MedicationDto {\n private Long id;\n private String name;\n private Integer weight;\n private String code;\n private String imageUrl;\n}"
},
{
"identifier": "DroneService",
"path": "src/main/java/exagonsoft/drones/service/DroneService.java",
"snippet": "public interface DroneService {\n DroneDto createDrone(DroneDto droneDto);\n\n DroneDto getDroneByID(Long droneID);\n\n List<DroneDto> listAllDrones();\n\n DroneDto updateDrone(Long id, DroneDto updatedDrone);\n\n List<DroneDto> listAvailableDrones();\n\n BatteryLevelDto checkDroneBatteryLevel(Long droneID);\n\n List<MedicationDto> listDroneMedications(Long droneID);\n\n boolean loadDroneMedications(Long droneID, List<Long> medicationsIds);\n}"
}
] | import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
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.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import com.fasterxml.jackson.databind.ObjectMapper;
import exagonsoft.drones.dto.BatteryLevelDto;
import exagonsoft.drones.dto.DroneDto;
import exagonsoft.drones.dto.MedicationDto;
import exagonsoft.drones.service.DroneService; | 1,144 | package exagonsoft.drones.controller;
@WebMvcTest(DroneController.class)
public class DroneControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private DroneService droneService;
@Autowired
private ObjectMapper objectMapper;
@Test
public void testCreateDrone() throws Exception {
// Arrange
DroneDto droneDto = new DroneDto(); // Initialize with necessary data
when(droneService.createDrone(droneDto)).thenReturn(droneDto);
// Act & Assert
mockMvc.perform(post("/api/drones")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(droneDto)))
.andExpect(status().isCreated());
}
@Test
public void testGetDroneById() throws Exception {
// Arrange
Long droneId = 1L;
DroneDto droneDto = new DroneDto(); // Initialize with necessary data
when(droneService.getDroneByID(droneId)).thenReturn(droneDto);
// Act & Assert
mockMvc.perform(get("/api/drones/{id}", droneId)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
@Test
public void testGetAllDrones() throws Exception {
// Arrange
List<DroneDto> droneList = new ArrayList<>(); // Add some drones to the list
when(droneService.listAllDrones()).thenReturn(droneList);
// Act & Assert
mockMvc.perform(get("/api/drones")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$").isEmpty());
}
@Test
public void testUpdateDrone() throws Exception {
// Arrange
Long droneId = 1L;
DroneDto updatedDroneDto = new DroneDto(); // Initialize with necessary data
when(droneService.updateDrone(droneId, updatedDroneDto)).thenReturn(updatedDroneDto);
// Act & Assert
mockMvc.perform(put("/api/drones/{id}", droneId)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(updatedDroneDto)))
.andExpect(status().isOk());
}
@Test
public void testGetAvailableDrones() throws Exception {
// Arrange
List<DroneDto> availableDroneList = new ArrayList<>(); // Add available drones to the list
when(droneService.listAvailableDrones()).thenReturn(availableDroneList);
// Act & Assert
mockMvc.perform(get("/api/drones/available")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$").isEmpty());
}
@Test
public void testCheckDroneBatteryLevel() throws Exception {
// Arrange
Long droneId = 1L; | package exagonsoft.drones.controller;
@WebMvcTest(DroneController.class)
public class DroneControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private DroneService droneService;
@Autowired
private ObjectMapper objectMapper;
@Test
public void testCreateDrone() throws Exception {
// Arrange
DroneDto droneDto = new DroneDto(); // Initialize with necessary data
when(droneService.createDrone(droneDto)).thenReturn(droneDto);
// Act & Assert
mockMvc.perform(post("/api/drones")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(droneDto)))
.andExpect(status().isCreated());
}
@Test
public void testGetDroneById() throws Exception {
// Arrange
Long droneId = 1L;
DroneDto droneDto = new DroneDto(); // Initialize with necessary data
when(droneService.getDroneByID(droneId)).thenReturn(droneDto);
// Act & Assert
mockMvc.perform(get("/api/drones/{id}", droneId)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
@Test
public void testGetAllDrones() throws Exception {
// Arrange
List<DroneDto> droneList = new ArrayList<>(); // Add some drones to the list
when(droneService.listAllDrones()).thenReturn(droneList);
// Act & Assert
mockMvc.perform(get("/api/drones")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$").isEmpty());
}
@Test
public void testUpdateDrone() throws Exception {
// Arrange
Long droneId = 1L;
DroneDto updatedDroneDto = new DroneDto(); // Initialize with necessary data
when(droneService.updateDrone(droneId, updatedDroneDto)).thenReturn(updatedDroneDto);
// Act & Assert
mockMvc.perform(put("/api/drones/{id}", droneId)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(updatedDroneDto)))
.andExpect(status().isOk());
}
@Test
public void testGetAvailableDrones() throws Exception {
// Arrange
List<DroneDto> availableDroneList = new ArrayList<>(); // Add available drones to the list
when(droneService.listAvailableDrones()).thenReturn(availableDroneList);
// Act & Assert
mockMvc.perform(get("/api/drones/available")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$").isEmpty());
}
@Test
public void testCheckDroneBatteryLevel() throws Exception {
// Arrange
Long droneId = 1L; | BatteryLevelDto batteryLevelDto = new BatteryLevelDto(); // Initialize with necessary data | 0 | 2023-10-16 08:32:39+00:00 | 2k |
LucassR0cha/demo-pattern-JDBC | src/application/Program.java | [
{
"identifier": "DaoFactory",
"path": "src/model/dao/DaoFactory.java",
"snippet": "public class DaoFactory {\n\t\n\tpublic static SellerDao createSellerDao() {\n\t\treturn new SellerDaoJDBC(DB.getConnection());\n\t}\n}"
},
{
"identifier": "SellerDao",
"path": "src/model/dao/SellerDao.java",
"snippet": "public interface SellerDao {\n\n\tvoid insert(Seller obj);\n\n\tvoid update(Seller obj);\n\n\tvoid deleteById(Integer id);\n\n\tSeller findById(Integer id);\n\n\tList<Seller> findAll();\n\n\tList<Seller> findByDepartment(Department department);\n}"
},
{
"identifier": "Department",
"path": "src/model/entities/Department.java",
"snippet": "public class Department implements Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tprivate Integer id;\n\tprivate String name;\n\n\tpublic Department() {\n\t}\n\n\tpublic Department(Integer id, String name) {\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t}\n\n\tpublic Integer getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Integer id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((id == null) ? 0 : id.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tDepartment other = (Department) obj;\n\t\tif (id == null) {\n\t\t\tif (other.id != null)\n\t\t\t\treturn false;\n\t\t} else if (!id.equals(other.id))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Department id: \" + id + \", name: \" + name;\n\t}\n}"
},
{
"identifier": "Seller",
"path": "src/model/entities/Seller.java",
"snippet": "public class Seller implements Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\t\n\tprivate Integer id;\n\tprivate String name;\n\tprivate String email;\n\tprivate Date birthDate;\n\tprivate Double baseSalary;\n\n\tprivate Department department;\n\n\tpublic Seller() {\n\t}\n\n\tpublic Seller(\n\t\t\tInteger id, String name, String email, \n\t\t\tDate birthDate, Double baseSalary, \n\t\t\tDepartment department) {\n\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t\tthis.email = email;\n\t\tthis.birthDate = birthDate;\n\t\tthis.baseSalary = baseSalary;\n\t\tthis.department = department;\n\t}\n\n\tpublic Integer getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Integer id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getEmail() {\n\t\treturn email;\n\t}\n\n\tpublic void setEmail(String email) {\n\t\tthis.email = email;\n\t}\n\n\tpublic Date getBirthDate() {\n\t\treturn birthDate;\n\t}\n\n\tpublic void setBirthDate(Date birthDate) {\n\t\tthis.birthDate = birthDate;\n\t}\n\n\tpublic Double getBaseSalary() {\n\t\treturn baseSalary;\n\t}\n\n\tpublic void setBaseSalary(Double baseSalary) {\n\t\tthis.baseSalary = baseSalary;\n\t}\n\n\tpublic Department getDepartment() {\n\t\treturn department;\n\t}\n\n\tpublic void setDepartment(Department department) {\n\t\tthis.department = department;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((id == null) ? 0 : id.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tSeller other = (Seller) obj;\n\t\tif (id == null) {\n\t\t\tif (other.id != null)\n\t\t\t\treturn false;\n\t\t} else if (!id.equals(other.id))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Seller id: \" + id + \", name: \" + name \n\t\t\t\t+ \", email: \" + email + \", birthDate: \" + birthDate\n\t\t\t\t+ \", baseSalary: \" + baseSalary \n\t\t\t\t+ \", department: \" + department;\n\t}\n}"
}
] | import java.util.Date;
import java.util.List;
import java.util.Scanner;
import model.dao.DaoFactory;
import model.dao.SellerDao;
import model.entities.Department;
import model.entities.Seller; | 1,343 | package application;
public class Program {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
SellerDao sellerDao = DaoFactory.createSellerDao();
System.out.println("=== TEST 1: Seller findById ===");
Seller seller = sellerDao.findById(3);
System.out.println(seller);
System.out.println("\n=== TEST 2: Seller findByDepartment ==="); | package application;
public class Program {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
SellerDao sellerDao = DaoFactory.createSellerDao();
System.out.println("=== TEST 1: Seller findById ===");
Seller seller = sellerDao.findById(3);
System.out.println(seller);
System.out.println("\n=== TEST 2: Seller findByDepartment ==="); | Department department = new Department(2, null); | 2 | 2023-10-16 23:09:51+00:00 | 2k |
weibocom/rill-flow | rill-flow-dag/olympicene-core/src/main/java/com/weibo/rill/flow/olympicene/core/model/dag/DAG.java | [
{
"identifier": "Mapping",
"path": "rill-flow-interfaces/src/main/java/com/weibo/rill/flow/interfaces/model/mapping/Mapping.java",
"snippet": "@AllArgsConstructor\n@NoArgsConstructor\n@Getter\n@Setter\n@ToString\n/**\n * 映射规则\n * 1. source 代表源集合以json path表示的值\n * 2. target 代表目标集合以json path表示的key\n *\n * 映射的过程是将 源集合中以source为key的value赋值到目标集合以target为key的值上\n * 如:\n * 集合 input {\"key1\": \"value1\"} context {\"key1\": \"value2\"}\n * 其中规则为:\n * - source: 'key1'\n * target: 'key3'\n *映射结果为:\n * 集合 input {\"key1\": \"value1\"} context {\"key1\": \"value2\", \"key3\": \"value1\"}\n *\n */\npublic class Mapping {\n private String reference;\n private Boolean tolerance;\n private String source;\n private String transform;\n private String target;\n private String variable;\n\n public Mapping(String source, String target) {\n this.source = source;\n this.target = target;\n }\n}"
},
{
"identifier": "BaseResource",
"path": "rill-flow-interfaces/src/main/java/com/weibo/rill/flow/interfaces/model/resource/BaseResource.java",
"snippet": "@AllArgsConstructor\n@NoArgsConstructor\n@Setter\n@Getter\n@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = \"category\", visible = true)\npublic class BaseResource {\n private String name;\n private List<Mapping> inputMappings;\n private String category;\n}"
},
{
"identifier": "CallbackConfig",
"path": "rill-flow-dag/olympicene-core/src/main/java/com/weibo/rill/flow/olympicene/core/model/strategy/CallbackConfig.java",
"snippet": "@NoArgsConstructor\n@Getter\n@Setter\n@ToString\npublic class CallbackConfig {\n private String resourceName;\n private Boolean fullDAGInfo;\n private Boolean fullContext;\n private List<Mapping> inputMappings;\n\n @JsonCreator\n public CallbackConfig(@JsonProperty(\"resourceName\") String resourceName,\n @JsonProperty(\"fullDAGInfo\") Boolean fullDAGInfo,\n @JsonProperty(\"fullContext\") Boolean fullContext,\n @JsonProperty(\"inputMappings\") List<Mapping> inputMappings) {\n this.resourceName = resourceName;\n this.fullDAGInfo = fullDAGInfo;\n this.fullContext = fullContext;\n this.inputMappings = inputMappings;\n }\n}"
},
{
"identifier": "Timeline",
"path": "rill-flow-interfaces/src/main/java/com/weibo/rill/flow/interfaces/model/strategy/Timeline.java",
"snippet": "@Setter\n@Getter\npublic class Timeline {\n private String timeoutInSeconds;\n private String suspenseIntervalSeconds;\n private String suspenseTimestamp;\n\n @JsonCreator\n public Timeline(@JsonProperty(\"timeoutInSeconds\") String timeoutInSeconds,\n @JsonProperty(\"suspenseIntervalSeconds\") String suspenseIntervalSeconds,\n @JsonProperty(\"suspenseTimestamp\") String suspenseTimestamp) {\n this.timeoutInSeconds = timeoutInSeconds;\n this.suspenseIntervalSeconds = suspenseIntervalSeconds;\n this.suspenseTimestamp = suspenseTimestamp;\n }\n}"
},
{
"identifier": "BaseTask",
"path": "rill-flow-interfaces/src/main/java/com/weibo/rill/flow/interfaces/model/task/BaseTask.java",
"snippet": "@AllArgsConstructor\n@NoArgsConstructor\n@Setter\n@Getter\n@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = \"category\", visible = true)\npublic abstract class BaseTask {\n\n private String name;\n private String category;\n private String next;\n private boolean tolerance = false;\n private List<Mapping> inputMappings;\n private List<Mapping> outputMappings;\n private Progress progress;\n private Degrade degrade;\n private Timeline timeline;\n private boolean isKeyCallback = false;\n private String keyExp;\n private Map<String,Object> parameters;\n\n public abstract List<BaseTask> subTasks();\n}"
}
] | import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.weibo.rill.flow.interfaces.model.mapping.Mapping;
import com.weibo.rill.flow.interfaces.model.resource.BaseResource;
import com.weibo.rill.flow.olympicene.core.model.strategy.CallbackConfig;
import com.weibo.rill.flow.interfaces.model.strategy.Timeline;
import com.weibo.rill.flow.interfaces.model.task.BaseTask;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import java.util.List;
import java.util.Map; | 1,309 | /*
* Copyright 2021-2023 Weibo, 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.weibo.rill.flow.olympicene.core.model.dag;
@Getter
@NoArgsConstructor
public class DAG {
private String workspace;
private String dagName;
private String version;
private DAGType type; | /*
* Copyright 2021-2023 Weibo, 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.weibo.rill.flow.olympicene.core.model.dag;
@Getter
@NoArgsConstructor
public class DAG {
private String workspace;
private String dagName;
private String version;
private DAGType type; | private Timeline timeline; | 3 | 2023-11-03 03:46:01+00:00 | 2k |
hei-school/poja-cli | tests/oracles/oracle-poja-base-without-postgres/src/test/java/com/company/base/endpoint/rest/controller/HealthControllerIT.java | [
{
"identifier": "OK",
"path": "tests/oracles/oracle-poja-base-with-java-env-vars/src/main/java/com/company/base/endpoint/rest/controller/health/PingController.java",
"snippet": "public static final ResponseEntity<String> OK = new ResponseEntity<>(\"OK\", HttpStatus.OK);"
},
{
"identifier": "FacadeIT",
"path": "tests/oracles/oracle-poja-base-with-java-env-vars/src/test/java/com/company/base/conf/FacadeIT.java",
"snippet": "@PojaGenerated\n@SpringBootTest(webEnvironment = RANDOM_PORT)\n@Slf4j\npublic class FacadeIT {\n\n private static final PostgresConf POSTGRES_CONF = new PostgresConf();\n\n @BeforeAll\n static void beforeAll() {\n POSTGRES_CONF.start();\n getRuntime()\n // Do _not_ stop postgresTest in afterAll as it is shared between multiple subclasses of\n // FacadeTest.\n // Doing so might cause some subclasses to stop it while other ones are still using it!\n .addShutdownHook(new Thread(POSTGRES_CONF::stop));\n }\n\n @SneakyThrows\n @DynamicPropertySource\n static void configureProperties(DynamicPropertyRegistry registry) {\n POSTGRES_CONF.configureProperties(registry);\n\n new EventConf().configureProperties(registry);\n new BucketConf().configureProperties(registry);\n new EmailConf().configureProperties(registry);\n\n try {\n var envConfClazz = Class.forName(\"com.company.base.conf.EnvConf\");\n var envConfConfigureProperties =\n envConfClazz.getDeclaredMethod(\"configureProperties\", DynamicPropertyRegistry.class);\n var envConf = envConfClazz.getConstructor().newInstance();\n envConfConfigureProperties.invoke(envConf, registry);\n } catch (ClassNotFoundException e) {\n log.warn(\"EnvConf missing: no project-specific test env vars will be set\");\n }\n }\n}"
},
{
"identifier": "HealthDbController",
"path": "tests/oracles/oracle-poja-base-with-java-env-vars/src/main/java/com/company/base/endpoint/rest/controller/health/HealthDbController.java",
"snippet": "@PojaGenerated\n@RestController\n@AllArgsConstructor\npublic class HealthDbController {\n\n DummyRepository dummyRepository;\n\n @GetMapping(\"/health/db\")\n public ResponseEntity<String> dummyTable_should_not_be_empty() {\n return dummyRepository.findAll().isEmpty() ? KO : OK;\n }\n}"
},
{
"identifier": "PingController",
"path": "tests/oracles/oracle-poja-base-with-java-env-vars/src/main/java/com/company/base/endpoint/rest/controller/health/PingController.java",
"snippet": "@PojaGenerated\n@RestController\n@AllArgsConstructor\npublic class PingController {\n\n DummyRepository dummyRepository;\n DummyUuidRepository dummyUuidRepository;\n\n public static final ResponseEntity<String> OK = new ResponseEntity<>(\"OK\", HttpStatus.OK);\n public static final ResponseEntity<String> KO =\n new ResponseEntity<>(\"KO\", HttpStatus.INTERNAL_SERVER_ERROR);\n\n @GetMapping(\"/ping\")\n public String ping() {\n return \"pong\";\n }\n}"
}
] | import static com.company.base.endpoint.rest.controller.health.PingController.OK;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.company.base.PojaGenerated;
import com.company.base.conf.FacadeIT;
import com.company.base.endpoint.rest.controller.health.HealthDbController;
import com.company.base.endpoint.rest.controller.health.PingController;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; | 850 | package com.company.base.endpoint.rest.controller;
@PojaGenerated
class HealthControllerIT extends FacadeIT {
@Autowired PingController pingController;
@Autowired HealthDbController healthDbController;
@Test
void ping() {
assertEquals("pong", pingController.ping());
}
@Test
void can_read_from_dummy_table() {
var responseEntity = healthDbController.dummyTable_should_not_be_empty(); | package com.company.base.endpoint.rest.controller;
@PojaGenerated
class HealthControllerIT extends FacadeIT {
@Autowired PingController pingController;
@Autowired HealthDbController healthDbController;
@Test
void ping() {
assertEquals("pong", pingController.ping());
}
@Test
void can_read_from_dummy_table() {
var responseEntity = healthDbController.dummyTable_should_not_be_empty(); | assertEquals(OK, responseEntity); | 0 | 2023-11-01 13:38:16+00:00 | 2k |
Yanyutin753/fakeApiTool-One-API | rearServer/src/main/java/com/yyandywt99/fakeapitool/interceptor/LoginCheckInterceptor.java | [
{
"identifier": "Result",
"path": "rearServer/src/main/java/com/yyandywt99/fakeapitool/pojo/Result.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class Result {\n private Integer code;//响应码,1 代表成功; 0 代表失败\n private String msg; //响应信息 描述字符串\n private Object data; //返回的数据\n\n //增删改 成功响应\n public static Result success(){\n return new Result(1,\"success\",null);\n }\n //查询 成功响应\n public static Result success(Object data){\n return new Result(1,\"success\",data);\n }\n //失败响应\n public static Result error(String msg){\n return new Result(0,msg,null);\n }\n}"
},
{
"identifier": "JwtUtils",
"path": "rearServer/src/main/java/com/yyandywt99/fakeapitool/util/JwtUtils.java",
"snippet": "public class JwtUtils {\n\n private static String signKey = \"fakeApiTool\";\n private static Long expire = 43200000L;\n\n /**\n * 生成JWT令牌\n * @param claims JWT第二部分负载 payload 中存储的内容\n * @return\n */\n public static String generateJwt(Map<String, Object> claims){\n String jwt = Jwts.builder()\n .addClaims(claims)\n .signWith(SignatureAlgorithm.HS256, signKey)\n .setExpiration(new Date(System.currentTimeMillis() + expire))\n .compact();\n return jwt;\n }\n\n /**\n * 解析JWT令牌\n * @param jwt JWT令牌\n * @return JWT第二部分负载 payload 中存储的内容\n */\n public static Claims parseJWT(String jwt){\n Claims claims = Jwts.parser()\n .setSigningKey(signKey)\n .parseClaimsJws(jwt)\n .getBody();\n return claims;\n }\n}"
}
] | import com.alibaba.fastjson.JSONObject;
import com.yyandywt99.fakeapitool.pojo.Result;
import com.yyandywt99.fakeapitool.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; | 927 | package com.yyandywt99.fakeapitool.interceptor;
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
@Override //目标资源方法运行前运行, 返回true: 放行, 放回false, 不放行
public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
//1.获取请求url。
String url = req.getRequestURL().toString();
log.info("请求的url: {}",url);
//2.判断请求url中是否包含login,如果包含,说明是登录操作,放行。
if(url.contains("login")){
log.info("登录操作, 放行...");
return true;
}
//3.获取请求头中的令牌(token)。
String jwt = req.getHeader("Authorization");
log.info(jwt);
//4.判断令牌是否存在,如果不存在,返回错误结果(未登录)。
if(!StringUtils.hasLength(jwt) || !jwt.startsWith("Bearer ")){
log.info("请求头token空或没有Bearer ,返回未登录的信息");
Result error = Result.error("NOT_LOGIN");
//手动转换 对象--json --------> 阿里巴巴fastJSON
String notLogin = JSONObject.toJSONString(error);
resp.getWriter().write(notLogin);
return false;
}
jwt = jwt.substring(7);
//5.解析token,如果解析失败,返回错误结果(未登录)。
try { | package com.yyandywt99.fakeapitool.interceptor;
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
@Override //目标资源方法运行前运行, 返回true: 放行, 放回false, 不放行
public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
//1.获取请求url。
String url = req.getRequestURL().toString();
log.info("请求的url: {}",url);
//2.判断请求url中是否包含login,如果包含,说明是登录操作,放行。
if(url.contains("login")){
log.info("登录操作, 放行...");
return true;
}
//3.获取请求头中的令牌(token)。
String jwt = req.getHeader("Authorization");
log.info(jwt);
//4.判断令牌是否存在,如果不存在,返回错误结果(未登录)。
if(!StringUtils.hasLength(jwt) || !jwt.startsWith("Bearer ")){
log.info("请求头token空或没有Bearer ,返回未登录的信息");
Result error = Result.error("NOT_LOGIN");
//手动转换 对象--json --------> 阿里巴巴fastJSON
String notLogin = JSONObject.toJSONString(error);
resp.getWriter().write(notLogin);
return false;
}
jwt = jwt.substring(7);
//5.解析token,如果解析失败,返回错误结果(未登录)。
try { | JwtUtils.parseJWT(jwt); | 1 | 2023-11-09 08:04:54+00:00 | 2k |
aliyun/alibabacloud-compute-nest-saas-boost | boost.common/src/main/java/org/example/common/dto/OrderDTO.java | [
{
"identifier": "PayPeriodUnit",
"path": "boost.common/src/main/java/org/example/common/constant/PayPeriodUnit.java",
"snippet": "public enum PayPeriodUnit {\n\n /**\n * Monthly subscription.\n */\n Month(\"月\"),\n\n /**\n * Daily subscription.\n */\n Day(\"日\"),\n\n /**\n * Annual subscription.\n */\n Year(\"年\");\n\n private String name;\n\n PayPeriodUnit(String name){\n this.name = name;\n }\n\n @Override\n public String toString() {\n return name();\n }\n}"
},
{
"identifier": "PaymentType",
"path": "boost.common/src/main/java/org/example/common/constant/PaymentType.java",
"snippet": "public enum PaymentType {\n\n /**\n * Alipay\n */\n ALIPAY(\"Alipay\", \"0\"),\n\n /**\n * Wechat pay\n */\n WECHATPAY(\"WeChat Pay\", \"1\"),\n\n /**\n * PayPal\n */\n PAYPAL(\"PayPal\", \"2\"),\n\n /**\n * credit card\n */\n CREDIT_CARD(\"Credit Card\", \"3\"),\n\n /**\n * Pay as you go\n */\n PAY_POST(\"Pay Post\", \"4\");\n\n private final String displayName;\n\n private final String value;\n\n PaymentType(String displayName, String value) {\n this.displayName = displayName;\n this.value = value;\n }\n\n PaymentType(String displayName) {\n this.displayName = displayName;\n this.value = \"0\";\n }\n\n public String getDisplayName() {\n return displayName;\n }\n\n public String getValue() {\n return value;\n }\n}"
},
{
"identifier": "ProductName",
"path": "boost.common/src/main/java/org/example/common/constant/ProductName.java",
"snippet": "public enum ProductName {\n\n /**\n * Compute nest service instance.\n */\n SERVICE_INSTANCE(\"serviceInstance\");\n private final String displayName;\n\n ProductName(String displayName) {\n this.displayName = displayName;\n }\n\n public String getDisplayName() {\n return displayName;\n }\n\n @Override\n public String toString() {\n return name();\n }\n}"
},
{
"identifier": "TradeStatus",
"path": "boost.common/src/main/java/org/example/common/constant/TradeStatus.java",
"snippet": "public enum TradeStatus {\n\n /**\n * The actions associated with this status are as follows:\n * 1. Unpaid transaction timeout closure\n * 2. full refund after payment is completed\n */\n TRADE_CLOSED(\"交易关闭\"),\n\n /**\n * Transaction payment successfully completed.\n */\n TRADE_SUCCESS(\"支付成功\"),\n\n /**\n * Transaction created, waiting for buyer's payment.\n */\n WAIT_BUYER_PAY(\"交易创建\"),\n\n /**\n * Transaction ended, non-refundable.\n */\n TRADE_FINISHED( \"交易完结\"),\n\n /**\n * Refunded.\n */\n REFUNDED(\"已经退款\"),\n\n /**\n * Refund in progress, awaiting processing by Function Compute.\n */\n REFUNDING(\"退款中\");\n\n private final String displayName;\n\n TradeStatus(String displayName) {\n this.displayName = displayName;\n }\n\n public String getDisplayName() {\n return displayName;\n }\n\n @Override\n public String toString() {\n return name();\n }\n}"
}
] | import org.example.common.constant.PayPeriodUnit;
import org.example.common.constant.PaymentType;
import org.example.common.constant.ProductName;
import org.example.common.constant.TradeStatus;
import lombok.Data; | 1,048 | /*
*Copyright (c) Alibaba Group;
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/
package org.example.common.dto;
@Data
public class OrderDTO {
/**
* The Order ID, which corresponds to the Alipay Out Transaction Number.
*/
private String orderId;
/**
* Transaction status.
*/ | /*
*Copyright (c) Alibaba Group;
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/
package org.example.common.dto;
@Data
public class OrderDTO {
/**
* The Order ID, which corresponds to the Alipay Out Transaction Number.
*/
private String orderId;
/**
* Transaction status.
*/ | private TradeStatus tradeStatus; | 3 | 2023-11-01 08:19:34+00:00 | 2k |
softwaremill/jox | core/src/test/java/com/softwaremill/jox/SegmentRendezvousTest.java | [
{
"identifier": "SEGMENT_SIZE",
"path": "core/src/main/java/com/softwaremill/jox/Segment.java",
"snippet": "static final int SEGMENT_SIZE = 32; // 2^5"
},
{
"identifier": "createSegmentChain",
"path": "core/src/test/java/com/softwaremill/jox/SegmentTest.java",
"snippet": "static Segment[] createSegmentChain(int count, long id, boolean isRendezvous) {\n var segments = new Segment[count];\n var thisSegment = new Segment(id, null, 0, isRendezvous);\n segments[0] = thisSegment;\n for (int i = 1; i < count; i++) {\n var nextSegment = new Segment(id + i, thisSegment, 0, isRendezvous);\n thisSegment.setNext(nextSegment);\n segments[i] = nextSegment;\n thisSegment = nextSegment;\n }\n return segments;\n}"
},
{
"identifier": "sendInterruptAllCells",
"path": "core/src/test/java/com/softwaremill/jox/SegmentTest.java",
"snippet": "static void sendInterruptAllCells(Segment s) {\n for (int i = 0; i < SEGMENT_SIZE; i++) {\n s.cellInterruptedSender();\n }\n}"
},
{
"identifier": "forkVoid",
"path": "core/src/test/java/com/softwaremill/jox/TestUtil.java",
"snippet": "public static Future<Void> forkVoid(StructuredTaskScope<Object> scope, RunnableWithException r) {\n return fork(scope, () -> {\n r.run();\n return null;\n });\n}"
},
{
"identifier": "scoped",
"path": "core/src/test/java/com/softwaremill/jox/TestUtil.java",
"snippet": "public static void scoped(ConsumerWithException<StructuredTaskScope<Object>> f) throws InterruptedException, ExecutionException {\n try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {\n // making sure everything runs in a VT\n scope.fork(() -> {\n f.accept(scope);\n return null;\n });\n scope.join().throwIfFailed();\n }\n}"
}
] | import org.junit.jupiter.api.Test;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReference;
import static com.softwaremill.jox.Segment.SEGMENT_SIZE;
import static com.softwaremill.jox.SegmentTest.createSegmentChain;
import static com.softwaremill.jox.SegmentTest.sendInterruptAllCells;
import static com.softwaremill.jox.TestUtil.forkVoid;
import static com.softwaremill.jox.TestUtil.scoped;
import static org.junit.jupiter.api.Assertions.*; | 1,585 | package com.softwaremill.jox;
public class SegmentRendezvousTest {
// rendezvous segment = where countProcessed is false
@Test
void segmentShouldBecomeRemovedOnceAllCellsInterrupted() {
// given
var ss = createSegmentChain(3, 0, true);
// when
for (int i = 0; i < SEGMENT_SIZE - 1; i++) {
ss[1].cellInterruptedReceiver();
// nothing should happen
assertFalse(ss[1].isRemoved());
assertEquals(ss[1].getPrev(), ss[0]);
assertEquals(ss[1].getNext(), ss[2]);
assertEquals(ss[0].getPrev(), null);
assertEquals(ss[0].getNext(), ss[1]);
assertEquals(ss[2].getPrev(), ss[1]);
assertEquals(ss[2].getNext(), null);
}
ss[1].cellInterruptedReceiver(); // last cell
assertTrue(ss[1].isRemoved());
// then
assertEquals(ss[0].getPrev(), null);
assertEquals(ss[0].getNext(), ss[2]);
assertEquals(ss[2].getPrev(), ss[0]);
assertEquals(ss[2].getNext(), null);
}
@Test
void shouldRemoveMultipleSegments() {
// given
var ss = createSegmentChain(5, 0, true);
// when
// first, preventing automatic removal
assertTrue(ss[1].tryIncPointers());
assertTrue(ss[2].tryIncPointers());
assertTrue(ss[3].tryIncPointers());
// interrupting all cells
for (int i = 0; i < SEGMENT_SIZE; i++) {
ss[1].cellInterruptedReceiver();
assertFalse(ss[1].isRemoved());
ss[2].cellInterruptedReceiver();
assertFalse(ss[2].isRemoved());
ss[3].cellInterruptedReceiver();
assertFalse(ss[3].isRemoved());
}
// decreasing number of pointers, segments become logically removed
assertTrue(ss[1].decPointers());
assertTrue(ss[2].decPointers());
assertTrue(ss[3].decPointers());
// but the chain is so far untouched
assertEquals(ss[0].getNext(), ss[1]);
assertEquals(ss[1].getNext(), ss[2]);
assertEquals(ss[2].getNext(), ss[3]);
assertEquals(ss[3].getNext(), ss[4]);
// finally, calling remove which should clean up
ss[2].remove();
// then
assertEquals(ss[0].getNext(), ss[4]);
assertEquals(ss[4].getPrev(), ss[0]);
}
@Test
void shouldNotIncrementIncomingPointersIfSegmentRemoved() {
// given
var ss = createSegmentChain(1, 0, true);
// when
sendInterruptAllCells(ss[0]);
// then
assertFalse(ss[0].tryIncPointers());
}
@Test
void shouldIncrementAndDecrementPointersInSegment() {
// given
var ss = createSegmentChain(1, 0, true);
// when
assertTrue(ss[0].tryIncPointers());
assertFalse(ss[0].decPointers());
}
@Test
void shouldNotRemoveSegmentIfThereAreIncomingPointers() {
// given
var ss = createSegmentChain(2, 0, true);
// when
assertTrue(ss[0].tryIncPointers());
for (int i = 0; i < SEGMENT_SIZE; i++) {
ss[0].cellInterruptedReceiver();
assertFalse(ss[0].isRemoved());
}
// decreasing the number of pointers
assertTrue(ss[0].decPointers());
assertTrue(ss[0].isRemoved());
ss[0].remove();
assertEquals(ss[1].getPrev(), null);
assertEquals(ss[1].getNext(), null);
}
@Test
void shouldRemoveSegmentsWhenRunConcurrently() throws ExecutionException, InterruptedException {
// given
int segmentCount = 30;
for (int k = 0; k < 1000; k++) {
var ss = createSegmentChain(segmentCount, 0, true);
// when
scoped(scope -> {
// first interrupting all cells but one in segments 2-(segmentCount-1))
for (int i = 1; i < ss.length - 1; i++) {
for (int j = 0; j < SEGMENT_SIZE - 1; j++) {
ss[i].cellInterruptedReceiver();
}
}
// then, running (segmentCount-2) forks which will interrupt the last cell in each segment
for (int i = 1; i < ss.length - 1; i++) {
int ii = i; | package com.softwaremill.jox;
public class SegmentRendezvousTest {
// rendezvous segment = where countProcessed is false
@Test
void segmentShouldBecomeRemovedOnceAllCellsInterrupted() {
// given
var ss = createSegmentChain(3, 0, true);
// when
for (int i = 0; i < SEGMENT_SIZE - 1; i++) {
ss[1].cellInterruptedReceiver();
// nothing should happen
assertFalse(ss[1].isRemoved());
assertEquals(ss[1].getPrev(), ss[0]);
assertEquals(ss[1].getNext(), ss[2]);
assertEquals(ss[0].getPrev(), null);
assertEquals(ss[0].getNext(), ss[1]);
assertEquals(ss[2].getPrev(), ss[1]);
assertEquals(ss[2].getNext(), null);
}
ss[1].cellInterruptedReceiver(); // last cell
assertTrue(ss[1].isRemoved());
// then
assertEquals(ss[0].getPrev(), null);
assertEquals(ss[0].getNext(), ss[2]);
assertEquals(ss[2].getPrev(), ss[0]);
assertEquals(ss[2].getNext(), null);
}
@Test
void shouldRemoveMultipleSegments() {
// given
var ss = createSegmentChain(5, 0, true);
// when
// first, preventing automatic removal
assertTrue(ss[1].tryIncPointers());
assertTrue(ss[2].tryIncPointers());
assertTrue(ss[3].tryIncPointers());
// interrupting all cells
for (int i = 0; i < SEGMENT_SIZE; i++) {
ss[1].cellInterruptedReceiver();
assertFalse(ss[1].isRemoved());
ss[2].cellInterruptedReceiver();
assertFalse(ss[2].isRemoved());
ss[3].cellInterruptedReceiver();
assertFalse(ss[3].isRemoved());
}
// decreasing number of pointers, segments become logically removed
assertTrue(ss[1].decPointers());
assertTrue(ss[2].decPointers());
assertTrue(ss[3].decPointers());
// but the chain is so far untouched
assertEquals(ss[0].getNext(), ss[1]);
assertEquals(ss[1].getNext(), ss[2]);
assertEquals(ss[2].getNext(), ss[3]);
assertEquals(ss[3].getNext(), ss[4]);
// finally, calling remove which should clean up
ss[2].remove();
// then
assertEquals(ss[0].getNext(), ss[4]);
assertEquals(ss[4].getPrev(), ss[0]);
}
@Test
void shouldNotIncrementIncomingPointersIfSegmentRemoved() {
// given
var ss = createSegmentChain(1, 0, true);
// when
sendInterruptAllCells(ss[0]);
// then
assertFalse(ss[0].tryIncPointers());
}
@Test
void shouldIncrementAndDecrementPointersInSegment() {
// given
var ss = createSegmentChain(1, 0, true);
// when
assertTrue(ss[0].tryIncPointers());
assertFalse(ss[0].decPointers());
}
@Test
void shouldNotRemoveSegmentIfThereAreIncomingPointers() {
// given
var ss = createSegmentChain(2, 0, true);
// when
assertTrue(ss[0].tryIncPointers());
for (int i = 0; i < SEGMENT_SIZE; i++) {
ss[0].cellInterruptedReceiver();
assertFalse(ss[0].isRemoved());
}
// decreasing the number of pointers
assertTrue(ss[0].decPointers());
assertTrue(ss[0].isRemoved());
ss[0].remove();
assertEquals(ss[1].getPrev(), null);
assertEquals(ss[1].getNext(), null);
}
@Test
void shouldRemoveSegmentsWhenRunConcurrently() throws ExecutionException, InterruptedException {
// given
int segmentCount = 30;
for (int k = 0; k < 1000; k++) {
var ss = createSegmentChain(segmentCount, 0, true);
// when
scoped(scope -> {
// first interrupting all cells but one in segments 2-(segmentCount-1))
for (int i = 1; i < ss.length - 1; i++) {
for (int j = 0; j < SEGMENT_SIZE - 1; j++) {
ss[i].cellInterruptedReceiver();
}
}
// then, running (segmentCount-2) forks which will interrupt the last cell in each segment
for (int i = 1; i < ss.length - 1; i++) {
int ii = i; | forkVoid(scope, () -> { | 3 | 2023-11-08 12:58:16+00:00 | 2k |
mioclient/oyvey-ported | src/main/java/me/alpha432/oyvey/features/commands/impl/FriendCommand.java | [
{
"identifier": "OyVey",
"path": "src/main/java/me/alpha432/oyvey/OyVey.java",
"snippet": "public class OyVey implements ModInitializer, ClientModInitializer {\n public static final String NAME = \"OyVey\";\n public static final String VERSION = \"0.0.3 - 1.20.1\";\n\n public static float TIMER = 1f;\n\n public static final Logger LOGGER = LogManager.getLogger(\"OyVey\");\n public static ServerManager serverManager;\n public static ColorManager colorManager;\n public static RotationManager rotationManager;\n public static PositionManager positionManager;\n public static HoleManager holeManager;\n public static EventManager eventManager;\n public static SpeedManager speedManager;\n public static CommandManager commandManager;\n public static FriendManager friendManager;\n public static ModuleManager moduleManager;\n public static ConfigManager configManager;\n\n\n @Override public void onInitialize() {\n eventManager = new EventManager();\n serverManager = new ServerManager();\n rotationManager = new RotationManager();\n positionManager = new PositionManager();\n friendManager = new FriendManager();\n colorManager = new ColorManager();\n commandManager = new CommandManager();\n moduleManager = new ModuleManager();\n speedManager = new SpeedManager();\n holeManager = new HoleManager();\n }\n\n\n @Override public void onInitializeClient() {\n eventManager.init();\n moduleManager.init();\n\n configManager = new ConfigManager();\n configManager.load();\n colorManager.init();\n Runtime.getRuntime().addShutdownHook(new Thread(() -> configManager.save()));\n }\n}"
},
{
"identifier": "Command",
"path": "src/main/java/me/alpha432/oyvey/features/commands/Command.java",
"snippet": "public abstract class Command\n extends Feature {\n protected String name;\n protected String[] commands;\n\n public Command(String name) {\n super(name);\n this.name = name;\n this.commands = new String[]{\"\"};\n }\n\n public Command(String name, String[] commands) {\n super(name);\n this.name = name;\n this.commands = commands;\n }\n\n public static void sendMessage(String message) {\n Command.sendSilentMessage(OyVey.commandManager.getClientMessage() + \" \" + Formatting.GRAY + message);\n }\n\n public static void sendSilentMessage(String message) {\n if (Command.nullCheck()) {\n return;\n }\n // TODO add silent support ig\n mc.inGameHud.getChatHud().addMessage(Text.literal(message));\n }\n\n public static String getCommandPrefix() {\n return OyVey.commandManager.getPrefix();\n }\n\n public abstract void execute(String[] var1);\n\n @Override\n public String getName() {\n return this.name;\n }\n\n public String[] getCommands() {\n return this.commands;\n }\n}"
}
] | import me.alpha432.oyvey.OyVey;
import me.alpha432.oyvey.features.commands.Command;
import net.minecraft.util.Formatting; | 803 | package me.alpha432.oyvey.features.commands.impl;
public class FriendCommand
extends Command {
public FriendCommand() {
super("friend", new String[]{"<add/del/name/clear>", "<name>"});
}
@Override
public void execute(String[] commands) {
if (commands.length == 1) { | package me.alpha432.oyvey.features.commands.impl;
public class FriendCommand
extends Command {
public FriendCommand() {
super("friend", new String[]{"<add/del/name/clear>", "<name>"});
}
@Override
public void execute(String[] commands) {
if (commands.length == 1) { | if (OyVey.friendManager.getFriends().isEmpty()) { | 0 | 2023-11-05 18:10:28+00:00 | 2k |
Jlan45/MCCTF | src/main/java/darkflow/mcctf/MCCTF.java | [
{
"identifier": "BlockFlagCollecter",
"path": "src/main/java/darkflow/mcctf/blocks/BlockFlagCollecter.java",
"snippet": "public class BlockFlagCollecter extends Block {\n public BlockFlagCollecter() {\n super(Settings.of(Material.ICE).hardness(-1f).dropsNothing());\n }\n @Override\n public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) {\n\n if(!world.isClient) {\n ItemStack itemStack = player.getHandItems().iterator().next();\n if (itemStack.getItem().getTranslationKey().equals(\"item.mcctf.flag\")) {\n //TODO flag验证\n String userFlag=itemStack.getNbt().getString(\"flag\");\n String questionUUID=itemStack.getNbt().getString(\"question\");\n Question tmpQuestion=new Question(\"test\", UUID.randomUUID().toString(),1000,\"\",\"\");\n try {\n if (verifyFlag(player,tmpQuestion, userFlag)) {\n player.sendMessage(Text.of(\"Flag验证成功\"), false);\n player.increaseStat(MCCTF.PLAYER_CONTEST_SCORE,tmpQuestion.getScore());\n ItemStack itemStack1 = new ItemStack(Items.AIR);\n player.setStackInHand(hand, itemStack1);\n }\n else {\n player.sendMessage(Text.of(\"Flag验证失败\"), false);\n }\n } catch (NoSuchAlgorithmException e) {\n throw new RuntimeException(e);\n }\n }\n }\n return ActionResult.SUCCESS;\n\n }\n}"
},
{
"identifier": "BlockFlagGetter",
"path": "src/main/java/darkflow/mcctf/blocks/BlockFlagGetter.java",
"snippet": "public class BlockFlagGetter extends Block {\n public BlockFlagGetter() {\n super(Settings.of(net.minecraft.block.Material.ICE).dropsNothing().strength(-1f,-1f));\n }\n\n @Override\n public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) {\n if(!world.isClient) {\n NbtCompound tag = new NbtCompound();\n tag.putString(\"flag\", \"FLAG{TEST}\");\n ItemStack itemStack = new ItemStack(FLAG);\n itemStack.setNbt(tag);\n player.giveItemStack(itemStack);\n }\n// else{\n// player.sendMessage(Text.of(\"要在服务器上跑才可以哦\"));\n// }\n return ActionResult.SUCCESS;\n\n\n }\n}"
},
{
"identifier": "TestCommand",
"path": "src/main/java/darkflow/mcctf/commands/TestCommand.java",
"snippet": "public class TestCommand {\n public static void register(CommandDispatcher<ServerCommandSource> dispatcher){\n dispatcher.register(literal(\"test\")\n .requires(source -> source.hasPermissionLevel(0)) // 只有管理员能够执行命令。命令不会对非操作员或低于 1 级权限的玩家显示在 tab-完成中,也不会让他们执行。\n .then(argument(\"message\", greedyString())\n .executes(ctx -> test(ctx.getSource(), getString(ctx, \"message\"))))); // 你可以在这里处理参数,并处理成命令。\n }\n\n public static int test(ServerCommandSource source, String message) {\n ServerPlayerEntity player=source.getPlayer();\n //获取玩家死亡次数\n StatHandler sh=player.getStatHandler();\n player.increaseStat(PLAYER_CONTEST_SCORE,1);\n player.resetStat(Stats.CUSTOM.getOrCreateStat(PLAYER_CONTEST_SCORE));\n int score=sh.getStat(Stats.CUSTOM.getOrCreateStat(PLAYER_CONTEST_SCORE));\n player.sendMessage(Text.of(\"你的分数是\"+score),false);\n return Command.SINGLE_SUCCESS; // 成功\n }\n}"
},
{
"identifier": "ItemFlag",
"path": "src/main/java/darkflow/mcctf/items/ItemFlag.java",
"snippet": "public class ItemFlag extends Item {\n public ItemFlag() {\n super(new FabricItemSettings().maxCount(1).rarity(Rarity.EPIC));\n }\n\n\n\n @Override\n public ActionResult useOnBlock(ItemUsageContext context) {\n if (!context.getWorld().isClient) {\n if(context.getPlayer()!=null){\n context.getPlayer().sendMessage(Text.of(\"Flag应该放到Flag箱里\"));\n }\n }\n return ActionResult.SUCCESS;\n }\n\n\n// @Override\n// public void appendTooltip(ItemStack itemStack, World world, List<Text> tooltip, TooltipContext tooltipContext) {\n// // 默认为白色文本\n// tooltip.add(Text.of(\"flag{thisisflag}\"));\n// }\n\n}"
},
{
"identifier": "ItemFlagCollecter",
"path": "src/main/java/darkflow/mcctf/items/ItemFlagCollecter.java",
"snippet": "public class ItemFlagCollecter extends BlockItem {\n\n public ItemFlagCollecter(Block block, Item.Settings settings) {\n super(block, settings);\n }\n}"
},
{
"identifier": "ItemFlagGetter",
"path": "src/main/java/darkflow/mcctf/items/ItemFlagGetter.java",
"snippet": "public class ItemFlagGetter extends BlockItem {\n public ItemFlagGetter(Block block, Settings settings) {\n super(block, settings);\n }\n}"
}
] | import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.tree.LiteralCommandNode;
import darkflow.mcctf.blocks.BlockFlagCollecter;
import darkflow.mcctf.blocks.BlockFlagGetter;
import darkflow.mcctf.commands.BroadCastCommand;
import darkflow.mcctf.commands.TestCommand;
import darkflow.mcctf.items.ItemFlag;
import darkflow.mcctf.items.ItemFlagCollecter;
import darkflow.mcctf.items.ItemFlagGetter;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.fabricmc.fabric.api.item.v1.FabricItemSettings;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
import net.fabricmc.fabric.api.object.builder.v1.block.entity.FabricBlockEntityTypeBuilder;
import net.minecraft.block.AbstractBlock;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.block.Material;
import net.minecraft.block.entity.BlockEntityType;
import net.minecraft.item.BlockItem;
import net.minecraft.stat.Stats;
import net.minecraft.util.Identifier;
import net.minecraft.util.Rarity;
import net.minecraft.util.registry.Registry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import static net.minecraft.client.render.entity.feature.TridentRiptideFeatureRenderer.BOX; | 1,541 | package darkflow.mcctf;
public class MCCTF implements ModInitializer {
/**
* Runs the mod initializer.
*/
public static final Logger LOGGER = LoggerFactory.getLogger("mcctf");
public static final ItemFlag FLAG=new ItemFlag(); | package darkflow.mcctf;
public class MCCTF implements ModInitializer {
/**
* Runs the mod initializer.
*/
public static final Logger LOGGER = LoggerFactory.getLogger("mcctf");
public static final ItemFlag FLAG=new ItemFlag(); | public static final BlockFlagGetter FLAG_GETTER_BLOCK=new BlockFlagGetter(); | 1 | 2023-11-01 14:11:07+00:00 | 2k |
EB-wilson/TooManyItems | src/main/java/tmi/recipe/EnvParameter.java | [
{
"identifier": "HeatMark",
"path": "src/main/java/tmi/recipe/types/HeatMark.java",
"snippet": "public class HeatMark extends RecipeItem<String> {\n public static HeatMark INSTANCE = TooManyItems.itemsManager.addItemWrap(\"heat-mark\", new HeatMark());\n\n private HeatMark() {\n super(\"heat-mark\");\n }\n\n @Override\n public int ordinal() {\n return -1;\n }\n\n @Override\n public int typeID() {\n return -1;\n }\n\n @Override\n public String name() {\n return item;\n }\n\n @Override\n public String localizedName() {\n return Core.bundle.get(\"tmi.\" + item);\n }\n\n @Override\n public TextureRegion icon() {\n return Icon.waves.getRegion();\n }\n\n @Override\n public boolean hidden() {\n return false;\n }\n}"
},
{
"identifier": "PowerMark",
"path": "src/main/java/tmi/recipe/types/PowerMark.java",
"snippet": "public class PowerMark extends RecipeItem<String> {\n public static PowerMark INSTANCE = TooManyItems.itemsManager.addItemWrap(\"power-mark\", new PowerMark());\n\n private PowerMark() {\n super(\"power-mark\");\n }\n\n @Override\n public int ordinal() {\n return -1;\n }\n\n @Override\n public int typeID() {\n return -1;\n }\n\n @Override\n public String name() {\n return item;\n }\n\n @Override\n public String localizedName() {\n return Core.bundle.get(\"tmi.\" + item);\n }\n\n @Override\n public TextureRegion icon() {\n return Icon.power.getRegion();\n }\n\n @Override\n public boolean hidden() {\n return false;\n }\n}"
},
{
"identifier": "RecipeItem",
"path": "src/main/java/tmi/recipe/types/RecipeItem.java",
"snippet": "public abstract class RecipeItem<T> implements Comparable<RecipeItem<?>>{\n public final T item;\n\n protected RecipeItem(T item) {\n this.item = item;\n }\n\n public abstract int ordinal();\n public abstract int typeID();\n public abstract String name();\n public abstract String localizedName();\n public abstract TextureRegion icon();\n public abstract boolean hidden();\n\n public boolean hasDetails(){ return false; }\n public void displayDetails(){}\n\n public boolean locked() {\n return false;\n }\n\n @Override\n public int compareTo(RecipeItem<?> o) {\n int n = Integer.compare(typeID(), o.typeID());\n\n if (n == 0){\n return ordinal() - o.ordinal();\n }\n\n return n;\n }\n\n @Override\n public boolean equals(Object object) {\n if (this == object) return true;\n if (object == null || getClass() != object.getClass()) return false;\n RecipeItem<?> that = (RecipeItem<?>) object;\n return Objects.equals(item, that.item);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(name());\n }\n}"
}
] | import arc.func.Cons2;
import arc.struct.ObjectFloatMap;
import tmi.recipe.types.HeatMark;
import tmi.recipe.types.PowerMark;
import tmi.recipe.types.RecipeItem; | 1,276 | package tmi.recipe;
public class EnvParameter {
private final ObjectFloatMap<RecipeItem<?>> inputs = new ObjectFloatMap<>();
private final ObjectFloatMap<RecipeItem<?>> attributes = new ObjectFloatMap<>();
public float getInputs(RecipeItem<?> b) {
return inputs.get(b, 0f);
}
public float getAttribute(RecipeItem<?> b) {
return attributes.get(b, 0f);
}
public EnvParameter add(RecipeItemStack item){
return add(item.item, item.amount, item.isAttribute);
}
public EnvParameter add(RecipeItem<?> item, float amount, boolean isAttribute){
if (isAttribute){
attributes.increment(item, 0, amount);
}
else inputs.increment(item, 0, amount);
return this;
}
public EnvParameter set(EnvParameter other){
other.attributes.each(e -> add(e.key, e.value, true));
other.inputs.each(e -> add(e.key, e.value, false));
return this;
}
public EnvParameter setInputs(EnvParameter other){
other.inputs.each(e -> add(e.key, e.value, false));
return this;
}
public EnvParameter setAttributes(EnvParameter other){
other.attributes.each(e -> add(e.key, e.value, true));
return this;
}
public EnvParameter resetInput(RecipeItem<?> item){
inputs.remove(item, 0);
return this;
}
public EnvParameter resetAttr(RecipeItem<?> item){
attributes.remove(item, 0);
return this;
}
public EnvParameter clearInputs(){
inputs.clear();
return this;
}
public EnvParameter clearAttr(){
attributes.clear();
return this;
}
public EnvParameter clear() {
clearInputs();
clearAttr();
return this;
}
public EnvParameter applyFullRecipe(Recipe recipe, boolean fillOptional, boolean applyAttribute, float multiplier){
for (RecipeItemStack stack : recipe.materials.values()) {
if (!fillOptional && stack.optionalCons) continue;
if (!applyAttribute && stack.isAttribute) continue;
inputs.put(stack.item, stack.amount*multiplier);
}
return this;
}
public EnvParameter addPower(float power){ | package tmi.recipe;
public class EnvParameter {
private final ObjectFloatMap<RecipeItem<?>> inputs = new ObjectFloatMap<>();
private final ObjectFloatMap<RecipeItem<?>> attributes = new ObjectFloatMap<>();
public float getInputs(RecipeItem<?> b) {
return inputs.get(b, 0f);
}
public float getAttribute(RecipeItem<?> b) {
return attributes.get(b, 0f);
}
public EnvParameter add(RecipeItemStack item){
return add(item.item, item.amount, item.isAttribute);
}
public EnvParameter add(RecipeItem<?> item, float amount, boolean isAttribute){
if (isAttribute){
attributes.increment(item, 0, amount);
}
else inputs.increment(item, 0, amount);
return this;
}
public EnvParameter set(EnvParameter other){
other.attributes.each(e -> add(e.key, e.value, true));
other.inputs.each(e -> add(e.key, e.value, false));
return this;
}
public EnvParameter setInputs(EnvParameter other){
other.inputs.each(e -> add(e.key, e.value, false));
return this;
}
public EnvParameter setAttributes(EnvParameter other){
other.attributes.each(e -> add(e.key, e.value, true));
return this;
}
public EnvParameter resetInput(RecipeItem<?> item){
inputs.remove(item, 0);
return this;
}
public EnvParameter resetAttr(RecipeItem<?> item){
attributes.remove(item, 0);
return this;
}
public EnvParameter clearInputs(){
inputs.clear();
return this;
}
public EnvParameter clearAttr(){
attributes.clear();
return this;
}
public EnvParameter clear() {
clearInputs();
clearAttr();
return this;
}
public EnvParameter applyFullRecipe(Recipe recipe, boolean fillOptional, boolean applyAttribute, float multiplier){
for (RecipeItemStack stack : recipe.materials.values()) {
if (!fillOptional && stack.optionalCons) continue;
if (!applyAttribute && stack.isAttribute) continue;
inputs.put(stack.item, stack.amount*multiplier);
}
return this;
}
public EnvParameter addPower(float power){ | add(PowerMark.INSTANCE, power + inputs.get(PowerMark.INSTANCE, 0f), false); | 1 | 2023-11-05 11:39:21+00:00 | 2k |
dulaiduwang003/DeepSee | microservices/ts-drawing/src/main/java/com/cn/controller/SdController.java | [
{
"identifier": "SdTaskDto",
"path": "microservices/ts-drawing/src/main/java/com/cn/dto/SdTaskDto.java",
"snippet": "@Data\n@Accessors(chain = true)\n@SuppressWarnings(\"all\")\npublic class SdTaskDto {\n\n private String images;\n\n @NotBlank(message = \"提示词不能为空\")\n private String prompt;\n\n @NotNull(message = \"图片宽度不能为空\")\n private Long width;\n\n @NotNull(message = \"图片高度不能为空\")\n private Long height;\n\n @NotBlank(message = \"模型名称不能为空\")\n private String modelName;\n\n @NotNull(message = \"迭代次数不能为空\")\n private Integer steps;\n\n @NotBlank(message = \"采样方法不能为空\")\n private String sampler_index;\n\n @NotBlank(message = \"外挂模型不能为空\")\n private String sd_vae;\n\n private String negative_prompt;\n\n private String mask;\n\n private Double denoising_strength;\n\n\n}"
},
{
"identifier": "DrawingException",
"path": "microservices/ts-drawing/src/main/java/com/cn/exception/DrawingException.java",
"snippet": "@SuppressWarnings(\"all\")\n@Data\npublic class DrawingException extends RuntimeException {\n\n private String message;\n\n private Integer code;\n\n\n public DrawingException(final String message, final Integer code) {\n super(message);\n this.message = message;\n this.code = code;\n }\n\n public DrawingException(final String message) {\n super(message);\n this.message = message;\n this.code = 500;\n }\n}"
},
{
"identifier": "Result",
"path": "microservices/ts-api/src/main/java/com/cn/msg/Result.java",
"snippet": "@SuppressWarnings(\"all\")\npublic class Result extends LinkedHashMap<String, Object> implements Serializable {\n\n\n private static final long serialVersionUID = 1L;\n\n public static final int CODE_SUCCESS = 200;\n\n public static final int CODE_ERROR = 500;\n\n\n public Result() {\n }\n\n public Result(int code, String msg, Object data) {\n this.setCode(code);\n this.setMsg(msg);\n this.setData(data);\n }\n\n\n public Result(Map<String, ?> map) {\n this.setMap(map);\n }\n\n public Integer getCode() {\n return (Integer) this.get(\"code\");\n }\n\n public String getMsg() {\n return (String) this.get(\"msg\");\n }\n\n\n public Object getData() {\n return this.get(\"data\");\n }\n\n\n public Result setCode(int code) {\n this.put(\"code\", code);\n return this;\n }\n\n\n public Result setMsg(String msg) {\n this.put(\"msg\", msg);\n return this;\n }\n\n\n public Result setData(Object data) {\n this.put(\"data\", data);\n return this;\n }\n\n public Result set(String key, Object data) {\n this.put(key, data);\n return this;\n }\n\n\n public Result setMap(Map<String, ?> map) {\n Iterator var2 = map.keySet().iterator();\n\n while (var2.hasNext()) {\n String key = (String) var2.next();\n this.put(key, map.get(key));\n }\n\n return this;\n }\n\n\n\n public static Result ok() {\n return new Result(CODE_SUCCESS, \"操作成功\", (Object) null);\n }\n\n public static Result ok(String msg) {\n return new Result(CODE_SUCCESS, msg, (Object) null);\n }\n\n public static Result code(int code) {\n return new Result(code, (String) null, (Object) null);\n }\n\n public static Result data(Object data) {\n return new Result(CODE_SUCCESS, \"ok\", data);\n }\n\n public static Result error() {\n return new Result(CODE_ERROR, \"操作失败\", (Object) null);\n }\n\n public static Result error(final String msg, final Integer code) {\n return new Result(code, msg, (Object) null);\n }\n\n public static Result error(String msg) {\n return new Result(CODE_ERROR, msg, (Object) null);\n }\n\n public static Result error(String msg, int code) {\n return new Result(code, msg, (Object) null);\n }\n\n public static Result build(int code, String msg, Object data) {\n return new Result(code, msg, data);\n }\n\n\n public String toString() {\n return \"{\\\"code\\\": \" + this.getCode() + \", \\\"msg\\\": \" + this.transValue(this.getMsg()) + \", \\\"data\\\": \" + this.transValue(this.getData()) + \"}\";\n }\n\n\n private String transValue(Object value) {\n return value instanceof String ? \"\\\"\" + value + \"\\\"\" : String.valueOf(value);\n }\n}"
},
{
"identifier": "SdService",
"path": "microservices/ts-drawing/src/main/java/com/cn/service/SdService.java",
"snippet": "public interface SdService {\n\n\n String addSdDrawingTask(final SdTaskDto dto);\n\n\n /**\n * Gets sd param.\n *\n * @return the sd param\n */\n SdParamVo getSdParam();\n\n}"
}
] | import com.cn.dto.SdTaskDto;
import com.cn.exception.DrawingException;
import com.cn.msg.Result;
import com.cn.service.SdService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*; | 1,427 | package com.cn.controller;
@Slf4j
@RestController
@RequestMapping("/sd")
@RequiredArgsConstructor
public class SdController {
private final SdService sdService;
/**
* Gets sd param.
*
* @return the sd param
*/
@GetMapping(value = "/get/param", name = "get the list of SD drawing parameters", produces = MediaType.APPLICATION_JSON_VALUE) | package com.cn.controller;
@Slf4j
@RestController
@RequestMapping("/sd")
@RequiredArgsConstructor
public class SdController {
private final SdService sdService;
/**
* Gets sd param.
*
* @return the sd param
*/
@GetMapping(value = "/get/param", name = "get the list of SD drawing parameters", produces = MediaType.APPLICATION_JSON_VALUE) | public Result getSdParam() { | 2 | 2023-11-05 16:26:39+00:00 | 2k |
ewolff/microservice-spring | microservice-spring-demo/microservice-spring-invoicing/src/main/java/com/ewolff/microservice/invoicing/poller/InvoicePoller.java | [
{
"identifier": "Invoice",
"path": "microservice-spring-demo/microservice-spring-invoicing/src/main/java/com/ewolff/microservice/invoicing/Invoice.java",
"snippet": "@Entity\npublic class Invoice {\n\n\t@Id\n\tprivate long id;\n\n\t@Embedded\n\tprivate Customer customer;\n\n\tprivate Date updated;\n\n\t@Embedded\n\tprivate Address billingAddress = new Address();\n\n\t@OneToMany(cascade = CascadeType.ALL)\n\tprivate List<InvoiceLine> invoiceLine;\n\n\tpublic Invoice() {\n\t\tsuper();\n\t\tinvoiceLine = new ArrayList<InvoiceLine>();\n\t}\n\n\tpublic Invoice(long id, Customer customer, Date updated, Address billingAddress, List<InvoiceLine> invoiceLine) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.customer = customer;\n\t\tthis.updated = updated;\n\t\tthis.billingAddress = billingAddress;\n\t\tthis.invoiceLine = invoiceLine;\n\t}\n\n\tpublic Address getBillingAddress() {\n\t\treturn billingAddress;\n\t}\n\n\tpublic void setBillingAddress(Address billingAddress) {\n\t\tthis.billingAddress = billingAddress;\n\t}\n\n\tpublic void setId(long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic long getId() {\n\t\treturn id;\n\t}\n\n\tpublic Date getUpdated() {\n\t\treturn updated;\n\t}\n\n\tpublic void setUpdated(Date created) {\n\t\tthis.updated = created;\n\t}\n\n\tpublic Customer getCustomer() {\n\t\treturn customer;\n\t}\n\n\tpublic void setCustomer(Customer customer) {\n\t\tthis.customer = customer;\n\t}\n\n\tpublic List<InvoiceLine> getInvoiceLine() {\n\t\treturn invoiceLine;\n\t}\n\n\tpublic void setInvoiceLine(List<InvoiceLine> invoiceLine) {\n\t\tthis.invoiceLine = invoiceLine;\n\t}\n\n\t@Transient\n\tpublic void setOrderLine(List<InvoiceLine> orderLine) {\n\t\tthis.invoiceLine = orderLine;\n\t}\n\n\tpublic void addLine(int count, Item item) {\n\t\tthis.invoiceLine.add(new InvoiceLine(count, item));\n\t}\n\n\tpublic int getNumberOfLines() {\n\t\treturn invoiceLine.size();\n\t}\n\n\tpublic double totalAmount() {\n\t\treturn invoiceLine.stream().map((ol) -> ol.getCount() * ol.getItem().getPrice()).reduce(0.0,\n\t\t\t\t(d1, d2) -> d1 + d2);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((billingAddress == null) ? 0 : billingAddress.hashCode());\n\t\tresult = prime * result + ((customer == null) ? 0 : customer.hashCode());\n\t\tresult = prime * result + (int) (id ^ (id >>> 32));\n\t\tresult = prime * result + ((invoiceLine == null) ? 0 : invoiceLine.hashCode());\n\t\tresult = prime * result + ((updated == null) ? 0 : updated.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tInvoice other = (Invoice) obj;\n\t\tif (billingAddress == null) {\n\t\t\tif (other.billingAddress != null)\n\t\t\t\treturn false;\n\t\t} else if (!billingAddress.equals(other.billingAddress))\n\t\t\treturn false;\n\t\tif (customer == null) {\n\t\t\tif (other.customer != null)\n\t\t\t\treturn false;\n\t\t} else if (!customer.equals(other.customer))\n\t\t\treturn false;\n\t\tif (id != other.id)\n\t\t\treturn false;\n\t\tif (invoiceLine == null) {\n\t\t\tif (other.invoiceLine != null)\n\t\t\t\treturn false;\n\t\t} else if (!invoiceLine.equals(other.invoiceLine))\n\t\t\treturn false;\n\t\tif (updated == null) {\n\t\t\tif (other.updated != null)\n\t\t\t\treturn false;\n\t\t} else if (!updated.equals(other.updated))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Invoice [id=\" + id + \", customer=\" + customer + \", updated=\" + updated + \", billingAddress=\"\n\t\t\t\t+ billingAddress + \", invoiceLine=\" + invoiceLine + \"]\";\n\t}\n\n}"
},
{
"identifier": "InvoiceService",
"path": "microservice-spring-demo/microservice-spring-invoicing/src/main/java/com/ewolff/microservice/invoicing/InvoiceService.java",
"snippet": "public interface InvoiceService {\r\n\r\n\tvoid generateInvoice(Invoice invoice);\r\n\r\n}"
}
] | import java.time.ZonedDateTime;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import com.ewolff.microservice.invoicing.Invoice;
import com.ewolff.microservice.invoicing.InvoiceService;
import io.github.resilience4j.retry.annotation.Retry; | 1,357 | package com.ewolff.microservice.invoicing.poller;
@Component
public class InvoicePoller {
private final Logger log = LoggerFactory.getLogger(InvoicePoller.class);
private String url = "";
private RestTemplate restTemplate = null;
private ZonedDateTime lastModified = null;
private boolean pollingActivated;
| package com.ewolff.microservice.invoicing.poller;
@Component
public class InvoicePoller {
private final Logger log = LoggerFactory.getLogger(InvoicePoller.class);
private String url = "";
private RestTemplate restTemplate = null;
private ZonedDateTime lastModified = null;
private boolean pollingActivated;
| private InvoiceService invoiceService; | 1 | 2023-11-03 17:36:15+00:00 | 2k |
xsreality/spring-modulith-with-ddd | src/main/java/example/borrow/loan/application/LoanMapper.java | [
{
"identifier": "Book",
"path": "src/main/java/example/borrow/book/domain/Book.java",
"snippet": "@AggregateRoot\n@Entity\n@Getter\n@NoArgsConstructor\n@Table(name = \"borrow_books\", uniqueConstraints = @UniqueConstraint(columnNames = {\"barcode\"}))\npublic class Book {\n\n @Identity\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n private String title;\n\n @Embedded\n private Barcode inventoryNumber;\n\n private String isbn;\n\n @Enumerated(EnumType.STRING)\n private BookStatus status;\n\n @Version\n private Long version;\n\n @ValueObject\n public record Barcode(String barcode) {\n }\n\n public boolean available() {\n return BookStatus.AVAILABLE.equals(this.status);\n }\n\n public boolean onHold() {\n return BookStatus.ON_HOLD.equals(this.status);\n }\n\n public boolean issued() {\n return BookStatus.ISSUED.equals(this.status);\n }\n\n public Book(String title, Barcode inventoryNumber, String isbn) {\n this.title = title;\n this.inventoryNumber = inventoryNumber;\n this.isbn = isbn;\n this.status = BookStatus.AVAILABLE;\n }\n\n public Book markIssued() {\n if (issued()) {\n throw new IllegalStateException(\"Book is already issued!\");\n }\n this.status = BookStatus.ISSUED;\n return this;\n }\n\n public Book markOnHold() {\n if (onHold()) {\n throw new IllegalStateException(\"Book is already available!\");\n }\n this.status = BookStatus.ON_HOLD;\n return this;\n }\n\n public Book markAvailable() {\n if (available()) {\n throw new IllegalStateException(\"Book is already available!\");\n }\n this.status = BookStatus.AVAILABLE;\n return this;\n }\n\n @ValueObject\n public enum BookStatus {\n AVAILABLE, ON_HOLD, ISSUED\n }\n}"
},
{
"identifier": "Loan",
"path": "src/main/java/example/borrow/loan/domain/Loan.java",
"snippet": "@AggregateRoot\n@Entity\n@Getter\n@NoArgsConstructor\npublic class Loan {\n\n @Identity\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Embedded\n private Barcode bookBarcode;\n\n private Long patronId;\n\n private LocalDate dateOfCheckout;\n\n private LocalDate dateOfHold;\n\n private int holdDurationInDays;\n\n private int loanDurationInDays;\n\n private LocalDate dateOfCheckin;\n\n @Enumerated(EnumType.STRING)\n private LoanStatus status;\n\n @Version\n private Long version;\n\n Loan(String barcode, LocalDate dateOfHold, Long patronId) {\n this.bookBarcode = new Barcode(barcode);\n this.dateOfHold = dateOfHold;\n this.patronId = patronId;\n this.holdDurationInDays = 3;\n this.status = LoanStatus.HOLDING;\n }\n\n public static Loan of(String barcode, LocalDate dateOfHold, Long patronId) {\n return new Loan(barcode, dateOfHold, patronId);\n }\n\n public boolean isActive() {\n return LoanStatus.ACTIVE.equals(this.status);\n }\n\n public boolean isHolding() {\n return LoanStatus.HOLDING.equals(this.status);\n }\n\n public boolean isOverdue() {\n return LoanStatus.OVERDUE.equals(this.status);\n }\n\n public boolean isCompleted() {\n return LoanStatus.COMPLETED.equals(this.status);\n }\n\n public void complete(LocalDate dateOfCheckin) {\n if (isCompleted()) {\n throw new IllegalStateException(\"Loan is not active!\");\n }\n this.status = LoanStatus.COMPLETED;\n this.dateOfCheckin = dateOfCheckin;\n }\n\n public void activate(LocalDate dateOfCheckout) {\n if (!isHolding()) {\n throw new IllegalStateException(\"Loan is not holding!\");\n }\n this.loanDurationInDays = 14;\n this.dateOfCheckout = dateOfCheckout;\n this.status = LoanStatus.ACTIVE;\n }\n\n @ValueObject\n public enum LoanStatus {\n HOLDING, ACTIVE, OVERDUE, COMPLETED\n }\n}"
}
] | import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.MappingConstants;
import org.mapstruct.Named;
import org.mapstruct.ReportingPolicy;
import example.borrow.book.domain.Book;
import example.borrow.loan.domain.Loan; | 1,177 | package example.borrow.loan.application;
@Mapper(componentModel = MappingConstants.ComponentModel.SPRING, unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface LoanMapper {
@Mapping(source = "bookBarcode", target = "bookBarcode", qualifiedByName = "normalizeBarcode")
LoanDto toDto(Loan loan);
Loan toEntity(LoanDto loanDto);
@Named("normalizeBarcode") | package example.borrow.loan.application;
@Mapper(componentModel = MappingConstants.ComponentModel.SPRING, unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface LoanMapper {
@Mapping(source = "bookBarcode", target = "bookBarcode", qualifiedByName = "normalizeBarcode")
LoanDto toDto(Loan loan);
Loan toEntity(LoanDto loanDto);
@Named("normalizeBarcode") | static String normalizeBarcode(Book.Barcode barcode) { | 0 | 2023-11-03 22:21:01+00:00 | 2k |
373675032/xw-fast | xw-fast-crud/src/main/java/world/xuewei/fast/crud/query/QueryBody.java | [
{
"identifier": "BusinessRunTimeException",
"path": "xw-fast-core/src/main/java/world/xuewei/fast/core/exception/BusinessRunTimeException.java",
"snippet": "@Setter\n@Getter\npublic class BusinessRunTimeException extends RuntimeException {\n\n private static final long serialVersionUID = -4879677283847539655L;\n\n protected int code;\n\n protected String message;\n\n public BusinessRunTimeException(int code, String message) {\n super(message);\n this.code = code;\n this.message = message;\n }\n\n public BusinessRunTimeException(String message, Object... objects) {\n super(message);\n for (Object o : objects) {\n message = message.replaceFirst(\"\\\\{\\\\}\", o.toString());\n }\n this.message = message;\n }\n\n /**\n * 设置原因\n *\n * @param cause 原因\n */\n public BusinessRunTimeException setCause(Throwable cause) {\n this.initCause(cause);\n return this;\n }\n}"
},
{
"identifier": "VariableNameUtils",
"path": "xw-fast-core/src/main/java/world/xuewei/fast/core/util/VariableNameUtils.java",
"snippet": "public class VariableNameUtils {\n\n private static final Pattern linePattern = Pattern.compile(\"_(\\\\w)\");\n private static final Pattern humpPattern = Pattern.compile(\"[A-Z]\");\n\n /**\n * 下划线转驼峰\n */\n public static String lineToHump(String str) {\n str = str.toLowerCase();\n Matcher matcher = linePattern.matcher(str);\n StringBuffer sb = new StringBuffer();\n while (matcher.find()) {\n matcher.appendReplacement(sb, matcher.group(1).toUpperCase());\n }\n matcher.appendTail(sb);\n return sb.toString();\n }\n\n\n /**\n * 驼峰转下划线\n */\n public static String humpToLine(String str) {\n Matcher matcher = humpPattern.matcher(str);\n StringBuffer sb = new StringBuffer();\n while (matcher.find()) {\n matcher.appendReplacement(sb, \"_\" + matcher.group(0).toLowerCase());\n }\n matcher.appendTail(sb);\n return sb.toString();\n }\n}"
}
] | import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import world.xuewei.fast.core.exception.BusinessRunTimeException;
import world.xuewei.fast.core.util.VariableNameUtils;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors; | 1,005 | package world.xuewei.fast.crud.query;
/**
* 自定义查询体
*
* @author XUEW
* @since 2023/9/4 14:04
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class QueryBody<T> {
/**
* 关键词查询内容
*/
private String keyword;
/**
* 关键字查询字段
*/
private List<String> keywordFields;
/**
* 结果返回指定字段
*/
private List<String> includeFields;
/**
* 查询条件
*/
private List<QueryCondition> conditions;
/**
* 排序信息
*/
private List<QueryOrder> orderBy;
/**
* 分页信息
*/
private QueryPage pageBy;
/**
* 参数合法性检查
*/
public void check() {
if (ObjectUtil.isNotEmpty(keyword) && ObjectUtil.isEmpty(keywordFields)) {
throw new BusinessRunTimeException("关键词查询时必须指定 keywordFields,且必须指定为字符类型字段");
}
if (ObjectUtil.isNotEmpty(conditions)) {
conditions.forEach(QueryCondition::check);
}
if (ObjectUtil.isNotEmpty(orderBy)) {
orderBy.forEach(QueryOrder::check);
}
}
/**
* 构建 QueryWrapper
*
* @return QueryWrapper
*/
public QueryWrapper<T> buildWrapper() {
QueryWrapper<T> wrapper = new QueryWrapper<>();
// 关键词
if (ObjectUtil.isNotEmpty(keywordFields) && ObjectUtil.isNotEmpty(keyword)) {
wrapper.and(orWrapper -> {
for (String keywordField : keywordFields) { | package world.xuewei.fast.crud.query;
/**
* 自定义查询体
*
* @author XUEW
* @since 2023/9/4 14:04
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class QueryBody<T> {
/**
* 关键词查询内容
*/
private String keyword;
/**
* 关键字查询字段
*/
private List<String> keywordFields;
/**
* 结果返回指定字段
*/
private List<String> includeFields;
/**
* 查询条件
*/
private List<QueryCondition> conditions;
/**
* 排序信息
*/
private List<QueryOrder> orderBy;
/**
* 分页信息
*/
private QueryPage pageBy;
/**
* 参数合法性检查
*/
public void check() {
if (ObjectUtil.isNotEmpty(keyword) && ObjectUtil.isEmpty(keywordFields)) {
throw new BusinessRunTimeException("关键词查询时必须指定 keywordFields,且必须指定为字符类型字段");
}
if (ObjectUtil.isNotEmpty(conditions)) {
conditions.forEach(QueryCondition::check);
}
if (ObjectUtil.isNotEmpty(orderBy)) {
orderBy.forEach(QueryOrder::check);
}
}
/**
* 构建 QueryWrapper
*
* @return QueryWrapper
*/
public QueryWrapper<T> buildWrapper() {
QueryWrapper<T> wrapper = new QueryWrapper<>();
// 关键词
if (ObjectUtil.isNotEmpty(keywordFields) && ObjectUtil.isNotEmpty(keyword)) {
wrapper.and(orWrapper -> {
for (String keywordField : keywordFields) { | orWrapper.like(VariableNameUtils.humpToLine(keywordField), keyword).or(); | 1 | 2023-11-07 11:45:40+00:00 | 2k |
daominh-studio/quick-mem | app/src/main/java/com/daominh/quickmem/adapter/folder/FolderAdapter.java | [
{
"identifier": "Folder",
"path": "app/src/main/java/com/daominh/quickmem/data/model/Folder.java",
"snippet": "public class Folder {\n private String id;\n private String name;\n private String description;\n private String user_id;\n private String created_at;\n private String updated_at;\n\n public Folder() {\n }\n\n public Folder(String id, String name, String description, String user_id, String created_at, String updated_at) {\n this.id = id;\n this.name = name;\n this.description = description;\n this.user_id = user_id;\n this.created_at = created_at;\n this.updated_at = updated_at;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public String getUser_id() {\n return user_id;\n }\n\n public void setUser_id(String user_id) {\n this.user_id = user_id;\n }\n\n public String getCreated_at() {\n return created_at;\n }\n\n public void setCreated_at(String created_at) {\n this.created_at = created_at;\n }\n\n public String getUpdated_at() {\n return updated_at;\n }\n\n public void setUpdated_at(String updated_at) {\n this.updated_at = updated_at;\n }\n}"
},
{
"identifier": "UserSharePreferences",
"path": "app/src/main/java/com/daominh/quickmem/preferen/UserSharePreferences.java",
"snippet": "public class UserSharePreferences {\n\n //create variables\n public static final String KEY_LOGIN = \"login\";\n public static final String KEY_ID = \"id\";\n private static final String KEY_AVATAR = \"avatar\";\n private static final String KEY_USER_NAME = \"user_name\";\n private static final String KEY_ROLE = \"role_user\";\n private static final String KEY_STATUS = \"status\";\n private static final String KEY_EMAIL = \"email\";\n public static final String KEY_CLASS_ID = \"class_id\";\n\n private final SharedPreferences sharedPreferences;\n\n public UserSharePreferences(Context context) {\n sharedPreferences = context.getSharedPreferences(\"user\", Context.MODE_PRIVATE);\n }\n\n //set login\n public void setLogin(boolean login) {\n sharedPreferences.edit().putBoolean(KEY_LOGIN, login).apply();\n }\n\n //get login\n public boolean getLogin() {\n return sharedPreferences.getBoolean(KEY_LOGIN, false);\n }\n\n //set id\n public void setId(String id) {\n sharedPreferences.edit().putString(KEY_ID, id).apply();\n }\n\n //get id\n public String getId() {\n return sharedPreferences.getString(KEY_ID, \"\");\n }\n\n // get, set role user\n public void setRole(int role) {\n sharedPreferences.edit().putInt(KEY_ROLE, role).apply();\n }\n\n //get role user\n public int getRole() {\n return sharedPreferences.getInt(KEY_ROLE, -1);\n }\n\n //set,get status\n public void setStatus(int status) {\n sharedPreferences.edit().putInt(KEY_STATUS, status).apply();\n }\n\n //get status\n public int getStatus() {\n return sharedPreferences.getInt(KEY_STATUS, -1);\n }\n\n //set avatar\n public void setAvatar(String avatar) {\n sharedPreferences.edit().putString(KEY_AVATAR, avatar).apply();\n }\n\n //get avatar\n public String getAvatar() {\n return sharedPreferences.getString(KEY_AVATAR, \"\");\n }\n\n //set username\n public void setUserName(String userName) {\n sharedPreferences.edit().putString(KEY_USER_NAME, userName).apply();\n }\n\n //get username\n public String getUserName() {\n return sharedPreferences.getString(KEY_USER_NAME, \"\");\n }\n\n //set email\n public void setEmail(String email) {\n sharedPreferences.edit().putString(KEY_EMAIL, email).apply();\n }\n\n //get email\n public String getEmail() {\n return sharedPreferences.getString(KEY_EMAIL, \"\");\n }\n\n //set class id\n public void setClassId(String classId) {\n sharedPreferences.edit().putString(KEY_CLASS_ID, classId).apply();\n }\n\n //get class id\n public String getClassId() {\n return sharedPreferences.getString(KEY_CLASS_ID, \"\");\n }\n\n //remove class id\n public void removeClassId() {\n sharedPreferences.edit().remove(KEY_CLASS_ID).apply();\n }\n\n //set user\n public void saveUser(User user) {\n setId(user.getId());\n setUserName(user.getUsername());\n setEmail(user.getEmail());\n setAvatar(user.getAvatar());\n setRole(user.getRole());\n setStatus(user.getStatus());\n setLogin(true);\n }\n\n //clear\n public void clear() {\n sharedPreferences.edit().clear().apply();\n }\n}"
}
] | import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.daominh.quickmem.data.model.Folder;
import com.daominh.quickmem.databinding.ItemFolderBinding;
import com.daominh.quickmem.preferen.UserSharePreferences;
import com.daominh.quickmem.ui.activities.folder.ViewFolderActivity;
import com.squareup.picasso.Picasso;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList; | 1,529 | package com.daominh.quickmem.adapter.folder;
public class FolderAdapter extends RecyclerView.Adapter<FolderAdapter.FolderViewHolder> {
private final Context context;
private final ArrayList<Folder> folders;
public FolderAdapter(Context context, ArrayList<Folder> folders) {
this.context = context;
this.folders = folders;
}
@NonNull
@NotNull
@Override
public FolderAdapter.FolderViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
ItemFolderBinding binding = ItemFolderBinding.inflate(inflater, parent, false);
return new FolderViewHolder(binding.getRoot());
}
@Override
public void onBindViewHolder(@NonNull @NotNull FolderAdapter.FolderViewHolder holder, int position) {
Folder folder = folders.get(position); | package com.daominh.quickmem.adapter.folder;
public class FolderAdapter extends RecyclerView.Adapter<FolderAdapter.FolderViewHolder> {
private final Context context;
private final ArrayList<Folder> folders;
public FolderAdapter(Context context, ArrayList<Folder> folders) {
this.context = context;
this.folders = folders;
}
@NonNull
@NotNull
@Override
public FolderAdapter.FolderViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
ItemFolderBinding binding = ItemFolderBinding.inflate(inflater, parent, false);
return new FolderViewHolder(binding.getRoot());
}
@Override
public void onBindViewHolder(@NonNull @NotNull FolderAdapter.FolderViewHolder holder, int position) {
Folder folder = folders.get(position); | UserSharePreferences userSharePreferences = new UserSharePreferences(context); | 1 | 2023-11-07 16:56:39+00:00 | 2k |
walidbosso/SpringBoot_Football_Matches | src/main/java/spring/tp/services/EquipeService.java | [
{
"identifier": "Equipe",
"path": "src/main/java/spring/tp/entities/Equipe.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Entity\npublic class Equipe {\n\t@Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n\tLong id; \n\tString nom;\n\tString pays;\n\t \n\t@OneToMany(mappedBy = \"equipe1\")\n\t@JsonIgnore\n List<Matche> matchesAsEquipe1;\n\n @OneToMany(mappedBy = \"equipe2\")\n @JsonIgnore\n List<Matche> matchesAsEquipe2;\n \n\t@OneToMany(mappedBy = \"equipe\") \n\t@JsonIgnore //on recupere list de groups we ignore the students, because if we want to recupere a student it will recupere id nom et note et son groupe ( et groupe contient id nom and students, we ignore students)\n\tList<Joueur> joueurs; \n}"
},
{
"identifier": "Joueur",
"path": "src/main/java/spring/tp/entities/Joueur.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Entity\npublic class Joueur {\n\t@Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n\tLong id;\n\tString nom;\n\tString poste;\n\n\t@ManyToOne\n\tEquipe equipe; \n}"
},
{
"identifier": "Matche",
"path": "src/main/java/spring/tp/entities/Matche.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Entity\npublic class Matche {\n\t@Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n\tLong id;\n\t@Temporal(TemporalType.DATE)\n private Date dateMatch;\n\n private String hourMatch;\n\n @ManyToOne\n private Stade stade;\n\n @ManyToOne\n @JoinColumn(name = \"equipe1_id\")\n private Equipe equipe1;\n\n @ManyToOne\n @JoinColumn(name = \"equipe2_id\")\n private Equipe equipe2;\n\n @ManyToOne\n private Arbitre arbitre; \n}"
},
{
"identifier": "EquipeRepository",
"path": "src/main/java/spring/tp/repositories/EquipeRepository.java",
"snippet": "@Repository\npublic interface EquipeRepository extends JpaRepository<Equipe, Long> {\n\n\tList<Equipe> findByPaysIgnoreCase(String nom); \n\tEquipe findByNom(String nom); \n}"
},
{
"identifier": "JoueurRepository",
"path": "src/main/java/spring/tp/repositories/JoueurRepository.java",
"snippet": "@Repository\npublic interface JoueurRepository extends JpaRepository<spring.tp.entities.Joueur, Long> {\n\n\tList<Joueur> findByEquipe(Equipe a); \n\n}"
},
{
"identifier": "MatcheRepository",
"path": "src/main/java/spring/tp/repositories/MatcheRepository.java",
"snippet": "@Repository\npublic interface MatcheRepository extends JpaRepository<Matche, Long> {\n\tList<Matche> findByArbitre(Arbitre a); \n\tList<Matche> findByStade(Stade a);\n\tList<Matche> findByEquipe1(Equipe a); \n\tList<Matche> findByEquipe2(Equipe a); \n\tList<Matche> findByDateMatchEquals(Date a);\n\tList<Matche> findByDateMatchLessThan(Date a); \n\n\n}"
}
] | import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import jakarta.persistence.EntityNotFoundException;
import spring.tp.entities.Equipe;
import spring.tp.entities.Joueur;
import spring.tp.entities.Matche;
import spring.tp.repositories.EquipeRepository;
import spring.tp.repositories.JoueurRepository;
import spring.tp.repositories.MatcheRepository; | 842 | package spring.tp.services;
@Service
public class EquipeService {
@Autowired
EquipeRepository er;
@Autowired | package spring.tp.services;
@Service
public class EquipeService {
@Autowired
EquipeRepository er;
@Autowired | JoueurRepository jr; | 4 | 2023-11-07 21:46:09+00:00 | 2k |
FRCTeam2910/2023CompetitionRobot-Public | src/main/java/org/frcteam2910/c2023/subsystems/drivetrain/DrivetrainSubsystem.java | [
{
"identifier": "DrivetrainConfiguration",
"path": "src/main/java/org/frcteam2910/c2023/config/DrivetrainConfiguration.java",
"snippet": "public class DrivetrainConfiguration {\n public double[] swerveModuleOffsets;\n public int mountingAngle;\n public double error;\n public PIDController xController = new PIDController(0, 0, 0);\n public PIDController yController = new PIDController(0, 0, 0);\n public PIDController rotationController = new PIDController(0, 0, 0);\n}"
},
{
"identifier": "VisionSubsystem",
"path": "src/main/java/org/frcteam2910/c2023/subsystems/vision/VisionSubsystem.java",
"snippet": "public class VisionSubsystem extends SubsystemBase {\n private static final double LOWEST_DISTANCE = Units.feetToMeters(10.0);\n\n private final VisionIO[] cameras;\n private final VisionIOInputsAutoLogged[] inputs;\n\n private final List<VisionSubsystem.PoseAndTimestamp> results = new ArrayList<>();\n\n private int acceptableTagID;\n private boolean useSingleTag = false;\n\n /**\n * Initializes cameras and input loggers\n *\n * @param cameras Array of cameras being used\n */\n public VisionSubsystem(VisionIO[] cameras) {\n this.cameras = cameras;\n inputs = new VisionIOInputsAutoLogged[cameras.length];\n\n for (int i = 0; i < cameras.length; i++) {\n inputs[i] = new VisionIOInputsAutoLogged();\n }\n }\n\n @Override\n public void periodic() {\n Logger.getInstance().recordOutput(\"useSingleTag\", useSingleTag);\n\n // clear results from last periodic\n results.clear();\n\n for (int i = 0; i < inputs.length; i++) {\n // update and process new inputs\n cameras[i].updateInputs(inputs[i]);\n Logger.getInstance().processInputs(\"Vision/\" + cameras[i].getName() + \"/Inputs\", inputs[i]);\n\n if (inputs[i].hasTarget\n && inputs[i].isNew\n && !DriverStation.isAutonomous()\n && inputs[i].maxDistance < LOWEST_DISTANCE) {\n if (useSingleTag) {\n if (inputs[i].singleIDUsed == acceptableTagID) {\n processVision(i);\n }\n } else {\n processVision(i);\n }\n }\n }\n\n Logger.getInstance().recordOutput(\"Vision/ResultCount\", results.size());\n }\n\n public void processVision(int cameraNum) {\n // create a new pose based off the new inputs\n Pose2d currentPose =\n new Pose2d(inputs[cameraNum].x, inputs[cameraNum].y, new Rotation2d(inputs[cameraNum].rotation));\n Logger.getInstance().recordOutput(cameras[cameraNum].getName() + \" pose\", currentPose);\n\n // add the new pose to a list\n results.add(new PoseAndTimestamp(currentPose, inputs[cameraNum].timestamp));\n }\n\n /**\n * Returns the last recorded pose\n */\n public List<VisionSubsystem.PoseAndTimestamp> getVisionOdometry() {\n return results;\n }\n\n /**\n * Inner class to record a pose and its timestamp\n */\n public static class PoseAndTimestamp {\n Pose2d pose;\n double timestamp;\n\n public PoseAndTimestamp(Pose2d pose, double timestamp) {\n this.pose = pose;\n this.timestamp = timestamp;\n }\n\n public Pose2d getPose() {\n return pose;\n }\n\n public double getTimestamp() {\n return timestamp;\n }\n }\n\n public void setUseSingleTag(boolean useSingleTag) {\n setUseSingleTag(useSingleTag, 0);\n }\n\n public void setUseSingleTag(boolean useSingleTag, int acceptableTagID) {\n this.useSingleTag = useSingleTag;\n this.acceptableTagID = acceptableTagID;\n }\n\n public void setReferencePose(Pose2d pose) {\n for (VisionIO io : cameras) {\n io.setReferencePose(pose);\n }\n }\n\n public double getMinDistance(int camera) {\n return inputs[camera].minDistance;\n }\n}"
}
] | import java.util.ArrayList;
import java.util.Arrays;
import com.ctre.phoenixpro.BaseStatusSignalValue;
import com.ctre.phoenixpro.StatusSignalValue;
import com.ctre.phoenixpro.Utils;
import com.pathplanner.lib.controllers.PPHolonomicDriveController;
import edu.wpi.first.math.VecBuilder;
import edu.wpi.first.math.controller.PIDController;
import edu.wpi.first.math.estimator.SwerveDrivePoseEstimator;
import edu.wpi.first.math.filter.LinearFilter;
import edu.wpi.first.math.geometry.Pose2d;
import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.math.geometry.Translation2d;
import edu.wpi.first.math.geometry.Twist2d;
import edu.wpi.first.math.kinematics.*;
import edu.wpi.first.math.util.Units;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import org.frcteam2910.c2023.config.DrivetrainConfiguration;
import org.frcteam2910.c2023.subsystems.vision.VisionSubsystem;
import org.littletonrobotics.junction.Logger; | 1,470 | package org.frcteam2910.c2023.subsystems.drivetrain;
/**
* Coordinator for the drivetrain. Speaks to the Gyro and the Swerve Modules
*/
public class DrivetrainSubsystem extends SubsystemBase {
/**
* Horizontal distance between the module centers
*/
private static final double WHEELBASE_METERS = Units.inchesToMeters(22.75);
/**
* Vertical distance between the module centers
*/
private static final double TRACK_METERS = Units.inchesToMeters(20.75);
private static final double ESTIMATION_COEFFICIENT = 0.025;
/**
* Max transitional velocity of the drivetrain
*/
private final double maxVelocityMetersPerSec;
/**
* Max angular velocity of the drivetrain
*/
private final double maxAngularVelocityRadPerSec;
/**
* Gyro IO interface. Used to update gyro values within the IO inner class
*/
private final GyroIO gyroIO;
| package org.frcteam2910.c2023.subsystems.drivetrain;
/**
* Coordinator for the drivetrain. Speaks to the Gyro and the Swerve Modules
*/
public class DrivetrainSubsystem extends SubsystemBase {
/**
* Horizontal distance between the module centers
*/
private static final double WHEELBASE_METERS = Units.inchesToMeters(22.75);
/**
* Vertical distance between the module centers
*/
private static final double TRACK_METERS = Units.inchesToMeters(20.75);
private static final double ESTIMATION_COEFFICIENT = 0.025;
/**
* Max transitional velocity of the drivetrain
*/
private final double maxVelocityMetersPerSec;
/**
* Max angular velocity of the drivetrain
*/
private final double maxAngularVelocityRadPerSec;
/**
* Gyro IO interface. Used to update gyro values within the IO inner class
*/
private final GyroIO gyroIO;
| private final VisionSubsystem vision; | 1 | 2023-11-03 02:12:12+00:00 | 2k |
YunaBraska/type-map | src/main/java/berlin/yuna/typemap/logic/JsonEncoder.java | [
{
"identifier": "arrayOf",
"path": "src/main/java/berlin/yuna/typemap/logic/TypeConverter.java",
"snippet": "public static <E> E[] arrayOf(final Object object, final E[] typeIndicator, final Class<E> componentType) {\n ArrayList<E> result = collectionOf(object, ArrayList::new, componentType);\n result = result == null ? new ArrayList<>() : result;\n return result.toArray(Arrays.copyOf(typeIndicator, result.size()));\n}"
},
{
"identifier": "convertObj",
"path": "src/main/java/berlin/yuna/typemap/logic/TypeConverter.java",
"snippet": "@SuppressWarnings({\"rawtypes\", \"unchecked\"})\npublic static <T> T convertObj(final Object value, final Class<T> targetType) {\n if (value == null) return null;\n if (targetType.isInstance(value)) {\n return targetType.cast(value);\n }\n\n // Handle non-empty arrays, collections, map\n final Object firstValue = getFirstItem(value);\n if (firstValue != null) {\n return convertObj(firstValue, targetType);\n }\n\n // Enums\n if (targetType.isEnum()) {\n return (T) enumOf(String.valueOf(value), (Class<Enum>) targetType);\n }\n\n final Class<?> sourceType = value.getClass();\n final Map<Class<?>, FunctionOrNull> conversions = TYPE_CONVERSIONS.getOrDefault(targetType, Collections.emptyMap());\n\n // First try to find exact match\n final FunctionOrNull exactMatch = conversions.get(sourceType);\n if (exactMatch != null) {\n return targetType.cast(exactMatch.apply(value));\n }\n\n // Fallback to more general converters\n for (final Map.Entry<Class<?>, FunctionOrNull> entry : conversions.entrySet()) {\n if (entry.getKey().isAssignableFrom(sourceType)) {\n return targetType.cast(entry.getValue().apply(value));\n }\n }\n\n // Fallback to string convert\n if (!String.class.equals(sourceType)) {\n return convertObj(String.valueOf(value), targetType);\n }\n return null;\n}"
}
] | import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.function.IntFunction;
import java.util.stream.Collectors;
import static berlin.yuna.typemap.logic.TypeConverter.arrayOf;
import static berlin.yuna.typemap.logic.TypeConverter.convertObj; | 1,533 | package berlin.yuna.typemap.logic;
public class JsonEncoder {
@SuppressWarnings({"java:S2386"})
public static final Map<Character, String> JSON_ESCAPE_SEQUENCES = new HashMap<>();
@SuppressWarnings({"java:S2386"})
public static final Map<String, String> JSON_UNESCAPE_SEQUENCES = new HashMap<>();
static {
JSON_ESCAPE_SEQUENCES.put('"', "\\\"");
JSON_ESCAPE_SEQUENCES.put('\\', "\\\\");
JSON_ESCAPE_SEQUENCES.put('\b', "\\b");
JSON_ESCAPE_SEQUENCES.put('\f', "\\f");
JSON_ESCAPE_SEQUENCES.put('\n', "\\n");
JSON_ESCAPE_SEQUENCES.put('\r', "\\r");
JSON_ESCAPE_SEQUENCES.put('\t', "\\t");
JSON_ESCAPE_SEQUENCES.forEach((key, value) -> JSON_UNESCAPE_SEQUENCES.put(value, key.toString()));
}
/**
* Converts any object to its JSON representation.
* This method dispatches the conversion task based on the type of the object.
* It handles Maps, Collections, Arrays (both primitive and object types),
* and other objects. If the object is null, it returns an empty JSON object ({}).
* Standalone objects are converted to JSON strings and wrapped in curly braces,
* making them single-property JSON objects.
*
* @param object The object to be converted to JSON.
* @return A JSON representation of the object as a String.
* If the object is null, returns "{}".
*/
public static String toJson(final Object object) {
if (object == null) {
return "{}";
} else if (object instanceof Map) {
return jsonOf((Map<?, ?>) object);
} else if (object instanceof Collection) {
return jsonOf((Collection<?>) object);
} else if (object.getClass().isArray()) {
return jsonOfArray(object, Object[]::new, Object.class);
} else {
return "{" + jsonify(object) + "}";
}
}
/**
* Escapes a String for JSON.
* This method replaces special characters in a String with their corresponding JSON escape sequences.
*
* @param str The string to be escaped for JSON.
* @return The escaped JSON string.
*/
public static String escapeJsonValue(final String str) {
return str == null ? null : str.chars()
.mapToObj(c -> escapeJson((char) c))
.collect(Collectors.joining());
}
/**
* Escapes a character for JSON.
* This method returns the JSON escape sequence for a given character, if necessary.
*
* @param c The character to be escaped for JSON.
* @return The escaped JSON character as a String.
*/
public static String escapeJson(final char c) {
return JSON_ESCAPE_SEQUENCES.getOrDefault(c, (c < 32 || c >= 127) ? String.format("\\u%04x", (int) c) : String.valueOf(c));
}
/**
* Unescapes a JSON string by replacing JSON escape sequences with their corresponding characters.
* <p>
* This method iterates through a predefined set of JSON escape sequences (like \" for double quotes,
* \\ for backslash, \n for newline, etc.) and replaces them in the input string with the actual characters
* they represent. The method is designed to process a JSON-encoded string and return a version with
* standard characters, making it suitable for further processing or display.
* <p>
* Note: This method assumes that the input string is a valid JSON string with correct escape sequences.
* It does not perform JSON validation.
*
* @param str The JSON string with escape sequences to be unescaped.
* @return The unescaped version of the JSON string.
*/
public static String unescapeJson(final String str) {
String result = str;
for (final Map.Entry<String, String> entry : JSON_UNESCAPE_SEQUENCES.entrySet()) {
result = result.replace(entry.getKey(), entry.getValue());
}
return result;
}
private static String jsonOf(final Map<?, ?> map) {
return map.entrySet().stream()
.map(entry -> jsonify(entry.getKey()) + ":" + jsonify(entry.getValue()))
.collect(Collectors.joining(",", "{", "}"));
}
private static String jsonOf(final Collection<?> collection) {
return collection.stream()
.map(JsonEncoder::jsonify)
.collect(Collectors.joining(",", "[", "]"));
}
@SuppressWarnings("SameParameterValue")
private static <E> String jsonOfArray(final Object object, final IntFunction<E[]> generator, final Class<E> componentType) { | package berlin.yuna.typemap.logic;
public class JsonEncoder {
@SuppressWarnings({"java:S2386"})
public static final Map<Character, String> JSON_ESCAPE_SEQUENCES = new HashMap<>();
@SuppressWarnings({"java:S2386"})
public static final Map<String, String> JSON_UNESCAPE_SEQUENCES = new HashMap<>();
static {
JSON_ESCAPE_SEQUENCES.put('"', "\\\"");
JSON_ESCAPE_SEQUENCES.put('\\', "\\\\");
JSON_ESCAPE_SEQUENCES.put('\b', "\\b");
JSON_ESCAPE_SEQUENCES.put('\f', "\\f");
JSON_ESCAPE_SEQUENCES.put('\n', "\\n");
JSON_ESCAPE_SEQUENCES.put('\r', "\\r");
JSON_ESCAPE_SEQUENCES.put('\t', "\\t");
JSON_ESCAPE_SEQUENCES.forEach((key, value) -> JSON_UNESCAPE_SEQUENCES.put(value, key.toString()));
}
/**
* Converts any object to its JSON representation.
* This method dispatches the conversion task based on the type of the object.
* It handles Maps, Collections, Arrays (both primitive and object types),
* and other objects. If the object is null, it returns an empty JSON object ({}).
* Standalone objects are converted to JSON strings and wrapped in curly braces,
* making them single-property JSON objects.
*
* @param object The object to be converted to JSON.
* @return A JSON representation of the object as a String.
* If the object is null, returns "{}".
*/
public static String toJson(final Object object) {
if (object == null) {
return "{}";
} else if (object instanceof Map) {
return jsonOf((Map<?, ?>) object);
} else if (object instanceof Collection) {
return jsonOf((Collection<?>) object);
} else if (object.getClass().isArray()) {
return jsonOfArray(object, Object[]::new, Object.class);
} else {
return "{" + jsonify(object) + "}";
}
}
/**
* Escapes a String for JSON.
* This method replaces special characters in a String with their corresponding JSON escape sequences.
*
* @param str The string to be escaped for JSON.
* @return The escaped JSON string.
*/
public static String escapeJsonValue(final String str) {
return str == null ? null : str.chars()
.mapToObj(c -> escapeJson((char) c))
.collect(Collectors.joining());
}
/**
* Escapes a character for JSON.
* This method returns the JSON escape sequence for a given character, if necessary.
*
* @param c The character to be escaped for JSON.
* @return The escaped JSON character as a String.
*/
public static String escapeJson(final char c) {
return JSON_ESCAPE_SEQUENCES.getOrDefault(c, (c < 32 || c >= 127) ? String.format("\\u%04x", (int) c) : String.valueOf(c));
}
/**
* Unescapes a JSON string by replacing JSON escape sequences with their corresponding characters.
* <p>
* This method iterates through a predefined set of JSON escape sequences (like \" for double quotes,
* \\ for backslash, \n for newline, etc.) and replaces them in the input string with the actual characters
* they represent. The method is designed to process a JSON-encoded string and return a version with
* standard characters, making it suitable for further processing or display.
* <p>
* Note: This method assumes that the input string is a valid JSON string with correct escape sequences.
* It does not perform JSON validation.
*
* @param str The JSON string with escape sequences to be unescaped.
* @return The unescaped version of the JSON string.
*/
public static String unescapeJson(final String str) {
String result = str;
for (final Map.Entry<String, String> entry : JSON_UNESCAPE_SEQUENCES.entrySet()) {
result = result.replace(entry.getKey(), entry.getValue());
}
return result;
}
private static String jsonOf(final Map<?, ?> map) {
return map.entrySet().stream()
.map(entry -> jsonify(entry.getKey()) + ":" + jsonify(entry.getValue()))
.collect(Collectors.joining(",", "{", "}"));
}
private static String jsonOf(final Collection<?> collection) {
return collection.stream()
.map(JsonEncoder::jsonify)
.collect(Collectors.joining(",", "[", "]"));
}
@SuppressWarnings("SameParameterValue")
private static <E> String jsonOfArray(final Object object, final IntFunction<E[]> generator, final Class<E> componentType) { | return object.getClass().isArray() ? Arrays.stream(arrayOf(object, generator, componentType)) | 0 | 2023-11-09 14:40:13+00:00 | 2k |
jlcorcuera/unipi-dsmt-2023-2024 | lab04/src/main/java/it/unipi/dsmt/jakartaee/lab04/servlets/BeerSearchServlet.java | [
{
"identifier": "BeersDAO",
"path": "lab04/src/main/java/it/unipi/dsmt/jakartaee/lab04/dao/BeersDAO.java",
"snippet": "public class BeersDAO {\n\n private static List<Beer> beerList = new ArrayList<Beer>();\n\n public static void init() {\n try {\n String beersJSONFile = \"data/beers.json\";\n ClassLoader classLoader = BeersDAO.class.getClassLoader();\n URL resource = classLoader.getResource(beersJSONFile);\n ObjectMapper objectMapper = new ObjectMapper();\n JsonNode jsonNode = objectMapper.readTree(resource);\n\n JsonNode searchResultNode = jsonNode.get(\"search_results\");\n Iterator<JsonNode> iterator = searchResultNode.iterator();\n while (iterator.hasNext()) {\n JsonNode beerJSON = iterator.next();\n Beer beer = new Beer();\n beer.setId(UUID.randomUUID().toString());\n beer.setName(beerJSON.get(\"title\").asText());\n beer.setAsin(beerJSON.get(\"asin\").asText());\n beer.setLink(beerJSON.get(\"link\").asText());\n beer.setImage(beerJSON.get(\"image\").asText());\n beer.setRating(beerJSON.get(\"rating\").asDouble());\n beer.setRatingsTotal(beerJSON.get(\"ratings_total\").asDouble());\n beerList.add(beer);\n }\n System.out.println(\"Loaded \" + beerList.size() + \" beers.\");\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n public static void create(BeerDTO beerDTO){\n Beer beer = new Beer();\n beer.setId(UUID.randomUUID().toString());\n beer.setName(beerDTO.getName());\n beer.setImage(beerDTO.getImageUrl());\n beer.setRating(beerDTO.getRating());\n beerList.add(beer);\n }\n public static List<BeerDTO> search(String keyword){\n return beerList.stream()\n .filter(beer -> beer.getName().toLowerCase().contains(keyword.toLowerCase()))\n .map(beer -> new BeerDTO(beer.getId(), beer.getName(), beer.getLink(), beer.getImage(), beer.getRating()))\n .collect(Collectors.toList());\n }\n\n}"
},
{
"identifier": "BeerDTO",
"path": "lab04/src/main/java/it/unipi/dsmt/jakartaee/lab04/dto/BeerDTO.java",
"snippet": "public class BeerDTO {\n private String id;\n private String name;\n private String link;\n private String imageUrl;\n private Double rating;\n private Integer quantity;\n public BeerDTO(String id, String name, Integer quantity) {\n this.id = id;\n this.name = name;\n this.quantity = quantity;\n }\n public BeerDTO(String name, String imageUrl, Double rating) {\n this.name = name;\n this.imageUrl = imageUrl;\n this.rating = rating;\n }\n public BeerDTO(String id, String name, String link, String imageUrl, Double rating) {\n this.id = id;\n this.name = name;\n this.link = link;\n this.imageUrl = imageUrl;\n this.rating = rating;\n }\n public String getId() {\n return id;\n }\n public void setId(String id) {\n this.id = id;\n }\n public Integer getQuantity() {\n return quantity;\n }\n\n public void setQuantity(Integer quantity) {\n this.quantity = quantity;\n }\n\n public Double getRating() {\n return rating;\n }\n\n public void setRating(Double rating) {\n this.rating = rating;\n }\n\n public String getImageUrl() {\n return imageUrl;\n }\n\n public void setImageUrl(String imageUrl) {\n this.imageUrl = imageUrl;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getLink() {\n return link;\n }\n\n public void setLink(String link) {\n this.link = link;\n }\n}"
}
] | import it.unipi.dsmt.jakartaee.lab04.dao.BeersDAO;
import it.unipi.dsmt.jakartaee.lab04.dto.BeerDTO;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List; | 1,112 | package it.unipi.dsmt.jakartaee.lab04.servlets;
@WebServlet(name = "BeerSearchServlet", value = "/BeerSearchServlet")
public class BeerSearchServlet extends HttpServlet {
private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String searchFilter = request.getParameter("search") != null ? request.getParameter("search") : ""; | package it.unipi.dsmt.jakartaee.lab04.servlets;
@WebServlet(name = "BeerSearchServlet", value = "/BeerSearchServlet")
public class BeerSearchServlet extends HttpServlet {
private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String searchFilter = request.getParameter("search") != null ? request.getParameter("search") : ""; | List<BeerDTO> beerDTOList = BeersDAO.search(searchFilter); | 1 | 2023-11-06 09:06:10+00:00 | 2k |
estkme-group/InfiLPA | core/src/main/java/com/infineon/esim/lpa/core/es9plus/HttpsClient.java | [
{
"identifier": "HttpResponse",
"path": "core/src/main/java/com/infineon/esim/lpa/core/es9plus/messages/HttpResponse.java",
"snippet": "public class HttpResponse {\n private String content;\n private int statusCode;\n\n public String getContent() {\n\n return content;\n }\n\n public void setContent(String content) {\n\n this.content = content;\n }\n\n public int getStatusCode() {\n\n return statusCode;\n }\n\n public void setStatusCode(int statusCode) {\n\n this.statusCode = statusCode;\n }\n}"
},
{
"identifier": "IO",
"path": "util/src/main/java/com/infineon/esim/util/IO.java",
"snippet": "public class IO {\n\n public static String readStringFormInputStream(InputStream inputStream, Charset charset) throws IOException {\n ByteArrayOutputStream result = new ByteArrayOutputStream();\n byte[] buffer = new byte[1024];\n\n for (int length; (length = inputStream.read(buffer)) != -1; ) {\n result.write(buffer, 0, length);\n }\n // StandardCharsets.UTF_8.name() > JDK 7\n return result.toString(charset.toString());\n }\n}"
},
{
"identifier": "Log",
"path": "app/src/test/java/com/infineon/esim/util/Log.java",
"snippet": "final public class Log {\n\n // Ref:\n // https://stackoverflow.com/questions/8355632/how-do-you-usually-tag-log-entries-android\n public static String getFileLineNumber() {\n String info = \"\";\n final StackTraceElement[] ste = Thread.currentThread().getStackTrace();\n for (int i = 0; i < ste.length; i++) {\n if (ste[i].getMethodName().equals(\"getFileLineNumber\")) {\n info = \"(\"+ste[i + 1].getFileName() + \":\" + ste[i + 1].getLineNumber()+\")\";\n }\n }\n return info;\n }\n\n public static void verbose(final String tag, final String msg) {\n System.out.println(\"V - \" + tag + \": \" + msg);\n }\n\n public static void debug(final String tag, final String msg) {\n System.out.println(\"D - \" + tag + \": \" + msg);\n }\n\n public static void info(final String tag, final String msg) {\n System.out.println(\"I- \" + tag + \": \" + msg);\n }\n\n public static void error(final String msg) {\n System.out.println(\"E- \" + msg);\n }\n\n public static void error(final String tag, final String msg) {\n System.out.println(\"E- \" + tag + \": \" + msg);\n }\n\n public static void error(final String tag, final String msg, final Throwable error) {\n System.out.println(\"E- \" + tag + \": \" + msg);\n error.printStackTrace();\n }\n}"
},
{
"identifier": "Strings",
"path": "util/src/main/java/com/infineon/esim/util/Strings.java",
"snippet": "public class Strings {\n private static final String TAG = Strings.class.getName();\n\n\n public static List<String> splitByLength(String input, int partLength) {\n List<String> output = new ArrayList<>();\n\n for(int i = 0; i < input.length(); i += partLength) {\n output.add(input.substring(i, Math.min(i+partLength,input.length())));\n }\n\n return output;\n }\n\n public static String replaceRegion(String input, String replace, int index) {\n StringBuilder stringBuffer = new StringBuilder(input);\n\n if(input.length() > index) {\n int end = Math.min(input.length(), index + replace.length());\n int replaceLength = Math.min(replace.length(), end - index);\n stringBuffer.replace(index, end, replace.substring(0, replaceLength));\n return stringBuffer.toString();\n } else {\n return input;\n }\n }\n\n public static boolean isNotBlankOrEmpty(String input) {\n if(input != null) {\n return !input.trim().isEmpty();\n } else {\n return false;\n }\n }\n}"
}
] | import java.io.OutputStreamWriter;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import javax.net.ssl.HttpsURLConnection;
import com.infineon.esim.lpa.core.es9plus.messages.HttpResponse;
import com.infineon.esim.util.IO;
import com.infineon.esim.util.Log;
import com.infineon.esim.util.Strings;
import java.io.BufferedWriter;
import java.io.OutputStream; | 1,469 | /*
* THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON
* TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR,
* STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
* SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
*
* THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES
* RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER
* REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR
* THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME.
*
* INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR
* CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR
* ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR
* PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE
* DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION
* WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR
* PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON
* WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE.
*
* (C)Copyright INFINEON TECHNOLOGIES All rights reserved
*/
package com.infineon.esim.lpa.core.es9plus;
public class HttpsClient {
private static final String TAG = HttpsClient.class.getName();
private final String gsmaVersion; // e.g. 2.2.0
private final int connectionTimeout; // e.g. 600000
private final int readTimeout; // e.g. 600000
public HttpsClient() {
this.gsmaVersion = "2.2.0";
this.connectionTimeout = 600000;
this.readTimeout = 600000;
}
| /*
* THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON
* TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR,
* STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
* SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
*
* THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES
* RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER
* REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR
* THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME.
*
* INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR
* CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR
* ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR
* PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE
* DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION
* WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR
* PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON
* WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE.
*
* (C)Copyright INFINEON TECHNOLOGIES All rights reserved
*/
package com.infineon.esim.lpa.core.es9plus;
public class HttpsClient {
private static final String TAG = HttpsClient.class.getName();
private final String gsmaVersion; // e.g. 2.2.0
private final int connectionTimeout; // e.g. 600000
private final int readTimeout; // e.g. 600000
public HttpsClient() {
this.gsmaVersion = "2.2.0";
this.connectionTimeout = 600000;
this.readTimeout = 600000;
}
| public HttpResponse sendRequest( | 0 | 2023-11-06 02:41:13+00:00 | 2k |
Teleight/TeleightBots | src/main/java/org/teleight/teleightbots/event/bot/group/BotLeftGroupEvent.java | [
{
"identifier": "Bot",
"path": "src/main/java/org/teleight/teleightbots/bot/Bot.java",
"snippet": "public class Bot implements TelegramBot {\n\n private final String token;\n private final String username;\n\n //Settings\n private final BotSettings botSettings;\n\n //Updates\n private final UpdateProcessor updateProcessor;\n\n //Scheduler\n private final Scheduler scheduler = Scheduler.newScheduler();\n\n //Events\n private final EventManager eventManager = new EventManagerImpl();\n\n //Menus\n private final MenuManager menuManager = new MenuManagerImpl();\n\n //Commands\n private final CommandManager commandManager = new CommandManagerImpl(this);\n\n //Conversations\n private final ConversationManager conversationManager = new ConversationManagerImpl(this);\n\n //Extensions\n private final ExtensionManager extensionManager = new ExtensionManagerImpl(this);\n\n public Bot(String token, String username, UpdateProcessor updateProcessor, BotSettings botSettings) {\n this.token = token;\n this.username = username;\n this.botSettings = botSettings;\n this.updateProcessor = updateProcessor;\n }\n\n @Override\n public @NotNull String getBotToken() {\n return token;\n }\n\n @Override\n public @NotNull String getBotUsername() {\n return username;\n }\n\n @Override\n public @NotNull Scheduler getScheduler() {\n return scheduler;\n }\n\n @Override\n public @NotNull UpdateProcessor getUpdateProcessor() {\n return updateProcessor;\n }\n\n @Override\n public @NotNull BotSettings getBotSettings() {\n return botSettings;\n }\n\n @Override\n public @NotNull EventManager getEventManager() {\n return eventManager;\n }\n\n @Override\n public @NotNull MenuManager getMenuManager() {\n return menuManager;\n }\n\n @Override\n public @NotNull Menu createMenu(@Nullable String name, Menu.@NotNull Builder builder) {\n final MenuBuilder.MenuBuilderImpl menuBuilder = new MenuBuilder.MenuBuilderImpl();\n final Menu rootMenu = menuBuilder.createMenu(name);\n builder.create(menuBuilder, rootMenu);\n\n for (final MenuImpl subMenu : menuBuilder.getAllMenus()) {\n subMenu.createKeyboard();\n\n menuManager.registerMenu(subMenu);\n }\n\n return rootMenu;\n }\n\n @Override\n public @NotNull CommandManager getCommandManager() {\n return commandManager;\n }\n\n @Override\n public @NotNull ConversationManager getConversationManager() {\n return conversationManager;\n }\n\n @Override\n public @NotNull ExtensionManager getExtensionManager() {\n return extensionManager;\n }\n\n @Override\n public void connect() {\n extensionManager.start();\n updateProcessor.start();\n }\n\n public void close() {\n try{\n extensionManager.shutdown();\n } catch (Exception e) {\n TeleightBots.getExceptionManager().handleException(e);\n }\n\n try {\n scheduler.close();\n } catch (Exception e) {\n TeleightBots.getExceptionManager().handleException(e);\n }\n\n try {\n updateProcessor.shutdown();\n } catch (Exception e) {\n TeleightBots.getExceptionManager().handleException(e);\n }\n }\n\n @Override\n public <R> @NotNull CompletableFuture<R> execute(@NotNull ApiMethod<R> method) {\n final CompletableFuture<String> responseFuture = updateProcessor.executeMethod(method);\n return responseFuture.thenApplyAsync(responseJson -> {\n final R result;\n try {\n result = method.deserializeResponse(responseJson);\n } catch (Exception e) {\n throw new TelegramRequestException(e);\n }\n eventManager.call(new MethodSendEvent<>(Bot.this, method, result));\n return result;\n });\n }\n\n}"
},
{
"identifier": "GroupBotEvent",
"path": "src/main/java/org/teleight/teleightbots/event/trait/GroupBotEvent.java",
"snippet": "public interface GroupBotEvent extends Event {\n\n Update update();\n\n default Chat chat() {\n if (update().myChatMember() != null) {\n return update().myChatMember().chat();\n } else {\n return update().message().chat();\n }\n }\n\n}"
}
] | import org.jetbrains.annotations.NotNull;
import org.teleight.teleightbots.api.objects.Update;
import org.teleight.teleightbots.bot.Bot;
import org.teleight.teleightbots.event.trait.GroupBotEvent; | 1,122 | package org.teleight.teleightbots.event.bot.group;
public record BotLeftGroupEvent(
@NotNull Bot bot,
@NotNull Update update | package org.teleight.teleightbots.event.bot.group;
public record BotLeftGroupEvent(
@NotNull Bot bot,
@NotNull Update update | ) implements GroupBotEvent { | 1 | 2023-11-04 16:55:27+00:00 | 2k |
CxyJerry/pilipala | src/main/java/com/jerry/pilipala/infrastructure/advice/GlobalExceptionHandler.java | [
{
"identifier": "BusinessException",
"path": "src/main/java/com/jerry/pilipala/infrastructure/common/errors/BusinessException.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class BusinessException extends RuntimeException implements IResponse {\n private final int code;\n private final String message;\n private final IResponse response;\n\n public BusinessException(IResponse response) {\n this(\"\", response, null);\n }\n\n public BusinessException(String message, IResponse response) {\n this(message, response, null);\n }\n\n public BusinessException(String message, IResponse response, Object[] args) {\n super(message == null ? response.getMessage() : message);\n this.code = response.getCode();\n this.response = response;\n this.message = MessageFormat.format(super.getMessage(), args);\n }\n\n\n @Override\n public int getCode() {\n return code;\n }\n\n @Override\n public String getMessage() {\n return message;\n }\n\n public static BusinessException businessError(String message) {\n return new BusinessException(message, StandardResponse.ERROR);\n }\n}"
},
{
"identifier": "CommonResponse",
"path": "src/main/java/com/jerry/pilipala/infrastructure/common/response/CommonResponse.java",
"snippet": "@Data\n@AllArgsConstructor\npublic class CommonResponse<T> implements IResponse {\n private final int code;\n private final String message;\n private final T data;\n\n public static <T> CommonResponse<T> success() {\n return success(null);\n }\n\n public static <T> CommonResponse<T> success(T data) {\n return new CommonResponse<>(200, \"success\", data);\n }\n\n @Override\n public int getCode() {\n return code;\n }\n\n @Override\n public String getMessage() {\n return message;\n }\n}"
},
{
"identifier": "StandardResponse",
"path": "src/main/java/com/jerry/pilipala/infrastructure/common/response/StandardResponse.java",
"snippet": "public enum StandardResponse implements IResponse {\n OK(200, \"success\"),\n BAD_REQUEST(400, \"Bad Request\"),\n FORBIDDEN(403, \"Access Denied\"),\n NOT_FOUND(404, \"Not Found\"),\n ERROR(500, \"Business Error\");\n private final int code;\n private final String message;\n\n StandardResponse(int code, String message) {\n this.code = code;\n this.message = message;\n }\n\n\n @Override\n public int getCode() {\n return code;\n }\n\n @Override\n public String getMessage() {\n return message;\n }\n}"
}
] | import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import com.jerry.pilipala.infrastructure.common.errors.BusinessException;
import com.jerry.pilipala.infrastructure.common.response.CommonResponse;
import com.jerry.pilipala.infrastructure.common.response.StandardResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import javax.validation.ConstraintViolationException; | 827 | package com.jerry.pilipala.infrastructure.advice;
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public Object handleBusinessException(BusinessException e) {
log.info(e.getMessage()); | package com.jerry.pilipala.infrastructure.advice;
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public Object handleBusinessException(BusinessException e) {
log.info(e.getMessage()); | return new CommonResponse<>(StandardResponse.ERROR.getCode(), e.getMessage(), null); | 2 | 2023-11-03 10:05:02+00:00 | 2k |
viego1999/xuecheng-plus-project | xuecheng-plus-content/xuecheng-plus-content-service/src/test/java/com/xuecheng/ContentServiceApplicationTests.java | [
{
"identifier": "PageParams",
"path": "xuecheng-plus-base/src/main/java/com/xuecheng/base/model/PageParams.java",
"snippet": "@Data\n@ToString\n@ApiModel(\"分页参数类\")\n@NoArgsConstructor\n@AllArgsConstructor\npublic class PageParams {\n\n // 当前页码默认值\n @ApiModelProperty(\"当前页码默认值\")\n public static final long DEFAULT_PAGE_CURRENT = 1L;\n // 每页记录数默认值\n @ApiModelProperty(\"每页记录数默认值\")\n public static final long DEFAULT_PAGE_SIZE = 10L;\n // 当前页码\n @ApiModelProperty(\"当前页码\")\n private Long pageNo = DEFAULT_PAGE_CURRENT;\n // 每页记录数默认值\n @ApiModelProperty(\"每页记录数默认值\")\n private Long pageSize = DEFAULT_PAGE_SIZE;\n\n}"
},
{
"identifier": "CourseBaseMapper",
"path": "xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/mapper/CourseBaseMapper.java",
"snippet": "public interface CourseBaseMapper extends BaseMapper<CourseBase> {\n\n}"
},
{
"identifier": "QueryCourseParamsDto",
"path": "xuecheng-plus-content/xuecheng-plus-content-model/src/main/java/com/xuecheng/content/model/dto/QueryCourseParamsDto.java",
"snippet": "@Data\n@ToString\npublic class QueryCourseParamsDto {\n //审核状态\n private String auditStatus;\n //课程名称\n private String courseName;\n //发布状态\n private String publishStatus;\n}"
},
{
"identifier": "CourseBaseInfoService",
"path": "xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/service/CourseBaseInfoService.java",
"snippet": "public interface CourseBaseInfoService {\n\n /**\n * 课程查询\n *\n * @param companyId 机构id\n * @param params 分页参数\n * @param queryCourseParams 查询条件\n * @return 分页结果\n */\n PageResult<CourseBase> queryCourseBaseList(Long companyId, PageParams params, QueryCourseParamsDto queryCourseParams);\n\n /**\n * 新增课程\n *\n * @param companyId 培训机构 id\n * @param addCourseDto 新增课程的信息\n * @return 课程信息包括基本信息,营销信息\n */\n CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto addCourseDto);\n\n /**\n * 根据课程id查询课程基本信息,包括基本信息和营销信息\n *\n * @param courseId 课程id\n * @return 返回对应的课程信息\n */\n CourseBaseInfoDto queryCourseBaseById(Long courseId);\n\n /**\n * 修改课程信息\n *\n * @param companyId 机构id(校验:本机构只能修改本机构的课程)\n * @param dto 课程信息\n * @return 返回修改后的课程信息\n */\n CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto dto);\n\n /**\n * 删除课程\n *\n * @param courseId 课程 id\n * @return 删除结果\n */\n RestResponse<Boolean> deleteCourseBase(Long courseId);\n\n}"
},
{
"identifier": "CourseCategoryService",
"path": "xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/service/CourseCategoryService.java",
"snippet": "public interface CourseCategoryService {\n\n /**\n * 课程分类查询\n *\n * @param id 根节点 id\n * @return 根节点下的所有子节点\n */\n List<CourseCategoryTreeDto> queryTreeNodes(String id);\n\n}"
}
] | import com.xuecheng.base.model.PageParams;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.model.dto.QueryCourseParamsDto;
import com.xuecheng.content.service.CourseBaseInfoService;
import com.xuecheng.content.service.CourseCategoryService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource; | 1,097 | package com.xuecheng;
@SpringBootTest
class ContentServiceApplicationTests {
@Resource
private CourseBaseMapper courseBaseMapper;
@Autowired
private CourseBaseInfoService courseBaseInfoService;
@Autowired
private CourseCategoryService courseCategoryService;
@Test
void testCourseBaseMapper() {
System.out.println(courseBaseMapper.selectById(22));
}
@Test
void testCourseBaseInfoService() {
Long companyId = 1232141425L; | package com.xuecheng;
@SpringBootTest
class ContentServiceApplicationTests {
@Resource
private CourseBaseMapper courseBaseMapper;
@Autowired
private CourseBaseInfoService courseBaseInfoService;
@Autowired
private CourseCategoryService courseCategoryService;
@Test
void testCourseBaseMapper() {
System.out.println(courseBaseMapper.selectById(22));
}
@Test
void testCourseBaseInfoService() {
Long companyId = 1232141425L; | System.out.println(courseBaseInfoService.queryCourseBaseList(companyId, new PageParams(), new QueryCourseParamsDto())); | 2 | 2023-11-04 07:15:26+00:00 | 2k |
SAHONGPAK/JWT-Example | jwt-springboot/src/main/java/com/example/jwt/controller/AuthController.java | [
{
"identifier": "AuthDto",
"path": "jwt-springboot/src/main/java/com/example/jwt/model/dto/AuthDto.java",
"snippet": "public class AuthDto {\n\tprivate String userId;\n\tprivate String refreshToken;\n\t\n\tpublic AuthDto(String userId, String refreshToken) {\n\t\tthis.userId = userId;\n\t\tthis.refreshToken = refreshToken;\n\t}\n\t\n\tpublic String getUserId() {\n\t\treturn userId;\n\t}\n\tpublic void setUserId(String userId) {\n\t\tthis.userId = userId;\n\t}\n\tpublic String getRefreshToken() {\n\t\treturn refreshToken;\n\t}\n\tpublic void setRefreshToken(String refreshToken) {\n\t\tthis.refreshToken = refreshToken;\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn \"AuthDto [userId=\" + userId + \", refreshToken=\" + refreshToken + \"]\";\n\t}\n}"
},
{
"identifier": "AuthService",
"path": "jwt-springboot/src/main/java/com/example/jwt/model/service/AuthService.java",
"snippet": "public interface AuthService {\n\tint setRefreshToken(AuthDto authDto);\n\tAuthDto getRefreshToken(String userId);\n\tint updateRefreshToken(AuthDto authDto);\n\t\n}"
},
{
"identifier": "JWTUtil",
"path": "jwt-springboot/src/main/java/com/example/jwt/util/JWTUtil.java",
"snippet": "@Component\npublic class JWTUtil {\n\t\n\t@Value(\"jwt.key\")\n\tprivate String jwtKey;\n\t\n\t@Value(\"${jwt.accesstoken.expiretime}\")\n\tprivate Long accessTokenExpireTime;\n\t\n\t@Value(\"${jwt.refreshtoken.expiretime}\")\n\tprivate Long refreshTokenExpireTime;\n\t\n\tpublic String createAccessToken(String userId) throws UnsupportedEncodingException {\n\t\n\t\t// 현재 시간을 저장한다.\n\t\tlong currentTimeMillis = System.currentTimeMillis();\n\t\t\n\t\t// accessToken을 생성한다.\n\t\tJwtBuilder jwtAccessTokenBuilder = Jwts.builder();\n\t\tjwtAccessTokenBuilder.claim(\"userId\", userId);\n\t\tjwtAccessTokenBuilder.setIssuedAt(new Date(currentTimeMillis));\n\t\tjwtAccessTokenBuilder.setExpiration(new Date(currentTimeMillis + accessTokenExpireTime*1000));\n\t\tjwtAccessTokenBuilder.signWith(SignatureAlgorithm.HS256, jwtKey.getBytes(\"UTF-8\"));\n\t\n\t\treturn jwtAccessTokenBuilder.compact();\n\t}\n\t\n\t\n\tpublic String createRefreshToken(String userId) throws UnsupportedEncodingException {\n\t\t\n\t\t// 현재 시간을 저장한다.\n\t\tlong currentTimeMillis = System.currentTimeMillis();\n\t\t\n\t\t\n\t\t// refreshToken을 생성한다.\n\t\tJwtBuilder jwtRefreshTokenBuilder = Jwts.builder();\n\t\tjwtRefreshTokenBuilder.claim(\"userId\", userId);\n\t\tjwtRefreshTokenBuilder.setIssuedAt(new Date(currentTimeMillis));\n\t\tjwtRefreshTokenBuilder.setExpiration(new Date(currentTimeMillis + refreshTokenExpireTime*1000));\n\t\tjwtRefreshTokenBuilder.signWith(SignatureAlgorithm.HS256, jwtKey.getBytes(\"UTF-8\"));\n\t\n\t\treturn jwtRefreshTokenBuilder.compact();\n\t}\n\t\n\tpublic String getUserId(String authorization) throws ParseException {\n\t\t// accessToken을 파싱한다.\n\t\tString[] chunks = authorization.split(\"\\\\.\");\n\t\tBase64.Decoder decoder = Base64.getUrlDecoder();\n\t\t\n\t\t// payload에 저장된 userId를 획득한다.\n\t\tString payload = new String(decoder.decode(chunks[1]));\n\t\tJSONParser parser = new JSONParser();\n\t\tJSONObject obj = (JSONObject) parser.parse(payload);\n\t\t\n\t\tString userId = (String) obj.get(\"userId\");\n\t\t\n\t\treturn userId;\n\t}\n\t\n\tpublic boolean vaildCheck(String token) {\n\t\t\n\t\t// 해당 토큰을 확인하면서 예외가 발생하는 경우\n\t\t// 만료가 되었거나, 잘못된 토큰이다.\n\t\ttry {\n\t\t\tJwts.parser().setSigningKey(jwtKey.getBytes(\"UTF-8\")).parseClaimsJws(token);\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\t// 예외가 발생한 경우 유효한 토큰이 아니다.\n\t\t\treturn false;\n\t\t}\n\t\n\t\t// 예외가 발생하지 않았다면 유효한 토큰이다.\n\t\treturn true;\n\t}\n}"
}
] | import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.jwt.annotation.AuthRequired;
import com.example.jwt.model.dto.AuthDto;
import com.example.jwt.model.service.AuthService;
import com.example.jwt.util.JWTUtil; | 1,248 | package com.example.jwt.controller;
// https://velog.io/@cloud_oort/Next.js-%EB%A1%9C%EA%B7%B8%EC%9D%B8-%EA%B5%AC%ED%98%84-Silent-refresh
@RestController
@RequestMapping("/api/v1")
public class AuthController {
@Value("${jwt.accesstoken.expiretime}")
private int accessTokenExpireTime;
@Value("${jwt.refreshtoken.expiretime}")
private int refreshTokenExpireTime;
private final JWTUtil jwtUtil; | package com.example.jwt.controller;
// https://velog.io/@cloud_oort/Next.js-%EB%A1%9C%EA%B7%B8%EC%9D%B8-%EA%B5%AC%ED%98%84-Silent-refresh
@RestController
@RequestMapping("/api/v1")
public class AuthController {
@Value("${jwt.accesstoken.expiretime}")
private int accessTokenExpireTime;
@Value("${jwt.refreshtoken.expiretime}")
private int refreshTokenExpireTime;
private final JWTUtil jwtUtil; | private final AuthService authService; | 1 | 2023-11-09 13:14:13+00:00 | 2k |
matthiasbergneels/dhbwmawwi2023a | src/lecture/chapter4/CarPoolExternalRun.java | [
{
"identifier": "CAR_BRAND",
"path": "src/lecture/chapter5/CAR_BRAND.java",
"snippet": "public enum CAR_BRAND {\n MERCEDES(\"$$$\"),\n FIAT(\"$\"),\n BMW(\"$$$\"),\n SMART(\"$$\"),\n LADA(\"$\");\n\n private String priceTag;\n\n CAR_BRAND(String priceTag){\n this.priceTag = priceTag;\n }\n\n public String getPriceTag(){\n return priceTag;\n }\n\n @Override\n public String toString(){\n return switch(this){\n case MERCEDES -> \"Mercedes\";\n case BMW -> \"BMW\";\n case FIAT -> \"F.I.A.T\";\n case LADA -> \"Lada\";\n case SMART -> \"Smart\";\n };\n }\n}"
},
{
"identifier": "Car",
"path": "src/lecture/chapter5/Car.java",
"snippet": "public class Car {\n\n private String color;\n private int hp;\n private byte seatCount;\n public final CAR_BRAND BRAND;\n private double weight;\n private String fuelType;\n private int currentSpeed;\n protected String licensePlate;\n\n private static int carCount = 0;\n private static Car[] carRegister;\n\n static{\n System.out.println(\"Erste Aufruf der Klasse\");\n carCount = 5; //\n carRegister = new Car[100];\n }\n\n {\n System.out.println(\"Objekt erzeugt\");\n this.weight = 1500;\n this.seatCount = 5;\n }\n\n public Car(String color, int hp, CAR_BRAND brand, String fuelType){\n this.setColor(color);\n this.hp = hp;\n\n if(brand != null){\n this.BRAND = brand;\n }else{\n this.BRAND = CAR_BRAND.MERCEDES;\n }\n\n this.fuelType = fuelType;\n\n this.currentSpeed = 0;\n carCount++;\n /*\n for(int i = 0; i < carRegister.length; i++){\n if(carRegister[i] == null){\n carRegister[i] = this;\n break;\n }\n }\n\n */\n }\n\n public void accelerate(int speedDelta){\n currentSpeed += speedDelta; // currentSpeed = currentSpeed + speedDelta;\n }\n\n public void brake(){\n if(currentSpeed >= 10){\n currentSpeed -= 10;\n } else {\n currentSpeed = 0;\n }\n }\n\n public String getColor(){\n return color;\n }\n\n public void setColor(String color){\n if(color.equals(\"weiss\") ||\n color.equals(\"blau\") ||\n color.equals(\"grün\") ||\n color.equals(\"schwarz\") ||\n color.equals(\"pink\")){\n this.color = color;\n } else {\n System.out.println(\"Ungültige Farbe - Auto wird schwarz!\");\n this.color = \"schwarz\";\n }\n\n }\n\n public int getHp(){\n return hp;\n }\n\n public int getCurrentSpeed(){\n return currentSpeed;\n }\n\n public String getPriceTag(){\n return BRAND.getPriceTag();\n }\n\n public static int getCarCount(){\n return carCount;\n }\n\n @Override\n protected void finalize() throws Throwable {\n carCount--;\n System.out.println(\"Auto kommt in die Schrottpresse \" + this.BRAND);\n }\n}"
}
] | import lecture.chapter5.CAR_BRAND;
import lecture.chapter5.Car; | 884 | package lecture.chapter4;
public class CarPoolExternalRun {
public static void main(String[] args) {
| package lecture.chapter4;
public class CarPoolExternalRun {
public static void main(String[] args) {
| Car myCar = new Car("weiss", 65, CAR_BRAND.LADA, "e-hybrid"); | 1 | 2023-11-02 11:41:07+00:00 | 2k |
Verusins/CMS-Android-Simulation | app/src/main/java/example/com/cmsandroidsimulation/apiwrapper/Student.java | [
{
"identifier": "FailedLoginException",
"path": "app/src/main/java/example/com/cmsandroidsimulation/FailedLoginException.java",
"snippet": "public class FailedLoginException extends RuntimeException {\n}"
},
{
"identifier": "EventComment",
"path": "app/src/main/java/example/com/cmsandroidsimulation/datastructures/EventComment.java",
"snippet": "public class EventComment extends UserPost {\n private final int rating;\n private final Date date;\n public EventComment(String author, String details, int rating, Date date) {\n super(author, null, details);\n this.rating = rating;\n this.date = date;\n }\n\n public int getRating() {\n return rating;\n }\n\n public Date getDate() {\n return date;\n }\n\n}"
},
{
"identifier": "EventInfo",
"path": "app/src/main/java/example/com/cmsandroidsimulation/datastructures/EventInfo.java",
"snippet": "public class EventInfo extends UserPost{\n\n // Might change to builder pattern later.\n\n private final ArrayList<EventComment> comments;\n private final Date eventStartDateTime;\n private final Date eventEndDateTime;\n private final String eventid;\n\n private final int maxppl;\n\n private final String location;\n\n private final ArrayList<String> attendees;\n\n public EventInfo(String eventid, String author, String title, String details,\n Date eventStartDateTime, Date eventEndDateTime,\n ArrayList<EventComment> comments, int maxppl, ArrayList<String> attendees, String location)\n {\n super(author, title, details);\n this.comments = comments;\n this.eventStartDateTime = eventStartDateTime;\n this.eventEndDateTime = eventEndDateTime;\n this.eventid = eventid;\n this.maxppl = maxppl;\n this.attendees = attendees;\n this.location = location;\n }\n\n public String getLocation() {return location;}\n public ArrayList<String> getAttendees(){return attendees;}\n\n public String getEventid(){\n return eventid;\n }\n\n public ArrayList<EventComment> getComments() {\n return comments;\n }\n\n public Date getEventEndDateTime() {\n return eventEndDateTime;\n }\n\n public int getMaxppl() {return maxppl;}\n\n public Date getEventStartDateTime() {\n return eventStartDateTime;\n }\n}"
}
] | import android.util.Log;
import androidx.annotation.NonNull;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import example.com.cmsandroidsimulation.FailedLoginException;
import example.com.cmsandroidsimulation.datastructures.EventComment;
import example.com.cmsandroidsimulation.datastructures.EventInfo; | 1,149 | package example.com.cmsandroidsimulation.apiwrapper;
public class Student extends User {
public void Logout(){
FirebaseAuth.getInstance().signOut();
instance = null;
}
public static Task<AuthResult> Register(String username, String email, String password) throws FailedLoginException
{
// Simulate an asynchronous API call
Task<AuthResult> authResult = mAuth.createUserWithEmailAndPassword(email, password);
authResult.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
instance = new Student();
instance.email = email;
user = mAuth.getCurrentUser();
Map<String, Object> user = new HashMap<>();
ArrayList<String> events = new ArrayList<>();
user.put("name", username);
user.put("email", email);
user.put("isAdmin", false);
user.put("events", events);
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users")
.add(user)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
Log.d("MASTER APP", "DocumentSnapshot added with ID: " + documentReference.getId());
}
});
} else {
// If sign in fails, display a message to the user.
Log.e("MASTER APP", "Login failed");
}
}
});
return authResult;
}
public static Student getInstance()
{
return (Student) instance;
}
public Task<DocumentSnapshot> postEventComment(EventInfo eventInfo, String content, int rating)
{
String eventid = eventInfo.getEventid();
FirebaseFirestore db = FirebaseFirestore.getInstance();
Task<DocumentSnapshot> task = db.collection("events").document(eventid).get()
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
getName(email).thenAccept((String username) -> { | package example.com.cmsandroidsimulation.apiwrapper;
public class Student extends User {
public void Logout(){
FirebaseAuth.getInstance().signOut();
instance = null;
}
public static Task<AuthResult> Register(String username, String email, String password) throws FailedLoginException
{
// Simulate an asynchronous API call
Task<AuthResult> authResult = mAuth.createUserWithEmailAndPassword(email, password);
authResult.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
instance = new Student();
instance.email = email;
user = mAuth.getCurrentUser();
Map<String, Object> user = new HashMap<>();
ArrayList<String> events = new ArrayList<>();
user.put("name", username);
user.put("email", email);
user.put("isAdmin", false);
user.put("events", events);
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users")
.add(user)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
Log.d("MASTER APP", "DocumentSnapshot added with ID: " + documentReference.getId());
}
});
} else {
// If sign in fails, display a message to the user.
Log.e("MASTER APP", "Login failed");
}
}
});
return authResult;
}
public static Student getInstance()
{
return (Student) instance;
}
public Task<DocumentSnapshot> postEventComment(EventInfo eventInfo, String content, int rating)
{
String eventid = eventInfo.getEventid();
FirebaseFirestore db = FirebaseFirestore.getInstance();
Task<DocumentSnapshot> task = db.collection("events").document(eventid).get()
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
getName(email).thenAccept((String username) -> { | ArrayList<EventComment> temp = (ArrayList<EventComment>) document.get("comments"); | 1 | 2023-11-07 16:52:01+00:00 | 2k |
ProjectBIGWHALE/bigwhale-api | src/main/java/com/whale/web/documents/certificategenerator/service/EditSVGFiles.java | [
{
"identifier": "Certificate",
"path": "src/main/java/com/whale/web/documents/certificategenerator/model/Certificate.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\n@Component\npublic class Certificate {\n\n private CertificateTypeEnum certificateTypeEnum;\n private String eventName;\n private String speakerName;\n private String speakerRole;\n private String eventWorkLoad;\n private String eventDate;\n private String eventLocale;\n private Long certificateModelId;\n}"
},
{
"identifier": "CertificateBasicInfosEnum",
"path": "src/main/java/com/whale/web/documents/certificategenerator/model/enums/CertificateBasicInfosEnum.java",
"snippet": "@Getter\n@ToString\npublic enum CertificateBasicInfosEnum {\n EVENT_NAME(\"basicInfoEventName\"), EVENT_NAME_BODY(\"basicInfoEventNameTwo\"), SPEAKER_NAME(\"basicInfoSpeakerName\"),\n SPEAKER_ROLE(\"basicInfoSpeakerRole\"), EVENT_DATE(\"basicInfoEventDate\"), WORKLOAD(\"basicInfoEventWorkload\"),\n EVENT_LOCALE(\"basicInfoEventLocale\"), EVENT_DATE_BODY(\"basicInfoEventDateTwo\");\n\n private final String tagId;\n\n CertificateBasicInfosEnum(String tagId) {\n this.tagId = tagId;\n }\n}"
},
{
"identifier": "PersonBasicInfosEnum",
"path": "src/main/java/com/whale/web/documents/certificategenerator/model/enums/PersonBasicInfosEnum.java",
"snippet": "@Getter\n@ToString\npublic enum PersonBasicInfosEnum {\n PERSON_NAME(\"personName\"), PERSON_NAME_BODY(\"personNameTwo\");\n\n private final String tagId;\n\n PersonBasicInfosEnum(String tagId) {\n this.tagId = tagId;\n }\n}"
},
{
"identifier": "FormatDataUtil",
"path": "src/main/java/com/whale/web/utils/FormatDataUtil.java",
"snippet": "public class FormatDataUtil {\n\n public static String formatData(String inputDateStr) {\n SimpleDateFormat inputFormat = new SimpleDateFormat(\"yyyy-MM-dd\");\n Date date;\n\n try {\n date = inputFormat.parse(inputDateStr);\n } catch (ParseException e) {\n throw new RuntimeException(e);\n }\n\n SimpleDateFormat outputFormat = new SimpleDateFormat(\"d 'de' MMMM 'de' yyyy\", new Locale(\"pt\", \"BR\"));\n return outputFormat.format(date);\n }\n}"
}
] | import com.whale.web.documents.certificategenerator.model.Certificate;
import com.whale.web.documents.certificategenerator.model.enums.CertificateBasicInfosEnum;
import com.whale.web.documents.certificategenerator.model.enums.PersonBasicInfosEnum;
import com.whale.web.utils.FormatDataUtil;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; | 1,178 | package com.whale.web.documents.certificategenerator.service;
@Service
public class EditSVGFiles {
public List<String> cretateListCertificate(Certificate certificate, List<String> names, String certificateTemplate) throws Exception {
Document patchModel = preparateCertificateWithBasicInfos(certificate, certificateTemplate);
List<String> listCertificates = new ArrayList<>();
for (String name : names) {
String certificateForPerson = preparateCertificateForPerson(name, patchModel);
listCertificates.add(certificateForPerson);
}
return listCertificates;
}
private String preparateCertificateForPerson(String personName, Document document) throws Exception {
List<PersonBasicInfosEnum> basicInfos = Arrays.asList(PersonBasicInfosEnum.values());
NodeList textElements = document.getElementsByTagName("tspan");
for (int i = 0; i < textElements.getLength(); i++) {
Element textElement = (Element) textElements.item(i);
String id = textElement.getAttribute("id");
for (PersonBasicInfosEnum basicInfo : basicInfos) {
if (id.equals(basicInfo.getTagId())) {
switch (basicInfo) {
case PERSON_NAME, PERSON_NAME_BODY -> textElement.setTextContent(personName);
}
}
}
}
return convertDocumentToString(document);
}
private Document preparateCertificateWithBasicInfos(Certificate certificate, String certificateTemplate)
throws ParserConfigurationException, IOException, SAXException, TransformerException {
List<CertificateBasicInfosEnum> basicInfos = Arrays.asList(CertificateBasicInfosEnum.values());
Document document = readSVG(certificateTemplate);
NodeList textElements = document.getElementsByTagName("tspan");
for (int i = 0; i < textElements.getLength(); i++) {
Element textElement = (Element) textElements.item(i);
String id = textElement.getAttribute("id");
for (CertificateBasicInfosEnum basicInfo : basicInfos) {
if (id.equals(basicInfo.getTagId())) {
switch (basicInfo) {
case EVENT_NAME, EVENT_NAME_BODY -> textElement.setTextContent(certificate.getEventName());
case SPEAKER_NAME -> textElement.setTextContent(certificate.getSpeakerName());
case SPEAKER_ROLE -> textElement.setTextContent(certificate.getSpeakerRole()); | package com.whale.web.documents.certificategenerator.service;
@Service
public class EditSVGFiles {
public List<String> cretateListCertificate(Certificate certificate, List<String> names, String certificateTemplate) throws Exception {
Document patchModel = preparateCertificateWithBasicInfos(certificate, certificateTemplate);
List<String> listCertificates = new ArrayList<>();
for (String name : names) {
String certificateForPerson = preparateCertificateForPerson(name, patchModel);
listCertificates.add(certificateForPerson);
}
return listCertificates;
}
private String preparateCertificateForPerson(String personName, Document document) throws Exception {
List<PersonBasicInfosEnum> basicInfos = Arrays.asList(PersonBasicInfosEnum.values());
NodeList textElements = document.getElementsByTagName("tspan");
for (int i = 0; i < textElements.getLength(); i++) {
Element textElement = (Element) textElements.item(i);
String id = textElement.getAttribute("id");
for (PersonBasicInfosEnum basicInfo : basicInfos) {
if (id.equals(basicInfo.getTagId())) {
switch (basicInfo) {
case PERSON_NAME, PERSON_NAME_BODY -> textElement.setTextContent(personName);
}
}
}
}
return convertDocumentToString(document);
}
private Document preparateCertificateWithBasicInfos(Certificate certificate, String certificateTemplate)
throws ParserConfigurationException, IOException, SAXException, TransformerException {
List<CertificateBasicInfosEnum> basicInfos = Arrays.asList(CertificateBasicInfosEnum.values());
Document document = readSVG(certificateTemplate);
NodeList textElements = document.getElementsByTagName("tspan");
for (int i = 0; i < textElements.getLength(); i++) {
Element textElement = (Element) textElements.item(i);
String id = textElement.getAttribute("id");
for (CertificateBasicInfosEnum basicInfo : basicInfos) {
if (id.equals(basicInfo.getTagId())) {
switch (basicInfo) {
case EVENT_NAME, EVENT_NAME_BODY -> textElement.setTextContent(certificate.getEventName());
case SPEAKER_NAME -> textElement.setTextContent(certificate.getSpeakerName());
case SPEAKER_ROLE -> textElement.setTextContent(certificate.getSpeakerRole()); | case EVENT_DATE, EVENT_DATE_BODY -> textElement.setTextContent(FormatDataUtil.formatData( | 3 | 2023-11-08 22:41:22+00:00 | 2k |
ballerina-platform/module-ballerina-data-xmldata | native/src/main/java/io/ballerina/stdlib/data/xmldata/xml/Native.java | [
{
"identifier": "DiagnosticErrorCode",
"path": "native/src/main/java/io/ballerina/stdlib/data/xmldata/utils/DiagnosticErrorCode.java",
"snippet": "public enum DiagnosticErrorCode {\n\n INVALID_TYPE(\"BDE_0001\", \"invalid.type\"),\n XML_ROOT_MISSING(\"BDE_0002\", \"xml.root.missing\"),\n INVALID_REST_TYPE(\"BDE_0003\", \"invalid.rest.type\"),\n ARRAY_SIZE_MISMATCH(\"BDE_0004\", \"array.size.mismatch\"),\n REQUIRED_FIELD_NOT_PRESENT(\"BDE_0005\", \"required.field.not.present\"),\n REQUIRED_ATTRIBUTE_NOT_PRESENT(\"BDE_0006\", \"required.attribute.not.present\"),\n DUPLICATE_FIELD(\"BDE_0007\", \"duplicate.field\"),\n FOUND_ARRAY_FOR_NON_ARRAY_TYPE(\"BDE_0008\", \"found.array.for.non.array.type\"),\n EXPECTED_ANYDATA_OR_JSON(\"BDE_0009\", \"expected.anydata.or.json\"),\n NAMESPACE_MISMATCH(\"BDE_0010\", \"namespace.mismatch\"),\n TYPE_NAME_MISMATCH_WITH_XML_ELEMENT(\"BDE_0011\", \"type.name.mismatch.with.xml.element\"),\n CAN_NOT_READ_STREAM(\"BDE_0012\", \"error.cannot.read.stream\"),\n CANNOT_CONVERT_TO_EXPECTED_TYPE(\"BDE_0013\", \"cannot.convert.to.expected.type\"),\n UNSUPPORTED_TYPE(\"BDE_0014\", \"unsupported.type\"),\n STREAM_BROKEN(\"BDE_0015\", \"stream.broken\"),\n XML_PARSE_ERROR(\"BDE_0016\", \"xml.parse.error\");\n\n String diagnosticId;\n String messageKey;\n\n DiagnosticErrorCode(String diagnosticId, String messageKey) {\n this.diagnosticId = diagnosticId;\n this.messageKey = messageKey;\n }\n\n public String messageKey() {\n return messageKey;\n }\n}"
},
{
"identifier": "DiagnosticLog",
"path": "native/src/main/java/io/ballerina/stdlib/data/xmldata/utils/DiagnosticLog.java",
"snippet": "public class DiagnosticLog {\n private static final String ERROR_PREFIX = \"error\";\n private static final String ERROR = \"Error\";\n private static final ResourceBundle MESSAGES = ResourceBundle.getBundle(\"error\", Locale.getDefault());\n\n public static BError error(DiagnosticErrorCode code, Object... args) {\n String msg = formatMessage(code, args);\n return getXmlError(msg);\n }\n\n private static String formatMessage(DiagnosticErrorCode code, Object[] args) {\n String msgKey = MESSAGES.getString(ERROR_PREFIX + \".\" + code.messageKey());\n return MessageFormat.format(msgKey, args);\n }\n\n public static BError getXmlError(String message) {\n return ErrorCreator.createError(ModuleUtils.getModule(), ERROR, StringUtils.fromString(message),\n null, null);\n }\n}"
}
] | import io.ballerina.stdlib.data.xmldata.utils.DiagnosticErrorCode;
import io.ballerina.stdlib.data.xmldata.utils.DiagnosticLog;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.function.Consumer;
import io.ballerina.runtime.api.Environment;
import io.ballerina.runtime.api.Future;
import io.ballerina.runtime.api.types.MethodType;
import io.ballerina.runtime.api.types.ObjectType;
import io.ballerina.runtime.api.utils.TypeUtils;
import io.ballerina.runtime.api.values.BArray;
import io.ballerina.runtime.api.values.BMap;
import io.ballerina.runtime.api.values.BObject;
import io.ballerina.runtime.api.values.BStream;
import io.ballerina.runtime.api.values.BString;
import io.ballerina.runtime.api.values.BTypedesc;
import io.ballerina.runtime.api.values.BXml; | 1,338 | /*
* Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com).
*
* WSO2 LLC. 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.ballerina.stdlib.data.xmldata.xml;
/**
* Xml conversion.
*
* @since 0.1.0
*/
public class Native {
private static final String METHOD_NAME_NEXT = "next";
private static final String METHOD_NAME_CLOSE = "close";
public static Object fromXmlWithType(BXml xml, BMap<BString, Object> options, BTypedesc typed) {
try {
return XmlTraversal.traverse(xml, typed.getDescribingType());
} catch (Exception e) {
return DiagnosticLog.getXmlError(e.getMessage());
}
}
public static Object fromXmlStringWithType(Environment env, Object xml, BMap<BString, Object> map,
BTypedesc typed) {
try {
if (xml instanceof BString) {
return XmlParser.parse(new StringReader(((BString) xml).getValue()), typed.getDescribingType());
} else if (xml instanceof BArray) {
byte[] bytes = ((BArray) xml).getBytes();
return XmlParser.parse(new InputStreamReader(new ByteArrayInputStream(bytes)),
typed.getDescribingType());
} else if (xml instanceof BStream) {
final BObject iteratorObj = ((BStream) xml).getIteratorObj();
final Future future = env.markAsync();
ResultConsumer<Object> resultConsumer = new ResultConsumer<>(future);
try (var byteBlockSteam = new BallerinaByteBlockInputStream(env, iteratorObj,
resolveNextMethod(iteratorObj),
resolveCloseMethod(iteratorObj),
resultConsumer)) {
Object result = XmlParser.parse(new InputStreamReader(byteBlockSteam), typed.getDescribingType());
future.complete(result);
return null;
} catch (Exception e) { | /*
* Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com).
*
* WSO2 LLC. 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.ballerina.stdlib.data.xmldata.xml;
/**
* Xml conversion.
*
* @since 0.1.0
*/
public class Native {
private static final String METHOD_NAME_NEXT = "next";
private static final String METHOD_NAME_CLOSE = "close";
public static Object fromXmlWithType(BXml xml, BMap<BString, Object> options, BTypedesc typed) {
try {
return XmlTraversal.traverse(xml, typed.getDescribingType());
} catch (Exception e) {
return DiagnosticLog.getXmlError(e.getMessage());
}
}
public static Object fromXmlStringWithType(Environment env, Object xml, BMap<BString, Object> map,
BTypedesc typed) {
try {
if (xml instanceof BString) {
return XmlParser.parse(new StringReader(((BString) xml).getValue()), typed.getDescribingType());
} else if (xml instanceof BArray) {
byte[] bytes = ((BArray) xml).getBytes();
return XmlParser.parse(new InputStreamReader(new ByteArrayInputStream(bytes)),
typed.getDescribingType());
} else if (xml instanceof BStream) {
final BObject iteratorObj = ((BStream) xml).getIteratorObj();
final Future future = env.markAsync();
ResultConsumer<Object> resultConsumer = new ResultConsumer<>(future);
try (var byteBlockSteam = new BallerinaByteBlockInputStream(env, iteratorObj,
resolveNextMethod(iteratorObj),
resolveCloseMethod(iteratorObj),
resultConsumer)) {
Object result = XmlParser.parse(new InputStreamReader(byteBlockSteam), typed.getDescribingType());
future.complete(result);
return null;
} catch (Exception e) { | future.complete(DiagnosticLog.error(DiagnosticErrorCode.STREAM_BROKEN, e.getMessage())); | 0 | 2023-11-08 04:13:52+00:00 | 2k |
Mau38/SparePartsFTC | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Teleop.java | [
{
"identifier": "ARM_LOWER_BOUND",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Constants.java",
"snippet": "public static int ARM_LOWER_BOUND = -800;"
},
{
"identifier": "ARM_UPPER_BOUND",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Constants.java",
"snippet": "public static int ARM_UPPER_BOUND = -50;"
},
{
"identifier": "armClimbPosition",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Constants.java",
"snippet": "public static int armClimbPosition = -460;"
},
{
"identifier": "armScorePosition",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Constants.java",
"snippet": "public static int armScorePosition = -730;"
},
{
"identifier": "revHubOrientation",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Constants.java",
"snippet": "public static RevHubOrientationOnRobot revHubOrientation= new RevHubOrientationOnRobot(\n // Check Values\n new Quaternion(\n (float) Math.cos(.5 * 90),\n (float) Math.sin(.5 * 90),\n 0.0f,\n 0.0f,\n System.nanoTime()\n )\n);"
}
] | import static org.firstinspires.ftc.teamcode.Constants.ARM_LOWER_BOUND;
import static org.firstinspires.ftc.teamcode.Constants.ARM_UPPER_BOUND;
import static org.firstinspires.ftc.teamcode.Constants.armClimbPosition;
import static org.firstinspires.ftc.teamcode.Constants.armScorePosition;
import static org.firstinspires.ftc.teamcode.Constants.revHubOrientation;
import com.acmerobotics.dashboard.config.Config;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorEx;
import com.qualcomm.robotcore.hardware.IMU;
import com.qualcomm.robotcore.hardware.Servo;
import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; | 1,201 | package org.firstinspires.ftc.teamcode;
@Config
@TeleOp(name = "CompTeleOp", group = "Comp")
public class Teleop extends OpMode {
private Drivetrain mecanum;
public static boolean USING_ARM = true;
private DcMotorEx motorA, motorB;
private Servo claw1, claw2, wrist;
public static int currentPosition = 0;
private int armSetpoint = 400;
private int armIncrement = 50;
private IMU imu;
// Enum for different arm states
private enum ArmState {
MANUAL_CONTROL,
ARM_UP,
ARM_DOWN,
ARM_SCORE,
ARM_CLIMB
}
private ArmState currentArmState = ArmState.MANUAL_CONTROL;
// PID constants for arm control
public static double armP = 0.1;
private static double armI = 0.01;
private static double armD = 0.001;
// Variables for PID control
private double previousError = 0;
private double integral = 0;
@Override
public void init() {
mecanum = new Drivetrain(gamepad1, hardwareMap);
imu = hardwareMap.get(IMU.class, "imu");
IMU.Parameters parameters = new IMU.Parameters(
revHubOrientation
);
imu.initialize(parameters);
imu.resetYaw();
if (USING_ARM) {
motorA = hardwareMap.get(DcMotorEx.class, "A1");
motorB = hardwareMap.get(DcMotorEx.class, "A2");
claw1 = hardwareMap.get(Servo.class, "leftPixel");
claw2 = hardwareMap.get(Servo.class, "rightPixel");
wrist = hardwareMap.get(Servo.class, "wrist");
motorB.setDirection(DcMotor.Direction.REVERSE);
setupMotor(motorA);
setupMotor(motorB);
resetArm();
}
telemetry.addData("Status", "Initialized");
}
@Override
public void loop() {
// mecanum.drive();
if (gamepad1.back) {
imu.resetYaw();
}
mecanum.drive(imu);
telemetry.addData("YAW", imu.getRobotYawPitchRollAngles().getYaw(AngleUnit.RADIANS));
if (USING_ARM) {
handleArmControls();
updateArmPosition();
handleClawControls();
telemetry.addData("Encoder PositionA", motorA.getCurrentPosition());
telemetry.addData("Encoder PositionB", motorB.getCurrentPosition());
telemetry.addData("Claw Position", claw1.getPosition());
telemetry.addData("Wrist Position", wrist.getPosition());
}
telemetry.update();
}
private void setupMotor(DcMotorEx motor) {
motor.setPower(0);
motor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
motor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
motor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
motor.setMode(DcMotor.RunMode.RUN_TO_POSITION);
}
private void handleArmControls() {
switch (currentArmState) {
case MANUAL_CONTROL:
// Allow manual control of the arm
currentPosition += (int) (gamepad1.left_trigger * armIncrement);
break;
case ARM_UP:
// Use PID control to move the arm to the desired setpoint
pidControlArm();
break;
case ARM_DOWN:
// Use PID control to move the arm to the desired setpoint
pidControlArm();
break;
case ARM_CLIMB: | package org.firstinspires.ftc.teamcode;
@Config
@TeleOp(name = "CompTeleOp", group = "Comp")
public class Teleop extends OpMode {
private Drivetrain mecanum;
public static boolean USING_ARM = true;
private DcMotorEx motorA, motorB;
private Servo claw1, claw2, wrist;
public static int currentPosition = 0;
private int armSetpoint = 400;
private int armIncrement = 50;
private IMU imu;
// Enum for different arm states
private enum ArmState {
MANUAL_CONTROL,
ARM_UP,
ARM_DOWN,
ARM_SCORE,
ARM_CLIMB
}
private ArmState currentArmState = ArmState.MANUAL_CONTROL;
// PID constants for arm control
public static double armP = 0.1;
private static double armI = 0.01;
private static double armD = 0.001;
// Variables for PID control
private double previousError = 0;
private double integral = 0;
@Override
public void init() {
mecanum = new Drivetrain(gamepad1, hardwareMap);
imu = hardwareMap.get(IMU.class, "imu");
IMU.Parameters parameters = new IMU.Parameters(
revHubOrientation
);
imu.initialize(parameters);
imu.resetYaw();
if (USING_ARM) {
motorA = hardwareMap.get(DcMotorEx.class, "A1");
motorB = hardwareMap.get(DcMotorEx.class, "A2");
claw1 = hardwareMap.get(Servo.class, "leftPixel");
claw2 = hardwareMap.get(Servo.class, "rightPixel");
wrist = hardwareMap.get(Servo.class, "wrist");
motorB.setDirection(DcMotor.Direction.REVERSE);
setupMotor(motorA);
setupMotor(motorB);
resetArm();
}
telemetry.addData("Status", "Initialized");
}
@Override
public void loop() {
// mecanum.drive();
if (gamepad1.back) {
imu.resetYaw();
}
mecanum.drive(imu);
telemetry.addData("YAW", imu.getRobotYawPitchRollAngles().getYaw(AngleUnit.RADIANS));
if (USING_ARM) {
handleArmControls();
updateArmPosition();
handleClawControls();
telemetry.addData("Encoder PositionA", motorA.getCurrentPosition());
telemetry.addData("Encoder PositionB", motorB.getCurrentPosition());
telemetry.addData("Claw Position", claw1.getPosition());
telemetry.addData("Wrist Position", wrist.getPosition());
}
telemetry.update();
}
private void setupMotor(DcMotorEx motor) {
motor.setPower(0);
motor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
motor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
motor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
motor.setMode(DcMotor.RunMode.RUN_TO_POSITION);
}
private void handleArmControls() {
switch (currentArmState) {
case MANUAL_CONTROL:
// Allow manual control of the arm
currentPosition += (int) (gamepad1.left_trigger * armIncrement);
break;
case ARM_UP:
// Use PID control to move the arm to the desired setpoint
pidControlArm();
break;
case ARM_DOWN:
// Use PID control to move the arm to the desired setpoint
pidControlArm();
break;
case ARM_CLIMB: | currentPosition = armClimbPosition; | 2 | 2023-11-06 21:25:54+00:00 | 2k |
RoshanAdi/GPTonDemand-Api | src/main/java/com/gpt/gptplus1/Service/WebSecurity/UserDetailsServiceImpl.java | [
{
"identifier": "User",
"path": "src/main/java/com/gpt/gptplus1/Entity/User.java",
"snippet": "@Entity\npublic class User {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @NotNull\n private int userId;\n\n private String firstName;\n private String lastName;\n private String email;\n private String phone;\n private String password;\n\n private String verificationCode;\n\n private boolean enabled;\n private String role;\n\n public int getUserId() {\n return userId;\n }\n\n public void setUserId(int userId) {\n this.userId = userId;\n }\n\n public String getFirstName() {\n return firstName;\n }\n\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n\n public String getLastName() {\n return lastName;\n }\n\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getPhone() {\n return phone;\n }\n\n public void setPhone(String phone) {\n this.phone = phone;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public String getVerificationCode() {\n return verificationCode;\n }\n\n public void setVerificationCode(String verificationCode) {\n this.verificationCode = verificationCode;\n }\n\n public boolean isEnabled() {\n return enabled;\n }\n\n public void setEnabled(boolean enabled) {\n this.enabled = enabled;\n }\n\n public String getRole() {\n return role;\n }\n\n public void setRole(String role) {\n this.role = role;\n }\n}"
},
{
"identifier": "UserRepo",
"path": "src/main/java/com/gpt/gptplus1/Repository/UserRepo.java",
"snippet": "@Repository\n@Component\npublic interface UserRepo extends JpaRepository<User,Integer>{\n\n public User findByEmail(String email);\n @Query(\"SELECT u FROM User u WHERE u.verificationCode = ?1\")\n public User findByVerificationCode(String code);\n}"
}
] | import com.gpt.gptplus1.Entity.User;
import com.gpt.gptplus1.Repository.UserRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.util.HashSet;
import java.util.Set; | 689 | package com.gpt.gptplus1.Service.WebSecurity;
@Service
@Component
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired | package com.gpt.gptplus1.Service.WebSecurity;
@Service
@Component
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired | UserRepo userRepo; | 1 | 2023-11-07 11:52:13+00:00 | 2k |
project-BarryBarry/coffeeport | src/main/java/com/barrybarry/coffeeport/handler/TaskHandler.java | [
{
"identifier": "ResponseData",
"path": "src/main/java/com/barrybarry/coffeeport/data/ResponseData.java",
"snippet": "@SuppressWarnings({\"FieldCanBeLocal\", \"unused\"})\n@Getter\n@Setter\npublic class ResponseData {\n private int res;\n private Object data;\n}"
},
{
"identifier": "TaskData",
"path": "src/main/java/com/barrybarry/coffeeport/data/task/TaskData.java",
"snippet": "@SuppressWarnings({\"FieldCanBeLocal\", \"unused\"})\n@Setter\n@Getter\npublic class TaskData {\n private String callback;\n\n private String sid;\n private VeraTaskData data;\n\n private Object callbackData;\n\n private String origin;\n\n public void setData(String json) {\n this.data = new Gson().fromJson(json, VeraTaskData.class);\n }\n\n @SuppressWarnings({\"LombokSetterMayBeUsed\", \"RedundantSuppression\"})\n public void setData(VeraTaskData data) {\n this.data = data;\n }\n}"
},
{
"identifier": "TaskListManager",
"path": "src/main/java/com/barrybarry/coffeeport/sigleton/TaskListManager.java",
"snippet": "@Getter\n@Setter\npublic class TaskListManager {\n private TaskListManager(){\n }\n private final ConcurrentHashMap<String, TaskData> tasks = new ConcurrentHashMap<>();\n\n private volatile boolean isInstallationRunning = false;\n\n private List<String> uiUpdate = Collections.synchronizedList(new ArrayList<>());\n public final TaskData getTask(String sid){\n return tasks.get(sid);\n }\n\n public final void setTask(String sid, TaskData task){\n tasks.put(sid, task);\n }\n\n public final void removeTask(String sid){\n tasks.remove(sid);\n }\n\n public final String[] getTaskList(){\n return tasks.keySet().toArray(new String[0]);\n }\n private static class Lazy{\n private static final TaskListManager instance = new TaskListManager();\n }\n public static TaskListManager getInstance() {\n return Lazy.instance;\n }\n}"
}
] | import com.barrybarry.coffeeport.data.ResponseData;
import com.barrybarry.coffeeport.data.task.TaskData;
import com.barrybarry.coffeeport.sigleton.TaskListManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | 699 | package com.barrybarry.coffeeport.handler;
public class TaskHandler extends Thread{
private static final Logger logger = LoggerFactory.getLogger(TaskHandler.class);
private boolean isRunning = true;
@Override
public void run() {
logger.debug("TaskHandler started!");
while (isRunning) {
String[] tasks = TaskListManager.getInstance().getTaskList();
for (String sid : tasks) {
TaskData taskData = TaskListManager.getInstance().getTask(sid);
if (taskData == null || taskData.getCallbackData() != null) {
continue;
}
logger.debug("Handling sid: " + sid);
if(taskData.getData().getCmd() != null) {
logger.debug("task cmd: {}", taskData.getData().getCmd());
} | package com.barrybarry.coffeeport.handler;
public class TaskHandler extends Thread{
private static final Logger logger = LoggerFactory.getLogger(TaskHandler.class);
private boolean isRunning = true;
@Override
public void run() {
logger.debug("TaskHandler started!");
while (isRunning) {
String[] tasks = TaskListManager.getInstance().getTaskList();
for (String sid : tasks) {
TaskData taskData = TaskListManager.getInstance().getTask(sid);
if (taskData == null || taskData.getCallbackData() != null) {
continue;
}
logger.debug("Handling sid: " + sid);
if(taskData.getData().getCmd() != null) {
logger.debug("task cmd: {}", taskData.getData().getCmd());
} | ResponseData res = new ResponseData(); | 0 | 2023-11-08 01:22:24+00:00 | 2k |
celedev97/asa-server-manager | src/main/java/dev/cele/asa_sm/services/UpdateService.java | [
{
"identifier": "Const",
"path": "src/main/java/dev/cele/asa_sm/Const.java",
"snippet": "public final class Const {\n public final static String ASA_STEAM_GAME_NUMBER = \"2430930\";\n\n public final static Path DATA_DIR = Path.of(\"data\");\n public final static Path PROFILES_DIR = DATA_DIR.resolve(\"profiles\");\n public final static Path SERVERS_DIR = Path.of(\"servers\");\n\n\n public final static Path THEME_DIR = DATA_DIR.resolve(\"themes\");\n public final static Path MOD_CACHE_DIR = DATA_DIR.resolve(\"mod_cache\");\n\n public final static Path SETTINGS_FILE = DATA_DIR.resolve(\"settings.json\");\n\n public final static Path TEMP_DIR = SystemUtils.getJavaIoTmpDir().toPath().resolve(\"asa_sm\");\n}"
},
{
"identifier": "Release",
"path": "src/main/java/dev/cele/asa_sm/dto/github/Release.java",
"snippet": "@Data\npublic class Release {\n private String id;\n private String html_url;\n private String tag_name;\n private String name;\n private Date published_at;\n private Asset[] assets;\n private String body;\n}"
},
{
"identifier": "GithubClient",
"path": "src/main/java/dev/cele/asa_sm/feign/GithubClient.java",
"snippet": "@FeignClient(name = \"github\", url = \"https://api.github.com\")\npublic interface GithubClient {\n\n @GetMapping(\"/repos/{owner}/{repo}/releases/latest\")\n Release getLatestRelease(@PathVariable String owner, @PathVariable String repo);\n\n}"
},
{
"identifier": "ProgressFrame",
"path": "src/main/java/dev/cele/asa_sm/ui/frames/ProgressFrame.java",
"snippet": "public class ProgressFrame extends JDialog {\n\n private final JLabel label = new JLabel();\n\n @Getter\n private final JProgressBar progressBar = new JProgressBar();\n\n public ProgressFrame(Frame owner, String title, String message, boolean indeterminate) {\n super(owner, title, true);\n setLocationRelativeTo(owner);\n\n label.setText(message == null ? \"\" : message);\n\n setLayout(new BorderLayout());\n\n add(label, BorderLayout.CENTER);\n add(progressBar, BorderLayout.SOUTH);\n\n if(!indeterminate) progressBar.setStringPainted(true);\n progressBar.setIndeterminate(indeterminate);\n\n pack();\n setSize(new Dimension(getWidth()+ 50, getHeight() + 20));\n setResizable(false);\n }\n\n public void setProgress(int progress, String message) {\n SwingUtilities.invokeLater(() -> {\n setProgress(progress);\n label.setText(message);\n });\n }\n\n public void setProgress(int progress) {\n SwingUtilities.invokeLater(() -> {\n progressBar.setValue(progress);\n });\n }\n\n public void setMessage(String message) {\n label.setText(message);\n }\n\n public void launch(Consumer<ProgressFrame> action) {\n new Thread(() -> {\n action.accept(this);\n setVisible(false);\n }).start();\n setVisible(true);\n }\n}"
}
] | import dev.cele.asa_sm.Const;
import dev.cele.asa_sm.dto.github.Release;
import dev.cele.asa_sm.feign.GithubClient;
import dev.cele.asa_sm.ui.frames.ProgressFrame;
import jakarta.annotation.PostConstruct;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import org.springframework.web.client.RestTemplate;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.regex.Pattern; | 937 | package dev.cele.asa_sm.services;
@Service
@RequiredArgsConstructor
@Slf4j
public class UpdateService {
private final GithubClient githubClient;
@Getter
@Value("${application.version}")
private String currentVersion;
private String ignoredVersion = "";
{
try { | package dev.cele.asa_sm.services;
@Service
@RequiredArgsConstructor
@Slf4j
public class UpdateService {
private final GithubClient githubClient;
@Getter
@Value("${application.version}")
private String currentVersion;
private String ignoredVersion = "";
{
try { | var ignoredVersionFile = Const.DATA_DIR.resolve("ignoredVersion.txt"); | 0 | 2023-11-07 19:36:49+00:00 | 2k |
fredpena/barcamp2023 | src/main/java/dev/fredpena/barcamp/controller/ClientController.java | [
{
"identifier": "Person",
"path": "src/main/java/dev/fredpena/barcamp/data/tenant/entity/Person.java",
"snippet": "@ToString\n@Getter\n@Setter\n@Entity\n@Audited(withModifiedFlag = true)\n@EqualsAndHashCode(of = \"code\", callSuper = false)\n@Table(name = \"person\", indexes = {@Index(columnList = \"firstName\"), @Index(columnList = \"lastName\"), @Index(columnList = \"email\")})\npublic class Person extends Auditable implements Serializable {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long code;\n @NotNull\n @Column(length = 50)\n @Length(message = \"This field can not be blank.\", min = 1, max = 50)\n private String firstName;\n @NotNull\n @Column(length = 50)\n @Length(message = \"This field can not be blank.\", min = 1, max = 50)\n private String lastName;\n @Email\n @NotNull\n @Column(length = 100)\n @Length(message = \"This field can not be blank.\", min = 1, max = 50)\n private String email;\n @NotNull\n @Column(length = 50)\n @Length(message = \"This field can not be blank.\", min = 1, max = 50)\n private String phone;\n @NotNull(message = \"This field can not be blank.\")\n private LocalDate dateOfBirth;\n @NotNull\n @Column(length = 100)\n @Length(message = \"This field can not be blank.\", min = 1, max = 50)\n private String occupation;\n @NotNull\n @Column(length = 50)\n @Length(message = \"This field can not be blank.\", min = 1, max = 50)\n private String role;\n\n private boolean important;\n\n\n}"
},
{
"identifier": "PersonService",
"path": "src/main/java/dev/fredpena/barcamp/data/tenant/service/PersonService.java",
"snippet": "@Service\npublic class PersonService {\n\n private final PersonRepository repository;\n\n public PersonService(PersonRepository repository) {\n this.repository = repository;\n }\n\n public Optional<Person> get(Long id) {\n if (id == null) return Optional.empty();\n\n return repository.findById(id);\n }\n\n public Person update(Person entity) {\n return repository.save(entity);\n }\n\n public void delete(Long id) {\n repository.deleteById(id);\n }\n\n public Page<Person> list(Pageable pageable) {\n return repository.findAll(pageable);\n }\n\n public Page<Person> list(Pageable pageable, Specification<Person> filter) {\n return repository.findAll(filter, pageable);\n }\n\n public List<Person> findAll() {\n return repository.findAll();\n }\n\n public int count() {\n return (int) repository.count();\n }\n\n}"
}
] | import dev.fredpena.barcamp.data.tenant.entity.Person;
import dev.fredpena.barcamp.data.tenant.service.PersonService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.data.repository.query.Param;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Optional; | 827 | package dev.fredpena.barcamp.controller;
@RestController
@RequestMapping("api/persons")
@RequiredArgsConstructor
public class ClientController {
| package dev.fredpena.barcamp.controller;
@RestController
@RequestMapping("api/persons")
@RequiredArgsConstructor
public class ClientController {
| private final PersonService personService; | 1 | 2023-11-08 18:12:12+00:00 | 2k |
HexHive/Crystallizer | src/dynamic/TrackStatistics.java | [
{
"identifier": "GadgetVertexSerializable",
"path": "src/static/src/main/java/analysis/GadgetVertexSerializable.java",
"snippet": "public class GadgetVertexSerializable implements Serializable {\n final GadgetMethodSerializable node;\n\n public GadgetVertexSerializable(GadgetMethodSerializable node) {\n this.node = node;\n }\n\n public String toString() {\n return node.keyString();\n }\n\n public String getType() {\n return node.getType();\n }\n\n public String getClsName() {\n return node.getClsName();\n }\n\n public String getMethodSignature() {\n return node.getMethodSignature();\n }\n\n public String getQualifiedName() {\n return node.getQualifiedName();\n }\n\n\n public int hashCode() {\n return toString().hashCode();\n }\n \n public boolean equals(Object o) {\n return (o instanceof GadgetVertexSerializable) && (toString().equals(o.toString()));\n }\n}"
},
{
"identifier": "GadgetMethodSerializable",
"path": "src/static/src/main/java/analysis/GadgetMethodSerializable.java",
"snippet": "public class GadgetMethodSerializable implements Serializable {\n\n final String clsName; \n final String methodSignature; \n\tfinal String qualifiedName; // The method name constructed to allow for comparison against what is output by method method in java \n final String type; // Type of gadget [Source/Sink/Chain]\n\n // We setup the unique key as <clsName: methodName(methodParameters)>\n public String keyString() {\n return this.methodSignature;\n }\n\n GadgetMethodSerializable(String clsName, String methodSignature, String type, String qualifiedName) {\n this.clsName = clsName;\n this.methodSignature = methodSignature;\n this.qualifiedName = qualifiedName;\n this.type = type;\n }\n\n String getMethodSignature() {\n return this.methodSignature;\n }\n\n String getClsName() {\n return this.clsName;\n }\n\n String getType() {\n return this.type;\n }\n\n String getQualifiedName() {\n return this.qualifiedName;\n }\n\n}"
}
] | import java.io.*;
import java.util.*;
import java.nio.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.nio.file.FileAlreadyExistsException;
import java.time.Instant;
import org.apache.log4j.Logger;
import org.jgrapht.*;
import org.jgrapht.graph.*;
import org.jgrapht.traverse.*;
import analysis.GadgetVertexSerializable;
import analysis.GadgetMethodSerializable; | 1,197 | package com.example;
// import org.apache.logging.log4j.Logger;
public class TrackStatistics {
private static final Logger LOGGER = Logger.getLogger(TrackStatistics.class);
// static String storeDir = "/root/SeriFuzz/jazzer_nogg/";
static String storeDir = "/root/SeriFuzz/jazzer/";
// Data structure to hold the progression made by the fuzzer while trying to concretize paths
// The data held is : [Length of path, number of nodes successfully instantiated, number of nodes successfully invoked, number of nodes sucessfully invoked during deserialization]
// Since the paths found are always in the same order we can use the order in which the paths are found as an implicit index
public static List<Integer[]> progressList = new ArrayList<>();
// Stats maintained to quantify success of SeriFuzz at exploring the state space
public static int numVertices = 0;
public static int correctInstantiations = 0; // Total number of gadgets for which declaring class objects were created successfully
public static int correctInvocations = 0; // Total number of gadgets which were correctly invoked using the constructed objects
public static int correctDeserializations = 0; // Total number of gadgets which were successfully triggered during deserialization
public static List<String> idMap = readgadgetIDMap();
public static List<String> readgadgetIDMap() {
LOGGER.info("Reading the fnidmap from disk");
try {
FileInputStream fin = new FileInputStream(GadgetDB.rootPath + "fnIDList.store");
ObjectInputStream oin = new ObjectInputStream(fin);
idMap = (List<String>) oin.readObject();
} catch (IOException | ClassNotFoundException ioe) {
ioe.printStackTrace();
}
// int idx = 0;
// for (String gadgetID: idMap) {
// LOGGER.debug(String.format("Idx:%d Gadget:%s" , idx, gadgetID));
// idx += 1;
// }
return idMap;
}
public static void resetCoverageFile() {
LOGGER.debug("Resetting coverage file");
File myObj = new File("test.txt");
myObj.delete();
}
public static void initProgressCounters() {
// See if the progress counter map has been initialized already by trying to read
// it from disk
try {
File toRead = new File(storeDir + "fuzzProgress.list");
FileInputStream fis = new FileInputStream(toRead);
ObjectInputStream ois = new ObjectInputStream(fis);
TrackStatistics.progressList = (List<Integer[]>)ois.readObject();
ois.close();
fis.close();
LOGGER.info("The progress map already exists, reading it from disk");
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
LOGGER.info("The progress map does not exist, initializing it from scratch"); | package com.example;
// import org.apache.logging.log4j.Logger;
public class TrackStatistics {
private static final Logger LOGGER = Logger.getLogger(TrackStatistics.class);
// static String storeDir = "/root/SeriFuzz/jazzer_nogg/";
static String storeDir = "/root/SeriFuzz/jazzer/";
// Data structure to hold the progression made by the fuzzer while trying to concretize paths
// The data held is : [Length of path, number of nodes successfully instantiated, number of nodes successfully invoked, number of nodes sucessfully invoked during deserialization]
// Since the paths found are always in the same order we can use the order in which the paths are found as an implicit index
public static List<Integer[]> progressList = new ArrayList<>();
// Stats maintained to quantify success of SeriFuzz at exploring the state space
public static int numVertices = 0;
public static int correctInstantiations = 0; // Total number of gadgets for which declaring class objects were created successfully
public static int correctInvocations = 0; // Total number of gadgets which were correctly invoked using the constructed objects
public static int correctDeserializations = 0; // Total number of gadgets which were successfully triggered during deserialization
public static List<String> idMap = readgadgetIDMap();
public static List<String> readgadgetIDMap() {
LOGGER.info("Reading the fnidmap from disk");
try {
FileInputStream fin = new FileInputStream(GadgetDB.rootPath + "fnIDList.store");
ObjectInputStream oin = new ObjectInputStream(fin);
idMap = (List<String>) oin.readObject();
} catch (IOException | ClassNotFoundException ioe) {
ioe.printStackTrace();
}
// int idx = 0;
// for (String gadgetID: idMap) {
// LOGGER.debug(String.format("Idx:%d Gadget:%s" , idx, gadgetID));
// idx += 1;
// }
return idMap;
}
public static void resetCoverageFile() {
LOGGER.debug("Resetting coverage file");
File myObj = new File("test.txt");
myObj.delete();
}
public static void initProgressCounters() {
// See if the progress counter map has been initialized already by trying to read
// it from disk
try {
File toRead = new File(storeDir + "fuzzProgress.list");
FileInputStream fis = new FileInputStream(toRead);
ObjectInputStream ois = new ObjectInputStream(fis);
TrackStatistics.progressList = (List<Integer[]>)ois.readObject();
ois.close();
fis.close();
LOGGER.info("The progress map already exists, reading it from disk");
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
LOGGER.info("The progress map does not exist, initializing it from scratch"); | for (GraphPath<GadgetVertexSerializable, DefaultEdge> path: GadgetDB.paths) { | 0 | 2023-11-07 22:03:19+00:00 | 2k |
1341191074/aibote4j | sdk-server/src/main/java/net/aibote/App.java | [
{
"identifier": "ScriptManager",
"path": "sdk-server/src/main/java/net/aibote/scripts/ScriptManager.java",
"snippet": "public class ScriptManager implements Runnable {\n\n @Override\n public void run() {\n while (true) {\n String channelId = ClientManager.poll();\n if (null != channelId) {\n Thread.ofVirtual().start(() -> {\n AiboteChannel aiboteChannel = AndroidClientManager.getInstance().get(channelId);\n AndroidBotTest androidBotTest = new AndroidBotTest();\n aiboteChannel.setAibote(androidBotTest);\n androidBotTest.doScript();\n });\n }else {\n try {\n Thread.sleep(2000);\n } catch (InterruptedException e) {\n }\n }\n }\n }\n}"
},
{
"identifier": "AndroidServer",
"path": "sdk-server/src/main/java/net/aibote/server/impl/AndroidServer.java",
"snippet": "public class AndroidServer extends BotServer {\n\n private static final AndroidServer instance = new AndroidServer();\n @Override\n public int getPort() {\n int port = 16997;\n return port;\n }\n\n @Override\n public void handlers(ChannelPipeline pipeline) {\n pipeline.addLast(new AndroidHandler());\n }\n\n public static BotServer getInstance() {\n return instance;\n }\n}"
},
{
"identifier": "WebServer",
"path": "sdk-server/src/main/java/net/aibote/server/impl/WebServer.java",
"snippet": "public class WebServer extends BotServer {\n\n private static final WebServer instance = new WebServer();\n\n @Override\n public int getPort() {\n int port = 16998;\n return port;\n }\n\n @Override\n public void handlers(ChannelPipeline pipeline) {\n pipeline.addLast(new WebHandler());\n }\n\n public static BotServer getInstance() {\n return instance;\n }\n}"
},
{
"identifier": "WinServer",
"path": "sdk-server/src/main/java/net/aibote/server/impl/WinServer.java",
"snippet": "public class WinServer extends BotServer {\n\n private static final WinServer instance = new WinServer();\n @Override\n public int getPort() {\n int port = 16999;\n return port;\n }\n\n @Override\n public void handlers(ChannelPipeline pipeline) {\n pipeline.addLast(new WinHandler());\n }\n\n public static BotServer getInstance() {\n return instance;\n }\n}"
}
] | import net.aibote.scripts.ScriptManager;
import net.aibote.server.impl.AndroidServer;
import net.aibote.server.impl.WebServer;
import net.aibote.server.impl.WinServer; | 694 | package net.aibote;
public class App {
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
AndroidServer.getInstance().start();
});
t1.start();
Thread t2 = new Thread(() -> {
WebServer.getInstance().start();
});
t2.start();
Thread t3 = new Thread(() -> {
WinServer.getInstance().start();
});
t3.start();
| package net.aibote;
public class App {
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
AndroidServer.getInstance().start();
});
t1.start();
Thread t2 = new Thread(() -> {
WebServer.getInstance().start();
});
t2.start();
Thread t3 = new Thread(() -> {
WinServer.getInstance().start();
});
t3.start();
| Thread scriptManager = Thread.ofVirtual().unstarted(new ScriptManager()); | 0 | 2023-11-08 14:31:58+00:00 | 2k |
LiedsonLB/BowllingJavaTestsJunit | Testbowling/Test/ValidTurn.java | [
{
"identifier": "InvalidTurn",
"path": "Testbowling/Exceptions/InvalidTurn.java",
"snippet": "public class InvalidTurn extends Exception{\n public InvalidTurn(){\n super(\"Jogada Invalida, numero de pinos acima do limite\");\n }\n}"
},
{
"identifier": "Game",
"path": "Testbowling/models/Game.java",
"snippet": "public class Game {\n private static int[] scoreBoard = new int[11];\n private static Turn[] roudsPrayer = new Turn[11];\n private int roudCurr;\n private int resultScoreBoard;\n\n // Game\n public Game(){\n this.roudCurr = 0;\n this.resultScoreBoard = 0;\n }\n\n // Verifica se a pontuação está zerada\n public boolean isEmpty(){\n for(int i = 0; i < 10; i++){\n if(scoreBoard[i] != 0){\n return false;\n }\n }\n return true;\n }\n\n // Adiciona a jogada\n public void add(Turn turnCurrent) throws InvalidTurn {\n // verifica se a jogada é invalida e lança uma exception\n if (turnCurrent.getTurnScore() > 10 && roudCurr != 9) {\n throw new InvalidTurn();\n }\n \n // adiciona jogada ao scoreboard\n roudsPrayer[roudCurr] = turnCurrent;\n scoreBoard[roudCurr] = turnCurrent.getTurnScore();\n\n // Verifica Strike seguido de Strike na 10ª rodada\n if (roudCurr == 9) {\n if (roudCurr > 0 && roudsPrayer[roudCurr - 1].turn1 == 10) {\n scoreBoard[roudCurr - 1] += turnCurrent.getTurnScore();\n if (turnCurrent.isStrike() && roudCurr > 1 && roudsPrayer[roudCurr - 2].turn1 == 10) {\n scoreBoard[roudCurr - 2] += turnCurrent.getTurn1();\n if (turnCurrent.isStrike() && roudCurr > 2 && roudsPrayer[roudCurr - 3].turn1 == 10) {\n scoreBoard[roudCurr - 3] += turnCurrent.getTurn1();\n }\n }\n }\n }\n \n // verifica Strike seguido de Strike\n if (roudCurr > 1 && roudsPrayer[roudCurr - 2].turn1 == 10 && roudsPrayer[roudCurr - 1].turn1 == 10) {\n scoreBoard[roudCurr - 2] += turnCurrent.getTurnScore();\n }\n\n // verifica Strike normal\n if (roudCurr > 0 && roudsPrayer[roudCurr - 1].turn1 == 10) {\n scoreBoard[roudCurr - 1] += turnCurrent.getTurnScore();\n }\n \n // verifica Spire\n if (roudCurr > 0 && roudsPrayer[roudCurr - 1].turn1 + roudsPrayer[roudCurr - 1].turn2 == 10 && roudsPrayer[roudCurr - 1].turn1 != 10) {\n scoreBoard[roudCurr - 1] += turnCurrent.getTurn1();\n }\n\n // verifica se é a ultima rodada e concede o bônus de spire\n if(roudCurr == 9) {\n if (roudCurr > 0 && roudsPrayer[roudCurr - 1].isSpare()) {\n scoreBoard[roudCurr] += turnCurrent.getTurn1();\n }\n }\n \n // proxima rodada\n roudCurr++;\n \n // Verifica se já acabou as 10 rodadas e soma a pontuação\n if (roudCurr == 10) {\n for (int i = 0; i < 10; i++) {\n resultScoreBoard += scoreBoard[i];\n System.out.println(\"Rodada \" + (i + 1) + \": \" + resultScoreBoard);\n }\n System.out.println(\"pontuação final: \" + resultScoreBoard);\n }\n }\n\n public int getResultScoreBoard(){\n return resultScoreBoard;\n }\n\n public int getRoudCurr(){\n return roudCurr;\n }\n}"
},
{
"identifier": "Turn",
"path": "Testbowling/models/Turn.java",
"snippet": "public class Turn {\n int turn1, turn2;\n\n public Turn(int turn1, int turn2){\n this.turn1 = turn1;\n this.turn2 = turn2;\n }\n\n public int getTurn1(){\n return turn1;\n }\n\n public int getTurn2(){\n return turn2;\n }\n\n public int getTurnScore(){\n if(turn1 == 10){\n \n }\n return turn1 + turn2;\n }\n\n // Strike\n public boolean isStrike(){\n if(turn1 == 10){\n return true;\n }\n return false;\n }\n\n // Spire\n public boolean isSpare(){\n if(turn1 + turn2 == 10 && turn1 != 10){\n return true;\n }\n return false;\n }\n}"
}
] | import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import Testbowling.Exceptions.InvalidTurn;
import Testbowling.models.Game;
import Testbowling.models.Turn; | 1,402 | package Testbowling.Test;
public class ValidTurn {
Game g = new Game();
@ParameterizedTest
@CsvSource({"10, 1","11, 1","13, 6","6, 5","7, 8","19, 0","8, 8","7, 7"}) // entre outros varios casos
public void invalidTurn(int a, int b) throws InvalidTurn{
assertThrows(InvalidTurn.class, () -> { | package Testbowling.Test;
public class ValidTurn {
Game g = new Game();
@ParameterizedTest
@CsvSource({"10, 1","11, 1","13, 6","6, 5","7, 8","19, 0","8, 8","7, 7"}) // entre outros varios casos
public void invalidTurn(int a, int b) throws InvalidTurn{
assertThrows(InvalidTurn.class, () -> { | g.add(new Turn(a, b)); | 2 | 2023-11-02 13:49:06+00:00 | 2k |
wuyu-wy/mgzm_volunteer | volunteer/src/main/java/com/blbd/volunteer/service/impl/TaskVolunteerImpl.java | [
{
"identifier": "TaskVolunteerEntityMapper",
"path": "volunteer/src/main/java/com/blbd/volunteer/dao/TaskVolunteerEntityMapper.java",
"snippet": "@Mapper\n@Repository\npublic interface TaskVolunteerEntityMapper {\n //接受任务\n int insert(TaskVolunteerEntity taskVolunteerEntity);\n\n //更新信息\n int updateNew(TaskVolunteerEntity taskVolunteerEntity);\n\n //更新志愿者任务信息\n int updateInfo(TaskVolunteerEntity taskVolunteerEntity);\n\n //志愿者评价任务\n int evaluateTask(TaskVolunteerEntity taskVolunteerEntity);\n\n //查询所有与志愿者未完成任务信息\n List<TaskVolunteerEntity> selectAll(TaskVolunteerEntity taskVolunteerEntity);\n\n //查询所有与未完成志愿者任务信息,模糊查询,根据taskName\n List<TaskVolunteerEntity> search(TaskVolunteerEntity taskVolunteerEntity);\n\n //查询所有已完成的任务信息\n List<TaskVolunteerEntity> finishTask(TaskVolunteerEntity taskVolunteerEntity);\n\n\n //查询所有与已完成志愿者任务信息,模糊查询,根据taskName\n List<TaskVolunteerEntity> finishSearchTask(TaskVolunteerEntity taskVolunteerEntity);\n\n //根据任务ID查询单一任务\n TaskVolunteerEntity selectOne(TaskVolunteerEntity taskVolunteerEntity);\n\n}"
},
{
"identifier": "TaskVolunteerEntity",
"path": "volunteer/src/main/java/com/blbd/volunteer/dao/entity/TaskVolunteerEntity.java",
"snippet": "@Data\npublic class TaskVolunteerEntity {\n private String volunteerId;\n private String childId;\n private String taskId;\n private Date approvalStartTime;\n private Date approvalFinishTime;\n private Date approvalEndTime;\n private byte isCompletedApproval;\n private String approvalComments;\n private String homeworkPhoto;\n private String taskPhoto;\n private String childName;\n private String taskName;\n private String taskVideo;\n private int getScore;\n}"
},
{
"identifier": "TaskVolunteerService",
"path": "volunteer/src/main/java/com/blbd/volunteer/service/TaskVolunteerService.java",
"snippet": "public interface TaskVolunteerService {\n\n\n\n\n int updateNew(TaskVolunteerEntity taskVolunteerEntity);\n\n\n}"
}
] | import com.blbd.volunteer.dao.TaskVolunteerEntityMapper;
import com.blbd.volunteer.dao.entity.TaskVolunteerEntity;
import com.blbd.volunteer.service.TaskVolunteerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List; | 655 | package com.blbd.volunteer.service.impl;
@Service
public class TaskVolunteerImpl implements TaskVolunteerService {
@Autowired
TaskVolunteerEntityMapper taskVolunteerEntityMapper;
//更新信息 | package com.blbd.volunteer.service.impl;
@Service
public class TaskVolunteerImpl implements TaskVolunteerService {
@Autowired
TaskVolunteerEntityMapper taskVolunteerEntityMapper;
//更新信息 | public int updateNew(TaskVolunteerEntity taskVolunteerEntity){ | 1 | 2023-11-02 05:55:45+00:00 | 2k |
baguchan/BetterWithAquatic | src/main/java/baguchan/better_with_aquatic/mixin/client/ModelPlayerMixin.java | [
{
"identifier": "ISwimModel",
"path": "src/main/java/baguchan/better_with_aquatic/api/ISwimModel.java",
"snippet": "public interface ISwimModel {\n\tEntity getEntity();\n\n\tvoid setEntity(Entity entity);\n}"
},
{
"identifier": "ISwiming",
"path": "src/main/java/baguchan/better_with_aquatic/api/ISwiming.java",
"snippet": "public interface ISwiming {\n\tvoid setSwimming(boolean swiming);\n\n\tboolean isSwimming();\n\n\tfloat getSwimAmount(float p_20999_);\n}"
},
{
"identifier": "MathUtil",
"path": "src/main/java/baguchan/better_with_aquatic/util/MathUtil.java",
"snippet": "public class MathUtil {\n\n\tpublic static float lerp(float p_14180_, float p_14181_, float p_14182_) {\n\t\treturn p_14181_ + p_14180_ * (p_14182_ - p_14181_);\n\t}\n}"
}
] | import baguchan.better_with_aquatic.api.ISwimModel;
import baguchan.better_with_aquatic.api.ISwiming;
import baguchan.better_with_aquatic.util.MathUtil;
import net.minecraft.client.render.model.Cube;
import net.minecraft.client.render.model.ModelBiped;
import net.minecraft.client.render.model.ModelPlayer;
import net.minecraft.core.entity.Entity;
import net.minecraft.core.util.helper.MathHelper;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; | 649 | package baguchan.better_with_aquatic.mixin.client;
@Mixin(value = ModelPlayer.class, remap = false)
public class ModelPlayerMixin extends ModelBiped implements ISwimModel {
@Shadow
public Cube bipedLeftArmOverlay;
@Shadow
public Cube bipedRightArmOverlay;
@Shadow
public Cube bipedLeftLegOverlay;
@Shadow
public Cube bipedRightLegOverlay;
@Shadow
public Cube bipedBodyOverlay;
private Entity entity;
@Inject(method = "setRotationAngles", at = @At("TAIL"))
public void setRotationAngles(float limbSwing, float limbYaw, float ticksExisted, float headYaw, float headPitch, float scale, CallbackInfo ci) {
if (entity instanceof ISwiming) {
float swimAmount = ((ISwiming) entity).getSwimAmount(ticksExisted - entity.tickCount);
if (swimAmount > 0.0F) {
float f5 = limbSwing % 26.0F;
float f1 = swimAmount;
float f2 = swimAmount;
if (f5 < 14.0F) {
this.bipedLeftArm.rotateAngleX = this.rotlerpRad(f2, this.bipedLeftArm.rotateAngleX, 0.0F); | package baguchan.better_with_aquatic.mixin.client;
@Mixin(value = ModelPlayer.class, remap = false)
public class ModelPlayerMixin extends ModelBiped implements ISwimModel {
@Shadow
public Cube bipedLeftArmOverlay;
@Shadow
public Cube bipedRightArmOverlay;
@Shadow
public Cube bipedLeftLegOverlay;
@Shadow
public Cube bipedRightLegOverlay;
@Shadow
public Cube bipedBodyOverlay;
private Entity entity;
@Inject(method = "setRotationAngles", at = @At("TAIL"))
public void setRotationAngles(float limbSwing, float limbYaw, float ticksExisted, float headYaw, float headPitch, float scale, CallbackInfo ci) {
if (entity instanceof ISwiming) {
float swimAmount = ((ISwiming) entity).getSwimAmount(ticksExisted - entity.tickCount);
if (swimAmount > 0.0F) {
float f5 = limbSwing % 26.0F;
float f1 = swimAmount;
float f2 = swimAmount;
if (f5 < 14.0F) {
this.bipedLeftArm.rotateAngleX = this.rotlerpRad(f2, this.bipedLeftArm.rotateAngleX, 0.0F); | this.bipedRightArm.rotateAngleX = MathUtil.lerp(f1, this.bipedRightArm.rotateAngleX, 0.0F); | 2 | 2023-11-08 23:02:14+00:00 | 2k |
Suff99/ExtraShells | common/src/main/java/mc/craig/software/extra_shells/mixins/GlobalShellRendererMixin.java | [
{
"identifier": "AnimationHackery",
"path": "common/src/main/java/mc/craig/software/extra_shells/AnimationHackery.java",
"snippet": "public interface AnimationHackery extends GeoAnimatable {\n\n @Nullable GlobalShellBlockEntity getShellEntity();\n @Nullable GlobalDoorBlockEntity getDoorEntity();\n}"
},
{
"identifier": "RenderShellGeo",
"path": "common/src/main/java/mc/craig/software/extra_shells/geo/RenderShellGeo.java",
"snippet": "public class RenderShellGeo extends GeoObjectRenderer<AnimationHackery> {\n\n public static RenderShellGeo INSTANCE = new RenderShellGeo();\n\n public RenderShellGeo() {\n super(new GeoShellModel());\n }\n\n @Override\n public void render(PoseStack poseStack, AnimationHackery animatable, MultiBufferSource bufferSource, RenderType renderType, VertexConsumer buffer, int packedLight) {\n poseStack.mulPose(Axis.YP.rotationDegrees(90));\n poseStack.translate(0, -0.5, 0);\n super.render(poseStack, animatable, bufferSource, renderType, buffer, packedLight);\n }\n}"
}
] | import com.mojang.blaze3d.vertex.PoseStack;
import mc.craig.software.extra_shells.AnimationHackery;
import mc.craig.software.extra_shells.geo.RenderShellGeo;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.resources.ResourceLocation;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import software.bernie.geckolib.animatable.GeoBlockEntity;
import software.bernie.geckolib.cache.object.BakedGeoModel;
import software.bernie.geckolib.core.animatable.GeoAnimatable;
import software.bernie.geckolib.core.animatable.instance.AnimatableInstanceCache;
import software.bernie.geckolib.core.animation.AnimatableManager;
import software.bernie.geckolib.model.GeoModel;
import software.bernie.geckolib.renderer.GeoRenderer;
import whocraft.tardis_refined.client.model.blockentity.shell.ShellModelCollection;
import whocraft.tardis_refined.client.renderer.blockentity.shell.GlobalShellRenderer;
import whocraft.tardis_refined.common.blockentity.shell.GlobalShellBlockEntity; | 699 | package mc.craig.software.extra_shells.mixins;
@Mixin(GlobalShellRenderer.class)
public class GlobalShellRendererMixin {
@Inject(cancellable = true, method = "render(Lwhocraft/tardis_refined/common/blockentity/shell/GlobalShellBlockEntity;FLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;II)V", at = @At(value = "HEAD"))
private void onRenderHead(GlobalShellBlockEntity blockEntity, float partialTicks, PoseStack matrixStack, MultiBufferSource buffer, int combinedLight, int combinedOverlay, CallbackInfo ci) {
if (blockEntity instanceof AnimationHackery geoAnimatable) {
if(ShellModelCollection.getInstance().getShellEntry(geoAnimatable.getShellEntity().theme()) == null) { | package mc.craig.software.extra_shells.mixins;
@Mixin(GlobalShellRenderer.class)
public class GlobalShellRendererMixin {
@Inject(cancellable = true, method = "render(Lwhocraft/tardis_refined/common/blockentity/shell/GlobalShellBlockEntity;FLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;II)V", at = @At(value = "HEAD"))
private void onRenderHead(GlobalShellBlockEntity blockEntity, float partialTicks, PoseStack matrixStack, MultiBufferSource buffer, int combinedLight, int combinedOverlay, CallbackInfo ci) {
if (blockEntity instanceof AnimationHackery geoAnimatable) {
if(ShellModelCollection.getInstance().getShellEntry(geoAnimatable.getShellEntity().theme()) == null) { | RenderShellGeo.INSTANCE.render(matrixStack, geoAnimatable, buffer, null, null, combinedLight); | 1 | 2023-11-04 22:53:31+00:00 | 2k |
By1337/BAuction | util/src/main/java/org/by1337/bauc/util/SyncDetectorManager.java | [
{
"identifier": "SyncDetector",
"path": "BaucApi/src/main/java/org/by1337/bauction/SyncDetector.java",
"snippet": "public interface SyncDetector {\n boolean isSync();\n}"
},
{
"identifier": "SyncDetectorV165",
"path": "nms/V1_16_5/src/main/java/org/by1337/v1_16_5/bauc/SyncDetectorV165.java",
"snippet": "public class SyncDetectorV165 implements SyncDetector {\n public boolean isSync(){\n return Thread.currentThread() == MinecraftServer.getServer().serverThread;\n }\n}"
},
{
"identifier": "SyncDetectorV171",
"path": "nms/V1_17_1/src/main/java/org/by1337/v1_17_1/bauc/SyncDetectorV171.java",
"snippet": "public class SyncDetectorV171 implements SyncDetector {\n public boolean isSync(){\n return Thread.currentThread() == MinecraftServer.getServer().serverThread;\n }\n}"
},
{
"identifier": "SyncDetectorV182",
"path": "nms/V1_18_2/src/main/java/org/by1337/v1_18_2/bauc/SyncDetectorV182.java",
"snippet": "public class SyncDetectorV182 implements SyncDetector {\n public boolean isSync(){\n return Thread.currentThread() == MinecraftServer.getServer().serverThread;\n }\n}"
},
{
"identifier": "SyncDetectorV194",
"path": "nms/V1_19_4/src/main/java/org/by1337/v1_19_4/bauc/SyncDetectorV194.java",
"snippet": "public class SyncDetectorV194 implements SyncDetector {\n public boolean isSync(){\n return Thread.currentThread() == MinecraftServer.getServer().serverThread;\n }\n}"
},
{
"identifier": "SyncDetectorV201",
"path": "nms/V1_20_1/src/main/java/org/by1337/v1_20_1/bauc/SyncDetectorV201.java",
"snippet": "public class SyncDetectorV201 implements SyncDetector {\n public boolean isSync(){\n return Thread.currentThread() == MinecraftServer.getServer().serverThread;\n }\n}"
},
{
"identifier": "SyncDetectorV202",
"path": "nms/V1_20_2/src/main/java/org/by1337/v1_20_2/bauc/SyncDetectorV202.java",
"snippet": "public class SyncDetectorV202 implements SyncDetector {\n public boolean isSync(){\n return Thread.currentThread() == MinecraftServer.getServer().serverThread;\n }\n}"
},
{
"identifier": "SyncDetectorV204",
"path": "nms/V1_20_4/src/main/java/org/by1337/v1_20_4/bauc/SyncDetectorV204.java",
"snippet": "public class SyncDetectorV204 implements SyncDetector {\n public boolean isSync(){\n return Thread.currentThread() == MinecraftServer.getServer().serverThread;\n }\n}"
}
] | import org.by1337.api.util.Version;
import org.by1337.bauction.SyncDetector;
import org.by1337.v1_16_5.bauc.SyncDetectorV165;
import org.by1337.v1_17_1.bauc.SyncDetectorV171;
import org.by1337.v1_18_2.bauc.SyncDetectorV182;
import org.by1337.v1_19_4.bauc.SyncDetectorV194;
import org.by1337.v1_20_1.bauc.SyncDetectorV201;
import org.by1337.v1_20_2.bauc.SyncDetectorV202;
import org.by1337.v1_20_4.bauc.SyncDetectorV204; | 741 | package org.by1337.bauc.util;
public class SyncDetectorManager {
private final static SyncDetector syncDetector;
static {
syncDetector = switch (Version.VERSION) {
case V1_16_5 -> new SyncDetectorV165(); | package org.by1337.bauc.util;
public class SyncDetectorManager {
private final static SyncDetector syncDetector;
static {
syncDetector = switch (Version.VERSION) {
case V1_16_5 -> new SyncDetectorV165(); | case V1_17_1 -> new SyncDetectorV171(); | 2 | 2023-11-08 18:25:18+00:00 | 2k |
Svydovets-Bobocode-Java-Ultimate-3-0/Bring | src/test/java/com/bobocode/svydovets/source/config/BasePackageWithAdditionalBeansConfig.java | [
{
"identifier": "CopyService",
"path": "src/test/java/com/bobocode/svydovets/source/autowire/method/CopyService.java",
"snippet": "@Component\npublic class CopyService {\n}"
},
{
"identifier": "OrderService",
"path": "src/test/java/com/bobocode/svydovets/source/autowire/method/OrderService.java",
"snippet": "@Component\npublic class OrderService {\n\n private MessageService messageService;\n private CommonService commonService;\n private NullService nullService;\n\n\n @Autowired\n public void setMessageService(MessageService messageService, CommonService commonService) {\n this.messageService = messageService;\n this.commonService = commonService;\n }\n\n //should not have @Autowired for test purpose\n public void setNullService(NullService nullService) {\n this.nullService = nullService;\n }\n\n\n public NullService getNullService() {\n return nullService;\n }\n\n\n public CommonService getCommonService() {\n return commonService;\n }\n\n public MessageService getMessageService() {\n return messageService;\n }\n\n\n}"
},
{
"identifier": "PrintLnService",
"path": "src/test/java/com/bobocode/svydovets/source/autowire/method/PrintLnService.java",
"snippet": "@Component\npublic class PrintLnService {\n\n}"
},
{
"identifier": "TrimService",
"path": "src/test/java/com/bobocode/svydovets/source/autowire/method/TrimService.java",
"snippet": "public class TrimService {\n private CommonService commonService;\n\n public CommonService getCommonService() {\n return commonService;\n }\n\n @Autowired\n public void setCommonService(CommonService commonService) {\n this.commonService = commonService;\n }\n}"
},
{
"identifier": "ApplicationContext",
"path": "src/main/java/svydovets/core/context/ApplicationContext.java",
"snippet": "public interface ApplicationContext {\r\n\r\n /**\r\n * Constant defines scope of bean as singleton.\r\n */\r\n String SCOPE_SINGLETON = \"singleton\";\r\n\r\n /**\r\n * Constant defines scope of bean as prototype.\r\n */\r\n String SCOPE_PROTOTYPE = \"prototype\";\r\n\r\n /**\r\n * Retrieve bean by its class type.\r\n *\r\n * @param <T> generic class type of bean\r\n * @param requiredType class type bean must match\r\n * @return an instance of the single bean matching the required type\r\n */\r\n <T> T getBean(Class<T> requiredType);\r\n\r\n /**\r\n * Retrieve bean by its name and class type.\r\n *\r\n * @param <T> generic class type of bean\r\n * @param name name of bean to retrieve\r\n * @param requiredType class type bean must match\r\n * @return an instance of the single bean matching the required type\r\n */\r\n <T> T getBean(String name, Class<T> requiredType);\r\n\r\n /**\r\n * Retrieve beans of a certain type.\r\n *\r\n * @param <T> generic class type of bean\r\n * @param requiredType class type bean must match\r\n * @return a map with matching beans, containing bean names as keys and corresponding bean instances as values\r\n */\r\n <T> Map<String, T> getBeansOfType(Class<T> requiredType);\r\n\r\n /**\r\n * Retrieve all beans present in the application context.\r\n *\r\n * @return a map with all beans, containing bean names as keys and corresponding bean instances as values\r\n */\r\n Map<String, Object> getBeans();\r\n}\r"
}
] | import com.bobocode.svydovets.source.autowire.method.CopyService;
import com.bobocode.svydovets.source.autowire.method.OrderService;
import com.bobocode.svydovets.source.autowire.method.PrintLnService;
import com.bobocode.svydovets.source.autowire.method.TrimService;
import svydovets.core.annotation.Bean;
import svydovets.core.annotation.ComponentScan;
import svydovets.core.annotation.Configuration;
import svydovets.core.annotation.Scope;
import svydovets.core.context.ApplicationContext; | 1,070 | package com.bobocode.svydovets.source.config;
@Configuration
@ComponentScan("com.bobocode.svydovets.source.base")
public class BasePackageWithAdditionalBeansConfig {
@Bean("megaTrimService")
public TrimService trimService() {
return new TrimService();
}
@Bean
public OrderService orderService() {
return new OrderService();
}
@Bean
@Scope
public CopyService copyService() {
return new CopyService();
}
@Bean
@Scope(ApplicationContext.SCOPE_PROTOTYPE) | package com.bobocode.svydovets.source.config;
@Configuration
@ComponentScan("com.bobocode.svydovets.source.base")
public class BasePackageWithAdditionalBeansConfig {
@Bean("megaTrimService")
public TrimService trimService() {
return new TrimService();
}
@Bean
public OrderService orderService() {
return new OrderService();
}
@Bean
@Scope
public CopyService copyService() {
return new CopyService();
}
@Bean
@Scope(ApplicationContext.SCOPE_PROTOTYPE) | public PrintLnService printLnService() { | 2 | 2023-11-07 06:36:50+00:00 | 2k |
oneqxz/RiseLoader | src/main/java/me/oneqxz/riseloader/fxml/components/impl/ErrorBox.java | [
{
"identifier": "FX",
"path": "src/main/java/me/oneqxz/riseloader/fxml/FX.java",
"snippet": "public class FX {\n\n private static double xOffset = 0;\n private static double yOffset = 0;\n\n private static final Logger logger = LogManager.getLogger(\"FXUtils\");\n\n public static void showScene(String title, String resource, Stage primaryStage, Controller controller) throws IOException {\n showScene(title, resource, primaryStage, controller, null);\n }\n public static void showScene(String title, String resource, Stage primaryStage) throws IOException {\n showScene(title, resource, primaryStage, null, null);\n }\n\n public static void showScene(String title, String resource, Stage primaryStage, Controller controller, Consumer<Parent> runnable) throws IOException {\n Scene scene = createNewScene(resource, controller, primaryStage);\n showScene(scene, title, primaryStage, runnable);\n }\n\n public static void showScene(Scene scene, String title, Stage primaryStage, Consumer<Parent> runnable) throws IOException {\n primaryStage.setScene(scene);\n primaryStage.initStyle(StageStyle.TRANSPARENT);\n\n primaryStage.setTitle(title);\n primaryStage.setResizable(false);\n\n primaryStage.getIcons().add(new javafx.scene.image.Image(\"/logo.png\"));\n\n primaryStage.show();\n\n if(runnable != null)\n runnable.accept(scene.getRoot());\n }\n\n public static Scene createNewScene(String resource, Controller controller, Stage stage) throws IOException {\n Scene scene = new Scene(createNewParent(resource, controller, stage));\n scene.setFill(Color.TRANSPARENT);\n new FadeIn(scene.getRoot()).play();\n\n logger.info(\"JavaFX scene will created with name \" + resource);\n return scene;\n }\n\n public static Parent createNewParent(String resource, Controller controller, Stage stage) throws IOException {\n FXMLLoader loader = new FXMLLoader(FX.class.getResource(\"/fxml/\" + resource));\n if(controller != null)\n loader.setController(controller);\n\n Parent root = loader.load();\n\n logger.debug(\"JavaFX parent will created with name \" + resource);\n\n if(controller != null)\n controller.init(root, stage);\n\n return root;\n }\n\n public static void setTimeout(Runnable runnable, Duration duration) {\n Timeline timeline = new Timeline(new KeyFrame(duration, event -> {\n runnable.run();\n }));\n timeline.play();\n }\n\n public static void setDraggable(Scene scene, String paneId)\n {\n Node root = scene.getRoot().lookup(\"#\" + paneId);\n\n root.setOnMousePressed((event) ->\n {\n xOffset = event.getSceneX();\n yOffset = event.getSceneY();\n });\n root.setOnMouseReleased((event) ->\n {\n xOffset = 0;\n yOffset = 0;\n });\n root.setOnMouseDragged((event) ->\n {\n Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow();\n stage.setX(event.getScreenX() - xOffset);\n stage.setY(event.getScreenY() - yOffset);\n });\n }\n\n public static void setMinimizeAndClose(Stage stage, String minimiseID, String closeID)\n {\n setMinimizeAndClose(stage, minimiseID, closeID, false);\n }\n\n public static void setMinimizeAndClose(Stage stage, String minimiseID, String closeID, boolean closeProgram)\n {\n setMinimizeAndClose(stage, minimiseID, closeID, null, closeProgram, false);\n }\n\n public static void setMinimizeAndClose(Stage stage, String minimiseID, String closeID, Runnable onClose, boolean closeProgram, boolean hideScene)\n {\n Node min = stage.getScene().getRoot().lookup(\"#\" + minimiseID);\n Node close = stage.getScene().getRoot().lookup(\"#\" + closeID);\n\n min.setOnMouseClicked((event) -> stage.setIconified(true));\n close.setOnMouseClicked((event) ->\n {\n if(hideScene)\n stage.hide();\n else stage.close();\n\n if(onClose != null)\n onClose.run();\n\n if(closeProgram)\n {\n logger.info(\"Goodbye!\");\n System.exit(0);\n }\n });\n }\n}"
},
{
"identifier": "Component",
"path": "src/main/java/me/oneqxz/riseloader/fxml/components/Component.java",
"snippet": "public abstract class Component {\n\n public abstract Stage show(Object... args) throws IOException;\n public static void close(Stage stage)\n {\n stage.close();\n }\n}"
},
{
"identifier": "ErrorBoxController",
"path": "src/main/java/me/oneqxz/riseloader/fxml/components/impl/controllers/ErrorBoxController.java",
"snippet": "public class ErrorBoxController extends Controller {\n\n private Throwable exception;\n\n public ErrorBoxController(Throwable e)\n {\n this.exception = e;\n }\n\n Label message;\n TextArea stacktrace;\n\n @Override\n protected void init() {\n message = (Label) root.lookup(\"#errorMessage\");\n stacktrace = (TextArea) root.lookup(\"#stacktrace\");\n\n message.setText(exception.getMessage());\n stacktrace.setText(printStacktrace(exception).toString());\n }\n\n private StringBuilder printStacktrace(Throwable throwable)\n {\n\n StringWriter sw = new StringWriter();\n PrintWriter pw = new PrintWriter(sw);\n throwable.printStackTrace(pw);\n String stackTraceString = sw.toString();\n\n StringBuilder sb = new StringBuilder();\n String[] stackTraceLines = stackTraceString.split(System.lineSeparator());\n\n sb.append(stackTraceLines[0]).append(\"\\n\");\n for(int i = 1; i < stackTraceLines.length; i++)\n {\n String str = stackTraceLines[i];\n sb.append(str);\n\n if(i < stackTraceLines.length - 1)\n sb.append(\"\\n\");\n }\n\n return sb;\n }\n\n}"
}
] | import javafx.stage.Stage;
import me.oneqxz.riseloader.fxml.FX;
import me.oneqxz.riseloader.fxml.components.Component;
import me.oneqxz.riseloader.fxml.components.impl.controllers.ErrorBoxController;
import java.io.IOException; | 1,480 | package me.oneqxz.riseloader.fxml.components.impl;
public class ErrorBox extends Component {
@Override
public Stage show(Object... args) {
try {
Stage stage = new Stage(); | package me.oneqxz.riseloader.fxml.components.impl;
public class ErrorBox extends Component {
@Override
public Stage show(Object... args) {
try {
Stage stage = new Stage(); | FX.showScene("RiseLoader error", "error.fxml", stage, new ErrorBoxController((Throwable) args[0])); | 0 | 2023-11-01 01:40:52+00:00 | 2k |
YufiriaMazenta/CrypticLib | nms/shaded/src/main/java/crypticlib/nms/entity/v1_14_R1/V1_14_R1NbtEntity.java | [
{
"identifier": "NbtEntity",
"path": "nms/common/src/main/java/crypticlib/nms/entity/NbtEntity.java",
"snippet": "public abstract class NbtEntity {\n\n protected NbtTagCompound nbtTagCompound;\n protected Entity bukkit;\n\n protected NbtEntity(Entity entity) {\n this.bukkit = entity;\n fromBukkit();\n }\n\n public NbtTagCompound nbtTagCompound() {\n return nbtTagCompound;\n }\n\n public NbtEntity setNbtTagCompound(NbtTagCompound nbtTagCompound) {\n this.nbtTagCompound = nbtTagCompound;\n return this;\n }\n\n public Entity bukkit() {\n return bukkit;\n }\n\n public NbtEntity setBukkitEntity(Entity bukkit) {\n this.bukkit = bukkit;\n return this;\n }\n\n public abstract NbtEntity saveNbtToEntity();\n\n public abstract void fromBukkit();\n\n public HoverEvent toHover() {\n return new HoverEvent(\n HoverEvent.Action.SHOW_ENTITY,\n new net.md_5.bungee.api.chat.hover.content.Entity(\n bukkit.getType().getKey().toString(),\n bukkit.getUniqueId().toString(),\n new TextComponent(TextComponent.fromLegacyText(bukkit.getName()))\n )\n );\n }\n\n}"
},
{
"identifier": "V1_14_R1NbtTagCompound",
"path": "nms/shaded/src/main/java/crypticlib/nms/nbt/v1_14_R1/V1_14_R1NbtTagCompound.java",
"snippet": "public class V1_14_R1NbtTagCompound extends NbtTagCompound {\n\n public V1_14_R1NbtTagCompound() {\n super(V1_14_R1NbtTranslator.INSTANCE);\n }\n\n public V1_14_R1NbtTagCompound(Object nmsNbtCompound) {\n super(nmsNbtCompound, V1_14_R1NbtTranslator.INSTANCE);\n }\n\n public V1_14_R1NbtTagCompound(Map<String, Object> nbtValueMap) {\n super(nbtValueMap, V1_14_R1NbtTranslator.INSTANCE);\n }\n\n public V1_14_R1NbtTagCompound(String mojangson) {\n super(mojangson, V1_14_R1NbtTranslator.INSTANCE);\n }\n\n @Override\n public void fromNms(@NotNull Object nmsNbt) {\n NBTTagCompound nms = (NBTTagCompound) nmsNbt;\n nbtMap.clear();\n for (String key : nms.getKeys()) {\n nbtMap.put(key, nbtTranslator.translateNmsNbt(nms.get(key)));\n }\n }\n\n @Override\n public @NotNull NBTTagCompound toNms() {\n NBTTagCompound nbtTagCompound = new NBTTagCompound();\n for (String key : nbtMap.keySet()) {\n nbtTagCompound.set(key, (NBTBase) get(key).toNms());\n }\n return nbtTagCompound;\n }\n\n @Override\n public void fromMojangson(String mojangson) {\n try {\n fromNms(MojangsonParser.parse(mojangson));\n } catch (Throwable e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public NbtTagCompound clone() {\n return new V1_14_R1NbtTagCompound(toString());\n }\n\n}"
}
] | import crypticlib.nms.entity.NbtEntity;
import crypticlib.nms.nbt.v1_14_R1.V1_14_R1NbtTagCompound;
import net.minecraft.server.v1_14_R1.NBTTagCompound;
import org.bukkit.craftbukkit.v1_14_R1.entity.CraftEntity;
import org.bukkit.entity.Entity; | 1,092 | package crypticlib.nms.entity.v1_14_R1;
public class V1_14_R1NbtEntity extends NbtEntity {
public V1_14_R1NbtEntity(Entity entity) {
super(entity);
}
@Override
public NbtEntity saveNbtToEntity() {
net.minecraft.server.v1_14_R1.Entity nmsEntity = ((CraftEntity) bukkit).getHandle();
nmsEntity.f((NBTTagCompound) nbtTagCompound.toNms());
return this;
}
@Override
public void fromBukkit() {
net.minecraft.server.v1_14_R1.Entity nmsEntity = ((CraftEntity) bukkit).getHandle();
NBTTagCompound nmsNbt = new NBTTagCompound(); | package crypticlib.nms.entity.v1_14_R1;
public class V1_14_R1NbtEntity extends NbtEntity {
public V1_14_R1NbtEntity(Entity entity) {
super(entity);
}
@Override
public NbtEntity saveNbtToEntity() {
net.minecraft.server.v1_14_R1.Entity nmsEntity = ((CraftEntity) bukkit).getHandle();
nmsEntity.f((NBTTagCompound) nbtTagCompound.toNms());
return this;
}
@Override
public void fromBukkit() {
net.minecraft.server.v1_14_R1.Entity nmsEntity = ((CraftEntity) bukkit).getHandle();
NBTTagCompound nmsNbt = new NBTTagCompound(); | this.setNbtTagCompound(new V1_14_R1NbtTagCompound(nmsEntity.save(nmsNbt))); | 1 | 2023-11-07 12:39:20+00:00 | 2k |