prefix
stringlengths
82
32.6k
middle
stringlengths
5
470
suffix
stringlengths
0
81.2k
file_path
stringlengths
6
168
repo_name
stringlengths
16
77
context
listlengths
5
5
lang
stringclasses
4 values
ground_truth
stringlengths
5
470
/* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.googlecodesamples.cloud.jss.lds.service; import com.googlecodesamples.cloud.jss.lds.model.BaseFile; import com.googlecodesamples.cloud.jss.lds.model.FileMeta; import com.googlecodesamples.cloud.jss.lds.util.LdsUtil; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import net.coobird.thumbnailator.Thumbnails; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; /** Backend service controller for Firestore and CloudStorage */ @Service public class FileService { private static final Logger log = LoggerFactory.getLogger(FirestoreService.class); private static final int THUMBNAIL_SIZE = 300; private final FirestoreService firestoreService; private final StorageService storageService; @Value("${resource.path}") private String basePath; @Value("${storage.bucket.name}") private String bucketName; public FileService(FirestoreService firestoreService, StorageService storageService) { this.firestoreService = firestoreService; this.storageService = storageService; } /** * Upload files to Firestore and Cloud Storage. * * @param files list of files upload to the server * @param tags list of tags label the files * @return list of uploaded files */ public List<BaseFile> uploadFiles(List<MultipartFile> files, List<String> tags) throws InterruptedException, ExecutionException, IOException { log.info("entering uploadFiles()"); List<BaseFile> fileList = new ArrayList<>(); for (MultipartFile file : files) { String fileId = LdsUtil.generateUuid(); BaseFile newFile = createOrUpdateFile(file, tags, fileId, fileId, file.getSize()); fileList.add(newFile); } return fileList; } /** * Update a file to Firestore and Cloud Storage. * * @param newFile new file upload to the server * @param tags list of tags label the new file * @param file previously uploaded file * @return the updated file */ public BaseFile updateFile(MultipartFile newFile, List<String> tags, BaseFile file) throws InterruptedException, ExecutionException, IOException { log.info("entering updateFile()"); String fileId = file.getId(); if (newFile == null) { String pathId = LdsUtil.getPathId(file.getPath()); return createOrUpdateFileMeta(tags, fileId, pathId, file.getName(), file.getSize()); } storageService.delete(bucketName, file.getPath()); storageService.delete(bucketName, file.genThumbnailPath()); String newFileId = LdsUtil.generateUuid(); return createOrUpdateFile(newFile, tags, fileId, newFileId, newFile.getSize()); } /** * Delete a file from Firestore and Cloud Storage. * * @param file the uploaded file */ public void deleteFile(BaseFile file) throws InterruptedException, ExecutionException { log.info("entering deleteFile()"); firestoreService.delete(file.getId()); storageService.delete(bucketName, file.getPath()); storageService.delete(bucketName, file.genThumbnailPath()); } /** * Search files with given tags. * * @param tags list of tags label the files * @param orderNo application defined column for referencing order * @param size number of files return * @return list of uploaded files */ public List<BaseFile> getFilesByTag(List<String> tags, String orderNo, int size) throws InterruptedException, ExecutionException { log.info("entering getFilesByTag()"); return firestoreService.getFilesByTag(tags, orderNo, size); } /** * Search a single file with given fileId. * * @param fileId unique id of the file * @return the uploaded file */ public BaseFile getFileById(String fileId) throws InterruptedException, ExecutionException { log.info("entering getFileById()"); return firestoreService.getFileById(fileId); } /** Delete all files from Firestore and Cloud Storage. */ public void resetFile() throws InterruptedException, ExecutionException { log.info("entering resetFile()"); firestoreService.deleteCollection(); storageService.batchDelete(bucketName); } /** * Create or update a file in Cloud Storage with the given fileId. * * @param file file upload to the server * @param tags list of tags label the file * @param fileId unique ID of the file * @param newFileId unique ID of the new file (for referencing Cloud Storage) * @param size size of the file * @return file data */ private BaseFile createOrUpdateFile( MultipartFile file, List<String> tags, String fileId, String newFileId, long size) throws InterruptedException, ExecutionException, IOException { BaseFile newFile = createOrUpdateFileMeta(tags, fileId, newFileId, file.getOriginalFilename(), size); storageService.save(bucketName, newFile.getPath(), file.getContentType(), file.getBytes()); if (newFile.checkImageFileType()) { createThumbnail(file, newFile.genThumbnailPath()); } return newFile; } /** * Create or update the metadata of a file in Firestore with the given fileId. * * @param tags list of tags label the file * @param fileId unique id of the file * @param newFileId unique id of the new file (for referencing Cloud Storage) * @param fileName name of the file * @param size size of the file * @return file data */ private BaseFile createOrUpdateFileMeta( List<String> tags, String fileId, String newFileId, String fileName, long size) throws InterruptedException, ExecutionException { String fileBucketPath
= LdsUtil.getFileBucketPath(basePath, newFileId);
FileMeta fileMeta = new FileMeta(fileId, fileBucketPath, fileName, tags, size); firestoreService.save(fileMeta); return getFileById(fileId); } /** * Create a thumbnail of the given file. * * @param file file to create thumbnail * @param thumbnailId unique id of the thumbnail file */ private void createThumbnail(MultipartFile file, String thumbnailId) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Thumbnails.of(file.getInputStream()) .size(THUMBNAIL_SIZE, THUMBNAIL_SIZE) .keepAspectRatio(false) .toOutputStream(byteArrayOutputStream); storageService.save( bucketName, thumbnailId, file.getContentType(), byteArrayOutputStream.toByteArray()); } }
api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FileService.java
GoogleCloudPlatform-app-large-data-sharing-java-fd21141
[ { "filename": "api/src/test/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreServiceIT.java", "retrieved_chunk": " }\n private FileMeta createFileMeta() {\n return new FileMeta(\n FILE_META_ID, FILE_META_PATH, FILE_META_NAME, FILE_META_TAGS, FILE_META_SIZE);\n }\n}", "score": 0.8603378534317017 }, { "filename": "api/src/test/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreServiceIT.java", "retrieved_chunk": " private static final String FILE_META_PATH = \"resource/test-id\";\n private static final String FILE_META_NAME = \"test\";\n private static final List<String> FILE_META_TAGS = List.of(\"test-tag\");\n private static final long FILE_META_SIZE = 100;\n private static final int LIST_SIZE = 10;\n @Autowired\n FirestoreService firestoreService;\n @Test\n public void testSaveFileMeta() throws InterruptedException, ExecutionException {\n try {", "score": 0.8554339408874512 }, { "filename": "api/src/test/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreServiceIT.java", "retrieved_chunk": " firestoreService.save(createFileMeta());\n BaseFile testFile = firestoreService.getFileById(FILE_META_ID);\n assertThat(testFile).isNotNull();\n } finally {\n firestoreService.delete(FILE_META_ID);\n }\n }\n @Test\n public void testGetFileById() throws InterruptedException, ExecutionException {\n try {", "score": 0.8380634188652039 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/controller/FileController.java", "retrieved_chunk": " * @param fileId unique ID of the file\n * @param file new file to be uploaded to the server\n * @param tags list of tags (separated by space) label the new file\n * @return file data\n */\n @PutMapping(\"/files/{id}\")\n public ResponseEntity<?> updateFile(\n @PathVariable(\"id\") String fileId,\n @RequestParam(required = false) MultipartFile file,\n @RequestParam String tags) throws Exception {", "score": 0.8253523111343384 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/model/FileMeta.java", "retrieved_chunk": " public FileMeta(String id, String path, String name, List<String> tags, long size) {\n this.id = id;\n this.path = path;\n this.name = name;\n this.tags = tags;\n this.orderNo = System.currentTimeMillis() + \"-\" + LdsUtil.getPathId(path);\n this.size = size;\n }\n public String getId() {\n return id;", "score": 0.8244538903236389 } ]
java
= LdsUtil.getFileBucketPath(basePath, newFileId);
/* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.googlecodesamples.cloud.jss.lds.service; import com.googlecodesamples.cloud.jss.lds.model.BaseFile; import com.googlecodesamples.cloud.jss.lds.model.FileMeta; import com.googlecodesamples.cloud.jss.lds.util.LdsUtil; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import net.coobird.thumbnailator.Thumbnails; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; /** Backend service controller for Firestore and CloudStorage */ @Service public class FileService { private static final Logger log = LoggerFactory.getLogger(FirestoreService.class); private static final int THUMBNAIL_SIZE = 300; private final FirestoreService firestoreService; private final StorageService storageService; @Value("${resource.path}") private String basePath; @Value("${storage.bucket.name}") private String bucketName; public FileService(FirestoreService firestoreService, StorageService storageService) { this.firestoreService = firestoreService; this.storageService = storageService; } /** * Upload files to Firestore and Cloud Storage. * * @param files list of files upload to the server * @param tags list of tags label the files * @return list of uploaded files */ public List<BaseFile> uploadFiles(List<MultipartFile> files, List<String> tags) throws InterruptedException, ExecutionException, IOException { log.info("entering uploadFiles()"); List<BaseFile> fileList = new ArrayList<>(); for (MultipartFile file : files) { String fileId = LdsUtil.generateUuid(); BaseFile newFile = createOrUpdateFile(file, tags, fileId, fileId, file.getSize()); fileList.add(newFile); } return fileList; } /** * Update a file to Firestore and Cloud Storage. * * @param newFile new file upload to the server * @param tags list of tags label the new file * @param file previously uploaded file * @return the updated file */ public BaseFile updateFile(MultipartFile newFile, List<String> tags, BaseFile file) throws InterruptedException, ExecutionException, IOException { log.info("entering updateFile()"); String fileId = file.getId(); if (newFile == null) { String pathId = LdsUtil.getPathId(file.getPath()); return createOrUpdateFileMeta(tags, fileId, pathId, file.getName(), file.getSize()); } storageService.delete(bucketName, file.getPath()); storageService.delete(bucketName, file.genThumbnailPath()); String newFileId = LdsUtil.generateUuid(); return createOrUpdateFile(newFile, tags, fileId, newFileId, newFile.getSize()); } /** * Delete a file from Firestore and Cloud Storage. * * @param file the uploaded file */ public void deleteFile(BaseFile file) throws InterruptedException, ExecutionException { log.info("entering deleteFile()"); firestoreService.delete(file.getId()); storageService.delete(bucketName, file.getPath()); storageService.delete(bucketName, file.genThumbnailPath()); } /** * Search files with given tags. * * @param tags list of tags label the files * @param orderNo application defined column for referencing order * @param size number of files return * @return list of uploaded files */ public List<BaseFile> getFilesByTag(List<String> tags, String orderNo, int size) throws InterruptedException, ExecutionException { log.info("entering getFilesByTag()"); return firestoreService.getFilesByTag(tags, orderNo, size); } /** * Search a single file with given fileId. * * @param fileId unique id of the file * @return the uploaded file */ public BaseFile getFileById(String fileId) throws InterruptedException, ExecutionException { log.info("entering getFileById()"); return firestoreService.getFileById(fileId); } /** Delete all files from Firestore and Cloud Storage. */ public void resetFile() throws InterruptedException, ExecutionException { log.info("entering resetFile()"); firestoreService.deleteCollection(); storageService.batchDelete(bucketName); } /** * Create or update a file in Cloud Storage with the given fileId. * * @param file file upload to the server * @param tags list of tags label the file * @param fileId unique ID of the file * @param newFileId unique ID of the new file (for referencing Cloud Storage) * @param size size of the file * @return file data */ private BaseFile createOrUpdateFile( MultipartFile file, List<String> tags, String fileId, String newFileId, long size) throws InterruptedException, ExecutionException, IOException { BaseFile newFile = createOrUpdateFileMeta(tags, fileId, newFileId, file.getOriginalFilename(), size); storageService.save(bucketName, newFile.getPath(), file.getContentType(), file.getBytes()); if
(newFile.checkImageFileType()) {
createThumbnail(file, newFile.genThumbnailPath()); } return newFile; } /** * Create or update the metadata of a file in Firestore with the given fileId. * * @param tags list of tags label the file * @param fileId unique id of the file * @param newFileId unique id of the new file (for referencing Cloud Storage) * @param fileName name of the file * @param size size of the file * @return file data */ private BaseFile createOrUpdateFileMeta( List<String> tags, String fileId, String newFileId, String fileName, long size) throws InterruptedException, ExecutionException { String fileBucketPath = LdsUtil.getFileBucketPath(basePath, newFileId); FileMeta fileMeta = new FileMeta(fileId, fileBucketPath, fileName, tags, size); firestoreService.save(fileMeta); return getFileById(fileId); } /** * Create a thumbnail of the given file. * * @param file file to create thumbnail * @param thumbnailId unique id of the thumbnail file */ private void createThumbnail(MultipartFile file, String thumbnailId) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Thumbnails.of(file.getInputStream()) .size(THUMBNAIL_SIZE, THUMBNAIL_SIZE) .keepAspectRatio(false) .toOutputStream(byteArrayOutputStream); storageService.save( bucketName, thumbnailId, file.getContentType(), byteArrayOutputStream.toByteArray()); } }
api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FileService.java
GoogleCloudPlatform-app-large-data-sharing-java-fd21141
[ { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/controller/FileController.java", "retrieved_chunk": " * @param fileId unique ID of the file\n * @param file new file to be uploaded to the server\n * @param tags list of tags (separated by space) label the new file\n * @return file data\n */\n @PutMapping(\"/files/{id}\")\n public ResponseEntity<?> updateFile(\n @PathVariable(\"id\") String fileId,\n @RequestParam(required = false) MultipartFile file,\n @RequestParam String tags) throws Exception {", "score": 0.8583545684814453 }, { "filename": "api/src/test/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreServiceIT.java", "retrieved_chunk": " }\n private FileMeta createFileMeta() {\n return new FileMeta(\n FILE_META_ID, FILE_META_PATH, FILE_META_NAME, FILE_META_TAGS, FILE_META_SIZE);\n }\n}", "score": 0.8549318313598633 }, { "filename": "api/src/test/java/com/googlecodesamples/cloud/jss/lds/service/FileServiceTest.java", "retrieved_chunk": " public void testUpdateFile() throws InterruptedException, ExecutionException, IOException {\n BaseFile file = fileService.updateFile(mockMultipartFiles.get(0), TAGS, mockFiles.get(0));\n assertThat(file).isNotNull();\n assertThat(file.checkImageFileType()).isTrue();\n assertThat(file.getTags()).isEqualTo(TAGS);\n }\n @Test\n public void testGetFilesByTag() throws InterruptedException, ExecutionException {\n List<BaseFile> files = fileService.getFilesByTag(TAGS, ORDER_NUM, LIST_SIZE);\n assertThat(files).isNotEmpty();", "score": 0.8542460203170776 }, { "filename": "api/src/test/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreServiceIT.java", "retrieved_chunk": " private static final String FILE_META_PATH = \"resource/test-id\";\n private static final String FILE_META_NAME = \"test\";\n private static final List<String> FILE_META_TAGS = List.of(\"test-tag\");\n private static final long FILE_META_SIZE = 100;\n private static final int LIST_SIZE = 10;\n @Autowired\n FirestoreService firestoreService;\n @Test\n public void testSaveFileMeta() throws InterruptedException, ExecutionException {\n try {", "score": 0.849554181098938 }, { "filename": "api/src/test/java/com/googlecodesamples/cloud/jss/lds/service/FileServiceTest.java", "retrieved_chunk": " }\n @Test\n public void testUploadFiles() throws InterruptedException, ExecutionException, IOException {\n List<BaseFile> files = fileService.uploadFiles(mockMultipartFiles, TAGS);\n assertThat(files).isNotEmpty();\n assertThat(files.size()).isEqualTo(LIST_SIZE);\n assertThat(files.get(0).checkImageFileType()).isTrue();\n assertThat(files.get(0).getTags()).isEqualTo(TAGS);\n }\n @Test", "score": 0.8485914468765259 } ]
java
(newFile.checkImageFileType()) {
/* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.googlecodesamples.cloud.jss.lds.service; import com.googlecodesamples.cloud.jss.lds.model.BaseFile; import com.googlecodesamples.cloud.jss.lds.model.FileMeta; import com.googlecodesamples.cloud.jss.lds.util.LdsUtil; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import net.coobird.thumbnailator.Thumbnails; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; /** Backend service controller for Firestore and CloudStorage */ @Service public class FileService { private static final Logger log = LoggerFactory.getLogger(FirestoreService.class); private static final int THUMBNAIL_SIZE = 300; private final FirestoreService firestoreService; private final StorageService storageService; @Value("${resource.path}") private String basePath; @Value("${storage.bucket.name}") private String bucketName; public FileService(FirestoreService firestoreService, StorageService storageService) { this.firestoreService = firestoreService; this.storageService = storageService; } /** * Upload files to Firestore and Cloud Storage. * * @param files list of files upload to the server * @param tags list of tags label the files * @return list of uploaded files */ public List<BaseFile> uploadFiles(List<MultipartFile> files, List<String> tags) throws InterruptedException, ExecutionException, IOException { log.info("entering uploadFiles()"); List<BaseFile> fileList = new ArrayList<>(); for (MultipartFile file : files) { String fileId = LdsUtil.generateUuid(); BaseFile newFile = createOrUpdateFile(file, tags, fileId, fileId, file.getSize()); fileList.add(newFile); } return fileList; } /** * Update a file to Firestore and Cloud Storage. * * @param newFile new file upload to the server * @param tags list of tags label the new file * @param file previously uploaded file * @return the updated file */ public BaseFile updateFile(MultipartFile newFile, List<String> tags, BaseFile file) throws InterruptedException, ExecutionException, IOException { log.info("entering updateFile()"); String fileId = file.getId(); if (newFile == null) { String pathId = LdsUtil.getPathId(file.getPath()); return createOrUpdateFileMeta(tags, fileId, pathId, file.getName(), file.getSize()); } storageService.delete(bucketName, file.getPath()); storageService.delete(bucketName, file.genThumbnailPath()); String newFileId = LdsUtil.generateUuid(); return createOrUpdateFile(newFile, tags, fileId, newFileId, newFile.getSize()); } /** * Delete a file from Firestore and Cloud Storage. * * @param file the uploaded file */ public void deleteFile(BaseFile file) throws InterruptedException, ExecutionException { log.info("entering deleteFile()"); firestoreService.delete(file.getId()); storageService.delete(bucketName, file.getPath()); storageService.delete(bucketName, file.genThumbnailPath()); } /** * Search files with given tags. * * @param tags list of tags label the files * @param orderNo application defined column for referencing order * @param size number of files return * @return list of uploaded files */ public List<BaseFile> getFilesByTag(List<String> tags, String orderNo, int size) throws InterruptedException, ExecutionException { log.info("entering getFilesByTag()"); return firestoreService.getFilesByTag(tags, orderNo, size); } /** * Search a single file with given fileId. * * @param fileId unique id of the file * @return the uploaded file */ public BaseFile getFileById(String fileId) throws InterruptedException, ExecutionException { log.info("entering getFileById()"); return firestoreService.getFileById(fileId); } /** Delete all files from Firestore and Cloud Storage. */ public void resetFile() throws InterruptedException, ExecutionException { log.info("entering resetFile()"); firestoreService.deleteCollection(); storageService.batchDelete(bucketName); } /** * Create or update a file in Cloud Storage with the given fileId. * * @param file file upload to the server * @param tags list of tags label the file * @param fileId unique ID of the file * @param newFileId unique ID of the new file (for referencing Cloud Storage) * @param size size of the file * @return file data */ private BaseFile createOrUpdateFile( MultipartFile file, List<String> tags, String fileId, String newFileId, long size) throws InterruptedException, ExecutionException, IOException { BaseFile newFile = createOrUpdateFileMeta(tags, fileId, newFileId, file.getOriginalFilename(), size); storageService.save(bucketName, newFile.getPath(), file.getContentType(), file.getBytes()); if (newFile.checkImageFileType()) { createThumbnail(file,
newFile.genThumbnailPath());
} return newFile; } /** * Create or update the metadata of a file in Firestore with the given fileId. * * @param tags list of tags label the file * @param fileId unique id of the file * @param newFileId unique id of the new file (for referencing Cloud Storage) * @param fileName name of the file * @param size size of the file * @return file data */ private BaseFile createOrUpdateFileMeta( List<String> tags, String fileId, String newFileId, String fileName, long size) throws InterruptedException, ExecutionException { String fileBucketPath = LdsUtil.getFileBucketPath(basePath, newFileId); FileMeta fileMeta = new FileMeta(fileId, fileBucketPath, fileName, tags, size); firestoreService.save(fileMeta); return getFileById(fileId); } /** * Create a thumbnail of the given file. * * @param file file to create thumbnail * @param thumbnailId unique id of the thumbnail file */ private void createThumbnail(MultipartFile file, String thumbnailId) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Thumbnails.of(file.getInputStream()) .size(THUMBNAIL_SIZE, THUMBNAIL_SIZE) .keepAspectRatio(false) .toOutputStream(byteArrayOutputStream); storageService.save( bucketName, thumbnailId, file.getContentType(), byteArrayOutputStream.toByteArray()); } }
api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FileService.java
GoogleCloudPlatform-app-large-data-sharing-java-fd21141
[ { "filename": "api/src/test/java/com/googlecodesamples/cloud/jss/lds/service/FileServiceTest.java", "retrieved_chunk": " public void testUpdateFile() throws InterruptedException, ExecutionException, IOException {\n BaseFile file = fileService.updateFile(mockMultipartFiles.get(0), TAGS, mockFiles.get(0));\n assertThat(file).isNotNull();\n assertThat(file.checkImageFileType()).isTrue();\n assertThat(file.getTags()).isEqualTo(TAGS);\n }\n @Test\n public void testGetFilesByTag() throws InterruptedException, ExecutionException {\n List<BaseFile> files = fileService.getFilesByTag(TAGS, ORDER_NUM, LIST_SIZE);\n assertThat(files).isNotEmpty();", "score": 0.8524076342582703 }, { "filename": "api/src/test/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreServiceIT.java", "retrieved_chunk": " private static final String FILE_META_PATH = \"resource/test-id\";\n private static final String FILE_META_NAME = \"test\";\n private static final List<String> FILE_META_TAGS = List.of(\"test-tag\");\n private static final long FILE_META_SIZE = 100;\n private static final int LIST_SIZE = 10;\n @Autowired\n FirestoreService firestoreService;\n @Test\n public void testSaveFileMeta() throws InterruptedException, ExecutionException {\n try {", "score": 0.8489316701889038 }, { "filename": "api/src/test/java/com/googlecodesamples/cloud/jss/lds/service/FileServiceTest.java", "retrieved_chunk": " }\n @Test\n public void testUploadFiles() throws InterruptedException, ExecutionException, IOException {\n List<BaseFile> files = fileService.uploadFiles(mockMultipartFiles, TAGS);\n assertThat(files).isNotEmpty();\n assertThat(files.size()).isEqualTo(LIST_SIZE);\n assertThat(files.get(0).checkImageFileType()).isTrue();\n assertThat(files.get(0).getTags()).isEqualTo(TAGS);\n }\n @Test", "score": 0.8460023999214172 }, { "filename": "api/src/test/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreServiceIT.java", "retrieved_chunk": " }\n private FileMeta createFileMeta() {\n return new FileMeta(\n FILE_META_ID, FILE_META_PATH, FILE_META_NAME, FILE_META_TAGS, FILE_META_SIZE);\n }\n}", "score": 0.8458316326141357 }, { "filename": "api/src/test/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreServiceIT.java", "retrieved_chunk": " firestoreService.save(createFileMeta());\n BaseFile testFile = firestoreService.getFileById(FILE_META_ID);\n assertThat(testFile).isNotNull();\n } finally {\n firestoreService.delete(FILE_META_ID);\n }\n }\n @Test\n public void testGetFileById() throws InterruptedException, ExecutionException {\n try {", "score": 0.8445104360580444 } ]
java
newFile.genThumbnailPath());
/* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.googlecodesamples.cloud.jss.lds.model; import com.googlecodesamples.cloud.jss.lds.util.LdsUtil; import java.util.List; /** * The FileMeta class represents the file metadata that corresponds to Firestore database schema */ public class FileMeta { private String id; private String path; private String name; private List<String> tags; private String orderNo; private long size; public FileMeta() { } public FileMeta(String id, String path, String name, List<String> tags, long size) { this.id = id; this.path = path; this.name = name; this.tags = tags; this
.orderNo = System.currentTimeMillis() + "-" + LdsUtil.getPathId(path);
this.size = size; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<String> getTags() { return tags; } public void setTags(List<String> tags) { this.tags = tags; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getOrderNo() { return orderNo; } public void setOrderNo(String orderNo) { this.orderNo = orderNo; } public long getSize() { return size; } public void setSize(long size) { this.size = size; } }
api/src/main/java/com/googlecodesamples/cloud/jss/lds/model/FileMeta.java
GoogleCloudPlatform-app-large-data-sharing-java-fd21141
[ { "filename": "api/src/test/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreServiceIT.java", "retrieved_chunk": " }\n private FileMeta createFileMeta() {\n return new FileMeta(\n FILE_META_ID, FILE_META_PATH, FILE_META_NAME, FILE_META_TAGS, FILE_META_SIZE);\n }\n}", "score": 0.8703898787498474 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FileService.java", "retrieved_chunk": " * @param newFileId unique id of the new file (for referencing Cloud Storage)\n * @param fileName name of the file\n * @param size size of the file\n * @return file data\n */\n private BaseFile createOrUpdateFileMeta(\n List<String> tags, String fileId, String newFileId, String fileName, long size)\n throws InterruptedException, ExecutionException {\n String fileBucketPath = LdsUtil.getFileBucketPath(basePath, newFileId);\n FileMeta fileMeta = new FileMeta(fileId, fileBucketPath, fileName, tags, size);", "score": 0.8343623876571655 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/model/BaseFile.java", "retrieved_chunk": " public BaseFile() {\n }\n public BaseFile(QueryDocumentSnapshot document, String resourceBasePath) {\n BaseFile file = document.toObject(BaseFile.class);\n BeanUtils.copyProperties(file, this);\n this.setUrl(resourceBasePath + file.getPath());\n this.setThumbUrl(resourceBasePath + file.genThumbnailPath());\n this.setCreateTime(document.getCreateTime().toDate());\n this.setUpdateTime(document.getUpdateTime().toDate());\n }", "score": 0.820598304271698 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/model/BaseFile.java", "retrieved_chunk": "/**\n * The BaseFile class represents a file being uploaded by the users\n */\npublic class BaseFile extends FileMeta {\n private static final List<String> IMG_EXTENSIONS = List.of(\"png\", \"jpeg\", \"jpg\", \"gif\");\n private static final String THUMBNAIL_EXTENSION = \"_small\";\n private String url;\n private String thumbUrl;\n private Date createTime;\n private Date updateTime;", "score": 0.8204216957092285 }, { "filename": "api/src/test/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreServiceIT.java", "retrieved_chunk": " private static final String FILE_META_PATH = \"resource/test-id\";\n private static final String FILE_META_NAME = \"test\";\n private static final List<String> FILE_META_TAGS = List.of(\"test-tag\");\n private static final long FILE_META_SIZE = 100;\n private static final int LIST_SIZE = 10;\n @Autowired\n FirestoreService firestoreService;\n @Test\n public void testSaveFileMeta() throws InterruptedException, ExecutionException {\n try {", "score": 0.818617582321167 } ]
java
.orderNo = System.currentTimeMillis() + "-" + LdsUtil.getPathId(path);
/* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.googlecodesamples.cloud.jss.lds.service; import com.googlecodesamples.cloud.jss.lds.model.BaseFile; import com.googlecodesamples.cloud.jss.lds.model.FileMeta; import com.googlecodesamples.cloud.jss.lds.util.LdsUtil; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import net.coobird.thumbnailator.Thumbnails; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; /** Backend service controller for Firestore and CloudStorage */ @Service public class FileService { private static final Logger log = LoggerFactory.getLogger(FirestoreService.class); private static final int THUMBNAIL_SIZE = 300; private final FirestoreService firestoreService; private final StorageService storageService; @Value("${resource.path}") private String basePath; @Value("${storage.bucket.name}") private String bucketName; public FileService(FirestoreService firestoreService, StorageService storageService) { this.firestoreService = firestoreService; this.storageService = storageService; } /** * Upload files to Firestore and Cloud Storage. * * @param files list of files upload to the server * @param tags list of tags label the files * @return list of uploaded files */ public List<BaseFile> uploadFiles(List<MultipartFile> files, List<String> tags) throws InterruptedException, ExecutionException, IOException { log.info("entering uploadFiles()"); List<BaseFile> fileList = new ArrayList<>(); for (MultipartFile file : files) { String fileId = LdsUtil.generateUuid(); BaseFile newFile = createOrUpdateFile(file, tags, fileId, fileId, file.getSize()); fileList.add(newFile); } return fileList; } /** * Update a file to Firestore and Cloud Storage. * * @param newFile new file upload to the server * @param tags list of tags label the new file * @param file previously uploaded file * @return the updated file */ public BaseFile updateFile(MultipartFile newFile, List<String> tags, BaseFile file) throws InterruptedException, ExecutionException, IOException { log.info("entering updateFile()"); String fileId = file.getId(); if (newFile == null) { String pathId = LdsUtil.getPathId(file.getPath()); return createOrUpdateFileMeta(tags, fileId, pathId, file.getName(), file.getSize()); } storageService.delete(bucketName, file.getPath()); storageService.delete(bucketName, file.genThumbnailPath()); String newFileId = LdsUtil.generateUuid(); return createOrUpdateFile(newFile, tags, fileId, newFileId, newFile.getSize()); } /** * Delete a file from Firestore and Cloud Storage. * * @param file the uploaded file */ public void deleteFile(BaseFile file) throws InterruptedException, ExecutionException { log.info("entering deleteFile()"); firestoreService.delete(file.getId()); storageService.delete(bucketName, file.getPath()); storageService.delete(bucketName, file.genThumbnailPath()); } /** * Search files with given tags. * * @param tags list of tags label the files * @param orderNo application defined column for referencing order * @param size number of files return * @return list of uploaded files */ public List<BaseFile> getFilesByTag(List<String> tags, String orderNo, int size) throws InterruptedException, ExecutionException { log.info("entering getFilesByTag()"); return firestoreService.getFilesByTag(tags, orderNo, size); } /** * Search a single file with given fileId. * * @param fileId unique id of the file * @return the uploaded file */ public BaseFile getFileById(String fileId) throws InterruptedException, ExecutionException { log.info("entering getFileById()"); return firestoreService.getFileById(fileId); } /** Delete all files from Firestore and Cloud Storage. */ public void resetFile() throws InterruptedException, ExecutionException { log.info("entering resetFile()"); firestoreService.deleteCollection();
storageService.batchDelete(bucketName);
} /** * Create or update a file in Cloud Storage with the given fileId. * * @param file file upload to the server * @param tags list of tags label the file * @param fileId unique ID of the file * @param newFileId unique ID of the new file (for referencing Cloud Storage) * @param size size of the file * @return file data */ private BaseFile createOrUpdateFile( MultipartFile file, List<String> tags, String fileId, String newFileId, long size) throws InterruptedException, ExecutionException, IOException { BaseFile newFile = createOrUpdateFileMeta(tags, fileId, newFileId, file.getOriginalFilename(), size); storageService.save(bucketName, newFile.getPath(), file.getContentType(), file.getBytes()); if (newFile.checkImageFileType()) { createThumbnail(file, newFile.genThumbnailPath()); } return newFile; } /** * Create or update the metadata of a file in Firestore with the given fileId. * * @param tags list of tags label the file * @param fileId unique id of the file * @param newFileId unique id of the new file (for referencing Cloud Storage) * @param fileName name of the file * @param size size of the file * @return file data */ private BaseFile createOrUpdateFileMeta( List<String> tags, String fileId, String newFileId, String fileName, long size) throws InterruptedException, ExecutionException { String fileBucketPath = LdsUtil.getFileBucketPath(basePath, newFileId); FileMeta fileMeta = new FileMeta(fileId, fileBucketPath, fileName, tags, size); firestoreService.save(fileMeta); return getFileById(fileId); } /** * Create a thumbnail of the given file. * * @param file file to create thumbnail * @param thumbnailId unique id of the thumbnail file */ private void createThumbnail(MultipartFile file, String thumbnailId) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Thumbnails.of(file.getInputStream()) .size(THUMBNAIL_SIZE, THUMBNAIL_SIZE) .keepAspectRatio(false) .toOutputStream(byteArrayOutputStream); storageService.save( bucketName, thumbnailId, file.getContentType(), byteArrayOutputStream.toByteArray()); } }
api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FileService.java
GoogleCloudPlatform-app-large-data-sharing-java-fd21141
[ { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreService.java", "retrieved_chunk": " public void delete(String fileId) throws InterruptedException, ExecutionException {\n firestore.collection(collectionName).document(fileId).delete().get();\n }\n /** Delete a collection in Firestore. */\n public void deleteCollection() throws InterruptedException, ExecutionException {\n firestore.recursiveDelete(firestore.collection(collectionName)).get();\n }\n /**\n * Convert documents retrieved from Firestore to BaseFile object.\n *", "score": 0.9024134874343872 }, { "filename": "api/src/test/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreServiceIT.java", "retrieved_chunk": " firestoreService.delete(FILE_META_ID);\n BaseFile testFile = firestoreService.getFileById(FILE_META_ID);\n assertThat(testFile).isNull();\n }\n @Test\n public void testDeleteCollection() throws InterruptedException, ExecutionException {\n firestoreService.save(createFileMeta());\n firestoreService.deleteCollection();\n BaseFile testFile = firestoreService.getFileById(FILE_META_ID);\n assertThat(testFile).isNull();", "score": 0.8988038301467896 }, { "filename": "api/src/test/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreServiceIT.java", "retrieved_chunk": " firestoreService.save(createFileMeta());\n BaseFile testFile = firestoreService.getFileById(FILE_META_ID);\n assertThat(testFile).isNotNull();\n } finally {\n firestoreService.delete(FILE_META_ID);\n }\n }\n @Test\n public void testGetFileById() throws InterruptedException, ExecutionException {\n try {", "score": 0.8754690885543823 }, { "filename": "api/src/test/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreServiceIT.java", "retrieved_chunk": " firestoreService.save(createFileMeta());\n BaseFile testFile = firestoreService.getFileById(FILE_META_ID);\n assertThat(testFile.getId()).isEqualTo(FILE_META_ID);\n } finally {\n firestoreService.delete(FILE_META_ID);\n }\n }\n @Test\n public void testDeleteDocument() throws InterruptedException, ExecutionException {\n firestoreService.save(createFileMeta());", "score": 0.8708208799362183 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreService.java", "retrieved_chunk": " * @param fileId unique id of the file\n * @return file data\n */\n public BaseFile getFileById(String fileId) throws InterruptedException, ExecutionException {\n ApiFuture<QuerySnapshot> future =\n firestore.collection(collectionName).whereEqualTo(FieldPath.documentId(), fileId).get();\n List<QueryDocumentSnapshot> documents = future.get().getDocuments();\n if (documents.isEmpty()) {\n return null;\n }", "score": 0.8673297166824341 } ]
java
storageService.batchDelete(bucketName);
/* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.googlecodesamples.cloud.jss.lds.service; import com.google.api.core.ApiFuture; import com.google.cloud.firestore.DocumentReference; import com.google.cloud.firestore.FieldPath; import com.google.cloud.firestore.Firestore; import com.google.cloud.firestore.FirestoreOptions; import com.google.cloud.firestore.Query; import com.google.cloud.firestore.QueryDocumentSnapshot; import com.google.cloud.firestore.QuerySnapshot; import com.googlecodesamples.cloud.jss.lds.model.BaseFile; import com.googlecodesamples.cloud.jss.lds.model.FileMeta; import com.googlecodesamples.cloud.jss.lds.util.LdsUtil; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import javax.annotation.PreDestroy; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; /** Backend service controller for Firestore */ @Service public class FirestoreService { private static final String TAGS = "tags"; private static final String ORDER_NO = "orderNo"; private final Firestore firestore; @Value("${firestore.collection.name}") private String collectionName; @Value("${resource.path}") private String basePath; public FirestoreService() { this.firestore = FirestoreOptions.getDefaultInstance().getService(); } /** * Save metadata of a file to Firestore. * * @param fileMeta metadata of the file */ public void save(FileMeta fileMeta) throws InterruptedException, ExecutionException { DocumentReference docRef = firestore.collection(collectionName).document(fileMeta.getId()); docRef.set(fileMeta).get(); } /** * Search a file with given fileId. * * @param fileId unique id of the file * @return file data */ public BaseFile getFileById(String fileId) throws InterruptedException, ExecutionException { ApiFuture<QuerySnapshot> future = firestore.collection(collectionName).whereEqualTo(FieldPath.documentId(), fileId).get(); List<QueryDocumentSnapshot> documents = future.get().getDocuments(); if (documents.isEmpty()) { return null; } return convertDoc2File(documents).get(0); } /** * Search files with given tags. * * @param tags list of tags label the files * @param orderNo application defined column for referencing order * @param size number of files return * @return list of files data */ public List<BaseFile> getFilesByTag(List<String> tags, String orderNo, int size) throws InterruptedException, ExecutionException { ApiFuture<QuerySnapshot> future; Query query = firestore.collection(collectionName).orderBy(ORDER_NO, Query.Direction.DESCENDING); if (!CollectionUtils.isEmpty(tags)) { query = query.whereArrayContainsAny(TAGS, tags); } if (StringUtils.hasText(orderNo)) { query = query.startAfter(orderNo); } future = query.limit(size).get(); List<QueryDocumentSnapshot> documents = future.get().getDocuments(); return convertDoc2File(documents); } /** * Delete a file from Firestore with given fileId. * * @param fileId unique id of the file */ public void delete(String fileId) throws InterruptedException, ExecutionException { firestore.collection(collectionName).document(fileId).delete().get(); } /** Delete a collection in Firestore. */ public void deleteCollection() throws InterruptedException, ExecutionException { firestore.recursiveDelete(firestore.collection(collectionName)).get(); } /** * Convert documents retrieved from Firestore to BaseFile object. * * @param documents lis of documents retrieved from Firestore * @return list of files data */ private List<BaseFile> convertDoc2File(List<QueryDocumentSnapshot> documents) { String
resourceBasePath = LdsUtil.getResourceBasePath(basePath);
return documents.stream() .map(doc -> new BaseFile(doc, resourceBasePath)) .collect(Collectors.toList()); } /** Close the channels and release resources. */ @PreDestroy public void close() throws Exception { firestore.close(); } }
api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreService.java
GoogleCloudPlatform-app-large-data-sharing-java-fd21141
[ { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/model/BaseFile.java", "retrieved_chunk": " public BaseFile() {\n }\n public BaseFile(QueryDocumentSnapshot document, String resourceBasePath) {\n BaseFile file = document.toObject(BaseFile.class);\n BeanUtils.copyProperties(file, this);\n this.setUrl(resourceBasePath + file.getPath());\n this.setThumbUrl(resourceBasePath + file.genThumbnailPath());\n this.setCreateTime(document.getCreateTime().toDate());\n this.setUpdateTime(document.getUpdateTime().toDate());\n }", "score": 0.7862317562103271 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FileService.java", "retrieved_chunk": " * @return list of uploaded files\n */\n public List<BaseFile> uploadFiles(List<MultipartFile> files, List<String> tags)\n throws InterruptedException, ExecutionException, IOException {\n log.info(\"entering uploadFiles()\");\n List<BaseFile> fileList = new ArrayList<>();\n for (MultipartFile file : files) {\n String fileId = LdsUtil.generateUuid();\n BaseFile newFile = createOrUpdateFile(file, tags, fileId, fileId, file.getSize());\n fileList.add(newFile);", "score": 0.7712812423706055 }, { "filename": "api/src/test/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreServiceIT.java", "retrieved_chunk": " * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.googlecodesamples.cloud.jss.lds.service;\nimport static com.google.common.truth.Truth.assertThat;\nimport com.googlecodesamples.cloud.jss.lds.model.BaseFile;\nimport com.googlecodesamples.cloud.jss.lds.model.FileMeta;\nimport java.util.List;", "score": 0.76441490650177 }, { "filename": "api/src/test/java/com/googlecodesamples/cloud/jss/lds/controller/FileControllerTest.java", "retrieved_chunk": " * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.googlecodesamples.cloud.jss.lds.controller;\nimport com.google.gson.Gson;\nimport com.google.gson.JsonObject;\nimport com.googlecodesamples.cloud.jss.lds.model.BaseFile;\nimport com.googlecodesamples.cloud.jss.lds.model.BaseFileTest;", "score": 0.7627332210540771 }, { "filename": "api/src/test/java/com/googlecodesamples/cloud/jss/lds/service/FileServiceTest.java", "retrieved_chunk": " mockFiles = BaseFileTest.getTestFiles(LIST_SIZE, IS_IMAGE);\n // set up mock service responses\n Mockito.when(firestoreService.getFileById(any())).thenReturn(mockFiles.get(0));\n Mockito.when(firestoreService.getFilesByTag(TAGS, ORDER_NUM, LIST_SIZE)).thenReturn(mockFiles);\n Mockito.doNothing().when(firestoreService).save(any());\n Mockito.doNothing().when(firestoreService).delete(any());\n Mockito.doNothing().when(firestoreService).deleteCollection();\n Mockito.doNothing().when(storageService).save(any(), any(), any(), any());\n Mockito.doNothing().when(storageService).delete(any(), any());\n Mockito.doNothing().when(storageService).batchDelete(any());", "score": 0.7613888382911682 } ]
java
resourceBasePath = LdsUtil.getResourceBasePath(basePath);
/* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.googlecodesamples.cloud.jss.lds.controller; import com.googlecodesamples.cloud.jss.lds.model.BaseFile; import com.googlecodesamples.cloud.jss.lds.model.FileListResponse; import com.googlecodesamples.cloud.jss.lds.model.FileResponse; import com.googlecodesamples.cloud.jss.lds.service.FileService; import com.googlecodesamples.cloud.jss.lds.service.OpenTelemetryService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** REST API controller of the backend service */ @RestController @RequestMapping("/api") public class FileController { private static final Logger log = LoggerFactory.getLogger(FileController.class); private static final String STRING_SEPARATOR = "\\s+"; private final FileService fileService; private final OpenTelemetryService openTelemetryService; public FileController(FileService fileService, OpenTelemetryService openTelemetryService) { this.fileService = fileService; this.openTelemetryService = openTelemetryService; } /** * The health check API. * * @return status OK is the service is alive */ @GetMapping("/healthchecker") public ResponseEntity<?> healthCheck() throws Exception { return openTelemetryService.spanScope(this.getClass().getName(), "healthCheck", () -> { log.info("entering healthCheck()"); return ResponseEntity.noContent().build(); }); } /** * Upload files with tags. * * @param files list of files upload to the server * @param tags list of tags (separated by space) label the files * @return list of uploaded files */ @PostMapping("/files") public ResponseEntity<?> uploadFiles( @RequestParam List<MultipartFile> files, @RequestParam String tags) throws Exception { return openTelemetryService.spanScope(this.getClass().getName(), "uploadFiles", () -> { log.info("entering uploadFiles()"); List<String> tagList = getTagList(tags); List<BaseFile> fileList = fileService.uploadFiles(files, tagList); return ResponseEntity.status(HttpStatus.CREATED).body(new FileListResponse(fileList)); }); } /** * Search files with the given tags. * * @param tags list of tags (separated by space) label the files * @param orderNo order number of the last file * @param size number of files return * @return list of files with pagination */ @GetMapping("/files") public ResponseEntity<?> getFilesByTag( @RequestParam(required = false) String tags, @RequestParam(required = false) String orderNo, @RequestParam(required = false, defaultValue = "50") int size) throws Exception { return openTelemetryService.spanScope(this.getClass().getName(), "getFilesByTag", () -> { log.info("entering getFilesByTag()"); List<String> tagList = getTagList(tags); List<BaseFile> fileList = fileService.getFilesByTag(tagList, orderNo, size); if (CollectionUtils.isEmpty(fileList)) { return ResponseEntity.ok().body(new FileListResponse(new ArrayList<>())); } return ResponseEntity.ok().body(new FileListResponse(fileList)); }); } /** * Update an existing file * * @param fileId unique ID of the file * @param file new file to be uploaded to the server * @param tags list of tags (separated by space) label the new file * @return file data */ @PutMapping("/files/{id}") public ResponseEntity<?> updateFile( @PathVariable("id") String fileId, @RequestParam(required = false) MultipartFile file, @RequestParam String tags) throws Exception { return openTelemetryService.spanScope(this.getClass().getName(), "updateFile", () -> { log.info("entering updateFile()");
BaseFile oldFile = fileService.getFileById(fileId);
if (oldFile == null) { return ResponseEntity.notFound().build(); } List<String> tagList = getTagList(tags); BaseFile newFile = fileService.updateFile(file, tagList, oldFile); return ResponseEntity.ok().body(new FileResponse(newFile)); }); } /** * Delete an existing file * * @param fileId unique ID of the file * @return status NoContent or NotFound */ @DeleteMapping("/files/{id}") public ResponseEntity<?> deleteFile(@PathVariable("id") String fileId) throws Exception { return openTelemetryService.spanScope(this.getClass().getName(), "deleteFile", () -> { log.info("entering deleteFile()"); BaseFile file = fileService.getFileById(fileId); if (file == null) { return ResponseEntity.notFound().build(); } fileService.deleteFile(file); return ResponseEntity.noContent().build(); }); } /** * Delete all files. * * @return status NoContent */ @DeleteMapping("/reset") public ResponseEntity<?> resetFile() throws Exception { return openTelemetryService.spanScope(this.getClass().getName(), "resetFile", () -> { log.info("entering resetFile()"); fileService.resetFile(); return ResponseEntity.noContent().build(); }); } /** * Split the string by separator. * * @param tags list of tags in a single string (separated by space) * @return list of tags */ private List<String> getTagList(String tags) { if (!StringUtils.hasText(tags)) { return new ArrayList<>(); } return Arrays.stream(tags.split(STRING_SEPARATOR)) .map(String::trim) .map(String::toLowerCase) .collect(Collectors.toList()); } }
api/src/main/java/com/googlecodesamples/cloud/jss/lds/controller/FileController.java
GoogleCloudPlatform-app-large-data-sharing-java-fd21141
[ { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FileService.java", "retrieved_chunk": " */\n public BaseFile updateFile(MultipartFile newFile, List<String> tags, BaseFile file)\n throws InterruptedException, ExecutionException, IOException {\n log.info(\"entering updateFile()\");\n String fileId = file.getId();\n if (newFile == null) {\n String pathId = LdsUtil.getPathId(file.getPath());\n return createOrUpdateFileMeta(tags, fileId, pathId, file.getName(), file.getSize());\n }\n storageService.delete(bucketName, file.getPath());", "score": 0.8878340125083923 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FileService.java", "retrieved_chunk": " * @param newFileId unique ID of the new file (for referencing Cloud Storage)\n * @param size size of the file\n * @return file data\n */\n private BaseFile createOrUpdateFile(\n MultipartFile file, List<String> tags, String fileId, String newFileId, long size)\n throws InterruptedException, ExecutionException, IOException {\n BaseFile newFile =\n createOrUpdateFileMeta(tags, fileId, newFileId, file.getOriginalFilename(), size);\n storageService.save(bucketName, newFile.getPath(), file.getContentType(), file.getBytes());", "score": 0.8610231876373291 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FileService.java", "retrieved_chunk": " * @param newFileId unique id of the new file (for referencing Cloud Storage)\n * @param fileName name of the file\n * @param size size of the file\n * @return file data\n */\n private BaseFile createOrUpdateFileMeta(\n List<String> tags, String fileId, String newFileId, String fileName, long size)\n throws InterruptedException, ExecutionException {\n String fileBucketPath = LdsUtil.getFileBucketPath(basePath, newFileId);\n FileMeta fileMeta = new FileMeta(fileId, fileBucketPath, fileName, tags, size);", "score": 0.8330546617507935 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FileService.java", "retrieved_chunk": " log.info(\"entering resetFile()\");\n firestoreService.deleteCollection();\n storageService.batchDelete(bucketName);\n }\n /**\n * Create or update a file in Cloud Storage with the given fileId.\n *\n * @param file file upload to the server\n * @param tags list of tags label the file\n * @param fileId unique ID of the file", "score": 0.8321691751480103 }, { "filename": "api/src/test/java/com/googlecodesamples/cloud/jss/lds/service/FileServiceTest.java", "retrieved_chunk": " public void testUpdateFile() throws InterruptedException, ExecutionException, IOException {\n BaseFile file = fileService.updateFile(mockMultipartFiles.get(0), TAGS, mockFiles.get(0));\n assertThat(file).isNotNull();\n assertThat(file.checkImageFileType()).isTrue();\n assertThat(file.getTags()).isEqualTo(TAGS);\n }\n @Test\n public void testGetFilesByTag() throws InterruptedException, ExecutionException {\n List<BaseFile> files = fileService.getFilesByTag(TAGS, ORDER_NUM, LIST_SIZE);\n assertThat(files).isNotEmpty();", "score": 0.8253222107887268 } ]
java
BaseFile oldFile = fileService.getFileById(fileId);
/* * Copyright (C) 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.fhir.cql.beam; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableSet.toImmutableSet; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.context.FhirVersionEnum; import ca.uhn.fhir.parser.IParser; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.json.JsonMapper; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.fhir.cql.beam.types.CqlEvaluationResult; import com.google.fhir.cql.beam.types.CqlLibraryId; import com.google.fhir.cql.beam.types.ResourceTypeAndId; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; import java.time.ZonedDateTime; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.values.KV; import org.cqframework.cql.elm.execution.ExpressionDef; import org.cqframework.cql.elm.execution.Library; import org.cqframework.cql.elm.execution.VersionedIdentifier; import org.hl7.fhir.r4.model.Bundle; import org.hl7.fhir.r4.model.Bundle.BundleType; import org.hl7.fhir.r4.model.Resource; import org.opencds.cqf.cql.engine.data.CompositeDataProvider; import org.opencds.cqf.cql.engine.execution.Context; import org.opencds.cqf.cql.engine.execution.InMemoryLibraryLoader; import org.opencds.cqf.cql.engine.execution.LibraryLoader; import org.opencds.cqf.cql.engine.fhir.model.R4FhirModelResolver; import org.opencds.cqf.cql.engine.model.ModelResolver; import org.opencds.cqf.cql.engine.retrieve.RetrieveProvider; import org.opencds.cqf.cql.engine.serializing.jackson.JsonCqlMapper; import org.opencds.cqf.cql.engine.terminology.TerminologyProvider; import org.opencds.cqf.cql.evaluator.engine.retrieve.BundleRetrieveProvider; import org.opencds.cqf.cql.evaluator.engine.terminology.BundleTerminologyProvider; /** * A function that evaluates a set of CQL libraries over the collection of resources, represented as * JSON strings, for a given context. The collection of resources should include every resource * necessary for evaluation of the CQL within the context (e.g., the entire Patient bundle). * * <p>The follow constraints currently exist: * * <ul> * <li>there is no support for accessing resources outside of the context (i.e., no support for * cross-context and related context retrieves). * <li>all resources for the context must fit within the memory of a worker. * <li>only boolean expressions are written to the resulting {@link CqlEvaluationResult} objects. * <li>there is no support for passing parameters to the CQL libraries. * </ul> */ public final class EvaluateCqlForContextFn extends DoFn<KV<ResourceTypeAndId, Iterable<String>>, CqlEvaluationResult> { /** A context that disallows evaluation of cross-context CQL expressions. */ private static class FixedContext extends Context { public FixedContext( Library library, ZonedDateTime evaluationZonedDateTime, ResourceTypeAndId contextValue) { super(library, evaluationZonedDateTime); super.setContextValue
(contextValue.getType(), contextValue.getId());
super.enterContext(contextValue.getType()); } @Override public void enterContext(String context) { if (!context.equals(getCurrentContext())) { throw new IllegalStateException("Context switching is not supported."); } super.enterContext(context); } } /** A wrapper around {@link Library} that supports Java serialization. */ private static class SerializableLibraryWrapper implements Serializable { private static JsonMapper jsonMapper = JsonCqlMapper.getMapper() .rebuild() .disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET) .disable(SerializationFeature.INDENT_OUTPUT) .build(); private Library library; public SerializableLibraryWrapper(Library library) { this.library = library; } public Library getLibrary() { return library; } private void readObject(ObjectInputStream inputStream) throws IOException { library = jsonMapper.readValue((InputStream) inputStream, Library.class); } private void writeObject(ObjectOutputStream outputStream) throws IOException { jsonMapper.writeValue((OutputStream) outputStream, library); } } private final ImmutableList<SerializableLibraryWrapper> cqlSources; private final ImmutableSet<CqlLibraryId> cqlLibraryIds; private final ImmutableList<String> valueSetJsonResources; private final ZonedDateTime evaluationDateTime; private final FhirVersionEnum fhirVersion; private transient ImmutableSet<VersionedIdentifier> cqlLibraryVersionedIdentifiers; private transient FhirContext fhirContext; private transient ModelResolver modelResolver; private transient TerminologyProvider terminologyProvider; private transient LibraryLoader libraryLoader; public EvaluateCqlForContextFn( Collection<Library> cqlSources, Set<CqlLibraryId> cqlLibraryIds, Collection<String> valueSetJsonResources, ZonedDateTime evaluationDateTime, FhirVersionEnum fhirVersion) { this.cqlSources = cqlSources.stream().map(SerializableLibraryWrapper::new).collect(toImmutableList()); this.cqlLibraryIds = ImmutableSet.copyOf(cqlLibraryIds); this.valueSetJsonResources = ImmutableList.copyOf(valueSetJsonResources); this.evaluationDateTime = checkNotNull(evaluationDateTime); this.fhirVersion = checkNotNull(fhirVersion); } @DoFn.Setup public void setup() { cqlLibraryVersionedIdentifiers = cqlLibraryIds.stream() .map(id -> new VersionedIdentifier().withId(id.getName()).withVersion(id.getVersion())) .collect(toImmutableSet()); fhirContext = new FhirContext(fhirVersion); modelResolver = new CachingModelResolver(new R4FhirModelResolver()); terminologyProvider = createTerminologyProvider(fhirContext, valueSetJsonResources); libraryLoader = new InMemoryLibraryLoader( cqlSources.stream() .map(SerializableLibraryWrapper::getLibrary) .collect(Collectors.toList())); } @ProcessElement public void processElement( @Element KV<ResourceTypeAndId, Iterable<String>> contextResources, OutputReceiver<CqlEvaluationResult> out) { RetrieveProvider retrieveProvider = createRetrieveProvider(contextResources.getValue()); for (VersionedIdentifier cqlLibraryId : cqlLibraryVersionedIdentifiers) { Library library = libraryLoader.load(cqlLibraryId); Context context = createContext(library, retrieveProvider, contextResources.getKey()); try { out.output( new CqlEvaluationResult( library.getIdentifier(), contextResources.getKey(), evaluationDateTime, evaluate(library, context, contextResources.getKey()))); } catch (Exception e) { out.output( new CqlEvaluationResult( library.getIdentifier(), contextResources.getKey(), evaluationDateTime, e)); } } } private Map<String, Boolean> evaluate( Library library, Context context, ResourceTypeAndId contextValue) { HashMap<String, Boolean> results = new HashMap<>(); for (ExpressionDef expression : library.getStatements().getDef()) { if (!expression.getContext().equals(contextValue.getType()) || !isBooleanExpression(expression)) { continue; } if (results.putIfAbsent(expression.getName(), (Boolean) expression.evaluate(context)) != null) { throw new InternalError("Duplicate expression name: " + expression.getName()); } } return results; } private static boolean isBooleanExpression(ExpressionDef expression) { return expression.getResultTypeName() != null && expression.getResultTypeName().getNamespaceURI().equals("urn:hl7-org:elm-types:r1") && expression.getResultTypeName().getLocalPart().equals("Boolean"); } private Context createContext( Library library, RetrieveProvider retrieveProvider, ResourceTypeAndId contextValue) { Context context = new FixedContext(library, evaluationDateTime, contextValue); context.setExpressionCaching(true); context.registerLibraryLoader(libraryLoader); context.registerTerminologyProvider(terminologyProvider); context.registerDataProvider( "http://hl7.org/fhir", new CompositeDataProvider(modelResolver, retrieveProvider)); // TODO(nasha): Set user defined parameters via `context.setParameter`. return context; } private static TerminologyProvider createTerminologyProvider( FhirContext fhirContext, ImmutableList<String> valueSetJsonStrings) { IParser parser = fhirContext.newJsonParser(); Bundle bundle = new Bundle(); bundle.setType(BundleType.COLLECTION); valueSetJsonStrings.stream() .map(parser::parseResource) .forEach((resource) -> bundle.addEntry().setResource((Resource) resource)); return new BundleTerminologyProvider(fhirContext, bundle); } private RetrieveProvider createRetrieveProvider(Iterable<String> jsonResource) { Bundle bundle = new Bundle(); bundle.setType(BundleType.COLLECTION); IParser parser = fhirContext.newJsonParser(); jsonResource.forEach( element -> { bundle.addEntry().setResource((Resource) parser.parseResource(element)); }); BundleRetrieveProvider provider = new BundleRetrieveProvider(fhirContext, bundle); provider.setTerminologyProvider(terminologyProvider); provider.setExpandValueSets(true); return provider; } }
src/main/java/com/google/fhir/cql/beam/EvaluateCqlForContextFn.java
google-cql-on-beam-82f1c68
[ { "filename": "src/test/java/com/google/fhir/cql/beam/EvaluateCqlForContextFnTest.java", "retrieved_chunk": " .apply(ParDo.of(new EvaluateCqlForContextFn(\n cqlToLibraries(\n \"library FooLibrary version '0.1'\\n\"\n + \"using FHIR version '4.0.1'\\n\"\n + \"context Unfiltered\\n\"\n + \"define \\\"Exp1\\\": true\\n\"\n + \"context Patient\\n\"\n + \"define \\\"Exp2\\\": \\\"Exp1\\\"\"),\n ImmutableSet.of(cqlLibraryId(\"FooLibrary\", \"0.1\")),\n ImmutableList.of(),", "score": 0.8482300043106079 }, { "filename": "src/test/java/com/google/fhir/cql/beam/EvaluateCqlForContextFnTest.java", "retrieved_chunk": "import org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.JUnit4;\nimport org.opencds.cqf.cql.evaluator.engine.elm.LibraryMapper;\n/** Tests for {@link EvaluateCqlForContextFn}. */\n@RunWith(JUnit4.class)\npublic class EvaluateCqlForContextFnTest {\n @Rule public TestPipeline testPipeline = TestPipeline.create();\n private static final ResourceTypeAndId PATIENT_1_ID = new ResourceTypeAndId(\"Patient\", \"1\");", "score": 0.8348400592803955 }, { "filename": "src/main/java/com/google/fhir/cql/beam/KeyForContextFn.java", "retrieved_chunk": "public final class KeyForContextFn extends DoFn<String, KV<ResourceTypeAndId, String>> {\n private static final Pattern REFERENCE_PATTERN = Pattern.compile(\"([^/]+)/([^/]+)\");\n private static final String REFERENCE_FIELD_NAME = \"reference\";\n private static final String SUBJECT_FIELD_NAME = \"subject\";\n private static final String PATIENT_FIELD_NAME = \"patient\";\n private final String context;\n private final ImmutableSetMultimap<String, String> relatedKeyElementByType;\n public KeyForContextFn(String context, ModelInfo modelInfo) {\n this.context = checkNotNull(context);\n this.relatedKeyElementByType = createRelatedKeyElementByTypeMap(context, modelInfo);", "score": 0.83149254322052 }, { "filename": "src/test/java/com/google/fhir/cql/beam/EvaluateCqlForContextFnTest.java", "retrieved_chunk": " }\n @Test\n public void expressionsThatDontMatchContextAreSkipped() {\n ImmutableMap<ResourceTypeAndId, Iterable<String>> input = ImmutableMap.of(\n PATIENT_1_ID, ImmutableList.of(PATIENT_1_AGE_21_RESOURCE_JSON));\n PCollection<CqlEvaluationResult> output = testPipeline.apply(Create.of(input))\n .apply(ParDo.of(new EvaluateCqlForContextFn(\n cqlToLibraries(\n \"library FooLibrary version '0.1'\\n\"\n + \"using FHIR version '4.0.1'\\n\"", "score": 0.826461136341095 }, { "filename": "src/test/java/com/google/fhir/cql/beam/EvaluateCqlForContextFnTest.java", "retrieved_chunk": " }\n @Test\n public void contextPopulated() {\n ImmutableMap<ResourceTypeAndId, Iterable<String>> input = ImmutableMap.of(\n PATIENT_1_ID, ImmutableList.of(PATIENT_1_AGE_21_RESOURCE_JSON));\n PCollection<CqlEvaluationResult> output = testPipeline.apply(Create.of(input))\n .apply(ParDo.of(new EvaluateCqlForContextFn(\n cqlToLibraries(\n \"library FooLibrary version '0.1'\\n\"\n + \"using FHIR version '4.0.1'\\n\"", "score": 0.8162258267402649 } ]
java
(contextValue.getType(), contextValue.getId());
/* * Copyright (C) 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.fhir.cql.beam; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableSet.toImmutableSet; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.context.FhirVersionEnum; import ca.uhn.fhir.parser.IParser; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.json.JsonMapper; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.fhir.cql.beam.types.CqlEvaluationResult; import com.google.fhir.cql.beam.types.CqlLibraryId; import com.google.fhir.cql.beam.types.ResourceTypeAndId; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; import java.time.ZonedDateTime; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.values.KV; import org.cqframework.cql.elm.execution.ExpressionDef; import org.cqframework.cql.elm.execution.Library; import org.cqframework.cql.elm.execution.VersionedIdentifier; import org.hl7.fhir.r4.model.Bundle; import org.hl7.fhir.r4.model.Bundle.BundleType; import org.hl7.fhir.r4.model.Resource; import org.opencds.cqf.cql.engine.data.CompositeDataProvider; import org.opencds.cqf.cql.engine.execution.Context; import org.opencds.cqf.cql.engine.execution.InMemoryLibraryLoader; import org.opencds.cqf.cql.engine.execution.LibraryLoader; import org.opencds.cqf.cql.engine.fhir.model.R4FhirModelResolver; import org.opencds.cqf.cql.engine.model.ModelResolver; import org.opencds.cqf.cql.engine.retrieve.RetrieveProvider; import org.opencds.cqf.cql.engine.serializing.jackson.JsonCqlMapper; import org.opencds.cqf.cql.engine.terminology.TerminologyProvider; import org.opencds.cqf.cql.evaluator.engine.retrieve.BundleRetrieveProvider; import org.opencds.cqf.cql.evaluator.engine.terminology.BundleTerminologyProvider; /** * A function that evaluates a set of CQL libraries over the collection of resources, represented as * JSON strings, for a given context. The collection of resources should include every resource * necessary for evaluation of the CQL within the context (e.g., the entire Patient bundle). * * <p>The follow constraints currently exist: * * <ul> * <li>there is no support for accessing resources outside of the context (i.e., no support for * cross-context and related context retrieves). * <li>all resources for the context must fit within the memory of a worker. * <li>only boolean expressions are written to the resulting {@link CqlEvaluationResult} objects. * <li>there is no support for passing parameters to the CQL libraries. * </ul> */ public final class EvaluateCqlForContextFn extends DoFn<KV<ResourceTypeAndId, Iterable<String>>, CqlEvaluationResult> { /** A context that disallows evaluation of cross-context CQL expressions. */ private static class FixedContext extends Context { public FixedContext( Library library, ZonedDateTime evaluationZonedDateTime, ResourceTypeAndId contextValue) { super(library, evaluationZonedDateTime); super.setContextValue(contextValue.getType(), contextValue.getId()); super.
enterContext(contextValue.getType());
} @Override public void enterContext(String context) { if (!context.equals(getCurrentContext())) { throw new IllegalStateException("Context switching is not supported."); } super.enterContext(context); } } /** A wrapper around {@link Library} that supports Java serialization. */ private static class SerializableLibraryWrapper implements Serializable { private static JsonMapper jsonMapper = JsonCqlMapper.getMapper() .rebuild() .disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET) .disable(SerializationFeature.INDENT_OUTPUT) .build(); private Library library; public SerializableLibraryWrapper(Library library) { this.library = library; } public Library getLibrary() { return library; } private void readObject(ObjectInputStream inputStream) throws IOException { library = jsonMapper.readValue((InputStream) inputStream, Library.class); } private void writeObject(ObjectOutputStream outputStream) throws IOException { jsonMapper.writeValue((OutputStream) outputStream, library); } } private final ImmutableList<SerializableLibraryWrapper> cqlSources; private final ImmutableSet<CqlLibraryId> cqlLibraryIds; private final ImmutableList<String> valueSetJsonResources; private final ZonedDateTime evaluationDateTime; private final FhirVersionEnum fhirVersion; private transient ImmutableSet<VersionedIdentifier> cqlLibraryVersionedIdentifiers; private transient FhirContext fhirContext; private transient ModelResolver modelResolver; private transient TerminologyProvider terminologyProvider; private transient LibraryLoader libraryLoader; public EvaluateCqlForContextFn( Collection<Library> cqlSources, Set<CqlLibraryId> cqlLibraryIds, Collection<String> valueSetJsonResources, ZonedDateTime evaluationDateTime, FhirVersionEnum fhirVersion) { this.cqlSources = cqlSources.stream().map(SerializableLibraryWrapper::new).collect(toImmutableList()); this.cqlLibraryIds = ImmutableSet.copyOf(cqlLibraryIds); this.valueSetJsonResources = ImmutableList.copyOf(valueSetJsonResources); this.evaluationDateTime = checkNotNull(evaluationDateTime); this.fhirVersion = checkNotNull(fhirVersion); } @DoFn.Setup public void setup() { cqlLibraryVersionedIdentifiers = cqlLibraryIds.stream() .map(id -> new VersionedIdentifier().withId(id.getName()).withVersion(id.getVersion())) .collect(toImmutableSet()); fhirContext = new FhirContext(fhirVersion); modelResolver = new CachingModelResolver(new R4FhirModelResolver()); terminologyProvider = createTerminologyProvider(fhirContext, valueSetJsonResources); libraryLoader = new InMemoryLibraryLoader( cqlSources.stream() .map(SerializableLibraryWrapper::getLibrary) .collect(Collectors.toList())); } @ProcessElement public void processElement( @Element KV<ResourceTypeAndId, Iterable<String>> contextResources, OutputReceiver<CqlEvaluationResult> out) { RetrieveProvider retrieveProvider = createRetrieveProvider(contextResources.getValue()); for (VersionedIdentifier cqlLibraryId : cqlLibraryVersionedIdentifiers) { Library library = libraryLoader.load(cqlLibraryId); Context context = createContext(library, retrieveProvider, contextResources.getKey()); try { out.output( new CqlEvaluationResult( library.getIdentifier(), contextResources.getKey(), evaluationDateTime, evaluate(library, context, contextResources.getKey()))); } catch (Exception e) { out.output( new CqlEvaluationResult( library.getIdentifier(), contextResources.getKey(), evaluationDateTime, e)); } } } private Map<String, Boolean> evaluate( Library library, Context context, ResourceTypeAndId contextValue) { HashMap<String, Boolean> results = new HashMap<>(); for (ExpressionDef expression : library.getStatements().getDef()) { if (!expression.getContext().equals(contextValue.getType()) || !isBooleanExpression(expression)) { continue; } if (results.putIfAbsent(expression.getName(), (Boolean) expression.evaluate(context)) != null) { throw new InternalError("Duplicate expression name: " + expression.getName()); } } return results; } private static boolean isBooleanExpression(ExpressionDef expression) { return expression.getResultTypeName() != null && expression.getResultTypeName().getNamespaceURI().equals("urn:hl7-org:elm-types:r1") && expression.getResultTypeName().getLocalPart().equals("Boolean"); } private Context createContext( Library library, RetrieveProvider retrieveProvider, ResourceTypeAndId contextValue) { Context context = new FixedContext(library, evaluationDateTime, contextValue); context.setExpressionCaching(true); context.registerLibraryLoader(libraryLoader); context.registerTerminologyProvider(terminologyProvider); context.registerDataProvider( "http://hl7.org/fhir", new CompositeDataProvider(modelResolver, retrieveProvider)); // TODO(nasha): Set user defined parameters via `context.setParameter`. return context; } private static TerminologyProvider createTerminologyProvider( FhirContext fhirContext, ImmutableList<String> valueSetJsonStrings) { IParser parser = fhirContext.newJsonParser(); Bundle bundle = new Bundle(); bundle.setType(BundleType.COLLECTION); valueSetJsonStrings.stream() .map(parser::parseResource) .forEach((resource) -> bundle.addEntry().setResource((Resource) resource)); return new BundleTerminologyProvider(fhirContext, bundle); } private RetrieveProvider createRetrieveProvider(Iterable<String> jsonResource) { Bundle bundle = new Bundle(); bundle.setType(BundleType.COLLECTION); IParser parser = fhirContext.newJsonParser(); jsonResource.forEach( element -> { bundle.addEntry().setResource((Resource) parser.parseResource(element)); }); BundleRetrieveProvider provider = new BundleRetrieveProvider(fhirContext, bundle); provider.setTerminologyProvider(terminologyProvider); provider.setExpandValueSets(true); return provider; } }
src/main/java/com/google/fhir/cql/beam/EvaluateCqlForContextFn.java
google-cql-on-beam-82f1c68
[ { "filename": "src/test/java/com/google/fhir/cql/beam/EvaluateCqlForContextFnTest.java", "retrieved_chunk": " .apply(ParDo.of(new EvaluateCqlForContextFn(\n cqlToLibraries(\n \"library FooLibrary version '0.1'\\n\"\n + \"using FHIR version '4.0.1'\\n\"\n + \"context Unfiltered\\n\"\n + \"define \\\"Exp1\\\": true\\n\"\n + \"context Patient\\n\"\n + \"define \\\"Exp2\\\": \\\"Exp1\\\"\"),\n ImmutableSet.of(cqlLibraryId(\"FooLibrary\", \"0.1\")),\n ImmutableList.of(),", "score": 0.8504927158355713 }, { "filename": "src/test/java/com/google/fhir/cql/beam/EvaluateCqlForContextFnTest.java", "retrieved_chunk": "import org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.JUnit4;\nimport org.opencds.cqf.cql.evaluator.engine.elm.LibraryMapper;\n/** Tests for {@link EvaluateCqlForContextFn}. */\n@RunWith(JUnit4.class)\npublic class EvaluateCqlForContextFnTest {\n @Rule public TestPipeline testPipeline = TestPipeline.create();\n private static final ResourceTypeAndId PATIENT_1_ID = new ResourceTypeAndId(\"Patient\", \"1\");", "score": 0.8355067372322083 }, { "filename": "src/main/java/com/google/fhir/cql/beam/KeyForContextFn.java", "retrieved_chunk": "public final class KeyForContextFn extends DoFn<String, KV<ResourceTypeAndId, String>> {\n private static final Pattern REFERENCE_PATTERN = Pattern.compile(\"([^/]+)/([^/]+)\");\n private static final String REFERENCE_FIELD_NAME = \"reference\";\n private static final String SUBJECT_FIELD_NAME = \"subject\";\n private static final String PATIENT_FIELD_NAME = \"patient\";\n private final String context;\n private final ImmutableSetMultimap<String, String> relatedKeyElementByType;\n public KeyForContextFn(String context, ModelInfo modelInfo) {\n this.context = checkNotNull(context);\n this.relatedKeyElementByType = createRelatedKeyElementByTypeMap(context, modelInfo);", "score": 0.8345763683319092 }, { "filename": "src/test/java/com/google/fhir/cql/beam/EvaluateCqlForContextFnTest.java", "retrieved_chunk": " }\n @Test\n public void expressionsThatDontMatchContextAreSkipped() {\n ImmutableMap<ResourceTypeAndId, Iterable<String>> input = ImmutableMap.of(\n PATIENT_1_ID, ImmutableList.of(PATIENT_1_AGE_21_RESOURCE_JSON));\n PCollection<CqlEvaluationResult> output = testPipeline.apply(Create.of(input))\n .apply(ParDo.of(new EvaluateCqlForContextFn(\n cqlToLibraries(\n \"library FooLibrary version '0.1'\\n\"\n + \"using FHIR version '4.0.1'\\n\"", "score": 0.8282710313796997 }, { "filename": "src/main/java/com/google/fhir/cql/beam/EvaluateCql.java", "retrieved_chunk": " \"Patient\", new ModelManager().resolveModel(\"FHIR\", \"4.0.1\").getModelInfo())))\n .apply(\"GroupByContext\", GroupByKey.<ResourceTypeAndId, String>create())\n .apply(\n \"EvaluateCql\",\n ParDo.of(\n new EvaluateCqlForContextFn(\n loadLibraries(toPath(options.getCqlFolder()), options.getCqlLibraries()),\n ImmutableSet.copyOf(options.getCqlLibraries()),\n loadFilesInDirectory(\n toPath(options.getValueSetFolder()),", "score": 0.8211554288864136 } ]
java
enterContext(contextValue.getType());
/* * Copyright (C) 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.fhir.cql.beam; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableSet.toImmutableSet; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.context.FhirVersionEnum; import ca.uhn.fhir.parser.IParser; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.json.JsonMapper; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.fhir.cql.beam.types.CqlEvaluationResult; import com.google.fhir.cql.beam.types.CqlLibraryId; import com.google.fhir.cql.beam.types.ResourceTypeAndId; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; import java.time.ZonedDateTime; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.values.KV; import org.cqframework.cql.elm.execution.ExpressionDef; import org.cqframework.cql.elm.execution.Library; import org.cqframework.cql.elm.execution.VersionedIdentifier; import org.hl7.fhir.r4.model.Bundle; import org.hl7.fhir.r4.model.Bundle.BundleType; import org.hl7.fhir.r4.model.Resource; import org.opencds.cqf.cql.engine.data.CompositeDataProvider; import org.opencds.cqf.cql.engine.execution.Context; import org.opencds.cqf.cql.engine.execution.InMemoryLibraryLoader; import org.opencds.cqf.cql.engine.execution.LibraryLoader; import org.opencds.cqf.cql.engine.fhir.model.R4FhirModelResolver; import org.opencds.cqf.cql.engine.model.ModelResolver; import org.opencds.cqf.cql.engine.retrieve.RetrieveProvider; import org.opencds.cqf.cql.engine.serializing.jackson.JsonCqlMapper; import org.opencds.cqf.cql.engine.terminology.TerminologyProvider; import org.opencds.cqf.cql.evaluator.engine.retrieve.BundleRetrieveProvider; import org.opencds.cqf.cql.evaluator.engine.terminology.BundleTerminologyProvider; /** * A function that evaluates a set of CQL libraries over the collection of resources, represented as * JSON strings, for a given context. The collection of resources should include every resource * necessary for evaluation of the CQL within the context (e.g., the entire Patient bundle). * * <p>The follow constraints currently exist: * * <ul> * <li>there is no support for accessing resources outside of the context (i.e., no support for * cross-context and related context retrieves). * <li>all resources for the context must fit within the memory of a worker. * <li>only boolean expressions are written to the resulting {@link CqlEvaluationResult} objects. * <li>there is no support for passing parameters to the CQL libraries. * </ul> */ public final class EvaluateCqlForContextFn extends DoFn<KV<ResourceTypeAndId, Iterable<String>>, CqlEvaluationResult> { /** A context that disallows evaluation of cross-context CQL expressions. */ private static class FixedContext extends Context { public FixedContext( Library library, ZonedDateTime evaluationZonedDateTime, ResourceTypeAndId contextValue) { super(library, evaluationZonedDateTime); super.setContextValue(contextValue.getType(),
contextValue.getId());
super.enterContext(contextValue.getType()); } @Override public void enterContext(String context) { if (!context.equals(getCurrentContext())) { throw new IllegalStateException("Context switching is not supported."); } super.enterContext(context); } } /** A wrapper around {@link Library} that supports Java serialization. */ private static class SerializableLibraryWrapper implements Serializable { private static JsonMapper jsonMapper = JsonCqlMapper.getMapper() .rebuild() .disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET) .disable(SerializationFeature.INDENT_OUTPUT) .build(); private Library library; public SerializableLibraryWrapper(Library library) { this.library = library; } public Library getLibrary() { return library; } private void readObject(ObjectInputStream inputStream) throws IOException { library = jsonMapper.readValue((InputStream) inputStream, Library.class); } private void writeObject(ObjectOutputStream outputStream) throws IOException { jsonMapper.writeValue((OutputStream) outputStream, library); } } private final ImmutableList<SerializableLibraryWrapper> cqlSources; private final ImmutableSet<CqlLibraryId> cqlLibraryIds; private final ImmutableList<String> valueSetJsonResources; private final ZonedDateTime evaluationDateTime; private final FhirVersionEnum fhirVersion; private transient ImmutableSet<VersionedIdentifier> cqlLibraryVersionedIdentifiers; private transient FhirContext fhirContext; private transient ModelResolver modelResolver; private transient TerminologyProvider terminologyProvider; private transient LibraryLoader libraryLoader; public EvaluateCqlForContextFn( Collection<Library> cqlSources, Set<CqlLibraryId> cqlLibraryIds, Collection<String> valueSetJsonResources, ZonedDateTime evaluationDateTime, FhirVersionEnum fhirVersion) { this.cqlSources = cqlSources.stream().map(SerializableLibraryWrapper::new).collect(toImmutableList()); this.cqlLibraryIds = ImmutableSet.copyOf(cqlLibraryIds); this.valueSetJsonResources = ImmutableList.copyOf(valueSetJsonResources); this.evaluationDateTime = checkNotNull(evaluationDateTime); this.fhirVersion = checkNotNull(fhirVersion); } @DoFn.Setup public void setup() { cqlLibraryVersionedIdentifiers = cqlLibraryIds.stream() .map(id -> new VersionedIdentifier().withId(id.getName()).withVersion(id.getVersion())) .collect(toImmutableSet()); fhirContext = new FhirContext(fhirVersion); modelResolver = new CachingModelResolver(new R4FhirModelResolver()); terminologyProvider = createTerminologyProvider(fhirContext, valueSetJsonResources); libraryLoader = new InMemoryLibraryLoader( cqlSources.stream() .map(SerializableLibraryWrapper::getLibrary) .collect(Collectors.toList())); } @ProcessElement public void processElement( @Element KV<ResourceTypeAndId, Iterable<String>> contextResources, OutputReceiver<CqlEvaluationResult> out) { RetrieveProvider retrieveProvider = createRetrieveProvider(contextResources.getValue()); for (VersionedIdentifier cqlLibraryId : cqlLibraryVersionedIdentifiers) { Library library = libraryLoader.load(cqlLibraryId); Context context = createContext(library, retrieveProvider, contextResources.getKey()); try { out.output( new CqlEvaluationResult( library.getIdentifier(), contextResources.getKey(), evaluationDateTime, evaluate(library, context, contextResources.getKey()))); } catch (Exception e) { out.output( new CqlEvaluationResult( library.getIdentifier(), contextResources.getKey(), evaluationDateTime, e)); } } } private Map<String, Boolean> evaluate( Library library, Context context, ResourceTypeAndId contextValue) { HashMap<String, Boolean> results = new HashMap<>(); for (ExpressionDef expression : library.getStatements().getDef()) { if (!expression.getContext().equals(contextValue.getType()) || !isBooleanExpression(expression)) { continue; } if (results.putIfAbsent(expression.getName(), (Boolean) expression.evaluate(context)) != null) { throw new InternalError("Duplicate expression name: " + expression.getName()); } } return results; } private static boolean isBooleanExpression(ExpressionDef expression) { return expression.getResultTypeName() != null && expression.getResultTypeName().getNamespaceURI().equals("urn:hl7-org:elm-types:r1") && expression.getResultTypeName().getLocalPart().equals("Boolean"); } private Context createContext( Library library, RetrieveProvider retrieveProvider, ResourceTypeAndId contextValue) { Context context = new FixedContext(library, evaluationDateTime, contextValue); context.setExpressionCaching(true); context.registerLibraryLoader(libraryLoader); context.registerTerminologyProvider(terminologyProvider); context.registerDataProvider( "http://hl7.org/fhir", new CompositeDataProvider(modelResolver, retrieveProvider)); // TODO(nasha): Set user defined parameters via `context.setParameter`. return context; } private static TerminologyProvider createTerminologyProvider( FhirContext fhirContext, ImmutableList<String> valueSetJsonStrings) { IParser parser = fhirContext.newJsonParser(); Bundle bundle = new Bundle(); bundle.setType(BundleType.COLLECTION); valueSetJsonStrings.stream() .map(parser::parseResource) .forEach((resource) -> bundle.addEntry().setResource((Resource) resource)); return new BundleTerminologyProvider(fhirContext, bundle); } private RetrieveProvider createRetrieveProvider(Iterable<String> jsonResource) { Bundle bundle = new Bundle(); bundle.setType(BundleType.COLLECTION); IParser parser = fhirContext.newJsonParser(); jsonResource.forEach( element -> { bundle.addEntry().setResource((Resource) parser.parseResource(element)); }); BundleRetrieveProvider provider = new BundleRetrieveProvider(fhirContext, bundle); provider.setTerminologyProvider(terminologyProvider); provider.setExpandValueSets(true); return provider; } }
src/main/java/com/google/fhir/cql/beam/EvaluateCqlForContextFn.java
google-cql-on-beam-82f1c68
[ { "filename": "src/test/java/com/google/fhir/cql/beam/EvaluateCqlForContextFnTest.java", "retrieved_chunk": " .apply(ParDo.of(new EvaluateCqlForContextFn(\n cqlToLibraries(\n \"library FooLibrary version '0.1'\\n\"\n + \"using FHIR version '4.0.1'\\n\"\n + \"context Unfiltered\\n\"\n + \"define \\\"Exp1\\\": true\\n\"\n + \"context Patient\\n\"\n + \"define \\\"Exp2\\\": \\\"Exp1\\\"\"),\n ImmutableSet.of(cqlLibraryId(\"FooLibrary\", \"0.1\")),\n ImmutableList.of(),", "score": 0.8483752012252808 }, { "filename": "src/test/java/com/google/fhir/cql/beam/EvaluateCqlForContextFnTest.java", "retrieved_chunk": "import org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.JUnit4;\nimport org.opencds.cqf.cql.evaluator.engine.elm.LibraryMapper;\n/** Tests for {@link EvaluateCqlForContextFn}. */\n@RunWith(JUnit4.class)\npublic class EvaluateCqlForContextFnTest {\n @Rule public TestPipeline testPipeline = TestPipeline.create();\n private static final ResourceTypeAndId PATIENT_1_ID = new ResourceTypeAndId(\"Patient\", \"1\");", "score": 0.8342229127883911 }, { "filename": "src/main/java/com/google/fhir/cql/beam/KeyForContextFn.java", "retrieved_chunk": "public final class KeyForContextFn extends DoFn<String, KV<ResourceTypeAndId, String>> {\n private static final Pattern REFERENCE_PATTERN = Pattern.compile(\"([^/]+)/([^/]+)\");\n private static final String REFERENCE_FIELD_NAME = \"reference\";\n private static final String SUBJECT_FIELD_NAME = \"subject\";\n private static final String PATIENT_FIELD_NAME = \"patient\";\n private final String context;\n private final ImmutableSetMultimap<String, String> relatedKeyElementByType;\n public KeyForContextFn(String context, ModelInfo modelInfo) {\n this.context = checkNotNull(context);\n this.relatedKeyElementByType = createRelatedKeyElementByTypeMap(context, modelInfo);", "score": 0.8322771191596985 }, { "filename": "src/test/java/com/google/fhir/cql/beam/EvaluateCqlForContextFnTest.java", "retrieved_chunk": " }\n @Test\n public void expressionsThatDontMatchContextAreSkipped() {\n ImmutableMap<ResourceTypeAndId, Iterable<String>> input = ImmutableMap.of(\n PATIENT_1_ID, ImmutableList.of(PATIENT_1_AGE_21_RESOURCE_JSON));\n PCollection<CqlEvaluationResult> output = testPipeline.apply(Create.of(input))\n .apply(ParDo.of(new EvaluateCqlForContextFn(\n cqlToLibraries(\n \"library FooLibrary version '0.1'\\n\"\n + \"using FHIR version '4.0.1'\\n\"", "score": 0.8275055885314941 }, { "filename": "src/test/java/com/google/fhir/cql/beam/EvaluateCqlForContextFnTest.java", "retrieved_chunk": " }\n @Test\n public void contextPopulated() {\n ImmutableMap<ResourceTypeAndId, Iterable<String>> input = ImmutableMap.of(\n PATIENT_1_ID, ImmutableList.of(PATIENT_1_AGE_21_RESOURCE_JSON));\n PCollection<CqlEvaluationResult> output = testPipeline.apply(Create.of(input))\n .apply(ParDo.of(new EvaluateCqlForContextFn(\n cqlToLibraries(\n \"library FooLibrary version '0.1'\\n\"\n + \"using FHIR version '4.0.1'\\n\"", "score": 0.816749095916748 } ]
java
contextValue.getId());
package com.dice.service; import com.dice.DTO.DiceSwDTO; import com.dice.DTO.ResultadoSwDTO; import com.dice.DTO.ResultadoSwForceDTO; import com.dice.model.Dice; import org.springframework.stereotype.Service; @Service public class StarWarsService { public StarWarsService() {} public ResultadoSwDTO rollSwDice(DiceSwDTO dice) { int success = 0; int triumph = 0; int advantage = 0; int failure = 0; int despair = 0; int threat = 0; // Obter os valores para cada tipo de dado. int boost = dice.getAmpliacao(); int ability = dice.getHabilidade(); int proficiency = dice.getProficiencia(); int setback = dice.getContratempo(); int difficulty = dice.getDificuldade(); int challenge = dice.getDesafio(); // Calcular os resultados dos dados. for (int i = 0; i < boost; i++) { Dice boostDice = new Dice(6); int result = boostDice.roll(); if (result == 1 || result == 2 ) { // Do nothing } else if (result == 3) { success += 1; } else if (result == 4) { success += 1; advantage += 1; } else if (result == 5) { advantage += 2; } else if (result == 6) { advantage += 1; } } for (int i = 0; i < ability; i++) { Dice abilityDice = new Dice(8); int result = abilityDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4) { success += 2; } else if (result == 5 || result == 6) { advantage += 1; } else if (result == 7) { success += 1; advantage += 1; } else if (result == 8) { advantage += 2; } } for (int i = 0; i < proficiency; i++) { Dice proficiencyDice = new Dice(12); int result = proficiencyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4 || result == 5) { success += 2; } else if (result == 6) { advantage += 1; } else if (result == 7 || result == 8 || result == 9) { success += 1; advantage += 1; } else if (result == 10 || result == 11) { advantage += 2; } else if (result == 12) { triumph += 1; } } for (int i = 0; i < setback; i++) { Dice setbackDice = new Dice(6); int result = setbackDice.roll(); if (result == 1 || result == 2) { // Do nothing } else if (result == 3 || result == 4) { failure += 1; } else if (result == 5 || result == 6) { threat += 1; } } for (int i = 0; i < difficulty; i++) { Dice difficultyDice = new Dice(8); int result = difficultyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2) { failure += 1; } else if (result == 3) { failure += 2; } else if (result == 4 || result == 5 || result == 6) { threat += 1; } else if (result == 7) { threat += 2; } else if (result == 8) { failure += 1; threat += 1; } } for (int i = 0; i < challenge; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { failure += 1; } else if (result == 4 || result == 5) { failure += 2; } else if (result == 6 || result == 7) { threat += 1; } else if (result == 8 || result == 9) { failure += 1; threat += 1; } else if (result == 10 || result == 11) { threat += 2; } else if (result == 12) { despair += 1; } } return getResultSwDice(success, triumph, advantage, failure, despair, threat); } private ResultadoSwDTO getResultSwDice(int success, int triumph, int advantage, int failure, int despair, int threat) { ResultadoSwDTO diceResult = new ResultadoSwDTO(); if (success - failure > 0) { diceResult.setSucessos(success - failure); diceResult.setFracassos(0); } else if (success - failure < 0) { diceResult.setSucessos(0); diceResult.setFracassos(failure - success); } else { diceResult.setSucessos(0); diceResult.setFracassos(0); } if (advantage - threat > 0) { diceResult.setVantagens(advantage - threat);
diceResult.setAmeacas(0);
} else if (advantage - threat < 0) { diceResult.setVantagens(0); diceResult.setAmeacas(threat - advantage); } else { diceResult.setVantagens(0); diceResult.setAmeacas(0); } if (triumph - despair > 0) { diceResult.setTriunfos(triumph - despair); diceResult.setDesesperos(0); } else if (triumph - despair < 0) { diceResult.setTriunfos(0); diceResult.setDesesperos(despair - triumph); } else { diceResult.setTriunfos(0); diceResult.setDesesperos(0); } return diceResult; } public ResultadoSwForceDTO rollForce(int quantity) { int light = 0; int dark = 0; for (int i = 0; i < quantity; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1 || result == 2 || result == 3 || result == 4 || result == 5 || result == 6) { dark += 1; } else if (result == 7) { dark += 2; } else if (result == 8 || result == 9) { light += 1; } else if (result == 10 || result == 11 || result == 12) { light += 2; } } ResultadoSwForceDTO forceResult = new ResultadoSwForceDTO(); forceResult.setLuz(light); forceResult.setNegro(dark); return forceResult; } }
src/main/java/com/dice/service/StarWarsService.java
grcreutzberg-dice-api-d58bb3d
[ { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " }\n int diceX = new Dice(dice).roll();\n int diceY = new Dice(dice).roll();\n int resultDice = new Dice(dice).roll();\n if (type.equalsIgnoreCase(\"Advantage\")) {\n return resultDice + Math.max(diceX, diceY); //Retorna Dado + Vantagem\n }\n return resultDice - Math.min(diceX, diceY); //Retorna Dado - Desvantagem\n }\n}", "score": 0.8801129460334778 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class ResultadoSwDTO {\n private int sucessos = 0;\n private int triunfos = 0;\n private int vantagens = 0;\n private int fracassos = 0;\n private int desesperos = 0;\n private int ameacas = 0;\n public int getSucessos() {\n return sucessos;", "score": 0.8402418494224548 }, { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " int[] results = new int[numberOfDice];\n Dice dice = new Dice(faces);\n for (int i = 0; i < numberOfDice; i++) {\n results[i] = dice.roll();\n }\n return results;\n }\n public int rollDisVantage(String type, int dice) {\n if (dice <= 0) {\n throw new IllegalArgumentException(\"O dado deve ser maior que zero.\");", "score": 0.8348006010055542 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": " }\n public void setSucessos(final int sucessos) {\n this.sucessos = sucessos;\n }\n public int getTriunfos() {\n return triunfos;\n }\n public void setTriunfos(final int triunfos) {\n this.triunfos = triunfos;\n }", "score": 0.8211561441421509 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": " public int getVantagens() {\n return vantagens;\n }\n public void setVantagens(final int vantagens) {\n this.vantagens = vantagens;\n }\n public int getFracassos() {\n return fracassos;\n }\n public void setFracassos(final int fracassos) {", "score": 0.8178920745849609 } ]
java
diceResult.setAmeacas(0);
package com.dice.service; import com.dice.DTO.DiceSwDTO; import com.dice.DTO.ResultadoSwDTO; import com.dice.DTO.ResultadoSwForceDTO; import com.dice.model.Dice; import org.springframework.stereotype.Service; @Service public class StarWarsService { public StarWarsService() {} public ResultadoSwDTO rollSwDice(DiceSwDTO dice) { int success = 0; int triumph = 0; int advantage = 0; int failure = 0; int despair = 0; int threat = 0; // Obter os valores para cada tipo de dado. int boost = dice.getAmpliacao(); int ability = dice.getHabilidade(); int proficiency = dice.getProficiencia(); int setback = dice.getContratempo(); int difficulty = dice.getDificuldade(); int challenge = dice.getDesafio(); // Calcular os resultados dos dados. for (int i = 0; i < boost; i++) { Dice boostDice = new Dice(6); int result = boostDice.roll(); if (result == 1 || result == 2 ) { // Do nothing } else if (result == 3) { success += 1; } else if (result == 4) { success += 1; advantage += 1; } else if (result == 5) { advantage += 2; } else if (result == 6) { advantage += 1; } } for (int i = 0; i < ability; i++) { Dice abilityDice = new Dice(8); int result = abilityDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4) { success += 2; } else if (result == 5 || result == 6) { advantage += 1; } else if (result == 7) { success += 1; advantage += 1; } else if (result == 8) { advantage += 2; } } for (int i = 0; i < proficiency; i++) { Dice proficiencyDice = new Dice(12); int result = proficiencyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4 || result == 5) { success += 2; } else if (result == 6) { advantage += 1; } else if (result == 7 || result == 8 || result == 9) { success += 1; advantage += 1; } else if (result == 10 || result == 11) { advantage += 2; } else if (result == 12) { triumph += 1; } } for (int i = 0; i < setback; i++) { Dice setbackDice = new Dice(6); int result = setbackDice.roll(); if (result == 1 || result == 2) { // Do nothing } else if (result == 3 || result == 4) { failure += 1; } else if (result == 5 || result == 6) { threat += 1; } } for (int i = 0; i < difficulty; i++) { Dice difficultyDice = new Dice(8); int result = difficultyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2) { failure += 1; } else if (result == 3) { failure += 2; } else if (result == 4 || result == 5 || result == 6) { threat += 1; } else if (result == 7) { threat += 2; } else if (result == 8) { failure += 1; threat += 1; } } for (int i = 0; i < challenge; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { failure += 1; } else if (result == 4 || result == 5) { failure += 2; } else if (result == 6 || result == 7) { threat += 1; } else if (result == 8 || result == 9) { failure += 1; threat += 1; } else if (result == 10 || result == 11) { threat += 2; } else if (result == 12) { despair += 1; } } return getResultSwDice(success, triumph, advantage, failure, despair, threat); } private ResultadoSwDTO getResultSwDice(int success, int triumph, int advantage, int failure, int despair, int threat) { ResultadoSwDTO diceResult = new ResultadoSwDTO(); if (success - failure > 0) { diceResult.setSucessos(success - failure);
diceResult.setFracassos(0);
} else if (success - failure < 0) { diceResult.setSucessos(0); diceResult.setFracassos(failure - success); } else { diceResult.setSucessos(0); diceResult.setFracassos(0); } if (advantage - threat > 0) { diceResult.setVantagens(advantage - threat); diceResult.setAmeacas(0); } else if (advantage - threat < 0) { diceResult.setVantagens(0); diceResult.setAmeacas(threat - advantage); } else { diceResult.setVantagens(0); diceResult.setAmeacas(0); } if (triumph - despair > 0) { diceResult.setTriunfos(triumph - despair); diceResult.setDesesperos(0); } else if (triumph - despair < 0) { diceResult.setTriunfos(0); diceResult.setDesesperos(despair - triumph); } else { diceResult.setTriunfos(0); diceResult.setDesesperos(0); } return diceResult; } public ResultadoSwForceDTO rollForce(int quantity) { int light = 0; int dark = 0; for (int i = 0; i < quantity; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1 || result == 2 || result == 3 || result == 4 || result == 5 || result == 6) { dark += 1; } else if (result == 7) { dark += 2; } else if (result == 8 || result == 9) { light += 1; } else if (result == 10 || result == 11 || result == 12) { light += 2; } } ResultadoSwForceDTO forceResult = new ResultadoSwForceDTO(); forceResult.setLuz(light); forceResult.setNegro(dark); return forceResult; } }
src/main/java/com/dice/service/StarWarsService.java
grcreutzberg-dice-api-d58bb3d
[ { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class ResultadoSwDTO {\n private int sucessos = 0;\n private int triunfos = 0;\n private int vantagens = 0;\n private int fracassos = 0;\n private int desesperos = 0;\n private int ameacas = 0;\n public int getSucessos() {\n return sucessos;", "score": 0.8830134868621826 }, { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " }\n int diceX = new Dice(dice).roll();\n int diceY = new Dice(dice).roll();\n int resultDice = new Dice(dice).roll();\n if (type.equalsIgnoreCase(\"Advantage\")) {\n return resultDice + Math.max(diceX, diceY); //Retorna Dado + Vantagem\n }\n return resultDice - Math.min(diceX, diceY); //Retorna Dado - Desvantagem\n }\n}", "score": 0.852735161781311 }, { "filename": "src/main/java/com/dice/DTO/DiceSwDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class DiceSwDTO {\n private int habilidade = 0;\n private int proficiencia = 0;\n private int dificuldade = 0;\n private int desafio = 0;\n private int ampliacao = 0;\n private int contratempo = 0;\n public int getHabilidade() {\n return habilidade;", "score": 0.8387177586555481 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwForceDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class ResultadoSwForceDTO {\n private int luz = 0;\n private int negro = 0;\n public int getLuz() {\n return luz;\n }\n public void setLuz(final int luz) {\n this.luz = luz;\n }", "score": 0.8356890678405762 }, { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " int[] results = new int[numberOfDice];\n Dice dice = new Dice(faces);\n for (int i = 0; i < numberOfDice; i++) {\n results[i] = dice.roll();\n }\n return results;\n }\n public int rollDisVantage(String type, int dice) {\n if (dice <= 0) {\n throw new IllegalArgumentException(\"O dado deve ser maior que zero.\");", "score": 0.8260800242424011 } ]
java
diceResult.setFracassos(0);
package com.dice.service; import com.dice.DTO.DiceSwDTO; import com.dice.DTO.ResultadoSwDTO; import com.dice.DTO.ResultadoSwForceDTO; import com.dice.model.Dice; import org.springframework.stereotype.Service; @Service public class StarWarsService { public StarWarsService() {} public ResultadoSwDTO rollSwDice(DiceSwDTO dice) { int success = 0; int triumph = 0; int advantage = 0; int failure = 0; int despair = 0; int threat = 0; // Obter os valores para cada tipo de dado. int boost = dice.getAmpliacao(); int ability = dice.getHabilidade(); int proficiency = dice.getProficiencia(); int setback = dice.getContratempo(); int difficulty = dice.getDificuldade(); int challenge = dice.getDesafio(); // Calcular os resultados dos dados. for (int i = 0; i < boost; i++) { Dice boostDice = new Dice(6); int result = boostDice.roll(); if (result == 1 || result == 2 ) { // Do nothing } else if (result == 3) { success += 1; } else if (result == 4) { success += 1; advantage += 1; } else if (result == 5) { advantage += 2; } else if (result == 6) { advantage += 1; } } for (int i = 0; i < ability; i++) { Dice abilityDice = new Dice(8); int result = abilityDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4) { success += 2; } else if (result == 5 || result == 6) { advantage += 1; } else if (result == 7) { success += 1; advantage += 1; } else if (result == 8) { advantage += 2; } } for (int i = 0; i < proficiency; i++) { Dice proficiencyDice = new Dice(12); int result = proficiencyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4 || result == 5) { success += 2; } else if (result == 6) { advantage += 1; } else if (result == 7 || result == 8 || result == 9) { success += 1; advantage += 1; } else if (result == 10 || result == 11) { advantage += 2; } else if (result == 12) { triumph += 1; } } for (int i = 0; i < setback; i++) { Dice setbackDice = new Dice(6); int result = setbackDice.roll(); if (result == 1 || result == 2) { // Do nothing } else if (result == 3 || result == 4) { failure += 1; } else if (result == 5 || result == 6) { threat += 1; } } for (int i = 0; i < difficulty; i++) { Dice difficultyDice = new Dice(8); int result = difficultyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2) { failure += 1; } else if (result == 3) { failure += 2; } else if (result == 4 || result == 5 || result == 6) { threat += 1; } else if (result == 7) { threat += 2; } else if (result == 8) { failure += 1; threat += 1; } } for (int i = 0; i < challenge; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { failure += 1; } else if (result == 4 || result == 5) { failure += 2; } else if (result == 6 || result == 7) { threat += 1; } else if (result == 8 || result == 9) { failure += 1; threat += 1; } else if (result == 10 || result == 11) { threat += 2; } else if (result == 12) { despair += 1; } } return getResultSwDice(success, triumph, advantage, failure, despair, threat); } private ResultadoSwDTO getResultSwDice(int success, int triumph, int advantage, int failure, int despair, int threat) { ResultadoSwDTO diceResult = new ResultadoSwDTO(); if (success - failure > 0) { diceResult.setSucessos(success - failure); diceResult.setFracassos(0); } else if (success - failure < 0) { diceResult.setSucessos(0);
diceResult.setFracassos(failure - success);
} else { diceResult.setSucessos(0); diceResult.setFracassos(0); } if (advantage - threat > 0) { diceResult.setVantagens(advantage - threat); diceResult.setAmeacas(0); } else if (advantage - threat < 0) { diceResult.setVantagens(0); diceResult.setAmeacas(threat - advantage); } else { diceResult.setVantagens(0); diceResult.setAmeacas(0); } if (triumph - despair > 0) { diceResult.setTriunfos(triumph - despair); diceResult.setDesesperos(0); } else if (triumph - despair < 0) { diceResult.setTriunfos(0); diceResult.setDesesperos(despair - triumph); } else { diceResult.setTriunfos(0); diceResult.setDesesperos(0); } return diceResult; } public ResultadoSwForceDTO rollForce(int quantity) { int light = 0; int dark = 0; for (int i = 0; i < quantity; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1 || result == 2 || result == 3 || result == 4 || result == 5 || result == 6) { dark += 1; } else if (result == 7) { dark += 2; } else if (result == 8 || result == 9) { light += 1; } else if (result == 10 || result == 11 || result == 12) { light += 2; } } ResultadoSwForceDTO forceResult = new ResultadoSwForceDTO(); forceResult.setLuz(light); forceResult.setNegro(dark); return forceResult; } }
src/main/java/com/dice/service/StarWarsService.java
grcreutzberg-dice-api-d58bb3d
[ { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class ResultadoSwDTO {\n private int sucessos = 0;\n private int triunfos = 0;\n private int vantagens = 0;\n private int fracassos = 0;\n private int desesperos = 0;\n private int ameacas = 0;\n public int getSucessos() {\n return sucessos;", "score": 0.8859419226646423 }, { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " }\n int diceX = new Dice(dice).roll();\n int diceY = new Dice(dice).roll();\n int resultDice = new Dice(dice).roll();\n if (type.equalsIgnoreCase(\"Advantage\")) {\n return resultDice + Math.max(diceX, diceY); //Retorna Dado + Vantagem\n }\n return resultDice - Math.min(diceX, diceY); //Retorna Dado - Desvantagem\n }\n}", "score": 0.8570284843444824 }, { "filename": "src/main/java/com/dice/DTO/DiceSwDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class DiceSwDTO {\n private int habilidade = 0;\n private int proficiencia = 0;\n private int dificuldade = 0;\n private int desafio = 0;\n private int ampliacao = 0;\n private int contratempo = 0;\n public int getHabilidade() {\n return habilidade;", "score": 0.8383647799491882 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwForceDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class ResultadoSwForceDTO {\n private int luz = 0;\n private int negro = 0;\n public int getLuz() {\n return luz;\n }\n public void setLuz(final int luz) {\n this.luz = luz;\n }", "score": 0.837572455406189 }, { "filename": "src/main/java/com/dice/controller/DiceRollController.java", "retrieved_chunk": " @GetMapping(\"/advantage\")\n public int rollAdvantage(\n @RequestParam(name = \"dice\", defaultValue = \"20\") int dice\n ) {\n return service.rollDisVantage(\"Advantage\", dice);\n }\n @GetMapping(\"/disadvantage\")\n public int rollDisadvantage(\n @RequestParam(name = \"dice\", defaultValue = \"20\") int dice\n ) {", "score": 0.8271108269691467 } ]
java
diceResult.setFracassos(failure - success);
package com.dice.service; import com.dice.DTO.DiceSwDTO; import com.dice.DTO.ResultadoSwDTO; import com.dice.DTO.ResultadoSwForceDTO; import com.dice.model.Dice; import org.springframework.stereotype.Service; @Service public class StarWarsService { public StarWarsService() {} public ResultadoSwDTO rollSwDice(DiceSwDTO dice) { int success = 0; int triumph = 0; int advantage = 0; int failure = 0; int despair = 0; int threat = 0; // Obter os valores para cada tipo de dado. int boost = dice.getAmpliacao(); int ability = dice.getHabilidade(); int proficiency = dice.getProficiencia(); int setback = dice.getContratempo(); int difficulty = dice.getDificuldade(); int challenge = dice.getDesafio(); // Calcular os resultados dos dados. for (int i = 0; i < boost; i++) { Dice boostDice = new Dice(6); int result = boostDice.roll(); if (result == 1 || result == 2 ) { // Do nothing } else if (result == 3) { success += 1; } else if (result == 4) { success += 1; advantage += 1; } else if (result == 5) { advantage += 2; } else if (result == 6) { advantage += 1; } } for (int i = 0; i < ability; i++) { Dice abilityDice = new Dice(8); int result = abilityDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4) { success += 2; } else if (result == 5 || result == 6) { advantage += 1; } else if (result == 7) { success += 1; advantage += 1; } else if (result == 8) { advantage += 2; } } for (int i = 0; i < proficiency; i++) { Dice proficiencyDice = new Dice(12); int result = proficiencyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4 || result == 5) { success += 2; } else if (result == 6) { advantage += 1; } else if (result == 7 || result == 8 || result == 9) { success += 1; advantage += 1; } else if (result == 10 || result == 11) { advantage += 2; } else if (result == 12) { triumph += 1; } } for (int i = 0; i < setback; i++) { Dice setbackDice = new Dice(6); int result = setbackDice.roll(); if (result == 1 || result == 2) { // Do nothing } else if (result == 3 || result == 4) { failure += 1; } else if (result == 5 || result == 6) { threat += 1; } } for (int i = 0; i < difficulty; i++) { Dice difficultyDice = new Dice(8); int result = difficultyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2) { failure += 1; } else if (result == 3) { failure += 2; } else if (result == 4 || result == 5 || result == 6) { threat += 1; } else if (result == 7) { threat += 2; } else if (result == 8) { failure += 1; threat += 1; } } for (int i = 0; i < challenge; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { failure += 1; } else if (result == 4 || result == 5) { failure += 2; } else if (result == 6 || result == 7) { threat += 1; } else if (result == 8 || result == 9) { failure += 1; threat += 1; } else if (result == 10 || result == 11) { threat += 2; } else if (result == 12) { despair += 1; } } return getResultSwDice(success, triumph, advantage, failure, despair, threat); } private ResultadoSwDTO getResultSwDice(int success, int triumph, int advantage, int failure, int despair, int threat) { ResultadoSwDTO diceResult = new ResultadoSwDTO(); if (success - failure > 0) {
diceResult.setSucessos(success - failure);
diceResult.setFracassos(0); } else if (success - failure < 0) { diceResult.setSucessos(0); diceResult.setFracassos(failure - success); } else { diceResult.setSucessos(0); diceResult.setFracassos(0); } if (advantage - threat > 0) { diceResult.setVantagens(advantage - threat); diceResult.setAmeacas(0); } else if (advantage - threat < 0) { diceResult.setVantagens(0); diceResult.setAmeacas(threat - advantage); } else { diceResult.setVantagens(0); diceResult.setAmeacas(0); } if (triumph - despair > 0) { diceResult.setTriunfos(triumph - despair); diceResult.setDesesperos(0); } else if (triumph - despair < 0) { diceResult.setTriunfos(0); diceResult.setDesesperos(despair - triumph); } else { diceResult.setTriunfos(0); diceResult.setDesesperos(0); } return diceResult; } public ResultadoSwForceDTO rollForce(int quantity) { int light = 0; int dark = 0; for (int i = 0; i < quantity; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1 || result == 2 || result == 3 || result == 4 || result == 5 || result == 6) { dark += 1; } else if (result == 7) { dark += 2; } else if (result == 8 || result == 9) { light += 1; } else if (result == 10 || result == 11 || result == 12) { light += 2; } } ResultadoSwForceDTO forceResult = new ResultadoSwForceDTO(); forceResult.setLuz(light); forceResult.setNegro(dark); return forceResult; } }
src/main/java/com/dice/service/StarWarsService.java
grcreutzberg-dice-api-d58bb3d
[ { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class ResultadoSwDTO {\n private int sucessos = 0;\n private int triunfos = 0;\n private int vantagens = 0;\n private int fracassos = 0;\n private int desesperos = 0;\n private int ameacas = 0;\n public int getSucessos() {\n return sucessos;", "score": 0.8811761736869812 }, { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " }\n int diceX = new Dice(dice).roll();\n int diceY = new Dice(dice).roll();\n int resultDice = new Dice(dice).roll();\n if (type.equalsIgnoreCase(\"Advantage\")) {\n return resultDice + Math.max(diceX, diceY); //Retorna Dado + Vantagem\n }\n return resultDice - Math.min(diceX, diceY); //Retorna Dado - Desvantagem\n }\n}", "score": 0.8581258058547974 }, { "filename": "src/main/java/com/dice/DTO/DiceSwDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class DiceSwDTO {\n private int habilidade = 0;\n private int proficiencia = 0;\n private int dificuldade = 0;\n private int desafio = 0;\n private int ampliacao = 0;\n private int contratempo = 0;\n public int getHabilidade() {\n return habilidade;", "score": 0.8332737684249878 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwForceDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class ResultadoSwForceDTO {\n private int luz = 0;\n private int negro = 0;\n public int getLuz() {\n return luz;\n }\n public void setLuz(final int luz) {\n this.luz = luz;\n }", "score": 0.8323431015014648 }, { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " int[] results = new int[numberOfDice];\n Dice dice = new Dice(faces);\n for (int i = 0; i < numberOfDice; i++) {\n results[i] = dice.roll();\n }\n return results;\n }\n public int rollDisVantage(String type, int dice) {\n if (dice <= 0) {\n throw new IllegalArgumentException(\"O dado deve ser maior que zero.\");", "score": 0.8279597759246826 } ]
java
diceResult.setSucessos(success - failure);
/* * Copyright (C) 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.fhir.cql.beam; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.ImmutableList.toImmutableList; import ca.uhn.fhir.context.FhirVersionEnum; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.fhir.cql.beam.types.CqlEvaluationResult; import com.google.fhir.cql.beam.types.CqlLibraryId; import com.google.fhir.cql.beam.types.ResourceTypeAndId; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Path; import java.nio.file.Paths; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.function.Function; import java.util.function.Predicate; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.extensions.avro.io.AvroIO; import org.apache.beam.sdk.io.TextIO; import org.apache.beam.sdk.options.Description; import org.apache.beam.sdk.options.PipelineOptions; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.apache.beam.sdk.options.Validation.Required; import org.apache.beam.sdk.transforms.GroupByKey; import org.apache.beam.sdk.transforms.ParDo; import org.cqframework.cql.cql2elm.CqlCompilerException; import org.cqframework.cql.cql2elm.CqlCompilerException.ErrorSeverity; import org.cqframework.cql.cql2elm.CqlTranslatorOptions; import org.cqframework.cql.cql2elm.CqlTranslatorOptions.Options; import org.cqframework.cql.cql2elm.LibraryManager; import org.cqframework.cql.cql2elm.ModelManager; import org.cqframework.cql.cql2elm.model.CompiledLibrary; import org.cqframework.cql.elm.execution.Library; import org.opencds.cqf.cql.evaluator.cql2elm.content.InMemoryLibrarySourceProvider; import org.opencds.cqf.cql.evaluator.engine.elm.LibraryMapper; /** * Main entry point for evaluating CQL libraries over a set of FHIR records with Apache Beam. * * <p>See README.md for additional information. */ public final class EvaluateCql { /** * Options supported by {@link EvaluateCql}. */ public interface EvaluateCqlOptions extends PipelineOptions { @Description( "The file pattern of the NDJSON FHIR files to read. Follows the conventions of " + "https://docs.oracle.com/javase/tutorial/essential/io/fileOps.html#glob.") @Required String getNdjsonFhirFilePattern(); void setNdjsonFhirFilePattern(String value); @Description( "Path to a folder that contains ValueSet FHIR records. Each file must contain exactly one " + "ValueSet FHIR record. Subfolders and their content are ignored.") @Required String getValueSetFolder(); void setValueSetFolder(String value); @Description( "Path to a folder that contains CQL libraries. Subfolders and their content are ignored.") @Required String getCqlFolder(); void setCqlFolder(String value); @Description( "A list of CQL library IDs and, optionally, versions that will be evaluated " + "against the provided FHIR. Format: " + "[{\"name\": \"ColorectalCancerScreeningsFHIR\"}, " + "{\"name\": \"ControllingHighBloodPressureFHIR\" \"version\": \"0.0.002\"}]") @Required @JsonSerialize @JsonDeserialize List<CqlLibraryId> getCqlLibraries(); void setCqlLibraries(List<CqlLibraryId> value); @Description("Path and name prefix of the file shards that will contain the pipeline output.") @Required String getOutputFilenamePrefix(); void setOutputFilenamePrefix(String value); } private static ImmutableList<String> loadFilesInDirectory( Path directory, Predicate<Path> pathFilter) { try { return FileLoader.loadFilesInDirectory(directory, pathFilter); } catch (IOException e) { throw new RuntimeException("Failed to read files in " + directory, e); } } private static Path toPath(String directory) { try { URI directoryUri = new URI(directory); if (new URI(directory).getScheme() != null) { return Paths.get(directoryUri); } } catch (URISyntaxException e) { // Fall through and treat as a file:// directory. } return new File(directory).toPath(); } private static final Options[] TRANSLATOR_OPTIONS = { Options.DisableListPromotion, Options.DisableListDemotion, Options.EnableResultTypes, Options.EnableLocators }; private static ImmutableList<Library> loadLibraries( Path cqlFolder, Collection<CqlLibraryId> cqlLibraryIds) { LibraryManager libraryManager = new LibraryManager(new ModelManager()); libraryManager .getLibrarySourceLoader() .registerProvider( new InMemoryLibrarySourceProvider( loadFilesInDirectory(cqlFolder, (path) -> path.toString().endsWith(".cql")))); libraryManager.enableCache(); for (CqlLibraryId libraryIds : cqlLibraryIds) { List<CqlCompilerException> errors = new ArrayList<>(); libraryManager.resolveLibrary( new org.hl7.elm.r1.VersionedIdentifier() .withId(libraryIds.getName()) .withVersion
(libraryIds.getVersion()), new CqlTranslatorOptions(TRANSLATOR_OPTIONS), errors);
if (errors.stream().filter(error -> error.getSeverity().equals(ErrorSeverity.Error)).count() > 0) { throw new RuntimeException( "Errors encountered while compiling CQL. " + errors.toString()); } } return libraryManager.getCompiledLibraries().values().stream() .map(CompiledLibrary::getLibrary) .map(LibraryMapper.INSTANCE::map) .collect(toImmutableList()); } private static void assemblePipeline( Pipeline pipeline, EvaluateCqlOptions options, ZonedDateTime evaluationDateTime) { checkArgument( !options.getCqlLibraries().isEmpty(), "At least one CQL library must be specified."); pipeline .apply("ReadNDJSON", TextIO.read().from(options.getNdjsonFhirFilePattern())) .apply("KeyForContext", ParDo.of(new KeyForContextFn( "Patient", new ModelManager().resolveModel("FHIR", "4.0.1").getModelInfo()))) .apply("GroupByContext", GroupByKey.<ResourceTypeAndId, String>create()) .apply( "EvaluateCql", ParDo.of( new EvaluateCqlForContextFn( loadLibraries(toPath(options.getCqlFolder()), options.getCqlLibraries()), ImmutableSet.copyOf(options.getCqlLibraries()), loadFilesInDirectory( toPath(options.getValueSetFolder()), (path) -> path.toString().endsWith(".json")), evaluationDateTime, FhirVersionEnum.R4))) .apply( "WriteCqlOutput", AvroIO.write(CqlEvaluationResult.class) .withSchema(CqlEvaluationResult.ResultCoder.SCHEMA) .to(options.getOutputFilenamePrefix()) .withSuffix(".avro")); } @VisibleForTesting static void runPipeline( Function<EvaluateCqlOptions, Pipeline> pipelineCreator, String[] args, ZonedDateTime evaluationDateTime) { EvaluateCqlOptions options = PipelineOptionsFactory.fromArgs(args).withValidation().as(EvaluateCqlOptions.class); Pipeline pipeline = pipelineCreator.apply(options); assemblePipeline(pipeline, options, evaluationDateTime); pipeline.run().waitUntilFinish(); } public static void main(String[] args) { runPipeline(Pipeline::create, args, ZonedDateTime.now()); } }
src/main/java/com/google/fhir/cql/beam/EvaluateCql.java
google-cql-on-beam-82f1c68
[ { "filename": "src/test/java/com/google/fhir/cql/beam/EvaluateCqlForContextFnTest.java", "retrieved_chunk": " try {\n for (String cql : cqlStrings) {\n libraries.add(LibraryMapper.INSTANCE.map(compiler.run(\n cql, Options.EnableResultTypes, Options.EnableLocators)));\n assertThat(compiler.getExceptions()).isEmpty();\n }\n return libraries;\n } catch (IOException e) {\n throw new RuntimeException(e);\n }", "score": 0.8813837766647339 }, { "filename": "src/test/java/com/google/fhir/cql/beam/EvaluateCqlForContextFnTest.java", "retrieved_chunk": " private static VersionedIdentifier versionedIdentifier(String id, String version) {\n VersionedIdentifier versionedIdentifier = new VersionedIdentifier();\n versionedIdentifier.setId(id);\n versionedIdentifier.setVersion(version);\n return versionedIdentifier;\n }\n private static Collection<Library> cqlToLibraries(String... cqlStrings) {\n ModelManager modelManager = new ModelManager();\n CqlCompiler compiler = new CqlCompiler(modelManager, new LibraryManager(modelManager));\n Collection<Library> libraries = new ArrayList<>();", "score": 0.8581433296203613 }, { "filename": "src/main/java/com/google/fhir/cql/beam/EvaluateCqlForContextFn.java", "retrieved_chunk": " .map(SerializableLibraryWrapper::getLibrary)\n .collect(Collectors.toList()));\n }\n @ProcessElement\n public void processElement(\n @Element KV<ResourceTypeAndId, Iterable<String>> contextResources,\n OutputReceiver<CqlEvaluationResult> out) {\n RetrieveProvider retrieveProvider = createRetrieveProvider(contextResources.getValue());\n for (VersionedIdentifier cqlLibraryId : cqlLibraryVersionedIdentifiers) {\n Library library = libraryLoader.load(cqlLibraryId);", "score": 0.8460839986801147 }, { "filename": "src/test/java/com/google/fhir/cql/beam/types/CqlLibraryIdTest.java", "retrieved_chunk": " new CqlLibraryId(\"Foo\", \"1.0\"),\n new CqlLibraryId(new VersionedIdentifier().withId(\"Foo\").withVersion(\"1.0\")))\n .addEqualityGroup(\n new CqlLibraryId(\"Bar\", null),\n new CqlLibraryId(new VersionedIdentifier().withId(\"Bar\")))\n .addEqualityGroup(new CqlLibraryId(\"Foo\", \"2.0\"))\n .addEqualityGroup(new CqlLibraryId(\"Bar\", \"1.0\"))\n .testEquals();\n }\n}", "score": 0.8275581002235413 }, { "filename": "src/main/java/com/google/fhir/cql/beam/EvaluateCqlForContextFn.java", "retrieved_chunk": " private final FhirVersionEnum fhirVersion;\n private transient ImmutableSet<VersionedIdentifier> cqlLibraryVersionedIdentifiers;\n private transient FhirContext fhirContext;\n private transient ModelResolver modelResolver;\n private transient TerminologyProvider terminologyProvider;\n private transient LibraryLoader libraryLoader;\n public EvaluateCqlForContextFn(\n Collection<Library> cqlSources,\n Set<CqlLibraryId> cqlLibraryIds,\n Collection<String> valueSetJsonResources,", "score": 0.8271565437316895 } ]
java
(libraryIds.getVersion()), new CqlTranslatorOptions(TRANSLATOR_OPTIONS), errors);
package com.dice.controller; import com.dice.service.DiceRollService; 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; @RestController @RequestMapping("/v1/dice") public class DiceRollController { private final DiceRollService service; public DiceRollController(DiceRollService diceRollService) { this.service = diceRollService; } @GetMapping("/roll") public int[] rollDice( @RequestParam(name = "quantity", defaultValue = "1") int quantity, @RequestParam(name = "faces", defaultValue = "20") int faces ) { return service.rollDice(quantity, faces); } @GetMapping("/advantage") public int rollAdvantage( @RequestParam(name = "dice", defaultValue = "20") int dice ) { return
service.rollDisVantage("Advantage", dice);
} @GetMapping("/disadvantage") public int rollDisadvantage( @RequestParam(name = "dice", defaultValue = "20") int dice ) { return service.rollDisVantage("Disadvantage", dice); } }
src/main/java/com/dice/controller/DiceRollController.java
grcreutzberg-dice-api-d58bb3d
[ { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": "package com.dice.service;\nimport com.dice.model.Dice;\nimport org.springframework.stereotype.Service;\n@Service\npublic class DiceRollService {\n public DiceRollService() {}\n public int[] rollDice(int numberOfDice, int faces) {\n if (numberOfDice <= 0) {\n throw new IllegalArgumentException(\"A quantidade de dados deve ser maior que zero.\");\n }", "score": 0.8789832592010498 }, { "filename": "src/main/java/com/dice/controller/StarWarsController.java", "retrieved_chunk": " }\n @PostMapping(\"/roll\")\n public ResponseEntity<ResultadoSwDTO> rollDice(@RequestBody DiceSwDTO dice) {\n return new ResponseEntity<ResultadoSwDTO>(service.rollSwDice(dice), HttpStatus.OK);\n }\n}", "score": 0.8711756467819214 }, { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " int[] results = new int[numberOfDice];\n Dice dice = new Dice(faces);\n for (int i = 0; i < numberOfDice; i++) {\n results[i] = dice.roll();\n }\n return results;\n }\n public int rollDisVantage(String type, int dice) {\n if (dice <= 0) {\n throw new IllegalArgumentException(\"O dado deve ser maior que zero.\");", "score": 0.8584578037261963 }, { "filename": "src/main/java/com/dice/controller/StarWarsController.java", "retrieved_chunk": "public class StarWarsController {\n private final StarWarsService service;\n public StarWarsController(StarWarsService starWarsService) {\n this.service = starWarsService;\n }\n @GetMapping(\"/force\")\n public ResponseEntity<ResultadoSwForceDTO> rollForce(\n @RequestParam(name = \"quantity\", defaultValue = \"1\") int quantity\n ) {\n return new ResponseEntity<ResultadoSwForceDTO>(service.rollForce(quantity), HttpStatus.OK);", "score": 0.8583551049232483 }, { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " }\n int diceX = new Dice(dice).roll();\n int diceY = new Dice(dice).roll();\n int resultDice = new Dice(dice).roll();\n if (type.equalsIgnoreCase(\"Advantage\")) {\n return resultDice + Math.max(diceX, diceY); //Retorna Dado + Vantagem\n }\n return resultDice - Math.min(diceX, diceY); //Retorna Dado - Desvantagem\n }\n}", "score": 0.8553736209869385 } ]
java
service.rollDisVantage("Advantage", dice);
package com.dice.service; import com.dice.DTO.DiceSwDTO; import com.dice.DTO.ResultadoSwDTO; import com.dice.DTO.ResultadoSwForceDTO; import com.dice.model.Dice; import org.springframework.stereotype.Service; @Service public class StarWarsService { public StarWarsService() {} public ResultadoSwDTO rollSwDice(DiceSwDTO dice) { int success = 0; int triumph = 0; int advantage = 0; int failure = 0; int despair = 0; int threat = 0; // Obter os valores para cada tipo de dado. int boost = dice.getAmpliacao(); int ability = dice.getHabilidade(); int proficiency = dice.getProficiencia(); int setback = dice.getContratempo(); int difficulty = dice.getDificuldade(); int challenge = dice.getDesafio(); // Calcular os resultados dos dados. for (int i = 0; i < boost; i++) { Dice boostDice = new Dice(6); int result = boostDice.roll(); if (result == 1 || result == 2 ) { // Do nothing } else if (result == 3) { success += 1; } else if (result == 4) { success += 1; advantage += 1; } else if (result == 5) { advantage += 2; } else if (result == 6) { advantage += 1; } } for (int i = 0; i < ability; i++) { Dice abilityDice = new Dice(8); int result = abilityDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4) { success += 2; } else if (result == 5 || result == 6) { advantage += 1; } else if (result == 7) { success += 1; advantage += 1; } else if (result == 8) { advantage += 2; } } for (int i = 0; i < proficiency; i++) { Dice proficiencyDice = new Dice(12); int result = proficiencyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4 || result == 5) { success += 2; } else if (result == 6) { advantage += 1; } else if (result == 7 || result == 8 || result == 9) { success += 1; advantage += 1; } else if (result == 10 || result == 11) { advantage += 2; } else if (result == 12) { triumph += 1; } } for (int i = 0; i < setback; i++) { Dice setbackDice = new Dice(6); int result = setbackDice.roll(); if (result == 1 || result == 2) { // Do nothing } else if (result == 3 || result == 4) { failure += 1; } else if (result == 5 || result == 6) { threat += 1; } } for (int i = 0; i < difficulty; i++) { Dice difficultyDice = new Dice(8); int result = difficultyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2) { failure += 1; } else if (result == 3) { failure += 2; } else if (result == 4 || result == 5 || result == 6) { threat += 1; } else if (result == 7) { threat += 2; } else if (result == 8) { failure += 1; threat += 1; } } for (int i = 0; i < challenge; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { failure += 1; } else if (result == 4 || result == 5) { failure += 2; } else if (result == 6 || result == 7) { threat += 1; } else if (result == 8 || result == 9) { failure += 1; threat += 1; } else if (result == 10 || result == 11) { threat += 2; } else if (result == 12) { despair += 1; } } return getResultSwDice(success, triumph, advantage, failure, despair, threat); } private ResultadoSwDTO getResultSwDice(int success, int triumph, int advantage, int failure, int despair, int threat) { ResultadoSwDTO diceResult = new ResultadoSwDTO(); if (success - failure > 0) { diceResult.setSucessos(success - failure); diceResult.setFracassos(0); } else if (success - failure < 0) { diceResult.setSucessos(0); diceResult.setFracassos(failure - success); } else { diceResult.setSucessos(0); diceResult.setFracassos(0); } if (advantage - threat > 0) {
diceResult.setVantagens(advantage - threat);
diceResult.setAmeacas(0); } else if (advantage - threat < 0) { diceResult.setVantagens(0); diceResult.setAmeacas(threat - advantage); } else { diceResult.setVantagens(0); diceResult.setAmeacas(0); } if (triumph - despair > 0) { diceResult.setTriunfos(triumph - despair); diceResult.setDesesperos(0); } else if (triumph - despair < 0) { diceResult.setTriunfos(0); diceResult.setDesesperos(despair - triumph); } else { diceResult.setTriunfos(0); diceResult.setDesesperos(0); } return diceResult; } public ResultadoSwForceDTO rollForce(int quantity) { int light = 0; int dark = 0; for (int i = 0; i < quantity; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1 || result == 2 || result == 3 || result == 4 || result == 5 || result == 6) { dark += 1; } else if (result == 7) { dark += 2; } else if (result == 8 || result == 9) { light += 1; } else if (result == 10 || result == 11 || result == 12) { light += 2; } } ResultadoSwForceDTO forceResult = new ResultadoSwForceDTO(); forceResult.setLuz(light); forceResult.setNegro(dark); return forceResult; } }
src/main/java/com/dice/service/StarWarsService.java
grcreutzberg-dice-api-d58bb3d
[ { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " }\n int diceX = new Dice(dice).roll();\n int diceY = new Dice(dice).roll();\n int resultDice = new Dice(dice).roll();\n if (type.equalsIgnoreCase(\"Advantage\")) {\n return resultDice + Math.max(diceX, diceY); //Retorna Dado + Vantagem\n }\n return resultDice - Math.min(diceX, diceY); //Retorna Dado - Desvantagem\n }\n}", "score": 0.8806064128875732 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class ResultadoSwDTO {\n private int sucessos = 0;\n private int triunfos = 0;\n private int vantagens = 0;\n private int fracassos = 0;\n private int desesperos = 0;\n private int ameacas = 0;\n public int getSucessos() {\n return sucessos;", "score": 0.8475358486175537 }, { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " int[] results = new int[numberOfDice];\n Dice dice = new Dice(faces);\n for (int i = 0; i < numberOfDice; i++) {\n results[i] = dice.roll();\n }\n return results;\n }\n public int rollDisVantage(String type, int dice) {\n if (dice <= 0) {\n throw new IllegalArgumentException(\"O dado deve ser maior que zero.\");", "score": 0.8397704362869263 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": " public int getVantagens() {\n return vantagens;\n }\n public void setVantagens(final int vantagens) {\n this.vantagens = vantagens;\n }\n public int getFracassos() {\n return fracassos;\n }\n public void setFracassos(final int fracassos) {", "score": 0.823508620262146 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": " }\n public void setSucessos(final int sucessos) {\n this.sucessos = sucessos;\n }\n public int getTriunfos() {\n return triunfos;\n }\n public void setTriunfos(final int triunfos) {\n this.triunfos = triunfos;\n }", "score": 0.8225504159927368 } ]
java
diceResult.setVantagens(advantage - threat);
/* * Copyright (C) 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.fhir.cql.beam; import java.util.concurrent.ConcurrentHashMap; import org.opencds.cqf.cql.engine.model.ModelResolver; /** * A {@link ModelResolver} that caches the results of calls to {@link ModelResolver#resolveType}. */ public class CachingModelResolver extends ForwardingModelResolver { private final ConcurrentHashMap<String, Class<?>> typeCache = new ConcurrentHashMap<>(); private final ConcurrentHashMap<Class<?>, Class<?>> objectTypeCache = new ConcurrentHashMap<>(); public CachingModelResolver(ModelResolver resolver) { super(resolver); } @Override public Class<?> resolveType(String typeName) { return typeCache.computeIfAbsent(typeName, super::resolveType); } @Override public Class<?> resolveType(Object value) { return objectTypeCache.computeIfAbsent( value.getClass(), (key) -> { return
super.resolveType(value);
}); } }
src/main/java/com/google/fhir/cql/beam/CachingModelResolver.java
google-cql-on-beam-82f1c68
[ { "filename": "src/main/java/com/google/fhir/cql/beam/ForwardingModelResolver.java", "retrieved_chunk": " }\n @Override\n public Class<?> resolveType(String typeName) {\n return resolver.resolveType(typeName);\n }\n @Override\n public Class<?> resolveType(Object value) {\n return resolver.resolveType(value);\n }\n @Override", "score": 0.9386370182037354 }, { "filename": "src/main/java/com/google/fhir/cql/beam/ForwardingModelResolver.java", "retrieved_chunk": " public Boolean is(Object value, Class<?> type) {\n return resolver.is(value, type);\n }\n @Override\n public Object as(Object value, Class<?> type, boolean isStrict) {\n return resolver.as(value, type, isStrict);\n }\n @Override\n public Object createInstance(String typeName) {\n return resolver.createInstance(typeName);", "score": 0.8799762725830078 }, { "filename": "src/main/java/com/google/fhir/cql/beam/ForwardingModelResolver.java", "retrieved_chunk": " }\n @Override\n public void setValue(Object target, String path, Object value) {\n resolver.setValue(target, path, value);\n }\n @Override\n public Boolean objectEqual(Object left, Object right) {\n return resolver.objectEqual(left, right);\n }\n @Override", "score": 0.8015879392623901 }, { "filename": "src/main/java/com/google/fhir/cql/beam/ForwardingModelResolver.java", "retrieved_chunk": " public Boolean objectEquivalent(Object left, Object right) {\n return resolver.objectEquivalent(left, right);\n }\n}", "score": 0.7920923233032227 }, { "filename": "src/main/java/com/google/fhir/cql/beam/ForwardingModelResolver.java", "retrieved_chunk": " public void setPackageName(String packageName) {\n resolver.setPackageName(packageName);\n }\n @Override\n public Object resolvePath(Object target, String path) {\n return resolver.resolvePath(target, path);\n }\n @Override\n public Object getContextPath(String contextType, String targetType) {\n return resolver.getContextPath(contextType, targetType);", "score": 0.7914680242538452 } ]
java
super.resolveType(value);
/* * Copyright (C) 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.fhir.cql.beam; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.ImmutableList.toImmutableList; import ca.uhn.fhir.context.FhirVersionEnum; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.fhir.cql.beam.types.CqlEvaluationResult; import com.google.fhir.cql.beam.types.CqlLibraryId; import com.google.fhir.cql.beam.types.ResourceTypeAndId; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Path; import java.nio.file.Paths; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.function.Function; import java.util.function.Predicate; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.extensions.avro.io.AvroIO; import org.apache.beam.sdk.io.TextIO; import org.apache.beam.sdk.options.Description; import org.apache.beam.sdk.options.PipelineOptions; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.apache.beam.sdk.options.Validation.Required; import org.apache.beam.sdk.transforms.GroupByKey; import org.apache.beam.sdk.transforms.ParDo; import org.cqframework.cql.cql2elm.CqlCompilerException; import org.cqframework.cql.cql2elm.CqlCompilerException.ErrorSeverity; import org.cqframework.cql.cql2elm.CqlTranslatorOptions; import org.cqframework.cql.cql2elm.CqlTranslatorOptions.Options; import org.cqframework.cql.cql2elm.LibraryManager; import org.cqframework.cql.cql2elm.ModelManager; import org.cqframework.cql.cql2elm.model.CompiledLibrary; import org.cqframework.cql.elm.execution.Library; import org.opencds.cqf.cql.evaluator.cql2elm.content.InMemoryLibrarySourceProvider; import org.opencds.cqf.cql.evaluator.engine.elm.LibraryMapper; /** * Main entry point for evaluating CQL libraries over a set of FHIR records with Apache Beam. * * <p>See README.md for additional information. */ public final class EvaluateCql { /** * Options supported by {@link EvaluateCql}. */ public interface EvaluateCqlOptions extends PipelineOptions { @Description( "The file pattern of the NDJSON FHIR files to read. Follows the conventions of " + "https://docs.oracle.com/javase/tutorial/essential/io/fileOps.html#glob.") @Required String getNdjsonFhirFilePattern(); void setNdjsonFhirFilePattern(String value); @Description( "Path to a folder that contains ValueSet FHIR records. Each file must contain exactly one " + "ValueSet FHIR record. Subfolders and their content are ignored.") @Required String getValueSetFolder(); void setValueSetFolder(String value); @Description( "Path to a folder that contains CQL libraries. Subfolders and their content are ignored.") @Required String getCqlFolder(); void setCqlFolder(String value); @Description( "A list of CQL library IDs and, optionally, versions that will be evaluated " + "against the provided FHIR. Format: " + "[{\"name\": \"ColorectalCancerScreeningsFHIR\"}, " + "{\"name\": \"ControllingHighBloodPressureFHIR\" \"version\": \"0.0.002\"}]") @Required @JsonSerialize @JsonDeserialize List<CqlLibraryId> getCqlLibraries(); void setCqlLibraries(List<CqlLibraryId> value); @Description("Path and name prefix of the file shards that will contain the pipeline output.") @Required String getOutputFilenamePrefix(); void setOutputFilenamePrefix(String value); } private static ImmutableList<String> loadFilesInDirectory( Path directory, Predicate<Path> pathFilter) { try { return FileLoader.loadFilesInDirectory(directory, pathFilter); } catch (IOException e) { throw new RuntimeException("Failed to read files in " + directory, e); } } private static Path toPath(String directory) { try { URI directoryUri = new URI(directory); if (new URI(directory).getScheme() != null) { return Paths.get(directoryUri); } } catch (URISyntaxException e) { // Fall through and treat as a file:// directory. } return new File(directory).toPath(); } private static final Options[] TRANSLATOR_OPTIONS = { Options.DisableListPromotion, Options.DisableListDemotion, Options.EnableResultTypes, Options.EnableLocators }; private static ImmutableList<Library> loadLibraries( Path cqlFolder, Collection<CqlLibraryId> cqlLibraryIds) { LibraryManager libraryManager = new LibraryManager(new ModelManager()); libraryManager .getLibrarySourceLoader() .registerProvider( new InMemoryLibrarySourceProvider( loadFilesInDirectory(cqlFolder, (path) -> path.toString().endsWith(".cql")))); libraryManager.enableCache(); for (CqlLibraryId libraryIds : cqlLibraryIds) { List<CqlCompilerException> errors = new ArrayList<>(); libraryManager.resolveLibrary( new org.hl7.elm.r1.VersionedIdentifier() .
withId(libraryIds.getName()) .withVersion(libraryIds.getVersion()), new CqlTranslatorOptions(TRANSLATOR_OPTIONS), errors);
if (errors.stream().filter(error -> error.getSeverity().equals(ErrorSeverity.Error)).count() > 0) { throw new RuntimeException( "Errors encountered while compiling CQL. " + errors.toString()); } } return libraryManager.getCompiledLibraries().values().stream() .map(CompiledLibrary::getLibrary) .map(LibraryMapper.INSTANCE::map) .collect(toImmutableList()); } private static void assemblePipeline( Pipeline pipeline, EvaluateCqlOptions options, ZonedDateTime evaluationDateTime) { checkArgument( !options.getCqlLibraries().isEmpty(), "At least one CQL library must be specified."); pipeline .apply("ReadNDJSON", TextIO.read().from(options.getNdjsonFhirFilePattern())) .apply("KeyForContext", ParDo.of(new KeyForContextFn( "Patient", new ModelManager().resolveModel("FHIR", "4.0.1").getModelInfo()))) .apply("GroupByContext", GroupByKey.<ResourceTypeAndId, String>create()) .apply( "EvaluateCql", ParDo.of( new EvaluateCqlForContextFn( loadLibraries(toPath(options.getCqlFolder()), options.getCqlLibraries()), ImmutableSet.copyOf(options.getCqlLibraries()), loadFilesInDirectory( toPath(options.getValueSetFolder()), (path) -> path.toString().endsWith(".json")), evaluationDateTime, FhirVersionEnum.R4))) .apply( "WriteCqlOutput", AvroIO.write(CqlEvaluationResult.class) .withSchema(CqlEvaluationResult.ResultCoder.SCHEMA) .to(options.getOutputFilenamePrefix()) .withSuffix(".avro")); } @VisibleForTesting static void runPipeline( Function<EvaluateCqlOptions, Pipeline> pipelineCreator, String[] args, ZonedDateTime evaluationDateTime) { EvaluateCqlOptions options = PipelineOptionsFactory.fromArgs(args).withValidation().as(EvaluateCqlOptions.class); Pipeline pipeline = pipelineCreator.apply(options); assemblePipeline(pipeline, options, evaluationDateTime); pipeline.run().waitUntilFinish(); } public static void main(String[] args) { runPipeline(Pipeline::create, args, ZonedDateTime.now()); } }
src/main/java/com/google/fhir/cql/beam/EvaluateCql.java
google-cql-on-beam-82f1c68
[ { "filename": "src/test/java/com/google/fhir/cql/beam/EvaluateCqlForContextFnTest.java", "retrieved_chunk": " try {\n for (String cql : cqlStrings) {\n libraries.add(LibraryMapper.INSTANCE.map(compiler.run(\n cql, Options.EnableResultTypes, Options.EnableLocators)));\n assertThat(compiler.getExceptions()).isEmpty();\n }\n return libraries;\n } catch (IOException e) {\n throw new RuntimeException(e);\n }", "score": 0.8829533457756042 }, { "filename": "src/test/java/com/google/fhir/cql/beam/EvaluateCqlForContextFnTest.java", "retrieved_chunk": " private static VersionedIdentifier versionedIdentifier(String id, String version) {\n VersionedIdentifier versionedIdentifier = new VersionedIdentifier();\n versionedIdentifier.setId(id);\n versionedIdentifier.setVersion(version);\n return versionedIdentifier;\n }\n private static Collection<Library> cqlToLibraries(String... cqlStrings) {\n ModelManager modelManager = new ModelManager();\n CqlCompiler compiler = new CqlCompiler(modelManager, new LibraryManager(modelManager));\n Collection<Library> libraries = new ArrayList<>();", "score": 0.8588511347770691 }, { "filename": "src/main/java/com/google/fhir/cql/beam/EvaluateCqlForContextFn.java", "retrieved_chunk": " .map(SerializableLibraryWrapper::getLibrary)\n .collect(Collectors.toList()));\n }\n @ProcessElement\n public void processElement(\n @Element KV<ResourceTypeAndId, Iterable<String>> contextResources,\n OutputReceiver<CqlEvaluationResult> out) {\n RetrieveProvider retrieveProvider = createRetrieveProvider(contextResources.getValue());\n for (VersionedIdentifier cqlLibraryId : cqlLibraryVersionedIdentifiers) {\n Library library = libraryLoader.load(cqlLibraryId);", "score": 0.8470284342765808 }, { "filename": "src/test/java/com/google/fhir/cql/beam/types/CqlLibraryIdTest.java", "retrieved_chunk": " new CqlLibraryId(\"Foo\", \"1.0\"),\n new CqlLibraryId(new VersionedIdentifier().withId(\"Foo\").withVersion(\"1.0\")))\n .addEqualityGroup(\n new CqlLibraryId(\"Bar\", null),\n new CqlLibraryId(new VersionedIdentifier().withId(\"Bar\")))\n .addEqualityGroup(new CqlLibraryId(\"Foo\", \"2.0\"))\n .addEqualityGroup(new CqlLibraryId(\"Bar\", \"1.0\"))\n .testEquals();\n }\n}", "score": 0.8281629085540771 }, { "filename": "src/main/java/com/google/fhir/cql/beam/EvaluateCqlForContextFn.java", "retrieved_chunk": " private final FhirVersionEnum fhirVersion;\n private transient ImmutableSet<VersionedIdentifier> cqlLibraryVersionedIdentifiers;\n private transient FhirContext fhirContext;\n private transient ModelResolver modelResolver;\n private transient TerminologyProvider terminologyProvider;\n private transient LibraryLoader libraryLoader;\n public EvaluateCqlForContextFn(\n Collection<Library> cqlSources,\n Set<CqlLibraryId> cqlLibraryIds,\n Collection<String> valueSetJsonResources,", "score": 0.8274186849594116 } ]
java
withId(libraryIds.getName()) .withVersion(libraryIds.getVersion()), new CqlTranslatorOptions(TRANSLATOR_OPTIONS), errors);
/* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.googlecodesamples.cloud.jss.lds.controller; import com.googlecodesamples.cloud.jss.lds.model.BaseFile; import com.googlecodesamples.cloud.jss.lds.model.FileListResponse; import com.googlecodesamples.cloud.jss.lds.model.FileResponse; import com.googlecodesamples.cloud.jss.lds.service.FileService; import com.googlecodesamples.cloud.jss.lds.service.OpenTelemetryService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** REST API controller of the backend service */ @RestController @RequestMapping("/api") public class FileController { private static final Logger log = LoggerFactory.getLogger(FileController.class); private static final String STRING_SEPARATOR = "\\s+"; private final FileService fileService; private final OpenTelemetryService openTelemetryService; public FileController(FileService fileService, OpenTelemetryService openTelemetryService) { this.fileService = fileService; this.openTelemetryService = openTelemetryService; } /** * The health check API. * * @return status OK is the service is alive */ @GetMapping("/healthchecker") public ResponseEntity<?> healthCheck() throws Exception {
return openTelemetryService.spanScope(this.getClass().getName(), "healthCheck", () -> {
log.info("entering healthCheck()"); return ResponseEntity.noContent().build(); }); } /** * Upload files with tags. * * @param files list of files upload to the server * @param tags list of tags (separated by space) label the files * @return list of uploaded files */ @PostMapping("/files") public ResponseEntity<?> uploadFiles( @RequestParam List<MultipartFile> files, @RequestParam String tags) throws Exception { return openTelemetryService.spanScope(this.getClass().getName(), "uploadFiles", () -> { log.info("entering uploadFiles()"); List<String> tagList = getTagList(tags); List<BaseFile> fileList = fileService.uploadFiles(files, tagList); return ResponseEntity.status(HttpStatus.CREATED).body(new FileListResponse(fileList)); }); } /** * Search files with the given tags. * * @param tags list of tags (separated by space) label the files * @param orderNo order number of the last file * @param size number of files return * @return list of files with pagination */ @GetMapping("/files") public ResponseEntity<?> getFilesByTag( @RequestParam(required = false) String tags, @RequestParam(required = false) String orderNo, @RequestParam(required = false, defaultValue = "50") int size) throws Exception { return openTelemetryService.spanScope(this.getClass().getName(), "getFilesByTag", () -> { log.info("entering getFilesByTag()"); List<String> tagList = getTagList(tags); List<BaseFile> fileList = fileService.getFilesByTag(tagList, orderNo, size); if (CollectionUtils.isEmpty(fileList)) { return ResponseEntity.ok().body(new FileListResponse(new ArrayList<>())); } return ResponseEntity.ok().body(new FileListResponse(fileList)); }); } /** * Update an existing file * * @param fileId unique ID of the file * @param file new file to be uploaded to the server * @param tags list of tags (separated by space) label the new file * @return file data */ @PutMapping("/files/{id}") public ResponseEntity<?> updateFile( @PathVariable("id") String fileId, @RequestParam(required = false) MultipartFile file, @RequestParam String tags) throws Exception { return openTelemetryService.spanScope(this.getClass().getName(), "updateFile", () -> { log.info("entering updateFile()"); BaseFile oldFile = fileService.getFileById(fileId); if (oldFile == null) { return ResponseEntity.notFound().build(); } List<String> tagList = getTagList(tags); BaseFile newFile = fileService.updateFile(file, tagList, oldFile); return ResponseEntity.ok().body(new FileResponse(newFile)); }); } /** * Delete an existing file * * @param fileId unique ID of the file * @return status NoContent or NotFound */ @DeleteMapping("/files/{id}") public ResponseEntity<?> deleteFile(@PathVariable("id") String fileId) throws Exception { return openTelemetryService.spanScope(this.getClass().getName(), "deleteFile", () -> { log.info("entering deleteFile()"); BaseFile file = fileService.getFileById(fileId); if (file == null) { return ResponseEntity.notFound().build(); } fileService.deleteFile(file); return ResponseEntity.noContent().build(); }); } /** * Delete all files. * * @return status NoContent */ @DeleteMapping("/reset") public ResponseEntity<?> resetFile() throws Exception { return openTelemetryService.spanScope(this.getClass().getName(), "resetFile", () -> { log.info("entering resetFile()"); fileService.resetFile(); return ResponseEntity.noContent().build(); }); } /** * Split the string by separator. * * @param tags list of tags in a single string (separated by space) * @return list of tags */ private List<String> getTagList(String tags) { if (!StringUtils.hasText(tags)) { return new ArrayList<>(); } return Arrays.stream(tags.split(STRING_SEPARATOR)) .map(String::trim) .map(String::toLowerCase) .collect(Collectors.toList()); } }
api/src/main/java/com/googlecodesamples/cloud/jss/lds/controller/FileController.java
GoogleCloudPlatform-app-large-data-sharing-java-fd21141
[ { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/OpenTelemetryService.java", "retrieved_chunk": "import org.springframework.stereotype.Service;\nimport java.util.concurrent.Callable;\n@Service\npublic class OpenTelemetryService {\n\tprivate final static String INSTRUMENTATION_SCOPE_VERSION = \"1.0.0\";\n\tprivate final OpenTelemetrySdk openTelemetrySdk;\n\tpublic OpenTelemetryService(OpenTelemetrySdk openTelemetrySdk) {\n\t\tthis.openTelemetrySdk = openTelemetrySdk;\n\t}\n\t/**", "score": 0.8206683397293091 }, { "filename": "api/src/test/java/com/googlecodesamples/cloud/jss/lds/controller/FileControllerTest.java", "retrieved_chunk": "@AutoConfigureMockMvc\npublic class FileControllerTest {\n private static final Logger log = LoggerFactory.getLogger(FileControllerTest.class);\n @Autowired\n MockMvc mockMvc;\n @MockBean\n FileService fileService;\n @Test\n public void testHealthCheckReturnsNoContent() throws Exception {\n mockMvc.perform(MockMvcRequestBuilders.get(\"/api/healthchecker\"))", "score": 0.8203152418136597 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/OpenTelemetryService.java", "retrieved_chunk": " * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.googlecodesamples.cloud.jss.lds.service;\nimport io.opentelemetry.api.trace.Span;\nimport io.opentelemetry.api.trace.Tracer;\nimport io.opentelemetry.context.Scope;\nimport io.opentelemetry.sdk.OpenTelemetrySdk;", "score": 0.7829064130783081 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/config/Config.java", "retrieved_chunk": "\tpublic OpenTelemetrySdk createOpenTelemetrySdk() throws IOException {\n\t\tTraceExporter googleTraceExporter = TraceExporter.createWithDefaultConfiguration();\n\t\tSdkTracerProvider tracerProvider = SdkTracerProvider.builder()\n\t\t\t\t.addSpanProcessor(BatchSpanProcessor.builder(googleTraceExporter).build())\n\t\t\t\t.build();\n\t\treturn OpenTelemetrySdk.builder()\n\t\t\t\t.setTracerProvider(tracerProvider)\n\t\t\t\t.build();\n\t}\n}", "score": 0.763769268989563 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/config/Config.java", "retrieved_chunk": "import org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport java.io.IOException;\n@Configuration\npublic class Config {\n\t/**\n\t * Create a distributed tracing system based on the OpenTelemetry\n\t * and uses the Google Cloud Trace Exporter\n\t */\n\t@Bean", "score": 0.7632864117622375 } ]
java
return openTelemetryService.spanScope(this.getClass().getName(), "healthCheck", () -> {
package com.dice.service; import com.dice.DTO.DiceSwDTO; import com.dice.DTO.ResultadoSwDTO; import com.dice.DTO.ResultadoSwForceDTO; import com.dice.model.Dice; import org.springframework.stereotype.Service; @Service public class StarWarsService { public StarWarsService() {} public ResultadoSwDTO rollSwDice(DiceSwDTO dice) { int success = 0; int triumph = 0; int advantage = 0; int failure = 0; int despair = 0; int threat = 0; // Obter os valores para cada tipo de dado. int boost = dice.getAmpliacao(); int ability = dice.getHabilidade(); int proficiency = dice.getProficiencia(); int setback = dice.getContratempo(); int difficulty = dice.getDificuldade(); int challenge = dice.getDesafio(); // Calcular os resultados dos dados. for (int i = 0; i < boost; i++) { Dice boostDice = new Dice(6); int result = boostDice.roll(); if (result == 1 || result == 2 ) { // Do nothing } else if (result == 3) { success += 1; } else if (result == 4) { success += 1; advantage += 1; } else if (result == 5) { advantage += 2; } else if (result == 6) { advantage += 1; } } for (int i = 0; i < ability; i++) { Dice abilityDice = new Dice(8); int result = abilityDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4) { success += 2; } else if (result == 5 || result == 6) { advantage += 1; } else if (result == 7) { success += 1; advantage += 1; } else if (result == 8) { advantage += 2; } } for (int i = 0; i < proficiency; i++) { Dice proficiencyDice = new Dice(12); int result = proficiencyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4 || result == 5) { success += 2; } else if (result == 6) { advantage += 1; } else if (result == 7 || result == 8 || result == 9) { success += 1; advantage += 1; } else if (result == 10 || result == 11) { advantage += 2; } else if (result == 12) { triumph += 1; } } for (int i = 0; i < setback; i++) { Dice setbackDice = new Dice(6); int result = setbackDice.roll(); if (result == 1 || result == 2) { // Do nothing } else if (result == 3 || result == 4) { failure += 1; } else if (result == 5 || result == 6) { threat += 1; } } for (int i = 0; i < difficulty; i++) { Dice difficultyDice = new Dice(8); int result = difficultyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2) { failure += 1; } else if (result == 3) { failure += 2; } else if (result == 4 || result == 5 || result == 6) { threat += 1; } else if (result == 7) { threat += 2; } else if (result == 8) { failure += 1; threat += 1; } } for (int i = 0; i < challenge; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { failure += 1; } else if (result == 4 || result == 5) { failure += 2; } else if (result == 6 || result == 7) { threat += 1; } else if (result == 8 || result == 9) { failure += 1; threat += 1; } else if (result == 10 || result == 11) { threat += 2; } else if (result == 12) { despair += 1; } } return getResultSwDice(success, triumph, advantage, failure, despair, threat); } private ResultadoSwDTO getResultSwDice(int success, int triumph, int advantage, int failure, int despair, int threat) { ResultadoSwDTO diceResult = new ResultadoSwDTO(); if (success - failure > 0) { diceResult.setSucessos(success - failure); diceResult.setFracassos(0); } else if (success - failure < 0) { diceResult.setSucessos(0); diceResult.setFracassos(failure - success); } else { diceResult.setSucessos(0); diceResult.setFracassos(0); } if (advantage - threat > 0) { diceResult.setVantagens(advantage - threat); diceResult.setAmeacas(0); } else if (advantage - threat < 0) { diceResult.setVantagens(0); diceResult.setAmeacas(threat - advantage); } else { diceResult.setVantagens(0); diceResult.setAmeacas(0); } if (triumph - despair > 0) { diceResult.setTriunfos(triumph - despair);
diceResult.setDesesperos(0);
} else if (triumph - despair < 0) { diceResult.setTriunfos(0); diceResult.setDesesperos(despair - triumph); } else { diceResult.setTriunfos(0); diceResult.setDesesperos(0); } return diceResult; } public ResultadoSwForceDTO rollForce(int quantity) { int light = 0; int dark = 0; for (int i = 0; i < quantity; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1 || result == 2 || result == 3 || result == 4 || result == 5 || result == 6) { dark += 1; } else if (result == 7) { dark += 2; } else if (result == 8 || result == 9) { light += 1; } else if (result == 10 || result == 11 || result == 12) { light += 2; } } ResultadoSwForceDTO forceResult = new ResultadoSwForceDTO(); forceResult.setLuz(light); forceResult.setNegro(dark); return forceResult; } }
src/main/java/com/dice/service/StarWarsService.java
grcreutzberg-dice-api-d58bb3d
[ { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " }\n int diceX = new Dice(dice).roll();\n int diceY = new Dice(dice).roll();\n int resultDice = new Dice(dice).roll();\n if (type.equalsIgnoreCase(\"Advantage\")) {\n return resultDice + Math.max(diceX, diceY); //Retorna Dado + Vantagem\n }\n return resultDice - Math.min(diceX, diceY); //Retorna Dado - Desvantagem\n }\n}", "score": 0.8906014561653137 }, { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " int[] results = new int[numberOfDice];\n Dice dice = new Dice(faces);\n for (int i = 0; i < numberOfDice; i++) {\n results[i] = dice.roll();\n }\n return results;\n }\n public int rollDisVantage(String type, int dice) {\n if (dice <= 0) {\n throw new IllegalArgumentException(\"O dado deve ser maior que zero.\");", "score": 0.8424903750419617 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class ResultadoSwDTO {\n private int sucessos = 0;\n private int triunfos = 0;\n private int vantagens = 0;\n private int fracassos = 0;\n private int desesperos = 0;\n private int ameacas = 0;\n public int getSucessos() {\n return sucessos;", "score": 0.8375934362411499 }, { "filename": "src/main/java/com/dice/controller/DiceRollController.java", "retrieved_chunk": " @GetMapping(\"/advantage\")\n public int rollAdvantage(\n @RequestParam(name = \"dice\", defaultValue = \"20\") int dice\n ) {\n return service.rollDisVantage(\"Advantage\", dice);\n }\n @GetMapping(\"/disadvantage\")\n public int rollDisadvantage(\n @RequestParam(name = \"dice\", defaultValue = \"20\") int dice\n ) {", "score": 0.8267413973808289 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": " public int getVantagens() {\n return vantagens;\n }\n public void setVantagens(final int vantagens) {\n this.vantagens = vantagens;\n }\n public int getFracassos() {\n return fracassos;\n }\n public void setFracassos(final int fracassos) {", "score": 0.8231649398803711 } ]
java
diceResult.setDesesperos(0);
package org.geysermc.hydraulic.mixin.ext; import com.github.steveice10.opennbt.tag.builtin.CompoundTag; import com.github.steveice10.opennbt.tag.builtin.ListTag; import com.github.steveice10.opennbt.tag.builtin.StringTag; import org.cloudburstmc.protocol.bedrock.data.inventory.ItemData; import org.geysermc.geyser.item.type.Item; import org.geysermc.geyser.registry.type.ItemMapping; import org.geysermc.geyser.session.GeyserSession; import org.geysermc.geyser.translator.inventory.item.ItemTranslator; import org.geysermc.hydraulic.HydraulicImpl; import org.geysermc.hydraulic.platform.mod.ModInfo; 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.ModifyVariable; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; @Mixin(value = ItemTranslator.class, remap = false) public class ItemTranslatorMixin { @Inject( method = "translateDisplayProperties(Lorg/geysermc/geyser/session/GeyserSession;Lcom/github/steveice10/opennbt/tag/builtin/CompoundTag;Lorg/geysermc/geyser/registry/type/ItemMapping;C)Lcom/github/steveice10/opennbt/tag/builtin/CompoundTag;", at = @At("RETURN"), cancellable = true ) private static void translateDisplayProperties(GeyserSession session, CompoundTag tag, ItemMapping mapping, char translationColor, CallbackInfoReturnable<CompoundTag> ci) { CompoundTag newNbt = tag; if (newNbt == null) { newNbt = new CompoundTag("nbt"); CompoundTag display = new CompoundTag("display"); display.put(new ListTag("Lore")); newNbt.put(display); } CompoundTag compoundTag = newNbt.get("display"); if (compoundTag == null) { compoundTag = new CompoundTag("display"); } ListTag listTag = compoundTag.get("Lore"); if (listTag == null) { listTag = new ListTag("Lore"); } String identifier = mapping.getJavaItem().javaIdentifier(); // Get the mod name from the identifier String modId = identifier.substring(0, identifier.indexOf(":")); ModInfo mod
= HydraulicImpl.instance().mod(modId);
String modName = "Minecraft"; if (mod != null) { modName = mod.name(); } listTag.add(new StringTag("", "§r§9§o" + modName)); compoundTag.put(listTag); newNbt.put(compoundTag); ci.setReturnValue(newNbt); } }
shared/src/main/java/org/geysermc/hydraulic/mixin/ext/ItemTranslatorMixin.java
GeyserMC-Hydraulic-80cb8ab
[ { "filename": "forge/src/main/java/org/geysermc/hydraulic/forge/platform/HydraulicForgeBootstrap.java", "retrieved_chunk": "public class HydraulicForgeBootstrap implements HydraulicBootstrap {\n @Override\n public @NotNull Set<ModInfo> mods() {\n return ModList.get().getMods().stream().map(modInfo ->\n new ModInfo(\n modInfo.getModId(),\n modInfo.getVersion().toString(),\n modInfo.getDisplayName(),\n modInfo.getOwningFile().getFile().getFilePath(),\n modInfo.getLogoFile().orElse(\"\")", "score": 0.8072357773780823 }, { "filename": "forge/src/main/java/org/geysermc/hydraulic/forge/platform/HydraulicForgeBootstrap.java", "retrieved_chunk": " )\n ).collect(Collectors.toUnmodifiableSet());\n }\n @Override\n public @Nullable ModInfo mod(@NotNull String modName) {\n return ModList.get().getModContainerById(modName).map(container ->\n new ModInfo(\n container.getModId(),\n container.getModInfo().getVersion().toString(),\n container.getModInfo().getDisplayName(),", "score": 0.8053235411643982 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/item/ItemPackModule.java", "retrieved_chunk": " DefaultedRegistry<Item> registry = BuiltInRegistries.ITEM;\n for (Item item : items) {\n ResourceLocation itemLocation = registry.getKey(item);\n NonVanillaCustomItemData.Builder customItemBuilder = NonVanillaCustomItemData.builder()\n .name(itemLocation.getPath())\n .displayName(\"%\" + item.getDescriptionId())\n .identifier(itemLocation.toString())\n .icon(itemLocation.toString())\n .javaId(registry.getId(item))\n .stackSize(item.getMaxStackSize())", "score": 0.8042716979980469 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/pack/context/PackContext.java", "retrieved_chunk": "package org.geysermc.hydraulic.pack.context;\nimport net.minecraft.core.Registry;\nimport net.minecraft.resources.ResourceKey;\nimport org.geysermc.hydraulic.HydraulicImpl;\nimport org.geysermc.hydraulic.pack.PackModule;\nimport org.geysermc.hydraulic.platform.mod.ModInfo;\nimport org.geysermc.hydraulic.storage.ModStorage;\nimport org.jetbrains.annotations.NotNull;\nimport java.util.List;\nimport java.util.Map;", "score": 0.8000242710113525 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/item/CreativeMappings.java", "retrieved_chunk": " }\n if (mapping == null) {\n return;\n }\n customItemBuilder.creativeGroup(mapping.creativeGroup()).creativeCategory(mapping.creativeCategory().id());\n }\n}", "score": 0.7995030879974365 } ]
java
= HydraulicImpl.instance().mod(modId);
package org.geysermc.hydraulic.storage; import com.mojang.logging.LogUtils; import org.geysermc.hydraulic.Constants; import org.geysermc.hydraulic.HydraulicImpl; import org.geysermc.hydraulic.block.Materials; import org.geysermc.hydraulic.platform.mod.ModInfo; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; /** * Stores data relevant to a mod. */ public class ModStorage { private static final Logger LOGGER = LogUtils.getLogger(); private ModInfo mod; private Materials materials = new Materials(); private ModStorage(@NotNull ModInfo mod) { this.mod = mod; } /** * Gets the materials for this mod. * * @return the materials */ @NotNull public Materials materials() { return this.materials; } /** * Sets the materials for this mod. * * @param materials the materials */ public void materials(@NotNull Materials materials) { this.materials = materials; } /** * Saves the mod storage. */ public void save() { try { Path path = storagePath(this.mod); if (Files.notExists(path)) { Files.createDirectories(path); } try (BufferedWriter writer = Files.newBufferedWriter(path.resolve("materials.json"))) { Constants.GSON.toJson(this.materials, writer); } } catch (IOException e) { LOGGER.error("Failed to save mod storage for {}", this.mod.id()); } } /** * Loads the mod storage for the given mod. * * @param mod the mod * @return the mod storage */ public static ModStorage load(@NotNull ModInfo mod) { Path path = storagePath(mod); if (Files.notExists(path)) { return new ModStorage(mod); } try { try (BufferedReader reader = Files.newBufferedReader(path.resolve("materials.json"))) { ModStorage storage = Constants.GSON.fromJson(reader, ModStorage.class); storage.mod = mod; return storage; } } catch (IOException e) { LOGGER.error("Failed to load mod storage for {}", mod.id()); return new ModStorage(mod); } } private static Path storagePath(@NotNull ModInfo mod) {
return HydraulicImpl.instance().dataFolder(Constants.MOD_ID) .resolve("storage") .resolve(mod.id());
} }
shared/src/main/java/org/geysermc/hydraulic/storage/ModStorage.java
GeyserMC-Hydraulic-80cb8ab
[ { "filename": "shared/src/main/java/org/geysermc/hydraulic/HydraulicImpl.java", "retrieved_chunk": " * Gets the mod storage for the specified mod.\n *\n * @param mod the mod\n * @return the mod storage\n */\n @NotNull\n public ModStorage modStorage(@NotNull ModInfo mod) {\n return this.modStorage.computeIfAbsent(mod.id(), e -> ModStorage.load(mod));\n }\n /**", "score": 0.8794903755187988 }, { "filename": "forge/src/main/java/org/geysermc/hydraulic/forge/platform/HydraulicForgeBootstrap.java", "retrieved_chunk": " container.getModInfo().getOwningFile().getFile().getFilePath(),\n container.getModInfo().getLogoFile().orElse(\"\")\n )\n ).orElse(null);\n }\n @Override\n public @NotNull Path dataFolder(@NotNull String modId) {\n return FMLPaths.CONFIGDIR.get().resolve(modId);\n }\n}", "score": 0.8756606578826904 }, { "filename": "fabric/src/main/java/org/geysermc/hydraulic/fabric/platform/HydraulicFabricBootstrap.java", "retrieved_chunk": " container.getMetadata().getVersion().getFriendlyString(),\n container.getMetadata().getName(),\n container.getRootPaths().get(0), // TODO: Multi-path support\n container.getMetadata().getIconPath(256).orElse(\"\")\n )\n ).orElse(null);\n }\n @Override\n public @NotNull Path dataFolder(@NotNull String modId) {\n return FabricLoader.getInstance().getConfigDir().resolve(modId);", "score": 0.868740439414978 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/platform/HydraulicBootstrap.java", "retrieved_chunk": " @NotNull\n Path dataFolder(@NotNull String modId);\n}", "score": 0.8651371598243713 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/pack/context/PackContext.java", "retrieved_chunk": " public ModInfo mod() {\n return this.mod;\n }\n /**\n * Gets the storage for the mod that owns this pack.\n *\n * @return the storage for the mod that owns this pack\n */\n @NotNull\n public ModStorage storage() {", "score": 0.8478468656539917 } ]
java
return HydraulicImpl.instance().dataFolder(Constants.MOD_ID) .resolve("storage") .resolve(mod.id());
package com.dice.service; import com.dice.DTO.DiceSwDTO; import com.dice.DTO.ResultadoSwDTO; import com.dice.DTO.ResultadoSwForceDTO; import com.dice.model.Dice; import org.springframework.stereotype.Service; @Service public class StarWarsService { public StarWarsService() {} public ResultadoSwDTO rollSwDice(DiceSwDTO dice) { int success = 0; int triumph = 0; int advantage = 0; int failure = 0; int despair = 0; int threat = 0; // Obter os valores para cada tipo de dado. int boost = dice.getAmpliacao(); int ability = dice.getHabilidade(); int proficiency = dice.getProficiencia(); int setback = dice.getContratempo(); int difficulty = dice.getDificuldade(); int challenge = dice.getDesafio(); // Calcular os resultados dos dados. for (int i = 0; i < boost; i++) { Dice boostDice = new Dice(6); int result = boostDice.roll(); if (result == 1 || result == 2 ) { // Do nothing } else if (result == 3) { success += 1; } else if (result == 4) { success += 1; advantage += 1; } else if (result == 5) { advantage += 2; } else if (result == 6) { advantage += 1; } } for (int i = 0; i < ability; i++) { Dice abilityDice = new Dice(8); int result = abilityDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4) { success += 2; } else if (result == 5 || result == 6) { advantage += 1; } else if (result == 7) { success += 1; advantage += 1; } else if (result == 8) { advantage += 2; } } for (int i = 0; i < proficiency; i++) { Dice proficiencyDice = new Dice(12); int result = proficiencyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4 || result == 5) { success += 2; } else if (result == 6) { advantage += 1; } else if (result == 7 || result == 8 || result == 9) { success += 1; advantage += 1; } else if (result == 10 || result == 11) { advantage += 2; } else if (result == 12) { triumph += 1; } } for (int i = 0; i < setback; i++) { Dice setbackDice = new Dice(6); int result = setbackDice.roll(); if (result == 1 || result == 2) { // Do nothing } else if (result == 3 || result == 4) { failure += 1; } else if (result == 5 || result == 6) { threat += 1; } } for (int i = 0; i < difficulty; i++) { Dice difficultyDice = new Dice(8); int result = difficultyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2) { failure += 1; } else if (result == 3) { failure += 2; } else if (result == 4 || result == 5 || result == 6) { threat += 1; } else if (result == 7) { threat += 2; } else if (result == 8) { failure += 1; threat += 1; } } for (int i = 0; i < challenge; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { failure += 1; } else if (result == 4 || result == 5) { failure += 2; } else if (result == 6 || result == 7) { threat += 1; } else if (result == 8 || result == 9) { failure += 1; threat += 1; } else if (result == 10 || result == 11) { threat += 2; } else if (result == 12) { despair += 1; } } return getResultSwDice(success, triumph, advantage, failure, despair, threat); } private ResultadoSwDTO getResultSwDice(int success, int triumph, int advantage, int failure, int despair, int threat) { ResultadoSwDTO diceResult = new ResultadoSwDTO(); if (success - failure > 0) { diceResult.setSucessos(success - failure); diceResult.setFracassos(0); } else if (success - failure < 0) { diceResult.setSucessos(0); diceResult.setFracassos(failure - success); } else { diceResult.setSucessos(0); diceResult.setFracassos(0); } if (advantage - threat > 0) { diceResult.setVantagens(advantage - threat); diceResult.setAmeacas(0); } else if (advantage - threat < 0) { diceResult.setVantagens(0); diceResult.setAmeacas(threat - advantage); } else { diceResult.setVantagens(0); diceResult.setAmeacas(0); } if (triumph - despair > 0) { diceResult.setTriunfos(triumph - despair); diceResult.setDesesperos(0); } else if (triumph - despair < 0) { diceResult.setTriunfos(0); diceResult.setDesesperos(despair - triumph); } else { diceResult.setTriunfos(0); diceResult.setDesesperos(0); } return diceResult; } public ResultadoSwForceDTO rollForce(int quantity) { int light = 0; int dark = 0; for (int i = 0; i < quantity; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1 || result == 2 || result == 3 || result == 4 || result == 5 || result == 6) { dark += 1; } else if (result == 7) { dark += 2; } else if (result == 8 || result == 9) { light += 1; } else if (result == 10 || result == 11 || result == 12) { light += 2; } } ResultadoSwForceDTO forceResult = new ResultadoSwForceDTO();
forceResult.setLuz(light);
forceResult.setNegro(dark); return forceResult; } }
src/main/java/com/dice/service/StarWarsService.java
grcreutzberg-dice-api-d58bb3d
[ { "filename": "src/main/java/com/dice/DTO/ResultadoSwForceDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class ResultadoSwForceDTO {\n private int luz = 0;\n private int negro = 0;\n public int getLuz() {\n return luz;\n }\n public void setLuz(final int luz) {\n this.luz = luz;\n }", "score": 0.884341835975647 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class ResultadoSwDTO {\n private int sucessos = 0;\n private int triunfos = 0;\n private int vantagens = 0;\n private int fracassos = 0;\n private int desesperos = 0;\n private int ameacas = 0;\n public int getSucessos() {\n return sucessos;", "score": 0.8060837388038635 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwForceDTO.java", "retrieved_chunk": " public int getNegro() {\n return negro;\n }\n public void setNegro(final int negro) {\n this.negro = negro;\n }\n}", "score": 0.7837372422218323 }, { "filename": "src/main/java/com/dice/DTO/DiceSwDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class DiceSwDTO {\n private int habilidade = 0;\n private int proficiencia = 0;\n private int dificuldade = 0;\n private int desafio = 0;\n private int ampliacao = 0;\n private int contratempo = 0;\n public int getHabilidade() {\n return habilidade;", "score": 0.7721935510635376 }, { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " }\n int diceX = new Dice(dice).roll();\n int diceY = new Dice(dice).roll();\n int resultDice = new Dice(dice).roll();\n if (type.equalsIgnoreCase(\"Advantage\")) {\n return resultDice + Math.max(diceX, diceY); //Retorna Dado + Vantagem\n }\n return resultDice - Math.min(diceX, diceY); //Retorna Dado - Desvantagem\n }\n}", "score": 0.7673209309577942 } ]
java
forceResult.setLuz(light);
package com.dice.service; import com.dice.DTO.DiceSwDTO; import com.dice.DTO.ResultadoSwDTO; import com.dice.DTO.ResultadoSwForceDTO; import com.dice.model.Dice; import org.springframework.stereotype.Service; @Service public class StarWarsService { public StarWarsService() {} public ResultadoSwDTO rollSwDice(DiceSwDTO dice) { int success = 0; int triumph = 0; int advantage = 0; int failure = 0; int despair = 0; int threat = 0; // Obter os valores para cada tipo de dado. int boost = dice.getAmpliacao(); int ability = dice.getHabilidade(); int proficiency = dice.getProficiencia(); int setback = dice.getContratempo(); int difficulty = dice.getDificuldade(); int challenge = dice.getDesafio(); // Calcular os resultados dos dados. for (int i = 0; i < boost; i++) { Dice boostDice = new Dice(6); int result = boostDice.roll(); if (result == 1 || result == 2 ) { // Do nothing } else if (result == 3) { success += 1; } else if (result == 4) { success += 1; advantage += 1; } else if (result == 5) { advantage += 2; } else if (result == 6) { advantage += 1; } } for (int i = 0; i < ability; i++) { Dice abilityDice = new Dice(8); int result = abilityDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4) { success += 2; } else if (result == 5 || result == 6) { advantage += 1; } else if (result == 7) { success += 1; advantage += 1; } else if (result == 8) { advantage += 2; } } for (int i = 0; i < proficiency; i++) { Dice proficiencyDice = new Dice(12); int result = proficiencyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4 || result == 5) { success += 2; } else if (result == 6) { advantage += 1; } else if (result == 7 || result == 8 || result == 9) { success += 1; advantage += 1; } else if (result == 10 || result == 11) { advantage += 2; } else if (result == 12) { triumph += 1; } } for (int i = 0; i < setback; i++) { Dice setbackDice = new Dice(6); int result = setbackDice.roll(); if (result == 1 || result == 2) { // Do nothing } else if (result == 3 || result == 4) { failure += 1; } else if (result == 5 || result == 6) { threat += 1; } } for (int i = 0; i < difficulty; i++) { Dice difficultyDice = new Dice(8); int result = difficultyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2) { failure += 1; } else if (result == 3) { failure += 2; } else if (result == 4 || result == 5 || result == 6) { threat += 1; } else if (result == 7) { threat += 2; } else if (result == 8) { failure += 1; threat += 1; } } for (int i = 0; i < challenge; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { failure += 1; } else if (result == 4 || result == 5) { failure += 2; } else if (result == 6 || result == 7) { threat += 1; } else if (result == 8 || result == 9) { failure += 1; threat += 1; } else if (result == 10 || result == 11) { threat += 2; } else if (result == 12) { despair += 1; } } return getResultSwDice(success, triumph, advantage, failure, despair, threat); } private ResultadoSwDTO getResultSwDice(int success, int triumph, int advantage, int failure, int despair, int threat) { ResultadoSwDTO diceResult = new ResultadoSwDTO(); if (success - failure > 0) { diceResult.setSucessos(success - failure); diceResult.setFracassos(0); } else if (success - failure < 0) { diceResult.setSucessos(0); diceResult.setFracassos(failure - success); } else { diceResult.setSucessos(0); diceResult.setFracassos(0); } if (advantage - threat > 0) { diceResult.setVantagens(advantage - threat); diceResult.setAmeacas(0); } else if (advantage - threat < 0) { diceResult.setVantagens(0); diceResult.setAmeacas(threat - advantage); } else { diceResult.setVantagens(0); diceResult.setAmeacas(0); } if (triumph - despair > 0) { diceResult.setTriunfos(triumph - despair); diceResult.setDesesperos(0); } else if (triumph - despair < 0) { diceResult.setTriunfos(0); diceResult.setDesesperos(despair - triumph); } else { diceResult.setTriunfos(0); diceResult.setDesesperos(0); } return diceResult; } public ResultadoSwForceDTO rollForce(int quantity) { int light = 0; int dark = 0; for (int i = 0; i < quantity; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1 || result == 2 || result == 3 || result == 4 || result == 5 || result == 6) { dark += 1; } else if (result == 7) { dark += 2; } else if (result == 8 || result == 9) { light += 1; } else if (result == 10 || result == 11 || result == 12) { light += 2; } } ResultadoSwForceDTO forceResult = new ResultadoSwForceDTO(); forceResult.setLuz(light);
forceResult.setNegro(dark);
return forceResult; } }
src/main/java/com/dice/service/StarWarsService.java
grcreutzberg-dice-api-d58bb3d
[ { "filename": "src/main/java/com/dice/DTO/ResultadoSwForceDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class ResultadoSwForceDTO {\n private int luz = 0;\n private int negro = 0;\n public int getLuz() {\n return luz;\n }\n public void setLuz(final int luz) {\n this.luz = luz;\n }", "score": 0.896000325679779 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwForceDTO.java", "retrieved_chunk": " public int getNegro() {\n return negro;\n }\n public void setNegro(final int negro) {\n this.negro = negro;\n }\n}", "score": 0.8114169836044312 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class ResultadoSwDTO {\n private int sucessos = 0;\n private int triunfos = 0;\n private int vantagens = 0;\n private int fracassos = 0;\n private int desesperos = 0;\n private int ameacas = 0;\n public int getSucessos() {\n return sucessos;", "score": 0.8080706596374512 }, { "filename": "src/main/java/com/dice/DTO/DiceSwDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class DiceSwDTO {\n private int habilidade = 0;\n private int proficiencia = 0;\n private int dificuldade = 0;\n private int desafio = 0;\n private int ampliacao = 0;\n private int contratempo = 0;\n public int getHabilidade() {\n return habilidade;", "score": 0.7755246758460999 }, { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " }\n int diceX = new Dice(dice).roll();\n int diceY = new Dice(dice).roll();\n int resultDice = new Dice(dice).roll();\n if (type.equalsIgnoreCase(\"Advantage\")) {\n return resultDice + Math.max(diceX, diceY); //Retorna Dado + Vantagem\n }\n return resultDice - Math.min(diceX, diceY); //Retorna Dado - Desvantagem\n }\n}", "score": 0.7739763259887695 } ]
java
forceResult.setNegro(dark);
package com.dice.service; import com.dice.DTO.DiceSwDTO; import com.dice.DTO.ResultadoSwDTO; import com.dice.DTO.ResultadoSwForceDTO; import com.dice.model.Dice; import org.springframework.stereotype.Service; @Service public class StarWarsService { public StarWarsService() {} public ResultadoSwDTO rollSwDice(DiceSwDTO dice) { int success = 0; int triumph = 0; int advantage = 0; int failure = 0; int despair = 0; int threat = 0; // Obter os valores para cada tipo de dado. int boost = dice.getAmpliacao(); int ability = dice.getHabilidade(); int proficiency = dice.getProficiencia(); int setback = dice.getContratempo(); int difficulty = dice.getDificuldade(); int challenge = dice.getDesafio(); // Calcular os resultados dos dados. for (int i = 0; i < boost; i++) { Dice boostDice = new Dice(6); int
result = boostDice.roll();
if (result == 1 || result == 2 ) { // Do nothing } else if (result == 3) { success += 1; } else if (result == 4) { success += 1; advantage += 1; } else if (result == 5) { advantage += 2; } else if (result == 6) { advantage += 1; } } for (int i = 0; i < ability; i++) { Dice abilityDice = new Dice(8); int result = abilityDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4) { success += 2; } else if (result == 5 || result == 6) { advantage += 1; } else if (result == 7) { success += 1; advantage += 1; } else if (result == 8) { advantage += 2; } } for (int i = 0; i < proficiency; i++) { Dice proficiencyDice = new Dice(12); int result = proficiencyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4 || result == 5) { success += 2; } else if (result == 6) { advantage += 1; } else if (result == 7 || result == 8 || result == 9) { success += 1; advantage += 1; } else if (result == 10 || result == 11) { advantage += 2; } else if (result == 12) { triumph += 1; } } for (int i = 0; i < setback; i++) { Dice setbackDice = new Dice(6); int result = setbackDice.roll(); if (result == 1 || result == 2) { // Do nothing } else if (result == 3 || result == 4) { failure += 1; } else if (result == 5 || result == 6) { threat += 1; } } for (int i = 0; i < difficulty; i++) { Dice difficultyDice = new Dice(8); int result = difficultyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2) { failure += 1; } else if (result == 3) { failure += 2; } else if (result == 4 || result == 5 || result == 6) { threat += 1; } else if (result == 7) { threat += 2; } else if (result == 8) { failure += 1; threat += 1; } } for (int i = 0; i < challenge; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { failure += 1; } else if (result == 4 || result == 5) { failure += 2; } else if (result == 6 || result == 7) { threat += 1; } else if (result == 8 || result == 9) { failure += 1; threat += 1; } else if (result == 10 || result == 11) { threat += 2; } else if (result == 12) { despair += 1; } } return getResultSwDice(success, triumph, advantage, failure, despair, threat); } private ResultadoSwDTO getResultSwDice(int success, int triumph, int advantage, int failure, int despair, int threat) { ResultadoSwDTO diceResult = new ResultadoSwDTO(); if (success - failure > 0) { diceResult.setSucessos(success - failure); diceResult.setFracassos(0); } else if (success - failure < 0) { diceResult.setSucessos(0); diceResult.setFracassos(failure - success); } else { diceResult.setSucessos(0); diceResult.setFracassos(0); } if (advantage - threat > 0) { diceResult.setVantagens(advantage - threat); diceResult.setAmeacas(0); } else if (advantage - threat < 0) { diceResult.setVantagens(0); diceResult.setAmeacas(threat - advantage); } else { diceResult.setVantagens(0); diceResult.setAmeacas(0); } if (triumph - despair > 0) { diceResult.setTriunfos(triumph - despair); diceResult.setDesesperos(0); } else if (triumph - despair < 0) { diceResult.setTriunfos(0); diceResult.setDesesperos(despair - triumph); } else { diceResult.setTriunfos(0); diceResult.setDesesperos(0); } return diceResult; } public ResultadoSwForceDTO rollForce(int quantity) { int light = 0; int dark = 0; for (int i = 0; i < quantity; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1 || result == 2 || result == 3 || result == 4 || result == 5 || result == 6) { dark += 1; } else if (result == 7) { dark += 2; } else if (result == 8 || result == 9) { light += 1; } else if (result == 10 || result == 11 || result == 12) { light += 2; } } ResultadoSwForceDTO forceResult = new ResultadoSwForceDTO(); forceResult.setLuz(light); forceResult.setNegro(dark); return forceResult; } }
src/main/java/com/dice/service/StarWarsService.java
grcreutzberg-dice-api-d58bb3d
[ { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " }\n int diceX = new Dice(dice).roll();\n int diceY = new Dice(dice).roll();\n int resultDice = new Dice(dice).roll();\n if (type.equalsIgnoreCase(\"Advantage\")) {\n return resultDice + Math.max(diceX, diceY); //Retorna Dado + Vantagem\n }\n return resultDice - Math.min(diceX, diceY); //Retorna Dado - Desvantagem\n }\n}", "score": 0.8816418647766113 }, { "filename": "src/main/java/com/dice/DTO/DiceSwDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class DiceSwDTO {\n private int habilidade = 0;\n private int proficiencia = 0;\n private int dificuldade = 0;\n private int desafio = 0;\n private int ampliacao = 0;\n private int contratempo = 0;\n public int getHabilidade() {\n return habilidade;", "score": 0.853553295135498 }, { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " int[] results = new int[numberOfDice];\n Dice dice = new Dice(faces);\n for (int i = 0; i < numberOfDice; i++) {\n results[i] = dice.roll();\n }\n return results;\n }\n public int rollDisVantage(String type, int dice) {\n if (dice <= 0) {\n throw new IllegalArgumentException(\"O dado deve ser maior que zero.\");", "score": 0.8483625650405884 }, { "filename": "src/main/java/com/dice/model/Dice.java", "retrieved_chunk": "package com.dice.model;\npublic class Dice {\n private int nFaces;\n public Dice(int nFaces) {\n if (nFaces < 2) {\n throw new IllegalArgumentException(\"O dado deve ter pelo menos duas faces.\");\n }\n this.nFaces = nFaces;\n }\n public int roll() {", "score": 0.8455613255500793 }, { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": "package com.dice.service;\nimport com.dice.model.Dice;\nimport org.springframework.stereotype.Service;\n@Service\npublic class DiceRollService {\n public DiceRollService() {}\n public int[] rollDice(int numberOfDice, int faces) {\n if (numberOfDice <= 0) {\n throw new IllegalArgumentException(\"A quantidade de dados deve ser maior que zero.\");\n }", "score": 0.8359202146530151 } ]
java
result = boostDice.roll();
package org.geysermc.hydraulic.pack.context; import net.minecraft.core.Registry; import net.minecraft.resources.ResourceKey; import org.geysermc.hydraulic.HydraulicImpl; import org.geysermc.hydraulic.pack.PackModule; import org.geysermc.hydraulic.platform.mod.ModInfo; import org.geysermc.hydraulic.storage.ModStorage; import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Map; /** * Represents the context of a pack. * * @param <T> the module type */ public class PackContext<T extends PackModule<T>> { private final HydraulicImpl hydraulic; private final ModInfo mod; private final T module; public PackContext(@NotNull HydraulicImpl hydraulic, @NotNull ModInfo mod, @NotNull T module) { this.hydraulic = hydraulic; this.mod = mod; this.module = module; } /** * Gets the mod that owns this pack. * * @return the mod that owns this pack */ @NotNull public ModInfo mod() { return this.mod; } /** * Gets the storage for the mod that owns this pack. * * @return the storage for the mod that owns this pack */ @NotNull public ModStorage storage() { return this.hydraulic.modStorage(this.mod); } /** * Gets the module that this context is part of. * * @return the module that this context is part of */ @NotNull public T module() { return this.module; } /** * Gets the values from the specified {@link Registry registry} * that are relevant for the {@link ModInfo mod} this pack is * part of. * * @param key the key of the registry to get the values from * @return the values from the specified registry that are relevant for this mod * @param <V> the type of the registry */ @NotNull public <V> List<V> registryValues(@NotNull ResourceKey<Registry<V>> key) { Registry<V> registry =
this.hydraulic.server().registryAccess().registryOrThrow(key);
return registry.entrySet().stream() .filter(entry -> entry.getKey().location().getNamespace().equals(this.mod.id())) .map(Map.Entry::getValue) .toList(); } }
shared/src/main/java/org/geysermc/hydraulic/pack/context/PackContext.java
GeyserMC-Hydraulic-80cb8ab
[ { "filename": "shared/src/main/java/org/geysermc/hydraulic/util/PackUtil.java", "retrieved_chunk": "package org.geysermc.hydraulic.util;\nimport org.geysermc.hydraulic.platform.mod.ModInfo;\nimport org.geysermc.pack.bedrock.resource.BedrockResourcePack;\nimport org.geysermc.pack.bedrock.resource.Manifest;\nimport org.geysermc.pack.bedrock.resource.manifest.Header;\nimport org.geysermc.pack.bedrock.resource.manifest.Modules;\nimport org.jetbrains.annotations.NotNull;\nimport java.nio.file.Path;\nimport java.util.List;\nimport java.util.UUID;", "score": 0.7541741132736206 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/block/BlockPackModule.java", "retrieved_chunk": "package org.geysermc.hydraulic.block;\nimport com.google.auto.service.AutoService;\nimport net.kyori.adventure.key.Key;\nimport net.minecraft.commands.arguments.blocks.BlockStateParser;\nimport net.minecraft.core.DefaultedRegistry;\nimport net.minecraft.core.registries.BuiltInRegistries;\nimport net.minecraft.core.registries.Registries;\nimport net.minecraft.resources.ResourceLocation;\nimport net.minecraft.util.StringRepresentable;\nimport net.minecraft.world.level.block.Block;", "score": 0.7536962032318115 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/item/ItemPackModule.java", "retrieved_chunk": "package org.geysermc.hydraulic.item;\nimport com.google.auto.service.AutoService;\nimport net.kyori.adventure.key.Key;\nimport net.minecraft.core.DefaultedRegistry;\nimport net.minecraft.core.registries.BuiltInRegistries;\nimport net.minecraft.core.registries.Registries;\nimport net.minecraft.resources.ResourceLocation;\nimport net.minecraft.world.item.*;\nimport org.geysermc.geyser.api.event.lifecycle.GeyserDefineCustomItemsEvent;\nimport org.geysermc.geyser.api.item.custom.NonVanillaCustomItemData;", "score": 0.752547025680542 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/pack/PackListener.java", "retrieved_chunk": " this.hydraulic = hydraulic;\n this.manager = manager;\n }\n @Subscribe\n public void onLoadResourcePacks(GeyserLoadResourcePacksEvent event) {\n // TODO: Add this to Geyser API\n Path packsPath = GeyserImpl.getInstance().getBootstrap().getConfigFolder().resolve(\"packs\");\n Map<String, Pair<ModInfo, Path>> packsToLoad = new HashMap<>();\n for (ModInfo mod : this.hydraulic.mods()) {\n if (PackManager.IGNORED_MODS.contains(mod.id())) {", "score": 0.7495352625846863 }, { "filename": "forge/src/main/java/org/geysermc/hydraulic/forge/platform/HydraulicForgeBootstrap.java", "retrieved_chunk": "public class HydraulicForgeBootstrap implements HydraulicBootstrap {\n @Override\n public @NotNull Set<ModInfo> mods() {\n return ModList.get().getMods().stream().map(modInfo ->\n new ModInfo(\n modInfo.getModId(),\n modInfo.getVersion().toString(),\n modInfo.getDisplayName(),\n modInfo.getOwningFile().getFile().getFilePath(),\n modInfo.getLogoFile().orElse(\"\")", "score": 0.749465823173523 } ]
java
this.hydraulic.server().registryAccess().registryOrThrow(key);
package io.github.heartalborada_del.newBingAPI.utils; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import io.github.heartalborada_del.newBingAPI.interfaces.Callback; import io.github.heartalborada_del.newBingAPI.interfaces.Logger; import io.github.heartalborada_del.newBingAPI.types.ChatWebsocketJson; import io.github.heartalborada_del.newBingAPI.types.chat.Argument; import io.github.heartalborada_del.newBingAPI.types.chat.Message; import io.github.heartalborada_del.newBingAPI.types.chat.Participant; import okhttp3.Response; import okhttp3.WebSocket; import okhttp3.WebSocketListener; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class ConversationWebsocket extends WebSocketListener { private final char TerminalChar = '\u001e'; private final String conversationId; private final String clientId; private final String conversationSignature; private final String question; private final String invocationID; private final Callback callback; private final Logger logger; private final String locale; private final String tone; public ConversationWebsocket(String ConversationId, String ClientId, String ConversationSignature, String question, short invocationID, Callback callback, Logger logger, String locale, String tone) { conversationId = ConversationId; clientId = ClientId; conversationSignature = ConversationSignature; this.question = question; this.invocationID = String.valueOf(invocationID); this.callback = callback; this.logger = logger; this.locale = locale; this.tone = tone; } @Override public void onClosed(@NotNull WebSocket webSocket, int code, @NotNull String reason) {
logger.Info(String.format("[%s] [%s] websocket is closed", conversationSignature, question));
super.onClosed(webSocket, code, reason); } @Override public void onClosing(@NotNull WebSocket webSocket, int code, @NotNull String reason) { logger.Info(String.format("[%s] [%s] websocket is closing", conversationSignature, question)); super.onClosing(webSocket, code, reason); } @Override public void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, @Nullable Response response) { //logger.Error(String.format("[%s] [%s] websocket is failed, reason: [%s]",conversationSignature,question, t.getCause())); webSocket.close(1000, String.valueOf(TerminalChar)); super.onFailure(webSocket, t, response); } @Override public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) { for (String textSpited : text.split(String.valueOf(TerminalChar))) { logger.Debug(String.format("[%s] [%s] websocket is received new message [%s]", conversationSignature, question, textSpited)); JsonObject json = JsonParser.parseString(textSpited).getAsJsonObject(); if (json.isEmpty()) { sendData(webSocket, "{\"type\":6}"); String s = new GsonBuilder().disableHtmlEscaping().create().toJson( new ChatWebsocketJson(new Argument[]{ new Argument( Utils.randomString(32).toLowerCase(), invocationID.equals("0"), new Message( locale, locale, null, null, null, Utils.getNowTime(), question ), conversationSignature, new Participant(clientId), conversationId, null, tone) }, invocationID) ); sendData(webSocket, s); } else if (json.has("type")) { int type = json.getAsJsonPrimitive("type").getAsInt(); if (type == 3) { //end webSocket.close(1000, String.valueOf(TerminalChar)); } else if (type == 6) { //resend packet sendData(webSocket, "{\"type\":6}"); } else if (type == 2) { if (json.getAsJsonObject("item").has("result") && !json.getAsJsonObject("item").getAsJsonObject("result").getAsJsonPrimitive("value").getAsString().equals("Success")) { callback.onFailure(json, json.getAsJsonObject("item").getAsJsonObject("result").getAsJsonPrimitive("message").getAsString()); } else { callback.onSuccess(json); } } else if (type == 1) { callback.onUpdate(json); } else if (type == 7) { callback.onFailure(json, json.getAsJsonPrimitive("error").getAsString()); webSocket.close(1000, String.valueOf(TerminalChar)); } } else if (json.has("error")) { callback.onFailure(json, json.getAsJsonPrimitive("error").getAsString()); webSocket.close(1000, String.valueOf(TerminalChar)); } } super.onMessage(webSocket, text); } @Override public void onOpen(@NotNull WebSocket webSocket, @NotNull Response response) { super.onOpen(webSocket, response); sendData(webSocket, "{\"protocol\":\"json\",\"version\":1}"); } private void sendData(@NotNull WebSocket ws, @NotNull String data) { logger.Debug(String.format("[%s] [%s] client send message [%s]", conversationSignature, question, data)); ws.send(data + TerminalChar); } }
src/main/java/io/github/heartalborada_del/newBingAPI/utils/ConversationWebsocket.java
heartalborada-del-newbingAPI-1102bfb
[ { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/instances/ChatInstance.java", "retrieved_chunk": " public void onFailure(JsonObject rawData, String cause) {\n callback.onFailure(rawData, cause);\n }\n @Override\n public void onUpdate(JsonObject rawData) {\n callback.onUpdate(rawData);\n }\n };\n Request request = new Request.Builder().get().url(\"wss://sydney.bing.com/sydney/ChatHub\").build();\n logger.Debug(String.format(\"Add a question [%s] to the queue,the current length of the queue is %d\", question, client.dispatcher().runningCallsCount()));", "score": 0.8359131813049316 }, { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/instances/ChatInstance.java", "retrieved_chunk": " private final OkHttpClient client;\n private final String conversationId;\n private final String clientId;\n private final String conversationSignature;\n private final Logger logger;\n private final String locale;\n private short chatCount;\n private int maxNumConversation = 15;\n private final long time;\n private final String tone;", "score": 0.8273754715919495 }, { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/instances/ChatInstance.java", "retrieved_chunk": " public ChatInstance(OkHttpClient.Builder httpClientBuilder, Logger logger, String locale, String tone) throws IOException, ConversationException {\n client = httpClientBuilder.dispatcher(new Dispatcher(threadPool)).build();\n this.logger = logger;\n this.locale = locale;\n this.tone = tone;\n logger.Debug(\"Creating Conversation ID\");\n Request req = new Request.Builder().url(\"https://www.bing.com/turing/conversation/create\").get().build();\n String s = Objects.requireNonNull(client.newCall(req).execute().body()).string();\n JsonObject json = JsonParser.parseString(Objects.requireNonNull(s)).getAsJsonObject();\n if (!json.getAsJsonObject(\"result\").getAsJsonPrimitive(\"value\").getAsString().equals(\"Success\"))", "score": 0.8120847940444946 }, { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/instances/ChatInstance.java", "retrieved_chunk": "package io.github.heartalborada_del.newBingAPI.instances;\nimport com.google.gson.JsonObject;\nimport com.google.gson.JsonParser;\nimport io.github.heartalborada_del.newBingAPI.exceptions.ConversationException;\nimport io.github.heartalborada_del.newBingAPI.exceptions.ConversationExpiredException;\nimport io.github.heartalborada_del.newBingAPI.exceptions.ConversationLimitedException;\nimport io.github.heartalborada_del.newBingAPI.exceptions.ConversationUninitializedException;\nimport io.github.heartalborada_del.newBingAPI.interfaces.Callback;\nimport io.github.heartalborada_del.newBingAPI.interfaces.Logger;\nimport io.github.heartalborada_del.newBingAPI.utils.ConversationWebsocket;", "score": 0.8109764456748962 }, { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/instances/ChatInstance.java", "retrieved_chunk": " throw new ConversationException(json.getAsJsonObject(\"result\").getAsJsonPrimitive(\"message\").getAsString());\n time = new Date().getTime();\n chatCount = 0;\n conversationId = json.getAsJsonPrimitive(\"conversationId\").getAsString();\n logger.Debug(String.format(\"New Conversation ID [%s]\", conversationId));\n clientId = json.getAsJsonPrimitive(\"clientId\").getAsString();\n conversationSignature = json.getAsJsonPrimitive(\"conversationSignature\").getAsString();\n }\n /**\n * Sends a new question to the conversation instance.", "score": 0.8099292516708374 } ]
java
logger.Info(String.format("[%s] [%s] websocket is closed", conversationSignature, question));
package io.github.heartalborada_del.newBingAPI.utils; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import io.github.heartalborada_del.newBingAPI.interfaces.Callback; import io.github.heartalborada_del.newBingAPI.interfaces.Logger; import io.github.heartalborada_del.newBingAPI.types.ChatWebsocketJson; import io.github.heartalborada_del.newBingAPI.types.chat.Argument; import io.github.heartalborada_del.newBingAPI.types.chat.Message; import io.github.heartalborada_del.newBingAPI.types.chat.Participant; import okhttp3.Response; import okhttp3.WebSocket; import okhttp3.WebSocketListener; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class ConversationWebsocket extends WebSocketListener { private final char TerminalChar = '\u001e'; private final String conversationId; private final String clientId; private final String conversationSignature; private final String question; private final String invocationID; private final Callback callback; private final Logger logger; private final String locale; private final String tone; public ConversationWebsocket(String ConversationId, String ClientId, String ConversationSignature, String question, short invocationID, Callback callback, Logger logger, String locale, String tone) { conversationId = ConversationId; clientId = ClientId; conversationSignature = ConversationSignature; this.question = question; this.invocationID = String.valueOf(invocationID); this.callback = callback; this.logger = logger; this.locale = locale; this.tone = tone; } @Override public void onClosed(@NotNull WebSocket webSocket, int code, @NotNull String reason) { logger.Info(String.format("[%s] [%s] websocket is closed", conversationSignature, question)); super.onClosed(webSocket, code, reason); } @Override public void onClosing(@NotNull WebSocket webSocket, int code, @NotNull String reason) { logger.Info(String.format("[%s] [%s] websocket is closing", conversationSignature, question)); super.onClosing(webSocket, code, reason); } @Override public void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, @Nullable Response response) { //logger.Error(String.format("[%s] [%s] websocket is failed, reason: [%s]",conversationSignature,question, t.getCause())); webSocket.close(1000, String.valueOf(TerminalChar)); super.onFailure(webSocket, t, response); } @Override public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) { for (String textSpited : text.split(String.valueOf(TerminalChar))) { logger.Debug(String.format("[%s] [%s] websocket is received new message [%s]", conversationSignature, question, textSpited)); JsonObject json = JsonParser.parseString(textSpited).getAsJsonObject(); if (json.isEmpty()) { sendData(webSocket, "{\"type\":6}"); String s = new GsonBuilder().disableHtmlEscaping().create().toJson( new ChatWebsocketJson(new Argument[]{ new Argument( Utils.randomString(32).toLowerCase(), invocationID.equals("0"), new Message( locale, locale, null, null, null, Utils.getNowTime(), question ), conversationSignature, new Participant(clientId), conversationId, null, tone) }, invocationID) ); sendData(webSocket, s); } else if (json.has("type")) { int type = json.getAsJsonPrimitive("type").getAsInt(); if (type == 3) { //end webSocket.close(1000, String.valueOf(TerminalChar)); } else if (type == 6) { //resend packet sendData(webSocket, "{\"type\":6}"); } else if (type == 2) { if (json.getAsJsonObject("item").has("result") && !json.getAsJsonObject("item").getAsJsonObject("result").getAsJsonPrimitive("value").getAsString().equals("Success")) { callback.onFailure(json, json.getAsJsonObject("item").getAsJsonObject("result").getAsJsonPrimitive("message").getAsString()); } else { callback.onSuccess(json); } } else if (type == 1) { callback.onUpdate(json); } else if (type == 7) { callback.onFailure(json, json.getAsJsonPrimitive("error").getAsString()); webSocket.close(1000, String.valueOf(TerminalChar)); } } else if (json.has("error")) { callback.onFailure(json, json.getAsJsonPrimitive("error").getAsString()); webSocket.close(1000, String.valueOf(TerminalChar)); } } super.onMessage(webSocket, text); } @Override public void onOpen(@NotNull WebSocket webSocket, @NotNull Response response) { super.onOpen(webSocket, response); sendData(webSocket, "{\"protocol\":\"json\",\"version\":1}"); } private void sendData(@NotNull WebSocket ws, @NotNull String data) {
logger.Debug(String.format("[%s] [%s] client send message [%s]", conversationSignature, question, data));
ws.send(data + TerminalChar); } }
src/main/java/io/github/heartalborada_del/newBingAPI/utils/ConversationWebsocket.java
heartalborada-del-newbingAPI-1102bfb
[ { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/instances/ChatInstance.java", "retrieved_chunk": " public void onFailure(JsonObject rawData, String cause) {\n callback.onFailure(rawData, cause);\n }\n @Override\n public void onUpdate(JsonObject rawData) {\n callback.onUpdate(rawData);\n }\n };\n Request request = new Request.Builder().get().url(\"wss://sydney.bing.com/sydney/ChatHub\").build();\n logger.Debug(String.format(\"Add a question [%s] to the queue,the current length of the queue is %d\", question, client.dispatcher().runningCallsCount()));", "score": 0.8409503698348999 }, { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/instances/ChatInstance.java", "retrieved_chunk": " throw new ConversationException(json.getAsJsonObject(\"result\").getAsJsonPrimitive(\"message\").getAsString());\n time = new Date().getTime();\n chatCount = 0;\n conversationId = json.getAsJsonPrimitive(\"conversationId\").getAsString();\n logger.Debug(String.format(\"New Conversation ID [%s]\", conversationId));\n clientId = json.getAsJsonPrimitive(\"clientId\").getAsString();\n conversationSignature = json.getAsJsonPrimitive(\"conversationSignature\").getAsString();\n }\n /**\n * Sends a new question to the conversation instance.", "score": 0.8145369291305542 }, { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/instances/ChatInstance.java", "retrieved_chunk": " client.newWebSocket(\n request,\n new ConversationWebsocket(\n conversationId,\n clientId,\n conversationSignature,\n question,\n chatCount,\n cb,\n logger,", "score": 0.809707522392273 }, { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/instances/ChatInstance.java", "retrieved_chunk": "package io.github.heartalborada_del.newBingAPI.instances;\nimport com.google.gson.JsonObject;\nimport com.google.gson.JsonParser;\nimport io.github.heartalborada_del.newBingAPI.exceptions.ConversationException;\nimport io.github.heartalborada_del.newBingAPI.exceptions.ConversationExpiredException;\nimport io.github.heartalborada_del.newBingAPI.exceptions.ConversationLimitedException;\nimport io.github.heartalborada_del.newBingAPI.exceptions.ConversationUninitializedException;\nimport io.github.heartalborada_del.newBingAPI.interfaces.Callback;\nimport io.github.heartalborada_del.newBingAPI.interfaces.Logger;\nimport io.github.heartalborada_del.newBingAPI.utils.ConversationWebsocket;", "score": 0.7926792502403259 }, { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/types/ChatWebsocketJson.java", "retrieved_chunk": "package io.github.heartalborada_del.newBingAPI.types;\nimport io.github.heartalborada_del.newBingAPI.types.chat.Argument;\npublic class ChatWebsocketJson {\n private final Argument[] arguments;\n private final String invocationId;\n private final String target = \"chat\";\n private final int type = 4;\n public ChatWebsocketJson(Argument[] args, String invocationId) {\n arguments = args;\n this.invocationId = invocationId;", "score": 0.786194920539856 } ]
java
logger.Debug(String.format("[%s] [%s] client send message [%s]", conversationSignature, question, data));
package org.geysermc.hydraulic; import net.minecraft.server.MinecraftServer; import org.geysermc.geyser.api.event.EventRegistrar; import org.geysermc.hydraulic.pack.PackManager; import org.geysermc.hydraulic.platform.HydraulicBootstrap; import org.geysermc.hydraulic.platform.HydraulicPlatform; import org.geysermc.hydraulic.platform.mod.ModInfo; import org.geysermc.hydraulic.storage.ModStorage; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Main class of the Hydraulic mod. */ public class HydraulicImpl implements EventRegistrar { private static final Logger LOGGER = LoggerFactory.getLogger("Hydraulic"); private static HydraulicImpl instance; private final HydraulicPlatform platform; private final HydraulicBootstrap bootstrap; private final PackManager packManager; private final Map<String, ModStorage> modStorage = new HashMap<>(); private MinecraftServer server; private HydraulicImpl(HydraulicPlatform platform, HydraulicBootstrap bootstrap) { instance = this; this.platform = platform; this.bootstrap = bootstrap; this.packManager = new PackManager(this); } /** * Called when the server is starting. * * @param server the Minecraft server instance */ public void onServerStarting(@NotNull MinecraftServer server) { this.server = server; this
.packManager.initialize();
} /** * Gets all the mods loaded on this platform. * * @return the mods loaded on this platform */ @NotNull public Set<ModInfo> mods() { return this.bootstrap.mods(); } /** * Gets the mod with the specified name, or null if not found. * * @param modName the name of the mod to get * @return the mod with the specified name */ @Nullable public ModInfo mod(@NotNull String modName) { return this.bootstrap.mod(modName); } /** * Gets the Minecraft server instance. * * @return the Minecraft server instance */ @NotNull public MinecraftServer server() { return this.server; } /** * Gets the data folder directory of this platform. * * @return the data folder directory */ @NotNull public Path dataFolder(@NotNull String modId) { return this.bootstrap.dataFolder(modId); } /** * Gets the mod storage for the specified mod. * * @param mod the mod * @return the mod storage */ @NotNull public ModStorage modStorage(@NotNull ModInfo mod) { return this.modStorage.computeIfAbsent(mod.id(), e -> ModStorage.load(mod)); } /** * Loads Hydraulic. * * @param platform the platform Hydraulic is running on * @param bootstrap the Hydraulic platform bootstrap * @return the loaded Hydraulic instance */ @NotNull public static HydraulicImpl load(@NotNull HydraulicPlatform platform, @NotNull HydraulicBootstrap bootstrap) { if (instance != null) { throw new IllegalStateException("Singleton HydraulicImpl has already been loaded!"); } return new HydraulicImpl(platform, bootstrap); } /** * Gets the Hydraulic instance. * * @return the Hydraulic instance */ @NotNull public static HydraulicImpl instance() { if (instance == null) { throw new IllegalStateException("Hydraulic has not been loaded!"); } return instance; } }
shared/src/main/java/org/geysermc/hydraulic/HydraulicImpl.java
GeyserMC-Hydraulic-80cb8ab
[ { "filename": "forge/src/main/java/org/geysermc/hydraulic/forge/HydraulicForgeMod.java", "retrieved_chunk": " private final HydraulicImpl hydraulic;\n public HydraulicForgeMod() {\n this.hydraulic = HydraulicImpl.load(HydraulicPlatform.FORGE, new HydraulicForgeBootstrap());\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onServerStarting);\n }\n private void onServerStarting(ServerStartingEvent event) {\n this.hydraulic.onServerStarting(event.getServer());\n }\n}", "score": 0.8014106750488281 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/pack/PackListener.java", "retrieved_chunk": " this.hydraulic = hydraulic;\n this.manager = manager;\n }\n @Subscribe\n public void onLoadResourcePacks(GeyserLoadResourcePacksEvent event) {\n // TODO: Add this to Geyser API\n Path packsPath = GeyserImpl.getInstance().getBootstrap().getConfigFolder().resolve(\"packs\");\n Map<String, Pair<ModInfo, Path>> packsToLoad = new HashMap<>();\n for (ModInfo mod : this.hydraulic.mods()) {\n if (PackManager.IGNORED_MODS.contains(mod.id())) {", "score": 0.7949693202972412 }, { "filename": "fabric/src/main/java/org/geysermc/hydraulic/fabric/HydraulicFabricMod.java", "retrieved_chunk": " this.hydraulic = HydraulicImpl.load(HydraulicPlatform.FABRIC, new HydraulicFabricBootstrap());\n ServerLifecycleEvents.SERVER_STARTING.register(this.hydraulic::onServerStarting);\n }\n}", "score": 0.7921480536460876 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/pack/PackManager.java", "retrieved_chunk": " * for loading the packs onto the server.\n */\npublic class PackManager {\n private static final Logger LOGGER = LogUtils.getLogger();\n static final Set<String> IGNORED_MODS = Set.of(\n \"minecraft\",\n \"java\",\n \"hydraulic\",\n \"geyser-fabric\",\n \"geyser-forge\",", "score": 0.7915443778038025 }, { "filename": "forge/src/main/java/org/geysermc/hydraulic/forge/HydraulicForgeMod.java", "retrieved_chunk": "package org.geysermc.hydraulic.forge;\nimport net.minecraftforge.event.server.ServerStartingEvent;\nimport net.minecraftforge.fml.common.Mod;\nimport net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;\nimport org.geysermc.hydraulic.Constants;\nimport org.geysermc.hydraulic.HydraulicImpl;\nimport org.geysermc.hydraulic.forge.platform.HydraulicForgeBootstrap;\nimport org.geysermc.hydraulic.platform.HydraulicPlatform;\n@Mod(Constants.MOD_ID)\npublic class HydraulicForgeMod {", "score": 0.7911368608474731 } ]
java
.packManager.initialize();
package io.github.heartalborada_del.newBingAPI.utils; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import io.github.heartalborada_del.newBingAPI.interfaces.Callback; import io.github.heartalborada_del.newBingAPI.interfaces.Logger; import io.github.heartalborada_del.newBingAPI.types.ChatWebsocketJson; import io.github.heartalborada_del.newBingAPI.types.chat.Argument; import io.github.heartalborada_del.newBingAPI.types.chat.Message; import io.github.heartalborada_del.newBingAPI.types.chat.Participant; import okhttp3.Response; import okhttp3.WebSocket; import okhttp3.WebSocketListener; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class ConversationWebsocket extends WebSocketListener { private final char TerminalChar = '\u001e'; private final String conversationId; private final String clientId; private final String conversationSignature; private final String question; private final String invocationID; private final Callback callback; private final Logger logger; private final String locale; private final String tone; public ConversationWebsocket(String ConversationId, String ClientId, String ConversationSignature, String question, short invocationID, Callback callback, Logger logger, String locale, String tone) { conversationId = ConversationId; clientId = ClientId; conversationSignature = ConversationSignature; this.question = question; this.invocationID = String.valueOf(invocationID); this.callback = callback; this.logger = logger; this.locale = locale; this.tone = tone; } @Override public void onClosed(@NotNull WebSocket webSocket, int code, @NotNull String reason) { logger.Info(String.format("[%s] [%s] websocket is closed", conversationSignature, question)); super.onClosed(webSocket, code, reason); } @Override public void onClosing(@NotNull WebSocket webSocket, int code, @NotNull String reason) { logger.Info(String.format("[%s] [%s] websocket is closing", conversationSignature, question)); super.onClosing(webSocket, code, reason); } @Override public void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, @Nullable Response response) { //logger.Error(String.format("[%s] [%s] websocket is failed, reason: [%s]",conversationSignature,question, t.getCause())); webSocket.close(1000, String.valueOf(TerminalChar)); super.onFailure(webSocket, t, response); } @Override public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) { for (String textSpited : text.split(String.valueOf(TerminalChar))) {
logger.Debug(String.format("[%s] [%s] websocket is received new message [%s]", conversationSignature, question, textSpited));
JsonObject json = JsonParser.parseString(textSpited).getAsJsonObject(); if (json.isEmpty()) { sendData(webSocket, "{\"type\":6}"); String s = new GsonBuilder().disableHtmlEscaping().create().toJson( new ChatWebsocketJson(new Argument[]{ new Argument( Utils.randomString(32).toLowerCase(), invocationID.equals("0"), new Message( locale, locale, null, null, null, Utils.getNowTime(), question ), conversationSignature, new Participant(clientId), conversationId, null, tone) }, invocationID) ); sendData(webSocket, s); } else if (json.has("type")) { int type = json.getAsJsonPrimitive("type").getAsInt(); if (type == 3) { //end webSocket.close(1000, String.valueOf(TerminalChar)); } else if (type == 6) { //resend packet sendData(webSocket, "{\"type\":6}"); } else if (type == 2) { if (json.getAsJsonObject("item").has("result") && !json.getAsJsonObject("item").getAsJsonObject("result").getAsJsonPrimitive("value").getAsString().equals("Success")) { callback.onFailure(json, json.getAsJsonObject("item").getAsJsonObject("result").getAsJsonPrimitive("message").getAsString()); } else { callback.onSuccess(json); } } else if (type == 1) { callback.onUpdate(json); } else if (type == 7) { callback.onFailure(json, json.getAsJsonPrimitive("error").getAsString()); webSocket.close(1000, String.valueOf(TerminalChar)); } } else if (json.has("error")) { callback.onFailure(json, json.getAsJsonPrimitive("error").getAsString()); webSocket.close(1000, String.valueOf(TerminalChar)); } } super.onMessage(webSocket, text); } @Override public void onOpen(@NotNull WebSocket webSocket, @NotNull Response response) { super.onOpen(webSocket, response); sendData(webSocket, "{\"protocol\":\"json\",\"version\":1}"); } private void sendData(@NotNull WebSocket ws, @NotNull String data) { logger.Debug(String.format("[%s] [%s] client send message [%s]", conversationSignature, question, data)); ws.send(data + TerminalChar); } }
src/main/java/io/github/heartalborada_del/newBingAPI/utils/ConversationWebsocket.java
heartalborada-del-newbingAPI-1102bfb
[ { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/instances/ChatInstance.java", "retrieved_chunk": " public void onFailure(JsonObject rawData, String cause) {\n callback.onFailure(rawData, cause);\n }\n @Override\n public void onUpdate(JsonObject rawData) {\n callback.onUpdate(rawData);\n }\n };\n Request request = new Request.Builder().get().url(\"wss://sydney.bing.com/sydney/ChatHub\").build();\n logger.Debug(String.format(\"Add a question [%s] to the queue,the current length of the queue is %d\", question, client.dispatcher().runningCallsCount()));", "score": 0.8542141318321228 }, { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/instances/ChatInstance.java", "retrieved_chunk": " @Override\n public void onSuccess(JsonObject rawData) {\n if (rawData.has(\"item\") && rawData.getAsJsonObject(\"item\").has(\"throttling\") && rawData.getAsJsonObject(\"item\").getAsJsonObject(\"throttling\").has(\"maxNumUserMessagesInConversation\")) {\n maxNumConversation = rawData.getAsJsonObject(\"item\")\n .getAsJsonObject(\"throttling\")\n .getAsJsonPrimitive(\"maxNumUserMessagesInConversation\").getAsInt();\n }\n callback.onSuccess(rawData);\n }\n @Override", "score": 0.7914201021194458 }, { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/instances/ChatInstance.java", "retrieved_chunk": " client.newWebSocket(\n request,\n new ConversationWebsocket(\n conversationId,\n clientId,\n conversationSignature,\n question,\n chatCount,\n cb,\n logger,", "score": 0.7908153533935547 }, { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/instances/ChatInstance.java", "retrieved_chunk": "package io.github.heartalborada_del.newBingAPI.instances;\nimport com.google.gson.JsonObject;\nimport com.google.gson.JsonParser;\nimport io.github.heartalborada_del.newBingAPI.exceptions.ConversationException;\nimport io.github.heartalborada_del.newBingAPI.exceptions.ConversationExpiredException;\nimport io.github.heartalborada_del.newBingAPI.exceptions.ConversationLimitedException;\nimport io.github.heartalborada_del.newBingAPI.exceptions.ConversationUninitializedException;\nimport io.github.heartalborada_del.newBingAPI.interfaces.Callback;\nimport io.github.heartalborada_del.newBingAPI.interfaces.Logger;\nimport io.github.heartalborada_del.newBingAPI.utils.ConversationWebsocket;", "score": 0.7844918370246887 }, { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/Chat.java", "retrieved_chunk": " public Chat(String defaultCookie, String tone) {\n this.tone = tone;\n c = new DefaultClient(defaultCookie).getClient().newBuilder();\n this.locale = \"zh-CN\";\n this.logger = new Logger() {\n @Override\n public void Info(String log) {\n }\n @Override\n public void Error(String log) {", "score": 0.7809697985649109 } ]
java
logger.Debug(String.format("[%s] [%s] websocket is received new message [%s]", conversationSignature, question, textSpited));
package com.phonenumberinput; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Color; import android.os.Build; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.recyclerview.selection.SelectionTracker; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.util.List; public class CountryPickerAdapter extends RecyclerView.Adapter<CountryPickerListItem> { private List<Country> countries; private final LayoutInflater inflater; private boolean darkMode; private SelectionTracker<String> selectionTracker; private int defaultCountry; private final LinearLayoutManager layoutManager; public CountryPickerAdapter(Context context, List<Country> countries, LinearLayoutManager layoutManager) { this.countries = countries; this.inflater = LayoutInflater.from(context); this.layoutManager = layoutManager; } public void onCountryClick(int index) { setSelectedIndex(index); notifyItemChanged(index); } public void setSelectionTracker(SelectionTracker<String> selectionTracker) { this.selectionTracker = selectionTracker; if (defaultCountry >= 0 && defaultCountry < countries.size()) { String countryCode = countries.get(defaultCountry).getCode(); selectionTracker.select(countryCode); } else { selectionTracker.clearSelection(); } } public void setCountries(List<Country> countries) { this.countries = countries; if (selectionTracker == null) { return; } if (defaultCountry >= 0 && defaultCountry < countries.size()) { String countryCode = countries.get(defaultCountry).getCode(); selectionTracker.select(countryCode); } else { selectionTracker.clearSelection(); } } @SuppressLint("NotifyDataSetChanged") public void setDarkMode(boolean darkMode) { this.darkMode = darkMode; notifyDataSetChanged(); } @RequiresApi(api = Build.VERSION_CODES.N) @NonNull @Override public CountryPickerListItem onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = inflater.inflate(R.layout.country_picker_list_item, parent, false); return new CountryPickerListItem(view, this::onCountryClick); } @Override public void onBindViewHolder(@NonNull CountryPickerListItem holder, int position) { Country country = countries.get(position); // Set the country flag, country name, and calling code for the current list item holder.countryName.setText
(String.format("%s %s", country.getEmoji(), country.getName()));
holder.callingCode.setText(country.getCallingCode()); int textColor = darkMode ? Color.parseColor("#FFFFFF") : Color.parseColor("#000000"); holder.countryName.setTextColor(textColor); holder.callingCode.setTextColor(textColor); holder.bind(country); boolean isSelected = selectionTracker.isSelected(country.getCode()); holder.itemView.setActivated(isSelected); holder.highlight(isSelected, darkMode); } @Override public int getItemCount() { return countries.size(); } public void setSelectedIndex(int selectedIndex) { defaultCountry = selectedIndex; if (selectionTracker == null) { return; } if (selectedIndex >= 0 && selectedIndex < countries.size()) { String countryCode = countries.get(selectedIndex).getCode(); selectionTracker.select(countryCode); layoutManager.scrollToPosition(selectedIndex); } else { selectionTracker.clearSelection(); } } }
android/src/main/java/com/phonenumberinput/CountryPickerAdapter.java
gtomitsuka-rn-phone-number-input-2f2e43b
[ { "filename": "android/src/main/java/com/phonenumberinput/CountryPickerListItem.java", "retrieved_chunk": "import java.util.function.Consumer;\npublic class CountryPickerListItem extends RecyclerView.ViewHolder {\n TextView countryName; // includes emoji\n TextView callingCode;\n Country country;\n @RequiresApi(api = Build.VERSION_CODES.N)\n public CountryPickerListItem(@NonNull View itemView, Consumer<Integer> countryClickListener) {\n super(itemView);\n countryName = itemView.findViewById(R.id.country_name);\n callingCode = itemView.findViewById(R.id.calling_code);", "score": 0.9155949354171753 }, { "filename": "android/src/main/java/com/phonenumberinput/CountryPickerListItem.java", "retrieved_chunk": " itemView.setOnClickListener(l -> {\n System.out.println(\"called\");\n int position = getBindingAdapterPosition();\n if (position != RecyclerView.NO_POSITION) {\n countryClickListener.accept(position);\n }\n });\n }\n public void bind(Country country) {\n this.country = country;", "score": 0.8819781541824341 }, { "filename": "android/src/main/java/com/phonenumberinput/CountryDetailsLookup.java", "retrieved_chunk": " return ((CountryPickerListItem) viewHolder).getItemDetails();\n }\n }\n return null;\n }\n}", "score": 0.8774386048316956 }, { "filename": "android/src/main/java/com/phonenumberinput/PhoneNumberInputViewManager.java", "retrieved_chunk": " if (adapter != null) {\n adapter.setCountries(countries);\n } else {\n LinearLayoutManager layoutManager = new LinearLayoutManager(view.getContext(), LinearLayoutManager.VERTICAL, false);\n view.setLayoutManager(layoutManager);\n LinearSnapHelper snapHelper = new LinearSnapHelper();\n snapHelper.attachToRecyclerView(view);\n adapter = new CountryPickerAdapter(view.getContext(), countries, layoutManager);\n view.setAdapter(adapter);\n }", "score": 0.8698428869247437 }, { "filename": "android/src/main/java/com/phonenumberinput/PhoneNumberInputViewManager.java", "retrieved_chunk": " // Set up the SelectionTracker\n SelectionTracker<String> selectionTracker = new SelectionTracker.Builder<>(\n \"countryPickerSelection\",\n view,\n new CountryKeyProvider(1, countries),\n new CountryDetailsLookup(view),\n StorageStrategy.createStringStorage())\n .withSelectionPredicate(SelectionPredicates.createSelectSingleAnything())\n .build();\n adapter.setSelectionTracker(selectionTracker);", "score": 0.8695108294487 } ]
java
(String.format("%s %s", country.getEmoji(), country.getName()));
package org.geysermc.hydraulic; import net.minecraft.server.MinecraftServer; import org.geysermc.geyser.api.event.EventRegistrar; import org.geysermc.hydraulic.pack.PackManager; import org.geysermc.hydraulic.platform.HydraulicBootstrap; import org.geysermc.hydraulic.platform.HydraulicPlatform; import org.geysermc.hydraulic.platform.mod.ModInfo; import org.geysermc.hydraulic.storage.ModStorage; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Main class of the Hydraulic mod. */ public class HydraulicImpl implements EventRegistrar { private static final Logger LOGGER = LoggerFactory.getLogger("Hydraulic"); private static HydraulicImpl instance; private final HydraulicPlatform platform; private final HydraulicBootstrap bootstrap; private final PackManager packManager; private final Map<String, ModStorage> modStorage = new HashMap<>(); private MinecraftServer server; private HydraulicImpl(HydraulicPlatform platform, HydraulicBootstrap bootstrap) { instance = this; this.platform = platform; this.bootstrap = bootstrap; this.packManager = new PackManager(this); } /** * Called when the server is starting. * * @param server the Minecraft server instance */ public void onServerStarting(@NotNull MinecraftServer server) { this.server = server; this.packManager.initialize(); } /** * Gets all the mods loaded on this platform. * * @return the mods loaded on this platform */ @NotNull public Set<ModInfo> mods() { return
this.bootstrap.mods();
} /** * Gets the mod with the specified name, or null if not found. * * @param modName the name of the mod to get * @return the mod with the specified name */ @Nullable public ModInfo mod(@NotNull String modName) { return this.bootstrap.mod(modName); } /** * Gets the Minecraft server instance. * * @return the Minecraft server instance */ @NotNull public MinecraftServer server() { return this.server; } /** * Gets the data folder directory of this platform. * * @return the data folder directory */ @NotNull public Path dataFolder(@NotNull String modId) { return this.bootstrap.dataFolder(modId); } /** * Gets the mod storage for the specified mod. * * @param mod the mod * @return the mod storage */ @NotNull public ModStorage modStorage(@NotNull ModInfo mod) { return this.modStorage.computeIfAbsent(mod.id(), e -> ModStorage.load(mod)); } /** * Loads Hydraulic. * * @param platform the platform Hydraulic is running on * @param bootstrap the Hydraulic platform bootstrap * @return the loaded Hydraulic instance */ @NotNull public static HydraulicImpl load(@NotNull HydraulicPlatform platform, @NotNull HydraulicBootstrap bootstrap) { if (instance != null) { throw new IllegalStateException("Singleton HydraulicImpl has already been loaded!"); } return new HydraulicImpl(platform, bootstrap); } /** * Gets the Hydraulic instance. * * @return the Hydraulic instance */ @NotNull public static HydraulicImpl instance() { if (instance == null) { throw new IllegalStateException("Hydraulic has not been loaded!"); } return instance; } }
shared/src/main/java/org/geysermc/hydraulic/HydraulicImpl.java
GeyserMC-Hydraulic-80cb8ab
[ { "filename": "shared/src/main/java/org/geysermc/hydraulic/platform/HydraulicBootstrap.java", "retrieved_chunk": " /**\n * Gets all the mods loaded on this platform.\n *\n * @return the mods loaded on this platform\n */\n @NotNull\n Set<ModInfo> mods();\n /**\n * Gets the mod with the specified name, or null if not found.\n *", "score": 0.8950875997543335 }, { "filename": "forge/src/main/java/org/geysermc/hydraulic/forge/platform/HydraulicForgeBootstrap.java", "retrieved_chunk": "public class HydraulicForgeBootstrap implements HydraulicBootstrap {\n @Override\n public @NotNull Set<ModInfo> mods() {\n return ModList.get().getMods().stream().map(modInfo ->\n new ModInfo(\n modInfo.getModId(),\n modInfo.getVersion().toString(),\n modInfo.getDisplayName(),\n modInfo.getOwningFile().getFile().getFilePath(),\n modInfo.getLogoFile().orElse(\"\")", "score": 0.8665085434913635 }, { "filename": "fabric/src/main/java/org/geysermc/hydraulic/fabric/platform/HydraulicFabricBootstrap.java", "retrieved_chunk": "public class HydraulicFabricBootstrap implements HydraulicBootstrap {\n @Override\n public @NotNull Set<ModInfo> mods() {\n return FabricLoader.getInstance().getAllMods().stream().filter(container -> !ignoreMod(container)).map(container ->\n new ModInfo(\n container.getMetadata().getId(),\n container.getMetadata().getVersion().getFriendlyString(),\n container.getMetadata().getName(),\n container.getRootPaths().get(0), // TODO: Multi-path support\n container.getMetadata().getIconPath(256).orElse(\"\")", "score": 0.8556893467903137 }, { "filename": "forge/src/main/java/org/geysermc/hydraulic/forge/platform/HydraulicForgeBootstrap.java", "retrieved_chunk": "package org.geysermc.hydraulic.forge.platform;\nimport net.minecraftforge.fml.ModList;\nimport net.minecraftforge.fml.loading.FMLPaths;\nimport org.geysermc.hydraulic.platform.HydraulicBootstrap;\nimport org.geysermc.hydraulic.platform.mod.ModInfo;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\nimport java.nio.file.Path;\nimport java.util.Set;\nimport java.util.stream.Collectors;", "score": 0.8333972692489624 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/platform/HydraulicBootstrap.java", "retrieved_chunk": "package org.geysermc.hydraulic.platform;\nimport org.geysermc.hydraulic.platform.mod.ModInfo;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\nimport java.nio.file.Path;\nimport java.util.Set;\n/**\n * Represents the bootstrap of a platform.\n */\npublic interface HydraulicBootstrap {", "score": 0.8253013491630554 } ]
java
this.bootstrap.mods();
package com.phonenumberinput; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Color; import android.os.Build; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.recyclerview.selection.SelectionTracker; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.util.List; public class CountryPickerAdapter extends RecyclerView.Adapter<CountryPickerListItem> { private List<Country> countries; private final LayoutInflater inflater; private boolean darkMode; private SelectionTracker<String> selectionTracker; private int defaultCountry; private final LinearLayoutManager layoutManager; public CountryPickerAdapter(Context context, List<Country> countries, LinearLayoutManager layoutManager) { this.countries = countries; this.inflater = LayoutInflater.from(context); this.layoutManager = layoutManager; } public void onCountryClick(int index) { setSelectedIndex(index); notifyItemChanged(index); } public void setSelectionTracker(SelectionTracker<String> selectionTracker) { this.selectionTracker = selectionTracker; if (defaultCountry >= 0 && defaultCountry < countries.size()) { String countryCode = countries.get(defaultCountry).getCode(); selectionTracker.select(countryCode); } else { selectionTracker.clearSelection(); } } public void setCountries(List<Country> countries) { this.countries = countries; if (selectionTracker == null) { return; } if (defaultCountry >= 0 && defaultCountry < countries.size()) { String countryCode = countries.get(defaultCountry).getCode(); selectionTracker.select(countryCode); } else { selectionTracker.clearSelection(); } } @SuppressLint("NotifyDataSetChanged") public void setDarkMode(boolean darkMode) { this.darkMode = darkMode; notifyDataSetChanged(); } @RequiresApi(api = Build.VERSION_CODES.N) @NonNull @Override public CountryPickerListItem onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = inflater.inflate(R.layout.country_picker_list_item, parent, false); return new CountryPickerListItem(view, this::onCountryClick); } @Override public void onBindViewHolder(@NonNull CountryPickerListItem holder, int position) { Country country = countries.get(position); // Set the country flag, country name, and calling code for the current list item holder.countryName.
setText(String.format("%s %s", country.getEmoji(), country.getName()));
holder.callingCode.setText(country.getCallingCode()); int textColor = darkMode ? Color.parseColor("#FFFFFF") : Color.parseColor("#000000"); holder.countryName.setTextColor(textColor); holder.callingCode.setTextColor(textColor); holder.bind(country); boolean isSelected = selectionTracker.isSelected(country.getCode()); holder.itemView.setActivated(isSelected); holder.highlight(isSelected, darkMode); } @Override public int getItemCount() { return countries.size(); } public void setSelectedIndex(int selectedIndex) { defaultCountry = selectedIndex; if (selectionTracker == null) { return; } if (selectedIndex >= 0 && selectedIndex < countries.size()) { String countryCode = countries.get(selectedIndex).getCode(); selectionTracker.select(countryCode); layoutManager.scrollToPosition(selectedIndex); } else { selectionTracker.clearSelection(); } } }
android/src/main/java/com/phonenumberinput/CountryPickerAdapter.java
gtomitsuka-rn-phone-number-input-2f2e43b
[ { "filename": "android/src/main/java/com/phonenumberinput/CountryPickerListItem.java", "retrieved_chunk": "import java.util.function.Consumer;\npublic class CountryPickerListItem extends RecyclerView.ViewHolder {\n TextView countryName; // includes emoji\n TextView callingCode;\n Country country;\n @RequiresApi(api = Build.VERSION_CODES.N)\n public CountryPickerListItem(@NonNull View itemView, Consumer<Integer> countryClickListener) {\n super(itemView);\n countryName = itemView.findViewById(R.id.country_name);\n callingCode = itemView.findViewById(R.id.calling_code);", "score": 0.9144564867019653 }, { "filename": "android/src/main/java/com/phonenumberinput/CountryPickerListItem.java", "retrieved_chunk": " itemView.setOnClickListener(l -> {\n System.out.println(\"called\");\n int position = getBindingAdapterPosition();\n if (position != RecyclerView.NO_POSITION) {\n countryClickListener.accept(position);\n }\n });\n }\n public void bind(Country country) {\n this.country = country;", "score": 0.8813213109970093 }, { "filename": "android/src/main/java/com/phonenumberinput/CountryDetailsLookup.java", "retrieved_chunk": " return ((CountryPickerListItem) viewHolder).getItemDetails();\n }\n }\n return null;\n }\n}", "score": 0.8773209452629089 }, { "filename": "android/src/main/java/com/phonenumberinput/PhoneNumberInputViewManager.java", "retrieved_chunk": " if (adapter != null) {\n adapter.setCountries(countries);\n } else {\n LinearLayoutManager layoutManager = new LinearLayoutManager(view.getContext(), LinearLayoutManager.VERTICAL, false);\n view.setLayoutManager(layoutManager);\n LinearSnapHelper snapHelper = new LinearSnapHelper();\n snapHelper.attachToRecyclerView(view);\n adapter = new CountryPickerAdapter(view.getContext(), countries, layoutManager);\n view.setAdapter(adapter);\n }", "score": 0.8690891265869141 }, { "filename": "android/src/main/java/com/phonenumberinput/PhoneNumberInputViewManager.java", "retrieved_chunk": " // Set up the SelectionTracker\n SelectionTracker<String> selectionTracker = new SelectionTracker.Builder<>(\n \"countryPickerSelection\",\n view,\n new CountryKeyProvider(1, countries),\n new CountryDetailsLookup(view),\n StorageStrategy.createStringStorage())\n .withSelectionPredicate(SelectionPredicates.createSelectSingleAnything())\n .build();\n adapter.setSelectionTracker(selectionTracker);", "score": 0.868151068687439 } ]
java
setText(String.format("%s %s", country.getEmoji(), country.getName()));
package com.phonenumberinput; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Color; import android.os.Build; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.recyclerview.selection.SelectionTracker; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.util.List; public class CountryPickerAdapter extends RecyclerView.Adapter<CountryPickerListItem> { private List<Country> countries; private final LayoutInflater inflater; private boolean darkMode; private SelectionTracker<String> selectionTracker; private int defaultCountry; private final LinearLayoutManager layoutManager; public CountryPickerAdapter(Context context, List<Country> countries, LinearLayoutManager layoutManager) { this.countries = countries; this.inflater = LayoutInflater.from(context); this.layoutManager = layoutManager; } public void onCountryClick(int index) { setSelectedIndex(index); notifyItemChanged(index); } public void setSelectionTracker(SelectionTracker<String> selectionTracker) { this.selectionTracker = selectionTracker; if (defaultCountry >= 0 && defaultCountry < countries.size()) { String countryCode = countries.get(defaultCountry).getCode(); selectionTracker.select(countryCode); } else { selectionTracker.clearSelection(); } } public void setCountries(List<Country> countries) { this.countries = countries; if (selectionTracker == null) { return; } if (defaultCountry >= 0 && defaultCountry < countries.size()) { String countryCode = countries.get(defaultCountry).getCode(); selectionTracker.select(countryCode); } else { selectionTracker.clearSelection(); } } @SuppressLint("NotifyDataSetChanged") public void setDarkMode(boolean darkMode) { this.darkMode = darkMode; notifyDataSetChanged(); } @RequiresApi(api = Build.VERSION_CODES.N) @NonNull @Override public CountryPickerListItem onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = inflater.inflate(R.layout.country_picker_list_item, parent, false); return new CountryPickerListItem(view, this::onCountryClick); } @Override public void onBindViewHolder(@NonNull CountryPickerListItem holder, int position) { Country country = countries.get(position); // Set the country flag, country name, and calling code for the current list item holder.countryName.setText(String.format("%s %s", country.getEmoji(), country.getName())); holder.callingCode.setText
(country.getCallingCode());
int textColor = darkMode ? Color.parseColor("#FFFFFF") : Color.parseColor("#000000"); holder.countryName.setTextColor(textColor); holder.callingCode.setTextColor(textColor); holder.bind(country); boolean isSelected = selectionTracker.isSelected(country.getCode()); holder.itemView.setActivated(isSelected); holder.highlight(isSelected, darkMode); } @Override public int getItemCount() { return countries.size(); } public void setSelectedIndex(int selectedIndex) { defaultCountry = selectedIndex; if (selectionTracker == null) { return; } if (selectedIndex >= 0 && selectedIndex < countries.size()) { String countryCode = countries.get(selectedIndex).getCode(); selectionTracker.select(countryCode); layoutManager.scrollToPosition(selectedIndex); } else { selectionTracker.clearSelection(); } } }
android/src/main/java/com/phonenumberinput/CountryPickerAdapter.java
gtomitsuka-rn-phone-number-input-2f2e43b
[ { "filename": "android/src/main/java/com/phonenumberinput/CountryPickerListItem.java", "retrieved_chunk": "import java.util.function.Consumer;\npublic class CountryPickerListItem extends RecyclerView.ViewHolder {\n TextView countryName; // includes emoji\n TextView callingCode;\n Country country;\n @RequiresApi(api = Build.VERSION_CODES.N)\n public CountryPickerListItem(@NonNull View itemView, Consumer<Integer> countryClickListener) {\n super(itemView);\n countryName = itemView.findViewById(R.id.country_name);\n callingCode = itemView.findViewById(R.id.calling_code);", "score": 0.9218277931213379 }, { "filename": "android/src/main/java/com/phonenumberinput/CountryPickerListItem.java", "retrieved_chunk": " itemView.setOnClickListener(l -> {\n System.out.println(\"called\");\n int position = getBindingAdapterPosition();\n if (position != RecyclerView.NO_POSITION) {\n countryClickListener.accept(position);\n }\n });\n }\n public void bind(Country country) {\n this.country = country;", "score": 0.8874097466468811 }, { "filename": "android/src/main/java/com/phonenumberinput/CountryDetailsLookup.java", "retrieved_chunk": " return ((CountryPickerListItem) viewHolder).getItemDetails();\n }\n }\n return null;\n }\n}", "score": 0.877011775970459 }, { "filename": "android/src/main/java/com/phonenumberinput/PhoneNumberInputViewManager.java", "retrieved_chunk": " ReadableMap map = a.getMap(i);\n String countryName = map.getString(\"name\");\n String countryEmoji = map.getString(\"emoji\");\n String countryCode = map.getString(\"code\");\n String callingCode = map.getString(\"tel\");\n Country country = new Country(countryName, countryCode, countryEmoji, callingCode);\n countries.add(country);\n }\n }\n CountryPickerAdapter adapter = (CountryPickerAdapter) view.getAdapter();", "score": 0.8731307983398438 }, { "filename": "android/src/main/java/com/phonenumberinput/PhoneNumberInputViewManager.java", "retrieved_chunk": " CountryPickerAdapter adapter = new CountryPickerAdapter(view.getContext(), new ArrayList<>(), layoutManager);\n view.setAdapter(adapter);\n return view;\n }\n @Override\n @ReactProp(name = \"items\")\n public void setItems(PhoneNumberInputView view, @Nullable ReadableArray a) {\n List<Country> countries = new ArrayList<>();\n if (a != null) {\n for (int i = 0; i < a.size(); i++) {", "score": 0.8667756915092468 } ]
java
(country.getCallingCode());
package com.phonenumberinput; import android.graphics.Color; import android.os.Build; import android.view.View; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.recyclerview.selection.ItemDetailsLookup; import androidx.recyclerview.widget.RecyclerView; import java.util.function.Consumer; public class CountryPickerListItem extends RecyclerView.ViewHolder { TextView countryName; // includes emoji TextView callingCode; Country country; @RequiresApi(api = Build.VERSION_CODES.N) public CountryPickerListItem(@NonNull View itemView, Consumer<Integer> countryClickListener) { super(itemView); countryName = itemView.findViewById(R.id.country_name); callingCode = itemView.findViewById(R.id.calling_code); itemView.setOnClickListener(l -> { System.out.println("called"); int position = getBindingAdapterPosition(); if (position != RecyclerView.NO_POSITION) { countryClickListener.accept(position); } }); } public void bind(Country country) { this.country = country; // Bind the country data to your views // ... } public void highlight(boolean isSelected, boolean darkMode) { if (isSelected) { int color = darkMode ? Color.parseColor("#7a7a7a") : Color.parseColor("#d9d9d9"); itemView.setBackgroundColor(color); } else { itemView.setBackgroundColor(Color.TRANSPARENT); } } public ItemDetailsLookup.ItemDetails<String> getItemDetails() { return new ItemDetailsLookup.ItemDetails<String>() { @Override public int getPosition() { return getBindingAdapterPosition(); } @Nullable @Override public String getSelectionKey() { return
country.getCode();
} }; } }
android/src/main/java/com/phonenumberinput/CountryPickerListItem.java
gtomitsuka-rn-phone-number-input-2f2e43b
[ { "filename": "android/src/main/java/com/phonenumberinput/CountryDetailsLookup.java", "retrieved_chunk": " return ((CountryPickerListItem) viewHolder).getItemDetails();\n }\n }\n return null;\n }\n}", "score": 0.8586395978927612 }, { "filename": "android/src/main/java/com/phonenumberinput/CountryDetailsLookup.java", "retrieved_chunk": "package com.phonenumberinput;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.recyclerview.selection.ItemDetailsLookup;\nimport androidx.recyclerview.widget.RecyclerView;\nimport com.phonenumberinput.CountryPickerListItem;\npublic class CountryDetailsLookup extends ItemDetailsLookup<String> {\n private final RecyclerView recyclerView;", "score": 0.8507450222969055 }, { "filename": "android/src/main/java/com/phonenumberinput/CountryDetailsLookup.java", "retrieved_chunk": " public CountryDetailsLookup(RecyclerView recyclerView) {\n this.recyclerView = recyclerView;\n }\n @Nullable\n @Override\n public ItemDetails<String> getItemDetails(@NonNull MotionEvent e) {\n View view = recyclerView.findChildViewUnder(e.getX(), e.getY());\n if (view != null) {\n RecyclerView.ViewHolder viewHolder = recyclerView.getChildViewHolder(view);\n if (viewHolder instanceof CountryPickerListItem) {", "score": 0.8454412817955017 }, { "filename": "android/src/main/java/com/phonenumberinput/CountryKeyProvider.java", "retrieved_chunk": "package com.phonenumberinput;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.recyclerview.selection.ItemKeyProvider;\nimport androidx.recyclerview.widget.RecyclerView;\nimport java.util.List;\npublic class CountryKeyProvider extends ItemKeyProvider<String> {\n private final List<Country> countries;\n public CountryKeyProvider(int scope, List<Country> countries) {\n super(scope);", "score": 0.8384261131286621 }, { "filename": "android/src/main/java/com/phonenumberinput/CountryKeyProvider.java", "retrieved_chunk": " this.countries = countries;\n }\n @Nullable\n @Override\n public String getKey(int position) {\n return countries.get(position).getCode();\n }\n @Override\n public int getPosition(@NonNull String key) {\n for (int i = 0; i < countries.size(); i++) {", "score": 0.8368000388145447 } ]
java
country.getCode();
/* * Copyright (C) 2015 The Android Open Source Project * * 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.android.traceur; import android.annotation.Nullable; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.icu.text.MessageFormat; import android.net.Uri; import android.os.Bundle; import androidx.preference.MultiSelectListPreference; import androidx.preference.ListPreference; import androidx.preference.Preference; import androidx.preference.PreferenceFragment; import androidx.preference.PreferenceManager; import androidx.preference.SwitchPreference; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Menu; import android.view.MenuInflater; import android.widget.Toast; import com.android.settingslib.HelpUtils; import java.util.ArrayList; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; public class MainFragment extends PreferenceFragment { static final String TAG = TraceUtils.TAG; public static final String ACTION_REFRESH_TAGS = "com.android.traceur.REFRESH_TAGS"; private static final String BETTERBUG_PACKAGE_NAME = "com.google.android.apps.internal.betterbug"; private static final String ROOT_MIME_TYPE = "vnd.android.document/root"; private static final String STORAGE_URI = "content://com.android.traceur.documents/root"; private SwitchPreference mTracingOn; private AlertDialog mAlertDialog; private SharedPreferences mPrefs; private MultiSelectListPreference mTags; private boolean mRefreshing; private BroadcastReceiver mRefreshReceiver; OnSharedPreferenceChangeListener mSharedPreferenceChangeListener = new OnSharedPreferenceChangeListener () { public void onSharedPreferenceChanged( SharedPreferences sharedPreferences, String key) { refreshUi(); } }; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Receiver.updateDeveloperOptionsWatcher(getContext()); mPrefs = PreferenceManager.getDefaultSharedPreferences( getActivity().getApplicationContext()); mTracingOn = (SwitchPreference) findPreference(getActivity().getString(R.string.pref_key_tracing_on)); mTracingOn.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { Receiver.updateTracing(getContext()); return true; } }); mTags = (MultiSelectListPreference) findPreference(getContext().getString(R.string.pref_key_tags)); mTags.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { if (mRefreshing) { return true; } Set<String> set = (Set<String>) newValue; TreeMap<String
, String> available = TraceUtils.listCategories();
ArrayList<String> clean = new ArrayList<>(set.size()); for (String s : set) { if (available.containsKey(s)) { clean.add(s); } } set.clear(); set.addAll(clean); return true; } }); findPreference("restore_default_tags").setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { refreshUi(/* restoreDefaultTags =*/ true); Toast.makeText(getContext(), getContext().getString(R.string.default_categories_restored), Toast.LENGTH_SHORT).show(); return true; } }); findPreference(getString(R.string.pref_key_quick_setting)) .setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { Receiver.updateQuickSettings(getContext()); return true; } }); findPreference("clear_saved_traces").setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { new AlertDialog.Builder(getContext()) .setTitle(R.string.clear_saved_traces_question) .setMessage(R.string.all_traces_will_be_deleted) .setPositiveButton(R.string.clear, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { TraceUtils.clearSavedTraces(); } }) .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create() .show(); return true; } }); findPreference("trace_link_button") .setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { Intent intent = buildTraceFileViewIntent(); try { startActivity(intent); } catch (ActivityNotFoundException e) { return false; } return true; } }); // This disables "Attach to bugreports" when long traces are enabled. This cannot be done in // main.xml because there are some other settings there that are enabled with long traces. SwitchPreference attachToBugreport = findPreference( getString(R.string.pref_key_attach_to_bugreport)); findPreference(getString(R.string.pref_key_long_traces)) .setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { if (((SwitchPreference) preference).isChecked()) { attachToBugreport.setEnabled(false); } else { attachToBugreport.setEnabled(true); } return true; } }); refreshUi(); mRefreshReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { refreshUi(); } }; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { setHasOptionsMenu(true); return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onStart() { super.onStart(); getPreferenceScreen().getSharedPreferences() .registerOnSharedPreferenceChangeListener(mSharedPreferenceChangeListener); getActivity().registerReceiver(mRefreshReceiver, new IntentFilter(ACTION_REFRESH_TAGS)); Receiver.updateTracing(getContext()); } @Override public void onStop() { getPreferenceScreen().getSharedPreferences() .unregisterOnSharedPreferenceChangeListener(mSharedPreferenceChangeListener); getActivity().unregisterReceiver(mRefreshReceiver); if (mAlertDialog != null) { mAlertDialog.cancel(); mAlertDialog = null; } super.onStop(); } @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { addPreferencesFromResource(R.xml.main); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { HelpUtils.prepareHelpMenuItem(getActivity(), menu, R.string.help_url, this.getClass().getName()); } private Intent buildTraceFileViewIntent() { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse(STORAGE_URI), ROOT_MIME_TYPE); return intent; } private void refreshUi() { refreshUi(/* restoreDefaultTags =*/ false); } /* * Refresh the preferences UI to make sure it reflects the current state of the preferences and * system. */ private void refreshUi(boolean restoreDefaultTags) { Context context = getContext(); // Make sure the Record Trace toggle matches the preference value. mTracingOn.setChecked(mTracingOn.getPreferenceManager().getSharedPreferences().getBoolean( mTracingOn.getKey(), false)); SwitchPreference stopOnReport = (SwitchPreference) findPreference(getString(R.string.pref_key_stop_on_bugreport)); stopOnReport.setChecked(mPrefs.getBoolean(stopOnReport.getKey(), false)); // Update category list to match the categories available on the system. Set<Entry<String, String>> availableTags = TraceUtils.listCategories().entrySet(); ArrayList<String> entries = new ArrayList<String>(availableTags.size()); ArrayList<String> values = new ArrayList<String>(availableTags.size()); for (Entry<String, String> entry : availableTags) { entries.add(entry.getKey() + ": " + entry.getValue()); values.add(entry.getKey()); } mRefreshing = true; try { mTags.setEntries(entries.toArray(new String[0])); mTags.setEntryValues(values.toArray(new String[0])); if (restoreDefaultTags || !mPrefs.contains(context.getString(R.string.pref_key_tags))) { mTags.setValues(Receiver.getDefaultTagList()); } } finally { mRefreshing = false; } // Update subtitles on this screen. Set<String> categories = mTags.getValues(); MessageFormat msgFormat = new MessageFormat( getResources().getString(R.string.num_categories_selected), Locale.getDefault()); Map<String, Object> arguments = new HashMap<>(); arguments.put("count", categories.size()); mTags.setSummary(Receiver.getDefaultTagList().equals(categories) ? context.getString(R.string.default_categories) : msgFormat.format(arguments)); ListPreference bufferSize = (ListPreference)findPreference( context.getString(R.string.pref_key_buffer_size)); bufferSize.setSummary(bufferSize.getEntry()); // If we are not using the Perfetto trace backend, // hide the unsupported preferences. if (TraceUtils.currentTraceEngine().equals(PerfettoUtils.NAME)) { ListPreference maxLongTraceSize = (ListPreference)findPreference( context.getString(R.string.pref_key_max_long_trace_size)); maxLongTraceSize.setSummary(maxLongTraceSize.getEntry()); ListPreference maxLongTraceDuration = (ListPreference)findPreference( context.getString(R.string.pref_key_max_long_trace_duration)); maxLongTraceDuration.setSummary(maxLongTraceDuration.getEntry()); } else { Preference longTraceCategory = findPreference("long_trace_category"); if (longTraceCategory != null) { getPreferenceScreen().removePreference(longTraceCategory); } } // Check if BetterBug is installed to see if Traceur should display either the toggle for // 'attach_to_bugreport' or 'stop_on_bugreport'. try { context.getPackageManager().getPackageInfo(BETTERBUG_PACKAGE_NAME, PackageManager.MATCH_SYSTEM_ONLY); findPreference(getString(R.string.pref_key_attach_to_bugreport)).setVisible(true); findPreference(getString(R.string.pref_key_stop_on_bugreport)).setVisible(false); // Changes the long traces summary to add that they cannot be attached to bugreports. findPreference(getString(R.string.pref_key_long_traces)) .setSummary(getString(R.string.long_traces_summary_betterbug)); } catch (PackageManager.NameNotFoundException e) { // attach_to_bugreport must be disabled here because it's true by default. mPrefs.edit().putBoolean( getString(R.string.pref_key_attach_to_bugreport), false).commit(); findPreference(getString(R.string.pref_key_attach_to_bugreport)).setVisible(false); findPreference(getString(R.string.pref_key_stop_on_bugreport)).setVisible(true); // Sets long traces summary to the default in case Betterbug was removed. findPreference(getString(R.string.pref_key_long_traces)) .setSummary(getString(R.string.long_traces_summary)); } // Check if an activity exists to handle the trace_link_button intent. If not, hide the UI // element PackageManager packageManager = context.getPackageManager(); Intent intent = buildTraceFileViewIntent(); if (intent.resolveActivity(packageManager) == null) { findPreference("trace_link_button").setVisible(false); } } }
src/com/android/traceur/MainFragment.java
GrapheneOS-Archive-platform_packages_apps_Traceur-2e6c52a
[ { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " Set<String> activeTags = getActiveTags(context, prefs, false);\n if (!activeAvailableTags.equals(activeTags)) {\n postCategoryNotification(context, prefs);\n }\n int bufferSize = Integer.parseInt(\n prefs.getString(context.getString(R.string.pref_key_buffer_size),\n context.getString(R.string.default_buffer_size)));\n boolean appTracing = prefs.getBoolean(context.getString(R.string.pref_key_apps), true);\n boolean longTrace = prefs.getBoolean(context.getString(R.string.pref_key_long_traces), true);\n int maxLongTraceSize = Integer.parseInt(", "score": 0.8702488541603088 }, { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " notificationManager.createNotificationChannel(saveTraceChannel);\n }\n public static Set<String> getActiveTags(Context context, SharedPreferences prefs, boolean onlyAvailable) {\n Set<String> tags = prefs.getStringSet(context.getString(R.string.pref_key_tags),\n getDefaultTagList());\n Set<String> available = TraceUtils.listCategories().keySet();\n if (onlyAvailable) {\n tags.retainAll(available);\n }\n Log.v(TAG, \"getActiveTags(onlyAvailable=\" + onlyAvailable + \") = \\\"\" + tags.toString() + \"\\\"\");", "score": 0.8636729717254639 }, { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " return tags;\n }\n public static Set<String> getActiveUnavailableTags(Context context, SharedPreferences prefs) {\n Set<String> tags = prefs.getStringSet(context.getString(R.string.pref_key_tags),\n getDefaultTagList());\n Set<String> available = TraceUtils.listCategories().keySet();\n tags.removeAll(available);\n Log.v(TAG, \"getActiveUnavailableTags() = \\\"\" + tags.toString() + \"\\\"\");\n return tags;\n }", "score": 0.8613349199295044 }, { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " }\n public static void updateTracing(Context context, boolean assumeTracingIsOff) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n boolean prefsTracingOn =\n prefs.getBoolean(context.getString(R.string.pref_key_tracing_on), false);\n boolean traceUtilsTracingOn = assumeTracingIsOff ? false : TraceUtils.isTracingOn();\n if (prefsTracingOn != traceUtilsTracingOn) {\n if (prefsTracingOn) {\n // Show notification if the tags in preferences are not all actually available.\n Set<String> activeAvailableTags = getActiveTags(context, prefs, true);", "score": 0.8556499481201172 }, { "filename": "src/com/android/traceur/QsService.java", "retrieved_chunk": " SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);\n boolean tracingOn = prefs.getBoolean(getString(R.string.pref_key_tracing_on), false);\n String titleString = getString(tracingOn ? R.string.stop_tracing: R.string.record_trace);\n getQsTile().setIcon(Icon.createWithResource(this, R.drawable.bugfood_icon));\n getQsTile().setState(tracingOn ? Tile.STATE_ACTIVE : Tile.STATE_INACTIVE);\n getQsTile().setLabel(titleString);\n getQsTile().updateTile();\n Receiver.updateDeveloperOptionsWatcher(this);\n }\n /** When we click the tile, toggle tracing state.", "score": 0.8189759850502014 } ]
java
, String> available = TraceUtils.listCategories();
/* * Copyright (C) 2015 The Android Open Source Project * * 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.android.traceur; import android.system.Os; import android.util.Log; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Collection; import java.util.List; import java.util.TreeMap; import java.util.concurrent.TimeUnit; import perfetto.protos.DataSourceDescriptorOuterClass.DataSourceDescriptor; import perfetto.protos.FtraceDescriptorOuterClass.FtraceDescriptor.AtraceCategory; import perfetto.protos.TracingServiceStateOuterClass.TracingServiceState; import perfetto.protos.TracingServiceStateOuterClass.TracingServiceState.DataSource; /** * Utility functions for calling Perfetto */ public class PerfettoUtils implements TraceUtils.TraceEngine { static final String TAG = "Traceur"; public static final String NAME = "PERFETTO"; private static final String OUTPUT_EXTENSION = "perfetto-trace"; private static final String TEMP_DIR= "/data/local/traces/"; private static final String TEMP_TRACE_LOCATION = "/data/local/traces/.trace-in-progress.trace"; private static final String PERFETTO_TAG = "traceur"; private static final String MARKER = "PERFETTO_ARGUMENTS"; private static final int LIST_TIMEOUT_MS = 10000; private static final int STARTUP_TIMEOUT_MS = 10000; private static final int STOP_TIMEOUT_MS = 30000; private static final long MEGABYTES_TO_BYTES = 1024L * 1024L; private static final long MINUTES_TO_MILLISECONDS = 60L * 1000L; private static final String CAMERA_TAG = "camera"; private static final String GFX_TAG = "gfx"; private static final String MEMORY_TAG = "memory"; private static final String POWER_TAG = "power"; private static final String SCHED_TAG = "sched"; private static final String WEBVIEW_TAG = "webview"; public String getName() { return NAME; } public String getOutputExtension() { return OUTPUT_EXTENSION; } public boolean traceStart(Collection<String> tags, int bufferSizeKb, boolean apps, boolean attachToBugreport, boolean longTrace, int maxLongTraceSizeMb, int maxLongTraceDurationMinutes) { if (isTracingOn()) { Log.e(TAG, "Attempting to start perfetto trace but trace is already in progress"); return false; } else { // Ensure the temporary trace file is cleared. try { Files.deleteIfExists(Paths.get(TEMP_TRACE_LOCATION)); } catch (Exception e) { throw new RuntimeException(e); } } // The user chooses a per-CPU buffer size due to atrace limitations. // So we use this to ensure that we reserve the correctly-sized buffer. int numCpus = Runtime.getRuntime().availableProcessors(); // Build the perfetto config that will be passed on the command line. StringBuilder config = new StringBuilder() .append("write_into_file: true\n") // Ensure that we flush ftrace data every 30s even if cpus are idle. .append("flush_period_ms: 30000\n"); // If the user has flagged that in-progress trace sessions should be grabbed // during bugreports, and BetterBug is present. if (attachToBugreport) { config.append("bugreport_score: 500\n"); } // Indicates that perfetto should notify Traceur if the tracing session's status // changes. config.append("notify_traceur: true\n"); if (longTrace) { if (maxLongTraceSizeMb != 0) { config.append("max_file_size_bytes: " + (maxLongTraceSizeMb * MEGABYTES_TO_BYTES) + "\n"); } if (maxLongTraceDurationMinutes != 0) { config.append("duration_ms: " + (maxLongTraceDurationMinutes * MINUTES_TO_MILLISECONDS) + "\n"); } // Default value for long traces to write to file. config.append("file_write_period_ms: 1000\n"); } else { // For short traces, we don't write to the file. // So, always use the maximum value here: 7 days. config.append("file_write_period_ms: 604800000\n"); } config.append("incremental_state_config {\n") .append(" clear_period_ms: 15000\n") .append("} \n") // This is target_buffer: 0, which is used for ftrace and the ftrace-derived // android.gpu.memory. .append("buffers {\n") .append(" size_kb: " + bufferSizeKb * numCpus + "\n") .append(" fill_policy: RING_BUFFER\n") .append("} \n") // This is target_buffer: 1, which is used for additional data sources. .append("buffers {\n") .append(" size_kb: 2048\n") .append(" fill_policy: RING_BUFFER\n") .append("} \n") .append("data_sources {\n") .append(" config {\n") .append(" name: \"linux.ftrace\"\n") .append(" target_buffer: 0\n") .append(" ftrace_config {\n") .append(" symbolize_ksyms: true\n"); for (String tag : tags) { // Tags are expected to be only letters, numbers, and underscores. String cleanTag = tag.replaceAll("[^a-zA-Z0-9_]", ""); if (!cleanTag.equals(tag)) { Log.w(TAG, "Attempting to use an invalid tag: " + tag); } config.append(" atrace_categories: \"" + cleanTag + "\"\n"); } if (apps) { config.append(" atrace_apps: \"*\"\n"); } // Request a dense encoding of the common sched events (sched_switch, sched_waking). if (tags.contains(SCHED_TAG)) { config.append(" compact_sched {\n"); config.append(" enabled: true\n"); config.append(" }\n"); } // These parameters affect only the kernel trace buffer size and how // frequently it gets moved into the userspace buffer defined above. config.append(" buffer_size_kb: 8192\n") .append(" drain_period_ms: 1000\n") .append(" }\n") .append(" }\n") .append("}\n") .append(" \n"); // Captures initial counter values, updates are captured in ftrace. if (tags.contains(MEMORY_TAG) || tags.contains(GFX_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.gpu.memory\"\n") .append(" target_buffer: 0\n") .append(" }\n") .append("}\n"); } // For process association. If the memory tag is enabled, // poll periodically instead of just once at the beginning. config.append("data_sources {\n") .append(" config {\n") .append(" name: \"linux.process_stats\"\n") .append(" target_buffer: 1\n"); if (tags.contains(MEMORY_TAG)) { config.append(" process_stats_config {\n") .append(" proc_stats_poll_ms: 60000\n") .append(" }\n"); } config.append(" }\n") .append("} \n"); if (tags.contains(POWER_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.power\"\n") .append(" target_buffer: 1\n") .append(" android_power_config {\n"); if (longTrace) { config.append(" battery_poll_ms: 5000\n"); } else { config.append(" battery_poll_ms: 1000\n"); } config.append(" collect_power_rails: true\n") .append(" battery_counters: BATTERY_COUNTER_CAPACITY_PERCENT\n") .append(" battery_counters: BATTERY_COUNTER_CHARGE\n") .append(" battery_counters: BATTERY_COUNTER_CURRENT\n") .append(" }\n") .append(" }\n") .append("}\n"); } if (tags.contains(MEMORY_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.sys_stats\"\n") .append(" target_buffer: 1\n") .append(" sys_stats_config {\n") .append(" vmstat_period_ms: 1000\n") .append(" }\n") .append(" }\n") .append("}\n"); } if (tags.contains(GFX_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.surfaceflinger.frametimeline\"\n") .append(" }\n") .append("}\n"); } if (tags.contains(CAMERA_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.hardware.camera\"\n") .append(" target_buffer: 1\n") .append(" }\n") .append("}\n"); } // Also enable Chrome events when the WebView tag is enabled. if (tags.contains(WEBVIEW_TAG)) { String chromeTraceConfig = "{" + "\\\"record_mode\\\":\\\"record-continuously\\\"," + "\\\"included_categories\\\":[\\\"*\\\"]" + "}"; config.append("data_sources: {\n") .append(" config {\n") .append(" name: \"org.chromium.trace_event\"\n") .append(" chrome_config {\n") .append(" trace_config: \"" + chromeTraceConfig + "\"\n") .append(" }\n") .append(" }\n") .append("}\n") .append("data_sources: {\n") .append(" config {\n") .append(" name: \"org.chromium.trace_metadata\"\n") .append(" chrome_config {\n") .append(" trace_config: \"" + chromeTraceConfig + "\"\n") .append(" }\n") .append(" }\n") .append("}\n"); } String configString = config.toString(); // If the here-doc ends early, within the config string, exit immediately. // This should never happen. if (configString.contains(MARKER)) { throw new RuntimeException("The arguments to the Perfetto command are malformed."); } String cmd = "perfetto --detach=" + PERFETTO_TAG + " -o " + TEMP_TRACE_LOCATION + " -c - --txt" + " <<" + MARKER +"\n" + configString + "\n" + MARKER; Log.v(TAG, "Starting perfetto trace."); try { Process process = TraceUtils.execWithTimeout(cmd, TEMP_DIR, STARTUP_TIMEOUT_MS); if (process == null) { return false; } else if (process.exitValue() != 0) { Log.e(TAG, "perfetto traceStart failed with: " + process.exitValue()); return false; } } catch (Exception e) { throw new RuntimeException(e); } Log.v(TAG, "perfetto traceStart succeeded!"); return true; } public void traceStop() { Log.v(TAG, "Stopping perfetto trace."); if (!isTracingOn()) { Log.w(TAG, "No trace appears to be in progress. Stopping perfetto trace may not work."); } String cmd = "perfetto --stop --attach=" + PERFETTO_TAG; try { Process process = TraceUtils.execWithTimeout(cmd, null, STOP_TIMEOUT_MS); if (process != null && process.exitValue() != 0) { Log.e(TAG, "perfetto traceStop failed with: " + process.exitValue()); } } catch (Exception e) { throw new RuntimeException(e); } } public boolean traceDump(File outFile) { traceStop(); // Short-circuit if a trace was not stopped. if (isTracingOn()) { Log.e(TAG, "Trace was not stopped successfully, aborting trace dump."); return false; } // Short-circuit if the file we're trying to dump to doesn't exist. if (!Files.exists(Paths.get(TEMP_TRACE_LOCATION))) { Log.e(TAG, "In-progress trace file doesn't exist, aborting trace dump."); return false; } Log.v(TAG, "Saving perfetto trace to " + outFile); try { Os.rename(TEMP_TRACE_LOCATION, outFile.getCanonicalPath()); } catch (Exception e) { throw new RuntimeException(e); } outFile.setReadable(true, false); // (readable, ownerOnly) outFile.setWritable(true, false); // (readable, ownerOnly) return true; } public boolean isTracingOn() { String cmd = "perfetto --is_detached=" + PERFETTO_TAG; try { Process process = TraceUtils.exec(cmd); // 0 represents a detached process exists with this name // 2 represents no detached process with this name // 1 (or other error code) represents an error int result = process.waitFor(); if (result == 0) { return true; } else if (result == 2) { return false; } else { throw new RuntimeException("Perfetto error: " + result); } } catch (Exception e) { throw new RuntimeException(e); } } public static TreeMap<String,String> perfettoListCategories() { String cmd = "perfetto --query-raw"; Log.v(TAG, "Listing tags: " + cmd); try { TreeMap<String, String> result = new TreeMap<>(); // execWithTimeout() cannot be used because stdout must be consumed before the process // is terminated.
Process perfetto = TraceUtils.exec(cmd, null, false);
TracingServiceState serviceState = TracingServiceState.parseFrom(perfetto.getInputStream()); // Destroy the perfetto process if it times out. if (!perfetto.waitFor(LIST_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { Log.e(TAG, "perfettoListCategories timed out after " + LIST_TIMEOUT_MS + " ms."); perfetto.destroyForcibly(); return result; } // The perfetto process completed and failed, but does not need to be destroyed. if (perfetto.exitValue() != 0) { Log.e(TAG, "perfettoListCategories failed with: " + perfetto.exitValue()); } List<AtraceCategory> categories = null; for (DataSource dataSource : serviceState.getDataSourcesList()) { DataSourceDescriptor dataSrcDescriptor = dataSource.getDsDescriptor(); if (dataSrcDescriptor.getName().equals("linux.ftrace")){ categories = dataSrcDescriptor.getFtraceDescriptor().getAtraceCategoriesList(); break; } } if (categories != null) { for (AtraceCategory category : categories) { result.put(category.getName(), category.getDescription()); } } return result; } catch (Exception e) { throw new RuntimeException(e); } } }
src/com/android/traceur/PerfettoUtils.java
GrapheneOS-Archive-platform_packages_apps_Traceur-2e6c52a
[ { "filename": "src/com/android/traceur/TraceUtils.java", "retrieved_chunk": " public static boolean isTracingOn() {\n return mTraceEngine.isTracingOn();\n }\n public static TreeMap<String, String> listCategories() {\n return PerfettoUtils.perfettoListCategories();\n }\n public static void clearSavedTraces() {\n String cmd = \"rm -f \" + TRACE_DIRECTORY + \"trace-*.*trace\";\n Log.v(TAG, \"Clearing trace directory: \" + cmd);\n try {", "score": 0.8489830493927002 }, { "filename": "src/com/android/traceur/MainFragment.java", "retrieved_chunk": " // Update category list to match the categories available on the system.\n Set<Entry<String, String>> availableTags = TraceUtils.listCategories().entrySet();\n ArrayList<String> entries = new ArrayList<String>(availableTags.size());\n ArrayList<String> values = new ArrayList<String>(availableTags.size());\n for (Entry<String, String> entry : availableTags) {\n entries.add(entry.getKey() + \": \" + entry.getValue());\n values.add(entry.getKey());\n }\n mRefreshing = true;\n try {", "score": 0.8252583742141724 }, { "filename": "src/com/android/traceur/TraceUtils.java", "retrieved_chunk": "import java.util.Collection;\nimport java.util.concurrent.TimeUnit;\nimport java.util.TreeMap;\n/**\n * Utility functions for tracing.\n * Will call atrace or perfetto depending on the setting.\n */\npublic class TraceUtils {\n static final String TAG = \"Traceur\";\n public static final String TRACE_DIRECTORY = \"/data/local/traces/\";", "score": 0.8211587071418762 }, { "filename": "src/com/android/traceur/AtraceUtils.java", "retrieved_chunk": " } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n public boolean traceDump(File outFile) {\n String cmd = \"atrace --async_stop -z -c -o \" + outFile;\n Log.v(TAG, \"Dumping async atrace: \" + cmd);\n try {\n Process atrace = TraceUtils.exec(cmd);\n if (atrace.waitFor() != 0) {", "score": 0.8093447685241699 }, { "filename": "src/com/android/traceur/TraceUtils.java", "retrieved_chunk": " // To change Traceur to use atrace to collect traces,\n // change mTraceEngine to point to AtraceUtils().\n private static TraceEngine mTraceEngine = new PerfettoUtils();\n private static final Runtime RUNTIME = Runtime.getRuntime();\n private static final int PROCESS_TIMEOUT_MS = 30000; // 30 seconds\n public interface TraceEngine {\n public String getName();\n public String getOutputExtension();\n public boolean traceStart(Collection<String> tags, int bufferSizeKb, boolean apps,\n boolean attachToBugreport, boolean longTrace, int maxLongTraceSizeMb,", "score": 0.8067517280578613 } ]
java
Process perfetto = TraceUtils.exec(cmd, null, false);
/* * Copyright (C) 2015 The Android Open Source Project * * 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.android.traceur; import android.app.IntentService; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.UserManager; import android.preference.PreferenceManager; import android.provider.Settings; import android.text.format.DateUtils; import android.util.EventLog; import android.util.Log; import java.io.File; import java.util.ArrayList; import java.util.Collection; public class TraceService extends IntentService { /* Indicates Perfetto has stopped tracing due to either the supplied long trace limitations * or limited storage capacity. */ static String INTENT_ACTION_NOTIFY_SESSION_STOPPED = "com.android.traceur.NOTIFY_SESSION_STOPPED"; /* Indicates a Traceur-associated tracing session has been attached to a bug report */ static String INTENT_ACTION_NOTIFY_SESSION_STOLEN = "com.android.traceur.NOTIFY_SESSION_STOLEN"; private static String INTENT_ACTION_STOP_TRACING = "com.android.traceur.STOP_TRACING"; private static String INTENT_ACTION_START_TRACING = "com.android.traceur.START_TRACING"; private static String INTENT_EXTRA_TAGS= "tags"; private static String INTENT_EXTRA_BUFFER = "buffer"; private static String INTENT_EXTRA_APPS = "apps"; private static String INTENT_EXTRA_LONG_TRACE = "long_trace"; private static String INTENT_EXTRA_LONG_TRACE_SIZE = "long_trace_size"; private static String INTENT_EXTRA_LONG_TRACE_DURATION = "long_trace_duration"; private static String BETTERBUG_PACKAGE_NAME = "com.google.android.apps.internal.betterbug"; private static int TRACE_NOTIFICATION = 1; private static int SAVING_TRACE_NOTIFICATION = 2; private static final int MIN_KEEP_COUNT = 3; private static final long MIN_KEEP_AGE = 4 * DateUtils.WEEK_IN_MILLIS; public static void startTracing(final Context context, Collection<String> tags, int bufferSizeKb, boolean apps, boolean longTrace, int maxLongTraceSizeMb, int maxLongTraceDurationMinutes) { Intent intent = new Intent(context, TraceService.class); intent.setAction(INTENT_ACTION_START_TRACING); intent.putExtra(INTENT_EXTRA_TAGS, new ArrayList(tags)); intent.putExtra(INTENT_EXTRA_BUFFER, bufferSizeKb); intent.putExtra(INTENT_EXTRA_APPS, apps); intent.putExtra(INTENT_EXTRA_LONG_TRACE, longTrace); intent.putExtra(INTENT_EXTRA_LONG_TRACE_SIZE, maxLongTraceSizeMb); intent.putExtra(INTENT_EXTRA_LONG_TRACE_DURATION, maxLongTraceDurationMinutes); context.startForegroundService(intent); } public static void stopTracing(final Context context) { Intent intent = new Intent(context, TraceService.class); intent.setAction(INTENT_ACTION_STOP_TRACING); context.startForegroundService(intent); } // Silently stops a trace without saving it. This is intended to be called when tracing is no // longer allowed, i.e. if developer options are turned off while tracing. The usual method of // stopping a trace via intent, stopTracing(), will not work because intents cannot be received // when developer options are disabled. static void stopTracingWithoutSaving(final Context context) { NotificationManager notificationManager = context.getSystemService(NotificationManager.class); notificationManager.cancel(TRACE_NOTIFICATION); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); prefs.edit().putBoolean(context.getString( R.string.pref_key_tracing_on), false).commit();
TraceUtils.traceStop();
} public TraceService() { this("TraceService"); } protected TraceService(String name) { super(name); setIntentRedelivery(true); } @Override public void onHandleIntent(Intent intent) { Context context = getApplicationContext(); // Checks that developer options are enabled and the user is an admin before continuing. boolean developerOptionsEnabled = Settings.Global.getInt(context.getContentResolver(), Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) != 0; if (!developerOptionsEnabled) { // Refer to b/204992293. EventLog.writeEvent(0x534e4554, "204992293", -1, ""); return; } UserManager userManager = context.getSystemService(UserManager.class); boolean isAdminUser = userManager.isAdminUser(); boolean debuggingDisallowed = userManager.hasUserRestriction( UserManager.DISALLOW_DEBUGGING_FEATURES); if (!isAdminUser || debuggingDisallowed) { return; } if (intent.getAction().equals(INTENT_ACTION_START_TRACING)) { startTracingInternal(intent.getStringArrayListExtra(INTENT_EXTRA_TAGS), intent.getIntExtra(INTENT_EXTRA_BUFFER, Integer.parseInt(context.getString(R.string.default_buffer_size))), intent.getBooleanExtra(INTENT_EXTRA_APPS, false), intent.getBooleanExtra(INTENT_EXTRA_LONG_TRACE, false), intent.getIntExtra(INTENT_EXTRA_LONG_TRACE_SIZE, Integer.parseInt(context.getString(R.string.default_long_trace_size))), intent.getIntExtra(INTENT_EXTRA_LONG_TRACE_DURATION, Integer.parseInt(context.getString(R.string.default_long_trace_duration)))); } else if (intent.getAction().equals(INTENT_ACTION_STOP_TRACING)) { stopTracingInternal(TraceUtils.getOutputFilename(), false, false); } else if (intent.getAction().equals(INTENT_ACTION_NOTIFY_SESSION_STOPPED)) { stopTracingInternal(TraceUtils.getOutputFilename(), true, false); } else if (intent.getAction().equals(INTENT_ACTION_NOTIFY_SESSION_STOLEN)) { stopTracingInternal("", false, true); } } private void startTracingInternal(Collection<String> tags, int bufferSizeKb, boolean appTracing, boolean longTrace, int maxLongTraceSizeMb, int maxLongTraceDurationMinutes) { Context context = getApplicationContext(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); Intent stopIntent = new Intent(Receiver.STOP_ACTION, null, context, Receiver.class); stopIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); String title = context.getString(R.string.trace_is_being_recorded); String msg = context.getString(R.string.tap_to_stop_tracing); boolean attachToBugreport = prefs.getBoolean(context.getString(R.string.pref_key_attach_to_bugreport), true); Notification.Builder notification = new Notification.Builder(context, Receiver.NOTIFICATION_CHANNEL_TRACING) .setSmallIcon(R.drawable.bugfood_icon) .setContentTitle(title) .setTicker(title) .setContentText(msg) .setContentIntent( PendingIntent.getBroadcast(context, 0, stopIntent, PendingIntent.FLAG_IMMUTABLE)) .setOngoing(true) .setLocalOnly(true) .setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE) .setColor(getColor( com.android.internal.R.color.system_notification_accent_color)); if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LEANBACK)) { notification.extend(new Notification.TvExtender()); } startForeground(TRACE_NOTIFICATION, notification.build()); if (TraceUtils.traceStart(tags, bufferSizeKb, appTracing, longTrace, attachToBugreport, maxLongTraceSizeMb, maxLongTraceDurationMinutes)) { stopForeground(Service.STOP_FOREGROUND_DETACH); } else { // Starting the trace was unsuccessful, so ensure that tracing // is stopped and the preference is reset. TraceUtils.traceStop(); prefs.edit().putBoolean(context.getString(R.string.pref_key_tracing_on), false).commit(); QsService.updateTile(); stopForeground(Service.STOP_FOREGROUND_REMOVE); } } private void stopTracingInternal(String outputFilename, boolean forceStop, boolean sessionStolen) { Context context = getApplicationContext(); NotificationManager notificationManager = getSystemService(NotificationManager.class); Notification.Builder notification; if (sessionStolen) { notification = getBaseTraceurNotification() .setContentTitle(getString(R.string.attaching_to_report)) .setTicker(getString(R.string.attaching_to_report)) .setProgress(1, 0, true); } else { notification = getBaseTraceurNotification() .setContentTitle(getString(R.string.saving_trace)) .setTicker(getString(R.string.saving_trace)) .setProgress(1, 0, true); } startForeground(SAVING_TRACE_NOTIFICATION, notification.build()); notificationManager.cancel(TRACE_NOTIFICATION); if (sessionStolen) { Notification.Builder notificationAttached = getBaseTraceurNotification() .setContentTitle(getString(R.string.attached_to_report)) .setTicker(getString(R.string.attached_to_report)) .setAutoCancel(true); Intent openIntent = getPackageManager().getLaunchIntentForPackage(BETTERBUG_PACKAGE_NAME); if (openIntent != null) { // Add "Tap to open BetterBug" to notification only if intent is non-null. notificationAttached.setContentText(getString( R.string.attached_to_report_summary)); notificationAttached.setContentIntent(PendingIntent.getActivity( context, 0, openIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE)); } // Adds an action button to the notification for starting a new trace. Intent restartIntent = new Intent(context, InternalReceiver.class); restartIntent.setAction(InternalReceiver.START_ACTION); PendingIntent restartPendingIntent = PendingIntent.getBroadcast(context, 0, restartIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE); Notification.Action action = new Notification.Action.Builder( R.drawable.bugfood_icon, context.getString(R.string.start_new_trace), restartPendingIntent).build(); notificationAttached.addAction(action); NotificationManager.from(context).notify(0, notificationAttached.build()); } else { File file = TraceUtils.getOutputFile(outputFilename); if (TraceUtils.traceDump(file)) { FileSender.postNotification(getApplicationContext(), file); } } stopForeground(Service.STOP_FOREGROUND_REMOVE); TraceUtils.cleanupOlderFiles(MIN_KEEP_COUNT, MIN_KEEP_AGE); } private Notification.Builder getBaseTraceurNotification() { Context context = getApplicationContext(); Notification.Builder notification = new Notification.Builder(this, Receiver.NOTIFICATION_CHANNEL_OTHER) .setSmallIcon(R.drawable.bugfood_icon) .setLocalOnly(true) .setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE) .setColor(context.getColor( com.android.internal.R.color.system_notification_accent_color)); if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LEANBACK)) { notification.extend(new Notification.TvExtender()); } return notification; } }
src/com/android/traceur/TraceService.java
GrapheneOS-Archive-platform_packages_apps_Traceur-2e6c52a
[ { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " prefs.edit().putBoolean(context.getString(R.string.pref_key_tracing_on), false).commit();\n updateTracing(context);\n }\n }\n }\n /*\n * Updates the current tracing state based on the current state of preferences.\n */\n public static void updateTracing(Context context) {\n updateTracing(context, false);", "score": 0.9044901132583618 }, { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " SharedPreferences prefs =\n PreferenceManager.getDefaultSharedPreferences(context);\n prefs.edit().putBoolean(\n context.getString(R.string.pref_key_quick_setting), false)\n .commit();\n updateQuickSettings(context);\n // Stop an ongoing trace if one exists.\n if (TraceUtils.isTracingOn()) {\n TraceService.stopTracingWithoutSaving(context);\n }", "score": 0.9009119272232056 }, { "filename": "src/com/android/traceur/StopTraceService.java", "retrieved_chunk": " SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n boolean prefsTracingOn =\n prefs.getBoolean(context.getString(R.string.pref_key_tracing_on), false);\n // If the user thinks tracing is off and the trace processor agrees, we have no work to do.\n // We must still start a foreground service, but let's log as an FYI.\n if (!prefsTracingOn && !TraceUtils.isTracingOn()) {\n Log.i(TAG, \"StopTraceService does not see a trace to stop.\");\n }\n PreferenceManager.getDefaultSharedPreferences(context)\n .edit().putBoolean(context.getString(R.string.pref_key_tracing_on),", "score": 0.8829454779624939 }, { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " }\n public static void updateTracing(Context context, boolean assumeTracingIsOff) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n boolean prefsTracingOn =\n prefs.getBoolean(context.getString(R.string.pref_key_tracing_on), false);\n boolean traceUtilsTracingOn = assumeTracingIsOff ? false : TraceUtils.isTracingOn();\n if (prefsTracingOn != traceUtilsTracingOn) {\n if (prefsTracingOn) {\n // Show notification if the tags in preferences are not all actually available.\n Set<String> activeAvailableTags = getActiveTags(context, prefs, true);", "score": 0.8717208504676819 }, { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " boolean debuggingDisallowed = userManager.hasUserRestriction(\n UserManager.DISALLOW_DEBUGGING_FEATURES);\n updateStorageProvider(context,\n developerOptionsEnabled && isAdminUser && !debuggingDisallowed);\n } else if (STOP_ACTION.equals(intent.getAction())) {\n prefs.edit().putBoolean(\n context.getString(R.string.pref_key_tracing_on), false).commit();\n updateTracing(context);\n } else if (OPEN_ACTION.equals(intent.getAction())) {\n context.sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));", "score": 0.8685014247894287 } ]
java
TraceUtils.traceStop();
/* * Copyright (C) 2015 The Android Open Source Project * * 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.android.traceur; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.database.ContentObserver; import android.net.Uri; import android.os.Build; import android.os.Handler; import android.os.RemoteException; import android.os.ServiceManager; import android.os.UserManager; import android.preference.PreferenceManager; import android.provider.Settings; import android.text.TextUtils; import android.util.ArraySet; import android.util.Log; import com.android.internal.statusbar.IStatusBarService; import java.util.Arrays; import java.util.List; import java.util.Set; public class Receiver extends BroadcastReceiver { public static final String STOP_ACTION = "com.android.traceur.STOP"; public static final String OPEN_ACTION = "com.android.traceur.OPEN"; public static final String BUGREPORT_STARTED = "com.android.internal.intent.action.BUGREPORT_STARTED"; public static final String NOTIFICATION_CHANNEL_TRACING = "trace-is-being-recorded"; public static final String NOTIFICATION_CHANNEL_OTHER = "system-tracing"; private static final List<String> TRACE_TAGS = Arrays.asList( "aidl", "am", "binder_driver", "camera", "dalvik", "disk", "freq", "gfx", "hal", "idle", "input", "memory", "memreclaim", "network", "power", "res", "sched", "sync", "thermal", "view", "webview", "wm", "workq"); /* The user list doesn't include workq or sync, because the user builds don't have * permissions for them. */ private static final List<String> TRACE_TAGS_USER = Arrays.asList( "aidl", "am", "binder_driver", "camera", "dalvik", "disk", "freq", "gfx", "hal", "idle", "input", "memory", "memreclaim", "network", "power", "res", "sched", "thermal", "view", "webview", "wm"); private static final String TAG = "Traceur"; private static final String BETTERBUG_PACKAGE_NAME = "com.google.android.apps.internal.betterbug"; private static Set<String> mDefaultTagList = null; private static ContentObserver mDeveloperOptionsObserver; @Override public void onReceive(Context context, Intent intent) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { Log.i(TAG, "Received BOOT_COMPLETE"); createNotificationChannels(context); updateDeveloperOptionsWatcher(context); // We know that Perfetto won't be tracing already at boot, so pass the // tracingIsOff argument to avoid the Perfetto check. updateTracing(context, /* assumeTracingIsOff= */ true); } else if (Intent.ACTION_USER_FOREGROUND.equals(intent.getAction())) { boolean developerOptionsEnabled = (1 == Settings.Global.getInt(context.getContentResolver(), Settings.Global.DEVELOPMENT_SETTINGS_ENABLED , 0)); UserManager userManager = context.getSystemService(UserManager.class); boolean isAdminUser = userManager.isAdminUser(); boolean debuggingDisallowed = userManager.hasUserRestriction( UserManager.DISALLOW_DEBUGGING_FEATURES); updateStorageProvider(context, developerOptionsEnabled && isAdminUser && !debuggingDisallowed); } else if (STOP_ACTION.equals(intent.getAction())) { prefs.edit().putBoolean( context.getString(R.string.pref_key_tracing_on), false).commit(); updateTracing(context); } else if (OPEN_ACTION.equals(intent.getAction())) { context.sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); context.startActivity(new Intent(context, MainActivity.class) .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); } else if (BUGREPORT_STARTED.equals(intent.getAction())) { // If stop_on_bugreport is set and attach_to_bugreport is not, stop tracing. // Otherwise, if attach_to_bugreport is set perfetto will end the session, // and we should not take action on the Traceur side. if (prefs.getBoolean(context.getString(R.string.pref_key_stop_on_bugreport), false) && !prefs.getBoolean(context.getString( R.string.pref_key_attach_to_bugreport), true)) { Log.d(TAG, "Bugreport started, ending trace."); prefs.edit().putBoolean(context.getString(R.string.pref_key_tracing_on), false).commit(); updateTracing(context); } } } /* * Updates the current tracing state based on the current state of preferences. */ public static void updateTracing(Context context) { updateTracing(context, false); } public static void updateTracing(Context context, boolean assumeTracingIsOff) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); boolean prefsTracingOn = prefs.getBoolean(context.getString(R.string.pref_key_tracing_on), false); boolean traceUtilsTracingOn = assumeTracingIsOff ?
false : TraceUtils.isTracingOn();
if (prefsTracingOn != traceUtilsTracingOn) { if (prefsTracingOn) { // Show notification if the tags in preferences are not all actually available. Set<String> activeAvailableTags = getActiveTags(context, prefs, true); Set<String> activeTags = getActiveTags(context, prefs, false); if (!activeAvailableTags.equals(activeTags)) { postCategoryNotification(context, prefs); } int bufferSize = Integer.parseInt( prefs.getString(context.getString(R.string.pref_key_buffer_size), context.getString(R.string.default_buffer_size))); boolean appTracing = prefs.getBoolean(context.getString(R.string.pref_key_apps), true); boolean longTrace = prefs.getBoolean(context.getString(R.string.pref_key_long_traces), true); int maxLongTraceSize = Integer.parseInt( prefs.getString(context.getString(R.string.pref_key_max_long_trace_size), context.getString(R.string.default_long_trace_size))); int maxLongTraceDuration = Integer.parseInt( prefs.getString(context.getString(R.string.pref_key_max_long_trace_duration), context.getString(R.string.default_long_trace_duration))); TraceService.startTracing(context, activeAvailableTags, bufferSize, appTracing, longTrace, maxLongTraceSize, maxLongTraceDuration); } else { TraceService.stopTracing(context); } } // Update the main UI and the QS tile. context.sendBroadcast(new Intent(MainFragment.ACTION_REFRESH_TAGS)); QsService.updateTile(); } /* * Updates the current Quick Settings tile state based on the current state * of preferences. */ public static void updateQuickSettings(Context context) { boolean quickSettingsEnabled = PreferenceManager.getDefaultSharedPreferences(context) .getBoolean(context.getString(R.string.pref_key_quick_setting), false); ComponentName name = new ComponentName(context, QsService.class); context.getPackageManager().setComponentEnabledSetting(name, quickSettingsEnabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); IStatusBarService statusBarService = IStatusBarService.Stub.asInterface( ServiceManager.checkService(Context.STATUS_BAR_SERVICE)); try { if (statusBarService != null) { if (quickSettingsEnabled) { statusBarService.addTile(name); } else { statusBarService.remTile(name); } } } catch (RemoteException e) { Log.e(TAG, "Failed to modify QS tile for Traceur.", e); } QsService.updateTile(); } /* * When Developer Options are toggled, also toggle the Storage Provider that * shows "System traces" in Files. * When Developer Options are turned off, reset the Show Quick Settings Tile * preference to false to hide the tile. The user will need to re-enable the * preference if they decide to turn Developer Options back on again. */ static void updateDeveloperOptionsWatcher(Context context) { if (mDeveloperOptionsObserver == null) { Uri settingUri = Settings.Global.getUriFor( Settings.Global.DEVELOPMENT_SETTINGS_ENABLED); mDeveloperOptionsObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { super.onChange(selfChange); boolean developerOptionsEnabled = (1 == Settings.Global.getInt(context.getContentResolver(), Settings.Global.DEVELOPMENT_SETTINGS_ENABLED , 0)); UserManager userManager = context.getSystemService(UserManager.class); boolean isAdminUser = userManager.isAdminUser(); boolean debuggingDisallowed = userManager.hasUserRestriction( UserManager.DISALLOW_DEBUGGING_FEATURES); updateStorageProvider(context, developerOptionsEnabled && isAdminUser && !debuggingDisallowed); if (!developerOptionsEnabled) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); prefs.edit().putBoolean( context.getString(R.string.pref_key_quick_setting), false) .commit(); updateQuickSettings(context); // Stop an ongoing trace if one exists. if (TraceUtils.isTracingOn()) { TraceService.stopTracingWithoutSaving(context); } } } }; context.getContentResolver().registerContentObserver(settingUri, false, mDeveloperOptionsObserver); mDeveloperOptionsObserver.onChange(true); } } // Enables/disables the System Traces storage component. enableProvider should be true iff // developer options are enabled and the current user is an admin user. static void updateStorageProvider(Context context, boolean enableProvider) { ComponentName name = new ComponentName(context, StorageProvider.class); context.getPackageManager().setComponentEnabledSetting(name, enableProvider ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); } private static void postCategoryNotification(Context context, SharedPreferences prefs) { Intent sendIntent = new Intent(context, MainActivity.class); String title = context.getString(R.string.tracing_categories_unavailable); String msg = TextUtils.join(", ", getActiveUnavailableTags(context, prefs)); final Notification.Builder builder = new Notification.Builder(context, NOTIFICATION_CHANNEL_OTHER) .setSmallIcon(R.drawable.bugfood_icon) .setContentTitle(title) .setTicker(title) .setContentText(msg) .setContentIntent(PendingIntent.getActivity( context, 0, sendIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE)) .setAutoCancel(true) .setLocalOnly(true) .setColor(context.getColor( com.android.internal.R.color.system_notification_accent_color)); if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LEANBACK)) { builder.extend(new Notification.TvExtender()); } context.getSystemService(NotificationManager.class) .notify(Receiver.class.getName(), 0, builder.build()); } private static void createNotificationChannels(Context context) { NotificationChannel tracingChannel = new NotificationChannel( NOTIFICATION_CHANNEL_TRACING, context.getString(R.string.trace_is_being_recorded), NotificationManager.IMPORTANCE_HIGH); tracingChannel.setBypassDnd(true); tracingChannel.enableVibration(true); tracingChannel.setSound(null, null); NotificationChannel saveTraceChannel = new NotificationChannel( NOTIFICATION_CHANNEL_OTHER, context.getString(R.string.saving_trace), NotificationManager.IMPORTANCE_HIGH); saveTraceChannel.setBypassDnd(true); saveTraceChannel.enableVibration(true); saveTraceChannel.setSound(null, null); NotificationManager notificationManager = context.getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(tracingChannel); notificationManager.createNotificationChannel(saveTraceChannel); } public static Set<String> getActiveTags(Context context, SharedPreferences prefs, boolean onlyAvailable) { Set<String> tags = prefs.getStringSet(context.getString(R.string.pref_key_tags), getDefaultTagList()); Set<String> available = TraceUtils.listCategories().keySet(); if (onlyAvailable) { tags.retainAll(available); } Log.v(TAG, "getActiveTags(onlyAvailable=" + onlyAvailable + ") = \"" + tags.toString() + "\""); return tags; } public static Set<String> getActiveUnavailableTags(Context context, SharedPreferences prefs) { Set<String> tags = prefs.getStringSet(context.getString(R.string.pref_key_tags), getDefaultTagList()); Set<String> available = TraceUtils.listCategories().keySet(); tags.removeAll(available); Log.v(TAG, "getActiveUnavailableTags() = \"" + tags.toString() + "\""); return tags; } public static Set<String> getDefaultTagList() { if (mDefaultTagList == null) { mDefaultTagList = new ArraySet<String>(Build.TYPE.equals("user") ? TRACE_TAGS_USER : TRACE_TAGS); } return mDefaultTagList; } }
src/com/android/traceur/Receiver.java
GrapheneOS-Archive-platform_packages_apps_Traceur-2e6c52a
[ { "filename": "src/com/android/traceur/StopTraceService.java", "retrieved_chunk": " SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n boolean prefsTracingOn =\n prefs.getBoolean(context.getString(R.string.pref_key_tracing_on), false);\n // If the user thinks tracing is off and the trace processor agrees, we have no work to do.\n // We must still start a foreground service, but let's log as an FYI.\n if (!prefsTracingOn && !TraceUtils.isTracingOn()) {\n Log.i(TAG, \"StopTraceService does not see a trace to stop.\");\n }\n PreferenceManager.getDefaultSharedPreferences(context)\n .edit().putBoolean(context.getString(R.string.pref_key_tracing_on),", "score": 0.8872125148773193 }, { "filename": "src/com/android/traceur/InternalReceiver.java", "retrieved_chunk": "import android.preference.PreferenceManager;\npublic class InternalReceiver extends BroadcastReceiver {\n public static final String START_ACTION = \"com.android.traceur.START\";\n @Override\n public void onReceive(Context context, Intent intent) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n if (START_ACTION.equals(intent.getAction())) {\n prefs.edit().putBoolean(\n context.getString(R.string.pref_key_tracing_on), true).commit();\n Receiver.updateTracing(context);", "score": 0.8568425178527832 }, { "filename": "src/com/android/traceur/TraceService.java", "retrieved_chunk": " intent.setAction(INTENT_ACTION_STOP_TRACING);\n context.startForegroundService(intent);\n }\n // Silently stops a trace without saving it. This is intended to be called when tracing is no\n // longer allowed, i.e. if developer options are turned off while tracing. The usual method of\n // stopping a trace via intent, stopTracing(), will not work because intents cannot be received\n // when developer options are disabled.\n static void stopTracingWithoutSaving(final Context context) {\n NotificationManager notificationManager =\n context.getSystemService(NotificationManager.class);", "score": 0.8539352416992188 }, { "filename": "src/com/android/traceur/TraceService.java", "retrieved_chunk": " return;\n }\n if (intent.getAction().equals(INTENT_ACTION_START_TRACING)) {\n startTracingInternal(intent.getStringArrayListExtra(INTENT_EXTRA_TAGS),\n intent.getIntExtra(INTENT_EXTRA_BUFFER,\n Integer.parseInt(context.getString(R.string.default_buffer_size))),\n intent.getBooleanExtra(INTENT_EXTRA_APPS, false),\n intent.getBooleanExtra(INTENT_EXTRA_LONG_TRACE, false),\n intent.getIntExtra(INTENT_EXTRA_LONG_TRACE_SIZE,\n Integer.parseInt(context.getString(R.string.default_long_trace_size))),", "score": 0.8464122414588928 }, { "filename": "src/com/android/traceur/MainFragment.java", "retrieved_chunk": " @Override\n public void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n Receiver.updateDeveloperOptionsWatcher(getContext());\n mPrefs = PreferenceManager.getDefaultSharedPreferences(\n getActivity().getApplicationContext());\n mTracingOn = (SwitchPreference) findPreference(getActivity().getString(R.string.pref_key_tracing_on));\n mTracingOn.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {\n @Override\n public boolean onPreferenceClick(Preference preference) {", "score": 0.8457177877426147 } ]
java
false : TraceUtils.isTracingOn();
/* * Copyright (C) 2015 The Android Open Source Project * * 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.android.traceur; import android.app.IntentService; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.UserManager; import android.preference.PreferenceManager; import android.provider.Settings; import android.text.format.DateUtils; import android.util.EventLog; import android.util.Log; import java.io.File; import java.util.ArrayList; import java.util.Collection; public class TraceService extends IntentService { /* Indicates Perfetto has stopped tracing due to either the supplied long trace limitations * or limited storage capacity. */ static String INTENT_ACTION_NOTIFY_SESSION_STOPPED = "com.android.traceur.NOTIFY_SESSION_STOPPED"; /* Indicates a Traceur-associated tracing session has been attached to a bug report */ static String INTENT_ACTION_NOTIFY_SESSION_STOLEN = "com.android.traceur.NOTIFY_SESSION_STOLEN"; private static String INTENT_ACTION_STOP_TRACING = "com.android.traceur.STOP_TRACING"; private static String INTENT_ACTION_START_TRACING = "com.android.traceur.START_TRACING"; private static String INTENT_EXTRA_TAGS= "tags"; private static String INTENT_EXTRA_BUFFER = "buffer"; private static String INTENT_EXTRA_APPS = "apps"; private static String INTENT_EXTRA_LONG_TRACE = "long_trace"; private static String INTENT_EXTRA_LONG_TRACE_SIZE = "long_trace_size"; private static String INTENT_EXTRA_LONG_TRACE_DURATION = "long_trace_duration"; private static String BETTERBUG_PACKAGE_NAME = "com.google.android.apps.internal.betterbug"; private static int TRACE_NOTIFICATION = 1; private static int SAVING_TRACE_NOTIFICATION = 2; private static final int MIN_KEEP_COUNT = 3; private static final long MIN_KEEP_AGE = 4 * DateUtils.WEEK_IN_MILLIS; public static void startTracing(final Context context, Collection<String> tags, int bufferSizeKb, boolean apps, boolean longTrace, int maxLongTraceSizeMb, int maxLongTraceDurationMinutes) { Intent intent = new Intent(context, TraceService.class); intent.setAction(INTENT_ACTION_START_TRACING); intent.putExtra(INTENT_EXTRA_TAGS, new ArrayList(tags)); intent.putExtra(INTENT_EXTRA_BUFFER, bufferSizeKb); intent.putExtra(INTENT_EXTRA_APPS, apps); intent.putExtra(INTENT_EXTRA_LONG_TRACE, longTrace); intent.putExtra(INTENT_EXTRA_LONG_TRACE_SIZE, maxLongTraceSizeMb); intent.putExtra(INTENT_EXTRA_LONG_TRACE_DURATION, maxLongTraceDurationMinutes); context.startForegroundService(intent); } public static void stopTracing(final Context context) { Intent intent = new Intent(context, TraceService.class); intent.setAction(INTENT_ACTION_STOP_TRACING); context.startForegroundService(intent); } // Silently stops a trace without saving it. This is intended to be called when tracing is no // longer allowed, i.e. if developer options are turned off while tracing. The usual method of // stopping a trace via intent, stopTracing(), will not work because intents cannot be received // when developer options are disabled. static void stopTracingWithoutSaving(final Context context) { NotificationManager notificationManager = context.getSystemService(NotificationManager.class); notificationManager.cancel(TRACE_NOTIFICATION); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); prefs.edit().putBoolean(context.getString( R.string.pref_key_tracing_on), false).commit(); TraceUtils.traceStop(); } public TraceService() { this("TraceService"); } protected TraceService(String name) { super(name); setIntentRedelivery(true); } @Override public void onHandleIntent(Intent intent) { Context context = getApplicationContext(); // Checks that developer options are enabled and the user is an admin before continuing. boolean developerOptionsEnabled = Settings.Global.getInt(context.getContentResolver(), Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) != 0; if (!developerOptionsEnabled) { // Refer to b/204992293. EventLog.writeEvent(0x534e4554, "204992293", -1, ""); return; } UserManager userManager = context.getSystemService(UserManager.class); boolean isAdminUser = userManager.isAdminUser(); boolean debuggingDisallowed = userManager.hasUserRestriction( UserManager.DISALLOW_DEBUGGING_FEATURES); if (!isAdminUser || debuggingDisallowed) { return; } if (intent.getAction().equals(INTENT_ACTION_START_TRACING)) { startTracingInternal(intent.getStringArrayListExtra(INTENT_EXTRA_TAGS), intent.getIntExtra(INTENT_EXTRA_BUFFER, Integer.parseInt(context.getString(R.string.default_buffer_size))), intent.getBooleanExtra(INTENT_EXTRA_APPS, false), intent.getBooleanExtra(INTENT_EXTRA_LONG_TRACE, false), intent.getIntExtra(INTENT_EXTRA_LONG_TRACE_SIZE, Integer.parseInt(context.getString(R.string.default_long_trace_size))), intent.getIntExtra(INTENT_EXTRA_LONG_TRACE_DURATION, Integer.parseInt(context.getString(R.string.default_long_trace_duration)))); } else if (intent.getAction().equals(INTENT_ACTION_STOP_TRACING)) { stopTracingInternal(TraceUtils.getOutputFilename(), false, false); } else if (intent.getAction().equals(INTENT_ACTION_NOTIFY_SESSION_STOPPED)) { stopTracingInternal(TraceUtils.getOutputFilename(), true, false); } else if (intent.getAction().equals(INTENT_ACTION_NOTIFY_SESSION_STOLEN)) { stopTracingInternal("", false, true); } } private void startTracingInternal(Collection<String> tags, int bufferSizeKb, boolean appTracing, boolean longTrace, int maxLongTraceSizeMb, int maxLongTraceDurationMinutes) { Context context = getApplicationContext(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); Intent stopIntent = new Intent(Receiver.STOP_ACTION, null, context, Receiver.class); stopIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); String title = context.getString(R.string.trace_is_being_recorded); String msg = context.getString(R.string.tap_to_stop_tracing); boolean attachToBugreport = prefs.getBoolean(context.getString(R.string.pref_key_attach_to_bugreport), true); Notification.Builder notification = new Notification.Builder(context, Receiver.NOTIFICATION_CHANNEL_TRACING) .setSmallIcon(R.drawable.bugfood_icon) .setContentTitle(title) .setTicker(title) .setContentText(msg) .setContentIntent( PendingIntent.getBroadcast(context, 0, stopIntent, PendingIntent.FLAG_IMMUTABLE)) .setOngoing(true) .setLocalOnly(true) .setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE) .setColor(getColor( com.android.internal.R.color.system_notification_accent_color)); if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LEANBACK)) { notification.extend(new Notification.TvExtender()); } startForeground(TRACE_NOTIFICATION, notification.build()); if
(TraceUtils.traceStart(tags, bufferSizeKb, appTracing, longTrace, attachToBugreport, maxLongTraceSizeMb, maxLongTraceDurationMinutes)) {
stopForeground(Service.STOP_FOREGROUND_DETACH); } else { // Starting the trace was unsuccessful, so ensure that tracing // is stopped and the preference is reset. TraceUtils.traceStop(); prefs.edit().putBoolean(context.getString(R.string.pref_key_tracing_on), false).commit(); QsService.updateTile(); stopForeground(Service.STOP_FOREGROUND_REMOVE); } } private void stopTracingInternal(String outputFilename, boolean forceStop, boolean sessionStolen) { Context context = getApplicationContext(); NotificationManager notificationManager = getSystemService(NotificationManager.class); Notification.Builder notification; if (sessionStolen) { notification = getBaseTraceurNotification() .setContentTitle(getString(R.string.attaching_to_report)) .setTicker(getString(R.string.attaching_to_report)) .setProgress(1, 0, true); } else { notification = getBaseTraceurNotification() .setContentTitle(getString(R.string.saving_trace)) .setTicker(getString(R.string.saving_trace)) .setProgress(1, 0, true); } startForeground(SAVING_TRACE_NOTIFICATION, notification.build()); notificationManager.cancel(TRACE_NOTIFICATION); if (sessionStolen) { Notification.Builder notificationAttached = getBaseTraceurNotification() .setContentTitle(getString(R.string.attached_to_report)) .setTicker(getString(R.string.attached_to_report)) .setAutoCancel(true); Intent openIntent = getPackageManager().getLaunchIntentForPackage(BETTERBUG_PACKAGE_NAME); if (openIntent != null) { // Add "Tap to open BetterBug" to notification only if intent is non-null. notificationAttached.setContentText(getString( R.string.attached_to_report_summary)); notificationAttached.setContentIntent(PendingIntent.getActivity( context, 0, openIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE)); } // Adds an action button to the notification for starting a new trace. Intent restartIntent = new Intent(context, InternalReceiver.class); restartIntent.setAction(InternalReceiver.START_ACTION); PendingIntent restartPendingIntent = PendingIntent.getBroadcast(context, 0, restartIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE); Notification.Action action = new Notification.Action.Builder( R.drawable.bugfood_icon, context.getString(R.string.start_new_trace), restartPendingIntent).build(); notificationAttached.addAction(action); NotificationManager.from(context).notify(0, notificationAttached.build()); } else { File file = TraceUtils.getOutputFile(outputFilename); if (TraceUtils.traceDump(file)) { FileSender.postNotification(getApplicationContext(), file); } } stopForeground(Service.STOP_FOREGROUND_REMOVE); TraceUtils.cleanupOlderFiles(MIN_KEEP_COUNT, MIN_KEEP_AGE); } private Notification.Builder getBaseTraceurNotification() { Context context = getApplicationContext(); Notification.Builder notification = new Notification.Builder(this, Receiver.NOTIFICATION_CHANNEL_OTHER) .setSmallIcon(R.drawable.bugfood_icon) .setLocalOnly(true) .setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE) .setColor(context.getColor( com.android.internal.R.color.system_notification_accent_color)); if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LEANBACK)) { notification.extend(new Notification.TvExtender()); } return notification; } }
src/com/android/traceur/TraceService.java
GrapheneOS-Archive-platform_packages_apps_Traceur-2e6c52a
[ { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " | PendingIntent.FLAG_CANCEL_CURRENT\n | PendingIntent.FLAG_IMMUTABLE))\n .setAutoCancel(true)\n .setLocalOnly(true)\n .setColor(context.getColor(\n com.android.internal.R.color.system_notification_accent_color));\n if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {\n builder.extend(new Notification.TvExtender());\n }\n context.getSystemService(NotificationManager.class)", "score": 0.9087212681770325 }, { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " .notify(Receiver.class.getName(), 0, builder.build());\n }\n private static void createNotificationChannels(Context context) {\n NotificationChannel tracingChannel = new NotificationChannel(\n NOTIFICATION_CHANNEL_TRACING,\n context.getString(R.string.trace_is_being_recorded),\n NotificationManager.IMPORTANCE_HIGH);\n tracingChannel.setBypassDnd(true);\n tracingChannel.enableVibration(true);\n tracingChannel.setSound(null, null);", "score": 0.8632818460464478 }, { "filename": "src/com/android/traceur/FileSender.java", "retrieved_chunk": " new Notification.Builder(context, Receiver.NOTIFICATION_CHANNEL_OTHER)\n .setSmallIcon(R.drawable.bugfood_icon)\n .setContentTitle(context.getString(R.string.trace_saved))\n .setTicker(context.getString(R.string.trace_saved))\n .setContentText(context.getString(R.string.tap_to_share))\n .setContentIntent(PendingIntent.getActivity(\n context, traceUri.hashCode(), intent, PendingIntent.FLAG_ONE_SHOT\n | PendingIntent.FLAG_CANCEL_CURRENT\n | PendingIntent.FLAG_IMMUTABLE))\n .setAutoCancel(true)", "score": 0.8573800325393677 }, { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " NotificationChannel saveTraceChannel = new NotificationChannel(\n NOTIFICATION_CHANNEL_OTHER,\n context.getString(R.string.saving_trace),\n NotificationManager.IMPORTANCE_HIGH);\n saveTraceChannel.setBypassDnd(true);\n saveTraceChannel.enableVibration(true);\n saveTraceChannel.setSound(null, null);\n NotificationManager notificationManager =\n context.getSystemService(NotificationManager.class);\n notificationManager.createNotificationChannel(tracingChannel);", "score": 0.8543325066566467 }, { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " String title = context.getString(R.string.tracing_categories_unavailable);\n String msg = TextUtils.join(\", \", getActiveUnavailableTags(context, prefs));\n final Notification.Builder builder =\n new Notification.Builder(context, NOTIFICATION_CHANNEL_OTHER)\n .setSmallIcon(R.drawable.bugfood_icon)\n .setContentTitle(title)\n .setTicker(title)\n .setContentText(msg)\n .setContentIntent(PendingIntent.getActivity(\n context, 0, sendIntent, PendingIntent.FLAG_ONE_SHOT", "score": 0.8345968127250671 } ]
java
(TraceUtils.traceStart(tags, bufferSizeKb, appTracing, longTrace, attachToBugreport, maxLongTraceSizeMb, maxLongTraceDurationMinutes)) {
/* * Copyright (C) 2015 The Android Open Source Project * * 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.android.traceur; import android.system.Os; import android.util.Log; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Collection; import java.util.List; import java.util.TreeMap; import java.util.concurrent.TimeUnit; import perfetto.protos.DataSourceDescriptorOuterClass.DataSourceDescriptor; import perfetto.protos.FtraceDescriptorOuterClass.FtraceDescriptor.AtraceCategory; import perfetto.protos.TracingServiceStateOuterClass.TracingServiceState; import perfetto.protos.TracingServiceStateOuterClass.TracingServiceState.DataSource; /** * Utility functions for calling Perfetto */ public class PerfettoUtils implements TraceUtils.TraceEngine { static final String TAG = "Traceur"; public static final String NAME = "PERFETTO"; private static final String OUTPUT_EXTENSION = "perfetto-trace"; private static final String TEMP_DIR= "/data/local/traces/"; private static final String TEMP_TRACE_LOCATION = "/data/local/traces/.trace-in-progress.trace"; private static final String PERFETTO_TAG = "traceur"; private static final String MARKER = "PERFETTO_ARGUMENTS"; private static final int LIST_TIMEOUT_MS = 10000; private static final int STARTUP_TIMEOUT_MS = 10000; private static final int STOP_TIMEOUT_MS = 30000; private static final long MEGABYTES_TO_BYTES = 1024L * 1024L; private static final long MINUTES_TO_MILLISECONDS = 60L * 1000L; private static final String CAMERA_TAG = "camera"; private static final String GFX_TAG = "gfx"; private static final String MEMORY_TAG = "memory"; private static final String POWER_TAG = "power"; private static final String SCHED_TAG = "sched"; private static final String WEBVIEW_TAG = "webview"; public String getName() { return NAME; } public String getOutputExtension() { return OUTPUT_EXTENSION; } public boolean traceStart(Collection<String> tags, int bufferSizeKb, boolean apps, boolean attachToBugreport, boolean longTrace, int maxLongTraceSizeMb, int maxLongTraceDurationMinutes) { if (isTracingOn()) { Log.e(TAG, "Attempting to start perfetto trace but trace is already in progress"); return false; } else { // Ensure the temporary trace file is cleared. try { Files.deleteIfExists(Paths.get(TEMP_TRACE_LOCATION)); } catch (Exception e) { throw new RuntimeException(e); } } // The user chooses a per-CPU buffer size due to atrace limitations. // So we use this to ensure that we reserve the correctly-sized buffer. int numCpus = Runtime.getRuntime().availableProcessors(); // Build the perfetto config that will be passed on the command line. StringBuilder config = new StringBuilder() .append("write_into_file: true\n") // Ensure that we flush ftrace data every 30s even if cpus are idle. .append("flush_period_ms: 30000\n"); // If the user has flagged that in-progress trace sessions should be grabbed // during bugreports, and BetterBug is present. if (attachToBugreport) { config.append("bugreport_score: 500\n"); } // Indicates that perfetto should notify Traceur if the tracing session's status // changes. config.append("notify_traceur: true\n"); if (longTrace) { if (maxLongTraceSizeMb != 0) { config.append("max_file_size_bytes: " + (maxLongTraceSizeMb * MEGABYTES_TO_BYTES) + "\n"); } if (maxLongTraceDurationMinutes != 0) { config.append("duration_ms: " + (maxLongTraceDurationMinutes * MINUTES_TO_MILLISECONDS) + "\n"); } // Default value for long traces to write to file. config.append("file_write_period_ms: 1000\n"); } else { // For short traces, we don't write to the file. // So, always use the maximum value here: 7 days. config.append("file_write_period_ms: 604800000\n"); } config.append("incremental_state_config {\n") .append(" clear_period_ms: 15000\n") .append("} \n") // This is target_buffer: 0, which is used for ftrace and the ftrace-derived // android.gpu.memory. .append("buffers {\n") .append(" size_kb: " + bufferSizeKb * numCpus + "\n") .append(" fill_policy: RING_BUFFER\n") .append("} \n") // This is target_buffer: 1, which is used for additional data sources. .append("buffers {\n") .append(" size_kb: 2048\n") .append(" fill_policy: RING_BUFFER\n") .append("} \n") .append("data_sources {\n") .append(" config {\n") .append(" name: \"linux.ftrace\"\n") .append(" target_buffer: 0\n") .append(" ftrace_config {\n") .append(" symbolize_ksyms: true\n"); for (String tag : tags) { // Tags are expected to be only letters, numbers, and underscores. String cleanTag = tag.replaceAll("[^a-zA-Z0-9_]", ""); if (!cleanTag.equals(tag)) { Log.w(TAG, "Attempting to use an invalid tag: " + tag); } config.append(" atrace_categories: \"" + cleanTag + "\"\n"); } if (apps) { config.append(" atrace_apps: \"*\"\n"); } // Request a dense encoding of the common sched events (sched_switch, sched_waking). if (tags.contains(SCHED_TAG)) { config.append(" compact_sched {\n"); config.append(" enabled: true\n"); config.append(" }\n"); } // These parameters affect only the kernel trace buffer size and how // frequently it gets moved into the userspace buffer defined above. config.append(" buffer_size_kb: 8192\n") .append(" drain_period_ms: 1000\n") .append(" }\n") .append(" }\n") .append("}\n") .append(" \n"); // Captures initial counter values, updates are captured in ftrace. if (tags.contains(MEMORY_TAG) || tags.contains(GFX_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.gpu.memory\"\n") .append(" target_buffer: 0\n") .append(" }\n") .append("}\n"); } // For process association. If the memory tag is enabled, // poll periodically instead of just once at the beginning. config.append("data_sources {\n") .append(" config {\n") .append(" name: \"linux.process_stats\"\n") .append(" target_buffer: 1\n"); if (tags.contains(MEMORY_TAG)) { config.append(" process_stats_config {\n") .append(" proc_stats_poll_ms: 60000\n") .append(" }\n"); } config.append(" }\n") .append("} \n"); if (tags.contains(POWER_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.power\"\n") .append(" target_buffer: 1\n") .append(" android_power_config {\n"); if (longTrace) { config.append(" battery_poll_ms: 5000\n"); } else { config.append(" battery_poll_ms: 1000\n"); } config.append(" collect_power_rails: true\n") .append(" battery_counters: BATTERY_COUNTER_CAPACITY_PERCENT\n") .append(" battery_counters: BATTERY_COUNTER_CHARGE\n") .append(" battery_counters: BATTERY_COUNTER_CURRENT\n") .append(" }\n") .append(" }\n") .append("}\n"); } if (tags.contains(MEMORY_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.sys_stats\"\n") .append(" target_buffer: 1\n") .append(" sys_stats_config {\n") .append(" vmstat_period_ms: 1000\n") .append(" }\n") .append(" }\n") .append("}\n"); } if (tags.contains(GFX_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.surfaceflinger.frametimeline\"\n") .append(" }\n") .append("}\n"); } if (tags.contains(CAMERA_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.hardware.camera\"\n") .append(" target_buffer: 1\n") .append(" }\n") .append("}\n"); } // Also enable Chrome events when the WebView tag is enabled. if (tags.contains(WEBVIEW_TAG)) { String chromeTraceConfig = "{" + "\\\"record_mode\\\":\\\"record-continuously\\\"," + "\\\"included_categories\\\":[\\\"*\\\"]" + "}"; config.append("data_sources: {\n") .append(" config {\n") .append(" name: \"org.chromium.trace_event\"\n") .append(" chrome_config {\n") .append(" trace_config: \"" + chromeTraceConfig + "\"\n") .append(" }\n") .append(" }\n") .append("}\n") .append("data_sources: {\n") .append(" config {\n") .append(" name: \"org.chromium.trace_metadata\"\n") .append(" chrome_config {\n") .append(" trace_config: \"" + chromeTraceConfig + "\"\n") .append(" }\n") .append(" }\n") .append("}\n"); } String configString = config.toString(); // If the here-doc ends early, within the config string, exit immediately. // This should never happen. if (configString.contains(MARKER)) { throw new RuntimeException("The arguments to the Perfetto command are malformed."); } String cmd = "perfetto --detach=" + PERFETTO_TAG + " -o " + TEMP_TRACE_LOCATION + " -c - --txt" + " <<" + MARKER +"\n" + configString + "\n" + MARKER; Log.v(TAG, "Starting perfetto trace."); try { Process process = TraceUtils.execWithTimeout(cmd, TEMP_DIR, STARTUP_TIMEOUT_MS); if (process == null) { return false; } else if (process.exitValue() != 0) { Log.e(TAG, "perfetto traceStart failed with: " + process.exitValue()); return false; } } catch (Exception e) { throw new RuntimeException(e); } Log.v(TAG, "perfetto traceStart succeeded!"); return true; } public void traceStop() { Log.v(TAG, "Stopping perfetto trace."); if (!isTracingOn()) { Log.w(TAG, "No trace appears to be in progress. Stopping perfetto trace may not work."); } String cmd = "perfetto --stop --attach=" + PERFETTO_TAG; try { Process process = TraceUtils.execWithTimeout(cmd, null, STOP_TIMEOUT_MS); if (process != null && process.exitValue() != 0) { Log.e(TAG, "perfetto traceStop failed with: " + process.exitValue()); } } catch (Exception e) { throw new RuntimeException(e); } } public boolean traceDump(File outFile) { traceStop(); // Short-circuit if a trace was not stopped. if (isTracingOn()) { Log.e(TAG, "Trace was not stopped successfully, aborting trace dump."); return false; } // Short-circuit if the file we're trying to dump to doesn't exist. if (!Files.exists(Paths.get(TEMP_TRACE_LOCATION))) { Log.e(TAG, "In-progress trace file doesn't exist, aborting trace dump."); return false; } Log.v(TAG, "Saving perfetto trace to " + outFile); try { Os.rename(TEMP_TRACE_LOCATION, outFile.getCanonicalPath()); } catch (Exception e) { throw new RuntimeException(e); } outFile.setReadable(true, false); // (readable, ownerOnly) outFile.setWritable(true, false); // (readable, ownerOnly) return true; } public boolean isTracingOn() { String cmd = "perfetto --is_detached=" + PERFETTO_TAG; try {
Process process = TraceUtils.exec(cmd);
// 0 represents a detached process exists with this name // 2 represents no detached process with this name // 1 (or other error code) represents an error int result = process.waitFor(); if (result == 0) { return true; } else if (result == 2) { return false; } else { throw new RuntimeException("Perfetto error: " + result); } } catch (Exception e) { throw new RuntimeException(e); } } public static TreeMap<String,String> perfettoListCategories() { String cmd = "perfetto --query-raw"; Log.v(TAG, "Listing tags: " + cmd); try { TreeMap<String, String> result = new TreeMap<>(); // execWithTimeout() cannot be used because stdout must be consumed before the process // is terminated. Process perfetto = TraceUtils.exec(cmd, null, false); TracingServiceState serviceState = TracingServiceState.parseFrom(perfetto.getInputStream()); // Destroy the perfetto process if it times out. if (!perfetto.waitFor(LIST_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { Log.e(TAG, "perfettoListCategories timed out after " + LIST_TIMEOUT_MS + " ms."); perfetto.destroyForcibly(); return result; } // The perfetto process completed and failed, but does not need to be destroyed. if (perfetto.exitValue() != 0) { Log.e(TAG, "perfettoListCategories failed with: " + perfetto.exitValue()); } List<AtraceCategory> categories = null; for (DataSource dataSource : serviceState.getDataSourcesList()) { DataSourceDescriptor dataSrcDescriptor = dataSource.getDsDescriptor(); if (dataSrcDescriptor.getName().equals("linux.ftrace")){ categories = dataSrcDescriptor.getFtraceDescriptor().getAtraceCategoriesList(); break; } } if (categories != null) { for (AtraceCategory category : categories) { result.put(category.getName(), category.getDescription()); } } return result; } catch (Exception e) { throw new RuntimeException(e); } } }
src/com/android/traceur/PerfettoUtils.java
GrapheneOS-Archive-platform_packages_apps_Traceur-2e6c52a
[ { "filename": "src/com/android/traceur/AtraceUtils.java", "retrieved_chunk": " // Set the new file world readable to allow it to be adb pulled.\n outFile.setReadable(true, false); // (readable, ownerOnly)\n outFile.setWritable(true, false); // (readable, ownerOnly)\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n return true;\n }\n public boolean isTracingOn() {\n boolean userInitiatedTracingFlag =", "score": 0.8966289758682251 }, { "filename": "src/com/android/traceur/AtraceUtils.java", "retrieved_chunk": " } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n public boolean traceDump(File outFile) {\n String cmd = \"atrace --async_stop -z -c -o \" + outFile;\n Log.v(TAG, \"Dumping async atrace: \" + cmd);\n try {\n Process atrace = TraceUtils.exec(cmd);\n if (atrace.waitFor() != 0) {", "score": 0.8718706965446472 }, { "filename": "src/com/android/traceur/AtraceUtils.java", "retrieved_chunk": " Log.e(TAG, \"atraceDump failed with: \" + atrace.exitValue());\n return false;\n }\n Process ps = TraceUtils.exec(\"ps -AT\", null, false);\n new Streamer(\"atraceDump:ps:stdout\",\n ps.getInputStream(), new FileOutputStream(outFile, true /* append */));\n if (ps.waitFor() != 0) {\n Log.e(TAG, \"atraceDump:ps failed with: \" + ps.exitValue());\n return false;\n }", "score": 0.862396240234375 }, { "filename": "src/com/android/traceur/AtraceUtils.java", "retrieved_chunk": " tracingOnContents = Files.readAllLines(debugTracingOnPath);\n } else if (Files.isReadable(tracingOnPath)) {\n tracingOnContents = Files.readAllLines(tracingOnPath);\n } else {\n return false;\n }\n tracingOnFlag = !tracingOnContents.get(0).equals(\"0\");\n } catch (IOException e) {\n throw new RuntimeException(e);\n }", "score": 0.8543810248374939 }, { "filename": "src/com/android/traceur/TraceUtils.java", "retrieved_chunk": " public static boolean isTracingOn() {\n return mTraceEngine.isTracingOn();\n }\n public static TreeMap<String, String> listCategories() {\n return PerfettoUtils.perfettoListCategories();\n }\n public static void clearSavedTraces() {\n String cmd = \"rm -f \" + TRACE_DIRECTORY + \"trace-*.*trace\";\n Log.v(TAG, \"Clearing trace directory: \" + cmd);\n try {", "score": 0.8498795628547668 } ]
java
Process process = TraceUtils.exec(cmd);
/* * Copyright (C) 2015 The Android Open Source Project * * 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.android.traceur; import android.app.IntentService; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.UserManager; import android.preference.PreferenceManager; import android.provider.Settings; import android.text.format.DateUtils; import android.util.EventLog; import android.util.Log; import java.io.File; import java.util.ArrayList; import java.util.Collection; public class TraceService extends IntentService { /* Indicates Perfetto has stopped tracing due to either the supplied long trace limitations * or limited storage capacity. */ static String INTENT_ACTION_NOTIFY_SESSION_STOPPED = "com.android.traceur.NOTIFY_SESSION_STOPPED"; /* Indicates a Traceur-associated tracing session has been attached to a bug report */ static String INTENT_ACTION_NOTIFY_SESSION_STOLEN = "com.android.traceur.NOTIFY_SESSION_STOLEN"; private static String INTENT_ACTION_STOP_TRACING = "com.android.traceur.STOP_TRACING"; private static String INTENT_ACTION_START_TRACING = "com.android.traceur.START_TRACING"; private static String INTENT_EXTRA_TAGS= "tags"; private static String INTENT_EXTRA_BUFFER = "buffer"; private static String INTENT_EXTRA_APPS = "apps"; private static String INTENT_EXTRA_LONG_TRACE = "long_trace"; private static String INTENT_EXTRA_LONG_TRACE_SIZE = "long_trace_size"; private static String INTENT_EXTRA_LONG_TRACE_DURATION = "long_trace_duration"; private static String BETTERBUG_PACKAGE_NAME = "com.google.android.apps.internal.betterbug"; private static int TRACE_NOTIFICATION = 1; private static int SAVING_TRACE_NOTIFICATION = 2; private static final int MIN_KEEP_COUNT = 3; private static final long MIN_KEEP_AGE = 4 * DateUtils.WEEK_IN_MILLIS; public static void startTracing(final Context context, Collection<String> tags, int bufferSizeKb, boolean apps, boolean longTrace, int maxLongTraceSizeMb, int maxLongTraceDurationMinutes) { Intent intent = new Intent(context, TraceService.class); intent.setAction(INTENT_ACTION_START_TRACING); intent.putExtra(INTENT_EXTRA_TAGS, new ArrayList(tags)); intent.putExtra(INTENT_EXTRA_BUFFER, bufferSizeKb); intent.putExtra(INTENT_EXTRA_APPS, apps); intent.putExtra(INTENT_EXTRA_LONG_TRACE, longTrace); intent.putExtra(INTENT_EXTRA_LONG_TRACE_SIZE, maxLongTraceSizeMb); intent.putExtra(INTENT_EXTRA_LONG_TRACE_DURATION, maxLongTraceDurationMinutes); context.startForegroundService(intent); } public static void stopTracing(final Context context) { Intent intent = new Intent(context, TraceService.class); intent.setAction(INTENT_ACTION_STOP_TRACING); context.startForegroundService(intent); } // Silently stops a trace without saving it. This is intended to be called when tracing is no // longer allowed, i.e. if developer options are turned off while tracing. The usual method of // stopping a trace via intent, stopTracing(), will not work because intents cannot be received // when developer options are disabled. static void stopTracingWithoutSaving(final Context context) { NotificationManager notificationManager = context.getSystemService(NotificationManager.class); notificationManager.cancel(TRACE_NOTIFICATION); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); prefs.edit().putBoolean(context.getString( R.string.pref_key_tracing_on), false).commit(); TraceUtils.traceStop(); } public TraceService() { this("TraceService"); } protected TraceService(String name) { super(name); setIntentRedelivery(true); } @Override public void onHandleIntent(Intent intent) { Context context = getApplicationContext(); // Checks that developer options are enabled and the user is an admin before continuing. boolean developerOptionsEnabled = Settings.Global.getInt(context.getContentResolver(), Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) != 0; if (!developerOptionsEnabled) { // Refer to b/204992293. EventLog.writeEvent(0x534e4554, "204992293", -1, ""); return; } UserManager userManager = context.getSystemService(UserManager.class); boolean isAdminUser = userManager.isAdminUser(); boolean debuggingDisallowed = userManager.hasUserRestriction( UserManager.DISALLOW_DEBUGGING_FEATURES); if (!isAdminUser || debuggingDisallowed) { return; } if (intent.getAction().equals(INTENT_ACTION_START_TRACING)) { startTracingInternal(intent.getStringArrayListExtra(INTENT_EXTRA_TAGS), intent.getIntExtra(INTENT_EXTRA_BUFFER, Integer.parseInt(context.getString(R.string.default_buffer_size))), intent.getBooleanExtra(INTENT_EXTRA_APPS, false), intent.getBooleanExtra(INTENT_EXTRA_LONG_TRACE, false), intent.getIntExtra(INTENT_EXTRA_LONG_TRACE_SIZE, Integer.parseInt(context.getString(R.string.default_long_trace_size))), intent.getIntExtra(INTENT_EXTRA_LONG_TRACE_DURATION, Integer.parseInt(context.getString(R.string.default_long_trace_duration)))); } else if (intent.getAction().equals(INTENT_ACTION_STOP_TRACING)) { stopTracingInternal
(TraceUtils.getOutputFilename(), false, false);
} else if (intent.getAction().equals(INTENT_ACTION_NOTIFY_SESSION_STOPPED)) { stopTracingInternal(TraceUtils.getOutputFilename(), true, false); } else if (intent.getAction().equals(INTENT_ACTION_NOTIFY_SESSION_STOLEN)) { stopTracingInternal("", false, true); } } private void startTracingInternal(Collection<String> tags, int bufferSizeKb, boolean appTracing, boolean longTrace, int maxLongTraceSizeMb, int maxLongTraceDurationMinutes) { Context context = getApplicationContext(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); Intent stopIntent = new Intent(Receiver.STOP_ACTION, null, context, Receiver.class); stopIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); String title = context.getString(R.string.trace_is_being_recorded); String msg = context.getString(R.string.tap_to_stop_tracing); boolean attachToBugreport = prefs.getBoolean(context.getString(R.string.pref_key_attach_to_bugreport), true); Notification.Builder notification = new Notification.Builder(context, Receiver.NOTIFICATION_CHANNEL_TRACING) .setSmallIcon(R.drawable.bugfood_icon) .setContentTitle(title) .setTicker(title) .setContentText(msg) .setContentIntent( PendingIntent.getBroadcast(context, 0, stopIntent, PendingIntent.FLAG_IMMUTABLE)) .setOngoing(true) .setLocalOnly(true) .setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE) .setColor(getColor( com.android.internal.R.color.system_notification_accent_color)); if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LEANBACK)) { notification.extend(new Notification.TvExtender()); } startForeground(TRACE_NOTIFICATION, notification.build()); if (TraceUtils.traceStart(tags, bufferSizeKb, appTracing, longTrace, attachToBugreport, maxLongTraceSizeMb, maxLongTraceDurationMinutes)) { stopForeground(Service.STOP_FOREGROUND_DETACH); } else { // Starting the trace was unsuccessful, so ensure that tracing // is stopped and the preference is reset. TraceUtils.traceStop(); prefs.edit().putBoolean(context.getString(R.string.pref_key_tracing_on), false).commit(); QsService.updateTile(); stopForeground(Service.STOP_FOREGROUND_REMOVE); } } private void stopTracingInternal(String outputFilename, boolean forceStop, boolean sessionStolen) { Context context = getApplicationContext(); NotificationManager notificationManager = getSystemService(NotificationManager.class); Notification.Builder notification; if (sessionStolen) { notification = getBaseTraceurNotification() .setContentTitle(getString(R.string.attaching_to_report)) .setTicker(getString(R.string.attaching_to_report)) .setProgress(1, 0, true); } else { notification = getBaseTraceurNotification() .setContentTitle(getString(R.string.saving_trace)) .setTicker(getString(R.string.saving_trace)) .setProgress(1, 0, true); } startForeground(SAVING_TRACE_NOTIFICATION, notification.build()); notificationManager.cancel(TRACE_NOTIFICATION); if (sessionStolen) { Notification.Builder notificationAttached = getBaseTraceurNotification() .setContentTitle(getString(R.string.attached_to_report)) .setTicker(getString(R.string.attached_to_report)) .setAutoCancel(true); Intent openIntent = getPackageManager().getLaunchIntentForPackage(BETTERBUG_PACKAGE_NAME); if (openIntent != null) { // Add "Tap to open BetterBug" to notification only if intent is non-null. notificationAttached.setContentText(getString( R.string.attached_to_report_summary)); notificationAttached.setContentIntent(PendingIntent.getActivity( context, 0, openIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE)); } // Adds an action button to the notification for starting a new trace. Intent restartIntent = new Intent(context, InternalReceiver.class); restartIntent.setAction(InternalReceiver.START_ACTION); PendingIntent restartPendingIntent = PendingIntent.getBroadcast(context, 0, restartIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE); Notification.Action action = new Notification.Action.Builder( R.drawable.bugfood_icon, context.getString(R.string.start_new_trace), restartPendingIntent).build(); notificationAttached.addAction(action); NotificationManager.from(context).notify(0, notificationAttached.build()); } else { File file = TraceUtils.getOutputFile(outputFilename); if (TraceUtils.traceDump(file)) { FileSender.postNotification(getApplicationContext(), file); } } stopForeground(Service.STOP_FOREGROUND_REMOVE); TraceUtils.cleanupOlderFiles(MIN_KEEP_COUNT, MIN_KEEP_AGE); } private Notification.Builder getBaseTraceurNotification() { Context context = getApplicationContext(); Notification.Builder notification = new Notification.Builder(this, Receiver.NOTIFICATION_CHANNEL_OTHER) .setSmallIcon(R.drawable.bugfood_icon) .setLocalOnly(true) .setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE) .setColor(context.getColor( com.android.internal.R.color.system_notification_accent_color)); if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LEANBACK)) { notification.extend(new Notification.TvExtender()); } return notification; } }
src/com/android/traceur/TraceService.java
GrapheneOS-Archive-platform_packages_apps_Traceur-2e6c52a
[ { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " prefs.getString(context.getString(R.string.pref_key_max_long_trace_size),\n context.getString(R.string.default_long_trace_size)));\n int maxLongTraceDuration = Integer.parseInt(\n prefs.getString(context.getString(R.string.pref_key_max_long_trace_duration),\n context.getString(R.string.default_long_trace_duration)));\n TraceService.startTracing(context, activeAvailableTags, bufferSize,\n appTracing, longTrace, maxLongTraceSize, maxLongTraceDuration);\n } else {\n TraceService.stopTracing(context);\n }", "score": 0.8846564888954163 }, { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " boolean debuggingDisallowed = userManager.hasUserRestriction(\n UserManager.DISALLOW_DEBUGGING_FEATURES);\n updateStorageProvider(context,\n developerOptionsEnabled && isAdminUser && !debuggingDisallowed);\n } else if (STOP_ACTION.equals(intent.getAction())) {\n prefs.edit().putBoolean(\n context.getString(R.string.pref_key_tracing_on), false).commit();\n updateTracing(context);\n } else if (OPEN_ACTION.equals(intent.getAction())) {\n context.sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));", "score": 0.8617533445358276 }, { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " context.startActivity(new Intent(context, MainActivity.class)\n .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));\n } else if (BUGREPORT_STARTED.equals(intent.getAction())) {\n // If stop_on_bugreport is set and attach_to_bugreport is not, stop tracing.\n // Otherwise, if attach_to_bugreport is set perfetto will end the session,\n // and we should not take action on the Traceur side.\n if (prefs.getBoolean(context.getString(R.string.pref_key_stop_on_bugreport), false) &&\n !prefs.getBoolean(context.getString(\n R.string.pref_key_attach_to_bugreport), true)) {\n Log.d(TAG, \"Bugreport started, ending trace.\");", "score": 0.858124315738678 }, { "filename": "src/com/android/traceur/InternalReceiver.java", "retrieved_chunk": "import android.preference.PreferenceManager;\npublic class InternalReceiver extends BroadcastReceiver {\n public static final String START_ACTION = \"com.android.traceur.START\";\n @Override\n public void onReceive(Context context, Intent intent) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n if (START_ACTION.equals(intent.getAction())) {\n prefs.edit().putBoolean(\n context.getString(R.string.pref_key_tracing_on), true).commit();\n Receiver.updateTracing(context);", "score": 0.8520277738571167 }, { "filename": "src/com/android/traceur/MainFragment.java", "retrieved_chunk": " findPreference(getString(R.string.pref_key_attach_to_bugreport)).setVisible(false);\n findPreference(getString(R.string.pref_key_stop_on_bugreport)).setVisible(true);\n // Sets long traces summary to the default in case Betterbug was removed.\n findPreference(getString(R.string.pref_key_long_traces))\n .setSummary(getString(R.string.long_traces_summary));\n }\n // Check if an activity exists to handle the trace_link_button intent. If not, hide the UI\n // element\n PackageManager packageManager = context.getPackageManager();\n Intent intent = buildTraceFileViewIntent();", "score": 0.8453789353370667 } ]
java
(TraceUtils.getOutputFilename(), false, false);
/* * Copyright (C) 2015 The Android Open Source Project * * 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.android.traceur; import android.system.Os; import android.util.Log; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Collection; import java.util.List; import java.util.TreeMap; import java.util.concurrent.TimeUnit; import perfetto.protos.DataSourceDescriptorOuterClass.DataSourceDescriptor; import perfetto.protos.FtraceDescriptorOuterClass.FtraceDescriptor.AtraceCategory; import perfetto.protos.TracingServiceStateOuterClass.TracingServiceState; import perfetto.protos.TracingServiceStateOuterClass.TracingServiceState.DataSource; /** * Utility functions for calling Perfetto */ public class PerfettoUtils implements TraceUtils.TraceEngine { static final String TAG = "Traceur"; public static final String NAME = "PERFETTO"; private static final String OUTPUT_EXTENSION = "perfetto-trace"; private static final String TEMP_DIR= "/data/local/traces/"; private static final String TEMP_TRACE_LOCATION = "/data/local/traces/.trace-in-progress.trace"; private static final String PERFETTO_TAG = "traceur"; private static final String MARKER = "PERFETTO_ARGUMENTS"; private static final int LIST_TIMEOUT_MS = 10000; private static final int STARTUP_TIMEOUT_MS = 10000; private static final int STOP_TIMEOUT_MS = 30000; private static final long MEGABYTES_TO_BYTES = 1024L * 1024L; private static final long MINUTES_TO_MILLISECONDS = 60L * 1000L; private static final String CAMERA_TAG = "camera"; private static final String GFX_TAG = "gfx"; private static final String MEMORY_TAG = "memory"; private static final String POWER_TAG = "power"; private static final String SCHED_TAG = "sched"; private static final String WEBVIEW_TAG = "webview"; public String getName() { return NAME; } public String getOutputExtension() { return OUTPUT_EXTENSION; } public boolean traceStart(Collection<String> tags, int bufferSizeKb, boolean apps, boolean attachToBugreport, boolean longTrace, int maxLongTraceSizeMb, int maxLongTraceDurationMinutes) { if (isTracingOn()) { Log.e(TAG, "Attempting to start perfetto trace but trace is already in progress"); return false; } else { // Ensure the temporary trace file is cleared. try { Files.deleteIfExists(Paths.get(TEMP_TRACE_LOCATION)); } catch (Exception e) { throw new RuntimeException(e); } } // The user chooses a per-CPU buffer size due to atrace limitations. // So we use this to ensure that we reserve the correctly-sized buffer. int numCpus = Runtime.getRuntime().availableProcessors(); // Build the perfetto config that will be passed on the command line. StringBuilder config = new StringBuilder() .append("write_into_file: true\n") // Ensure that we flush ftrace data every 30s even if cpus are idle. .append("flush_period_ms: 30000\n"); // If the user has flagged that in-progress trace sessions should be grabbed // during bugreports, and BetterBug is present. if (attachToBugreport) { config.append("bugreport_score: 500\n"); } // Indicates that perfetto should notify Traceur if the tracing session's status // changes. config.append("notify_traceur: true\n"); if (longTrace) { if (maxLongTraceSizeMb != 0) { config.append("max_file_size_bytes: " + (maxLongTraceSizeMb * MEGABYTES_TO_BYTES) + "\n"); } if (maxLongTraceDurationMinutes != 0) { config.append("duration_ms: " + (maxLongTraceDurationMinutes * MINUTES_TO_MILLISECONDS) + "\n"); } // Default value for long traces to write to file. config.append("file_write_period_ms: 1000\n"); } else { // For short traces, we don't write to the file. // So, always use the maximum value here: 7 days. config.append("file_write_period_ms: 604800000\n"); } config.append("incremental_state_config {\n") .append(" clear_period_ms: 15000\n") .append("} \n") // This is target_buffer: 0, which is used for ftrace and the ftrace-derived // android.gpu.memory. .append("buffers {\n") .append(" size_kb: " + bufferSizeKb * numCpus + "\n") .append(" fill_policy: RING_BUFFER\n") .append("} \n") // This is target_buffer: 1, which is used for additional data sources. .append("buffers {\n") .append(" size_kb: 2048\n") .append(" fill_policy: RING_BUFFER\n") .append("} \n") .append("data_sources {\n") .append(" config {\n") .append(" name: \"linux.ftrace\"\n") .append(" target_buffer: 0\n") .append(" ftrace_config {\n") .append(" symbolize_ksyms: true\n"); for (String tag : tags) { // Tags are expected to be only letters, numbers, and underscores. String cleanTag = tag.replaceAll("[^a-zA-Z0-9_]", ""); if (!cleanTag.equals(tag)) { Log.w(TAG, "Attempting to use an invalid tag: " + tag); } config.append(" atrace_categories: \"" + cleanTag + "\"\n"); } if (apps) { config.append(" atrace_apps: \"*\"\n"); } // Request a dense encoding of the common sched events (sched_switch, sched_waking). if (tags.contains(SCHED_TAG)) { config.append(" compact_sched {\n"); config.append(" enabled: true\n"); config.append(" }\n"); } // These parameters affect only the kernel trace buffer size and how // frequently it gets moved into the userspace buffer defined above. config.append(" buffer_size_kb: 8192\n") .append(" drain_period_ms: 1000\n") .append(" }\n") .append(" }\n") .append("}\n") .append(" \n"); // Captures initial counter values, updates are captured in ftrace. if (tags.contains(MEMORY_TAG) || tags.contains(GFX_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.gpu.memory\"\n") .append(" target_buffer: 0\n") .append(" }\n") .append("}\n"); } // For process association. If the memory tag is enabled, // poll periodically instead of just once at the beginning. config.append("data_sources {\n") .append(" config {\n") .append(" name: \"linux.process_stats\"\n") .append(" target_buffer: 1\n"); if (tags.contains(MEMORY_TAG)) { config.append(" process_stats_config {\n") .append(" proc_stats_poll_ms: 60000\n") .append(" }\n"); } config.append(" }\n") .append("} \n"); if (tags.contains(POWER_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.power\"\n") .append(" target_buffer: 1\n") .append(" android_power_config {\n"); if (longTrace) { config.append(" battery_poll_ms: 5000\n"); } else { config.append(" battery_poll_ms: 1000\n"); } config.append(" collect_power_rails: true\n") .append(" battery_counters: BATTERY_COUNTER_CAPACITY_PERCENT\n") .append(" battery_counters: BATTERY_COUNTER_CHARGE\n") .append(" battery_counters: BATTERY_COUNTER_CURRENT\n") .append(" }\n") .append(" }\n") .append("}\n"); } if (tags.contains(MEMORY_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.sys_stats\"\n") .append(" target_buffer: 1\n") .append(" sys_stats_config {\n") .append(" vmstat_period_ms: 1000\n") .append(" }\n") .append(" }\n") .append("}\n"); } if (tags.contains(GFX_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.surfaceflinger.frametimeline\"\n") .append(" }\n") .append("}\n"); } if (tags.contains(CAMERA_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.hardware.camera\"\n") .append(" target_buffer: 1\n") .append(" }\n") .append("}\n"); } // Also enable Chrome events when the WebView tag is enabled. if (tags.contains(WEBVIEW_TAG)) { String chromeTraceConfig = "{" + "\\\"record_mode\\\":\\\"record-continuously\\\"," + "\\\"included_categories\\\":[\\\"*\\\"]" + "}"; config.append("data_sources: {\n") .append(" config {\n") .append(" name: \"org.chromium.trace_event\"\n") .append(" chrome_config {\n") .append(" trace_config: \"" + chromeTraceConfig + "\"\n") .append(" }\n") .append(" }\n") .append("}\n") .append("data_sources: {\n") .append(" config {\n") .append(" name: \"org.chromium.trace_metadata\"\n") .append(" chrome_config {\n") .append(" trace_config: \"" + chromeTraceConfig + "\"\n") .append(" }\n") .append(" }\n") .append("}\n"); } String configString = config.toString(); // If the here-doc ends early, within the config string, exit immediately. // This should never happen. if (configString.contains(MARKER)) { throw new RuntimeException("The arguments to the Perfetto command are malformed."); } String cmd = "perfetto --detach=" + PERFETTO_TAG + " -o " + TEMP_TRACE_LOCATION + " -c - --txt" + " <<" + MARKER +"\n" + configString + "\n" + MARKER; Log.v(TAG, "Starting perfetto trace."); try { Process process
= TraceUtils.execWithTimeout(cmd, TEMP_DIR, STARTUP_TIMEOUT_MS);
if (process == null) { return false; } else if (process.exitValue() != 0) { Log.e(TAG, "perfetto traceStart failed with: " + process.exitValue()); return false; } } catch (Exception e) { throw new RuntimeException(e); } Log.v(TAG, "perfetto traceStart succeeded!"); return true; } public void traceStop() { Log.v(TAG, "Stopping perfetto trace."); if (!isTracingOn()) { Log.w(TAG, "No trace appears to be in progress. Stopping perfetto trace may not work."); } String cmd = "perfetto --stop --attach=" + PERFETTO_TAG; try { Process process = TraceUtils.execWithTimeout(cmd, null, STOP_TIMEOUT_MS); if (process != null && process.exitValue() != 0) { Log.e(TAG, "perfetto traceStop failed with: " + process.exitValue()); } } catch (Exception e) { throw new RuntimeException(e); } } public boolean traceDump(File outFile) { traceStop(); // Short-circuit if a trace was not stopped. if (isTracingOn()) { Log.e(TAG, "Trace was not stopped successfully, aborting trace dump."); return false; } // Short-circuit if the file we're trying to dump to doesn't exist. if (!Files.exists(Paths.get(TEMP_TRACE_LOCATION))) { Log.e(TAG, "In-progress trace file doesn't exist, aborting trace dump."); return false; } Log.v(TAG, "Saving perfetto trace to " + outFile); try { Os.rename(TEMP_TRACE_LOCATION, outFile.getCanonicalPath()); } catch (Exception e) { throw new RuntimeException(e); } outFile.setReadable(true, false); // (readable, ownerOnly) outFile.setWritable(true, false); // (readable, ownerOnly) return true; } public boolean isTracingOn() { String cmd = "perfetto --is_detached=" + PERFETTO_TAG; try { Process process = TraceUtils.exec(cmd); // 0 represents a detached process exists with this name // 2 represents no detached process with this name // 1 (or other error code) represents an error int result = process.waitFor(); if (result == 0) { return true; } else if (result == 2) { return false; } else { throw new RuntimeException("Perfetto error: " + result); } } catch (Exception e) { throw new RuntimeException(e); } } public static TreeMap<String,String> perfettoListCategories() { String cmd = "perfetto --query-raw"; Log.v(TAG, "Listing tags: " + cmd); try { TreeMap<String, String> result = new TreeMap<>(); // execWithTimeout() cannot be used because stdout must be consumed before the process // is terminated. Process perfetto = TraceUtils.exec(cmd, null, false); TracingServiceState serviceState = TracingServiceState.parseFrom(perfetto.getInputStream()); // Destroy the perfetto process if it times out. if (!perfetto.waitFor(LIST_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { Log.e(TAG, "perfettoListCategories timed out after " + LIST_TIMEOUT_MS + " ms."); perfetto.destroyForcibly(); return result; } // The perfetto process completed and failed, but does not need to be destroyed. if (perfetto.exitValue() != 0) { Log.e(TAG, "perfettoListCategories failed with: " + perfetto.exitValue()); } List<AtraceCategory> categories = null; for (DataSource dataSource : serviceState.getDataSourcesList()) { DataSourceDescriptor dataSrcDescriptor = dataSource.getDsDescriptor(); if (dataSrcDescriptor.getName().equals("linux.ftrace")){ categories = dataSrcDescriptor.getFtraceDescriptor().getAtraceCategoriesList(); break; } } if (categories != null) { for (AtraceCategory category : categories) { result.put(category.getName(), category.getDescription()); } } return result; } catch (Exception e) { throw new RuntimeException(e); } } }
src/com/android/traceur/PerfettoUtils.java
GrapheneOS-Archive-platform_packages_apps_Traceur-2e6c52a
[ { "filename": "src/com/android/traceur/AtraceUtils.java", "retrieved_chunk": " Log.v(TAG, \"Starting async atrace: \" + cmd);\n try {\n Process atrace = TraceUtils.exec(cmd);\n if (atrace.waitFor() != 0) {\n Log.e(TAG, \"atraceStart failed with: \" + atrace.exitValue());\n return false;\n }\n } catch (Exception e) {\n throw new RuntimeException(e);\n }", "score": 0.8542104363441467 }, { "filename": "src/com/android/traceur/TraceUtils.java", "retrieved_chunk": " // To change Traceur to use atrace to collect traces,\n // change mTraceEngine to point to AtraceUtils().\n private static TraceEngine mTraceEngine = new PerfettoUtils();\n private static final Runtime RUNTIME = Runtime.getRuntime();\n private static final int PROCESS_TIMEOUT_MS = 30000; // 30 seconds\n public interface TraceEngine {\n public String getName();\n public String getOutputExtension();\n public boolean traceStart(Collection<String> tags, int bufferSizeKb, boolean apps,\n boolean attachToBugreport, boolean longTrace, int maxLongTraceSizeMb,", "score": 0.8455241918563843 }, { "filename": "src/com/android/traceur/AtraceUtils.java", "retrieved_chunk": " } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n public boolean traceDump(File outFile) {\n String cmd = \"atrace --async_stop -z -c -o \" + outFile;\n Log.v(TAG, \"Dumping async atrace: \" + cmd);\n try {\n Process atrace = TraceUtils.exec(cmd);\n if (atrace.waitFor() != 0) {", "score": 0.8405007719993591 }, { "filename": "src/com/android/traceur/TraceUtils.java", "retrieved_chunk": " Process rm = exec(cmd);\n if (rm.waitFor() != 0) {\n Log.e(TAG, \"clearSavedTraces failed with: \" + rm.exitValue());\n }\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n public static Process exec(String cmd) throws IOException {\n return exec(cmd, null);", "score": 0.8355783224105835 }, { "filename": "src/com/android/traceur/AtraceUtils.java", "retrieved_chunk": " public String getOutputExtension() {\n return OUTPUT_EXTENSION;\n }\n /* Note: attachToBugreport, longTrace, maxLongTrace* parameters are ignored in atrace mode. */\n public boolean traceStart(Collection<String> tags, int bufferSizeKb, boolean apps,\n boolean attachToBugreport, boolean longTrace, int maxLongTraceSizeMb,\n int maxLongTraceDurationMinutes) {\n String appParameter = apps ? \"-a '*' \" : \"\";\n String cmd = \"atrace --async_start -c -b \" + bufferSizeKb + \" \"\n + appParameter + TextUtils.join(\" \", tags);", "score": 0.8235606551170349 } ]
java
= TraceUtils.execWithTimeout(cmd, TEMP_DIR, STARTUP_TIMEOUT_MS);
/* * Copyright (C) 2015 The Android Open Source Project * * 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.android.traceur; import android.sysprop.TraceProperties; import android.text.TextUtils; import android.util.Log; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collection; import java.util.List; import com.android.traceur.TraceUtils.Streamer; /** * Utility functions for calling atrace */ public class AtraceUtils implements TraceUtils.TraceEngine { static final String TAG = "Traceur"; private static final String DEBUG_TRACING_FILE = "/sys/kernel/debug/tracing/tracing_on"; private static final String TRACING_FILE = "/sys/kernel/tracing/tracing_on"; public static String NAME = "ATRACE"; private static String OUTPUT_EXTENSION = "ctrace"; public String getName() { return NAME; } public String getOutputExtension() { return OUTPUT_EXTENSION; } /* Note: attachToBugreport, longTrace, maxLongTrace* parameters are ignored in atrace mode. */ public boolean traceStart(Collection<String> tags, int bufferSizeKb, boolean apps, boolean attachToBugreport, boolean longTrace, int maxLongTraceSizeMb, int maxLongTraceDurationMinutes) { String appParameter = apps ? "-a '*' " : ""; String cmd = "atrace --async_start -c -b " + bufferSizeKb + " " + appParameter + TextUtils.join(" ", tags); Log.v(TAG, "Starting async atrace: " + cmd); try { Process atrace = TraceUtils.exec(cmd); if (atrace.waitFor() != 0) { Log.e(TAG, "atraceStart failed with: " + atrace.exitValue()); return false; } } catch (Exception e) { throw new RuntimeException(e); } return true; } public void traceStop() { String cmd = "atrace --async_stop > /dev/null"; Log.v(TAG, "Stopping async atrace: " + cmd); try { Process atrace = TraceUtils.exec(cmd); if (atrace.waitFor() != 0) { Log.e(TAG, "atraceStop failed with: " + atrace.exitValue()); } } catch (Exception e) { throw new RuntimeException(e); } } public boolean traceDump(File outFile) { String cmd = "atrace --async_stop -z -c -o " + outFile; Log.v(TAG, "Dumping async atrace: " + cmd); try { Process atrace = TraceUtils.exec(cmd); if (atrace.waitFor() != 0) { Log.e(TAG, "atraceDump failed with: " + atrace.exitValue()); return false; } Process
ps = TraceUtils.exec("ps -AT", null, false);
new Streamer("atraceDump:ps:stdout", ps.getInputStream(), new FileOutputStream(outFile, true /* append */)); if (ps.waitFor() != 0) { Log.e(TAG, "atraceDump:ps failed with: " + ps.exitValue()); return false; } // Set the new file world readable to allow it to be adb pulled. outFile.setReadable(true, false); // (readable, ownerOnly) outFile.setWritable(true, false); // (readable, ownerOnly) } catch (Exception e) { throw new RuntimeException(e); } return true; } public boolean isTracingOn() { boolean userInitiatedTracingFlag = TraceProperties.user_initiated().orElse(false); if (!userInitiatedTracingFlag) { return false; } boolean tracingOnFlag = false; try { List<String> tracingOnContents; Path debugTracingOnPath = Paths.get(DEBUG_TRACING_FILE); Path tracingOnPath = Paths.get(TRACING_FILE); if (Files.isReadable(debugTracingOnPath)) { tracingOnContents = Files.readAllLines(debugTracingOnPath); } else if (Files.isReadable(tracingOnPath)) { tracingOnContents = Files.readAllLines(tracingOnPath); } else { return false; } tracingOnFlag = !tracingOnContents.get(0).equals("0"); } catch (IOException e) { throw new RuntimeException(e); } return userInitiatedTracingFlag && tracingOnFlag; } }
src/com/android/traceur/AtraceUtils.java
GrapheneOS-Archive-platform_packages_apps_Traceur-2e6c52a
[ { "filename": "src/com/android/traceur/PerfettoUtils.java", "retrieved_chunk": " try {\n Process process = TraceUtils.execWithTimeout(cmd, null, STOP_TIMEOUT_MS);\n if (process != null && process.exitValue() != 0) {\n Log.e(TAG, \"perfetto traceStop failed with: \" + process.exitValue());\n }\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n public boolean traceDump(File outFile) {", "score": 0.8993610739707947 }, { "filename": "src/com/android/traceur/PerfettoUtils.java", "retrieved_chunk": " try {\n Process process = TraceUtils.execWithTimeout(cmd, TEMP_DIR, STARTUP_TIMEOUT_MS);\n if (process == null) {\n return false;\n } else if (process.exitValue() != 0) {\n Log.e(TAG, \"perfetto traceStart failed with: \" + process.exitValue());\n return false;\n }\n } catch (Exception e) {\n throw new RuntimeException(e);", "score": 0.8745201826095581 }, { "filename": "src/com/android/traceur/PerfettoUtils.java", "retrieved_chunk": " }\n Log.v(TAG, \"perfetto traceStart succeeded!\");\n return true;\n }\n public void traceStop() {\n Log.v(TAG, \"Stopping perfetto trace.\");\n if (!isTracingOn()) {\n Log.w(TAG, \"No trace appears to be in progress. Stopping perfetto trace may not work.\");\n }\n String cmd = \"perfetto --stop --attach=\" + PERFETTO_TAG;", "score": 0.8639251589775085 }, { "filename": "src/com/android/traceur/PerfettoUtils.java", "retrieved_chunk": " traceStop();\n // Short-circuit if a trace was not stopped.\n if (isTracingOn()) {\n Log.e(TAG, \"Trace was not stopped successfully, aborting trace dump.\");\n return false;\n }\n // Short-circuit if the file we're trying to dump to doesn't exist.\n if (!Files.exists(Paths.get(TEMP_TRACE_LOCATION))) {\n Log.e(TAG, \"In-progress trace file doesn't exist, aborting trace dump.\");\n return false;", "score": 0.8631511926651001 }, { "filename": "src/com/android/traceur/PerfettoUtils.java", "retrieved_chunk": " }\n public boolean isTracingOn() {\n String cmd = \"perfetto --is_detached=\" + PERFETTO_TAG;\n try {\n Process process = TraceUtils.exec(cmd);\n // 0 represents a detached process exists with this name\n // 2 represents no detached process with this name\n // 1 (or other error code) represents an error\n int result = process.waitFor();\n if (result == 0) {", "score": 0.8476435542106628 } ]
java
ps = TraceUtils.exec("ps -AT", null, false);
/* * Copyright (C) 2015 The Android Open Source Project * * 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.android.traceur; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.UserManager; import android.preference.PreferenceManager; import android.provider.Settings; import android.util.EventLog; import android.util.Log; public class StopTraceService extends TraceService { private static final String TAG = "Traceur"; public StopTraceService() { super("StopTraceService"); setIntentRedelivery(true); } /* If we stop a trace using this entrypoint, we must also reset the preference and the * Quick Settings UI, since this may be the only indication that the user wants to stop the * trace. */ @Override public void onHandleIntent(Intent intent) { Context context = getApplicationContext(); // Checks that developer options are enabled and the user is an admin before continuing. boolean developerOptionsEnabled = Settings.Global.getInt(context.getContentResolver(), Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) != 0; if (!developerOptionsEnabled) { // Refer to b/204992293. EventLog.writeEvent(0x534e4554, "204992293", -1, ""); return; } UserManager userManager = context.getSystemService(UserManager.class); boolean isAdminUser = userManager.isAdminUser(); boolean debuggingDisallowed = userManager.hasUserRestriction( UserManager.DISALLOW_DEBUGGING_FEATURES); if (!isAdminUser || debuggingDisallowed) { return; } // Ensures that only intents that pertain to stopping a trace and need to be accessed from // outside Traceur are passed to TraceService through StopTraceService. String intentAction = intent.getAction(); if (!intentAction.equals(TraceService.INTENT_ACTION_NOTIFY_SESSION_STOLEN) && !intentAction.equals(TraceService.INTENT_ACTION_NOTIFY_SESSION_STOPPED)) { return; } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); boolean prefsTracingOn = prefs.getBoolean(context.getString(R.string.pref_key_tracing_on), false); // If the user thinks tracing is off and the trace processor agrees, we have no work to do. // We must still start a foreground service, but let's log as an FYI. if (!
prefsTracingOn && !TraceUtils.isTracingOn()) {
Log.i(TAG, "StopTraceService does not see a trace to stop."); } PreferenceManager.getDefaultSharedPreferences(context) .edit().putBoolean(context.getString(R.string.pref_key_tracing_on), false).commit(); context.sendBroadcast(new Intent(MainFragment.ACTION_REFRESH_TAGS)); QsService.updateTile(); super.onHandleIntent(intent); } }
src/com/android/traceur/StopTraceService.java
GrapheneOS-Archive-platform_packages_apps_Traceur-2e6c52a
[ { "filename": "src/com/android/traceur/TraceService.java", "retrieved_chunk": " stopForeground(Service.STOP_FOREGROUND_DETACH);\n } else {\n // Starting the trace was unsuccessful, so ensure that tracing\n // is stopped and the preference is reset.\n TraceUtils.traceStop();\n prefs.edit().putBoolean(context.getString(R.string.pref_key_tracing_on),\n false).commit();\n QsService.updateTile();\n stopForeground(Service.STOP_FOREGROUND_REMOVE);\n }", "score": 0.890978217124939 }, { "filename": "src/com/android/traceur/TraceService.java", "retrieved_chunk": " intent.setAction(INTENT_ACTION_STOP_TRACING);\n context.startForegroundService(intent);\n }\n // Silently stops a trace without saving it. This is intended to be called when tracing is no\n // longer allowed, i.e. if developer options are turned off while tracing. The usual method of\n // stopping a trace via intent, stopTracing(), will not work because intents cannot be received\n // when developer options are disabled.\n static void stopTracingWithoutSaving(final Context context) {\n NotificationManager notificationManager =\n context.getSystemService(NotificationManager.class);", "score": 0.8885270357131958 }, { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " prefs.edit().putBoolean(context.getString(R.string.pref_key_tracing_on), false).commit();\n updateTracing(context);\n }\n }\n }\n /*\n * Updates the current tracing state based on the current state of preferences.\n */\n public static void updateTracing(Context context) {\n updateTracing(context, false);", "score": 0.8828717470169067 }, { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " boolean debuggingDisallowed = userManager.hasUserRestriction(\n UserManager.DISALLOW_DEBUGGING_FEATURES);\n updateStorageProvider(context,\n developerOptionsEnabled && isAdminUser && !debuggingDisallowed);\n } else if (STOP_ACTION.equals(intent.getAction())) {\n prefs.edit().putBoolean(\n context.getString(R.string.pref_key_tracing_on), false).commit();\n updateTracing(context);\n } else if (OPEN_ACTION.equals(intent.getAction())) {\n context.sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));", "score": 0.8806455135345459 }, { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " SharedPreferences prefs =\n PreferenceManager.getDefaultSharedPreferences(context);\n prefs.edit().putBoolean(\n context.getString(R.string.pref_key_quick_setting), false)\n .commit();\n updateQuickSettings(context);\n // Stop an ongoing trace if one exists.\n if (TraceUtils.isTracingOn()) {\n TraceService.stopTracingWithoutSaving(context);\n }", "score": 0.8789796829223633 } ]
java
prefsTracingOn && !TraceUtils.isTracingOn()) {
/* * Copyright (C) 2015 The Android Open Source Project * * 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.android.traceur; import android.annotation.Nullable; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.icu.text.MessageFormat; import android.net.Uri; import android.os.Bundle; import androidx.preference.MultiSelectListPreference; import androidx.preference.ListPreference; import androidx.preference.Preference; import androidx.preference.PreferenceFragment; import androidx.preference.PreferenceManager; import androidx.preference.SwitchPreference; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Menu; import android.view.MenuInflater; import android.widget.Toast; import com.android.settingslib.HelpUtils; import java.util.ArrayList; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; public class MainFragment extends PreferenceFragment { static final String TAG = TraceUtils.TAG; public static final String ACTION_REFRESH_TAGS = "com.android.traceur.REFRESH_TAGS"; private static final String BETTERBUG_PACKAGE_NAME = "com.google.android.apps.internal.betterbug"; private static final String ROOT_MIME_TYPE = "vnd.android.document/root"; private static final String STORAGE_URI = "content://com.android.traceur.documents/root"; private SwitchPreference mTracingOn; private AlertDialog mAlertDialog; private SharedPreferences mPrefs; private MultiSelectListPreference mTags; private boolean mRefreshing; private BroadcastReceiver mRefreshReceiver; OnSharedPreferenceChangeListener mSharedPreferenceChangeListener = new OnSharedPreferenceChangeListener () { public void onSharedPreferenceChanged( SharedPreferences sharedPreferences, String key) { refreshUi(); } }; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Receiver.updateDeveloperOptionsWatcher(getContext()); mPrefs = PreferenceManager.getDefaultSharedPreferences( getActivity().getApplicationContext()); mTracingOn = (SwitchPreference) findPreference(getActivity().getString(R.string.pref_key_tracing_on)); mTracingOn.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { Receiver.updateTracing(getContext()); return true; } }); mTags = (MultiSelectListPreference) findPreference(getContext().getString(R.string.pref_key_tags)); mTags.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { if (mRefreshing) { return true; } Set<String> set = (Set<String>) newValue; TreeMap<String, String> available = TraceUtils.listCategories(); ArrayList<String> clean = new ArrayList<>(set.size()); for (String s : set) { if (available.containsKey(s)) { clean.add(s); } } set.clear(); set.addAll(clean); return true; } }); findPreference("restore_default_tags").setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { refreshUi(/* restoreDefaultTags =*/ true); Toast.makeText(getContext(), getContext().getString(R.string.default_categories_restored), Toast.LENGTH_SHORT).show(); return true; } }); findPreference(getString(R.string.pref_key_quick_setting)) .setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { Receiver.updateQuickSettings(getContext()); return true; } }); findPreference("clear_saved_traces").setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { new AlertDialog.Builder(getContext()) .setTitle(R.string.clear_saved_traces_question) .setMessage(R.string.all_traces_will_be_deleted) .setPositiveButton(R.string.clear, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) {
TraceUtils.clearSavedTraces();
} }) .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create() .show(); return true; } }); findPreference("trace_link_button") .setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { Intent intent = buildTraceFileViewIntent(); try { startActivity(intent); } catch (ActivityNotFoundException e) { return false; } return true; } }); // This disables "Attach to bugreports" when long traces are enabled. This cannot be done in // main.xml because there are some other settings there that are enabled with long traces. SwitchPreference attachToBugreport = findPreference( getString(R.string.pref_key_attach_to_bugreport)); findPreference(getString(R.string.pref_key_long_traces)) .setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { if (((SwitchPreference) preference).isChecked()) { attachToBugreport.setEnabled(false); } else { attachToBugreport.setEnabled(true); } return true; } }); refreshUi(); mRefreshReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { refreshUi(); } }; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { setHasOptionsMenu(true); return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onStart() { super.onStart(); getPreferenceScreen().getSharedPreferences() .registerOnSharedPreferenceChangeListener(mSharedPreferenceChangeListener); getActivity().registerReceiver(mRefreshReceiver, new IntentFilter(ACTION_REFRESH_TAGS)); Receiver.updateTracing(getContext()); } @Override public void onStop() { getPreferenceScreen().getSharedPreferences() .unregisterOnSharedPreferenceChangeListener(mSharedPreferenceChangeListener); getActivity().unregisterReceiver(mRefreshReceiver); if (mAlertDialog != null) { mAlertDialog.cancel(); mAlertDialog = null; } super.onStop(); } @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { addPreferencesFromResource(R.xml.main); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { HelpUtils.prepareHelpMenuItem(getActivity(), menu, R.string.help_url, this.getClass().getName()); } private Intent buildTraceFileViewIntent() { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse(STORAGE_URI), ROOT_MIME_TYPE); return intent; } private void refreshUi() { refreshUi(/* restoreDefaultTags =*/ false); } /* * Refresh the preferences UI to make sure it reflects the current state of the preferences and * system. */ private void refreshUi(boolean restoreDefaultTags) { Context context = getContext(); // Make sure the Record Trace toggle matches the preference value. mTracingOn.setChecked(mTracingOn.getPreferenceManager().getSharedPreferences().getBoolean( mTracingOn.getKey(), false)); SwitchPreference stopOnReport = (SwitchPreference) findPreference(getString(R.string.pref_key_stop_on_bugreport)); stopOnReport.setChecked(mPrefs.getBoolean(stopOnReport.getKey(), false)); // Update category list to match the categories available on the system. Set<Entry<String, String>> availableTags = TraceUtils.listCategories().entrySet(); ArrayList<String> entries = new ArrayList<String>(availableTags.size()); ArrayList<String> values = new ArrayList<String>(availableTags.size()); for (Entry<String, String> entry : availableTags) { entries.add(entry.getKey() + ": " + entry.getValue()); values.add(entry.getKey()); } mRefreshing = true; try { mTags.setEntries(entries.toArray(new String[0])); mTags.setEntryValues(values.toArray(new String[0])); if (restoreDefaultTags || !mPrefs.contains(context.getString(R.string.pref_key_tags))) { mTags.setValues(Receiver.getDefaultTagList()); } } finally { mRefreshing = false; } // Update subtitles on this screen. Set<String> categories = mTags.getValues(); MessageFormat msgFormat = new MessageFormat( getResources().getString(R.string.num_categories_selected), Locale.getDefault()); Map<String, Object> arguments = new HashMap<>(); arguments.put("count", categories.size()); mTags.setSummary(Receiver.getDefaultTagList().equals(categories) ? context.getString(R.string.default_categories) : msgFormat.format(arguments)); ListPreference bufferSize = (ListPreference)findPreference( context.getString(R.string.pref_key_buffer_size)); bufferSize.setSummary(bufferSize.getEntry()); // If we are not using the Perfetto trace backend, // hide the unsupported preferences. if (TraceUtils.currentTraceEngine().equals(PerfettoUtils.NAME)) { ListPreference maxLongTraceSize = (ListPreference)findPreference( context.getString(R.string.pref_key_max_long_trace_size)); maxLongTraceSize.setSummary(maxLongTraceSize.getEntry()); ListPreference maxLongTraceDuration = (ListPreference)findPreference( context.getString(R.string.pref_key_max_long_trace_duration)); maxLongTraceDuration.setSummary(maxLongTraceDuration.getEntry()); } else { Preference longTraceCategory = findPreference("long_trace_category"); if (longTraceCategory != null) { getPreferenceScreen().removePreference(longTraceCategory); } } // Check if BetterBug is installed to see if Traceur should display either the toggle for // 'attach_to_bugreport' or 'stop_on_bugreport'. try { context.getPackageManager().getPackageInfo(BETTERBUG_PACKAGE_NAME, PackageManager.MATCH_SYSTEM_ONLY); findPreference(getString(R.string.pref_key_attach_to_bugreport)).setVisible(true); findPreference(getString(R.string.pref_key_stop_on_bugreport)).setVisible(false); // Changes the long traces summary to add that they cannot be attached to bugreports. findPreference(getString(R.string.pref_key_long_traces)) .setSummary(getString(R.string.long_traces_summary_betterbug)); } catch (PackageManager.NameNotFoundException e) { // attach_to_bugreport must be disabled here because it's true by default. mPrefs.edit().putBoolean( getString(R.string.pref_key_attach_to_bugreport), false).commit(); findPreference(getString(R.string.pref_key_attach_to_bugreport)).setVisible(false); findPreference(getString(R.string.pref_key_stop_on_bugreport)).setVisible(true); // Sets long traces summary to the default in case Betterbug was removed. findPreference(getString(R.string.pref_key_long_traces)) .setSummary(getString(R.string.long_traces_summary)); } // Check if an activity exists to handle the trace_link_button intent. If not, hide the UI // element PackageManager packageManager = context.getPackageManager(); Intent intent = buildTraceFileViewIntent(); if (intent.resolveActivity(packageManager) == null) { findPreference("trace_link_button").setVisible(false); } } }
src/com/android/traceur/MainFragment.java
GrapheneOS-Archive-platform_packages_apps_Traceur-2e6c52a
[ { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " SharedPreferences prefs =\n PreferenceManager.getDefaultSharedPreferences(context);\n prefs.edit().putBoolean(\n context.getString(R.string.pref_key_quick_setting), false)\n .commit();\n updateQuickSettings(context);\n // Stop an ongoing trace if one exists.\n if (TraceUtils.isTracingOn()) {\n TraceService.stopTracingWithoutSaving(context);\n }", "score": 0.8369700908660889 }, { "filename": "src/com/android/traceur/QsService.java", "retrieved_chunk": " SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);\n boolean tracingOn = prefs.getBoolean(getString(R.string.pref_key_tracing_on), false);\n String titleString = getString(tracingOn ? R.string.stop_tracing: R.string.record_trace);\n getQsTile().setIcon(Icon.createWithResource(this, R.drawable.bugfood_icon));\n getQsTile().setState(tracingOn ? Tile.STATE_ACTIVE : Tile.STATE_INACTIVE);\n getQsTile().setLabel(titleString);\n getQsTile().updateTile();\n Receiver.updateDeveloperOptionsWatcher(this);\n }\n /** When we click the tile, toggle tracing state.", "score": 0.8362917900085449 }, { "filename": "src/com/android/traceur/QsService.java", "retrieved_chunk": " * If tracing is being turned off, dump and offer to share. */\n @Override\n public void onClick() {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);\n boolean newTracingState = !prefs.getBoolean(getString(R.string.pref_key_tracing_on), false);\n prefs.edit().putBoolean(getString(R.string.pref_key_tracing_on), newTracingState).commit();\n Receiver.updateTracing(this);\n }\n}", "score": 0.832463264465332 }, { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " prefs.edit().putBoolean(context.getString(R.string.pref_key_tracing_on), false).commit();\n updateTracing(context);\n }\n }\n }\n /*\n * Updates the current tracing state based on the current state of preferences.\n */\n public static void updateTracing(Context context) {\n updateTracing(context, false);", "score": 0.8247370719909668 }, { "filename": "src/com/android/traceur/StopTraceService.java", "retrieved_chunk": " SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n boolean prefsTracingOn =\n prefs.getBoolean(context.getString(R.string.pref_key_tracing_on), false);\n // If the user thinks tracing is off and the trace processor agrees, we have no work to do.\n // We must still start a foreground service, but let's log as an FYI.\n if (!prefsTracingOn && !TraceUtils.isTracingOn()) {\n Log.i(TAG, \"StopTraceService does not see a trace to stop.\");\n }\n PreferenceManager.getDefaultSharedPreferences(context)\n .edit().putBoolean(context.getString(R.string.pref_key_tracing_on),", "score": 0.8176960945129395 } ]
java
TraceUtils.clearSavedTraces();
/* * Copyright (C) 2015 The Android Open Source Project * * 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.android.traceur; import android.system.Os; import android.util.Log; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Collection; import java.util.List; import java.util.TreeMap; import java.util.concurrent.TimeUnit; import perfetto.protos.DataSourceDescriptorOuterClass.DataSourceDescriptor; import perfetto.protos.FtraceDescriptorOuterClass.FtraceDescriptor.AtraceCategory; import perfetto.protos.TracingServiceStateOuterClass.TracingServiceState; import perfetto.protos.TracingServiceStateOuterClass.TracingServiceState.DataSource; /** * Utility functions for calling Perfetto */ public class PerfettoUtils implements TraceUtils.TraceEngine { static final String TAG = "Traceur"; public static final String NAME = "PERFETTO"; private static final String OUTPUT_EXTENSION = "perfetto-trace"; private static final String TEMP_DIR= "/data/local/traces/"; private static final String TEMP_TRACE_LOCATION = "/data/local/traces/.trace-in-progress.trace"; private static final String PERFETTO_TAG = "traceur"; private static final String MARKER = "PERFETTO_ARGUMENTS"; private static final int LIST_TIMEOUT_MS = 10000; private static final int STARTUP_TIMEOUT_MS = 10000; private static final int STOP_TIMEOUT_MS = 30000; private static final long MEGABYTES_TO_BYTES = 1024L * 1024L; private static final long MINUTES_TO_MILLISECONDS = 60L * 1000L; private static final String CAMERA_TAG = "camera"; private static final String GFX_TAG = "gfx"; private static final String MEMORY_TAG = "memory"; private static final String POWER_TAG = "power"; private static final String SCHED_TAG = "sched"; private static final String WEBVIEW_TAG = "webview"; public String getName() { return NAME; } public String getOutputExtension() { return OUTPUT_EXTENSION; } public boolean traceStart(Collection<String> tags, int bufferSizeKb, boolean apps, boolean attachToBugreport, boolean longTrace, int maxLongTraceSizeMb, int maxLongTraceDurationMinutes) { if (isTracingOn()) { Log.e(TAG, "Attempting to start perfetto trace but trace is already in progress"); return false; } else { // Ensure the temporary trace file is cleared. try { Files.deleteIfExists(Paths.get(TEMP_TRACE_LOCATION)); } catch (Exception e) { throw new RuntimeException(e); } } // The user chooses a per-CPU buffer size due to atrace limitations. // So we use this to ensure that we reserve the correctly-sized buffer. int numCpus = Runtime.getRuntime().availableProcessors(); // Build the perfetto config that will be passed on the command line. StringBuilder config = new StringBuilder() .append("write_into_file: true\n") // Ensure that we flush ftrace data every 30s even if cpus are idle. .append("flush_period_ms: 30000\n"); // If the user has flagged that in-progress trace sessions should be grabbed // during bugreports, and BetterBug is present. if (attachToBugreport) { config.append("bugreport_score: 500\n"); } // Indicates that perfetto should notify Traceur if the tracing session's status // changes. config.append("notify_traceur: true\n"); if (longTrace) { if (maxLongTraceSizeMb != 0) { config.append("max_file_size_bytes: " + (maxLongTraceSizeMb * MEGABYTES_TO_BYTES) + "\n"); } if (maxLongTraceDurationMinutes != 0) { config.append("duration_ms: " + (maxLongTraceDurationMinutes * MINUTES_TO_MILLISECONDS) + "\n"); } // Default value for long traces to write to file. config.append("file_write_period_ms: 1000\n"); } else { // For short traces, we don't write to the file. // So, always use the maximum value here: 7 days. config.append("file_write_period_ms: 604800000\n"); } config.append("incremental_state_config {\n") .append(" clear_period_ms: 15000\n") .append("} \n") // This is target_buffer: 0, which is used for ftrace and the ftrace-derived // android.gpu.memory. .append("buffers {\n") .append(" size_kb: " + bufferSizeKb * numCpus + "\n") .append(" fill_policy: RING_BUFFER\n") .append("} \n") // This is target_buffer: 1, which is used for additional data sources. .append("buffers {\n") .append(" size_kb: 2048\n") .append(" fill_policy: RING_BUFFER\n") .append("} \n") .append("data_sources {\n") .append(" config {\n") .append(" name: \"linux.ftrace\"\n") .append(" target_buffer: 0\n") .append(" ftrace_config {\n") .append(" symbolize_ksyms: true\n"); for (String tag : tags) { // Tags are expected to be only letters, numbers, and underscores. String cleanTag = tag.replaceAll("[^a-zA-Z0-9_]", ""); if (!cleanTag.equals(tag)) { Log.w(TAG, "Attempting to use an invalid tag: " + tag); } config.append(" atrace_categories: \"" + cleanTag + "\"\n"); } if (apps) { config.append(" atrace_apps: \"*\"\n"); } // Request a dense encoding of the common sched events (sched_switch, sched_waking). if (tags.contains(SCHED_TAG)) { config.append(" compact_sched {\n"); config.append(" enabled: true\n"); config.append(" }\n"); } // These parameters affect only the kernel trace buffer size and how // frequently it gets moved into the userspace buffer defined above. config.append(" buffer_size_kb: 8192\n") .append(" drain_period_ms: 1000\n") .append(" }\n") .append(" }\n") .append("}\n") .append(" \n"); // Captures initial counter values, updates are captured in ftrace. if (tags.contains(MEMORY_TAG) || tags.contains(GFX_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.gpu.memory\"\n") .append(" target_buffer: 0\n") .append(" }\n") .append("}\n"); } // For process association. If the memory tag is enabled, // poll periodically instead of just once at the beginning. config.append("data_sources {\n") .append(" config {\n") .append(" name: \"linux.process_stats\"\n") .append(" target_buffer: 1\n"); if (tags.contains(MEMORY_TAG)) { config.append(" process_stats_config {\n") .append(" proc_stats_poll_ms: 60000\n") .append(" }\n"); } config.append(" }\n") .append("} \n"); if (tags.contains(POWER_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.power\"\n") .append(" target_buffer: 1\n") .append(" android_power_config {\n"); if (longTrace) { config.append(" battery_poll_ms: 5000\n"); } else { config.append(" battery_poll_ms: 1000\n"); } config.append(" collect_power_rails: true\n") .append(" battery_counters: BATTERY_COUNTER_CAPACITY_PERCENT\n") .append(" battery_counters: BATTERY_COUNTER_CHARGE\n") .append(" battery_counters: BATTERY_COUNTER_CURRENT\n") .append(" }\n") .append(" }\n") .append("}\n"); } if (tags.contains(MEMORY_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.sys_stats\"\n") .append(" target_buffer: 1\n") .append(" sys_stats_config {\n") .append(" vmstat_period_ms: 1000\n") .append(" }\n") .append(" }\n") .append("}\n"); } if (tags.contains(GFX_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.surfaceflinger.frametimeline\"\n") .append(" }\n") .append("}\n"); } if (tags.contains(CAMERA_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.hardware.camera\"\n") .append(" target_buffer: 1\n") .append(" }\n") .append("}\n"); } // Also enable Chrome events when the WebView tag is enabled. if (tags.contains(WEBVIEW_TAG)) { String chromeTraceConfig = "{" + "\\\"record_mode\\\":\\\"record-continuously\\\"," + "\\\"included_categories\\\":[\\\"*\\\"]" + "}"; config.append("data_sources: {\n") .append(" config {\n") .append(" name: \"org.chromium.trace_event\"\n") .append(" chrome_config {\n") .append(" trace_config: \"" + chromeTraceConfig + "\"\n") .append(" }\n") .append(" }\n") .append("}\n") .append("data_sources: {\n") .append(" config {\n") .append(" name: \"org.chromium.trace_metadata\"\n") .append(" chrome_config {\n") .append(" trace_config: \"" + chromeTraceConfig + "\"\n") .append(" }\n") .append(" }\n") .append("}\n"); } String configString = config.toString(); // If the here-doc ends early, within the config string, exit immediately. // This should never happen. if (configString.contains(MARKER)) { throw new RuntimeException("The arguments to the Perfetto command are malformed."); } String cmd = "perfetto --detach=" + PERFETTO_TAG + " -o " + TEMP_TRACE_LOCATION + " -c - --txt" + " <<" + MARKER +"\n" + configString + "\n" + MARKER; Log.v(TAG, "Starting perfetto trace."); try { Process process = TraceUtils.execWithTimeout(cmd, TEMP_DIR, STARTUP_TIMEOUT_MS); if (process == null) { return false; } else if (process.exitValue() != 0) { Log.e(TAG, "perfetto traceStart failed with: " + process.exitValue()); return false; } } catch (Exception e) { throw new RuntimeException(e); } Log.v(TAG, "perfetto traceStart succeeded!"); return true; } public void traceStop() { Log.v(TAG, "Stopping perfetto trace."); if (!isTracingOn()) { Log.w(TAG, "No trace appears to be in progress. Stopping perfetto trace may not work."); } String cmd = "perfetto --stop --attach=" + PERFETTO_TAG; try { Process
process = TraceUtils.execWithTimeout(cmd, null, STOP_TIMEOUT_MS);
if (process != null && process.exitValue() != 0) { Log.e(TAG, "perfetto traceStop failed with: " + process.exitValue()); } } catch (Exception e) { throw new RuntimeException(e); } } public boolean traceDump(File outFile) { traceStop(); // Short-circuit if a trace was not stopped. if (isTracingOn()) { Log.e(TAG, "Trace was not stopped successfully, aborting trace dump."); return false; } // Short-circuit if the file we're trying to dump to doesn't exist. if (!Files.exists(Paths.get(TEMP_TRACE_LOCATION))) { Log.e(TAG, "In-progress trace file doesn't exist, aborting trace dump."); return false; } Log.v(TAG, "Saving perfetto trace to " + outFile); try { Os.rename(TEMP_TRACE_LOCATION, outFile.getCanonicalPath()); } catch (Exception e) { throw new RuntimeException(e); } outFile.setReadable(true, false); // (readable, ownerOnly) outFile.setWritable(true, false); // (readable, ownerOnly) return true; } public boolean isTracingOn() { String cmd = "perfetto --is_detached=" + PERFETTO_TAG; try { Process process = TraceUtils.exec(cmd); // 0 represents a detached process exists with this name // 2 represents no detached process with this name // 1 (or other error code) represents an error int result = process.waitFor(); if (result == 0) { return true; } else if (result == 2) { return false; } else { throw new RuntimeException("Perfetto error: " + result); } } catch (Exception e) { throw new RuntimeException(e); } } public static TreeMap<String,String> perfettoListCategories() { String cmd = "perfetto --query-raw"; Log.v(TAG, "Listing tags: " + cmd); try { TreeMap<String, String> result = new TreeMap<>(); // execWithTimeout() cannot be used because stdout must be consumed before the process // is terminated. Process perfetto = TraceUtils.exec(cmd, null, false); TracingServiceState serviceState = TracingServiceState.parseFrom(perfetto.getInputStream()); // Destroy the perfetto process if it times out. if (!perfetto.waitFor(LIST_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { Log.e(TAG, "perfettoListCategories timed out after " + LIST_TIMEOUT_MS + " ms."); perfetto.destroyForcibly(); return result; } // The perfetto process completed and failed, but does not need to be destroyed. if (perfetto.exitValue() != 0) { Log.e(TAG, "perfettoListCategories failed with: " + perfetto.exitValue()); } List<AtraceCategory> categories = null; for (DataSource dataSource : serviceState.getDataSourcesList()) { DataSourceDescriptor dataSrcDescriptor = dataSource.getDsDescriptor(); if (dataSrcDescriptor.getName().equals("linux.ftrace")){ categories = dataSrcDescriptor.getFtraceDescriptor().getAtraceCategoriesList(); break; } } if (categories != null) { for (AtraceCategory category : categories) { result.put(category.getName(), category.getDescription()); } } return result; } catch (Exception e) { throw new RuntimeException(e); } } }
src/com/android/traceur/PerfettoUtils.java
GrapheneOS-Archive-platform_packages_apps_Traceur-2e6c52a
[ { "filename": "src/com/android/traceur/AtraceUtils.java", "retrieved_chunk": " return true;\n }\n public void traceStop() {\n String cmd = \"atrace --async_stop > /dev/null\";\n Log.v(TAG, \"Stopping async atrace: \" + cmd);\n try {\n Process atrace = TraceUtils.exec(cmd);\n if (atrace.waitFor() != 0) {\n Log.e(TAG, \"atraceStop failed with: \" + atrace.exitValue());\n }", "score": 0.8940178751945496 }, { "filename": "src/com/android/traceur/TraceUtils.java", "retrieved_chunk": " public static boolean isTracingOn() {\n return mTraceEngine.isTracingOn();\n }\n public static TreeMap<String, String> listCategories() {\n return PerfettoUtils.perfettoListCategories();\n }\n public static void clearSavedTraces() {\n String cmd = \"rm -f \" + TRACE_DIRECTORY + \"trace-*.*trace\";\n Log.v(TAG, \"Clearing trace directory: \" + cmd);\n try {", "score": 0.8538758754730225 }, { "filename": "src/com/android/traceur/AtraceUtils.java", "retrieved_chunk": " } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n public boolean traceDump(File outFile) {\n String cmd = \"atrace --async_stop -z -c -o \" + outFile;\n Log.v(TAG, \"Dumping async atrace: \" + cmd);\n try {\n Process atrace = TraceUtils.exec(cmd);\n if (atrace.waitFor() != 0) {", "score": 0.8487547039985657 }, { "filename": "src/com/android/traceur/TraceService.java", "retrieved_chunk": "import android.util.Log;\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.Collection;\npublic class TraceService extends IntentService {\n /* Indicates Perfetto has stopped tracing due to either the supplied long trace limitations\n * or limited storage capacity. */\n static String INTENT_ACTION_NOTIFY_SESSION_STOPPED =\n \"com.android.traceur.NOTIFY_SESSION_STOPPED\";\n /* Indicates a Traceur-associated tracing session has been attached to a bug report */", "score": 0.8442274332046509 }, { "filename": "src/com/android/traceur/TraceUtils.java", "retrieved_chunk": " int maxLongTraceDurationMinutes) {\n return mTraceEngine.traceStart(tags, bufferSizeKb, apps,\n attachToBugreport, longTrace, maxLongTraceSizeMb, maxLongTraceDurationMinutes);\n }\n public static void traceStop() {\n mTraceEngine.traceStop();\n }\n public static boolean traceDump(File outFile) {\n return mTraceEngine.traceDump(outFile);\n }", "score": 0.836333692073822 } ]
java
process = TraceUtils.execWithTimeout(cmd, null, STOP_TIMEOUT_MS);
/* * Copyright 2022 QuiltMC * * 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 ho.artisan.lib.recipe.mixin; import com.google.gson.JsonObject; import ho.artisan.lib.recipe.api.serializer.FabricRecipeSerializer; import org.spongepowered.asm.mixin.Mixin; import net.minecraft.data.server.recipe.SmithingRecipeJsonBuilder; import net.minecraft.recipe.SmithingRecipe; import ho.artisan.lib.recipe.api.serializer.FabricRecipeSerializer; @Mixin(SmithingRecipe.Serializer.class) public abstract class SmithingRecipeSerializerMixin implements FabricRecipeSerializer<SmithingRecipe> { @Override public JsonObject toJson(SmithingRecipe recipe) { var accessor = (SmithingRecipeAccessor) recipe; return new SmithingRecipeJsonBuilder.SmithingRecipeJsonProvider( recipe.getId(), this, accessor.getBase(
), accessor.getAddition(), recipe.getOutput().getItem(), null, null ).toJson();
} }
src/main/java/ho/artisan/lib/recipe/mixin/SmithingRecipeSerializerMixin.java
HO-Artisan-RecipeInProgramming-09cc072
[ { "filename": "src/main/java/ho/artisan/lib/recipe/mixin/CookingRecipeSerializerMixin.java", "retrieved_chunk": "import net.minecraft.recipe.CookingRecipeSerializer;\nimport ho.artisan.lib.recipe.api.serializer.FabricRecipeSerializer;\n@Mixin(CookingRecipeSerializer.class)\npublic abstract class CookingRecipeSerializerMixin<T extends AbstractCookingRecipe> implements FabricRecipeSerializer<T> {\n\t@Override\n\tpublic JsonObject toJson(T recipe) {\n\t\treturn new CookingRecipeJsonBuilder.CookingRecipeJsonProvider(recipe.getId(), recipe.getGroup(),\n\t\t\t\trecipe.getIngredients().get(0), recipe.getOutput().getItem(),\n\t\t\t\trecipe.getExperience(), recipe.getCookTime(), null, null, this)\n\t\t\t\t.toJson();", "score": 0.9016690850257874 }, { "filename": "src/main/java/ho/artisan/lib/recipe/mixin/ShapelessRecipeSerializerMixin.java", "retrieved_chunk": "import ho.artisan.lib.recipe.api.serializer.FabricRecipeSerializer;\n@Mixin(ShapelessRecipe.Serializer.class)\npublic abstract class ShapelessRecipeSerializerMixin implements FabricRecipeSerializer<ShapelessRecipe> {\n\t@Override\n\tpublic JsonObject toJson(ShapelessRecipe recipe) {\n\t\treturn new ShapelessRecipeJsonBuilder.ShapelessRecipeJsonProvider(recipe.getId(),\n\t\t\t\trecipe.getOutput().getItem(), recipe.getOutput().getCount(),\n\t\t\t\trecipe.getGroup(), recipe.getIngredients(), null, null)\n\t\t\t\t.toJson();\n\t}", "score": 0.8864368796348572 }, { "filename": "src/main/java/ho/artisan/lib/recipe/mixin/CuttingRecipeSerializerMixin.java", "retrieved_chunk": "import ho.artisan.lib.recipe.api.serializer.FabricRecipeSerializer;\n@Mixin(CuttingRecipe.Serializer.class)\npublic abstract class CuttingRecipeSerializerMixin<T extends CuttingRecipe> implements FabricRecipeSerializer<T> {\n\t@Override\n\tpublic JsonObject toJson(T recipe) {\n\t\treturn new SingleItemRecipeJsonBuilder.SingleItemRecipeJsonProvider(recipe.getId(), this, recipe.getGroup(),\n\t\t\t\trecipe.getIngredients().get(0), recipe.getOutput().getItem(), recipe.getOutput().getCount(),\n\t\t\t\tnull, null)\n\t\t\t\t.toJson();\n\t}", "score": 0.8817934393882751 }, { "filename": "src/main/java/ho/artisan/lib/recipe/mixin/SpecialRecipeSerializerMixin.java", "retrieved_chunk": "import net.minecraft.recipe.SpecialRecipeSerializer;\nimport net.minecraft.util.registry.Registry;\nimport ho.artisan.lib.recipe.api.serializer.FabricRecipeSerializer;\n@Mixin(SpecialRecipeSerializer.class)\npublic abstract class SpecialRecipeSerializerMixin<T extends Recipe<?>> implements FabricRecipeSerializer<T> {\n\t@Override\n\tpublic JsonObject toJson(T recipe) {\n\t\tvar json = new JsonObject();\n\t\tjson.addProperty(\"type\", Objects.requireNonNull(Registry.RECIPE_SERIALIZER.getId(this)).toString());\n\t\treturn json;", "score": 0.8804195523262024 }, { "filename": "src/main/java/ho/artisan/lib/recipe/mixin/ShapedRecipeSerializerMixin.java", "retrieved_chunk": "import it.unimi.dsi.fastutil.objects.Object2CharOpenHashMap;\nimport org.spongepowered.asm.mixin.Mixin;\nimport net.minecraft.data.server.recipe.ShapedRecipeJsonBuilder;\nimport net.minecraft.recipe.Ingredient;\nimport net.minecraft.recipe.ShapedRecipe;\nimport net.minecraft.util.collection.DefaultedList;\n@Mixin(ShapedRecipe.Serializer.class)\npublic abstract class ShapedRecipeSerializerMixin implements FabricRecipeSerializer<ShapedRecipe> {\n\t@Override\n\tpublic JsonObject toJson(ShapedRecipe recipe) {", "score": 0.8704389333724976 } ]
java
), accessor.getAddition(), recipe.getOutput().getItem(), null, null ).toJson();
package com.HiWord9.RPRenames.configGeneration; import com.HiWord9.RPRenames.RPRenames; import com.HiWord9.RPRenames.Rename; import com.google.gson.Gson; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Objects; import java.util.Properties; public class CITConfig { public static void propertiesToJson(Properties p, String outputPath) { String items = p.getProperty("matchItems"); if (items == null) { items = p.getProperty("items"); } if (items != null) { while (items.endsWith(" ")) { items = items.substring(0, items.length() - 1); } String item = null; boolean finish = false; while (!finish) { int i = 0; while (i < items.length()) { if (String.valueOf(items.charAt(i)).equals(" ")) { item = items.substring(0, i); items = items.substring(i + 1); finish = false; break; } i++; finish = true; } if (finish) { item = items; } item = Objects.requireNonNull(item).replace("minecraft:", ""); File currentFile = new File(outputPath + item + ".json"); if (currentFile.exists() && p.getProperty("nbt.display.Name") != null) { Rename alreadyExist = ConfigManager.configRead(currentFile); String[] ae = alreadyExist.getName(); if (!Arrays.stream(ae).toList(
).contains(ConfigManager.getFirstName(p.getProperty("nbt.display.Name")))) {
int AEsize = ae.length; String[] newConfig = new String[AEsize + 1]; int h = 0; while (h < AEsize) { newConfig[h] = ae[h]; h++; } newConfig[h] = ConfigManager.getFirstName(p.getProperty("nbt.display.Name")); Rename newRename = new Rename(newConfig); ArrayList<Rename> listFiles = new ArrayList<>(); listFiles.add(newRename); try { FileWriter fileWriter = new FileWriter(currentFile); Gson gson = new Gson(); gson.toJson(listFiles, fileWriter); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } else { if (p.getProperty("nbt.display.Name") != null) { new File(outputPath).mkdirs(); try { RPRenames.LOGGER.info("Created new file for config: " + outputPath + item + ".json"); ArrayList<Rename> listNames = new ArrayList<>(); Rename name1 = new Rename(new String[]{ConfigManager.getFirstName(p.getProperty("nbt.display.Name"))}); listNames.add(name1); FileWriter fileWriter = new FileWriter(currentFile); Gson gson = new Gson(); gson.toJson(listNames, fileWriter); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } } } } }
src/main/java/com/HiWord9/RPRenames/configGeneration/CITConfig.java
HiWord9-RPRenames-fabric-046f2f8
[ { "filename": "src/main/java/com/HiWord9/RPRenames/configGeneration/CEMConfig.java", "retrieved_chunk": " File currentFile = new File(outputPath + fileName + \".json\");\n if (currentFile.exists()) {\n List<String> namesValues = p.stringPropertyNames().stream().toList();\n ArrayList<String> skins = new ArrayList<>();\n for (String s : namesValues) {\n if (s.startsWith(\"name.\")) {\n if (!skins.contains(p.getProperty(\"skins.\" + s.substring(5)))) {\n skins.add(p.getProperty(\"skins.\" + s.substring(5)));\n String name = ConfigManager.getFirstName(p.getProperty(s));\n if (currentFile.exists() && name != null) {", "score": 0.8910648822784424 }, { "filename": "src/main/java/com/HiWord9/RPRenames/mixin/AnvilScreenMixin.java", "retrieved_chunk": "\t\t\t\t\t\tRename newRename = new Rename(newConfig);\n\t\t\t\t\t\tlistNames.add(newRename);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (new File(RPRenames.configPathFavorite).mkdirs()) {\n\t\t\t\t\t\tSystem.out.println(\"[RPR] Created folder for favorites config: \" + RPRenames.configPathFavorite);\n\t\t\t\t\t}\n\t\t\t\t\tSystem.out.println(\"[RPR] Created new file for favorites config: \" + RPRenames.configPathFavorite + item + \".json\");\n\t\t\t\t\tRename name1 = new Rename(new String[]{favoriteName});\n\t\t\t\t\tlistNames.add(name1);", "score": 0.8486611843109131 }, { "filename": "src/main/java/com/HiWord9/RPRenames/mixin/AnvilScreenMixin.java", "retrieved_chunk": "\t\t\t\tif (!item.equals(\"air\") && !checked.contains(item) && item.toUpperCase(Locale.ROOT).contains(itemSearchTag.toUpperCase(Locale.ROOT))) {\n\t\t\t\t\tFile jsonRenamesClientLocal = new File(RPRenames.configPathClient + RPRenames.configPathNameCIT + \"/\" + item + \".json\");\n\t\t\t\t\tFile jsonRenamesServerLocal = new File(RPRenames.configPathServer + RPRenames.configPathNameCIT + \"/\" + item + \".json\");\n\t\t\t\t\tboolean clientConfigReadableLocal = jsonRenamesClientLocal.exists();\n\t\t\t\t\tboolean serverConfigReadableLocal = jsonRenamesServerLocal.exists();\n\t\t\t\t\tboolean clientConfigCEMReadableLocal = RPRenames.configClientCEMFolder.exists();\n\t\t\t\t\tboolean serverConfigCEMReadableLocal = RPRenames.configServerCEMFolder.exists();\n\t\t\t\t\tif (!isOnServer) {\n\t\t\t\t\t\tserverConfigReadableLocal = false;\n\t\t\t\t\t\tserverConfigCEMReadableLocal = false;", "score": 0.8474740386009216 }, { "filename": "src/main/java/com/HiWord9/RPRenames/configGeneration/CEMConfig.java", "retrieved_chunk": " renameArray.add(rename);\n if (names.length != 0) {\n try {\n new File(outputPath).mkdirs();\n RPRenames.LOGGER.info(\"Created new file for config: \" + outputPath + fileName + \".json\");\n FileWriter fileWriter = new FileWriter(currentFile);\n Gson gson = new Gson();\n gson.toJson(renameArray, fileWriter);\n fileWriter.close();\n } catch (IOException e) {", "score": 0.8392236828804016 }, { "filename": "src/main/java/com/HiWord9/RPRenames/mixin/AnvilScreenMixin.java", "retrieved_chunk": "\t\t\t}\n\t\t}\n\t\tif (!showOpenerPlus) {\n\t\t\tcurrentItemList = getInventory();\n\t\t\tcurrentInvOrder.clear();\n\t\t\tArrayList<String> checked = new ArrayList<>();\n\t\t\tfor (String s : currentItemList) {\n\t\t\t\tString item = cutTranslationKey(s);\n\t\t\t\tif (!item.equals(\"air\") && !checked.contains(item)) {\n\t\t\t\t\tFile jsonRenamesClientLocal = new File(RPRenames.configPathClient + RPRenames.configPathNameCIT + \"/\" + item + \".json\");", "score": 0.8293256759643555 } ]
java
).contains(ConfigManager.getFirstName(p.getProperty("nbt.display.Name")))) {
package com.lint.rpc.common.transport; import com.lint.rpc.common.protocol.RequestBody; import com.lint.rpc.common.protocol.RequestContent; import com.lint.rpc.common.protocol.RequestHeader; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.CombinedChannelDuplexHandler; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.codec.MessageToByteEncoder; import java.io.*; import java.util.List; /** * 内部服务器消息编解码器 * * @author 周鹏程 * @date 2023-05-26 19:34:07 */ public final class InternalServerMsgCodec extends CombinedChannelDuplexHandler<InternalServerMsgCodec.Decoder, InternalServerMsgCodec.Encoder> { /** * 类默认构造器 */ public InternalServerMsgCodec() { super.init(new Decoder(), new Encoder()); } /** * 消息解码器 */ static final class Decoder extends ByteToMessageDecoder { private static final int HEAD_LENGTH = 107; @Override protected void decode(ChannelHandlerContext ctx, ByteBuf buff, List<Object> out) { // 如果消息不满足上面这个两个条件 直接不处理 if(buff.readableBytes() < HEAD_LENGTH){ return; } // 标记读取位置 buff.markReaderIndex(); byte[] headByteArray = new byte[HEAD_LENGTH]; buff.readBytes(headByteArray); RequestHeader requestHeader = null; try(ByteArrayInputStream in = new ByteArrayInputStream(headByteArray); ObjectInputStream ois = new ObjectInputStream(in); ) { requestHeader = (RequestHeader) ois.readObject(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } // 如果消息体长度不够 直接退出 if(null == requestHeader || buff.readableBytes() < requestHeader.getLength()){ // 回到标记读取位置 // 什么时候 消息读全了 什么时候再继续往后执行 buff.resetReaderIndex(); return; } byte[] bodyByteArray = new byte[requestHeader.getLength()]; buff.readBytes(bodyByteArray); RequestBody requestBody; try(ByteArrayInputStream in = new ByteArrayInputStream(bodyByteArray); ObjectInputStream ois = new ObjectInputStream(in); ) { requestBody = (RequestBody) ois.readObject(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); requestBody = new RequestBody(); } // System.out.println("收到消息 => " + // "requestId = "+requestHeader.getRequestId() + // ", flag = "+requestHeader.getFlag()+ // ", bodyName = "+requestBody.getName()+ // ", bodyMethodName = "+requestBody.getMethodName()); RequestContent requestContent = new RequestContent(); requestContent.setRequestHeader(requestHeader); requestContent.setRequestBody(requestBody); // 出发消息读取事件 ctx.fireChannelRead(requestContent); } } /** * 消息编码器 */ static final class Encoder extends MessageToByteEncoder<RequestContent> { @Override protected void encode(ChannelHandlerContext ctx, RequestContent innerMsg, ByteBuf byteBuf) { // 写出head byteBuf.writeBytes(innerMsg.getRequestHeader().toBytesArray()); // 写出body byteBuf.writeBytes(innerMsg.getRequestBody().toBytesArray()); // 释放内存
innerMsg.free();
} } }
lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/InternalServerMsgCodec.java
hiparker-lint-rpc-framework-e64aac0
[ { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/ServerChannelHandler.java", "retrieved_chunk": " }catch (Exception e){\n e.printStackTrace();\n }\n requestHeader.setLength(requestBody.toBytesArray().length);\n ctx.channel().writeAndFlush(content);\n // 转多线程处理\n// ExecuteThread et = ExecuteThread.getInstance();\n// et.execute(()->{\n// ProvideServiceSpi spi = ProvideServiceSpi.getInstance();\n// LintService service = spi.getService(requestBody.getName(), requestHeader.getVersion());", "score": 0.8363267183303833 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/ClientChannelHandler.java", "retrieved_chunk": " public void channelRead(ChannelHandlerContext ctx, Object msg) {\n if(!(msg instanceof RequestContent)){\n return;\n }\n //System.out.println(\"客户端处理数据......\");\n RequestContent content = (RequestContent) msg;\n RequestHeader requestHeader = content.getRequestHeader();\n RequestBody requestBody = content.getRequestBody();\n MsgPool.put(requestHeader.getRequestId(), requestBody.getRes());\n CountDownLatchPool.countDown(requestHeader.getRequestId());", "score": 0.8262898325920105 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/ServerChannelHandler.java", "retrieved_chunk": "// }\n//\n// requestHeader.setLength(requestBody.toBytesArray().length);\n// ctx.channel().writeAndFlush(content);\n// });\n }\n}", "score": 0.8251419067382812 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/ServerChannelHandler.java", "retrieved_chunk": "public class ServerChannelHandler extends ChannelInboundHandlerAdapter {\n @Override\n public void channelRead(ChannelHandlerContext ctx, Object msg) {\n if(!(msg instanceof RequestContent)){\n return;\n }\n //System.out.println(Thread.currentThread().getName() + \" 服务端处理数据......\");\n RequestContent content = (RequestContent) msg;\n RequestHeader requestHeader = content.getRequestHeader();\n RequestBody requestBody = content.getRequestBody();", "score": 0.8194016218185425 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/ClientChannelHandler.java", "retrieved_chunk": "package com.lint.rpc.common.transport;\nimport com.lint.rpc.common.pool.CountDownLatchPool;\nimport com.lint.rpc.common.pool.MsgPool;\nimport com.lint.rpc.common.protocol.RequestBody;\nimport com.lint.rpc.common.protocol.RequestContent;\nimport com.lint.rpc.common.protocol.RequestHeader;\nimport io.netty.channel.ChannelHandlerContext;\nimport io.netty.channel.ChannelInboundHandlerAdapter;\npublic class ClientChannelHandler extends ChannelInboundHandlerAdapter {\n @Override", "score": 0.8128212690353394 } ]
java
innerMsg.free();
package com.lint.rpc.common.transport; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import java.net.InetSocketAddress; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.concurrent.Future; import java.util.function.Consumer; /** * Netty 客户端 * * @author 周鹏程 * @date 2023-05-26 12:45 PM **/ public class NettyClient { private final NettyConf conf; private volatile NioSocketChannel ch; public NettyClient(NettyConf conf){ this.conf = conf; } public boolean sendMsg(Object msg){ if(ch == null){ synchronized (this){ if(ch == null){ this.connect(); } } } if(ch == null){ return false; } try { ch.writeAndFlush(msg).sync(); return true; } catch (InterruptedException e) { e.printStackTrace(); } return false; } public NettyConf getConf() { return conf; } private void connect(){ if(null == conf.getAddress()){ return; } NioEventLoopGroup workGroup = new NioEventLoopGroup(); Bootstrap bs = new Bootstrap(); bs.group(workGroup) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<NioSocketChannel>() { @Override protected void initChannel(NioSocketChannel ch) { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new InternalServerMsgCodec()); pipeline.addLast(new ClientChannelHandler()); } }); try { ChannelFuture f = bs.connect(conf.getAddress()).sync(); if (!f.isSuccess()) { return; } ch = (NioSocketChannel) f.channel(); ch.closeFuture().addListener(this::onLoseConnect);
System.out.println(">>> 连接到业务服务器成功! "+conf.getAddress()+" <<<");
} catch (InterruptedException e) { e.printStackTrace(); } } /** * 当失去连接时 * * @param f 预期 */ private void onLoseConnect(Future<?> f) { System.out.println("系统通知 - 注意: 服务器连接关闭! >>> " + conf.getAddress()); this.ch = null; final Consumer<NettyClient> closeCallback = conf.getCloseCallback(); if(null != closeCallback){ closeCallback.accept(this); } } @Override public int hashCode() { return Objects.hash(conf.getAddress().getHostName(), conf.getAddress().getPort()); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()){ return false; } NettyConf selfConf = this.getConf(); NettyClient client = (NettyClient) obj; NettyConf clientConf = client.getConf(); return selfConf.getAddress().getHostName().equals(clientConf.getAddress().getHostName()) && selfConf.getAddress().getPort() == clientConf.getAddress().getPort(); } }
lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyClient.java
hiparker-lint-rpc-framework-e64aac0
[ { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyServer.java", "retrieved_chunk": " }\n public NettyServerConf getConf() {\n return conf;\n }\n public void init(){\n int cpuCount = Runtime.getRuntime().availableProcessors();\n NioEventLoopGroup bossGroup = new NioEventLoopGroup();\n NioEventLoopGroup workerGroup = new NioEventLoopGroup(getThreadMaxCount(cpuCount));\n ServerBootstrap bs = new ServerBootstrap();\n ChannelFuture bind = bs.channel(NioServerSocketChannel.class)", "score": 0.8527957201004028 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyServer.java", "retrieved_chunk": " try {\n System.out.println(\"Lint Server port: \" + conf.getPort());\n ChannelFuture f = bind.sync();\n if (!f.isSuccess()) {\n throw new RpcException(RpcMsg.EXCEPTION_SERVICE_NOT_STARTED);\n }\n bind.channel().closeFuture().sync();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }", "score": 0.8516374826431274 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ClientPool.java", "retrieved_chunk": " }\n }\n }\n return nc;\n }\n private NettyClient createClient(String serviceName, InetSocketAddress address){\n NettyConf conf = new NettyConf();\n conf.setAddress(address);\n conf.setCloseCallback((c)->{\n try {", "score": 0.8471615314483643 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyServer.java", "retrieved_chunk": " .group(bossGroup, workerGroup)\n .childHandler(new ChannelInitializer<NioSocketChannel>() {\n @Override\n protected void initChannel(NioSocketChannel ch) {\n ChannelPipeline p = ch.pipeline();\n p.addLast(new InternalServerMsgCodec());\n p.addLast(new ServerChannelHandler());\n }\n })\n .bind(conf.getPort());", "score": 0.842989444732666 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyServer.java", "retrieved_chunk": "/**\n * Netty 服务端\n *\n * @author 周鹏程\n * @date 2023-05-26 12:45 PM\n **/\npublic class NettyServer {\n private final NettyServerConf conf;\n public NettyServer(NettyServerConf conf){\n this.conf = conf;", "score": 0.8260409235954285 } ]
java
System.out.println(">>> 连接到业务服务器成功! "+conf.getAddress()+" <<<");
package com.lint.rpc.common.pool; import com.lint.rpc.common.LintConf; import com.lint.rpc.common.balance.ILoadBalancePolicy; import com.lint.rpc.common.service.ProvideSpi; import com.lint.rpc.common.transport.ClientFactory; import com.lint.rpc.common.transport.NettyClient; import com.lint.rpc.common.transport.NettyConf; import java.net.InetSocketAddress; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; /** * 客户端连接池 * * @author 周鹏程 * @date 2023-05-26 7:38 PM **/ public final class ClientPool { // serviceName 为服务名 // hostname+port 为组名 // 连接池 private final Map<String, LinkedHashSet<NettyClient>> groupPool = new ConcurrentHashMap<>(); private final Map<String, LinkedHashSet<String>> servicePool = new ConcurrentHashMap<>(); private final ReentrantLock rLock = new ReentrantLock(); public NettyClient get(String serviceName, ILoadBalancePolicy loadBalancePolicy){ ConfPool confPool = ConfPool.getInstance(); LintConf lintConf = confPool.get(); ProvideSpi provideSpi = ProvideSpi.getInstance(); LinkedHashSet<InetSocketAddress> addressSet = provideSpi.getAddressByServiceName(serviceName); if(null == addressSet){ return null; } LinkedHashSet<String> groupNameSet = servicePool.get(serviceName); if(null == groupNameSet || groupNameSet.isEmpty()){ try { rLock.lock(); groupNameSet = servicePool.get(serviceName); if(null == groupNameSet || groupNameSet.isEmpty()){ int clientIndex = loadBalancePolicy.getClientIndex(addressSet.size()); InetSocketAddress inetSocketAddress = linkedHashSetGetByIndex(addressSet, clientIndex); NettyClient ch = createClient(serviceName, inetSocketAddress); return put(serviceName, ch); } }finally { rLock.unlock(); } } NettyClient ch = null; // 如果不相等 优先使用为开辟的新链接 if(groupNameSet.size() != addressSet.size()){ try { rLock.lock(); if(groupNameSet.size() != addressSet.size()) { InetSocketAddress address = null; Iterator<InetSocketAddress> iterator = addressSet.stream().iterator(); while (iterator.hasNext()){ address = iterator.next(); String groupName = getGroupName(address); boolean contains = groupNameSet.contains(groupName); if(!contains){ break; } } ch = createClient(serviceName, address); if(ch != null){ return put(serviceName, ch); } } }finally { rLock.unlock(); } } // 如果上述操作 ch == null 或者 group相等 那就准备 从现有队列中选择一位连接 int groupIndex = loadBalancePolicy.getClientIndex(groupNameSet.size()); String groupName = linkedHashSetGetByIndex(groupNameSet, groupIndex); LinkedHashSet<NettyClient> ncSet = groupPool.get(groupName); if(null != ncSet){ // 如果当前开辟的连接数 还未达到自定义配置的最大值 则继续开辟连接 if(ncSet.size() < lintConf.getClientMaxConnCount()){ try { rLock.lock(); if(ncSet.size() < lintConf.getClientMaxConnCount()){ String[] address = groupName.split(":"); InetSocketAddress inetSocketAddress = new InetSocketAddress( address[0], Integer.parseInt(address[1])); ch = createClient(serviceName, inetSocketAddress); return put(serviceName, ch); } }finally { rLock.unlock(); } } int
chIndex = loadBalancePolicy.getClientIndex(groupNameSet.size());
ch = linkedHashSetGetByIndex(ncSet, chIndex); } return ch; } private NettyClient put( String serviceName, NettyClient nc){ if(null == nc){ return null; } int lockCount = 0; try { Set<String> groupSet = servicePool.get(serviceName); if(null == groupSet){ rLock.lock(); lockCount++; groupSet = servicePool.computeIfAbsent(serviceName, k -> new LinkedHashSet<>()); } NettyConf conf = nc.getConf(); String groupName = getGroupName(conf.getAddress()); Set<NettyClient> nettyClientSet = groupPool.get(groupName); if(null == nettyClientSet){ rLock.lock(); lockCount++; nettyClientSet = groupPool.computeIfAbsent(groupName, k -> new LinkedHashSet<>()); } rLock.lock(); lockCount++; if(nettyClientSet.isEmpty()){ groupSet.add(groupName); } nettyClientSet.add(nc); }finally { if(lockCount > 0){ for (int i = 0; i < lockCount; i++) { rLock.unlock(); } } } return nc; } private NettyClient createClient(String serviceName, InetSocketAddress address){ NettyConf conf = new NettyConf(); conf.setAddress(address); conf.setCloseCallback((c)->{ try { rLock.lock(); String groupName = getGroupName(address); Set<NettyClient> nettyClients = groupPool.get(groupName); nettyClients.remove(c); if(nettyClients.isEmpty()){ groupPool.remove(groupName); Set<String> groupSet = servicePool.get(serviceName); groupSet.remove(groupName); if(groupSet.isEmpty()){ servicePool.remove(serviceName); } } }finally { rLock.unlock(); } }); ClientFactory factory = ClientFactory.getInstance(); return factory.create(conf); } private String getGroupName(InetSocketAddress address){ String hostName = address.getHostName(); int port = address.getPort(); return hostName+":"+port; } private <T> T linkedHashSetGetByIndex(LinkedHashSet<T> linkedHashSet, int index){ if(null == linkedHashSet){ return null; } T t = null; int chCurrIndex = 0; Iterator<T> chIterator = linkedHashSet.stream().iterator(); while (chIterator.hasNext() && chCurrIndex++ <= index){ t = chIterator.next(); } return t; } private static class LazyHolder { private static final ClientPool INSTANCE = new ClientPool(); } public static ClientPool getInstance() { return ClientPool.LazyHolder.INSTANCE; } private ClientPool(){} }
lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ClientPool.java
hiparker-lint-rpc-framework-e64aac0
[ { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/service/ProvideSpi.java", "retrieved_chunk": " }\n provideService = ps;\n break;\n }\n isInit = true;\n }\n }\n }\n }\n public LinkedHashSet<InetSocketAddress> getAddressByServiceName(String serviceName){", "score": 0.8112093210220337 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/proxy/RpcInvocationHandler.java", "retrieved_chunk": " requestContent.setRequestHeader(requestHeader);\n requestContent.setRequestBody(requestBody);\n LoadBalancePolicyFactory loadBalancePolicyFactory = LoadBalancePolicyFactory.getInstance();\n NettyClient nc = loadBalancePolicyFactory\n .getClient(interfaceInfo);\n Object responseMsg = null;\n try {\n boolean sendFlag = nc.sendMsg(requestContent);\n if(!sendFlag){\n // 无法建立连接", "score": 0.8070075511932373 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/balance/LoadBalancePolicyFactory.java", "retrieved_chunk": " return null;\n }\n ClientPool pool = ClientPool.getInstance();\n // 选择客户端\n return pool.get(rpcClientAnnotation.name(), loadBalancePolicy);\n }\n private ILoadBalancePolicy getLoadBalancePolicy(\n Class<? extends ILoadBalancePolicy> loadBalancePolicyClazz){\n ILoadBalancePolicy loadBalancePolicy = loadBalancePolicyMap.get(loadBalancePolicyClazz);\n if(null != loadBalancePolicy){", "score": 0.805247962474823 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/balance/LoadBalancePolicyFactory.java", "retrieved_chunk": " * @date 2023-05-26 10:53 AM\n **/\npublic class LoadBalancePolicyFactory {\n private final Object lock = new Object();\n private final Map<Class<? extends ILoadBalancePolicy>, ILoadBalancePolicy>\n loadBalancePolicyMap = new ConcurrentHashMap<>();\n public NettyClient getClient(Class<?> interfaceClazz) {\n RpcClient rpcClientAnnotation = interfaceClazz.getAnnotation(RpcClient.class);\n ILoadBalancePolicy loadBalancePolicy = getLoadBalancePolicy(rpcClientAnnotation.loadBalancePolicy());\n if(null == loadBalancePolicy){", "score": 0.8016210794448853 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyClient.java", "retrieved_chunk": " pipeline.addLast(new ClientChannelHandler());\n }\n });\n try {\n ChannelFuture f = bs.connect(conf.getAddress()).sync();\n if (!f.isSuccess()) {\n return;\n }\n ch = (NioSocketChannel) f.channel();\n ch.closeFuture().addListener(this::onLoseConnect);", "score": 0.797142505645752 } ]
java
chIndex = loadBalancePolicy.getClientIndex(groupNameSet.size());
package com.lint.rpc.common.transport; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import java.net.InetSocketAddress; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.concurrent.Future; import java.util.function.Consumer; /** * Netty 客户端 * * @author 周鹏程 * @date 2023-05-26 12:45 PM **/ public class NettyClient { private final NettyConf conf; private volatile NioSocketChannel ch; public NettyClient(NettyConf conf){ this.conf = conf; } public boolean sendMsg(Object msg){ if(ch == null){ synchronized (this){ if(ch == null){ this.connect(); } } } if(ch == null){ return false; } try { ch.writeAndFlush(msg).sync(); return true; } catch (InterruptedException e) { e.printStackTrace(); } return false; } public NettyConf getConf() { return conf; } private void connect(){ if(null == conf.getAddress()){ return; } NioEventLoopGroup workGroup = new NioEventLoopGroup(); Bootstrap bs = new Bootstrap(); bs.group(workGroup) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<NioSocketChannel>() { @Override protected void initChannel(NioSocketChannel ch) { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new InternalServerMsgCodec()); pipeline.addLast(new ClientChannelHandler()); } }); try { ChannelFuture f = bs.connect(conf.getAddress()).sync(); if (!f.isSuccess()) { return; } ch = (NioSocketChannel) f.channel(); ch.closeFuture().addListener(this::onLoseConnect); System.out.println(">>> 连接到业务服务器成功! "+conf.getAddress()+" <<<"); } catch (InterruptedException e) { e.printStackTrace(); } } /** * 当失去连接时 * * @param f 预期 */ private void onLoseConnect(Future<?> f) { System.out.println
("系统通知 - 注意: 服务器连接关闭! >>> " + conf.getAddress());
this.ch = null; final Consumer<NettyClient> closeCallback = conf.getCloseCallback(); if(null != closeCallback){ closeCallback.accept(this); } } @Override public int hashCode() { return Objects.hash(conf.getAddress().getHostName(), conf.getAddress().getPort()); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()){ return false; } NettyConf selfConf = this.getConf(); NettyClient client = (NettyClient) obj; NettyConf clientConf = client.getConf(); return selfConf.getAddress().getHostName().equals(clientConf.getAddress().getHostName()) && selfConf.getAddress().getPort() == clientConf.getAddress().getPort(); } }
lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyClient.java
hiparker-lint-rpc-framework-e64aac0
[ { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyServer.java", "retrieved_chunk": " try {\n System.out.println(\"Lint Server port: \" + conf.getPort());\n ChannelFuture f = bind.sync();\n if (!f.isSuccess()) {\n throw new RpcException(RpcMsg.EXCEPTION_SERVICE_NOT_STARTED);\n }\n bind.channel().closeFuture().sync();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }", "score": 0.8068193197250366 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ClientPool.java", "retrieved_chunk": " }\n }\n }\n return nc;\n }\n private NettyClient createClient(String serviceName, InetSocketAddress address){\n NettyConf conf = new NettyConf();\n conf.setAddress(address);\n conf.setCloseCallback((c)->{\n try {", "score": 0.7910446524620056 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/ExceptionCaughtHandler.java", "retrieved_chunk": " @Override\n public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {\n cause.printStackTrace();\n }\n}", "score": 0.7862522602081299 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyConf.java", "retrieved_chunk": "package com.lint.rpc.common.transport;\nimport java.net.InetSocketAddress;\nimport java.util.function.Consumer;\npublic class NettyConf {\n private InetSocketAddress address;\n private Consumer<NettyClient> closeCallback;\n public InetSocketAddress getAddress() {\n return address;\n }\n public void setAddress(InetSocketAddress address) {", "score": 0.7830174565315247 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/CountDownLatchPool.java", "retrieved_chunk": " timeoutSeconds = 0;\n }\n CountDownLatch countDownLatch = new CountDownLatch(1);\n // 超时自动释放\n MSG_POOL_MAP.putIfAbsent(requestId, countDownLatch);\n countDownLatch.await(timeoutSeconds, TimeUnit.SECONDS);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }", "score": 0.7784808278083801 } ]
java
("系统通知 - 注意: 服务器连接关闭! >>> " + conf.getAddress());
package com.lint.rpc.common.pool; import com.lint.rpc.common.LintConf; import com.lint.rpc.common.balance.ILoadBalancePolicy; import com.lint.rpc.common.service.ProvideSpi; import com.lint.rpc.common.transport.ClientFactory; import com.lint.rpc.common.transport.NettyClient; import com.lint.rpc.common.transport.NettyConf; import java.net.InetSocketAddress; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; /** * 客户端连接池 * * @author 周鹏程 * @date 2023-05-26 7:38 PM **/ public final class ClientPool { // serviceName 为服务名 // hostname+port 为组名 // 连接池 private final Map<String, LinkedHashSet<NettyClient>> groupPool = new ConcurrentHashMap<>(); private final Map<String, LinkedHashSet<String>> servicePool = new ConcurrentHashMap<>(); private final ReentrantLock rLock = new ReentrantLock(); public NettyClient get(String serviceName, ILoadBalancePolicy loadBalancePolicy){ ConfPool confPool = ConfPool.getInstance(); LintConf lintConf = confPool.get(); ProvideSpi provideSpi = ProvideSpi.getInstance(); LinkedHashSet<InetSocketAddress> addressSet = provideSpi.getAddressByServiceName(serviceName); if(null == addressSet){ return null; } LinkedHashSet<String> groupNameSet = servicePool.get(serviceName); if(null == groupNameSet || groupNameSet.isEmpty()){ try { rLock.lock(); groupNameSet = servicePool.get(serviceName); if(null == groupNameSet || groupNameSet.isEmpty()){ int clientIndex = loadBalancePolicy.getClientIndex(addressSet.size()); InetSocketAddress inetSocketAddress = linkedHashSetGetByIndex(addressSet, clientIndex); NettyClient ch = createClient(serviceName, inetSocketAddress); return put(serviceName, ch); } }finally { rLock.unlock(); } } NettyClient ch = null; // 如果不相等 优先使用为开辟的新链接 if(groupNameSet.size() != addressSet.size()){ try { rLock.lock(); if(groupNameSet.size() != addressSet.size()) { InetSocketAddress address = null; Iterator<InetSocketAddress> iterator = addressSet.stream().iterator(); while (iterator.hasNext()){ address = iterator.next(); String groupName = getGroupName(address); boolean contains = groupNameSet.contains(groupName); if(!contains){ break; } } ch = createClient(serviceName, address); if(ch != null){ return put(serviceName, ch); } } }finally { rLock.unlock(); } } // 如果上述操作 ch == null 或者 group相等 那就准备 从现有队列中选择一位连接 int groupIndex = loadBalancePolicy.getClientIndex(groupNameSet.size()); String groupName = linkedHashSetGetByIndex(groupNameSet, groupIndex); LinkedHashSet<NettyClient> ncSet = groupPool.get(groupName); if(null != ncSet){ // 如果当前开辟的连接数 还未达到自定义配置的最大值 则继续开辟连接 if(ncSet.size
() < lintConf.getClientMaxConnCount()){
try { rLock.lock(); if(ncSet.size() < lintConf.getClientMaxConnCount()){ String[] address = groupName.split(":"); InetSocketAddress inetSocketAddress = new InetSocketAddress( address[0], Integer.parseInt(address[1])); ch = createClient(serviceName, inetSocketAddress); return put(serviceName, ch); } }finally { rLock.unlock(); } } int chIndex = loadBalancePolicy.getClientIndex(groupNameSet.size()); ch = linkedHashSetGetByIndex(ncSet, chIndex); } return ch; } private NettyClient put( String serviceName, NettyClient nc){ if(null == nc){ return null; } int lockCount = 0; try { Set<String> groupSet = servicePool.get(serviceName); if(null == groupSet){ rLock.lock(); lockCount++; groupSet = servicePool.computeIfAbsent(serviceName, k -> new LinkedHashSet<>()); } NettyConf conf = nc.getConf(); String groupName = getGroupName(conf.getAddress()); Set<NettyClient> nettyClientSet = groupPool.get(groupName); if(null == nettyClientSet){ rLock.lock(); lockCount++; nettyClientSet = groupPool.computeIfAbsent(groupName, k -> new LinkedHashSet<>()); } rLock.lock(); lockCount++; if(nettyClientSet.isEmpty()){ groupSet.add(groupName); } nettyClientSet.add(nc); }finally { if(lockCount > 0){ for (int i = 0; i < lockCount; i++) { rLock.unlock(); } } } return nc; } private NettyClient createClient(String serviceName, InetSocketAddress address){ NettyConf conf = new NettyConf(); conf.setAddress(address); conf.setCloseCallback((c)->{ try { rLock.lock(); String groupName = getGroupName(address); Set<NettyClient> nettyClients = groupPool.get(groupName); nettyClients.remove(c); if(nettyClients.isEmpty()){ groupPool.remove(groupName); Set<String> groupSet = servicePool.get(serviceName); groupSet.remove(groupName); if(groupSet.isEmpty()){ servicePool.remove(serviceName); } } }finally { rLock.unlock(); } }); ClientFactory factory = ClientFactory.getInstance(); return factory.create(conf); } private String getGroupName(InetSocketAddress address){ String hostName = address.getHostName(); int port = address.getPort(); return hostName+":"+port; } private <T> T linkedHashSetGetByIndex(LinkedHashSet<T> linkedHashSet, int index){ if(null == linkedHashSet){ return null; } T t = null; int chCurrIndex = 0; Iterator<T> chIterator = linkedHashSet.stream().iterator(); while (chIterator.hasNext() && chCurrIndex++ <= index){ t = chIterator.next(); } return t; } private static class LazyHolder { private static final ClientPool INSTANCE = new ClientPool(); } public static ClientPool getInstance() { return ClientPool.LazyHolder.INSTANCE; } private ClientPool(){} }
lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ClientPool.java
hiparker-lint-rpc-framework-e64aac0
[ { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/balance/LoadBalancePolicyFactory.java", "retrieved_chunk": " return null;\n }\n ClientPool pool = ClientPool.getInstance();\n // 选择客户端\n return pool.get(rpcClientAnnotation.name(), loadBalancePolicy);\n }\n private ILoadBalancePolicy getLoadBalancePolicy(\n Class<? extends ILoadBalancePolicy> loadBalancePolicyClazz){\n ILoadBalancePolicy loadBalancePolicy = loadBalancePolicyMap.get(loadBalancePolicyClazz);\n if(null != loadBalancePolicy){", "score": 0.8417942523956299 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/proxy/RpcInvocationHandler.java", "retrieved_chunk": " requestContent.setRequestHeader(requestHeader);\n requestContent.setRequestBody(requestBody);\n LoadBalancePolicyFactory loadBalancePolicyFactory = LoadBalancePolicyFactory.getInstance();\n NettyClient nc = loadBalancePolicyFactory\n .getClient(interfaceInfo);\n Object responseMsg = null;\n try {\n boolean sendFlag = nc.sendMsg(requestContent);\n if(!sendFlag){\n // 无法建立连接", "score": 0.8125089406967163 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/LintConf.java", "retrieved_chunk": "package com.lint.rpc.common;\npublic class LintConf {\n /**\n * 客户端最大连接数量\n */\n private byte clientMaxConnCount = 1;\n /**\n * 加载 provide spi 列表类型\n * 如 local nacos 等\n */", "score": 0.8090137839317322 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/LintConf.java", "retrieved_chunk": " private String provideSpiType;\n /**\n * 客户端最大请求等待时间\n */\n private int requestWaitTimeBySeconds = 60;\n public byte getClientMaxConnCount() {\n return clientMaxConnCount;\n }\n public LintConf setClientMaxConnCount(byte clientMaxConnCount) {\n this.clientMaxConnCount = clientMaxConnCount;", "score": 0.8072144389152527 }, { "filename": "lint-rpc-demo/lint-rpc-demo-consumer/src/main/java/com/lint/rpc/demo/consumer/ConsumerApplication.java", "retrieved_chunk": " CountDownLatch c = new CountDownLatch(20);\n // 拟并发请求\n for (int i = 0; i < c.getCount(); i++) {\n new Thread(()->{\n // 调用链路1 生产者1 -> 生产者2 , 输出合并结果\n ProvideEatInterfaceSpi provide1 =\n ProxyPool.getProxyGet(ProvideEatInterfaceSpi.class);\n // 调用链路2 生产这2 ,输出一个List集合\n ProvideDrinkInterfaceSpi provide2 =\n ProxyPool.getProxyGet(ProvideDrinkInterfaceSpi.class);", "score": 0.8056031465530396 } ]
java
() < lintConf.getClientMaxConnCount()){
package com.lint.rpc.common.transport; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import java.net.InetSocketAddress; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.concurrent.Future; import java.util.function.Consumer; /** * Netty 客户端 * * @author 周鹏程 * @date 2023-05-26 12:45 PM **/ public class NettyClient { private final NettyConf conf; private volatile NioSocketChannel ch; public NettyClient(NettyConf conf){ this.conf = conf; } public boolean sendMsg(Object msg){ if(ch == null){ synchronized (this){ if(ch == null){ this.connect(); } } } if(ch == null){ return false; } try { ch.writeAndFlush(msg).sync(); return true; } catch (InterruptedException e) { e.printStackTrace(); } return false; } public NettyConf getConf() { return conf; } private void connect(){
if(null == conf.getAddress()){
return; } NioEventLoopGroup workGroup = new NioEventLoopGroup(); Bootstrap bs = new Bootstrap(); bs.group(workGroup) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<NioSocketChannel>() { @Override protected void initChannel(NioSocketChannel ch) { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new InternalServerMsgCodec()); pipeline.addLast(new ClientChannelHandler()); } }); try { ChannelFuture f = bs.connect(conf.getAddress()).sync(); if (!f.isSuccess()) { return; } ch = (NioSocketChannel) f.channel(); ch.closeFuture().addListener(this::onLoseConnect); System.out.println(">>> 连接到业务服务器成功! "+conf.getAddress()+" <<<"); } catch (InterruptedException e) { e.printStackTrace(); } } /** * 当失去连接时 * * @param f 预期 */ private void onLoseConnect(Future<?> f) { System.out.println("系统通知 - 注意: 服务器连接关闭! >>> " + conf.getAddress()); this.ch = null; final Consumer<NettyClient> closeCallback = conf.getCloseCallback(); if(null != closeCallback){ closeCallback.accept(this); } } @Override public int hashCode() { return Objects.hash(conf.getAddress().getHostName(), conf.getAddress().getPort()); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()){ return false; } NettyConf selfConf = this.getConf(); NettyClient client = (NettyClient) obj; NettyConf clientConf = client.getConf(); return selfConf.getAddress().getHostName().equals(clientConf.getAddress().getHostName()) && selfConf.getAddress().getPort() == clientConf.getAddress().getPort(); } }
lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyClient.java
hiparker-lint-rpc-framework-e64aac0
[ { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyServer.java", "retrieved_chunk": " }\n public NettyServerConf getConf() {\n return conf;\n }\n public void init(){\n int cpuCount = Runtime.getRuntime().availableProcessors();\n NioEventLoopGroup bossGroup = new NioEventLoopGroup();\n NioEventLoopGroup workerGroup = new NioEventLoopGroup(getThreadMaxCount(cpuCount));\n ServerBootstrap bs = new ServerBootstrap();\n ChannelFuture bind = bs.channel(NioServerSocketChannel.class)", "score": 0.8566906452178955 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ClientPool.java", "retrieved_chunk": " }\n }\n }\n return nc;\n }\n private NettyClient createClient(String serviceName, InetSocketAddress address){\n NettyConf conf = new NettyConf();\n conf.setAddress(address);\n conf.setCloseCallback((c)->{\n try {", "score": 0.8536377549171448 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyConf.java", "retrieved_chunk": "package com.lint.rpc.common.transport;\nimport java.net.InetSocketAddress;\nimport java.util.function.Consumer;\npublic class NettyConf {\n private InetSocketAddress address;\n private Consumer<NettyClient> closeCallback;\n public InetSocketAddress getAddress() {\n return address;\n }\n public void setAddress(InetSocketAddress address) {", "score": 0.8516337275505066 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyServer.java", "retrieved_chunk": " try {\n System.out.println(\"Lint Server port: \" + conf.getPort());\n ChannelFuture f = bind.sync();\n if (!f.isSuccess()) {\n throw new RpcException(RpcMsg.EXCEPTION_SERVICE_NOT_STARTED);\n }\n bind.channel().closeFuture().sync();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }", "score": 0.8373944759368896 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ClientPool.java", "retrieved_chunk": " }\n }\n }finally {\n rLock.unlock();\n }\n });\n ClientFactory factory = ClientFactory.getInstance();\n return factory.create(conf);\n }\n private String getGroupName(InetSocketAddress address){", "score": 0.833961009979248 } ]
java
if(null == conf.getAddress()){
package com.lint.rpc.common.transport; import com.lint.rpc.common.protocol.RequestBody; import com.lint.rpc.common.protocol.RequestContent; import com.lint.rpc.common.protocol.RequestHeader; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.CombinedChannelDuplexHandler; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.codec.MessageToByteEncoder; import java.io.*; import java.util.List; /** * 内部服务器消息编解码器 * * @author 周鹏程 * @date 2023-05-26 19:34:07 */ public final class InternalServerMsgCodec extends CombinedChannelDuplexHandler<InternalServerMsgCodec.Decoder, InternalServerMsgCodec.Encoder> { /** * 类默认构造器 */ public InternalServerMsgCodec() { super.init(new Decoder(), new Encoder()); } /** * 消息解码器 */ static final class Decoder extends ByteToMessageDecoder { private static final int HEAD_LENGTH = 107; @Override protected void decode(ChannelHandlerContext ctx, ByteBuf buff, List<Object> out) { // 如果消息不满足上面这个两个条件 直接不处理 if(buff.readableBytes() < HEAD_LENGTH){ return; } // 标记读取位置 buff.markReaderIndex(); byte[] headByteArray = new byte[HEAD_LENGTH]; buff.readBytes(headByteArray); RequestHeader requestHeader = null; try(ByteArrayInputStream in = new ByteArrayInputStream(headByteArray); ObjectInputStream ois = new ObjectInputStream(in); ) { requestHeader = (RequestHeader) ois.readObject(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } // 如果消息体长度不够 直接退出 if(null == requestHeader || buff.readableBytes() < requestHeader.getLength()){ // 回到标记读取位置 // 什么时候 消息读全了 什么时候再继续往后执行 buff.resetReaderIndex(); return; } byte[] bodyByteArray = new byte[requestHeader.getLength()]; buff.readBytes(bodyByteArray); RequestBody requestBody; try(ByteArrayInputStream in = new ByteArrayInputStream(bodyByteArray); ObjectInputStream ois = new ObjectInputStream(in); ) { requestBody = (RequestBody) ois.readObject(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); requestBody = new RequestBody(); } // System.out.println("收到消息 => " + // "requestId = "+requestHeader.getRequestId() + // ", flag = "+requestHeader.getFlag()+ // ", bodyName = "+requestBody.getName()+ // ", bodyMethodName = "+requestBody.getMethodName()); RequestContent requestContent = new RequestContent(); requestContent.setRequestHeader(requestHeader); requestContent.setRequestBody(requestBody); // 出发消息读取事件 ctx.fireChannelRead(requestContent); } } /** * 消息编码器 */ static final class Encoder extends MessageToByteEncoder<RequestContent> { @Override protected void encode(ChannelHandlerContext ctx, RequestContent innerMsg, ByteBuf byteBuf) { // 写出head byteBuf
.writeBytes(innerMsg.getRequestHeader().toBytesArray());
// 写出body byteBuf.writeBytes(innerMsg.getRequestBody().toBytesArray()); // 释放内存 innerMsg.free(); } } }
lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/InternalServerMsgCodec.java
hiparker-lint-rpc-framework-e64aac0
[ { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/ServerChannelHandler.java", "retrieved_chunk": " }catch (Exception e){\n e.printStackTrace();\n }\n requestHeader.setLength(requestBody.toBytesArray().length);\n ctx.channel().writeAndFlush(content);\n // 转多线程处理\n// ExecuteThread et = ExecuteThread.getInstance();\n// et.execute(()->{\n// ProvideServiceSpi spi = ProvideServiceSpi.getInstance();\n// LintService service = spi.getService(requestBody.getName(), requestHeader.getVersion());", "score": 0.8370847105979919 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/ServerChannelHandler.java", "retrieved_chunk": "public class ServerChannelHandler extends ChannelInboundHandlerAdapter {\n @Override\n public void channelRead(ChannelHandlerContext ctx, Object msg) {\n if(!(msg instanceof RequestContent)){\n return;\n }\n //System.out.println(Thread.currentThread().getName() + \" 服务端处理数据......\");\n RequestContent content = (RequestContent) msg;\n RequestHeader requestHeader = content.getRequestHeader();\n RequestBody requestBody = content.getRequestBody();", "score": 0.8370308876037598 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/ClientChannelHandler.java", "retrieved_chunk": " public void channelRead(ChannelHandlerContext ctx, Object msg) {\n if(!(msg instanceof RequestContent)){\n return;\n }\n //System.out.println(\"客户端处理数据......\");\n RequestContent content = (RequestContent) msg;\n RequestHeader requestHeader = content.getRequestHeader();\n RequestBody requestBody = content.getRequestBody();\n MsgPool.put(requestHeader.getRequestId(), requestBody.getRes());\n CountDownLatchPool.countDown(requestHeader.getRequestId());", "score": 0.836545467376709 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/ServerChannelHandler.java", "retrieved_chunk": "// }\n//\n// requestHeader.setLength(requestBody.toBytesArray().length);\n// ctx.channel().writeAndFlush(content);\n// });\n }\n}", "score": 0.8255678415298462 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/ClientChannelHandler.java", "retrieved_chunk": "package com.lint.rpc.common.transport;\nimport com.lint.rpc.common.pool.CountDownLatchPool;\nimport com.lint.rpc.common.pool.MsgPool;\nimport com.lint.rpc.common.protocol.RequestBody;\nimport com.lint.rpc.common.protocol.RequestContent;\nimport com.lint.rpc.common.protocol.RequestHeader;\nimport io.netty.channel.ChannelHandlerContext;\nimport io.netty.channel.ChannelInboundHandlerAdapter;\npublic class ClientChannelHandler extends ChannelInboundHandlerAdapter {\n @Override", "score": 0.8248128294944763 } ]
java
.writeBytes(innerMsg.getRequestHeader().toBytesArray());
package com.lint.rpc.common.transport; import com.lint.rpc.common.protocol.RequestBody; import com.lint.rpc.common.protocol.RequestContent; import com.lint.rpc.common.protocol.RequestHeader; import com.lint.rpc.common.service.ProvideServiceSpi; import com.lint.rpc.common.spi.LintService; import com.lint.rpc.common.thread.ExecuteThread; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import java.lang.reflect.Method; public class ServerChannelHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if(!(msg instanceof RequestContent)){ return; } //System.out.println(Thread.currentThread().getName() + " 服务端处理数据......"); RequestContent content = (RequestContent) msg; RequestHeader requestHeader = content.getRequestHeader(); RequestBody requestBody = content.getRequestBody(); // 本身可以受到 NettyEventLoop线程 进行多线程执行 ProvideServiceSpi spi = ProvideServiceSpi.getInstance(); LintService service = spi.getService(requestBody.getName(), requestHeader.getVersion()); if(null == service){ return; } try { Method method = service.getClass().getMethod(requestBody.getMethodName()); Object res = method.invoke(service, requestBody.getArgs());
requestBody.setRes(res);
}catch (Exception e){ e.printStackTrace(); } requestHeader.setLength(requestBody.toBytesArray().length); ctx.channel().writeAndFlush(content); // 转多线程处理 // ExecuteThread et = ExecuteThread.getInstance(); // et.execute(()->{ // ProvideServiceSpi spi = ProvideServiceSpi.getInstance(); // LintService service = spi.getService(requestBody.getName(), requestHeader.getVersion()); // if(null == service){ // return; // } // // try { // Method method = service.getClass().getMethod(requestBody.getMethodName()); // Object res = method.invoke(service, requestBody.getArgs()); // requestBody.setRes(res); // }catch (Exception e){ // e.printStackTrace(); // } // // requestHeader.setLength(requestBody.toBytesArray().length); // ctx.channel().writeAndFlush(content); // }); } }
lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/ServerChannelHandler.java
hiparker-lint-rpc-framework-e64aac0
[ { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/InternalServerMsgCodec.java", "retrieved_chunk": "// \", bodyName = \"+requestBody.getName()+\n// \", bodyMethodName = \"+requestBody.getMethodName());\n RequestContent requestContent = new RequestContent();\n requestContent.setRequestHeader(requestHeader);\n requestContent.setRequestBody(requestBody);\n // 出发消息读取事件\n ctx.fireChannelRead(requestContent);\n }\n }\n /**", "score": 0.8395037651062012 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/proxy/RpcInvocationHandler.java", "retrieved_chunk": " CountDownLatchPool.free(requestHeader.getRequestId());\n }\n long endTime = System.currentTimeMillis();\n System.out.println(\"Invoke \"+interfaceInfo.getName()+\n \"(\"+annotation.name()+\":\"+annotation.version()+\n \") used >>> \" + (endTime - startTime) + \" ms!\");\n // 序列化处理\n return responseMsg;\n }\n}", "score": 0.8282194137573242 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/bootstrap/LintRpcClientApplication.java", "retrieved_chunk": " provideSpi.init();\n // TODO baseClazz 后序扩展一下\n }\n}", "score": 0.81723952293396 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/bootstrap/LintRpcServerApplication.java", "retrieved_chunk": " confPool.init(conf);\n // 2. 加载SPI 并初始化\n ProvideSpi provideSpi = ProvideSpi.getInstance();\n provideSpi.init();\n // 3. 加载服务端SPI\n ProvideServiceSpi provideServiceSpi = ProvideServiceSpi.getInstance();\n provideServiceSpi.init();\n // TODO baseClazz 后序扩展一下\n // 4. 启动服务端\n NettyServerConf nettyServerConf = new NettyServerConf();", "score": 0.8169780373573303 }, { "filename": "lint-rpc-demo/lint-rpc-demo-consumer/src/main/java/com/lint/rpc/demo/consumer/proxy/ProvideEatInterfaceSpi.java", "retrieved_chunk": "package com.lint.rpc.demo.consumer.proxy;\nimport com.lint.rpc.common.annotation.RpcClient;\nimport com.lint.rpc.demo.spi.ProvideEatInterface;\n@RpcClient(name = \"provide1\", version = 1)\npublic interface ProvideEatInterfaceSpi extends ProvideEatInterface {\n}", "score": 0.8162699341773987 } ]
java
requestBody.setRes(res);
package com.lint.rpc.common.transport; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import java.net.InetSocketAddress; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.concurrent.Future; import java.util.function.Consumer; /** * Netty 客户端 * * @author 周鹏程 * @date 2023-05-26 12:45 PM **/ public class NettyClient { private final NettyConf conf; private volatile NioSocketChannel ch; public NettyClient(NettyConf conf){ this.conf = conf; } public boolean sendMsg(Object msg){ if(ch == null){ synchronized (this){ if(ch == null){ this.connect(); } } } if(ch == null){ return false; } try { ch.writeAndFlush(msg).sync(); return true; } catch (InterruptedException e) { e.printStackTrace(); } return false; } public NettyConf getConf() { return conf; } private void connect(){ if(null == conf.getAddress()){ return; } NioEventLoopGroup workGroup = new NioEventLoopGroup(); Bootstrap bs = new Bootstrap(); bs.group(workGroup) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<NioSocketChannel>() { @Override protected void initChannel(NioSocketChannel ch) { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new InternalServerMsgCodec()); pipeline.addLast(new ClientChannelHandler()); } }); try { ChannelFuture f = bs.connect(conf.getAddress()).sync(); if (!f.isSuccess()) { return; } ch = (NioSocketChannel) f.channel(); ch.closeFuture().addListener(this::onLoseConnect); System.out.println(">>> 连接到业务服务器成功! "+conf.getAddress()+" <<<"); } catch (InterruptedException e) { e.printStackTrace(); } } /** * 当失去连接时 * * @param f 预期 */ private void onLoseConnect(Future<?> f) { System.out.println("系统通知 - 注意: 服务器连接关闭! >>> " + conf.getAddress()); this.ch = null; final Consumer<
NettyClient> closeCallback = conf.getCloseCallback();
if(null != closeCallback){ closeCallback.accept(this); } } @Override public int hashCode() { return Objects.hash(conf.getAddress().getHostName(), conf.getAddress().getPort()); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()){ return false; } NettyConf selfConf = this.getConf(); NettyClient client = (NettyClient) obj; NettyConf clientConf = client.getConf(); return selfConf.getAddress().getHostName().equals(clientConf.getAddress().getHostName()) && selfConf.getAddress().getPort() == clientConf.getAddress().getPort(); } }
lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyClient.java
hiparker-lint-rpc-framework-e64aac0
[ { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyConf.java", "retrieved_chunk": "package com.lint.rpc.common.transport;\nimport java.net.InetSocketAddress;\nimport java.util.function.Consumer;\npublic class NettyConf {\n private InetSocketAddress address;\n private Consumer<NettyClient> closeCallback;\n public InetSocketAddress getAddress() {\n return address;\n }\n public void setAddress(InetSocketAddress address) {", "score": 0.8039466142654419 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyConf.java", "retrieved_chunk": " this.address = address;\n }\n public Consumer<NettyClient> getCloseCallback() {\n return closeCallback;\n }\n public void setCloseCallback(Consumer<NettyClient> closeCallback) {\n this.closeCallback = closeCallback;\n }\n}", "score": 0.8036926984786987 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyServer.java", "retrieved_chunk": " try {\n System.out.println(\"Lint Server port: \" + conf.getPort());\n ChannelFuture f = bind.sync();\n if (!f.isSuccess()) {\n throw new RpcException(RpcMsg.EXCEPTION_SERVICE_NOT_STARTED);\n }\n bind.channel().closeFuture().sync();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }", "score": 0.7998684048652649 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ClientPool.java", "retrieved_chunk": " }\n }\n }\n return nc;\n }\n private NettyClient createClient(String serviceName, InetSocketAddress address){\n NettyConf conf = new NettyConf();\n conf.setAddress(address);\n conf.setCloseCallback((c)->{\n try {", "score": 0.7972902655601501 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyServer.java", "retrieved_chunk": "/**\n * Netty 服务端\n *\n * @author 周鹏程\n * @date 2023-05-26 12:45 PM\n **/\npublic class NettyServer {\n private final NettyServerConf conf;\n public NettyServer(NettyServerConf conf){\n this.conf = conf;", "score": 0.788396954536438 } ]
java
NettyClient> closeCallback = conf.getCloseCallback();
package com.lint.rpc.common.transport; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import java.net.InetSocketAddress; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.concurrent.Future; import java.util.function.Consumer; /** * Netty 客户端 * * @author 周鹏程 * @date 2023-05-26 12:45 PM **/ public class NettyClient { private final NettyConf conf; private volatile NioSocketChannel ch; public NettyClient(NettyConf conf){ this.conf = conf; } public boolean sendMsg(Object msg){ if(ch == null){ synchronized (this){ if(ch == null){ this.connect(); } } } if(ch == null){ return false; } try { ch.writeAndFlush(msg).sync(); return true; } catch (InterruptedException e) { e.printStackTrace(); } return false; } public NettyConf getConf() { return conf; } private void connect(){ if(null == conf.getAddress()){ return; } NioEventLoopGroup workGroup = new NioEventLoopGroup(); Bootstrap bs = new Bootstrap(); bs.group(workGroup) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<NioSocketChannel>() { @Override protected void initChannel(NioSocketChannel ch) { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new InternalServerMsgCodec()); pipeline.addLast(new ClientChannelHandler()); } }); try { ChannelFuture f =
bs.connect(conf.getAddress()).sync();
if (!f.isSuccess()) { return; } ch = (NioSocketChannel) f.channel(); ch.closeFuture().addListener(this::onLoseConnect); System.out.println(">>> 连接到业务服务器成功! "+conf.getAddress()+" <<<"); } catch (InterruptedException e) { e.printStackTrace(); } } /** * 当失去连接时 * * @param f 预期 */ private void onLoseConnect(Future<?> f) { System.out.println("系统通知 - 注意: 服务器连接关闭! >>> " + conf.getAddress()); this.ch = null; final Consumer<NettyClient> closeCallback = conf.getCloseCallback(); if(null != closeCallback){ closeCallback.accept(this); } } @Override public int hashCode() { return Objects.hash(conf.getAddress().getHostName(), conf.getAddress().getPort()); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()){ return false; } NettyConf selfConf = this.getConf(); NettyClient client = (NettyClient) obj; NettyConf clientConf = client.getConf(); return selfConf.getAddress().getHostName().equals(clientConf.getAddress().getHostName()) && selfConf.getAddress().getPort() == clientConf.getAddress().getPort(); } }
lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyClient.java
hiparker-lint-rpc-framework-e64aac0
[ { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyServer.java", "retrieved_chunk": " .group(bossGroup, workerGroup)\n .childHandler(new ChannelInitializer<NioSocketChannel>() {\n @Override\n protected void initChannel(NioSocketChannel ch) {\n ChannelPipeline p = ch.pipeline();\n p.addLast(new InternalServerMsgCodec());\n p.addLast(new ServerChannelHandler());\n }\n })\n .bind(conf.getPort());", "score": 0.902729868888855 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyServer.java", "retrieved_chunk": " }\n public NettyServerConf getConf() {\n return conf;\n }\n public void init(){\n int cpuCount = Runtime.getRuntime().availableProcessors();\n NioEventLoopGroup bossGroup = new NioEventLoopGroup();\n NioEventLoopGroup workerGroup = new NioEventLoopGroup(getThreadMaxCount(cpuCount));\n ServerBootstrap bs = new ServerBootstrap();\n ChannelFuture bind = bs.channel(NioServerSocketChannel.class)", "score": 0.8756229877471924 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyServer.java", "retrieved_chunk": "package com.lint.rpc.common.transport;\nimport com.lint.rpc.common.enums.RpcMsg;\nimport com.lint.rpc.common.exception.RpcException;\nimport io.netty.bootstrap.ServerBootstrap;\nimport io.netty.channel.ChannelFuture;\nimport io.netty.channel.ChannelInitializer;\nimport io.netty.channel.ChannelPipeline;\nimport io.netty.channel.nio.NioEventLoopGroup;\nimport io.netty.channel.socket.nio.NioServerSocketChannel;\nimport io.netty.channel.socket.nio.NioSocketChannel;", "score": 0.8387934565544128 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyServer.java", "retrieved_chunk": " try {\n System.out.println(\"Lint Server port: \" + conf.getPort());\n ChannelFuture f = bind.sync();\n if (!f.isSuccess()) {\n throw new RpcException(RpcMsg.EXCEPTION_SERVICE_NOT_STARTED);\n }\n bind.channel().closeFuture().sync();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }", "score": 0.8341907858848572 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyServer.java", "retrieved_chunk": "/**\n * Netty 服务端\n *\n * @author 周鹏程\n * @date 2023-05-26 12:45 PM\n **/\npublic class NettyServer {\n private final NettyServerConf conf;\n public NettyServer(NettyServerConf conf){\n this.conf = conf;", "score": 0.8339366316795349 } ]
java
bs.connect(conf.getAddress()).sync();
package com.lint.rpc.common.transport; import com.lint.rpc.common.protocol.RequestBody; import com.lint.rpc.common.protocol.RequestContent; import com.lint.rpc.common.protocol.RequestHeader; import com.lint.rpc.common.service.ProvideServiceSpi; import com.lint.rpc.common.spi.LintService; import com.lint.rpc.common.thread.ExecuteThread; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import java.lang.reflect.Method; public class ServerChannelHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if(!(msg instanceof RequestContent)){ return; } //System.out.println(Thread.currentThread().getName() + " 服务端处理数据......"); RequestContent content = (RequestContent) msg; RequestHeader requestHeader = content.getRequestHeader(); RequestBody requestBody = content.getRequestBody(); // 本身可以受到 NettyEventLoop线程 进行多线程执行 ProvideServiceSpi spi = ProvideServiceSpi.getInstance(); LintService service = spi.getService(requestBody.getName(), requestHeader.getVersion()); if(null == service){ return; } try { Method method = service.getClass().getMethod(requestBody.getMethodName()); Object res = method.invoke(service, requestBody.getArgs()); requestBody.setRes(res); }catch (Exception e){ e.printStackTrace(); } requestHeader
.setLength(requestBody.toBytesArray().length);
ctx.channel().writeAndFlush(content); // 转多线程处理 // ExecuteThread et = ExecuteThread.getInstance(); // et.execute(()->{ // ProvideServiceSpi spi = ProvideServiceSpi.getInstance(); // LintService service = spi.getService(requestBody.getName(), requestHeader.getVersion()); // if(null == service){ // return; // } // // try { // Method method = service.getClass().getMethod(requestBody.getMethodName()); // Object res = method.invoke(service, requestBody.getArgs()); // requestBody.setRes(res); // }catch (Exception e){ // e.printStackTrace(); // } // // requestHeader.setLength(requestBody.toBytesArray().length); // ctx.channel().writeAndFlush(content); // }); } }
lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/ServerChannelHandler.java
hiparker-lint-rpc-framework-e64aac0
[ { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/proxy/RpcInvocationHandler.java", "retrieved_chunk": " String methodName = method.getName();\n Class<?>[] parameterTypes = method.getParameterTypes();\n RequestBody requestBody = new RequestBody();\n requestBody.setName(annotation.name());\n requestBody.setMethodName(methodName);\n requestBody.setParameterTypes(parameterTypes);\n requestBody.setArgs(args);\n RequestHeader requestHeader = new RequestHeader(requestBody.toBytesArray());\n requestHeader.setVersion(annotation.version());\n RequestContent requestContent = new RequestContent();", "score": 0.8672837018966675 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/protocol/RequestContent.java", "retrieved_chunk": " private RequestBody requestBody;\n public RequestHeader getRequestHeader() {\n return requestHeader;\n }\n public void setRequestHeader(RequestHeader requestHeader) {\n this.requestHeader = requestHeader;\n }\n public RequestBody getRequestBody() {\n return requestBody;\n }", "score": 0.8525077104568481 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/InternalServerMsgCodec.java", "retrieved_chunk": " ObjectInputStream ois = new ObjectInputStream(in);\n ) {\n requestBody = (RequestBody) ois.readObject();\n } catch (IOException | ClassNotFoundException e) {\n e.printStackTrace();\n requestBody = new RequestBody();\n }\n// System.out.println(\"收到消息 => \" +\n// \"requestId = \"+requestHeader.getRequestId() +\n// \", flag = \"+requestHeader.getFlag()+", "score": 0.8524085283279419 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/InternalServerMsgCodec.java", "retrieved_chunk": " RequestHeader requestHeader = null;\n try(ByteArrayInputStream in = new ByteArrayInputStream(headByteArray);\n ObjectInputStream ois = new ObjectInputStream(in);\n ) {\n requestHeader = (RequestHeader) ois.readObject();\n } catch (IOException | ClassNotFoundException e) {\n e.printStackTrace();\n }\n // 如果消息体长度不够 直接退出\n if(null == requestHeader ||", "score": 0.8462969064712524 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/protocol/RequestHeader.java", "retrieved_chunk": "public class RequestHeader implements Serializable {\n /** 标识 */\n private int flag;\n /** 请求ID */\n private long requestId;\n /** 长度 */\n private int length;\n public RequestHeader(byte[] requestBodyBytes){\n requestId = Math.abs(UUID.randomUUID().getLeastSignificantBits());\n length = requestBodyBytes.length;", "score": 0.8456591963768005 } ]
java
.setLength(requestBody.toBytesArray().length);
package com.lint.rpc.common.transport; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import java.net.InetSocketAddress; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.concurrent.Future; import java.util.function.Consumer; /** * Netty 客户端 * * @author 周鹏程 * @date 2023-05-26 12:45 PM **/ public class NettyClient { private final NettyConf conf; private volatile NioSocketChannel ch; public NettyClient(NettyConf conf){ this.conf = conf; } public boolean sendMsg(Object msg){ if(ch == null){ synchronized (this){ if(ch == null){ this.connect(); } } } if(ch == null){ return false; } try { ch.writeAndFlush(msg).sync(); return true; } catch (InterruptedException e) { e.printStackTrace(); } return false; } public NettyConf getConf() { return conf; } private void connect(){ if(null == conf.getAddress()){ return; } NioEventLoopGroup workGroup = new NioEventLoopGroup(); Bootstrap bs = new Bootstrap(); bs.group(workGroup) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<NioSocketChannel>() { @Override protected void initChannel(NioSocketChannel ch) { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new InternalServerMsgCodec()); pipeline.addLast(new ClientChannelHandler()); } }); try { ChannelFuture f = bs.connect(conf.getAddress()).sync(); if (!f.isSuccess()) { return; } ch = (NioSocketChannel) f.channel(); ch.closeFuture().addListener(this::onLoseConnect); System.out.println(">>> 连接到业务服务器成功! "+conf.getAddress()+" <<<"); } catch (InterruptedException e) { e.printStackTrace(); } } /** * 当失去连接时 * * @param f 预期 */ private void onLoseConnect(Future<?> f) { System.out.println("系统通知 - 注意: 服务器连接关闭! >>> " + conf.getAddress()); this.ch = null; final Consumer<NettyClient> closeCallback = conf.getCloseCallback(); if(null != closeCallback){ closeCallback.accept(this); } } @Override public int hashCode() { return
Objects.hash(conf.getAddress().getHostName(), conf.getAddress().getPort());
} @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()){ return false; } NettyConf selfConf = this.getConf(); NettyClient client = (NettyClient) obj; NettyConf clientConf = client.getConf(); return selfConf.getAddress().getHostName().equals(clientConf.getAddress().getHostName()) && selfConf.getAddress().getPort() == clientConf.getAddress().getPort(); } }
lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyClient.java
hiparker-lint-rpc-framework-e64aac0
[ { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyConf.java", "retrieved_chunk": " this.address = address;\n }\n public Consumer<NettyClient> getCloseCallback() {\n return closeCallback;\n }\n public void setCloseCallback(Consumer<NettyClient> closeCallback) {\n this.closeCallback = closeCallback;\n }\n}", "score": 0.8673731684684753 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyConf.java", "retrieved_chunk": "package com.lint.rpc.common.transport;\nimport java.net.InetSocketAddress;\nimport java.util.function.Consumer;\npublic class NettyConf {\n private InetSocketAddress address;\n private Consumer<NettyClient> closeCallback;\n public InetSocketAddress getAddress() {\n return address;\n }\n public void setAddress(InetSocketAddress address) {", "score": 0.8614388108253479 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ClientPool.java", "retrieved_chunk": " }\n }\n }\n return nc;\n }\n private NettyClient createClient(String serviceName, InetSocketAddress address){\n NettyConf conf = new NettyConf();\n conf.setAddress(address);\n conf.setCloseCallback((c)->{\n try {", "score": 0.8378787040710449 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyServer.java", "retrieved_chunk": " }\n public NettyServerConf getConf() {\n return conf;\n }\n public void init(){\n int cpuCount = Runtime.getRuntime().availableProcessors();\n NioEventLoopGroup bossGroup = new NioEventLoopGroup();\n NioEventLoopGroup workerGroup = new NioEventLoopGroup(getThreadMaxCount(cpuCount));\n ServerBootstrap bs = new ServerBootstrap();\n ChannelFuture bind = bs.channel(NioServerSocketChannel.class)", "score": 0.8303980827331543 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyServer.java", "retrieved_chunk": "/**\n * Netty 服务端\n *\n * @author 周鹏程\n * @date 2023-05-26 12:45 PM\n **/\npublic class NettyServer {\n private final NettyServerConf conf;\n public NettyServer(NettyServerConf conf){\n this.conf = conf;", "score": 0.8162801861763 } ]
java
Objects.hash(conf.getAddress().getHostName(), conf.getAddress().getPort());
package com.lint.rpc.common.pool; import com.lint.rpc.common.LintConf; import com.lint.rpc.common.balance.ILoadBalancePolicy; import com.lint.rpc.common.service.ProvideSpi; import com.lint.rpc.common.transport.ClientFactory; import com.lint.rpc.common.transport.NettyClient; import com.lint.rpc.common.transport.NettyConf; import java.net.InetSocketAddress; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; /** * 客户端连接池 * * @author 周鹏程 * @date 2023-05-26 7:38 PM **/ public final class ClientPool { // serviceName 为服务名 // hostname+port 为组名 // 连接池 private final Map<String, LinkedHashSet<NettyClient>> groupPool = new ConcurrentHashMap<>(); private final Map<String, LinkedHashSet<String>> servicePool = new ConcurrentHashMap<>(); private final ReentrantLock rLock = new ReentrantLock(); public NettyClient get(String serviceName, ILoadBalancePolicy loadBalancePolicy){ ConfPool confPool = ConfPool.getInstance(); LintConf lintConf = confPool.get(); ProvideSpi provideSpi = ProvideSpi.getInstance(); LinkedHashSet<InetSocketAddress> addressSet = provideSpi.getAddressByServiceName(serviceName); if(null == addressSet){ return null; } LinkedHashSet<String> groupNameSet = servicePool.get(serviceName); if(null == groupNameSet || groupNameSet.isEmpty()){ try { rLock.lock(); groupNameSet = servicePool.get(serviceName); if(null == groupNameSet || groupNameSet.isEmpty()){ int clientIndex =
loadBalancePolicy.getClientIndex(addressSet.size());
InetSocketAddress inetSocketAddress = linkedHashSetGetByIndex(addressSet, clientIndex); NettyClient ch = createClient(serviceName, inetSocketAddress); return put(serviceName, ch); } }finally { rLock.unlock(); } } NettyClient ch = null; // 如果不相等 优先使用为开辟的新链接 if(groupNameSet.size() != addressSet.size()){ try { rLock.lock(); if(groupNameSet.size() != addressSet.size()) { InetSocketAddress address = null; Iterator<InetSocketAddress> iterator = addressSet.stream().iterator(); while (iterator.hasNext()){ address = iterator.next(); String groupName = getGroupName(address); boolean contains = groupNameSet.contains(groupName); if(!contains){ break; } } ch = createClient(serviceName, address); if(ch != null){ return put(serviceName, ch); } } }finally { rLock.unlock(); } } // 如果上述操作 ch == null 或者 group相等 那就准备 从现有队列中选择一位连接 int groupIndex = loadBalancePolicy.getClientIndex(groupNameSet.size()); String groupName = linkedHashSetGetByIndex(groupNameSet, groupIndex); LinkedHashSet<NettyClient> ncSet = groupPool.get(groupName); if(null != ncSet){ // 如果当前开辟的连接数 还未达到自定义配置的最大值 则继续开辟连接 if(ncSet.size() < lintConf.getClientMaxConnCount()){ try { rLock.lock(); if(ncSet.size() < lintConf.getClientMaxConnCount()){ String[] address = groupName.split(":"); InetSocketAddress inetSocketAddress = new InetSocketAddress( address[0], Integer.parseInt(address[1])); ch = createClient(serviceName, inetSocketAddress); return put(serviceName, ch); } }finally { rLock.unlock(); } } int chIndex = loadBalancePolicy.getClientIndex(groupNameSet.size()); ch = linkedHashSetGetByIndex(ncSet, chIndex); } return ch; } private NettyClient put( String serviceName, NettyClient nc){ if(null == nc){ return null; } int lockCount = 0; try { Set<String> groupSet = servicePool.get(serviceName); if(null == groupSet){ rLock.lock(); lockCount++; groupSet = servicePool.computeIfAbsent(serviceName, k -> new LinkedHashSet<>()); } NettyConf conf = nc.getConf(); String groupName = getGroupName(conf.getAddress()); Set<NettyClient> nettyClientSet = groupPool.get(groupName); if(null == nettyClientSet){ rLock.lock(); lockCount++; nettyClientSet = groupPool.computeIfAbsent(groupName, k -> new LinkedHashSet<>()); } rLock.lock(); lockCount++; if(nettyClientSet.isEmpty()){ groupSet.add(groupName); } nettyClientSet.add(nc); }finally { if(lockCount > 0){ for (int i = 0; i < lockCount; i++) { rLock.unlock(); } } } return nc; } private NettyClient createClient(String serviceName, InetSocketAddress address){ NettyConf conf = new NettyConf(); conf.setAddress(address); conf.setCloseCallback((c)->{ try { rLock.lock(); String groupName = getGroupName(address); Set<NettyClient> nettyClients = groupPool.get(groupName); nettyClients.remove(c); if(nettyClients.isEmpty()){ groupPool.remove(groupName); Set<String> groupSet = servicePool.get(serviceName); groupSet.remove(groupName); if(groupSet.isEmpty()){ servicePool.remove(serviceName); } } }finally { rLock.unlock(); } }); ClientFactory factory = ClientFactory.getInstance(); return factory.create(conf); } private String getGroupName(InetSocketAddress address){ String hostName = address.getHostName(); int port = address.getPort(); return hostName+":"+port; } private <T> T linkedHashSetGetByIndex(LinkedHashSet<T> linkedHashSet, int index){ if(null == linkedHashSet){ return null; } T t = null; int chCurrIndex = 0; Iterator<T> chIterator = linkedHashSet.stream().iterator(); while (chIterator.hasNext() && chCurrIndex++ <= index){ t = chIterator.next(); } return t; } private static class LazyHolder { private static final ClientPool INSTANCE = new ClientPool(); } public static ClientPool getInstance() { return ClientPool.LazyHolder.INSTANCE; } private ClientPool(){} }
lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ClientPool.java
hiparker-lint-rpc-framework-e64aac0
[ { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/balance/LoadBalancePolicyFactory.java", "retrieved_chunk": " return null;\n }\n ClientPool pool = ClientPool.getInstance();\n // 选择客户端\n return pool.get(rpcClientAnnotation.name(), loadBalancePolicy);\n }\n private ILoadBalancePolicy getLoadBalancePolicy(\n Class<? extends ILoadBalancePolicy> loadBalancePolicyClazz){\n ILoadBalancePolicy loadBalancePolicy = loadBalancePolicyMap.get(loadBalancePolicyClazz);\n if(null != loadBalancePolicy){", "score": 0.8631985187530518 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/service/ProvideSpi.java", "retrieved_chunk": " }\n provideService = ps;\n break;\n }\n isInit = true;\n }\n }\n }\n }\n public LinkedHashSet<InetSocketAddress> getAddressByServiceName(String serviceName){", "score": 0.8378296494483948 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/balance/LoadBalancePolicyFactory.java", "retrieved_chunk": " return loadBalancePolicy;\n }\n // DCL\n synchronized (lock){\n loadBalancePolicy = loadBalancePolicyMap.get(loadBalancePolicyClazz);\n if(null != loadBalancePolicy){\n return loadBalancePolicy;\n }\n try {\n loadBalancePolicy = loadBalancePolicyClazz.newInstance();", "score": 0.8274307250976562 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/balance/LoadBalancePolicyFactory.java", "retrieved_chunk": " * @date 2023-05-26 10:53 AM\n **/\npublic class LoadBalancePolicyFactory {\n private final Object lock = new Object();\n private final Map<Class<? extends ILoadBalancePolicy>, ILoadBalancePolicy>\n loadBalancePolicyMap = new ConcurrentHashMap<>();\n public NettyClient getClient(Class<?> interfaceClazz) {\n RpcClient rpcClientAnnotation = interfaceClazz.getAnnotation(RpcClient.class);\n ILoadBalancePolicy loadBalancePolicy = getLoadBalancePolicy(rpcClientAnnotation.loadBalancePolicy());\n if(null == loadBalancePolicy){", "score": 0.8102257251739502 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/balance/LoadBalancePolicyFactory.java", "retrieved_chunk": " loadBalancePolicyMap.putIfAbsent(loadBalancePolicyClazz, loadBalancePolicy);\n }catch (Exception e){\n e.printStackTrace();\n }\n return loadBalancePolicy;\n }\n }\n private LoadBalancePolicyFactory(){}\n private static class LazyHolder {\n private static final LoadBalancePolicyFactory INSTANCE = new LoadBalancePolicyFactory();", "score": 0.8044916391372681 } ]
java
loadBalancePolicy.getClientIndex(addressSet.size());
package com.lint.rpc.common.pool; import com.lint.rpc.common.LintConf; import com.lint.rpc.common.balance.ILoadBalancePolicy; import com.lint.rpc.common.service.ProvideSpi; import com.lint.rpc.common.transport.ClientFactory; import com.lint.rpc.common.transport.NettyClient; import com.lint.rpc.common.transport.NettyConf; import java.net.InetSocketAddress; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; /** * 客户端连接池 * * @author 周鹏程 * @date 2023-05-26 7:38 PM **/ public final class ClientPool { // serviceName 为服务名 // hostname+port 为组名 // 连接池 private final Map<String, LinkedHashSet<NettyClient>> groupPool = new ConcurrentHashMap<>(); private final Map<String, LinkedHashSet<String>> servicePool = new ConcurrentHashMap<>(); private final ReentrantLock rLock = new ReentrantLock(); public NettyClient get(String serviceName, ILoadBalancePolicy loadBalancePolicy){ ConfPool confPool = ConfPool.getInstance(); LintConf lintConf = confPool.get(); ProvideSpi provideSpi = ProvideSpi.getInstance(); LinkedHashSet<InetSocketAddress> addressSet = provideSpi.getAddressByServiceName(serviceName); if(null == addressSet){ return null; } LinkedHashSet<String> groupNameSet = servicePool.get(serviceName); if(null == groupNameSet || groupNameSet.isEmpty()){ try { rLock.lock(); groupNameSet = servicePool.get(serviceName); if(null == groupNameSet || groupNameSet.isEmpty()){ int clientIndex = loadBalancePolicy.getClientIndex(addressSet.size()); InetSocketAddress inetSocketAddress = linkedHashSetGetByIndex(addressSet, clientIndex); NettyClient ch = createClient(serviceName, inetSocketAddress); return put(serviceName, ch); } }finally { rLock.unlock(); } } NettyClient ch = null; // 如果不相等 优先使用为开辟的新链接 if(groupNameSet.size() != addressSet.size()){ try { rLock.lock(); if(groupNameSet.size() != addressSet.size()) { InetSocketAddress address = null; Iterator<InetSocketAddress> iterator = addressSet.stream().iterator(); while (iterator.hasNext()){ address = iterator.next(); String groupName = getGroupName(address); boolean contains = groupNameSet.contains(groupName); if(!contains){ break; } } ch = createClient(serviceName, address); if(ch != null){ return put(serviceName, ch); } } }finally { rLock.unlock(); } } // 如果上述操作 ch == null 或者 group相等 那就准备 从现有队列中选择一位连接 int groupIndex = loadBalancePolicy.getClientIndex(groupNameSet.size()); String groupName = linkedHashSetGetByIndex(groupNameSet, groupIndex); LinkedHashSet<NettyClient> ncSet = groupPool.get(groupName); if(null != ncSet){ // 如果当前开辟的连接数 还未达到自定义配置的最大值 则继续开辟连接 if(ncSet.size() < lintConf.getClientMaxConnCount()){ try { rLock.lock(); if(ncSet.size() < lintConf.getClientMaxConnCount()){ String[] address = groupName.split(":"); InetSocketAddress inetSocketAddress = new InetSocketAddress( address[0], Integer.parseInt(address[1])); ch = createClient(serviceName, inetSocketAddress); return put(serviceName, ch); } }finally { rLock.unlock(); } } int chIndex = loadBalancePolicy.getClientIndex(groupNameSet.size()); ch = linkedHashSetGetByIndex(ncSet, chIndex); } return ch; } private NettyClient put( String serviceName, NettyClient nc){ if(null == nc){ return null; } int lockCount = 0; try { Set<String> groupSet = servicePool.get(serviceName); if(null == groupSet){ rLock.lock(); lockCount++; groupSet = servicePool.computeIfAbsent(serviceName, k -> new LinkedHashSet<>()); } NettyConf conf = nc.getConf(); String groupName = getGroupName(conf.getAddress()); Set<NettyClient> nettyClientSet = groupPool.get(groupName); if(null == nettyClientSet){ rLock.lock(); lockCount++; nettyClientSet = groupPool.computeIfAbsent(groupName, k -> new LinkedHashSet<>()); } rLock.lock(); lockCount++; if(nettyClientSet.isEmpty()){ groupSet.add(groupName); } nettyClientSet.add(nc); }finally { if(lockCount > 0){ for (int i = 0; i < lockCount; i++) { rLock.unlock(); } } } return nc; } private NettyClient createClient(String serviceName, InetSocketAddress address){ NettyConf conf = new NettyConf(); conf.setAddress(address); conf.setCloseCallback((c)->{ try { rLock.lock(); String groupName = getGroupName(address); Set<NettyClient> nettyClients = groupPool.get(groupName); nettyClients.remove(c); if(nettyClients.isEmpty()){ groupPool.remove(groupName); Set<String> groupSet = servicePool.get(serviceName); groupSet.remove(groupName); if(groupSet.isEmpty()){ servicePool.remove(serviceName); } } }finally { rLock.unlock(); } }); ClientFactory
factory = ClientFactory.getInstance();
return factory.create(conf); } private String getGroupName(InetSocketAddress address){ String hostName = address.getHostName(); int port = address.getPort(); return hostName+":"+port; } private <T> T linkedHashSetGetByIndex(LinkedHashSet<T> linkedHashSet, int index){ if(null == linkedHashSet){ return null; } T t = null; int chCurrIndex = 0; Iterator<T> chIterator = linkedHashSet.stream().iterator(); while (chIterator.hasNext() && chCurrIndex++ <= index){ t = chIterator.next(); } return t; } private static class LazyHolder { private static final ClientPool INSTANCE = new ClientPool(); } public static ClientPool getInstance() { return ClientPool.LazyHolder.INSTANCE; } private ClientPool(){} }
lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ClientPool.java
hiparker-lint-rpc-framework-e64aac0
[ { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/balance/LoadBalancePolicyFactory.java", "retrieved_chunk": " return null;\n }\n ClientPool pool = ClientPool.getInstance();\n // 选择客户端\n return pool.get(rpcClientAnnotation.name(), loadBalancePolicy);\n }\n private ILoadBalancePolicy getLoadBalancePolicy(\n Class<? extends ILoadBalancePolicy> loadBalancePolicyClazz){\n ILoadBalancePolicy loadBalancePolicy = loadBalancePolicyMap.get(loadBalancePolicyClazz);\n if(null != loadBalancePolicy){", "score": 0.8018708229064941 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/service/ProvideSpi.java", "retrieved_chunk": " }\n provideService = ps;\n break;\n }\n isInit = true;\n }\n }\n }\n }\n public LinkedHashSet<InetSocketAddress> getAddressByServiceName(String serviceName){", "score": 0.7984985709190369 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/CountDownLatchPool.java", "retrieved_chunk": " timeoutSeconds = 0;\n }\n CountDownLatch countDownLatch = new CountDownLatch(1);\n // 超时自动释放\n MSG_POOL_MAP.putIfAbsent(requestId, countDownLatch);\n countDownLatch.await(timeoutSeconds, TimeUnit.SECONDS);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }", "score": 0.7942901253700256 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/ClientFactory.java", "retrieved_chunk": " }\n private static class LazyHolder {\n private static final ClientFactory INSTANCE = new ClientFactory();\n }\n public static ClientFactory getInstance() {\n return ClientFactory.LazyHolder.INSTANCE;\n }\n private ClientFactory(){}\n}", "score": 0.78666090965271 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/service/ProvideServiceSpi.java", "retrieved_chunk": " return serviceMap.get(serviceName+\":\"+version);\n }\n private static class LazyHolder {\n private static final ProvideServiceSpi INSTANCE = new ProvideServiceSpi();\n }\n public static ProvideServiceSpi getInstance() {\n return LazyHolder.INSTANCE;\n }\n private ProvideServiceSpi(){}\n}", "score": 0.7807986736297607 } ]
java
factory = ClientFactory.getInstance();
package com.lint.rpc.common.pool; import com.lint.rpc.common.LintConf; import com.lint.rpc.common.balance.ILoadBalancePolicy; import com.lint.rpc.common.service.ProvideSpi; import com.lint.rpc.common.transport.ClientFactory; import com.lint.rpc.common.transport.NettyClient; import com.lint.rpc.common.transport.NettyConf; import java.net.InetSocketAddress; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; /** * 客户端连接池 * * @author 周鹏程 * @date 2023-05-26 7:38 PM **/ public final class ClientPool { // serviceName 为服务名 // hostname+port 为组名 // 连接池 private final Map<String, LinkedHashSet<NettyClient>> groupPool = new ConcurrentHashMap<>(); private final Map<String, LinkedHashSet<String>> servicePool = new ConcurrentHashMap<>(); private final ReentrantLock rLock = new ReentrantLock(); public NettyClient get(String serviceName, ILoadBalancePolicy loadBalancePolicy){ ConfPool confPool = ConfPool.getInstance(); LintConf lintConf = confPool.get(); ProvideSpi provideSpi = ProvideSpi.getInstance(); LinkedHashSet<InetSocketAddress> addressSet = provideSpi.getAddressByServiceName(serviceName); if(null == addressSet){ return null; } LinkedHashSet<String> groupNameSet = servicePool.get(serviceName); if(null == groupNameSet || groupNameSet.isEmpty()){ try { rLock.lock(); groupNameSet = servicePool.get(serviceName); if(null == groupNameSet || groupNameSet.isEmpty()){ int clientIndex = loadBalancePolicy.getClientIndex(addressSet.size()); InetSocketAddress inetSocketAddress = linkedHashSetGetByIndex(addressSet, clientIndex); NettyClient ch = createClient(serviceName, inetSocketAddress); return put(serviceName, ch); } }finally { rLock.unlock(); } } NettyClient ch = null; // 如果不相等 优先使用为开辟的新链接 if(groupNameSet.size() != addressSet.size()){ try { rLock.lock(); if(groupNameSet.size() != addressSet.size()) { InetSocketAddress address = null; Iterator<InetSocketAddress> iterator = addressSet.stream().iterator(); while (iterator.hasNext()){ address = iterator.next(); String groupName = getGroupName(address); boolean contains = groupNameSet.contains(groupName); if(!contains){ break; } } ch = createClient(serviceName, address); if(ch != null){ return put(serviceName, ch); } } }finally { rLock.unlock(); } } // 如果上述操作 ch == null 或者 group相等 那就准备 从现有队列中选择一位连接 int
groupIndex = loadBalancePolicy.getClientIndex(groupNameSet.size());
String groupName = linkedHashSetGetByIndex(groupNameSet, groupIndex); LinkedHashSet<NettyClient> ncSet = groupPool.get(groupName); if(null != ncSet){ // 如果当前开辟的连接数 还未达到自定义配置的最大值 则继续开辟连接 if(ncSet.size() < lintConf.getClientMaxConnCount()){ try { rLock.lock(); if(ncSet.size() < lintConf.getClientMaxConnCount()){ String[] address = groupName.split(":"); InetSocketAddress inetSocketAddress = new InetSocketAddress( address[0], Integer.parseInt(address[1])); ch = createClient(serviceName, inetSocketAddress); return put(serviceName, ch); } }finally { rLock.unlock(); } } int chIndex = loadBalancePolicy.getClientIndex(groupNameSet.size()); ch = linkedHashSetGetByIndex(ncSet, chIndex); } return ch; } private NettyClient put( String serviceName, NettyClient nc){ if(null == nc){ return null; } int lockCount = 0; try { Set<String> groupSet = servicePool.get(serviceName); if(null == groupSet){ rLock.lock(); lockCount++; groupSet = servicePool.computeIfAbsent(serviceName, k -> new LinkedHashSet<>()); } NettyConf conf = nc.getConf(); String groupName = getGroupName(conf.getAddress()); Set<NettyClient> nettyClientSet = groupPool.get(groupName); if(null == nettyClientSet){ rLock.lock(); lockCount++; nettyClientSet = groupPool.computeIfAbsent(groupName, k -> new LinkedHashSet<>()); } rLock.lock(); lockCount++; if(nettyClientSet.isEmpty()){ groupSet.add(groupName); } nettyClientSet.add(nc); }finally { if(lockCount > 0){ for (int i = 0; i < lockCount; i++) { rLock.unlock(); } } } return nc; } private NettyClient createClient(String serviceName, InetSocketAddress address){ NettyConf conf = new NettyConf(); conf.setAddress(address); conf.setCloseCallback((c)->{ try { rLock.lock(); String groupName = getGroupName(address); Set<NettyClient> nettyClients = groupPool.get(groupName); nettyClients.remove(c); if(nettyClients.isEmpty()){ groupPool.remove(groupName); Set<String> groupSet = servicePool.get(serviceName); groupSet.remove(groupName); if(groupSet.isEmpty()){ servicePool.remove(serviceName); } } }finally { rLock.unlock(); } }); ClientFactory factory = ClientFactory.getInstance(); return factory.create(conf); } private String getGroupName(InetSocketAddress address){ String hostName = address.getHostName(); int port = address.getPort(); return hostName+":"+port; } private <T> T linkedHashSetGetByIndex(LinkedHashSet<T> linkedHashSet, int index){ if(null == linkedHashSet){ return null; } T t = null; int chCurrIndex = 0; Iterator<T> chIterator = linkedHashSet.stream().iterator(); while (chIterator.hasNext() && chCurrIndex++ <= index){ t = chIterator.next(); } return t; } private static class LazyHolder { private static final ClientPool INSTANCE = new ClientPool(); } public static ClientPool getInstance() { return ClientPool.LazyHolder.INSTANCE; } private ClientPool(){} }
lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ClientPool.java
hiparker-lint-rpc-framework-e64aac0
[ { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/balance/LoadBalancePolicyFactory.java", "retrieved_chunk": " return null;\n }\n ClientPool pool = ClientPool.getInstance();\n // 选择客户端\n return pool.get(rpcClientAnnotation.name(), loadBalancePolicy);\n }\n private ILoadBalancePolicy getLoadBalancePolicy(\n Class<? extends ILoadBalancePolicy> loadBalancePolicyClazz){\n ILoadBalancePolicy loadBalancePolicy = loadBalancePolicyMap.get(loadBalancePolicyClazz);\n if(null != loadBalancePolicy){", "score": 0.8333234786987305 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/balance/LoadBalancePolicyFactory.java", "retrieved_chunk": " return loadBalancePolicy;\n }\n // DCL\n synchronized (lock){\n loadBalancePolicy = loadBalancePolicyMap.get(loadBalancePolicyClazz);\n if(null != loadBalancePolicy){\n return loadBalancePolicy;\n }\n try {\n loadBalancePolicy = loadBalancePolicyClazz.newInstance();", "score": 0.7943509817123413 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/proxy/RpcInvocationHandler.java", "retrieved_chunk": " requestContent.setRequestHeader(requestHeader);\n requestContent.setRequestBody(requestBody);\n LoadBalancePolicyFactory loadBalancePolicyFactory = LoadBalancePolicyFactory.getInstance();\n NettyClient nc = loadBalancePolicyFactory\n .getClient(interfaceInfo);\n Object responseMsg = null;\n try {\n boolean sendFlag = nc.sendMsg(requestContent);\n if(!sendFlag){\n // 无法建立连接", "score": 0.7911438345909119 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/CountDownLatchPool.java", "retrieved_chunk": " timeoutSeconds = 0;\n }\n CountDownLatch countDownLatch = new CountDownLatch(1);\n // 超时自动释放\n MSG_POOL_MAP.putIfAbsent(requestId, countDownLatch);\n countDownLatch.await(timeoutSeconds, TimeUnit.SECONDS);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }", "score": 0.7890352010726929 }, { "filename": "lint-rpc-demo/lint-rpc-demo-consumer/src/main/java/com/lint/rpc/demo/consumer/ConsumerApplication.java", "retrieved_chunk": " CountDownLatch c = new CountDownLatch(20);\n // 拟并发请求\n for (int i = 0; i < c.getCount(); i++) {\n new Thread(()->{\n // 调用链路1 生产者1 -> 生产者2 , 输出合并结果\n ProvideEatInterfaceSpi provide1 =\n ProxyPool.getProxyGet(ProvideEatInterfaceSpi.class);\n // 调用链路2 生产这2 ,输出一个List集合\n ProvideDrinkInterfaceSpi provide2 =\n ProxyPool.getProxyGet(ProvideDrinkInterfaceSpi.class);", "score": 0.7871930003166199 } ]
java
groupIndex = loadBalancePolicy.getClientIndex(groupNameSet.size());
package com.lint.rpc.common.exception; import com.lint.rpc.common.enums.BaseMsg; /** * 框架服务异常 * * @author Parker * @date 2020-09-13 19:41 */ public class RpcException extends RuntimeException{ private Integer code; private String errorMessage; public RpcException(Integer code, String errorMessage) { super(errorMessage); this.code = code; this.errorMessage = errorMessage; } public RpcException(Integer code, String errorMessage, Throwable e) { super(errorMessage, e); this.code = code; this.errorMessage = errorMessage; } public RpcException(BaseMsg msg) { super(
msg.getMessage());
this.code = msg.getCode(); this.errorMessage = msg.getMessage(); } public RpcException(BaseMsg msg, Throwable e) { super(msg.getMessage(), e); this.code = msg.getCode(); this.errorMessage = msg.getMessage(); } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } }
lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/exception/RpcException.java
hiparker-lint-rpc-framework-e64aac0
[ { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/enums/RpcMsg.java", "retrieved_chunk": " EXCEPTION_NOT_CONNECTION(501,\"Unable to establish connection\"),\n /** 请求错误 */\n EXCEPTION_ERROR(500,\"Request error\"),\n ;\n private final int code;\n private final String message;\n RpcMsg(int code, String message){\n this.code = code;\n this.message = message;\n }", "score": 0.8716278672218323 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/enums/RpcMsg.java", "retrieved_chunk": " * @date 2020-09-13 19:41\n */\npublic enum RpcMsg implements BaseMsg {\n /** 未设置配置 */\n EXCEPTION_NOT_SET_CONF(2,\"The producer spi type is not set in the configuration or is specified in the configuration\"),\n /** 服务未启动 */\n EXCEPTION_SERVICE_NOT_STARTED(2,\"Service not started\"),\n /** 请求超时 */\n EXCEPTION_TIMEOUT(408,\"Request timeout\"),\n /** 无法建立连接 */", "score": 0.8114482164382935 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/enums/RpcMsg.java", "retrieved_chunk": " @Override\n public Integer getCode() {\n return this.code;\n }\n @Override\n public String getMessage() {\n return this.message;\n }\n}", "score": 0.8095951080322266 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyServer.java", "retrieved_chunk": "package com.lint.rpc.common.transport;\nimport com.lint.rpc.common.enums.RpcMsg;\nimport com.lint.rpc.common.exception.RpcException;\nimport io.netty.bootstrap.ServerBootstrap;\nimport io.netty.channel.ChannelFuture;\nimport io.netty.channel.ChannelInitializer;\nimport io.netty.channel.ChannelPipeline;\nimport io.netty.channel.nio.NioEventLoopGroup;\nimport io.netty.channel.socket.nio.NioServerSocketChannel;\nimport io.netty.channel.socket.nio.NioSocketChannel;", "score": 0.7698779702186584 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/enums/BaseMsg.java", "retrieved_chunk": " * @author Parker\n * @date 2020-09-22 17:07\n */\npublic interface BaseMsg {\n /**\n * 获取消息的状态码\n */\n Integer getCode();\n /**\n * 获取消息提示信息", "score": 0.7665446400642395 } ]
java
msg.getMessage());
package com.lint.rpc.common.transport; import com.lint.rpc.common.protocol.RequestBody; import com.lint.rpc.common.protocol.RequestContent; import com.lint.rpc.common.protocol.RequestHeader; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.CombinedChannelDuplexHandler; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.codec.MessageToByteEncoder; import java.io.*; import java.util.List; /** * 内部服务器消息编解码器 * * @author 周鹏程 * @date 2023-05-26 19:34:07 */ public final class InternalServerMsgCodec extends CombinedChannelDuplexHandler<InternalServerMsgCodec.Decoder, InternalServerMsgCodec.Encoder> { /** * 类默认构造器 */ public InternalServerMsgCodec() { super.init(new Decoder(), new Encoder()); } /** * 消息解码器 */ static final class Decoder extends ByteToMessageDecoder { private static final int HEAD_LENGTH = 107; @Override protected void decode(ChannelHandlerContext ctx, ByteBuf buff, List<Object> out) { // 如果消息不满足上面这个两个条件 直接不处理 if(buff.readableBytes() < HEAD_LENGTH){ return; } // 标记读取位置 buff.markReaderIndex(); byte[] headByteArray = new byte[HEAD_LENGTH]; buff.readBytes(headByteArray); RequestHeader requestHeader = null; try(ByteArrayInputStream in = new ByteArrayInputStream(headByteArray); ObjectInputStream ois = new ObjectInputStream(in); ) { requestHeader = (RequestHeader) ois.readObject(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } // 如果消息体长度不够 直接退出 if(null == requestHeader || buff.readableBytes() <
requestHeader.getLength()){
// 回到标记读取位置 // 什么时候 消息读全了 什么时候再继续往后执行 buff.resetReaderIndex(); return; } byte[] bodyByteArray = new byte[requestHeader.getLength()]; buff.readBytes(bodyByteArray); RequestBody requestBody; try(ByteArrayInputStream in = new ByteArrayInputStream(bodyByteArray); ObjectInputStream ois = new ObjectInputStream(in); ) { requestBody = (RequestBody) ois.readObject(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); requestBody = new RequestBody(); } // System.out.println("收到消息 => " + // "requestId = "+requestHeader.getRequestId() + // ", flag = "+requestHeader.getFlag()+ // ", bodyName = "+requestBody.getName()+ // ", bodyMethodName = "+requestBody.getMethodName()); RequestContent requestContent = new RequestContent(); requestContent.setRequestHeader(requestHeader); requestContent.setRequestBody(requestBody); // 出发消息读取事件 ctx.fireChannelRead(requestContent); } } /** * 消息编码器 */ static final class Encoder extends MessageToByteEncoder<RequestContent> { @Override protected void encode(ChannelHandlerContext ctx, RequestContent innerMsg, ByteBuf byteBuf) { // 写出head byteBuf.writeBytes(innerMsg.getRequestHeader().toBytesArray()); // 写出body byteBuf.writeBytes(innerMsg.getRequestBody().toBytesArray()); // 释放内存 innerMsg.free(); } } }
lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/InternalServerMsgCodec.java
hiparker-lint-rpc-framework-e64aac0
[ { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/protocol/RequestHeader.java", "retrieved_chunk": "public class RequestHeader implements Serializable {\n /** 标识 */\n private int flag;\n /** 请求ID */\n private long requestId;\n /** 长度 */\n private int length;\n public RequestHeader(byte[] requestBodyBytes){\n requestId = Math.abs(UUID.randomUUID().getLeastSignificantBits());\n length = requestBodyBytes.length;", "score": 0.8542541265487671 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/ServerChannelHandler.java", "retrieved_chunk": " }catch (Exception e){\n e.printStackTrace();\n }\n requestHeader.setLength(requestBody.toBytesArray().length);\n ctx.channel().writeAndFlush(content);\n // 转多线程处理\n// ExecuteThread et = ExecuteThread.getInstance();\n// et.execute(()->{\n// ProvideServiceSpi spi = ProvideServiceSpi.getInstance();\n// LintService service = spi.getService(requestBody.getName(), requestHeader.getVersion());", "score": 0.8401970267295837 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/protocol/RequestBody.java", "retrieved_chunk": "package com.lint.rpc.common.protocol;\nimport com.lint.rpc.common.util.ByteUtil;\nimport java.io.Serializable;\n/**\n * 请求头\n *\n * @author 周鹏程\n * @date 2023-05-26 11:26 AM\n **/\npublic class RequestBody implements Serializable {", "score": 0.8286373019218445 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/proxy/RpcInvocationHandler.java", "retrieved_chunk": " requestHeader.getRequestId(), lintConf.getRequestWaitTimeBySeconds());\n // 消息池查询数据 如果查到则序列化返回 ,超时则返回超时 或者 调用兜底补偿\n responseMsg = MsgPool.getAndRemove(requestHeader.getRequestId());\n if(null == responseMsg){\n // 请求超时\n throw new RpcException(RpcMsg.EXCEPTION_TIMEOUT);\n }\n }catch (RpcException re){\n re.printStackTrace();\n }finally {", "score": 0.8279813528060913 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/protocol/RequestContent.java", "retrieved_chunk": "package com.lint.rpc.common.protocol;\nimport java.io.Serializable;\n/**\n * 综合体\n *\n * @author 周鹏程\n * @date 2023-05-26 11:26 AM\n **/\npublic class RequestContent implements Serializable {\n private RequestHeader requestHeader;", "score": 0.8266208171844482 } ]
java
requestHeader.getLength()){
package com.utils.InteractionApi; import com.utils.HypsApiPlugin.NPCs; import com.utils.Packets.MousePackets; import com.utils.Packets.NPCPackets; import net.runelite.api.NPC; import java.util.Optional; import java.util.function.Predicate; public class NPCInteraction { public static boolean interact(String name, String... actions) { return NPCs.search().withName(name).first().flatMap(npc -> { MousePackets.queueClickPacket(); NPCPackets.queueNPCAction(npc, actions); return Optional.of(true); }).orElse(false); } public static boolean interact(int id, String... actions) { return NPCs.search().withId(id).first().flatMap(npc -> { MousePackets.queueClickPacket(); NPCPackets.queueNPCAction(npc, actions); return Optional.of(true); }).orElse(false); } public static boolean interact(Predicate<? super NPC> predicate, String... actions) { return NPCs.search().filter(predicate).first().flatMap(npc -> { MousePackets.queueClickPacket(); NPCPackets.queueNPCAction(npc, actions); return Optional.of(true); }).orElse(false); } public static boolean interactIndex(int index, String... actions) { return
NPCs.search().indexIs(index).first().flatMap(npc -> {
MousePackets.queueClickPacket(); NPCPackets.queueNPCAction(npc, actions); return Optional.of(true); }).orElse(false); } public static boolean interact(NPC npc, String... actions) { if (npc == null) { return false; } MousePackets.queueClickPacket(); NPCPackets.queueNPCAction(npc, actions); return true; } }
src/main/java/com/utils/InteractionApi/NPCInteraction.java
Hypsster-hUtils-d265b4f
[ { "filename": "src/main/java/com/utils/InteractionApi/InventoryInteraction.java", "retrieved_chunk": "\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItemIndex(int index, String... actions)\n\t{\n\t\treturn Inventory.search().indexIs(index).first().flatMap(item ->\n\t\t{", "score": 0.9208106994628906 }, { "filename": "src/main/java/com/utils/InteractionApi/BankInventoryInteraction.java", "retrieved_chunk": "\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItemIndex(int index, String... actions)\n\t{\n\t\treturn BankInventory.search().indexIs(index).first().flatMap(item ->\n\t\t{", "score": 0.9185535907745361 }, { "filename": "src/main/java/com/utils/InteractionApi/BankInteraction.java", "retrieved_chunk": "\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItemIndex(int index, String... actions)\n\t{\n\t\treturn Bank.search().indexIs(index).first().flatMap(item ->\n\t\t{", "score": 0.9159495234489441 }, { "filename": "src/main/java/com/utils/InteractionApi/PlayerInteractionHelper.java", "retrieved_chunk": "\t{\n\t\tif (player == null)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\tMousePackets.queueClickPacket();\n\t\tPlayerPackets.queuePlayerAction(player, actions);\n\t\treturn true;\n\t}\n\tpublic static boolean interact(String name, String... actions)", "score": 0.8900351524353027 }, { "filename": "src/main/java/com/utils/InteractionApi/PlayerInteractionHelper.java", "retrieved_chunk": "\t{\n\t\treturn Players.search().withName(name).first().flatMap(Player ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tPlayerPackets.queuePlayerAction(Player, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean interact(Predicate<? super Player> predicate, String... actions)\n\t{", "score": 0.8891170024871826 } ]
java
NPCs.search().indexIs(index).first().flatMap(npc -> {
package com.utils.InteractionApi; import com.utils.HypsApiPlugin.Bank; import com.utils.Packets.MousePackets; import com.utils.Packets.WidgetPackets; import net.runelite.api.widgets.Widget; import java.util.Optional; import java.util.function.Predicate; public class BankInteraction { public static boolean useItem(String name, String... actions) { return Bank.search().withName(name).first().flatMap(item -> { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(item, actions); return Optional.of(true); }).orElse(false); } public static boolean useItem(int id, String... actions) { return Bank.search().withId(id).first().flatMap(item -> { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(item, actions); return Optional.of(true); }).orElse(false); } public static boolean useItem(Predicate<? super Widget> predicate, String... actions) { return Bank.search().filter(predicate).first().flatMap(item -> { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(item, actions); return Optional.of(true); }).orElse(false); } public static boolean useItemIndex(int index, String... actions) {
return Bank.search().indexIs(index).first().flatMap(item -> {
MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(item, actions); return Optional.of(true); }).orElse(false); } public static boolean useItem(Widget item, String... actions) { if (item == null) { return false; } MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(item, actions); return true; } }
src/main/java/com/utils/InteractionApi/BankInteraction.java
Hypsster-hUtils-d265b4f
[ { "filename": "src/main/java/com/utils/InteractionApi/BankInventoryInteraction.java", "retrieved_chunk": "\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItemIndex(int index, String... actions)\n\t{\n\t\treturn BankInventory.search().indexIs(index).first().flatMap(item ->\n\t\t{", "score": 0.9897884726524353 }, { "filename": "src/main/java/com/utils/InteractionApi/InventoryInteraction.java", "retrieved_chunk": "\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItemIndex(int index, String... actions)\n\t{\n\t\treturn Inventory.search().indexIs(index).first().flatMap(item ->\n\t\t{", "score": 0.9753477573394775 }, { "filename": "src/main/java/com/utils/InteractionApi/BankInventoryInteraction.java", "retrieved_chunk": "\t{\n\t\treturn BankInventory.search().withName(name).first().flatMap(item ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItem(int id, String... actions)\n\t{", "score": 0.9299691915512085 }, { "filename": "src/main/java/com/utils/InteractionApi/BankInventoryInteraction.java", "retrieved_chunk": "\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItem(Widget item, String... actions)\n\t{\n\t\tif (item == null)\n\t\t{\n\t\t\treturn false;", "score": 0.924775242805481 }, { "filename": "src/main/java/com/utils/InteractionApi/InventoryInteraction.java", "retrieved_chunk": "\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItem(Widget item, String... actions)\n\t{\n\t\tif (item == null)\n\t\t{\n\t\t\treturn false;", "score": 0.924751877784729 } ]
java
return Bank.search().indexIs(index).first().flatMap(item -> {
package com.ialdrich23xx.libasynwebhook.api.discord; import com.ialdrich23xx.libasynwebhook.api.Loader; import com.ialdrich23xx.libasynwebhook.api.discord.body.Base; import com.ialdrich23xx.libasynwebhook.api.discord.body.embed.base.BodyException; import javax.net.ssl.HttpsURLConnection; import java.io.OutputStream; import java.net.URL; import java.util.concurrent.CompletableFuture; public class WebHook { private final String url; private Base body; public WebHook(String url, Base body) { this.url = url; this.body = body; } public static WebHook make(String url, Base body) { return new WebHook(url, body); } public String getUrl() { return this.url; } public Base getBody() { return this.body; } public WebHook setBody(Base body) { this.body = body; return this; } public void send() { if (this.getBody() == null) throw new BodyException("Body of webhook is null"); if (Loader.getInstance().isValidUrl(this.getUrl
()) && this.getBody().build()) {
CompletableFuture.runAsync(() -> { try { URL url = new URL(this.url); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.addRequestProperty("Content-Type", "application/json"); connection.addRequestProperty("User-Agent", "CloverCube"); connection.setDoOutput(true); connection.setRequestMethod("POST"); OutputStream stream = connection.getOutputStream(); stream.write(this.getBody().toJson().getBytes()); stream.flush(); stream.close(); connection.getInputStream().close(); //I'm not sure why, but it doesn't work without getting the InputStream connection.disconnect(); } catch (Exception e) { System.out.println(e.getMessage()); } }); } else throw new BodyException("Url not valid: " + this.getUrl()); } }
libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/WebHook.java
iAldrich23xX-libasynWebhook-52a1773
[ { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/base/Structure.java", "retrieved_chunk": " }\n public String getUrl() {\n if (!(this instanceof URL)) throw new BodyException(\"Error this class not implements URL\");\n return this.url;\n }\n public Boolean urlBuild() {\n if (this.getUrl().isEmpty()) return false;\n return Loader.getInstance().isValidUrl(this.getUrl());\n }\n public Map<String, Object> urlToArray() {", "score": 0.8454317450523376 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/base/Structure.java", "retrieved_chunk": " if (!(this instanceof Name)) throw new BodyException(\"Error this class not implements name\");\n return \"name=\" + this.getName();\n }\n public Structure setUrl(String newUrl) {\n if (!(this instanceof URL)) {\n throw new BodyException(\"Error this class not implements URL\");\n } else {\n this.url = newUrl;\n }\n return this;", "score": 0.827442467212677 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/base/Structure.java", "retrieved_chunk": " if (!(this instanceof IconURL)) {\n throw new BodyException(\"Error this class not implements IconURL\");\n } else {\n this.icon = newIcon;\n }\n return this;\n }\n public Boolean iconBuild() {\n if (this.getIcon().isEmpty()) return false;\n return Loader.getInstance().isValidUrl(this.getIcon());", "score": 0.8151081204414368 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/base/Structure.java", "retrieved_chunk": " if (!(this instanceof URL)) throw new BodyException(\"Error this class not implements URL\");\n Map<String, Object> result = new HashMap<>();\n result.put(\"url\", this.getUrl());\n return result;\n }\n public String urlToString() {\n if (!(this instanceof URL)) throw new BodyException(\"Error this class not implements URL\");\n return \"url=\" + this.getUrl();\n }\n public Structure setIcon(String newIcon) {", "score": 0.811061441898346 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/base/URL.java", "retrieved_chunk": "package com.ialdrich23xx.libasynwebhook.api.discord.body.embed.base;\nimport java.util.Map;\npublic interface URL {\n Structure setUrl(String url);\n String getUrl();\n Boolean urlBuild();\n Map<String, Object> urlToArray();\n String urlToString();\n}", "score": 0.8041753172874451 } ]
java
()) && this.getBody().build()) {
package com.ialdrich23xx.libasynwebhook.api.discord; import com.ialdrich23xx.libasynwebhook.api.Loader; import com.ialdrich23xx.libasynwebhook.api.discord.body.Base; import com.ialdrich23xx.libasynwebhook.api.discord.body.embed.base.BodyException; import javax.net.ssl.HttpsURLConnection; import java.io.OutputStream; import java.net.URL; import java.util.concurrent.CompletableFuture; public class WebHook { private final String url; private Base body; public WebHook(String url, Base body) { this.url = url; this.body = body; } public static WebHook make(String url, Base body) { return new WebHook(url, body); } public String getUrl() { return this.url; } public Base getBody() { return this.body; } public WebHook setBody(Base body) { this.body = body; return this; } public void send() { if (this.getBody() == null) throw new BodyException("Body of webhook is null"); if (Loader.getInstance().isValidUrl(this.getUrl()) && this.getBody().build()) { CompletableFuture.runAsync(() -> { try { URL url = new URL(this.url); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.addRequestProperty("Content-Type", "application/json"); connection.addRequestProperty("User-Agent", "CloverCube"); connection.setDoOutput(true); connection.setRequestMethod("POST"); OutputStream stream = connection.getOutputStream(); stream.write(this
.getBody().toJson().getBytes());
stream.flush(); stream.close(); connection.getInputStream().close(); //I'm not sure why, but it doesn't work without getting the InputStream connection.disconnect(); } catch (Exception e) { System.out.println(e.getMessage()); } }); } else throw new BodyException("Url not valid: " + this.getUrl()); } }
libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/WebHook.java
iAldrich23xX-libasynWebhook-52a1773
[ { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/base/Structure.java", "retrieved_chunk": " }\n public String getUrl() {\n if (!(this instanceof URL)) throw new BodyException(\"Error this class not implements URL\");\n return this.url;\n }\n public Boolean urlBuild() {\n if (this.getUrl().isEmpty()) return false;\n return Loader.getInstance().isValidUrl(this.getUrl());\n }\n public Map<String, Object> urlToArray() {", "score": 0.7933317422866821 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/base/Structure.java", "retrieved_chunk": " if (!(this instanceof URL)) throw new BodyException(\"Error this class not implements URL\");\n Map<String, Object> result = new HashMap<>();\n result.put(\"url\", this.getUrl());\n return result;\n }\n public String urlToString() {\n if (!(this instanceof URL)) throw new BodyException(\"Error this class not implements URL\");\n return \"url=\" + this.getUrl();\n }\n public Structure setIcon(String newIcon) {", "score": 0.7896494269371033 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/base/Structure.java", "retrieved_chunk": " }\n public String iconToString() {\n if (!(this instanceof IconURL)) throw new BodyException(\"Error this class not implements IconURL\");\n return \"icon=\" + this.getIcon();\n }\n}", "score": 0.7815278768539429 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/base/URL.java", "retrieved_chunk": "package com.ialdrich23xx.libasynwebhook.api.discord.body.embed.base;\nimport java.util.Map;\npublic interface URL {\n Structure setUrl(String url);\n String getUrl();\n Boolean urlBuild();\n Map<String, Object> urlToArray();\n String urlToString();\n}", "score": 0.7750630974769592 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/base/Structure.java", "retrieved_chunk": " if (!(this instanceof Name)) throw new BodyException(\"Error this class not implements name\");\n return \"name=\" + this.getName();\n }\n public Structure setUrl(String newUrl) {\n if (!(this instanceof URL)) {\n throw new BodyException(\"Error this class not implements URL\");\n } else {\n this.url = newUrl;\n }\n return this;", "score": 0.7743480205535889 } ]
java
.getBody().toJson().getBytes());
package com.lint.rpc.common.proxy; import com.lint.rpc.common.LintConf; import com.lint.rpc.common.annotation.RpcClient; import com.lint.rpc.common.pool.ConfPool; import com.lint.rpc.common.pool.CountDownLatchPool; import com.lint.rpc.common.pool.MsgPool; import com.lint.rpc.common.enums.RpcMsg; import com.lint.rpc.common.exception.RpcException; import com.lint.rpc.common.balance.LoadBalancePolicyFactory; import com.lint.rpc.common.protocol.RequestBody; import com.lint.rpc.common.protocol.RequestContent; import com.lint.rpc.common.protocol.RequestHeader; import com.lint.rpc.common.transport.NettyClient; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; /** * Rpc 代理执行类 * * @author 周鹏程 * @date 2023-05-26 11:53 AM **/ public class RpcInvocationHandler implements InvocationHandler { private final Class<?> interfaceInfo; public RpcInvocationHandler(Class<?> interfaceInfo){ this.interfaceInfo = interfaceInfo; } @Override public Object invoke(Object proxy, Method method, Object[] args) { long startTime = System.currentTimeMillis(); RpcClient annotation = interfaceInfo.getAnnotation(RpcClient.class); String methodName = method.getName(); Class<?>[] parameterTypes = method.getParameterTypes(); RequestBody requestBody = new RequestBody(); requestBody.setName(annotation.name()); requestBody.setMethodName(methodName); requestBody.setParameterTypes(parameterTypes); requestBody.setArgs(args); RequestHeader requestHeader = new RequestHeader(requestBody.toBytesArray()); requestHeader.setVersion(annotation.version()); RequestContent requestContent = new RequestContent(); requestContent.setRequestHeader(requestHeader); requestContent.setRequestBody(requestBody); LoadBalancePolicyFactory loadBalancePolicyFactory = LoadBalancePolicyFactory.getInstance(); NettyClient nc = loadBalancePolicyFactory .getClient(interfaceInfo); Object responseMsg = null; try { boolean sendFlag = nc.sendMsg(requestContent); if(!sendFlag){ // 无法建立连接 throw new RpcException(RpcMsg.EXCEPTION_NOT_CONNECTION); } // 如果无返回值 则直接退出 if(method.getReturnType().equals(Void.TYPE)){ return responseMsg; } ConfPool confPool = ConfPool.getInstance(); LintConf lintConf = confPool.get(); // 锁定线程 并等待 60秒,如果有结果会直接返回 CountDownLatchPool.await( requestHeader
.getRequestId(), lintConf.getRequestWaitTimeBySeconds());
// 消息池查询数据 如果查到则序列化返回 ,超时则返回超时 或者 调用兜底补偿 responseMsg = MsgPool.getAndRemove(requestHeader.getRequestId()); if(null == responseMsg){ // 请求超时 throw new RpcException(RpcMsg.EXCEPTION_TIMEOUT); } }catch (RpcException re){ re.printStackTrace(); }finally { CountDownLatchPool.free(requestHeader.getRequestId()); } long endTime = System.currentTimeMillis(); System.out.println("Invoke "+interfaceInfo.getName()+ "("+annotation.name()+":"+annotation.version()+ ") used >>> " + (endTime - startTime) + " ms!"); // 序列化处理 return responseMsg; } }
lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/proxy/RpcInvocationHandler.java
hiparker-lint-rpc-framework-e64aac0
[ { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/CountDownLatchPool.java", "retrieved_chunk": " timeoutSeconds = 0;\n }\n CountDownLatch countDownLatch = new CountDownLatch(1);\n // 超时自动释放\n MSG_POOL_MAP.putIfAbsent(requestId, countDownLatch);\n countDownLatch.await(timeoutSeconds, TimeUnit.SECONDS);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }", "score": 0.8724529147148132 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/CountDownLatchPool.java", "retrieved_chunk": " **/\npublic final class CountDownLatchPool {\n private static final int TIME_OUT = 60;\n private static final Map<Long, CountDownLatch> MSG_POOL_MAP = new ConcurrentHashMap<>();\n public static void put(long requestId, CountDownLatch countDownLatch){\n MSG_POOL_MAP.putIfAbsent(requestId, countDownLatch);\n }\n public static void await(long requestId){\n try {\n CountDownLatch countDownLatch = new CountDownLatch(1);", "score": 0.845543622970581 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/CountDownLatchPool.java", "retrieved_chunk": " // 超时自动释放\n MSG_POOL_MAP.putIfAbsent(requestId, countDownLatch);\n countDownLatch.await(TIME_OUT, TimeUnit.SECONDS);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n public static void await(long requestId, int timeoutSeconds){\n try {\n if(timeoutSeconds < 0){", "score": 0.8409338593482971 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/ServerChannelHandler.java", "retrieved_chunk": " }catch (Exception e){\n e.printStackTrace();\n }\n requestHeader.setLength(requestBody.toBytesArray().length);\n ctx.channel().writeAndFlush(content);\n // 转多线程处理\n// ExecuteThread et = ExecuteThread.getInstance();\n// et.execute(()->{\n// ProvideServiceSpi spi = ProvideServiceSpi.getInstance();\n// LintService service = spi.getService(requestBody.getName(), requestHeader.getVersion());", "score": 0.8315412998199463 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/ServerChannelHandler.java", "retrieved_chunk": " // 本身可以受到 NettyEventLoop线程 进行多线程执行\n ProvideServiceSpi spi = ProvideServiceSpi.getInstance();\n LintService service = spi.getService(requestBody.getName(), requestHeader.getVersion());\n if(null == service){\n return;\n }\n try {\n Method method = service.getClass().getMethod(requestBody.getMethodName());\n Object res = method.invoke(service, requestBody.getArgs());\n requestBody.setRes(res);", "score": 0.831535816192627 } ]
java
.getRequestId(), lintConf.getRequestWaitTimeBySeconds());
package com.utils.InteractionApi; import com.utils.HypsApiPlugin.Players; import com.utils.Packets.MousePackets; import com.utils.Packets.PlayerPackets; import net.runelite.api.Player; import java.util.Optional; import java.util.function.Predicate; public class PlayerInteractionHelper { public static boolean interact(Player player, String... actions) { if (player == null) { return false; } MousePackets.queueClickPacket(); PlayerPackets.queuePlayerAction(player, actions); return true; } public static boolean interact(String name, String... actions) { return Players.search().withName(name).first().flatMap(Player -> { MousePackets.queueClickPacket(); PlayerPackets.queuePlayerAction(Player, actions); return Optional.of(true); }).orElse(false); } public static boolean interact(Predicate<? super Player> predicate, String... actions) { return
Players.search().filter(predicate).first().flatMap(Player -> {
MousePackets.queueClickPacket(); PlayerPackets.queuePlayerAction(Player, actions); return Optional.of(true); }).orElse(false); } }
src/main/java/com/utils/InteractionApi/PlayerInteractionHelper.java
Hypsster-hUtils-d265b4f
[ { "filename": "src/main/java/com/utils/InteractionApi/NPCInteraction.java", "retrieved_chunk": "\t\treturn NPCs.search().withId(id).first().flatMap(npc ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tNPCPackets.queueNPCAction(npc, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean interact(Predicate<? super NPC> predicate, String... actions)\n\t{\n\t\treturn NPCs.search().filter(predicate).first().flatMap(npc ->", "score": 0.9322417974472046 }, { "filename": "src/main/java/com/utils/InteractionApi/NPCInteraction.java", "retrieved_chunk": "\t\t\tMousePackets.queueClickPacket();\n\t\t\tNPCPackets.queueNPCAction(npc, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean interact(NPC npc, String... actions)\n\t{\n\t\tif (npc == null)\n\t\t{\n\t\t\treturn false;", "score": 0.9067015647888184 }, { "filename": "src/main/java/com/utils/InteractionApi/NPCInteraction.java", "retrieved_chunk": "\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tNPCPackets.queueNPCAction(npc, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean interactIndex(int index, String... actions)\n\t{\n\t\treturn NPCs.search().indexIs(index).first().flatMap(npc ->\n\t\t{", "score": 0.9066242575645447 }, { "filename": "src/main/java/com/utils/InteractionApi/NPCInteraction.java", "retrieved_chunk": "\t{\n\t\treturn NPCs.search().withName(name).first().flatMap(npc ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tNPCPackets.queueNPCAction(npc, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean interact(int id, String... actions)\n\t{", "score": 0.9004521369934082 }, { "filename": "src/main/java/com/utils/InteractionApi/InventoryInteraction.java", "retrieved_chunk": "\t\treturn Inventory.search().withId(id).first().flatMap(item ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItem(Predicate<? super Widget> predicate, String... actions)\n\t{\n\t\treturn Inventory.search().filter(predicate).first().flatMap(item ->", "score": 0.9001666307449341 } ]
java
Players.search().filter(predicate).first().flatMap(Player -> {
package com.utils.InteractionApi; import com.utils.HypsApiPlugin.BankInventory; import com.utils.Packets.MousePackets; import com.utils.Packets.WidgetPackets; import net.runelite.api.widgets.Widget; import java.util.Optional; import java.util.function.Predicate; public class BankInventoryInteraction { public static boolean useItem(String name, String... actions) { return BankInventory.search().withName(name).first().flatMap(item -> { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(item, actions); return Optional.of(true); }).orElse(false); } public static boolean useItem(int id, String... actions) { return BankInventory.search().withId(id).first().flatMap(item -> { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(item, actions); return Optional.of(true); }).orElse(false); } public static boolean useItem(Predicate<? super Widget> predicate, String... actions) { return BankInventory.search().filter(predicate).first().flatMap(item -> { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(item, actions); return Optional.of(true); }).orElse(false); } public static boolean useItemIndex(int index, String... actions) { return
BankInventory.search().indexIs(index).first().flatMap(item -> {
MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(item, actions); return Optional.of(true); }).orElse(false); } public static boolean useItem(Widget item, String... actions) { if (item == null) { return false; } MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(item, actions); return true; } }
src/main/java/com/utils/InteractionApi/BankInventoryInteraction.java
Hypsster-hUtils-d265b4f
[ { "filename": "src/main/java/com/utils/InteractionApi/BankInteraction.java", "retrieved_chunk": "\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItemIndex(int index, String... actions)\n\t{\n\t\treturn Bank.search().indexIs(index).first().flatMap(item ->\n\t\t{", "score": 0.9862481951713562 }, { "filename": "src/main/java/com/utils/InteractionApi/InventoryInteraction.java", "retrieved_chunk": "\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItemIndex(int index, String... actions)\n\t{\n\t\treturn Inventory.search().indexIs(index).first().flatMap(item ->\n\t\t{", "score": 0.9787564873695374 }, { "filename": "src/main/java/com/utils/InteractionApi/BankInteraction.java", "retrieved_chunk": "\t{\n\t\treturn Bank.search().withName(name).first().flatMap(item ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItem(int id, String... actions)\n\t{", "score": 0.9334943294525146 }, { "filename": "src/main/java/com/utils/InteractionApi/BankInteraction.java", "retrieved_chunk": "\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItem(Widget item, String... actions)\n\t{\n\t\tif (item == null)\n\t\t{\n\t\t\treturn false;", "score": 0.9332020282745361 }, { "filename": "src/main/java/com/utils/InteractionApi/InventoryInteraction.java", "retrieved_chunk": "\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItem(Widget item, String... actions)\n\t{\n\t\tif (item == null)\n\t\t{\n\t\t\treturn false;", "score": 0.9331822395324707 } ]
java
BankInventory.search().indexIs(index).first().flatMap(item -> {
package com.utils.InteractionApi; import com.utils.HypsApiPlugin.NPCs; import com.utils.Packets.MousePackets; import com.utils.Packets.NPCPackets; import net.runelite.api.NPC; import java.util.Optional; import java.util.function.Predicate; public class NPCInteraction { public static boolean interact(String name, String... actions) { return NPCs.search().withName(name).first().flatMap(npc -> { MousePackets.queueClickPacket(); NPCPackets.queueNPCAction(npc, actions); return Optional.of(true); }).orElse(false); } public static boolean interact(int id, String... actions) { return NPCs.search().withId(id).first().flatMap(npc -> { MousePackets.queueClickPacket(); NPCPackets.queueNPCAction(npc, actions); return Optional.of(true); }).orElse(false); } public static boolean interact(Predicate<? super NPC> predicate, String... actions) { return
NPCs.search().filter(predicate).first().flatMap(npc -> {
MousePackets.queueClickPacket(); NPCPackets.queueNPCAction(npc, actions); return Optional.of(true); }).orElse(false); } public static boolean interactIndex(int index, String... actions) { return NPCs.search().indexIs(index).first().flatMap(npc -> { MousePackets.queueClickPacket(); NPCPackets.queueNPCAction(npc, actions); return Optional.of(true); }).orElse(false); } public static boolean interact(NPC npc, String... actions) { if (npc == null) { return false; } MousePackets.queueClickPacket(); NPCPackets.queueNPCAction(npc, actions); return true; } }
src/main/java/com/utils/InteractionApi/NPCInteraction.java
Hypsster-hUtils-d265b4f
[ { "filename": "src/main/java/com/utils/InteractionApi/PlayerInteractionHelper.java", "retrieved_chunk": "\t{\n\t\treturn Players.search().withName(name).first().flatMap(Player ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tPlayerPackets.queuePlayerAction(Player, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean interact(Predicate<? super Player> predicate, String... actions)\n\t{", "score": 0.9365013837814331 }, { "filename": "src/main/java/com/utils/InteractionApi/InventoryInteraction.java", "retrieved_chunk": "\t\treturn Inventory.search().withId(id).first().flatMap(item ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItem(Predicate<? super Widget> predicate, String... actions)\n\t{\n\t\treturn Inventory.search().filter(predicate).first().flatMap(item ->", "score": 0.8926843404769897 }, { "filename": "src/main/java/com/utils/InteractionApi/PlayerInteractionHelper.java", "retrieved_chunk": "\t\treturn Players.search().filter(predicate).first().flatMap(Player ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tPlayerPackets.queuePlayerAction(Player, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n}", "score": 0.8857105374336243 }, { "filename": "src/main/java/com/utils/InteractionApi/PlayerInteractionHelper.java", "retrieved_chunk": "\t{\n\t\tif (player == null)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\tMousePackets.queueClickPacket();\n\t\tPlayerPackets.queuePlayerAction(player, actions);\n\t\treturn true;\n\t}\n\tpublic static boolean interact(String name, String... actions)", "score": 0.8843034505844116 }, { "filename": "src/main/java/com/utils/InteractionApi/BankInventoryInteraction.java", "retrieved_chunk": "\t\treturn BankInventory.search().withId(id).first().flatMap(item ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItem(Predicate<? super Widget> predicate, String... actions)\n\t{\n\t\treturn BankInventory.search().filter(predicate).first().flatMap(item ->", "score": 0.8806028962135315 } ]
java
NPCs.search().filter(predicate).first().flatMap(npc -> {
package com.utils; import com.utils.PacketType; import com.utils.Packets.BufferMethods; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import net.runelite.api.Client; import javax.inject.Inject; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @Slf4j public class PacketReflection { public static Class classWithgetPacketBufferNode = null; public static Method getPacketBufferNode = null; public static Class ClientPacket = null; public static Class isaacClass = null; public static Class PacketBufferNode = null; public static Field PACKETWRITER = null; public static Object isaac = null; public static Field mouseHandlerLastPressedTime = null; public static Field clientMouseLastLastPressedTimeMillis = null; @Inject Client clientInstance; public static Client client = null; @SneakyThrows public boolean LoadPackets() { try { client = clientInstance; classWithgetPacketBufferNode = clientInstance.getClass().getClassLoader().loadClass(ObfuscatedNames.classContainingGetPacketBufferNodeName); ClientPacket = clientInstance.getClass().getClassLoader().loadClass(ObfuscatedNames.clientPacketClassName); PACKETWRITER = clientInstance.getClass().getDeclaredField(ObfuscatedNames.packetWriterFieldName); PacketBufferNode = clientInstance.getClass().getClassLoader().loadClass(ObfuscatedNames.packetBufferNodeClassName); PACKETWRITER.setAccessible(true); Field isaac2 = PACKETWRITER.get(null).getClass().getDeclaredField(ObfuscatedNames.isaacCipherFieldName); isaac2.setAccessible(true); isaac = isaac2.get(PACKETWRITER.get(null)); isaac2.setAccessible(false); PACKETWRITER.setAccessible(false); isaacClass = isaac.getClass(); getPacketBufferNode = Arrays.stream(classWithgetPacketBufferNode.getDeclaredMethods()).filter(m -> m.getReturnType().equals(PacketBufferNode)).collect(Collectors.toList()).get(0); mouseHandlerLastPressedTime = clientInstance.getClass().getClassLoader().loadClass(ObfuscatedNames.MouseHandler_lastPressedTimeMillisClass).getDeclaredField(ObfuscatedNames.MouseHandler_lastPressedTimeMillisField); clientMouseLastLastPressedTimeMillis = clientInstance.getClass().getDeclaredField(ObfuscatedNames.clientMouseLastLastPressedTimeMillis); } catch (Exception e) { e.printStackTrace(); log.warn("Failed to load Packets Into Client"); return false; } return true; } @SneakyThrows public static void writeObject(String obfname, Object buffer, Object input) { switch (obfname) { case "du":
BufferMethods.du(buffer, (Integer) input);
break; case "bu": BufferMethods.bu(buffer, (Integer) input); break; case "dh": BufferMethods.dh(buffer, (Integer) input); break; case "bf": BufferMethods.bf(buffer, (Integer) input); break; case "dy": BufferMethods.dy(buffer, (Integer) input); break; case "el": BufferMethods.el(buffer, (Integer) input); break; case "dn": BufferMethods.dn(buffer, (Integer) input); break; case "dp": BufferMethods.dp(buffer, (Integer) input); break; case "eb": BufferMethods.eb(buffer, (Integer) input); break; case "ds": BufferMethods.ds(buffer, (Integer) input); break; case "ba": BufferMethods.ba(buffer, (Integer) input); break; } } @SneakyThrows public static void sendPacket(PacketDef def, Object... objects) { Object packetBufferNode = null; getPacketBufferNode.setAccessible(true); long garbageValue = Math.abs(Long.parseLong(ObfuscatedNames.getPacketBufferNodeGarbageValue)); if (garbageValue < 256) { packetBufferNode = getPacketBufferNode.invoke(null, fetchPacketField(def.name).get(ClientPacket), isaac, Byte.parseByte(ObfuscatedNames.getPacketBufferNodeGarbageValue)); } else if (garbageValue < 32768) { packetBufferNode = getPacketBufferNode.invoke(null, fetchPacketField(def.name).get(ClientPacket), isaac, Short.parseShort(ObfuscatedNames.getPacketBufferNodeGarbageValue)); } else if (garbageValue < Integer.MAX_VALUE) { packetBufferNode = getPacketBufferNode.invoke(null, fetchPacketField(def.name).get(ClientPacket), isaac, Integer.parseInt(ObfuscatedNames.getPacketBufferNodeGarbageValue)); } Object buffer = packetBufferNode.getClass().getDeclaredField(ObfuscatedNames.packetBufferFieldName).get(packetBufferNode); getPacketBufferNode.setAccessible(false); List<String> params = null; if (def.type == PacketType.RESUME_PAUSEBUTTON) { params = List.of("var0", "var1"); } if (def.type == PacketType.IF_BUTTON) { params = List.of("widgetId", "slot", "itemId"); } if (def.type == PacketType.OPLOC) { params = List.of("objectId", "worldPointX", "worldPointY", "ctrlDown"); } if (def.type == PacketType.OPNPC) { params = List.of("npcIndex", "ctrlDown"); } if (def.type == PacketType.OPPLAYER) { params = List.of("playerIndex", "ctrlDown"); } if (def.type == PacketType.OPOBJ) { params = List.of("objectId", "worldPointX", "worldPointY", "ctrlDown"); } if (def.type == PacketType.OPOBJT) { params = List.of("objectId", "worldPointX", "worldPointY", "slot", "itemId", "widgetId", "ctrlDown"); } if (def.type == PacketType.EVENT_MOUSE_CLICK) { params = List.of("mouseInfo", "mouseX", "mouseY"); } if (def.type == PacketType.MOVE_GAMECLICK) { params = List.of("worldPointX", "worldPointY", "ctrlDown", "5"); } if (def.type == PacketType.IF_BUTTONT) { params = List.of("sourceWidgetId", "sourceSlot", "sourceItemId", "destinationWidgetId", "destinationSlot", "destinationItemId"); } if (def.type == PacketType.OPLOCT) { params = List.of("objectId", "worldPointX", "worldPointY", "slot", "itemId", "widgetId", "ctrlDown"); } if (def.type == PacketType.OPPLAYERT) { params = List.of("playerIndex", "itemId", "slot", "widgetId", "ctrlDown"); } if (def.type == PacketType.OPNPCT) { params = List.of("npcIndex", "itemId", "slot", "widgetId", "ctrlDown"); } if (params != null) { for (Map.Entry<String, String> stringEntry : def.fields.entrySet()) { if (params.contains(stringEntry.getKey())) { writeObject(stringEntry.getValue(), buffer, objects[params.indexOf(stringEntry.getKey())]); } } PACKETWRITER.setAccessible(true); Method addNode = PACKETWRITER.get(null).getClass().getDeclaredMethod(ObfuscatedNames.addNodeMethodName,PACKETWRITER.get(null).getClass(),packetBufferNode.getClass(), int.class); addNode.setAccessible(true); addNode.invoke(null,PACKETWRITER.get(null),packetBufferNode, Integer.parseInt(ObfuscatedNames.addNodeGarbageValue)); addNode.setAccessible(false); PACKETWRITER.setAccessible(false); } } @SneakyThrows static Field fetchPacketField(String name) { return ClientPacket.getDeclaredField(name); } }
src/main/java/com/utils/PacketReflection.java
Hypsster-hUtils-d265b4f
[ { "filename": "src/main/java/com/utils/Packets/BufferMethods.java", "retrieved_chunk": "\t@SneakyThrows\n\tpublic static void bf(Object bufferInstance, int writtenValue){\n\t\tField arrayField = bufferInstance.getClass().getField(ObfuscatedNames.bufferArrayField);\n\t\tField offsetField = bufferInstance.getClass().getField(ObfuscatedNames.bufferOffsetField);\n\t\tarrayField.setAccessible(true);\n\t\toffsetField.setAccessible(true);\n\t\tbyte array[] = (byte[]) arrayField.get(bufferInstance);\n\t\tint offset = offsetField.getInt(bufferInstance);\n\t\tarray[(offset += -1516355947) * -1633313603 - 1] = (byte)(writtenValue >> 8);\n\t\tarray[(offset += -1516355947) * -1633313603 - 1] = (byte)writtenValue;", "score": 0.834474503993988 }, { "filename": "src/main/java/com/utils/Packets/BufferMethods.java", "retrieved_chunk": "package com.utils.Packets;\nimport com.utils.ObfuscatedNames;\nimport lombok.SneakyThrows;\nimport java.lang.reflect.Field;\npublic class BufferMethods\n{\n\t//al = array\n\t//at = offset\n\t@SneakyThrows\n\tpublic static void du(Object bufferInstance, int writtenValue){", "score": 0.8328696489334106 }, { "filename": "src/main/java/com/utils/Packets/BufferMethods.java", "retrieved_chunk": "\t\toffsetField.setAccessible(false);\n\t}\n\t@SneakyThrows\n\tpublic static void dp(Object bufferInstance, int writtenValue){\n\t\tField arrayField = bufferInstance.getClass().getField(ObfuscatedNames.bufferArrayField);\n\t\tField offsetField = bufferInstance.getClass().getField(ObfuscatedNames.bufferOffsetField);\n\t\tarrayField.setAccessible(true);\n\t\toffsetField.setAccessible(true);\n\t\tbyte array[] = (byte[]) arrayField.get(bufferInstance);\n\t\tint offset = offsetField.getInt(bufferInstance);", "score": 0.825553297996521 }, { "filename": "src/main/java/com/utils/Packets/BufferMethods.java", "retrieved_chunk": "\t\tarrayField.setAccessible(false);\n\t\toffsetField.setAccessible(false);\n\t}\n\t@SneakyThrows\n\tpublic static void ds(Object bufferInstance, int writtenValue){\n\t\tField arrayField = bufferInstance.getClass().getField(ObfuscatedNames.bufferArrayField);\n\t\tField offsetField = bufferInstance.getClass().getField(ObfuscatedNames.bufferOffsetField);\n\t\tarrayField.setAccessible(true);\n\t\toffsetField.setAccessible(true);\n\t\tbyte array[] = (byte[]) arrayField.get(bufferInstance);", "score": 0.8248759508132935 }, { "filename": "src/main/java/com/utils/Packets/BufferMethods.java", "retrieved_chunk": "\t@SneakyThrows\n\tpublic static void el(Object bufferInstance, int writtenValue){\n\t\tField arrayField = bufferInstance.getClass().getField(ObfuscatedNames.bufferArrayField);\n\t\tField offsetField = bufferInstance.getClass().getField(ObfuscatedNames.bufferOffsetField);\n\t\tarrayField.setAccessible(true);\n\t\toffsetField.setAccessible(true);\n\t\tbyte array[] = (byte[]) arrayField.get(bufferInstance);\n\t\tint offset = offsetField.getInt(bufferInstance);\n\t\tarray[(offset += -1516355947) * -1633313603 - 1] = (byte)(writtenValue >> 16);\n\t\tarray[(offset += -1516355947) * -1633313603 - 1] = (byte)(writtenValue >> 24);", "score": 0.8244575262069702 } ]
java
BufferMethods.du(buffer, (Integer) input);
package com.utils.gauntletFlicker; import com.utils.HypsApiPlugin.HypsApiPlugin; import com.utils.HypsApiPlugin.QuickPrayer; import com.utils.InteractionApi.InteractionHelper; import com.utils.PacketUtilsPlugin; import com.utils.Packets.MousePackets; import com.utils.Packets.WidgetPackets; import lombok.extern.slf4j.Slf4j; import net.runelite.api.Client; import net.runelite.api.EquipmentInventorySlot; import net.runelite.api.GameState; import net.runelite.api.HeadIcon; import net.runelite.api.InventoryID; import net.runelite.api.Item; import net.runelite.api.ItemComposition; import net.runelite.api.NPC; import net.runelite.api.NpcID; import net.runelite.api.Skill; import net.runelite.api.events.AnimationChanged; import net.runelite.api.events.GameTick; import net.runelite.api.events.MenuOptionClicked; import net.runelite.api.widgets.Widget; import net.runelite.api.widgets.WidgetInfo; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.game.ItemManager; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDependency; import net.runelite.client.plugins.PluginDescriptor; import javax.inject.Inject; import java.util.Set; @PluginDescriptor( name = "Gauntlet Flicker and Switcher", description = "", tags = {"Hyps"} ) @PluginDependency(HypsApiPlugin.class) @PluginDependency(PacketUtilsPlugin.class) @Slf4j public class gauntletFlicker extends Plugin { @Inject Client client; @Inject ItemManager manager; String updatedWeapon = ""; boolean forceTab = false; Set<Integer> HUNLLEF_IDS = Set.of(NpcID.CORRUPTED_HUNLLEF, NpcID.CORRUPTED_HUNLLEF_9036, NpcID.CORRUPTED_HUNLLEF_9037, NpcID.CORRUPTED_HUNLLEF_9038, NpcID.CRYSTALLINE_HUNLLEF, NpcID.CRYSTALLINE_HUNLLEF_9022, NpcID.CRYSTALLINE_HUNLLEF_9023, NpcID.CRYSTALLINE_HUNLLEF_9024); boolean isRange = true; @Subscribe public void onGameTick(GameTick e) { if (client.getLocalPlayer().isDead() || client.getLocalPlayer().getHealthRatio() == 0) { forceTab = false; return; } if (client.getGameState() != GameState.LOGGED_IN) { forceTab = false; return; } Item weapon = null; try { weapon = client.getItemContainer(InventoryID.EQUIPMENT).getItem(EquipmentInventorySlot.WEAPON.getSlotIdx()); } catch (NullPointerException ex) { //todo } String name = ""; if (weapon != null) { ItemComposition itemComp = manager.getItemComposition(client.getItemContainer(InventoryID.EQUIPMENT).getItem(EquipmentInventorySlot.WEAPON.getSlotIdx()).getId()); name = itemComp.getName() == null ? "" : itemComp.getName(); } NPC hunllef = client.getNpcs().stream().filter(x -> HUNLLEF_IDS.contains(x.getId())).findFirst().orElse(null); if (client.getVarbitValue(9177) != 1) { forceTab = false; return; } if (client.getVarbitValue(9178) != 1) { isRange = true; forceTab = false; updatedWeapon = ""; return; } if (forceTab) { client.runScript(915, 3); forceTab = false; } if (client.getWidget(5046276) == null) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(client.getWidget(WidgetInfo.MINIMAP_QUICK_PRAYER_ORB), "Setup"); forceTab = true; } if (isRange && !HypsApiPlugin.isQuickPrayerActive(QuickPrayer.PROTECT_FROM_MISSILES)) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetActionPacket(1, 5046276, -1, 13); //quickPrayer range } else if (!isRange && !HypsApiPlugin.isQuickPrayerActive(QuickPrayer.PROTECT_FROM_MAGIC)) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetActionPacket(1, 5046276, -1, 12); //quickPrayer magic } if (hunllef != null) { if (HypsApiPlugin.getHeadIcon(hunllef) == HeadIcon.MAGIC && (!name.contains("bow") && !name.contains("halberd"))) {
Widget bow = HypsApiPlugin.getItem("*bow*");
Widget halberd = HypsApiPlugin.getItem("*halberd*"); if (bow != null) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(bow, "Wield"); updatedWeapon = "bow"; } else if (halberd != null) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(halberd, "Wield"); updatedWeapon = "halberd"; } } if (HypsApiPlugin.getHeadIcon(hunllef) == HeadIcon.RANGED && (!name.contains("staff") && !name.contains("halberd"))) { Widget staff = HypsApiPlugin.getItem("*staff*"); Widget halberd = HypsApiPlugin.getItem("*halberd*"); if (staff != null) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(staff, "Wield"); updatedWeapon = "staff"; } else if (halberd != null) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(halberd, "Wield"); updatedWeapon = "halberd"; } } if (HypsApiPlugin.getHeadIcon(hunllef) == HeadIcon.MELEE && (!name.contains("staff") && !name.contains("bow"))) { Widget staff = HypsApiPlugin.getItem("*staff*"); Widget bow = HypsApiPlugin.getItem("*bow*"); if (staff != null) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(staff, "Wield"); updatedWeapon = "staff"; } else if (bow != null) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(bow, "Wield"); updatedWeapon = "bow"; } } String weaponTesting = updatedWeapon.isEmpty() ? name : updatedWeapon; if (weaponTesting.contains("bow")) { if (rigourUnlocked() && !HypsApiPlugin.isQuickPrayerActive(QuickPrayer.RIGOUR)) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetActionPacket(1, 5046276, -1, 24); //quickPrayer rigour } else if (!rigourUnlocked() && !HypsApiPlugin.isQuickPrayerActive(QuickPrayer.EAGLE_EYE)) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetActionPacket(1, 5046276, -1, 22); //quickPrayer eagle eye } } else if (weaponTesting.contains("staff")) { if (auguryUnlucked() && !HypsApiPlugin.isQuickPrayerActive(QuickPrayer.AUGURY)) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetActionPacket(1, 5046276, -1, 27); //quickPrayer augury } else if (!auguryUnlucked() && !HypsApiPlugin.isQuickPrayerActive(QuickPrayer.MYSTIC_MIGHT)) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetActionPacket(1, 5046276, -1, 23); //quickPrayer mystic might } } else if (weaponTesting.contains("halberd")) { if (pietyUnlocked() && !HypsApiPlugin.isQuickPrayerActive(QuickPrayer.PIETY)) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetActionPacket(1, 5046276, -1, 26); } else if (!pietyUnlocked() && !HypsApiPlugin.isQuickPrayerActive(QuickPrayer.ULTIMATE_STRENGTH)) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetActionPacket(1, 5046276, -1, 10); if (!HypsApiPlugin.isQuickPrayerActive(QuickPrayer.INCREDIBLE_REFLEXES)) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetActionPacket(1, 5046276, -1, 11); } }else if(!pietyUnlocked() && !HypsApiPlugin.isQuickPrayerActive(QuickPrayer.STEEL_SKIN)) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetActionPacket(1, 5046276, -1, QuickPrayer.STEEL_SKIN.getIndex()); } } } if (HypsApiPlugin.isQuickPrayerEnabled()) { InteractionHelper.togglePrayer(); } InteractionHelper.togglePrayer(); } public boolean rigourUnlocked() { return !(client.getVarbitValue(5451) == 0)&&client.getRealSkillLevel(Skill.PRAYER)>=74&&client.getRealSkillLevel(Skill.DEFENCE)>=70; } public boolean pietyUnlocked() { return client.getVarbitValue(3909) == 8&&client.getRealSkillLevel(Skill.PRAYER)>=70&&client.getRealSkillLevel(Skill.DEFENCE)>=70; } public boolean auguryUnlucked() { return !(client.getVarbitValue(5452) == 0)&&client.getRealSkillLevel(Skill.PRAYER)>=77&&client.getRealSkillLevel(Skill.DEFENCE)>=70; } @Subscribe public void onMenuOptionClicked(MenuOptionClicked event) { if (event.getMenuOption().toLowerCase().contains("pass")) { isRange = true; } } @Override protected void startUp() { isRange = true; forceTab = false; updatedWeapon = ""; } @Subscribe public void onAnimationChanged(AnimationChanged e) { if (e.getActor() == null) { return; } if (!(e.getActor() instanceof NPC)) { return; } NPC npc = (NPC) e.getActor(); if (!HUNLLEF_IDS.contains(npc.getId())) { return; } if (e.getActor().getAnimation() == 8754) { isRange = false; } if (e.getActor().getAnimation() == 8755) { isRange = true; } } private boolean isHunllefVarbitSet() { return client.getVarbitValue(9177) == 1; } }
src/main/java/com/utils/gauntletFlicker/gauntletFlicker.java
Hypsster-hUtils-d265b4f
[ { "filename": "src/main/java/com/utils/InteractionApi/InteractionHelper.java", "retrieved_chunk": "\t}\n\tpublic static void togglePrayer()\n\t{\n\t\tMousePackets.queueClickPacket(0, 0);\n\t\tWidgetPackets.queueWidgetActionPacket(1, quickPrayerWidgetID, -1, -1);\n\t}\n}", "score": 0.8523885011672974 }, { "filename": "src/main/java/com/utils/AutoTele/AutoTele.java", "retrieved_chunk": "\t\t\t\t}\n\t\t\t\tif (rowEquipment != null && !teleported)\n\t\t\t\t{\n\t\t\t\t\tteleported = true;\n\t\t\t\t\tMousePackets.queueClickPacket();\n\t\t\t\t\tWidgetPackets.queueWidgetActionPacket(3, 25362456, -1, -1);\n\t\t\t\t}\n\t\t\t\tif (teleported)\n\t\t\t\t{\n\t\t\t\t\tteleportedFromSkulledPlayer = HypsApiPlugin.getSkullIcon(player) != null;", "score": 0.8398619294166565 }, { "filename": "src/main/java/com/utils/InteractionApi/InteractionHelper.java", "retrieved_chunk": "package com.utils.InteractionApi;\nimport com.utils.Packets.MousePackets;\nimport com.utils.Packets.WidgetPackets;\nimport net.runelite.api.widgets.WidgetInfo;\nimport java.util.List;\npublic class InteractionHelper\n{\n\tstatic private int quickPrayerWidgetID = WidgetInfo.MINIMAP_QUICK_PRAYER_ORB.getPackedId();\n\tpublic static void toggleNormalPrayer(int packedWidgID)\n\t{", "score": 0.8366149663925171 }, { "filename": "src/main/java/com/utils/InteractionApi/InteractionHelper.java", "retrieved_chunk": "\t\tMousePackets.queueClickPacket();\n\t\tWidgetPackets.queueWidgetActionPacket(1, packedWidgID, -1, -1);\n\t}\n\tpublic static void toggleNormalPrayers(List<Integer> packedWidgIDs)\n\t{\n\t\tfor (Integer packedWidgID : packedWidgIDs)\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetActionPacket(1, packedWidgID, -1, -1);\n\t\t}", "score": 0.8307304382324219 }, { "filename": "src/main/java/com/utils/InteractionApi/NPCInteraction.java", "retrieved_chunk": "\t\t}\n\t\tMousePackets.queueClickPacket();\n\t\tNPCPackets.queueNPCAction(npc, actions);\n\t\treturn true;\n\t}\n}", "score": 0.8212470412254333 } ]
java
Widget bow = HypsApiPlugin.getItem("*bow*");
package com.ialdrich23xx.libasynwebhook.api.discord.body; import com.ialdrich23xx.libasynwebhook.api.Loader; import com.ialdrich23xx.libasynwebhook.api.discord.body.embed.EmbedManager; import com.ialdrich23xx.libasynwebhook.api.discord.body.embed.base.Structure; import java.util.*; public class Base extends Structure { private String content = null; private String username = null; private String avatar = null; private Boolean textToSpeech = false; private String threadName = null; private List<EmbedManager> embeds = new ArrayList<>(); public Base() {} public static Base make() { return new Base(); } public Base setContent(String content) { this.content = content; return this; } public String getContent() { return this.content; } public Base setUsername(String username) { this.username = username; return this; } public String getUsername() { return this.username; } public Base setAvatar(String avatar) { this.avatar = avatar; return this; } public String getAvatar() { return this.avatar; } public Base setTextToSpeech(Boolean textToSpeech) { this.textToSpeech = textToSpeech; return this; } public Boolean isTextToSpeech() { return this.textToSpeech; } public Base addEmbed(EmbedManager embed) { this.embeds.add(embed); return this; } public Base resetEmbeds() { this.embeds = new ArrayList<>(); return this; } public List<EmbedManager> getEmbeds() { return this.embeds; } public Base setForumTitle(String forumTitle) { this.threadName = forumTitle; return this; } public String getForumTitle() { return this.threadName; } public Boolean isForum() { return this.threadName != null; } @Override public Boolean build() { if (this.getAvatar() != null && !Loader.getInstance().isValidUrl(this.getAvatar())) return false; if (this.getContent() == null && this.getEmbeds().isEmpty()) return false; if (this.getContent() != null && this.getContent().length() == 0) return false; return true; } @Override public Map<String, Object> toArray() { Map<String, Object> result = new HashMap<>(); result.put("tts", this.isTextToSpeech()); if (this.getContent() != null) result.put("content", this.getContent()); if (this.getUsername() != null) result.put("username", this.getUsername()); if (this.getAvatar() != null) result.put("avatar_url", this.getAvatar()); List<Object> embedList = new ArrayList<>(); this.getEmbeds().forEach(embed -> embedList.add(Loader.getInstance().formatToJson
(embed.toArray().entrySet())));
if (!embedList.isEmpty()) { result.put("embeds", embedList.toArray()); } if (this.isForum()) result.put("thread_name", this.getForumTitle()); return result; } @Override public String toString() { return "Base(content=" + this.getContent() + ",username=" + this.getUsername() + ",avatar=" + this.getAvatar() + ";embeds=Array(" + this.getEmbeds().size() + ")"; } public String toJson() { return Loader.getInstance().formatToJson(this.toArray().entrySet()); } private String quote(String string) { return "\"" + string + "\""; } }
libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/Base.java
iAldrich23xX-libasynWebhook-52a1773
[ { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/EmbedManager.java", "retrieved_chunk": " if (this.getAuthor() != null) result.put(\"author\", this.getAuthor().toArray());\n if (this.getFooter() != null) result.put(\"footer\", this.getFooter().toArray());\n if (this.getThumbnail() != null) result.put(\"thumbnail\", this.getThumbnail().toArray());\n if (this.getImage() != null) result.put(\"image\", this.getImage().toArray());\n if (this.getTimestamp() != null) result.put(\"timestamp\", this.getTimestamp().getFormat().format(this.getTimestamp().getDate()));\n List<Object> fieldList = new ArrayList<>();\n this.getFields().forEach(field -> fieldList.add(Loader.getInstance().formatToJson(field.toArray().entrySet())));\n if (!fieldList.isEmpty()) {\n result.put(\"fields\", fieldList.toArray());\n }", "score": 0.8896645903587341 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/components/Author.java", "retrieved_chunk": " @Override\n public Map<String, Object> toArray() {\n Map<String, Object> result = this.nameToArray();\n if (!this.getUrl().isEmpty()) result.putAll(this.urlToArray());\n if (!this.getIcon().isEmpty()) result.putAll(this.iconToArray());\n return result;\n }\n @Override\n public String toString() {\n return \"Author(\" + this.nameToString() + \",\" + this.urlToString() + \",\" + this.iconToString() + \")\";", "score": 0.8876103162765503 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/components/Field.java", "retrieved_chunk": " @Override\n public Map<String, Object> toArray() {\n Map<String, Object> result = this.nameToArray();\n result.put(\"value\", this.getName());\n result.put(\"inline\", this.getInline());\n return result;\n }\n @Override\n public String toString() {\n return \"Field(\" + this.nameToString() + \",value=\" + this.getValue() + \",inline=\" + this.getInline().toString() + \")\";", "score": 0.880879819393158 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/EmbedManager.java", "retrieved_chunk": " @Override\n public Boolean build() {\n return !this.getTitle().isEmpty() && !this.getDescription().isEmpty() || !this.getFields().isEmpty();\n }\n @Override\n public Map<String, Object> toArray() {\n Map<String, Object> result = new HashMap<>();\n result.put(\"title\", this.getTitle());\n result.put(\"description\", this.getDescription());\n result.put(\"color\", this.getColor());", "score": 0.8427510261535645 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/components/Footer.java", "retrieved_chunk": " Map<String, Object> result = new HashMap<>();\n result.put(\"text\", this.getText());\n if (!this.getIcon().isEmpty()) result.putAll(this.iconToArray());\n return result;\n }\n @Override\n public String toString() {\n return \"Footer(text=\" + this.getText() + \",\" + this.iconToString() + \")\";\n }\n}", "score": 0.8340380191802979 } ]
java
(embed.toArray().entrySet())));
package org.easycontactforms.core.services; import org.easycontactforms.core.dtos.ContactFormDto; import org.easycontactforms.core.models.ContactForm; import org.easycontactforms.core.repositories.ContactFormRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; /** * Service to handle processing of contact form input */ @Slf4j @Service public class ContactFormService { private final ContactFormRepository repository; private final MailingService mailingService; @Value("${redirect.mode}") private String mode; @Autowired public ContactFormService(ContactFormRepository repository, MailingService mailingService){ this.repository = repository; this.mailingService = mailingService; } /** * handles initial request * @param contactFormDto * @return */ public ContactForm saveContactForm(ContactFormDto contactFormDto){ ContactForm contactForm = repository.save(ContactForm.fromContactFormDto(contactFormDto)); if(mode.equalsIgnoreCase("email")){ log.info("Redirecting Contact Form to email"); MailSendThread thread = new MailSendThread(this, mailingService, contactForm); thread.start(); } log.info("Saved Contact Form"); return contactForm; } /** * updates single instance in database * @param contactForm changed object * @return result from database */ public ContactForm updateContactForm(ContactForm contactForm){ repository.save(contactForm); return contactForm; } public List<ContactForm> getContactForms(boolean onlyNotSendEmails){ if(!onlyNotSendEmails){ return repository.findAll(); }else {
return repository.findByEmailSent(false);
} } }
src/main/java/org/easycontactforms/core/services/ContactFormService.java
Jan222333444-EasyContactForms-a2cf723
[ { "filename": "src/main/java/org/easycontactforms/core/repositories/ContactFormRepository.java", "retrieved_chunk": "package org.easycontactforms.core.repositories;\nimport org.easycontactforms.core.models.ContactForm;\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport java.util.List;\n/**\n * Repository to interact with database\n */\npublic interface ContactFormRepository extends JpaRepository<ContactForm, Integer> {\n public List<ContactForm> findByEmailSent(boolean emailSent);\n}", "score": 0.8763372898101807 }, { "filename": "src/main/java/org/easycontactforms/core/services/MailSendThread.java", "retrieved_chunk": " ApplicationState.smtpAvailable = false;\n e.printStackTrace();\n return;\n }\n if(!ApplicationState.smtpAvailable && resendPolicy){\n ApplicationState.smtpAvailable = true;\n mailingService.resendMails(true, contactFormService);\n }\n contactForm.setEmailSent(true);\n contactFormService.updateContactForm(contactForm);", "score": 0.8447360992431641 }, { "filename": "src/test/java/org/easycontactforms/unittests/testpluginclasses/Testplugin3.java", "retrieved_chunk": " public boolean beforeContactFormProcessing(ContactFormDto contactForm) {\n return false;\n }\n @Override\n public boolean contactFormProcessed(ContactForm contactForm) {\n return false;\n }\n @Override\n public boolean onMailSent(ContactForm contactForm) {\n return false;", "score": 0.8437470197677612 }, { "filename": "src/test/java/org/easycontactforms/unittests/testpluginclasses/Testplugin2.java", "retrieved_chunk": " public boolean beforeContactFormProcessing(ContactFormDto contactForm) {\n return false;\n }\n @Override\n public boolean contactFormProcessed(ContactForm contactForm) {\n return false;\n }\n @Override\n public boolean onMailSent(ContactForm contactForm) {\n return false;", "score": 0.8437470197677612 }, { "filename": "src/test/java/org/easycontactforms/unittests/testpluginclasses/Testplugin1.java", "retrieved_chunk": " public boolean beforeContactFormProcessing(ContactFormDto contactForm) {\n return false;\n }\n @Override\n public boolean contactFormProcessed(ContactForm contactForm) {\n return false;\n }\n @Override\n public boolean onMailSent(ContactForm contactForm) {\n return false;", "score": 0.8437470197677612 } ]
java
return repository.findByEmailSent(false);
package org.easycontactforms.core; import jakarta.annotation.PreDestroy; import lombok.extern.slf4j.Slf4j; import org.easycontactforms.api.PluginFactory; import org.easycontactforms.core.commandhandler.CommandHandlerThread; import org.easycontactforms.core.pluginloader.PluginLoader; import org.easycontactforms.core.pluginloader.PluginStore; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.scheduling.annotation.EnableScheduling; import java.io.File; import java.util.Map; /** * Main class of application * Handles startup and teardown of Plugins and application */ @Slf4j @SpringBootApplication @EnableScheduling public class EasyContactFormsApplication { public static void main(String[] args) { String pluginsPath = "plugins"; new FirstStartupChecker().checkDirectories(); loadPlugins(pluginsPath); //Starts all plugins for (String key : PluginStore.instance.plugins.keySet()) { PluginStore.instance.plugins.get(key).onStartup(); } //Starts Spring Boot server ApplicationContext context = SpringApplication.run(EasyContactFormsApplication.class, args); //Executes on load hook for (String key : PluginStore.instance.plugins.keySet()) { PluginStore.instance.plugins.get(key).onLoad(); } CommandHandlerThread handlerThread = new CommandHandlerThread(context, System.in, args); handlerThread.start(); } public static void loadPlugins(String pluginsPath) { PluginLoader pluginLoader = new PluginLoader(new File(pluginsPath)); pluginLoader.loadPlugins(); Map<String, PluginFactory> factories
= pluginLoader.getPluginFactories();
for (String key : factories.keySet()) { PluginStore.instance.plugins.put(key, factories.get(key).build()); } } @PreDestroy public static void teardown() { for (String key : PluginStore.instance.plugins.keySet()) { PluginStore.instance.plugins.get(key).onTeardown(); } } }
src/main/java/org/easycontactforms/core/EasyContactFormsApplication.java
Jan222333444-EasyContactForms-a2cf723
[ { "filename": "src/main/java/org/easycontactforms/core/commandhandler/CommandHandler.java", "retrieved_chunk": " //Executes on load hook\n for (String key : PluginStore.instance.plugins.keySet()) {\n PluginStore.instance.plugins.get(key).onLoad();\n }\n }\n /**\n * logic for shutdown command\n * @param args command line arguments\n */\n private void shutdown(String... args){", "score": 0.870814323425293 }, { "filename": "src/main/java/org/easycontactforms/core/commandhandler/CommandHandler.java", "retrieved_chunk": " return PluginStore.instance.plugins.values().stream().sorted(Comparator.comparingInt(plugin -> plugin.priority.value)).collect(Collectors.toList());\n }\n /**\n * executes plugin commands\n * @param command executed command\n * @param args command line arguments\n */\n private boolean onCommandPlugins(String command, String... args) {\n for (Plugin plugin : plugins) {\n try {", "score": 0.8563642501831055 }, { "filename": "TestPlugin/src/main/java/org/easycontactforms/testplugin/TestPlugin.java", "retrieved_chunk": " factories.add(new TestPluginFactory());\n return factories;\n }\n @Override\n public boolean onStartup() {\n System.out.println(\"Im started\");\n return true;\n }\n @Override\n public boolean onLoad() {", "score": 0.8518629670143127 }, { "filename": "src/test/java/org/easycontactforms/unittests/CommandHandlerTest.java", "retrieved_chunk": " @Test\n public void testPluginCommand(){\n Plugin pluginFirst = new Testplugin1();\n PluginStore.instance.plugins.put(\"first\", pluginFirst);\n CommandHandler handler = new CommandHandler(null, null);\n boolean result = handler.onCommand(\"plugintestcommand\", \"plugintestcommand\");\n Assertions.assertTrue(result);\n }\n @Test\n public void testCommandHandlerThread() throws InterruptedException {", "score": 0.8508689403533936 }, { "filename": "src/main/java/org/easycontactforms/core/commandhandler/CommandHandler.java", "retrieved_chunk": " * JVM arguments for startup of service\n */\n private final String[] baseArgs;\n /**\n * List of all plugins ordered by priority\n */\n private List<Plugin> plugins;\n public CommandHandler(ApplicationContext context, String[] args){\n this.context = context;\n this.baseArgs = args;", "score": 0.8403777480125427 } ]
java
= pluginLoader.getPluginFactories();
package com.utils.AutoTele; import com.utils.HypsApiPlugin.HypsApiPlugin; import com.utils.HypsApiPlugin.Inventory; import com.utils.InteractionApi.InventoryInteraction; import com.utils.PacketUtilsPlugin; import com.utils.Packets.MousePackets; import com.utils.Packets.WidgetPackets; import com.google.inject.Inject; import com.google.inject.Provides; import net.runelite.api.ChatMessageType; import net.runelite.api.Client; import net.runelite.api.EquipmentInventorySlot; import net.runelite.api.InventoryID; import net.runelite.api.Item; import net.runelite.api.ItemID; import net.runelite.api.Player; import net.runelite.api.events.AnimationChanged; import net.runelite.api.events.GameTick; import net.runelite.api.widgets.Widget; import net.runelite.api.widgets.WidgetInfo; import net.runelite.client.config.ConfigManager; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.game.ItemManager; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDependency; import net.runelite.client.plugins.PluginDescriptor; import java.util.Optional; import java.util.Set; @PluginDescriptor( name = "AutoTele", enabledByDefault = false, tags = {"Hyps"} ) @PluginDependency(HypsApiPlugin.class) @PluginDependency(PacketUtilsPlugin.class) public class AutoTele extends Plugin { @Inject Client client; int timeout; static final int RING_OF_WEALTH = 714; static final int SEED_POD = 4544; int previousLevel = -1; public static boolean teleportedFromSkulledPlayer = false; @Inject ItemManager itemManager; @Inject AutoTeleConfig config; static final Set<Integer> RING_OF_WEALTH_ITEM_IDS = Set.of(ItemID.RING_OF_WEALTH_1, ItemID.RING_OF_WEALTH_2, ItemID.RING_OF_WEALTH_3, ItemID.RING_OF_WEALTH_4, ItemID.RING_OF_WEALTH_5, ItemID.RING_OF_WEALTH_I1, ItemID.RING_OF_WEALTH_I2, ItemID.RING_OF_WEALTH_I3, ItemID.RING_OF_WEALTH_I4, ItemID.RING_OF_WEALTH_I5); @Provides public AutoTeleConfig getConfig(ConfigManager configManager) { return configManager.getConfig(AutoTeleConfig.class); } @Subscribe public void onGameTick(GameTick event) { if (timeout > 0) { timeout--; return; } Widget wildernessLevel = client.getWidget(WidgetInfo.PVP_WILDERNESS_LEVEL); int level = -1; if (wildernessLevel != null && !wildernessLevel.getText().equals("")) { try { if (wildernessLevel.getText().contains("<br>")) { String text = wildernessLevel.getText().split("<br>")[0]; level = Integer.parseInt(text.replaceAll("Level: ", "")); } else { level = Integer.parseInt(wildernessLevel.getText().replaceAll("Level: ", "")); } } catch (NumberFormatException ex) { //ignore } } if (previousLevel != -1 && level == -1) { previousLevel = -1; } Item rowEquipment = null; if (client.getItemContainer(InventoryID.EQUIPMENT) != null) { rowEquipment = client.getItemContainer(InventoryID.EQUIPMENT).getItem(EquipmentInventorySlot.RING.getSlotIdx()); } if ((rowEquipment != null && !RING_OF_WEALTH_ITEM_IDS.contains(rowEquipment.getId()))) { rowEquipment = null; } if (level > -1) { if (previousLevel == -1) { previousLevel = level; Optional<Widget> royal_seed_pod = Inventory.search().withId(ItemID.ROYAL_SEED_POD).first(); Optional
<Widget> ring_of_wealth = Inventory.search().nameContains("Ring of wealth (").first();
if (config.alert()) { if (royal_seed_pod.isPresent() || ring_of_wealth.isPresent() || (rowEquipment != null && RING_OF_WEALTH_ITEM_IDS.contains(rowEquipment.getId()))) { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "<col=7cfc00>Entering wilderness with a teleport item." + " " + "AutoTele is ready to save you", null); } else { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "<col=ff0000> Entering wilderness without a " + "supported " + "teleport possible mistake?", null); } } } } for (Player player : client.getPlayers()) { int lowRange = client.getLocalPlayer().getCombatLevel() - level; int highRange = client.getLocalPlayer().getCombatLevel() + level; if (player.equals(client.getLocalPlayer())) { continue; } if (player.getCombatLevel() >= lowRange && player.getCombatLevel() <= highRange || !config.combatrange()) { // boolean hadMage = false; // boolean skippableWeapon = false; // if (config.mageFilter()) // { // int mageBonus = 0; // for (int equipmentId : player.getPlayerComposition().getEquipmentIds()) // { // if (equipmentId == -1) // { // continue; // } // if (equipmentId == 6512) // { // continue; // } // if (equipmentId >= 512) // { // return; // } // int realId = equipmentId - 512; // ItemEquipmentStats itemStats = itemManager.getItemStats(realId, false).getEquipment(); // if (itemStats == null) // { // continue; // } // mageBonus += itemStats.getAmagic(); // } // if (mageBonus > 0) // { // hadMage = true; // } // } // if (!config.weaponFilter().equals("")) // { // List<String> filteredWeapons = getFilteredWeapons(); // for (int equipment : player.getPlayerComposition().getEquipmentIds()) // { // int equipmentId = equipment - 512; // if (equipmentId > 0) // { // ItemComposition equipmentComp = itemManager.getItemComposition(equipmentId); // if (filteredWeapons.stream().anyMatch(item -> WildcardMatcher.matches(item.toLowerCase(), // Text.removeTags(equipmentComp.getName().toLowerCase())))) // { // skippableWeapon = true; // } // } // } // } // if (skippableWeapon) // { // if (!hadMage) // { // continue; // } // } boolean teleported = false; Optional<Widget> widget = Inventory.search().withId(ItemID.ROYAL_SEED_POD).first(); if (widget.isPresent()) { teleported = true; InventoryInteraction.useItem(widget.get(), "Commune"); } Optional<Widget> row = Inventory.search().nameContains("Ring of wealth (").first(); if (row.isPresent() && !teleported) { teleported = true; InventoryInteraction.useItem(row.get(), "Rub"); MousePackets.queueClickPacket(); WidgetPackets.queueResumePause(14352385, 2); } if (rowEquipment != null && !teleported) { teleported = true; MousePackets.queueClickPacket(); WidgetPackets.queueWidgetActionPacket(3, 25362456, -1, -1); } if (teleported) { teleportedFromSkulledPlayer = HypsApiPlugin.getSkullIcon(player) != null; if (teleportedFromSkulledPlayer) { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "Teleported from skulled player", null); } else { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "Teleported from non-skulled player", null); } } return; } } } // public List<String> getFilteredWeapons() // { // List<String> itemNames = new ArrayList<>(); // for (String s : config.weaponFilter().split(",")) // { // if (StringUtils.isNumeric(s)) // { // itemNames.add(Text.removeTags(itemManager.getItemComposition(Integer.parseInt(s)).getName())); // } // else // { // itemNames.add(s); // } // } // return itemNames; // } @Subscribe public void onAnimationChanged(AnimationChanged e) { Widget wildernessLevel = client.getWidget(WidgetInfo.PVP_WILDERNESS_LEVEL); int level = -1; if (wildernessLevel != null && !wildernessLevel.getText().equals("")) { try { if (wildernessLevel.getText().contains("<br>")) { String text = wildernessLevel.getText().split("<br>")[0]; level = Integer.parseInt(text.replaceAll("Level: ", "")); } else { level = Integer.parseInt(wildernessLevel.getText().replaceAll("Level: ", "")); } } catch (NumberFormatException ex) { //ignore } } if (level > -1) { if (e.getActor() == client.getLocalPlayer()) { int animation = client.getLocalPlayer().getAnimation(); if (animation == SEED_POD || animation == RING_OF_WEALTH) { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "timeout triggered", null); timeout = 10; } } } } }
src/main/java/com/utils/AutoTele/AutoTele.java
Hypsster-hUtils-d265b4f
[ { "filename": "src/main/java/com/utils/gauntletFlicker/gauntletFlicker.java", "retrieved_chunk": "\t\t\t{\n\t\t\t\tWidget staff = HypsApiPlugin.getItem(\"*staff*\");\n\t\t\t\tWidget bow = HypsApiPlugin.getItem(\"*bow*\");\n\t\t\t\tif (staff != null)\n\t\t\t\t{\n\t\t\t\t\tMousePackets.queueClickPacket();\n\t\t\t\t\tWidgetPackets.queueWidgetAction(staff, \"Wield\");\n\t\t\t\t\tupdatedWeapon = \"staff\";\n\t\t\t\t}\n\t\t\t\telse if (bow != null)", "score": 0.7976756691932678 }, { "filename": "src/main/java/com/utils/HypsApiPlugin/BankInventory.java", "retrieved_chunk": "\t\t\t\t\t\t\tArrays.stream(client.getWidget(WidgetInfo.BANK_INVENTORY_ITEMS_CONTAINER).getDynamicChildren()).filter(Objects::nonNull).filter(x -> x.getItemId() != 6512 && x.getItemId() != -1).collect(Collectors.toList());\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcatch (NullPointerException err)\n\t\t\t\t{\n\t\t\t\t\tBankInventory.bankIventoryItems.clear();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t}\n\t}", "score": 0.7956621646881104 }, { "filename": "src/main/java/com/utils/HypsApiPlugin/Equipment.java", "retrieved_chunk": "\t\t\t\t}\n\t\t\t\tif (item.getId() == 6512 || item.getId() == -1)\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tWidget w = client.getWidget(WidgetInfo.EQUIPMENT.getGroupId(), equipmentSlotWidgetMapping.get(i));\n\t\t\t\tif(w==null||w.getActions()==null){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tequipment.add(new EquipmentItemWidget(w.getName(),item.getId(),w.getId(),i,w.getActions()));", "score": 0.7921551465988159 }, { "filename": "src/main/java/com/utils/HypsApiPlugin/Equipment.java", "retrieved_chunk": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\npublic class Equipment\n{\n\tstatic Client client = RuneLite.getInjector().getInstance(Client.class);\n\tstatic List<EquipmentItemWidget> equipment = new ArrayList<>();\n\tstatic HashMap<Integer, Integer> equipmentSlotWidgetMapping = new HashMap<>();\n\tstatic\n\t{", "score": 0.7902563810348511 }, { "filename": "src/main/java/com/utils/HypsApiPlugin/Equipment.java", "retrieved_chunk": "\t\tequipmentSlotWidgetMapping.put(13, 25);\n\t}\n\tpublic static EquipmentItemQuery search()\n\t{\n\t\treturn new EquipmentItemQuery(equipment);\n\t}\n\t@SneakyThrows\n\t@Subscribe\n\tpublic void onItemContainerChanged(ItemContainerChanged e)\n\t{", "score": 0.7900339961051941 } ]
java
<Widget> ring_of_wealth = Inventory.search().nameContains("Ring of wealth (").first();
package org.easycontactforms.core.commandhandler; import lombok.extern.slf4j.Slf4j; import org.springframework.context.ApplicationContext; import java.io.InputStream; import java.util.Scanner; /** * Thread for processing command line inputs */ @Slf4j public class CommandHandlerThread extends Thread { private final ApplicationContext context; private final String[] baseArgs; private final InputStream inputStream; public CommandHandlerThread(ApplicationContext context, InputStream inputStream, String... baseArgs){ this.context = context; this.baseArgs = baseArgs; this.inputStream = inputStream; } @Override public void run() { //Waiting and processing commands from std in Scanner scanner = new Scanner(inputStream); CommandHandler handler = new CommandHandler(context, baseArgs); while (true) { String input = scanner.nextLine(); String[] arguments = input.split(" "); String command = arguments[0]; boolean result =
handler.onCommand(command, arguments);
if (!result) { if(command.equalsIgnoreCase("stopCommandHandler")){ break; } log.error("Could not recognize command"); } } log.info("Stopped command handler!"); } }
src/main/java/org/easycontactforms/core/commandhandler/CommandHandlerThread.java
Jan222333444-EasyContactForms-a2cf723
[ { "filename": "src/test/java/org/easycontactforms/unittests/CommandHandlerTest.java", "retrieved_chunk": " InputStream stream = new ByteArrayInputStream(\"stopCommandHandler\\n\".getBytes());\n CommandHandlerThread thread = new CommandHandlerThread(null, stream, \"\");\n thread.start();\n thread.join();\n }\n}", "score": 0.8266128897666931 }, { "filename": "src/main/java/org/easycontactforms/core/commandhandler/CommandHandler.java", "retrieved_chunk": " * JVM arguments for startup of service\n */\n private final String[] baseArgs;\n /**\n * List of all plugins ordered by priority\n */\n private List<Plugin> plugins;\n public CommandHandler(ApplicationContext context, String[] args){\n this.context = context;\n this.baseArgs = args;", "score": 0.8104061484336853 }, { "filename": "src/main/java/org/easycontactforms/core/commandhandler/CommandHandler.java", "retrieved_chunk": " this.plugins = this.priorities();\n }\n /**\n * gets executed if new line is entered\n * @param command base command (everything before first white space)\n * @param args all command line arguments (including command)\n */\n public boolean onCommand(String command, String... args) {\n boolean internalCommand = internalCommands(command, args);\n boolean external = false;", "score": 0.8022950887680054 }, { "filename": "src/test/java/org/easycontactforms/unittests/testpluginclasses/Testplugin3.java", "retrieved_chunk": " }\n @Override\n public boolean onCommand(String command, String... args) {\n return false;\n }\n}", "score": 0.8017902374267578 }, { "filename": "src/test/java/org/easycontactforms/unittests/testpluginclasses/Testplugin2.java", "retrieved_chunk": " }\n @Override\n public boolean onCommand(String command, String... args) {\n return false;\n }\n}", "score": 0.8017902374267578 } ]
java
handler.onCommand(command, arguments);
package org.easycontactforms.core.commandhandler; import lombok.extern.slf4j.Slf4j; import org.easycontactforms.api.Plugin; import org.easycontactforms.core.EasyContactFormsApplication; import org.easycontactforms.core.pluginloader.PluginStore; import org.springframework.boot.SpringApplication; import org.springframework.context.ApplicationContext; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; /** * Class for handling command line inputs */ @Slf4j public class CommandHandler { /** * Currently used Spring Application Context */ private ApplicationContext context; /** * JVM arguments for startup of service */ private final String[] baseArgs; /** * List of all plugins ordered by priority */ private List<Plugin> plugins; public CommandHandler(ApplicationContext context, String[] args){ this.context = context; this.baseArgs = args; this.plugins = this.priorities(); } /** * gets executed if new line is entered * @param command base command (everything before first white space) * @param args all command line arguments (including command) */ public boolean onCommand(String command, String... args) { boolean internalCommand = internalCommands(command, args); boolean external = false; if(!internalCommand){ external = onCommandPlugins(command, args); } return internalCommand || external; } /** * Sorts plugins by priority * @return list of all plugins loaded sorted by priority from Highest to Lowest */ private List<Plugin> priorities(){ return PluginStore.instance.plugins.values().stream().sorted(Comparator.comparingInt(plugin -> plugin.priority.value)).collect(Collectors.toList()); } /** * executes plugin commands * @param command executed command * @param args command line arguments */ private boolean onCommandPlugins(String command, String... args) { for (Plugin plugin : plugins) { try { boolean handled = plugin.onCommand(command, args); if (handled) { return true; } } catch (AbstractMethodError error) { log.warn("Plugin does not implement onCommand Method"); log.warn(error.getMessage()); } } return false; } /** * executes basic internal commands from command line * @param command executed command * @param args command line arguments * @return true if command is internal, else false */ private boolean internalCommands(String command, String... args) { if (command.equalsIgnoreCase("stop")) { System.exit(0); return true; } else if (command.equalsIgnoreCase("reloadplugins")) { reloadPlugins(); return true; } else if (command.equalsIgnoreCase("reloadspring")) { SpringApplication.exit(context); this.context = SpringApplication.run(EasyContactFormsApplication.class, this.baseArgs); return true; } else if (command.equalsIgnoreCase("reload")) { SpringApplication.exit(context); this.context = SpringApplication.run(EasyContactFormsApplication.class, this.baseArgs); reloadPlugins(); return true; } else if (command.equalsIgnoreCase("shutdown")) { shutdown(args); return true; } return false; } /** * reloads all plugins from source */ private void reloadPlugins(){ String pluginsPath = "plugins";
EasyContactFormsApplication.loadPlugins(pluginsPath);
plugins = priorities(); //Starts all plugins for (String key : PluginStore.instance.plugins.keySet()) { PluginStore.instance.plugins.get(key).onStartup(); } //Executes on load hook for (String key : PluginStore.instance.plugins.keySet()) { PluginStore.instance.plugins.get(key).onLoad(); } } /** * logic for shutdown command * @param args command line arguments */ private void shutdown(String... args){ // standard execution if(args.length == 1){ try { TimeUnit.SECONDS.sleep(10); } catch (InterruptedException e) { throw new RuntimeException(e); } System.exit(0); return; } // initiates shutdown immediately (like stop command) if(args[1].equalsIgnoreCase("now")){ System.exit(0); return; } // initiates shutdown after given delay in seconds try{ int delay = Integer.parseInt(args[1]); TimeUnit.SECONDS.sleep(delay); System.exit(0); } catch (NumberFormatException exception) { log.error("Cannot parse input. Argument 1 is not of type integer: {}", args[1]); } catch (InterruptedException e) { log.error("Something went wrong on Shutdown"); } } /** * * @return List of Plugins ordered from highest to lowest priority */ public List<Plugin> getPluginsByPriority(){ return plugins; } }
src/main/java/org/easycontactforms/core/commandhandler/CommandHandler.java
Jan222333444-EasyContactForms-a2cf723
[ { "filename": "src/main/java/org/easycontactforms/core/EasyContactFormsApplication.java", "retrieved_chunk": " ApplicationContext context = SpringApplication.run(EasyContactFormsApplication.class, args);\n //Executes on load hook\n for (String key : PluginStore.instance.plugins.keySet()) {\n PluginStore.instance.plugins.get(key).onLoad();\n }\n CommandHandlerThread handlerThread = new CommandHandlerThread(context, System.in, args);\n handlerThread.start();\n }\n public static void loadPlugins(String pluginsPath) {\n PluginLoader pluginLoader = new PluginLoader(new File(pluginsPath));", "score": 0.8566968441009521 }, { "filename": "src/main/java/org/easycontactforms/core/EasyContactFormsApplication.java", "retrieved_chunk": "public class EasyContactFormsApplication {\n public static void main(String[] args) {\n String pluginsPath = \"plugins\";\n new FirstStartupChecker().checkDirectories();\n loadPlugins(pluginsPath);\n //Starts all plugins\n for (String key : PluginStore.instance.plugins.keySet()) {\n PluginStore.instance.plugins.get(key).onStartup();\n }\n //Starts Spring Boot server", "score": 0.8501206636428833 }, { "filename": "src/main/java/org/easycontactforms/core/EasyContactFormsApplication.java", "retrieved_chunk": "package org.easycontactforms.core;\nimport jakarta.annotation.PreDestroy;\nimport lombok.extern.slf4j.Slf4j;\nimport org.easycontactforms.api.PluginFactory;\nimport org.easycontactforms.core.commandhandler.CommandHandlerThread;\nimport org.easycontactforms.core.pluginloader.PluginLoader;\nimport org.easycontactforms.core.pluginloader.PluginStore;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.context.ApplicationContext;", "score": 0.8270426988601685 }, { "filename": "TestPlugin/src/main/java/org/easycontactforms/testplugin/TestPlugin.java", "retrieved_chunk": " factories.add(new TestPluginFactory());\n return factories;\n }\n @Override\n public boolean onStartup() {\n System.out.println(\"Im started\");\n return true;\n }\n @Override\n public boolean onLoad() {", "score": 0.8217982053756714 }, { "filename": "src/main/java/org/easycontactforms/core/pluginloader/PluginLoader.java", "retrieved_chunk": "package org.easycontactforms.core.pluginloader;\nimport org.easycontactforms.api.Plugin;\nimport org.easycontactforms.api.PluginFactory;\nimport lombok.extern.slf4j.Slf4j;\nimport org.springframework.stereotype.Controller;\nimport java.net.MalformedURLException;\nimport java.net.URI;\nimport java.net.URL;\nimport java.io.File;\nimport java.net.URLClassLoader;", "score": 0.8210482597351074 } ]
java
EasyContactFormsApplication.loadPlugins(pluginsPath);
package org.easycontactforms.core.services; import org.easycontactforms.core.models.ContactForm; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; import org.thymeleaf.templatemode.TemplateMode; import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import java.io.UnsupportedEncodingException; import java.util.List; import java.util.Properties; /** * Service to send emails */ @Slf4j @Service public class MailingService { @Value("${mail.user.name}") private String name; @Value("${mail.user.password}") private String password; @Value("${mail.smtp.auth}") private String auth; @Value("${mail.smtp.ssl.enable}") private String enable; @Value("${mail.smtp.host}") private String host; @Value("${mail.smtp.port}") private String port; @Value("${mail.smtp.ssl.protocols}") private String protocols; @Value("${mail.smtp.ssl.trust}") private String trust; @Value("${mail.user.address}") private String address; @Value("${mail.recipient.address}") private String recipient; @Value("${mail.user.displayName}") private String displayName; /** * method sends email based on configuration of application * @param contactForm contact form to redirect * @throws MessagingException is thrown if smtp server is not reachable * @throws UnsupportedEncodingException unexpected error */ public void sendMail(ContactForm contactForm) throws MessagingException, UnsupportedEncodingException { Properties prop = new Properties(); prop.put("mail.smtp.auth", auth); prop.put("mail.smtp.ssl.enable", enable); prop.put("mail.smtp.host", host); prop.put("mail.smtp.port", port); prop.put("mail.smtp.ssl.protocols", protocols); prop.put("mail.smtp.ssl.trust", trust); Session session = Session.getInstance(prop, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( name, password); } }); String msg = renderHTML(contactForm); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(address, displayName)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient)); message.setSubject("New Contact Request from: " + contactForm.getEmail()); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(msg, "text/html"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); message.setContent(multipart); Transport.send(message); } /** * Renders HTML for Email based on contact form * @param contactForm information to render HTML * @return rendered HTML as String */ public String renderHTML(ContactForm contactForm) { ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver(); templateResolver.setSuffix(".html"); templateResolver.setTemplateMode(TemplateMode.HTML); TemplateEngine templateEngine = new TemplateEngine(); templateEngine.setTemplateResolver(templateResolver); String[] msg = contactForm.getMessage().split("\n"); Context context = new Context(); context.setVariable("name", contactForm.getName() == null ? "" : contactForm.getName()); context.setVariable("subject", contactForm.getSubject() == null ? "" : contactForm.getSubject()); context.setVariable("message", msg); context.setVariable("email", contactForm.getEmail()); context.setVariable("id", contactForm.getId()); return templateEngine.process("mail-template", context); } public void resendMails(boolean resendOnlyNotSendMails, ContactFormService contactFormService){ if(resendOnlyNotSendMails){ List
<ContactForm> forms = contactFormService.getContactForms(true);
for (ContactForm contactForm : forms){ MailSendThread thread = new MailSendThread(contactFormService, this, contactForm); thread.start(); } } } }
src/main/java/org/easycontactforms/core/services/MailingService.java
Jan222333444-EasyContactForms-a2cf723
[ { "filename": "src/main/java/org/easycontactforms/core/services/MailSendThread.java", "retrieved_chunk": " ApplicationState.smtpAvailable = false;\n e.printStackTrace();\n return;\n }\n if(!ApplicationState.smtpAvailable && resendPolicy){\n ApplicationState.smtpAvailable = true;\n mailingService.resendMails(true, contactFormService);\n }\n contactForm.setEmailSent(true);\n contactFormService.updateContactForm(contactForm);", "score": 0.9029904007911682 }, { "filename": "src/main/java/org/easycontactforms/core/scheduled/ResendEmailsScheduler.java", "retrieved_chunk": "public class ResendEmailsScheduler {\n private final MailingService mailingService;\n private final ContactFormService contactFormService;\n @Value(\"${redirect.mode.resend}\")\n private boolean resend;\n @Autowired\n public ResendEmailsScheduler(MailingService mailingService, ContactFormService contactFormService){\n this.mailingService = mailingService;\n this.contactFormService = contactFormService;\n }", "score": 0.8792548775672913 }, { "filename": "src/main/java/org/easycontactforms/core/scheduled/ResendEmailsScheduler.java", "retrieved_chunk": " @Scheduled(fixedRateString = \"${redirect.mode.resend.interval}\")\n public void resendEmails(){\n if(resend) {\n log.info(\"Resending not send emails\");\n mailingService.resendMails(true, contactFormService);\n }\n }\n}", "score": 0.8649431467056274 }, { "filename": "src/main/java/org/easycontactforms/core/services/MailSendThread.java", "retrieved_chunk": " private final MailingService mailingService;\n private final ContactFormService contactFormService;\n private final ContactForm contactForm;\n @Value(\"${redirect.mode.resend}\")\n private boolean resendPolicy;\n public MailSendThread(ContactFormService contactFormService, MailingService mailingService, ContactForm contactForm) {\n this.contactFormService = contactFormService;\n this.mailingService = mailingService;\n this.contactForm = contactForm;\n }", "score": 0.8589420318603516 }, { "filename": "TestPlugin/src/main/java/org/easycontactforms/testplugin/TestPlugin.java", "retrieved_chunk": " System.out.println(\"Before Processing\");\n return false;\n }\n @Override\n public boolean contactFormProcessed(ContactForm contactForm) {\n System.out.println(\"Processed\");\n return false;\n }\n @Override\n public boolean onMailSent(ContactForm contactForm) {", "score": 0.8538496494293213 } ]
java
<ContactForm> forms = contactFormService.getContactForms(true);
package com.utils.AutoTele; import com.utils.HypsApiPlugin.HypsApiPlugin; import com.utils.HypsApiPlugin.Inventory; import com.utils.InteractionApi.InventoryInteraction; import com.utils.PacketUtilsPlugin; import com.utils.Packets.MousePackets; import com.utils.Packets.WidgetPackets; import com.google.inject.Inject; import com.google.inject.Provides; import net.runelite.api.ChatMessageType; import net.runelite.api.Client; import net.runelite.api.EquipmentInventorySlot; import net.runelite.api.InventoryID; import net.runelite.api.Item; import net.runelite.api.ItemID; import net.runelite.api.Player; import net.runelite.api.events.AnimationChanged; import net.runelite.api.events.GameTick; import net.runelite.api.widgets.Widget; import net.runelite.api.widgets.WidgetInfo; import net.runelite.client.config.ConfigManager; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.game.ItemManager; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDependency; import net.runelite.client.plugins.PluginDescriptor; import java.util.Optional; import java.util.Set; @PluginDescriptor( name = "AutoTele", enabledByDefault = false, tags = {"Hyps"} ) @PluginDependency(HypsApiPlugin.class) @PluginDependency(PacketUtilsPlugin.class) public class AutoTele extends Plugin { @Inject Client client; int timeout; static final int RING_OF_WEALTH = 714; static final int SEED_POD = 4544; int previousLevel = -1; public static boolean teleportedFromSkulledPlayer = false; @Inject ItemManager itemManager; @Inject AutoTeleConfig config; static final Set<Integer> RING_OF_WEALTH_ITEM_IDS = Set.of(ItemID.RING_OF_WEALTH_1, ItemID.RING_OF_WEALTH_2, ItemID.RING_OF_WEALTH_3, ItemID.RING_OF_WEALTH_4, ItemID.RING_OF_WEALTH_5, ItemID.RING_OF_WEALTH_I1, ItemID.RING_OF_WEALTH_I2, ItemID.RING_OF_WEALTH_I3, ItemID.RING_OF_WEALTH_I4, ItemID.RING_OF_WEALTH_I5); @Provides public AutoTeleConfig getConfig(ConfigManager configManager) { return configManager.getConfig(AutoTeleConfig.class); } @Subscribe public void onGameTick(GameTick event) { if (timeout > 0) { timeout--; return; } Widget wildernessLevel = client.getWidget(WidgetInfo.PVP_WILDERNESS_LEVEL); int level = -1; if (wildernessLevel != null && !wildernessLevel.getText().equals("")) { try { if (wildernessLevel.getText().contains("<br>")) { String text = wildernessLevel.getText().split("<br>")[0]; level = Integer.parseInt(text.replaceAll("Level: ", "")); } else { level = Integer.parseInt(wildernessLevel.getText().replaceAll("Level: ", "")); } } catch (NumberFormatException ex) { //ignore } } if (previousLevel != -1 && level == -1) { previousLevel = -1; } Item rowEquipment = null; if (client.getItemContainer(InventoryID.EQUIPMENT) != null) { rowEquipment = client.getItemContainer(InventoryID.EQUIPMENT).getItem(EquipmentInventorySlot.RING.getSlotIdx()); } if ((rowEquipment != null && !RING_OF_WEALTH_ITEM_IDS.contains(rowEquipment.getId()))) { rowEquipment = null; } if (level > -1) { if (previousLevel == -1) { previousLevel = level; Optional<Widget
> royal_seed_pod = Inventory.search().withId(ItemID.ROYAL_SEED_POD).first();
Optional<Widget> ring_of_wealth = Inventory.search().nameContains("Ring of wealth (").first(); if (config.alert()) { if (royal_seed_pod.isPresent() || ring_of_wealth.isPresent() || (rowEquipment != null && RING_OF_WEALTH_ITEM_IDS.contains(rowEquipment.getId()))) { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "<col=7cfc00>Entering wilderness with a teleport item." + " " + "AutoTele is ready to save you", null); } else { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "<col=ff0000> Entering wilderness without a " + "supported " + "teleport possible mistake?", null); } } } } for (Player player : client.getPlayers()) { int lowRange = client.getLocalPlayer().getCombatLevel() - level; int highRange = client.getLocalPlayer().getCombatLevel() + level; if (player.equals(client.getLocalPlayer())) { continue; } if (player.getCombatLevel() >= lowRange && player.getCombatLevel() <= highRange || !config.combatrange()) { // boolean hadMage = false; // boolean skippableWeapon = false; // if (config.mageFilter()) // { // int mageBonus = 0; // for (int equipmentId : player.getPlayerComposition().getEquipmentIds()) // { // if (equipmentId == -1) // { // continue; // } // if (equipmentId == 6512) // { // continue; // } // if (equipmentId >= 512) // { // return; // } // int realId = equipmentId - 512; // ItemEquipmentStats itemStats = itemManager.getItemStats(realId, false).getEquipment(); // if (itemStats == null) // { // continue; // } // mageBonus += itemStats.getAmagic(); // } // if (mageBonus > 0) // { // hadMage = true; // } // } // if (!config.weaponFilter().equals("")) // { // List<String> filteredWeapons = getFilteredWeapons(); // for (int equipment : player.getPlayerComposition().getEquipmentIds()) // { // int equipmentId = equipment - 512; // if (equipmentId > 0) // { // ItemComposition equipmentComp = itemManager.getItemComposition(equipmentId); // if (filteredWeapons.stream().anyMatch(item -> WildcardMatcher.matches(item.toLowerCase(), // Text.removeTags(equipmentComp.getName().toLowerCase())))) // { // skippableWeapon = true; // } // } // } // } // if (skippableWeapon) // { // if (!hadMage) // { // continue; // } // } boolean teleported = false; Optional<Widget> widget = Inventory.search().withId(ItemID.ROYAL_SEED_POD).first(); if (widget.isPresent()) { teleported = true; InventoryInteraction.useItem(widget.get(), "Commune"); } Optional<Widget> row = Inventory.search().nameContains("Ring of wealth (").first(); if (row.isPresent() && !teleported) { teleported = true; InventoryInteraction.useItem(row.get(), "Rub"); MousePackets.queueClickPacket(); WidgetPackets.queueResumePause(14352385, 2); } if (rowEquipment != null && !teleported) { teleported = true; MousePackets.queueClickPacket(); WidgetPackets.queueWidgetActionPacket(3, 25362456, -1, -1); } if (teleported) { teleportedFromSkulledPlayer = HypsApiPlugin.getSkullIcon(player) != null; if (teleportedFromSkulledPlayer) { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "Teleported from skulled player", null); } else { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "Teleported from non-skulled player", null); } } return; } } } // public List<String> getFilteredWeapons() // { // List<String> itemNames = new ArrayList<>(); // for (String s : config.weaponFilter().split(",")) // { // if (StringUtils.isNumeric(s)) // { // itemNames.add(Text.removeTags(itemManager.getItemComposition(Integer.parseInt(s)).getName())); // } // else // { // itemNames.add(s); // } // } // return itemNames; // } @Subscribe public void onAnimationChanged(AnimationChanged e) { Widget wildernessLevel = client.getWidget(WidgetInfo.PVP_WILDERNESS_LEVEL); int level = -1; if (wildernessLevel != null && !wildernessLevel.getText().equals("")) { try { if (wildernessLevel.getText().contains("<br>")) { String text = wildernessLevel.getText().split("<br>")[0]; level = Integer.parseInt(text.replaceAll("Level: ", "")); } else { level = Integer.parseInt(wildernessLevel.getText().replaceAll("Level: ", "")); } } catch (NumberFormatException ex) { //ignore } } if (level > -1) { if (e.getActor() == client.getLocalPlayer()) { int animation = client.getLocalPlayer().getAnimation(); if (animation == SEED_POD || animation == RING_OF_WEALTH) { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "timeout triggered", null); timeout = 10; } } } } }
src/main/java/com/utils/AutoTele/AutoTele.java
Hypsster-hUtils-d265b4f
[ { "filename": "src/main/java/com/utils/SpecDamage/specDamage.java", "retrieved_chunk": "\t\t}\n\t}\n\tprivate void drop()\n\t{\n\t\tOptional<Widget> fish = Inventory.search().idInList(List.of(371, 13441)).first();\n\t\tif (fish.isPresent())\n\t\t{\n\t\t\tWidgetPackets.queueWidgetAction(fish.get(), \"Eat\");\n\t\t}\n\t}", "score": 0.7896005511283875 }, { "filename": "src/main/java/com/utils/HypsApiPlugin/BankInventory.java", "retrieved_chunk": "\t\t\t\t\t\t\tArrays.stream(client.getWidget(WidgetInfo.BANK_INVENTORY_ITEMS_CONTAINER).getDynamicChildren()).filter(Objects::nonNull).filter(x -> x.getItemId() != 6512 && x.getItemId() != -1).collect(Collectors.toList());\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcatch (NullPointerException err)\n\t\t\t\t{\n\t\t\t\t\tBankInventory.bankIventoryItems.clear();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t}\n\t}", "score": 0.7891531586647034 }, { "filename": "src/main/java/com/utils/gauntletFlicker/gauntletFlicker.java", "retrieved_chunk": "\t\t\t{\n\t\t\t\tWidget staff = HypsApiPlugin.getItem(\"*staff*\");\n\t\t\t\tWidget bow = HypsApiPlugin.getItem(\"*bow*\");\n\t\t\t\tif (staff != null)\n\t\t\t\t{\n\t\t\t\t\tMousePackets.queueClickPacket();\n\t\t\t\t\tWidgetPackets.queueWidgetAction(staff, \"Wield\");\n\t\t\t\t\tupdatedWeapon = \"staff\";\n\t\t\t\t}\n\t\t\t\telse if (bow != null)", "score": 0.7886493802070618 }, { "filename": "src/main/java/com/utils/HypsApiPlugin/Equipment.java", "retrieved_chunk": "\t\tequipmentSlotWidgetMapping.put(13, 25);\n\t}\n\tpublic static EquipmentItemQuery search()\n\t{\n\t\treturn new EquipmentItemQuery(equipment);\n\t}\n\t@SneakyThrows\n\t@Subscribe\n\tpublic void onItemContainerChanged(ItemContainerChanged e)\n\t{", "score": 0.7870212197303772 }, { "filename": "src/main/java/com/utils/HypsApiPlugin/Equipment.java", "retrieved_chunk": "\t\tif (e.getContainerId() == InventoryID.EQUIPMENT.getId())\n\t\t{\n\t\t\tequipment.clear();\n\t\t\tint i = -1;\n\t\t\tfor (Item item : e.getItemContainer().getItems())\n\t\t\t{\n\t\t\t\ti++;\n\t\t\t\tif (item == null)\n\t\t\t\t{\n\t\t\t\t\tcontinue;", "score": 0.7807925939559937 } ]
java
> royal_seed_pod = Inventory.search().withId(ItemID.ROYAL_SEED_POD).first();
package com.blamejared.searchables.api.autcomplete; import com.blamejared.searchables.api.TokenRange; import com.blamejared.searchables.lang.StringSearcher; import com.blamejared.searchables.lang.expression.type.*; import com.blamejared.searchables.lang.expression.visitor.Visitor; import java.util.*; import java.util.function.Consumer; /** * Generates a list of TokenRanges that can be used to split a given string into parts. * Mainly used to split strings for completion purposes. */ public class CompletionVisitor implements Visitor<TokenRange>, Consumer<String> { private final List<TokenRange> tokens = new ArrayList<>(); private TokenRange lastRange = TokenRange.EMPTY; /** * Resets this visitor to a state that allows it to run again. */ public void reset() { tokens.clear(); lastRange = TokenRange.EMPTY; } /** * Reduces the tokens into their outermost parts. * For example the string {@code "shape:square color:red"} will be split into: * {@code [ * TokenRange(0, 12, [TokenRange(0, 5), TokenRange(5, 6), TokenRange(6, 12)]), * TokenRange(13, 22, [TokenRange(13, 18), TokenRange(18, 19), TokenRange(19, 22)]) * ]} */ protected void reduceTokens() { // Can this be done while visiting? ListIterator<TokenRange> iterator = tokens.listIterator(tokens.size()); TokenRange lastRange = null; while(iterator.hasPrevious()) { TokenRange previous = iterator.previous(); if(lastRange == null) { lastRange = previous; } else { if(
lastRange.covers(previous)) {
lastRange.addRange(previous); iterator.remove(); } else { lastRange = previous; } } } } /** * Gets the tokens in this visitor. * * @return The tokens in this visitor. */ public List<TokenRange> tokens() { return tokens; } /** * Gets the {@link Optional<TokenRange>} at the given position. * * @param position The current cursor position. * * @return An {@link Optional<TokenRange>} at the given position, or an empty optional if out of bounds. */ public Optional<TokenRange> tokenAt(final int position) { return tokens.stream() .filter(range -> range.contains(position)) .findFirst(); } /** * Gets the {@link TokenRange} at the given position, or {@link TokenRange#EMPTY} if out of bounds. * * @param position The current cursor position. * * @return An {@link TokenRange} at the given range, or {@link TokenRange#EMPTY} if out of bounds. */ public TokenRange rangeAt(final int position) { return tokenAt(position).orElse(TokenRange.EMPTY); } @Override public TokenRange visitGrouping(final GroupingExpression expr) { TokenRange leftRange = expr.left().accept(this); getAndPushRange(); TokenRange rightRange = expr.right().accept(this); return TokenRange.encompassing(leftRange, rightRange); } @Override public TokenRange visitComponent(final ComponentExpression expr) { TokenRange leftRange = expr.left().accept(this); addToken(getAndPushRange()); TokenRange rightRange = expr.right().accept(this); return addToken(TokenRange.encompassing(leftRange, rightRange)); } @Override public TokenRange visitLiteral(final LiteralExpression expr) { return addToken(getAndPushRange(expr.displayValue().length())); } @Override public TokenRange visitPaired(final PairedExpression expr) { TokenRange leftRange = addToken(expr.first().accept(this)); TokenRange rightRange = addToken(expr.second().accept(this)); return addToken(TokenRange.encompassing(leftRange, rightRange)); } private TokenRange addToken(final TokenRange range) { this.tokens.add(range.recalculate()); return range; } private TokenRange getAndPushRange() { return getAndPushRange(1); } private TokenRange getAndPushRange(final int end) { TokenRange oldRange = lastRange; lastRange = TokenRange.between(lastRange.end(), lastRange.end() + end); return TokenRange.between(oldRange.end(), oldRange.end() + end); } /** * Resets this visitor and compiles a list of {@link TokenRange} from the given String * * @param search The string to search */ @Override public void accept(final String search) { reset(); StringSearcher.search(search, this); } @Override public TokenRange postVisit(final TokenRange obj) { this.reduceTokens(); return Visitor.super.postVisit(obj); } }
common/src/main/java/com/blamejared/searchables/api/autcomplete/CompletionVisitor.java
jaredlll08-searchables-2cb19ff
[ { "filename": "common/src/main/java/com/blamejared/searchables/api/formatter/FormattingVisitor.java", "retrieved_chunk": " for(Pair<TokenRange, Style> token : tokens) {\n TokenRange range = token.getFirst();\n int subEnd = Math.max(range.start() - offset, 0);\n if(subEnd >= currentString.length()) {\n break;\n }\n int subStart = Math.min(range.end() - offset, currentString.length());\n if(subStart > 0) {\n sequences.add(FormattedCharSequence.forward(currentString.substring(index, subEnd), token.getSecond()));\n sequences.add(FormattedCharSequence.forward(currentString.substring(subEnd, subStart), token.getSecond()));", "score": 0.8170933723449707 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/formatter/FormattingVisitor.java", "retrieved_chunk": " /**\n * Resets this visitor to a state that allows it to run again.\n */\n public void reset() {\n tokens.clear();\n lastRange = TokenRange.at(0);\n }\n public List<Pair<TokenRange, Style>> tokens() {\n return tokens;\n }", "score": 0.815151035785675 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/TokenRange.java", "retrieved_chunk": " if(!this.contains(position)) {\n throw new IndexOutOfBoundsException();\n }\n int i = 0;\n for(TokenRange subRange : subRanges()) {\n if(!subRange.contains(position)) {\n i++;\n continue;\n }\n break;", "score": 0.8037464022636414 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/formatter/FormattingVisitor.java", "retrieved_chunk": " TokenRange rightRange = expr.second().accept(this, context);\n return TokenRange.encompassing(leftRange, rightRange);\n }\n private TokenRange getAndPushRange() {\n return getAndPushRange(1);\n }\n private TokenRange getAndPushRange(final int end) {\n TokenRange oldRange = lastRange;\n lastRange = TokenRange.between(lastRange.end(), lastRange.end() + end);\n return TokenRange.between(oldRange.end(), oldRange.end() + end);", "score": 0.7983046174049377 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/TokenRange.java", "retrieved_chunk": " return this;\n }\n int start = this.subRanges()\n .stream()\n .min(Comparator.comparing(TokenRange::end))\n .map(TokenRange::start)\n .orElse(this.start());\n int end = this.subRanges()\n .stream()\n .max(Comparator.comparing(TokenRange::end))", "score": 0.798027515411377 } ]
java
lastRange.covers(previous)) {
package com.blamejared.searchables.api.autcomplete; import com.blamejared.searchables.api.TokenRange; import com.blamejared.searchables.lang.StringSearcher; import com.blamejared.searchables.lang.expression.type.*; import com.blamejared.searchables.lang.expression.visitor.Visitor; import java.util.*; import java.util.function.Consumer; /** * Generates a list of TokenRanges that can be used to split a given string into parts. * Mainly used to split strings for completion purposes. */ public class CompletionVisitor implements Visitor<TokenRange>, Consumer<String> { private final List<TokenRange> tokens = new ArrayList<>(); private TokenRange lastRange = TokenRange.EMPTY; /** * Resets this visitor to a state that allows it to run again. */ public void reset() { tokens.clear(); lastRange = TokenRange.EMPTY; } /** * Reduces the tokens into their outermost parts. * For example the string {@code "shape:square color:red"} will be split into: * {@code [ * TokenRange(0, 12, [TokenRange(0, 5), TokenRange(5, 6), TokenRange(6, 12)]), * TokenRange(13, 22, [TokenRange(13, 18), TokenRange(18, 19), TokenRange(19, 22)]) * ]} */ protected void reduceTokens() { // Can this be done while visiting? ListIterator<TokenRange> iterator = tokens.listIterator(tokens.size()); TokenRange lastRange = null; while(iterator.hasPrevious()) { TokenRange previous = iterator.previous(); if(lastRange == null) { lastRange = previous; } else { if(lastRange.covers(previous)) {
lastRange.addRange(previous);
iterator.remove(); } else { lastRange = previous; } } } } /** * Gets the tokens in this visitor. * * @return The tokens in this visitor. */ public List<TokenRange> tokens() { return tokens; } /** * Gets the {@link Optional<TokenRange>} at the given position. * * @param position The current cursor position. * * @return An {@link Optional<TokenRange>} at the given position, or an empty optional if out of bounds. */ public Optional<TokenRange> tokenAt(final int position) { return tokens.stream() .filter(range -> range.contains(position)) .findFirst(); } /** * Gets the {@link TokenRange} at the given position, or {@link TokenRange#EMPTY} if out of bounds. * * @param position The current cursor position. * * @return An {@link TokenRange} at the given range, or {@link TokenRange#EMPTY} if out of bounds. */ public TokenRange rangeAt(final int position) { return tokenAt(position).orElse(TokenRange.EMPTY); } @Override public TokenRange visitGrouping(final GroupingExpression expr) { TokenRange leftRange = expr.left().accept(this); getAndPushRange(); TokenRange rightRange = expr.right().accept(this); return TokenRange.encompassing(leftRange, rightRange); } @Override public TokenRange visitComponent(final ComponentExpression expr) { TokenRange leftRange = expr.left().accept(this); addToken(getAndPushRange()); TokenRange rightRange = expr.right().accept(this); return addToken(TokenRange.encompassing(leftRange, rightRange)); } @Override public TokenRange visitLiteral(final LiteralExpression expr) { return addToken(getAndPushRange(expr.displayValue().length())); } @Override public TokenRange visitPaired(final PairedExpression expr) { TokenRange leftRange = addToken(expr.first().accept(this)); TokenRange rightRange = addToken(expr.second().accept(this)); return addToken(TokenRange.encompassing(leftRange, rightRange)); } private TokenRange addToken(final TokenRange range) { this.tokens.add(range.recalculate()); return range; } private TokenRange getAndPushRange() { return getAndPushRange(1); } private TokenRange getAndPushRange(final int end) { TokenRange oldRange = lastRange; lastRange = TokenRange.between(lastRange.end(), lastRange.end() + end); return TokenRange.between(oldRange.end(), oldRange.end() + end); } /** * Resets this visitor and compiles a list of {@link TokenRange} from the given String * * @param search The string to search */ @Override public void accept(final String search) { reset(); StringSearcher.search(search, this); } @Override public TokenRange postVisit(final TokenRange obj) { this.reduceTokens(); return Visitor.super.postVisit(obj); } }
common/src/main/java/com/blamejared/searchables/api/autcomplete/CompletionVisitor.java
jaredlll08-searchables-2cb19ff
[ { "filename": "common/src/main/java/com/blamejared/searchables/api/formatter/FormattingVisitor.java", "retrieved_chunk": " for(Pair<TokenRange, Style> token : tokens) {\n TokenRange range = token.getFirst();\n int subEnd = Math.max(range.start() - offset, 0);\n if(subEnd >= currentString.length()) {\n break;\n }\n int subStart = Math.min(range.end() - offset, currentString.length());\n if(subStart > 0) {\n sequences.add(FormattedCharSequence.forward(currentString.substring(index, subEnd), token.getSecond()));\n sequences.add(FormattedCharSequence.forward(currentString.substring(subEnd, subStart), token.getSecond()));", "score": 0.8308835625648499 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/formatter/FormattingVisitor.java", "retrieved_chunk": " TokenRange rightRange = expr.second().accept(this, context);\n return TokenRange.encompassing(leftRange, rightRange);\n }\n private TokenRange getAndPushRange() {\n return getAndPushRange(1);\n }\n private TokenRange getAndPushRange(final int end) {\n TokenRange oldRange = lastRange;\n lastRange = TokenRange.between(lastRange.end(), lastRange.end() + end);\n return TokenRange.between(oldRange.end(), oldRange.end() + end);", "score": 0.8113281726837158 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/formatter/FormattingVisitor.java", "retrieved_chunk": " /**\n * Resets this visitor to a state that allows it to run again.\n */\n public void reset() {\n tokens.clear();\n lastRange = TokenRange.at(0);\n }\n public List<Pair<TokenRange, Style>> tokens() {\n return tokens;\n }", "score": 0.8110952377319336 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/TokenRange.java", "retrieved_chunk": " if(!this.contains(position)) {\n throw new IndexOutOfBoundsException();\n }\n int i = 0;\n for(TokenRange subRange : subRanges()) {\n if(!subRange.contains(position)) {\n i++;\n continue;\n }\n break;", "score": 0.8009167909622192 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/formatter/FormattingVisitor.java", "retrieved_chunk": " .findFirst();\n }\n @Override\n public TokenRange visitGrouping(final GroupingExpression expr, final FormattingContext context) {\n TokenRange leftRange = expr.left().accept(this, context);\n tokens.add(Pair.of(getAndPushRange(), context.style()));\n TokenRange rightRange = expr.right().accept(this, context);\n return TokenRange.encompassing(leftRange, rightRange);\n }\n @Override", "score": 0.7957601547241211 } ]
java
lastRange.addRange(previous);
package com.blamejared.searchables.api.autcomplete; import com.blamejared.searchables.api.TokenRange; import com.blamejared.searchables.lang.StringSearcher; import com.blamejared.searchables.lang.expression.type.*; import com.blamejared.searchables.lang.expression.visitor.Visitor; import java.util.*; import java.util.function.Consumer; /** * Generates a list of TokenRanges that can be used to split a given string into parts. * Mainly used to split strings for completion purposes. */ public class CompletionVisitor implements Visitor<TokenRange>, Consumer<String> { private final List<TokenRange> tokens = new ArrayList<>(); private TokenRange lastRange = TokenRange.EMPTY; /** * Resets this visitor to a state that allows it to run again. */ public void reset() { tokens.clear(); lastRange = TokenRange.EMPTY; } /** * Reduces the tokens into their outermost parts. * For example the string {@code "shape:square color:red"} will be split into: * {@code [ * TokenRange(0, 12, [TokenRange(0, 5), TokenRange(5, 6), TokenRange(6, 12)]), * TokenRange(13, 22, [TokenRange(13, 18), TokenRange(18, 19), TokenRange(19, 22)]) * ]} */ protected void reduceTokens() { // Can this be done while visiting? ListIterator<TokenRange> iterator = tokens.listIterator(tokens.size()); TokenRange lastRange = null; while(iterator.hasPrevious()) { TokenRange previous = iterator.previous(); if(lastRange == null) { lastRange = previous; } else { if(lastRange.covers(previous)) { lastRange.addRange(previous); iterator.remove(); } else { lastRange = previous; } } } } /** * Gets the tokens in this visitor. * * @return The tokens in this visitor. */ public List<TokenRange> tokens() { return tokens; } /** * Gets the {@link Optional<TokenRange>} at the given position. * * @param position The current cursor position. * * @return An {@link Optional<TokenRange>} at the given position, or an empty optional if out of bounds. */ public Optional<TokenRange> tokenAt(final int position) { return tokens.stream() .filter(range -> range.contains(position)) .findFirst(); } /** * Gets the {@link TokenRange} at the given position, or {@link TokenRange#EMPTY} if out of bounds. * * @param position The current cursor position. * * @return An {@link TokenRange} at the given range, or {@link TokenRange#EMPTY} if out of bounds. */ public TokenRange rangeAt(final int position) { return tokenAt(position).orElse(TokenRange.EMPTY); } @Override public TokenRange visitGrouping(final GroupingExpression expr) { TokenRange leftRange = expr.left().accept(this); getAndPushRange(); TokenRange rightRange = expr.right().accept(this); return TokenRange.encompassing(leftRange, rightRange); } @Override public TokenRange visitComponent(final ComponentExpression expr) { TokenRange leftRange = expr.left().accept(this); addToken(getAndPushRange()); TokenRange rightRange = expr.right().accept(this); return addToken(TokenRange.encompassing(leftRange, rightRange)); } @Override public TokenRange visitLiteral(final LiteralExpression expr) { return addToken(getAndPushRange(expr.displayValue().length())); } @Override public TokenRange visitPaired(final PairedExpression expr) { TokenRange leftRange = addToken(expr.first().accept(this)); TokenRange rightRange = addToken(expr.second().accept(this)); return addToken(TokenRange.encompassing(leftRange, rightRange)); } private TokenRange addToken(final TokenRange range) { this.
tokens.add(range.recalculate());
return range; } private TokenRange getAndPushRange() { return getAndPushRange(1); } private TokenRange getAndPushRange(final int end) { TokenRange oldRange = lastRange; lastRange = TokenRange.between(lastRange.end(), lastRange.end() + end); return TokenRange.between(oldRange.end(), oldRange.end() + end); } /** * Resets this visitor and compiles a list of {@link TokenRange} from the given String * * @param search The string to search */ @Override public void accept(final String search) { reset(); StringSearcher.search(search, this); } @Override public TokenRange postVisit(final TokenRange obj) { this.reduceTokens(); return Visitor.super.postVisit(obj); } }
common/src/main/java/com/blamejared/searchables/api/autcomplete/CompletionVisitor.java
jaredlll08-searchables-2cb19ff
[ { "filename": "common/src/main/java/com/blamejared/searchables/api/formatter/FormattingVisitor.java", "retrieved_chunk": " if(!context.valid() || context.isKey() && !type.components().containsKey(expr.value())) {\n style = FormattingConstants.INVALID;\n }\n TokenRange range = getAndPushRange(expr.displayValue().length());\n tokens.add(Pair.of(range, style));\n return range;\n }\n @Override\n public TokenRange visitPaired(final PairedExpression expr, final FormattingContext context) {\n TokenRange leftRange = expr.first().accept(this, context);", "score": 0.9052649140357971 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/formatter/FormattingVisitor.java", "retrieved_chunk": " .findFirst();\n }\n @Override\n public TokenRange visitGrouping(final GroupingExpression expr, final FormattingContext context) {\n TokenRange leftRange = expr.left().accept(this, context);\n tokens.add(Pair.of(getAndPushRange(), context.style()));\n TokenRange rightRange = expr.right().accept(this, context);\n return TokenRange.encompassing(leftRange, rightRange);\n }\n @Override", "score": 0.892525315284729 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/context/ContextVisitor.java", "retrieved_chunk": " public SearchContext<T> visitPaired(final PairedExpression expr) {\n expr.first().accept(this);\n expr.second().accept(this);\n return context;\n }\n}", "score": 0.8864415884017944 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/formatter/FormattingVisitor.java", "retrieved_chunk": " TokenRange rightRange = expr.second().accept(this, context);\n return TokenRange.encompassing(leftRange, rightRange);\n }\n private TokenRange getAndPushRange() {\n return getAndPushRange(1);\n }\n private TokenRange getAndPushRange(final int end) {\n TokenRange oldRange = lastRange;\n lastRange = TokenRange.between(lastRange.end(), lastRange.end() + end);\n return TokenRange.between(oldRange.end(), oldRange.end() + end);", "score": 0.8795943260192871 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/formatter/FormattingVisitor.java", "retrieved_chunk": " public TokenRange visitComponent(final ComponentExpression expr, final FormattingContext context) {\n boolean valid = context.valid() && expr.left() instanceof LiteralExpression && expr.right() instanceof LiteralExpression;\n TokenRange leftRange = expr.left().accept(this, FormattingContext.key(FormattingConstants.KEY, valid));\n tokens.add(Pair.of(getAndPushRange(), context.style(valid)));\n TokenRange rightRange = expr.right().accept(this, FormattingContext.literal(FormattingConstants.TERM, valid));\n return TokenRange.encompassing(leftRange, rightRange);\n }\n @Override\n public TokenRange visitLiteral(final LiteralExpression expr, final FormattingContext context) {\n Style style = context.style();", "score": 0.8653874397277832 } ]
java
tokens.add(range.recalculate());
package com.blamejared.searchables.api.autcomplete; import com.blamejared.searchables.api.TokenRange; import com.blamejared.searchables.lang.StringSearcher; import com.blamejared.searchables.lang.expression.type.*; import com.blamejared.searchables.lang.expression.visitor.Visitor; import java.util.*; import java.util.function.Consumer; /** * Generates a list of TokenRanges that can be used to split a given string into parts. * Mainly used to split strings for completion purposes. */ public class CompletionVisitor implements Visitor<TokenRange>, Consumer<String> { private final List<TokenRange> tokens = new ArrayList<>(); private TokenRange lastRange = TokenRange.EMPTY; /** * Resets this visitor to a state that allows it to run again. */ public void reset() { tokens.clear(); lastRange = TokenRange.EMPTY; } /** * Reduces the tokens into their outermost parts. * For example the string {@code "shape:square color:red"} will be split into: * {@code [ * TokenRange(0, 12, [TokenRange(0, 5), TokenRange(5, 6), TokenRange(6, 12)]), * TokenRange(13, 22, [TokenRange(13, 18), TokenRange(18, 19), TokenRange(19, 22)]) * ]} */ protected void reduceTokens() { // Can this be done while visiting? ListIterator<TokenRange> iterator = tokens.listIterator(tokens.size()); TokenRange lastRange = null; while(iterator.hasPrevious()) { TokenRange previous = iterator.previous(); if(lastRange == null) { lastRange = previous; } else { if(lastRange.covers(previous)) { lastRange.addRange(previous); iterator.remove(); } else { lastRange = previous; } } } } /** * Gets the tokens in this visitor. * * @return The tokens in this visitor. */ public List<TokenRange> tokens() { return tokens; } /** * Gets the {@link Optional<TokenRange>} at the given position. * * @param position The current cursor position. * * @return An {@link Optional<TokenRange>} at the given position, or an empty optional if out of bounds. */ public Optional<TokenRange> tokenAt(final int position) { return tokens.stream() .filter(range -> range.contains(position)) .findFirst(); } /** * Gets the {@link TokenRange} at the given position, or {@link TokenRange#EMPTY} if out of bounds. * * @param position The current cursor position. * * @return An {@link TokenRange} at the given range, or {@link TokenRange#EMPTY} if out of bounds. */ public TokenRange rangeAt(final int position) { return tokenAt(position).orElse(TokenRange.EMPTY); } @Override public TokenRange visitGrouping(final GroupingExpression expr) { TokenRange leftRange = expr.left().accept(this); getAndPushRange(); TokenRange rightRange = expr.right().accept(this); return TokenRange.encompassing(leftRange, rightRange); } @Override public TokenRange visitComponent(final ComponentExpression expr) { TokenRange leftRange = expr.left().accept(this); addToken(getAndPushRange()); TokenRange rightRange = expr.right().accept(this); return addToken(TokenRange.encompassing(leftRange, rightRange)); } @Override public TokenRange visitLiteral(final LiteralExpression expr) { return addToken(getAndPushRange(expr.displayValue().length())); } @Override public TokenRange visitPaired(final PairedExpression expr) { TokenRange leftRange = addToken(expr.first().accept(this)); TokenRange rightRange = addToken(expr.second().accept(this)); return addToken(TokenRange.encompassing(leftRange, rightRange)); } private TokenRange addToken(final TokenRange range) { this.tokens.add(range.recalculate()); return range; } private TokenRange getAndPushRange() { return getAndPushRange(1); } private TokenRange getAndPushRange(final int end) { TokenRange oldRange = lastRange; lastRange = TokenRange.between(lastRange.end(), lastRange.end() + end); return TokenRange.between(oldRange.end(), oldRange.end() + end); } /** * Resets this visitor and compiles a list of {@link TokenRange} from the given String * * @param search The string to search */ @Override public void accept(final String search) { reset();
StringSearcher.search(search, this);
} @Override public TokenRange postVisit(final TokenRange obj) { this.reduceTokens(); return Visitor.super.postVisit(obj); } }
common/src/main/java/com/blamejared/searchables/api/autcomplete/CompletionVisitor.java
jaredlll08-searchables-2cb19ff
[ { "filename": "common/src/main/java/com/blamejared/searchables/api/formatter/FormattingVisitor.java", "retrieved_chunk": " }\n @Override\n public void accept(final String search) {\n reset();\n StringSearcher.search(search, this, FormattingContext.empty());\n }\n @Override\n public FormattedCharSequence apply(final String currentString, final Integer offset) {\n List<FormattedCharSequence> sequences = new ArrayList<>();\n int index = 0;", "score": 0.8858747482299805 }, { "filename": "common/src/main/java/com/blamejared/searchables/lang/StringSearcher.java", "retrieved_chunk": "package com.blamejared.searchables.lang;\nimport com.blamejared.searchables.lang.expression.Expression;\nimport com.blamejared.searchables.lang.expression.visitor.ContextAwareVisitor;\nimport com.blamejared.searchables.lang.expression.visitor.Visitor;\nimport java.util.Optional;\npublic class StringSearcher {\n /**\n * Parses the string and visits the given visitor.\n *\n * @param search The string to search.", "score": 0.8070403337478638 }, { "filename": "common/src/test/java/com/blamejared/searchables/tests/AutoCompleteTest.java", "retrieved_chunk": "package com.blamejared.searchables.tests;\nimport com.blamejared.searchables.TestConstants;\nimport com.blamejared.searchables.api.TokenRange;\nimport com.blamejared.searchables.api.autcomplete.CompletionSuggestion;\nimport com.blamejared.searchables.api.autcomplete.CompletionVisitor;\nimport com.blamejared.searchables.lang.StringSearcher;\nimport net.minecraft.network.chat.Component;\nimport org.junit.jupiter.api.Test;\nimport java.util.List;\nimport static org.hamcrest.MatcherAssert.assertThat;", "score": 0.7994141578674316 }, { "filename": "common/src/test/java/com/blamejared/searchables/tests/AutoCompleteTest.java", "retrieved_chunk": " }\n @Test\n public void testStringsTerm() {\n String search = \"type:`\";\n int position = 6;\n CompletionVisitor visitor = new CompletionVisitor();\n StringSearcher.search(search, visitor);\n TokenRange replacementRange = visitor.rangeAt(position);\n List<CompletionSuggestion> suggestions = TestConstants.SHAPE.getSuggestionsFor(TestConstants.SHAPES, search, position, replacementRange);\n assertThat(suggestions, hasSize(7));", "score": 0.7979850769042969 }, { "filename": "common/src/test/java/com/blamejared/searchables/tests/AutoCompleteTest.java", "retrieved_chunk": " CompletionVisitor visitor = new CompletionVisitor();\n StringSearcher.search(search, visitor);\n TokenRange replacementRange = visitor.rangeAt(position);\n List<CompletionSuggestion> suggestions = TestConstants.SHAPE.getSuggestionsFor(TestConstants.SHAPES, search, position, replacementRange);\n assertThat(suggestions, hasSize(1));\n assertThat(suggestions, contains(\n suggestion(\"name\", \"name\", \":\", 11, 16))\n );\n assertThat(suggestions.get(0).replaceIn(search), is(\"colour:red name: type:square\"));\n }", "score": 0.7978713512420654 } ]
java
StringSearcher.search(search, this);
package com.jessetzh.handler; import com.jessetzh.parameters.BasicParameter; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.DefaultProxyRoutePlanner; /** * Basic parameter validation. */ public class BasicParameterHandler { public static void check(BasicParameter basicParameter, HttpClientBuilder builder) { if (basicParameter.isAuthEnable()) { if (basicParameter.getUser() == null || basicParameter.getPassword() == null) { throw new StableDiffusionException("The username and password cannot be empty when authentication is enabled!"); } // Identity verification information CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(basicParameter.getUser(), basicParameter.getPassword()); provider.setCredentials(AuthScope.ANY, credentials); // Set CredentialsProvider object to HttpClientBuilder builder.setDefaultCredentialsProvider(provider); } if (basicParameter.isProxyEnable()) { if (basicParameter.getProxyHost() == null || basicParameter.getProxyPort() == 0) { throw new StableDiffusionException("When using a proxy server, please specify the proxy server address and port."); } // Access an API using a proxy server. builder.setRoutePlanner(new DefaultProxyRoutePlanner(new HttpHost(basicParameter.getProxyHost(), basicParameter.getProxyPort()))); } if (
basicParameter.getApiUrl() == null) {
throw new StableDiffusionException("API url can not be empty!"); } } }
src/main/java/com/jessetzh/handler/BasicParameterHandler.java
JesseTzh-stable-diffusion-java-20f5a07
[ { "filename": "src/main/java/com/jessetzh/parameters/BasicParameter.java", "retrieved_chunk": "package com.jessetzh.parameters;\npublic class BasicParameter {\n\tprivate String apiUrl;\n\tprivate boolean proxyEnable;\n\tprivate String proxyHost;\n\tprivate int proxyPort;\n\tprivate boolean authEnable;\n\tprivate String user;\n\tprivate String password;\n\tpublic String getApiUrl() {", "score": 0.8429099917411804 }, { "filename": "src/main/java/com/jessetzh/parameters/BasicParameter.java", "retrieved_chunk": "\t}\n\tpublic BasicParameter(String url) {\n\t\tthis.proxyEnable = false;\n\t\tthis.authEnable = false;\n\t\tif (url != null) {\n\t\t\tif ( url.endsWith(\"/\")) {\n\t\t\t\turl = url.substring(0, url.length() - 1);\n\t\t\t}\n\t\t}\n\t\tthis.apiUrl = url;", "score": 0.842401385307312 }, { "filename": "src/main/java/com/jessetzh/request/RequestExecutor.java", "retrieved_chunk": "\t\t\tSystem.err.println(\"Stable-Diffusion request error!\");\n\t\t\tthrow new StableDiffusionException(e.getMessage());\n\t\t} catch (IOException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t} finally {\n\t\t\tif (response != null) {\n\t\t\t\tresponse.close();\n\t\t\t}\n\t\t\tif (httpClient != null) {\n\t\t\t\thttpClient.close();", "score": 0.8017289638519287 }, { "filename": "src/main/java/com/jessetzh/handler/SdResHandler.java", "retrieved_chunk": " throw new StableDiffusionException(EntityUtils.toString(response.getEntity()));\n } else {\n throw new StableDiffusionException(\"Interface call error, please check if the URL is correct.\");\n }\n } else {\n if (response.getEntity() == null) {\n System.err.println(\"The result is empty!\");\n }\n }\n }", "score": 0.799493134021759 }, { "filename": "src/main/java/com/jessetzh/request/RequestExecutor.java", "retrieved_chunk": "\t\ttry {\n\t\t\thttpClient = builder.build();\n\t\t\tlong startTime = System.currentTimeMillis();\n\t\t\tresponse = httpClient.execute(httpPost);\n\t\t\tSystem.out.println(\"Request duration: \" + (System.currentTimeMillis() - startTime) + \"ms\");\n\t\t\t// Process the request result.\n\t\t\tSdResHandler.process(response);\n\t\t\tGson gson = new Gson();\n\t\t\tresponses = gson.fromJson(new InputStreamReader(response.getEntity().getContent()), SdResponses.class);\n\t\t} catch (StableDiffusionException e) {", "score": 0.7985079288482666 } ]
java
basicParameter.getApiUrl() == null) {
package com.utils.AutoTele; import com.utils.HypsApiPlugin.HypsApiPlugin; import com.utils.HypsApiPlugin.Inventory; import com.utils.InteractionApi.InventoryInteraction; import com.utils.PacketUtilsPlugin; import com.utils.Packets.MousePackets; import com.utils.Packets.WidgetPackets; import com.google.inject.Inject; import com.google.inject.Provides; import net.runelite.api.ChatMessageType; import net.runelite.api.Client; import net.runelite.api.EquipmentInventorySlot; import net.runelite.api.InventoryID; import net.runelite.api.Item; import net.runelite.api.ItemID; import net.runelite.api.Player; import net.runelite.api.events.AnimationChanged; import net.runelite.api.events.GameTick; import net.runelite.api.widgets.Widget; import net.runelite.api.widgets.WidgetInfo; import net.runelite.client.config.ConfigManager; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.game.ItemManager; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDependency; import net.runelite.client.plugins.PluginDescriptor; import java.util.Optional; import java.util.Set; @PluginDescriptor( name = "AutoTele", enabledByDefault = false, tags = {"Hyps"} ) @PluginDependency(HypsApiPlugin.class) @PluginDependency(PacketUtilsPlugin.class) public class AutoTele extends Plugin { @Inject Client client; int timeout; static final int RING_OF_WEALTH = 714; static final int SEED_POD = 4544; int previousLevel = -1; public static boolean teleportedFromSkulledPlayer = false; @Inject ItemManager itemManager; @Inject AutoTeleConfig config; static final Set<Integer> RING_OF_WEALTH_ITEM_IDS = Set.of(ItemID.RING_OF_WEALTH_1, ItemID.RING_OF_WEALTH_2, ItemID.RING_OF_WEALTH_3, ItemID.RING_OF_WEALTH_4, ItemID.RING_OF_WEALTH_5, ItemID.RING_OF_WEALTH_I1, ItemID.RING_OF_WEALTH_I2, ItemID.RING_OF_WEALTH_I3, ItemID.RING_OF_WEALTH_I4, ItemID.RING_OF_WEALTH_I5); @Provides public AutoTeleConfig getConfig(ConfigManager configManager) { return configManager.getConfig(AutoTeleConfig.class); } @Subscribe public void onGameTick(GameTick event) { if (timeout > 0) { timeout--; return; } Widget wildernessLevel = client.getWidget(WidgetInfo.PVP_WILDERNESS_LEVEL); int level = -1; if (wildernessLevel != null && !wildernessLevel.getText().equals("")) { try { if (wildernessLevel.getText().contains("<br>")) { String text = wildernessLevel.getText().split("<br>")[0]; level = Integer.parseInt(text.replaceAll("Level: ", "")); } else { level = Integer.parseInt(wildernessLevel.getText().replaceAll("Level: ", "")); } } catch (NumberFormatException ex) { //ignore } } if (previousLevel != -1 && level == -1) { previousLevel = -1; } Item rowEquipment = null; if (client.getItemContainer(InventoryID.EQUIPMENT) != null) { rowEquipment = client.getItemContainer(InventoryID.EQUIPMENT).getItem(EquipmentInventorySlot.RING.getSlotIdx()); } if ((rowEquipment != null && !RING_OF_WEALTH_ITEM_IDS.contains(rowEquipment.getId()))) { rowEquipment = null; } if (level > -1) { if (previousLevel == -1) { previousLevel = level; Optional<Widget> royal_seed_pod = Inventory.search().withId(ItemID.ROYAL_SEED_POD).first(); Optional<Widget> ring_of_wealth = Inventory.search().nameContains("Ring of wealth (").first(); if (config.alert()) { if (royal_seed_pod.isPresent() || ring_of_wealth.isPresent() || (rowEquipment != null && RING_OF_WEALTH_ITEM_IDS.contains(rowEquipment.getId()))) { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "<col=7cfc00>Entering wilderness with a teleport item." + " " + "AutoTele is ready to save you", null); } else { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "<col=ff0000> Entering wilderness without a " + "supported " + "teleport possible mistake?", null); } } } } for (Player player : client.getPlayers()) { int lowRange = client.getLocalPlayer().getCombatLevel() - level; int highRange = client.getLocalPlayer().getCombatLevel() + level; if (player.equals(client.getLocalPlayer())) { continue; } if (player.getCombatLevel() >= lowRange && player.getCombatLevel() <= highRange || !config.combatrange()) { // boolean hadMage = false; // boolean skippableWeapon = false; // if (config.mageFilter()) // { // int mageBonus = 0; // for (int equipmentId : player.getPlayerComposition().getEquipmentIds()) // { // if (equipmentId == -1) // { // continue; // } // if (equipmentId == 6512) // { // continue; // } // if (equipmentId >= 512) // { // return; // } // int realId = equipmentId - 512; // ItemEquipmentStats itemStats = itemManager.getItemStats(realId, false).getEquipment(); // if (itemStats == null) // { // continue; // } // mageBonus += itemStats.getAmagic(); // } // if (mageBonus > 0) // { // hadMage = true; // } // } // if (!config.weaponFilter().equals("")) // { // List<String> filteredWeapons = getFilteredWeapons(); // for (int equipment : player.getPlayerComposition().getEquipmentIds()) // { // int equipmentId = equipment - 512; // if (equipmentId > 0) // { // ItemComposition equipmentComp = itemManager.getItemComposition(equipmentId); // if (filteredWeapons.stream().anyMatch(item -> WildcardMatcher.matches(item.toLowerCase(), // Text.removeTags(equipmentComp.getName().toLowerCase())))) // { // skippableWeapon = true; // } // } // } // } // if (skippableWeapon) // { // if (!hadMage) // { // continue; // } // } boolean teleported = false; Optional<Widget
> widget = Inventory.search().withId(ItemID.ROYAL_SEED_POD).first();
if (widget.isPresent()) { teleported = true; InventoryInteraction.useItem(widget.get(), "Commune"); } Optional<Widget> row = Inventory.search().nameContains("Ring of wealth (").first(); if (row.isPresent() && !teleported) { teleported = true; InventoryInteraction.useItem(row.get(), "Rub"); MousePackets.queueClickPacket(); WidgetPackets.queueResumePause(14352385, 2); } if (rowEquipment != null && !teleported) { teleported = true; MousePackets.queueClickPacket(); WidgetPackets.queueWidgetActionPacket(3, 25362456, -1, -1); } if (teleported) { teleportedFromSkulledPlayer = HypsApiPlugin.getSkullIcon(player) != null; if (teleportedFromSkulledPlayer) { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "Teleported from skulled player", null); } else { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "Teleported from non-skulled player", null); } } return; } } } // public List<String> getFilteredWeapons() // { // List<String> itemNames = new ArrayList<>(); // for (String s : config.weaponFilter().split(",")) // { // if (StringUtils.isNumeric(s)) // { // itemNames.add(Text.removeTags(itemManager.getItemComposition(Integer.parseInt(s)).getName())); // } // else // { // itemNames.add(s); // } // } // return itemNames; // } @Subscribe public void onAnimationChanged(AnimationChanged e) { Widget wildernessLevel = client.getWidget(WidgetInfo.PVP_WILDERNESS_LEVEL); int level = -1; if (wildernessLevel != null && !wildernessLevel.getText().equals("")) { try { if (wildernessLevel.getText().contains("<br>")) { String text = wildernessLevel.getText().split("<br>")[0]; level = Integer.parseInt(text.replaceAll("Level: ", "")); } else { level = Integer.parseInt(wildernessLevel.getText().replaceAll("Level: ", "")); } } catch (NumberFormatException ex) { //ignore } } if (level > -1) { if (e.getActor() == client.getLocalPlayer()) { int animation = client.getLocalPlayer().getAnimation(); if (animation == SEED_POD || animation == RING_OF_WEALTH) { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "timeout triggered", null); timeout = 10; } } } } }
src/main/java/com/utils/AutoTele/AutoTele.java
Hypsster-hUtils-d265b4f
[ { "filename": "src/main/java/com/utils/HypsApiPlugin/BankInventory.java", "retrieved_chunk": "//\t\t\t\t//\t\t\t\t\t\t\tArrays.stream(client.getWidget(WidgetInfo.BANK_INVENTORY_ITEMS_CONTAINER).getDynamicChildren()).filter(Objects::nonNull).filter(x -> x.getItemId() != 6512 && x.getItemId() != -1).collect(Collectors.toList());\n//\t\t\t\t//\t\t\t\t\tbreak;\n//\t\t\t\t//\t\t\t\t}\n//\t\t\t\t//\t\t\t\tcatch (NullPointerException err)\n//\t\t\t\t//\t\t\t\t{\n//\t\t\t\t//\t\t\t\t\tBankInventory.bankIventoryItems.clear();\n//\t\t\t\t//\t\t\t\t\tbreak;\n//\t\t\t\t//\t\t\t\t}\n//\t\t}\n//\t}", "score": 0.8180049657821655 }, { "filename": "src/main/java/com/utils/gauntletFlicker/gauntletFlicker.java", "retrieved_chunk": "\t\t\t{\n\t\t\t\tWidget staff = HypsApiPlugin.getItem(\"*staff*\");\n\t\t\t\tWidget bow = HypsApiPlugin.getItem(\"*bow*\");\n\t\t\t\tif (staff != null)\n\t\t\t\t{\n\t\t\t\t\tMousePackets.queueClickPacket();\n\t\t\t\t\tWidgetPackets.queueWidgetAction(staff, \"Wield\");\n\t\t\t\t\tupdatedWeapon = \"staff\";\n\t\t\t\t}\n\t\t\t\telse if (bow != null)", "score": 0.8128286600112915 }, { "filename": "src/main/java/com/utils/HypsApiPlugin/BankInventory.java", "retrieved_chunk": "//\t\t\t\t\t\t}\n//\n//\t\t\t\t\t\tBankInventory.bankIventoryItems.add(new MinimalItemWidget(counter,\n//\t\t\t\t\t\t\t\tWidgetInfo.BANK_INVENTORY_ITEMS_CONTAINER.getPackedId(), item.getId(),\n//\t\t\t\t\t\t\t\ttempComp.getName(), item.getQuantity(), actions));\n//\t\t\t\t\t}\n//\t\t\t\t\tcatch (ExecutionException err)\n//\t\t\t\t\t{\n//\t\t\t\t\t\t// do nothing\n//\t\t\t\t\t}", "score": 0.8057606220245361 }, { "filename": "src/main/java/com/utils/HypsApiPlugin/Bank.java", "retrieved_chunk": "//\t\t\t\t\tif(item.getId() == 6512){\n//\t\t\t\t\t\tcounter++;\n//\t\t\t\t\t\tcontinue;\n//\t\t\t\t\t}\n//\t\t\t\t\tItemComposition tempComp = HypsApiPlugin.itemDefs.get(item.getId());\n//\t\t\t\t\tString withdrawCustom = \"Withdraw-\" + client.getVarbitValue(3960);\n//\t\t\t\t\tString[] actions = new String[]{\"\", \"Withdraw-1\", \"Withdraw-5\", \"Withdraw-10\", withdrawCustom, \"Withdraw-X\", \"Withdraw-All\", \"Withdraw-All-but-1\", null, \"Examine\"};\n//\t\t\t\t\tBank.bankItems.add(new MinimalItemWidget(counter,\n//\t\t\t\t\t\t\tWidgetInfo.BANK_ITEM_CONTAINER.getPackedId(), item.getId(),\n//\t\t\t\t\t\t\ttempComp.getName(), item.getQuantity(), actions));", "score": 0.8004381060600281 }, { "filename": "src/main/java/com/utils/gauntletFlicker/gauntletFlicker.java", "retrieved_chunk": "\t\t\telse if (weaponTesting.contains(\"staff\"))\n\t\t\t{\n\t\t\t\tif (auguryUnlucked() && !HypsApiPlugin.isQuickPrayerActive(QuickPrayer.AUGURY))\n\t\t\t\t{\n\t\t\t\t\tMousePackets.queueClickPacket();\n\t\t\t\t\tWidgetPackets.queueWidgetActionPacket(1, 5046276, -1, 27); //quickPrayer augury\n\t\t\t\t}\n\t\t\t\telse if (!auguryUnlucked() && !HypsApiPlugin.isQuickPrayerActive(QuickPrayer.MYSTIC_MIGHT))\n\t\t\t\t{\n\t\t\t\t\tMousePackets.queueClickPacket();", "score": 0.8004141449928284 } ]
java
> widget = Inventory.search().withId(ItemID.ROYAL_SEED_POD).first();
package org.chelonix.dagger.client.engineconn; import io.smallrye.graphql.client.dynamic.api.DynamicGraphQLClient; import io.smallrye.graphql.client.vertx.dynamic.VertxDynamicGraphQLClientBuilder; import io.vertx.core.Vertx; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.Optional; public final class Connection { static final Logger LOG = LoggerFactory.getLogger(Connection.class); private final DynamicGraphQLClient graphQLClient; private final Vertx vertx; private final Optional<CLIRunner> daggerRunner; Connection(DynamicGraphQLClient graphQLClient, Vertx vertx, Optional<CLIRunner> daggerRunner) { this.graphQLClient = graphQLClient; this.vertx = vertx; this.daggerRunner = daggerRunner; } public DynamicGraphQLClient getGraphQLClient() { return this.graphQLClient; } public void close() throws Exception { this.graphQLClient.close(); this.vertx.close(); this.daggerRunner.ifPresent(CLIRunner::shutdown); } static Optional<Connection> fromEnv() { LOG.info("Trying initializing connection with engine from environment variables..."); String portStr = System.getenv("DAGGER_SESSION_PORT"); String sessionToken = System.getenv("DAGGER_SESSION_TOKEN"); if (portStr != null && sessionToken != null) { try { int port = Integer.parseInt(portStr); return Optional.of(getConnection(port, sessionToken, Optional.empty())); } catch (NumberFormatException nfe) { LOG.error("invalid port value in DAGGER_SESSION_PORT", nfe); } } else if (portStr == null) { LOG.error("DAGGER_SESSION_TOKEN is required when using DAGGER_SESSION_PORT"); } else if (sessionToken == null) { LOG.error("DAGGER_SESSION_PORT is required when using DAGGER_SESSION_TOKEN"); } return Optional.empty(); } static Connection fromCLI(CLIRunner cliRunner) throws IOException { LOG.info("Trying initializing connection with engine from automatic provisioning..."); try {
cliRunner.start();
ConnectParams connectParams = cliRunner.getConnectionParams(); return getConnection(connectParams.getPort(), connectParams.getSessionToken(), Optional.of(cliRunner)); } catch (IOException ioe) { cliRunner.shutdown(); throw ioe; } } public static Connection get(String workingDir) throws IOException { return fromEnv().orElse(fromCLI(new CLIRunner(workingDir))); } private static Connection getConnection(int port, String token, Optional<CLIRunner> runner) { Vertx vertx = Vertx.vertx(); String encodedToken = Base64.getEncoder().encodeToString((token + ":").getBytes(StandardCharsets.UTF_8)); DynamicGraphQLClient dynamicGraphQLClient = new VertxDynamicGraphQLClientBuilder() .vertx(vertx) .url(String.format("http://127.0.0.1:%d/query", port)) .header("authorization", "Basic " + encodedToken) .build(); return new Connection(dynamicGraphQLClient, vertx, runner); } }
dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/Connection.java
jcsirot-dagger-java-sdk-366c947
[ { "filename": "dagger-java-sdk/src/test/java/org/chelonix/dagger/client/engineconn/ConnectionTest.java", "retrieved_chunk": " assertThat(conn).isPresent();\n }\n @Test\n public void should_return_empty_connection_when_env_not_set() throws Exception {\n Optional<Connection> conn;\n environmentVariables.set(\"DAGGER_SESSION_PORT\", null);\n environmentVariables.set(\"DAGGER_SESSION_TOKEN\", null);\n conn = Connection.fromEnv();\n assertThat(conn).isEmpty();\n environmentVariables.set(\"DAGGER_SESSION_PORT\", \"52037\");", "score": 0.8386408090591431 }, { "filename": "dagger-java-sdk/src/test/java/org/chelonix/dagger/client/engineconn/ConnectionTest.java", "retrieved_chunk": " environmentVariables.set(\"DAGGER_SESSION_TOKEN\", null);\n conn = Connection.fromEnv();\n assertThat(conn).isEmpty();\n environmentVariables.set(\"DAGGER_SESSION_PORT\", null);\n environmentVariables.set(\"DAGGER_SESSION_TOKEN\", \"189de95f-07df-415d-b42a-7851c731359d\");\n conn = Connection.fromEnv();\n assertThat(conn).isEmpty();\n }\n @Test\n public void should_return_connection_from_dynamic_provisioning() throws Exception {", "score": 0.8315936326980591 }, { "filename": "dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/CLIRunner.java", "retrieved_chunk": "import java.util.concurrent.Executors;\nclass CLIRunner implements Runnable {\n static final Logger LOG = LoggerFactory.getLogger(CLIRunner.class);\n private final FluentProcess process;\n private ConnectParams params;\n private boolean failed = false;\n private final ExecutorService executorService;\n private static String getCLIPath() throws IOException {\n String cliBinPath = System.getenv(\"_EXPERIMENTAL_DAGGER_CLI_BIN\");\n if (cliBinPath == null) {", "score": 0.8267541527748108 }, { "filename": "dagger-java-sdk/src/test/java/org/chelonix/dagger/client/engineconn/ConnectionTest.java", "retrieved_chunk": " CLIRunner runner = mock(CLIRunner.class);\n when(runner.getConnectionParams()).thenReturn(new ConnectParams(57535, \"6fb6d80b-5e7a-42f7-913c-31a6e50c140d\"));\n Connection conn = Connection.fromCLI(runner);\n verify(runner, times(1)).getConnectionParams();\n conn.close();\n verify(runner, times(1)).shutdown();\n }\n @Test\n public void should_fail_when_clirunner_fails() throws Exception {\n CLIRunner runner = mock(CLIRunner.class);", "score": 0.8256651163101196 }, { "filename": "dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/CLIRunner.java", "retrieved_chunk": " cliBinPath = new CLIDownloader().downloadCLI();\n }\n return cliBinPath;\n }\n public CLIRunner(String workingDir) throws IOException {\n String bin = getCLIPath();\n this.process = FluentProcess.start(bin, \"session\",\n \"--workdir\", workingDir,\n \"--label\", \"dagger.io/sdk.name:java\",\n \"--label\", \"dagger.io/sdk.version:\" + CLIDownloader.CLI_VERSION)", "score": 0.8232229948043823 } ]
java
cliRunner.start();
package org.chelonix.dagger.client.engineconn; import io.smallrye.graphql.client.dynamic.api.DynamicGraphQLClient; import io.smallrye.graphql.client.vertx.dynamic.VertxDynamicGraphQLClientBuilder; import io.vertx.core.Vertx; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.Optional; public final class Connection { static final Logger LOG = LoggerFactory.getLogger(Connection.class); private final DynamicGraphQLClient graphQLClient; private final Vertx vertx; private final Optional<CLIRunner> daggerRunner; Connection(DynamicGraphQLClient graphQLClient, Vertx vertx, Optional<CLIRunner> daggerRunner) { this.graphQLClient = graphQLClient; this.vertx = vertx; this.daggerRunner = daggerRunner; } public DynamicGraphQLClient getGraphQLClient() { return this.graphQLClient; } public void close() throws Exception { this.graphQLClient.close(); this.vertx.close(); this.daggerRunner.ifPresent(CLIRunner::shutdown); } static Optional<Connection> fromEnv() { LOG.info("Trying initializing connection with engine from environment variables..."); String portStr = System.getenv("DAGGER_SESSION_PORT"); String sessionToken = System.getenv("DAGGER_SESSION_TOKEN"); if (portStr != null && sessionToken != null) { try { int port = Integer.parseInt(portStr); return Optional.of(getConnection(port, sessionToken, Optional.empty())); } catch (NumberFormatException nfe) { LOG.error("invalid port value in DAGGER_SESSION_PORT", nfe); } } else if (portStr == null) { LOG.error("DAGGER_SESSION_TOKEN is required when using DAGGER_SESSION_PORT"); } else if (sessionToken == null) { LOG.error("DAGGER_SESSION_PORT is required when using DAGGER_SESSION_TOKEN"); } return Optional.empty(); } static Connection fromCLI(CLIRunner cliRunner) throws IOException { LOG.info("Trying initializing connection with engine from automatic provisioning..."); try { cliRunner.start(); ConnectParams
connectParams = cliRunner.getConnectionParams();
return getConnection(connectParams.getPort(), connectParams.getSessionToken(), Optional.of(cliRunner)); } catch (IOException ioe) { cliRunner.shutdown(); throw ioe; } } public static Connection get(String workingDir) throws IOException { return fromEnv().orElse(fromCLI(new CLIRunner(workingDir))); } private static Connection getConnection(int port, String token, Optional<CLIRunner> runner) { Vertx vertx = Vertx.vertx(); String encodedToken = Base64.getEncoder().encodeToString((token + ":").getBytes(StandardCharsets.UTF_8)); DynamicGraphQLClient dynamicGraphQLClient = new VertxDynamicGraphQLClientBuilder() .vertx(vertx) .url(String.format("http://127.0.0.1:%d/query", port)) .header("authorization", "Basic " + encodedToken) .build(); return new Connection(dynamicGraphQLClient, vertx, runner); } }
dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/Connection.java
jcsirot-dagger-java-sdk-366c947
[ { "filename": "dagger-java-sdk/src/test/java/org/chelonix/dagger/client/engineconn/ConnectionTest.java", "retrieved_chunk": " assertThat(conn).isPresent();\n }\n @Test\n public void should_return_empty_connection_when_env_not_set() throws Exception {\n Optional<Connection> conn;\n environmentVariables.set(\"DAGGER_SESSION_PORT\", null);\n environmentVariables.set(\"DAGGER_SESSION_TOKEN\", null);\n conn = Connection.fromEnv();\n assertThat(conn).isEmpty();\n environmentVariables.set(\"DAGGER_SESSION_PORT\", \"52037\");", "score": 0.8417214751243591 }, { "filename": "dagger-java-sdk/src/test/java/org/chelonix/dagger/client/engineconn/ConnectionTest.java", "retrieved_chunk": " CLIRunner runner = mock(CLIRunner.class);\n when(runner.getConnectionParams()).thenReturn(new ConnectParams(57535, \"6fb6d80b-5e7a-42f7-913c-31a6e50c140d\"));\n Connection conn = Connection.fromCLI(runner);\n verify(runner, times(1)).getConnectionParams();\n conn.close();\n verify(runner, times(1)).shutdown();\n }\n @Test\n public void should_fail_when_clirunner_fails() throws Exception {\n CLIRunner runner = mock(CLIRunner.class);", "score": 0.8397010564804077 }, { "filename": "dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/CLIRunner.java", "retrieved_chunk": "import java.util.concurrent.Executors;\nclass CLIRunner implements Runnable {\n static final Logger LOG = LoggerFactory.getLogger(CLIRunner.class);\n private final FluentProcess process;\n private ConnectParams params;\n private boolean failed = false;\n private final ExecutorService executorService;\n private static String getCLIPath() throws IOException {\n String cliBinPath = System.getenv(\"_EXPERIMENTAL_DAGGER_CLI_BIN\");\n if (cliBinPath == null) {", "score": 0.838977575302124 }, { "filename": "dagger-java-sdk/src/test/java/org/chelonix/dagger/client/engineconn/ConnectionTest.java", "retrieved_chunk": " environmentVariables.set(\"DAGGER_SESSION_TOKEN\", null);\n conn = Connection.fromEnv();\n assertThat(conn).isEmpty();\n environmentVariables.set(\"DAGGER_SESSION_PORT\", null);\n environmentVariables.set(\"DAGGER_SESSION_TOKEN\", \"189de95f-07df-415d-b42a-7851c731359d\");\n conn = Connection.fromEnv();\n assertThat(conn).isEmpty();\n }\n @Test\n public void should_return_connection_from_dynamic_provisioning() throws Exception {", "score": 0.8365499973297119 }, { "filename": "dagger-java-sdk/src/test/java/org/chelonix/dagger/client/engineconn/ConnectionTest.java", "retrieved_chunk": " when(runner.getConnectionParams()).thenThrow(new IOException(\"FAILED\"));\n assertThatThrownBy(() -> Connection.fromCLI(runner)).isInstanceOf(IOException.class).hasMessage(\"FAILED\");\n }\n}", "score": 0.8257200717926025 } ]
java
connectParams = cliRunner.getConnectionParams();
package com.jessetzh.test; import com.jessetzh.parameters.Img2ImgParameter; import com.jessetzh.parameters.SamplerEnums; import com.jessetzh.parameters.Text2ImgParameter; import com.jessetzh.request.Img2Img; import com.jessetzh.request.Text2Img; import com.jessetzh.res.SdResponses; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.math.BigDecimal; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Base64; /** * */ public class GeneratorTest { //支持直接使用 gradio.live WebUI 地址调用 static final String URL = "https://xxxxxxxxxxxxx.gradio.live/"; public static void main(String[] args) throws IOException { new GeneratorTest().img2imgTest(); } private void text2ImgText() throws IOException { Text2ImgParameter parameter = new Text2ImgParameter(URL); //如需要代理则解开下列代码注释 // parameter.getBasicParameter().setProxyEnable(true); // parameter.getBasicParameter().setProxyHost("127.0.0.1"); // parameter.getBasicParameter().setProxyPort(7890); parameter.setPrompt("One Golden Retriever"); SdResponses res = Text2Img.generate(parameter); for (String image : res.getImages()) { BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(Base64.getDecoder().decode(image))); File output = new File("image.png"); ImageIO.write(bufferedImage, "png", output); } } private void img2imgTest() throws IOException { Img2ImgParameter parameter = new Img2ImgParameter(URL); //重绘幅度 parameter.setDenoisingStrength(new BigDecimal("0.55")); parameter.setSeed(-1); parameter.setSteps(30); parameter.setCfgScale(7); parameter.setWidth(512); parameter.setHeight(512); parameter.setSamplerName(SamplerEnums.DPM_2M_Karras.getInfo()); Path path = Paths.get("test.jpeg"); byte[] bytes = Files.readAllBytes(path); Base64.Encoder encoder = Base64.getEncoder(); String base64String = encoder.encodeToString(bytes);
parameter.setInit_images(new String[]{
base64String}); parameter.setPrompt("dog"); parameter.setNegativePrompt("cat"); SdResponses res = Img2Img.generate(parameter); for (String image : res.getImages()) { BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(Base64.getDecoder().decode(image))); File output = new File("image.png"); ImageIO.write(bufferedImage, "png", output); System.out.println(res.getInfo()); } } }
src/main/java/com/jessetzh/test/GeneratorTest.java
JesseTzh-stable-diffusion-java-20f5a07
[ { "filename": "src/main/java/com/jessetzh/request/Img2Img.java", "retrieved_chunk": "public class Img2Img {\n\tprivate static final String API_PATH = \"/sdapi/v1/img2img\";\n\tpublic static SdResponses generate(Img2ImgParameter parameter) throws IOException {\n\t\tHttpClientBuilder builder = HttpClients.custom();\n\t\tBasicParameterHandler.check(parameter.getBasicParameter(), builder);\n\t\tparameter.getBasicParameter().setApiUrl(parameter.getBasicParameter().getApiUrl() + API_PATH);\n\t\tHttpPost httpPost = new HttpPost(parameter.getBasicParameter().getApiUrl());\n\t\tStringEntity entity = new StringEntity(new GsonBuilder().create().toJson(parameter));\n\t\treturn RequestExecutor.execute(builder, entity, httpPost);\n\t}", "score": 0.8191227912902832 }, { "filename": "src/main/java/com/jessetzh/request/Text2Img.java", "retrieved_chunk": "public class Text2Img {\n\tprivate static final String API_PATH = \"/sdapi/v1/img2img\";\n\tpublic static SdResponses generate(Text2ImgParameter parameter) throws IOException {\n\t\tHttpClientBuilder builder = HttpClients.custom();\n\t\tBasicParameterHandler.check(parameter.getBasicParameter(), builder);\n\t\tparameter.getBasicParameter().setApiUrl(parameter.getBasicParameter().getApiUrl() + API_PATH);\n\t\tHttpPost httpPost = new HttpPost(parameter.getBasicParameter().getApiUrl());\n\t\tStringEntity entity = new StringEntity(new GsonBuilder().create().toJson(parameter));\n\t\treturn RequestExecutor.execute(builder, entity, httpPost);\n\t}", "score": 0.8105350732803345 }, { "filename": "src/main/java/com/jessetzh/parameters/Img2ImgParameter.java", "retrieved_chunk": "package com.jessetzh.parameters;\nimport com.google.gson.annotations.SerializedName;\nimport java.math.BigDecimal;\npublic class Img2ImgParameter extends SdParameter {\n String[] init_images;\n @SerializedName(\"denoising_strength\")\n private BigDecimal denoisingStrength;\n public BigDecimal getDenoisingStrength() {\n return denoisingStrength;\n }", "score": 0.8020915985107422 }, { "filename": "src/main/java/com/jessetzh/parameters/SdParameter.java", "retrieved_chunk": "package com.jessetzh.parameters;\nimport com.google.gson.annotations.SerializedName;\nimport java.math.BigDecimal;\npublic class SdParameter {\n\tprivate transient BasicParameter basicParameter;\n\tprivate String prompt;\n\t@SerializedName(\"negative_prompt\")\n\tprivate String negativePrompt;\n\tprivate int steps;\n\t@SerializedName(\"resize_mode\")", "score": 0.801550030708313 }, { "filename": "src/main/java/com/jessetzh/parameters/Img2ImgParameter.java", "retrieved_chunk": " public void setDenoisingStrength(BigDecimal denoisingStrength) {\n this.denoisingStrength = denoisingStrength;\n }\n public String[] getInit_images() {\n return init_images;\n }\n public void setInit_images(String[] init_images) {\n this.init_images = init_images;\n }\n public Img2ImgParameter() {", "score": 0.8014605045318604 } ]
java
parameter.setInit_images(new String[]{
package com.jessetzh.test; import com.jessetzh.parameters.Img2ImgParameter; import com.jessetzh.parameters.SamplerEnums; import com.jessetzh.parameters.Text2ImgParameter; import com.jessetzh.request.Img2Img; import com.jessetzh.request.Text2Img; import com.jessetzh.res.SdResponses; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.math.BigDecimal; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Base64; /** * */ public class GeneratorTest { //支持直接使用 gradio.live WebUI 地址调用 static final String URL = "https://xxxxxxxxxxxxx.gradio.live/"; public static void main(String[] args) throws IOException { new GeneratorTest().img2imgTest(); } private void text2ImgText() throws IOException { Text2ImgParameter parameter = new Text2ImgParameter(URL); //如需要代理则解开下列代码注释 // parameter.getBasicParameter().setProxyEnable(true); // parameter.getBasicParameter().setProxyHost("127.0.0.1"); // parameter.getBasicParameter().setProxyPort(7890); parameter.setPrompt("One Golden Retriever"); SdResponses res = Text2Img.generate(parameter); for (String image : res.getImages()) { BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(Base64.getDecoder().decode(image))); File output = new File("image.png"); ImageIO.write(bufferedImage, "png", output); } } private void img2imgTest() throws IOException { Img2ImgParameter parameter = new Img2ImgParameter(URL); //重绘幅度
parameter.setDenoisingStrength(new BigDecimal("0.55"));
parameter.setSeed(-1); parameter.setSteps(30); parameter.setCfgScale(7); parameter.setWidth(512); parameter.setHeight(512); parameter.setSamplerName(SamplerEnums.DPM_2M_Karras.getInfo()); Path path = Paths.get("test.jpeg"); byte[] bytes = Files.readAllBytes(path); Base64.Encoder encoder = Base64.getEncoder(); String base64String = encoder.encodeToString(bytes); parameter.setInit_images(new String[]{base64String}); parameter.setPrompt("dog"); parameter.setNegativePrompt("cat"); SdResponses res = Img2Img.generate(parameter); for (String image : res.getImages()) { BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(Base64.getDecoder().decode(image))); File output = new File("image.png"); ImageIO.write(bufferedImage, "png", output); System.out.println(res.getInfo()); } } }
src/main/java/com/jessetzh/test/GeneratorTest.java
JesseTzh-stable-diffusion-java-20f5a07
[ { "filename": "src/main/java/com/jessetzh/request/Img2Img.java", "retrieved_chunk": "public class Img2Img {\n\tprivate static final String API_PATH = \"/sdapi/v1/img2img\";\n\tpublic static SdResponses generate(Img2ImgParameter parameter) throws IOException {\n\t\tHttpClientBuilder builder = HttpClients.custom();\n\t\tBasicParameterHandler.check(parameter.getBasicParameter(), builder);\n\t\tparameter.getBasicParameter().setApiUrl(parameter.getBasicParameter().getApiUrl() + API_PATH);\n\t\tHttpPost httpPost = new HttpPost(parameter.getBasicParameter().getApiUrl());\n\t\tStringEntity entity = new StringEntity(new GsonBuilder().create().toJson(parameter));\n\t\treturn RequestExecutor.execute(builder, entity, httpPost);\n\t}", "score": 0.8722559809684753 }, { "filename": "src/main/java/com/jessetzh/request/Text2Img.java", "retrieved_chunk": "public class Text2Img {\n\tprivate static final String API_PATH = \"/sdapi/v1/img2img\";\n\tpublic static SdResponses generate(Text2ImgParameter parameter) throws IOException {\n\t\tHttpClientBuilder builder = HttpClients.custom();\n\t\tBasicParameterHandler.check(parameter.getBasicParameter(), builder);\n\t\tparameter.getBasicParameter().setApiUrl(parameter.getBasicParameter().getApiUrl() + API_PATH);\n\t\tHttpPost httpPost = new HttpPost(parameter.getBasicParameter().getApiUrl());\n\t\tStringEntity entity = new StringEntity(new GsonBuilder().create().toJson(parameter));\n\t\treturn RequestExecutor.execute(builder, entity, httpPost);\n\t}", "score": 0.8576874732971191 }, { "filename": "src/main/java/com/jessetzh/request/Img2Img.java", "retrieved_chunk": "package com.jessetzh.request;\nimport com.google.gson.GsonBuilder;\nimport com.jessetzh.handler.BasicParameterHandler;\nimport com.jessetzh.parameters.Img2ImgParameter;\nimport com.jessetzh.res.SdResponses;\nimport org.apache.http.client.methods.HttpPost;\nimport org.apache.http.entity.StringEntity;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.impl.client.HttpClients;\nimport java.io.IOException;", "score": 0.8309482336044312 }, { "filename": "src/main/java/com/jessetzh/parameters/Img2ImgParameter.java", "retrieved_chunk": "package com.jessetzh.parameters;\nimport com.google.gson.annotations.SerializedName;\nimport java.math.BigDecimal;\npublic class Img2ImgParameter extends SdParameter {\n String[] init_images;\n @SerializedName(\"denoising_strength\")\n private BigDecimal denoisingStrength;\n public BigDecimal getDenoisingStrength() {\n return denoisingStrength;\n }", "score": 0.8207866549491882 }, { "filename": "src/main/java/com/jessetzh/parameters/Img2ImgParameter.java", "retrieved_chunk": " public void setDenoisingStrength(BigDecimal denoisingStrength) {\n this.denoisingStrength = denoisingStrength;\n }\n public String[] getInit_images() {\n return init_images;\n }\n public void setInit_images(String[] init_images) {\n this.init_images = init_images;\n }\n public Img2ImgParameter() {", "score": 0.8184231519699097 } ]
java
parameter.setDenoisingStrength(new BigDecimal("0.55"));
package org.chelonix.dagger.client.engineconn; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveInputStream; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; import org.freedesktop.BaseDirectory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.HexFormat; import java.util.Map; class CLIDownloader { static final Logger LOG = LoggerFactory.getLogger(CLIDownloader.class); private static final File CACHE_DIR = Paths.get(BaseDirectory.get(BaseDirectory.XDG_CACHE_HOME), "dagger").toFile(); public static final String CLI_VERSION = "0.6.2"; private static final String DAGGER_CLI_BIN_PREFIX = "dagger-"; private final FileFetcher fetcher; public CLIDownloader(FileFetcher fetcher) { this.fetcher = fetcher; } public CLIDownloader() { this(url -> new URL(url).openStream()); } public String downloadCLI(String version) throws IOException { CACHE_DIR.mkdirs(); CACHE_DIR.setExecutable(true, true); CACHE_DIR.setReadable(true, true); CACHE_DIR.setWritable(true, true); String binName = DAGGER_CLI_BIN_PREFIX + version; if (isWindows()) { binName += ".exe"; } Path binPath = Paths.get(CACHE_DIR.getPath(), binName); if (!binPath.toFile().exists()) { downloadCLI(version, binPath); } return binPath.toString(); } public String downloadCLI() throws IOException { return downloadCLI(CLI_VERSION); } private void downloadCLI(String version, Path binPath) throws IOException { String binName = binPath.getFileName().toString(); Path tmpBin = Files.createTempFile(CACHE_DIR.toPath(), "tmp-" + binName, null); try { String archiveName = getDefaultCLIArchiveName(version); String expectedChecksum = expectedChecksum(version, archiveName); if (expectedChecksum == null) { throw new IOException("Could not find checksum for " + archiveName); } String actualChecksum = extractCLI(archiveName, version, tmpBin); if (!actualChecksum.equals(expectedChecksum)) { throw new IOException("Checksum validation failed"); } tmpBin.toFile().setExecutable(true); Files.move(tmpBin, binPath); } finally { Files.deleteIfExists(tmpBin); } } private String expectedChecksum(String version, String archiveName) throws IOException { Map<String, String> checksums = fetchChecksumMap(version); return checksums.get(archiveName); } private String getDefaultCLIArchiveName(String version) { String ext = isWindows() ? "zip" : "tar.gz"; return String.format("dagger_v%s_%s_%s.%s", version, getOS(), getArch(), ext); } private Map<String, String> fetchChecksumMap(String version) throws IOException { Map<String, String> checksums = new HashMap<>(); String checksumMapURL = String.format("https://dl.dagger.io/dagger/releases/%s/checksums.txt", version); try
(BufferedInputStream in = new BufferedInputStream(fetcher.fetch(checksumMapURL))) {
ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] dataBuffer = new byte[1024]; int bytesRead; while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) { out.write(dataBuffer, 0, bytesRead); } BufferedReader reader = new BufferedReader(new StringReader(out.toString(StandardCharsets.UTF_8))); String line; while ((line = reader.readLine()) != null) { String[] arr = line.split("\\s+"); checksums.put(arr[1], arr[0]); } return checksums; } } private String extractCLI(String archiveName, String version, Path dest) throws IOException { String cliArchiveURL = String.format("https://dl.dagger.io/dagger/releases/%s/%s", version, archiveName); LOG.info("Downloading Dagger CLI from " + cliArchiveURL); MessageDigest sha256; try { sha256 = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException nsae) { throw new IOException("Could not instantiate SHA-256 digester", nsae); } LOG.info("Extracting archive..."); try (InputStream in = new BufferedInputStream(new DigestInputStream(fetcher.fetch(cliArchiveURL), sha256))) { if (isWindows()) { extractZip(in, dest); } else { extractTarGZ(in, dest); } byte[] checksum = sha256.digest(); return HexFormat.of().formatHex(checksum); } } private void extractZip(InputStream in, Path dest) throws IOException { try (ZipArchiveInputStream zipIn = new ZipArchiveInputStream(in)) { extractCLIBin(zipIn, "dagger.exe", dest); } } private static void extractCLIBin(ArchiveInputStream in, String binName, Path dest) throws IOException { boolean found = false; ArchiveEntry entry; while ((entry = in.getNextEntry()) != null) { if (entry.isDirectory() || !binName.equals(entry.getName())) { continue; } int count; byte[] data = new byte[4096]; FileOutputStream fos = new FileOutputStream(dest.toFile()); try (BufferedOutputStream out = new BufferedOutputStream(fos, 4096)) { while ((count = in.read(data, 0, 4096)) != -1) { out.write(data, 0, count); } } found = true; break; } if (!found) { throw new IOException("Could not find dagger binary in CLI archive"); } } private void extractTarGZ(InputStream in, Path dest) throws IOException { boolean found = false; try (GzipCompressorInputStream gzipIn = new GzipCompressorInputStream(in); TarArchiveInputStream tarIn = new TarArchiveInputStream(gzipIn)) { extractCLIBin(tarIn, "dagger", dest); } } private static boolean isWindows() { return System.getProperty("os.name").toLowerCase().contains("win"); } private static String getOS() { String os = System.getProperty("os.name").toLowerCase(); if (os.contains("win")) { return "windows"; } else if (os.contains("linux")) { return "linux"; } else if (os.contains("darwin") || os.contains("mac")) { return "darwin"; } else { return "unknown"; } } private static String getArch() { String arch = System.getProperty("os.arch").toLowerCase(); if (arch.contains("x86_64") || arch.contains("amd64")) { return "amd64"; } else if (arch.contains("x86")) { return "x86"; } else if (arch.contains("arm")) { return "armv7"; } else if (arch.contains("aarch64")) { return "arm64"; } else { return "unknown"; } } }
dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/CLIDownloader.java
jcsirot-dagger-java-sdk-366c947
[ { "filename": "dagger-java-samples/src/main/java/org/chelonix/dagger/sample/GetGitVersion.java", "retrieved_chunk": "package org.chelonix.dagger.sample;\nimport org.chelonix.dagger.client.*;\nimport java.util.List;\npublic class GetGitVersion {\n public static void main(String... args) throws Exception {\n try(Client client = Dagger.connect()) {\n Directory dir = client.git(\"https://github.com/dagger/dagger\").tag(\"v0.6.2\").tree();\n Container daggerImg = client.container().build(dir);\n String stdout = daggerImg.withExec(List.of(\"version\")).stdout();\n System.out.println(stdout);", "score": 0.821134090423584 }, { "filename": "dagger-codegen-maven-plugin/src/main/java/org/chelonix/dagger/codegen/DaggerCodegenMojo.java", "retrieved_chunk": " } else if (introspectionQuertyURL == null) {\n in = new URL(String.format(\"https://raw.githubusercontent.com/dagger/dagger/v%s/codegen/introspection/introspection.graphql\", version)).openStream();\n } else if (introspectionQuertyURL != null) {\n in = new URL(introspectionQuertyURL).openStream();\n } else {\n throw new MojoFailureException(\"Could not locate, download or generate GraphQL schema\");\n }\n ByteArrayOutputStream out = new ByteArrayOutputStream();\n FluentProcess.start(bin, \"query\")\n .withTimeout(Duration.of(60, ChronoUnit.SECONDS))", "score": 0.8072750568389893 }, { "filename": "dagger-codegen-maven-plugin/src/main/java/org/chelonix/dagger/codegen/DaggerCodegenMojo.java", "retrieved_chunk": " }\n if (project != null) {\n // Tell Maven that there are some new source files underneath the output directory.\n project.addCompileSourceRoot(getOutputDirectory().getPath());\n }\n }\n private InputStream daggerSchema() throws IOException, InterruptedException, MojoFailureException {\n if (!online) {\n InputStream in = getClass().getClassLoader().getResourceAsStream(String.format(\"schemas/schema-v%s.json\", version));\n if (in == null) {", "score": 0.7934097051620483 }, { "filename": "dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/CLIRunner.java", "retrieved_chunk": " cliBinPath = new CLIDownloader().downloadCLI();\n }\n return cliBinPath;\n }\n public CLIRunner(String workingDir) throws IOException {\n String bin = getCLIPath();\n this.process = FluentProcess.start(bin, \"session\",\n \"--workdir\", workingDir,\n \"--label\", \"dagger.io/sdk.name:java\",\n \"--label\", \"dagger.io/sdk.version:\" + CLIDownloader.CLI_VERSION)", "score": 0.7927656173706055 }, { "filename": "dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/FileFetcher.java", "retrieved_chunk": "package org.chelonix.dagger.client.engineconn;\nimport java.io.IOException;\nimport java.io.InputStream;\n@FunctionalInterface\ninterface FileFetcher {\n InputStream fetch(String url) throws IOException;\n}", "score": 0.7894890308380127 } ]
java
(BufferedInputStream in = new BufferedInputStream(fetcher.fetch(checksumMapURL))) {
package com.utils.AutoTele; import com.utils.HypsApiPlugin.HypsApiPlugin; import com.utils.HypsApiPlugin.Inventory; import com.utils.InteractionApi.InventoryInteraction; import com.utils.PacketUtilsPlugin; import com.utils.Packets.MousePackets; import com.utils.Packets.WidgetPackets; import com.google.inject.Inject; import com.google.inject.Provides; import net.runelite.api.ChatMessageType; import net.runelite.api.Client; import net.runelite.api.EquipmentInventorySlot; import net.runelite.api.InventoryID; import net.runelite.api.Item; import net.runelite.api.ItemID; import net.runelite.api.Player; import net.runelite.api.events.AnimationChanged; import net.runelite.api.events.GameTick; import net.runelite.api.widgets.Widget; import net.runelite.api.widgets.WidgetInfo; import net.runelite.client.config.ConfigManager; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.game.ItemManager; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDependency; import net.runelite.client.plugins.PluginDescriptor; import java.util.Optional; import java.util.Set; @PluginDescriptor( name = "AutoTele", enabledByDefault = false, tags = {"Hyps"} ) @PluginDependency(HypsApiPlugin.class) @PluginDependency(PacketUtilsPlugin.class) public class AutoTele extends Plugin { @Inject Client client; int timeout; static final int RING_OF_WEALTH = 714; static final int SEED_POD = 4544; int previousLevel = -1; public static boolean teleportedFromSkulledPlayer = false; @Inject ItemManager itemManager; @Inject AutoTeleConfig config; static final Set<Integer> RING_OF_WEALTH_ITEM_IDS = Set.of(ItemID.RING_OF_WEALTH_1, ItemID.RING_OF_WEALTH_2, ItemID.RING_OF_WEALTH_3, ItemID.RING_OF_WEALTH_4, ItemID.RING_OF_WEALTH_5, ItemID.RING_OF_WEALTH_I1, ItemID.RING_OF_WEALTH_I2, ItemID.RING_OF_WEALTH_I3, ItemID.RING_OF_WEALTH_I4, ItemID.RING_OF_WEALTH_I5); @Provides public AutoTeleConfig getConfig(ConfigManager configManager) { return configManager.getConfig(AutoTeleConfig.class); } @Subscribe public void onGameTick(GameTick event) { if (timeout > 0) { timeout--; return; } Widget wildernessLevel = client.getWidget(WidgetInfo.PVP_WILDERNESS_LEVEL); int level = -1; if (wildernessLevel != null && !wildernessLevel.getText().equals("")) { try { if (wildernessLevel.getText().contains("<br>")) { String text = wildernessLevel.getText().split("<br>")[0]; level = Integer.parseInt(text.replaceAll("Level: ", "")); } else { level = Integer.parseInt(wildernessLevel.getText().replaceAll("Level: ", "")); } } catch (NumberFormatException ex) { //ignore } } if (previousLevel != -1 && level == -1) { previousLevel = -1; } Item rowEquipment = null; if (client.getItemContainer(InventoryID.EQUIPMENT) != null) { rowEquipment = client.getItemContainer(InventoryID.EQUIPMENT).getItem(EquipmentInventorySlot.RING.getSlotIdx()); } if ((rowEquipment != null && !RING_OF_WEALTH_ITEM_IDS.contains(rowEquipment.getId()))) { rowEquipment = null; } if (level > -1) { if (previousLevel == -1) { previousLevel = level; Optional<Widget> royal_seed_pod = Inventory.search().withId(ItemID.ROYAL_SEED_POD).first(); Optional<Widget> ring_of_wealth = Inventory.search().nameContains("Ring of wealth (").first(); if (config.alert()) { if (royal_seed_pod.isPresent() || ring_of_wealth.isPresent() || (rowEquipment != null && RING_OF_WEALTH_ITEM_IDS.contains(rowEquipment.getId()))) { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "<col=7cfc00>Entering wilderness with a teleport item." + " " + "AutoTele is ready to save you", null); } else { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "<col=ff0000> Entering wilderness without a " + "supported " + "teleport possible mistake?", null); } } } } for (Player player : client.getPlayers()) { int lowRange = client.getLocalPlayer().getCombatLevel() - level; int highRange = client.getLocalPlayer().getCombatLevel() + level; if (player.equals(client.getLocalPlayer())) { continue; } if (player.getCombatLevel() >= lowRange && player.getCombatLevel() <= highRange || !config.combatrange()) { // boolean hadMage = false; // boolean skippableWeapon = false; // if (config.mageFilter()) // { // int mageBonus = 0; // for (int equipmentId : player.getPlayerComposition().getEquipmentIds()) // { // if (equipmentId == -1) // { // continue; // } // if (equipmentId == 6512) // { // continue; // } // if (equipmentId >= 512) // { // return; // } // int realId = equipmentId - 512; // ItemEquipmentStats itemStats = itemManager.getItemStats(realId, false).getEquipment(); // if (itemStats == null) // { // continue; // } // mageBonus += itemStats.getAmagic(); // } // if (mageBonus > 0) // { // hadMage = true; // } // } // if (!config.weaponFilter().equals("")) // { // List<String> filteredWeapons = getFilteredWeapons(); // for (int equipment : player.getPlayerComposition().getEquipmentIds()) // { // int equipmentId = equipment - 512; // if (equipmentId > 0) // { // ItemComposition equipmentComp = itemManager.getItemComposition(equipmentId); // if (filteredWeapons.stream().anyMatch(item -> WildcardMatcher.matches(item.toLowerCase(), // Text.removeTags(equipmentComp.getName().toLowerCase())))) // { // skippableWeapon = true; // } // } // } // } // if (skippableWeapon) // { // if (!hadMage) // { // continue; // } // } boolean teleported = false; Optional<Widget> widget = Inventory.search().withId(ItemID.ROYAL_SEED_POD).first(); if (widget.isPresent()) { teleported = true; InventoryInteraction.useItem(widget.get(), "Commune"); } Optional<
Widget> row = Inventory.search().nameContains("Ring of wealth (").first();
if (row.isPresent() && !teleported) { teleported = true; InventoryInteraction.useItem(row.get(), "Rub"); MousePackets.queueClickPacket(); WidgetPackets.queueResumePause(14352385, 2); } if (rowEquipment != null && !teleported) { teleported = true; MousePackets.queueClickPacket(); WidgetPackets.queueWidgetActionPacket(3, 25362456, -1, -1); } if (teleported) { teleportedFromSkulledPlayer = HypsApiPlugin.getSkullIcon(player) != null; if (teleportedFromSkulledPlayer) { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "Teleported from skulled player", null); } else { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "Teleported from non-skulled player", null); } } return; } } } // public List<String> getFilteredWeapons() // { // List<String> itemNames = new ArrayList<>(); // for (String s : config.weaponFilter().split(",")) // { // if (StringUtils.isNumeric(s)) // { // itemNames.add(Text.removeTags(itemManager.getItemComposition(Integer.parseInt(s)).getName())); // } // else // { // itemNames.add(s); // } // } // return itemNames; // } @Subscribe public void onAnimationChanged(AnimationChanged e) { Widget wildernessLevel = client.getWidget(WidgetInfo.PVP_WILDERNESS_LEVEL); int level = -1; if (wildernessLevel != null && !wildernessLevel.getText().equals("")) { try { if (wildernessLevel.getText().contains("<br>")) { String text = wildernessLevel.getText().split("<br>")[0]; level = Integer.parseInt(text.replaceAll("Level: ", "")); } else { level = Integer.parseInt(wildernessLevel.getText().replaceAll("Level: ", "")); } } catch (NumberFormatException ex) { //ignore } } if (level > -1) { if (e.getActor() == client.getLocalPlayer()) { int animation = client.getLocalPlayer().getAnimation(); if (animation == SEED_POD || animation == RING_OF_WEALTH) { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "timeout triggered", null); timeout = 10; } } } } }
src/main/java/com/utils/AutoTele/AutoTele.java
Hypsster-hUtils-d265b4f
[ { "filename": "src/main/java/com/utils/TestPlugin/Tester.java", "retrieved_chunk": "\t{\n\t\tOptional<Widget> fish = Inventory.search().idInList(List.of(371, 13441)).first();\n\t\tif (fish.isPresent())\n\t\t{\n\t\t\tWidgetPackets.queueWidgetAction(fish.get(), \"Eat\");\n\t\t}\n\t}\n}", "score": 0.8308218121528625 }, { "filename": "src/main/java/com/utils/gauntletFlicker/gauntletFlicker.java", "retrieved_chunk": "\t\t\t{\n\t\t\t\tWidget staff = HypsApiPlugin.getItem(\"*staff*\");\n\t\t\t\tWidget bow = HypsApiPlugin.getItem(\"*bow*\");\n\t\t\t\tif (staff != null)\n\t\t\t\t{\n\t\t\t\t\tMousePackets.queueClickPacket();\n\t\t\t\t\tWidgetPackets.queueWidgetAction(staff, \"Wield\");\n\t\t\t\t\tupdatedWeapon = \"staff\";\n\t\t\t\t}\n\t\t\t\telse if (bow != null)", "score": 0.8264929056167603 }, { "filename": "src/main/java/com/utils/InteractionApi/InventoryInteraction.java", "retrieved_chunk": "\t{\n\t\treturn Inventory.search().withName(name).first().flatMap(item ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItem(int id, String... actions)\n\t{", "score": 0.820503294467926 }, { "filename": "src/main/java/com/utils/InteractionApi/BankInventoryInteraction.java", "retrieved_chunk": "\t{\n\t\treturn BankInventory.search().withName(name).first().flatMap(item ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItem(int id, String... actions)\n\t{", "score": 0.8197464346885681 }, { "filename": "src/main/java/com/utils/InteractionApi/BankInventoryInteraction.java", "retrieved_chunk": "\t\treturn BankInventory.search().withId(id).first().flatMap(item ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItem(Predicate<? super Widget> predicate, String... actions)\n\t{\n\t\treturn BankInventory.search().filter(predicate).first().flatMap(item ->", "score": 0.817786455154419 } ]
java
Widget> row = Inventory.search().nameContains("Ring of wealth (").first();
package org.chelonix.dagger.client.engineconn; import io.smallrye.graphql.client.dynamic.api.DynamicGraphQLClient; import io.smallrye.graphql.client.vertx.dynamic.VertxDynamicGraphQLClientBuilder; import io.vertx.core.Vertx; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.Optional; public final class Connection { static final Logger LOG = LoggerFactory.getLogger(Connection.class); private final DynamicGraphQLClient graphQLClient; private final Vertx vertx; private final Optional<CLIRunner> daggerRunner; Connection(DynamicGraphQLClient graphQLClient, Vertx vertx, Optional<CLIRunner> daggerRunner) { this.graphQLClient = graphQLClient; this.vertx = vertx; this.daggerRunner = daggerRunner; } public DynamicGraphQLClient getGraphQLClient() { return this.graphQLClient; } public void close() throws Exception { this.graphQLClient.close(); this.vertx.close(); this.daggerRunner.ifPresent(CLIRunner::shutdown); } static Optional<Connection> fromEnv() { LOG.info("Trying initializing connection with engine from environment variables..."); String portStr = System.getenv("DAGGER_SESSION_PORT"); String sessionToken = System.getenv("DAGGER_SESSION_TOKEN"); if (portStr != null && sessionToken != null) { try { int port = Integer.parseInt(portStr); return Optional.of(getConnection(port, sessionToken, Optional.empty())); } catch (NumberFormatException nfe) { LOG.error("invalid port value in DAGGER_SESSION_PORT", nfe); } } else if (portStr == null) { LOG.error("DAGGER_SESSION_TOKEN is required when using DAGGER_SESSION_PORT"); } else if (sessionToken == null) { LOG.error("DAGGER_SESSION_PORT is required when using DAGGER_SESSION_TOKEN"); } return Optional.empty(); } static Connection fromCLI(CLIRunner cliRunner) throws IOException { LOG.info("Trying initializing connection with engine from automatic provisioning..."); try { cliRunner.start(); ConnectParams connectParams = cliRunner.getConnectionParams(); return getConnection(connectParams.getPort(), connectParams.getSessionToken(), Optional.of(cliRunner)); } catch (IOException ioe) {
cliRunner.shutdown();
throw ioe; } } public static Connection get(String workingDir) throws IOException { return fromEnv().orElse(fromCLI(new CLIRunner(workingDir))); } private static Connection getConnection(int port, String token, Optional<CLIRunner> runner) { Vertx vertx = Vertx.vertx(); String encodedToken = Base64.getEncoder().encodeToString((token + ":").getBytes(StandardCharsets.UTF_8)); DynamicGraphQLClient dynamicGraphQLClient = new VertxDynamicGraphQLClientBuilder() .vertx(vertx) .url(String.format("http://127.0.0.1:%d/query", port)) .header("authorization", "Basic " + encodedToken) .build(); return new Connection(dynamicGraphQLClient, vertx, runner); } }
dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/Connection.java
jcsirot-dagger-java-sdk-366c947
[ { "filename": "dagger-java-sdk/src/test/java/org/chelonix/dagger/client/engineconn/ConnectionTest.java", "retrieved_chunk": " CLIRunner runner = mock(CLIRunner.class);\n when(runner.getConnectionParams()).thenReturn(new ConnectParams(57535, \"6fb6d80b-5e7a-42f7-913c-31a6e50c140d\"));\n Connection conn = Connection.fromCLI(runner);\n verify(runner, times(1)).getConnectionParams();\n conn.close();\n verify(runner, times(1)).shutdown();\n }\n @Test\n public void should_fail_when_clirunner_fails() throws Exception {\n CLIRunner runner = mock(CLIRunner.class);", "score": 0.8569179773330688 }, { "filename": "dagger-java-sdk/src/test/java/org/chelonix/dagger/client/engineconn/ConnectionTest.java", "retrieved_chunk": " when(runner.getConnectionParams()).thenThrow(new IOException(\"FAILED\"));\n assertThatThrownBy(() -> Connection.fromCLI(runner)).isInstanceOf(IOException.class).hasMessage(\"FAILED\");\n }\n}", "score": 0.8444840312004089 }, { "filename": "dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/CLIRunner.java", "retrieved_chunk": "import java.util.concurrent.Executors;\nclass CLIRunner implements Runnable {\n static final Logger LOG = LoggerFactory.getLogger(CLIRunner.class);\n private final FluentProcess process;\n private ConnectParams params;\n private boolean failed = false;\n private final ExecutorService executorService;\n private static String getCLIPath() throws IOException {\n String cliBinPath = System.getenv(\"_EXPERIMENTAL_DAGGER_CLI_BIN\");\n if (cliBinPath == null) {", "score": 0.8241477608680725 }, { "filename": "dagger-java-sdk/src/test/java/org/chelonix/dagger/client/engineconn/ConnectionTest.java", "retrieved_chunk": " assertThat(conn).isPresent();\n }\n @Test\n public void should_return_empty_connection_when_env_not_set() throws Exception {\n Optional<Connection> conn;\n environmentVariables.set(\"DAGGER_SESSION_PORT\", null);\n environmentVariables.set(\"DAGGER_SESSION_TOKEN\", null);\n conn = Connection.fromEnv();\n assertThat(conn).isEmpty();\n environmentVariables.set(\"DAGGER_SESSION_PORT\", \"52037\");", "score": 0.816006064414978 }, { "filename": "dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/CLIRunner.java", "retrieved_chunk": " cliBinPath = new CLIDownloader().downloadCLI();\n }\n return cliBinPath;\n }\n public CLIRunner(String workingDir) throws IOException {\n String bin = getCLIPath();\n this.process = FluentProcess.start(bin, \"session\",\n \"--workdir\", workingDir,\n \"--label\", \"dagger.io/sdk.name:java\",\n \"--label\", \"dagger.io/sdk.version:\" + CLIDownloader.CLI_VERSION)", "score": 0.8122464418411255 } ]
java
cliRunner.shutdown();
package com.rosan.dhizuku.api; import android.content.ComponentName; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import androidx.annotation.NonNull; import com.rosan.dhizuku.aidl.IDhizuku; import com.rosan.dhizuku.aidl.IDhizukuUserServiceConnection; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; class DhizukuServiceConnections { static final IDhizukuUserServiceConnection iDhizukuUserServiceConnection = new IDhizukuUserServiceConnection.Stub() { @Override public void connected(Bundle bundle, IBinder service) { onServiceConnected(bundle, service); try { service.linkToDeath(() -> { died(bundle); }, 0); } catch (RemoteException ignored) { } } void onServiceConnected(Bundle bundle, IBinder service) { DhizukuUserServiceArgs args = new DhizukuUserServiceArgs(bundle); ComponentName name = args.getComponentName(); String token = name.flattenToString(); services.put(token, service); DhizukuServiceConnection serviceConnection = map.get(token); if (serviceConnection == null) return; serviceConnection.onServiceConnected(name, service); } @Override public void died(Bundle bundle) { DhizukuUserServiceArgs args = new DhizukuUserServiceArgs(bundle); ComponentName name = args.getComponentName(); String token = name.flattenToString(); services.remove(token); DhizukuServiceConnection serviceConnection = map.get(token); if (serviceConnection == null) return; serviceConnection.onServiceDisconnected(name); } }; private static final Map<String, DhizukuServiceConnection> map = new HashMap<>(); private static final Map<String, IBinder> services = new HashMap<>(); static void start(@NonNull IDhizuku dhizuku, @NonNull DhizukuUserServiceArgs args) throws RemoteException { ComponentName name = args.getComponentName(); String token = name.flattenToString(); IBinder service = services.get(token); if (service == null) dhizuku.bindUserService(iDhizukuUserServiceConnection, args.build()); } static void stop(@NonNull IDhizuku dhizuku, @NonNull DhizukuUserServiceArgs args) throws RemoteException { dhizuku.unbindUserService(args.build()); } static void bind(@NonNull IDhizuku dhizuku, @NonNull DhizukuUserServiceArgs args, @NonNull ServiceConnection connection) throws RemoteException { ComponentName name = args.getComponentName(); String token = name.flattenToString(); DhizukuServiceConnection serviceConnection = map.get(token); if (serviceConnection == null) { serviceConnection = new DhizukuServiceConnection(); map.put(token, serviceConnection); } serviceConnection.add(connection); IBinder service = services.get(token); if (service == null) dhizuku.bindUserService(iDhizukuUserServiceConnection, args.build()); else connection.onServiceConnected(name, service); } static void unbind(@NonNull IDhizuku dhizuku, @NonNull ServiceConnection connection) throws RemoteException { List<String> tokens = new ArrayList<>(); for (Map.Entry<String, DhizukuServiceConnection> entry : map.entrySet()) { String token = entry.getKey(); DhizukuServiceConnection serviceConnection = entry.getValue(); if (serviceConnection == null) { tokens.add(token); continue; } serviceConnection.remove(connection); if
(serviceConnection.isEmpty()) tokens.add(token);
} for (String token : tokens) { map.remove(token); ComponentName name = ComponentName.unflattenFromString(token); DhizukuUserServiceArgs args = new DhizukuUserServiceArgs(name); stop(dhizuku, args); } } }
dhizuku-api-impl/src/main/java/com/rosan/dhizuku/api/DhizukuServiceConnections.java
iamr0s-Dhizuku-API-009d517
[ { "filename": "dhizuku-api-impl/src/main/java/com/rosan/dhizuku/api/DhizukuServiceConnection.java", "retrieved_chunk": " for (ServiceConnection connection : connections) {\n connection.onServiceDisconnected(name);\n }\n });\n }\n void add(ServiceConnection connection) {\n connections.add(connection);\n }\n void remove(ServiceConnection connection) {\n connections.remove(connection);", "score": 0.8382828831672668 }, { "filename": "dhizuku-api-impl/src/main/java/com/rosan/dhizuku/api/DhizukuServiceConnection.java", "retrieved_chunk": "package com.rosan.dhizuku.api;\nimport android.content.ComponentName;\nimport android.content.ServiceConnection;\nimport android.os.Handler;\nimport android.os.IBinder;\nimport android.os.Looper;\nimport java.util.ArrayList;\nimport java.util.List;\nclass DhizukuServiceConnection {\n private final Handler handler = new Handler(Looper.getMainLooper());", "score": 0.8170334696769714 }, { "filename": "dhizuku-api-impl/src/main/java/com/rosan/dhizuku/api/DhizukuServiceConnection.java", "retrieved_chunk": " private final List<ServiceConnection> connections = new ArrayList<>();\n public void onServiceConnected(ComponentName name, IBinder service) {\n handler.post(() -> {\n for (ServiceConnection connection : connections) {\n connection.onServiceConnected(name, service);\n }\n });\n }\n public void onServiceDisconnected(ComponentName name) {\n handler.post(() -> {", "score": 0.8109189867973328 }, { "filename": "dhizuku-api-impl/src/main/java/com/rosan/dhizuku/api/DhizukuServiceConnection.java", "retrieved_chunk": " }\n boolean isEmpty() {\n return connections.isEmpty();\n }\n}", "score": 0.7988455295562744 }, { "filename": "dhizuku-api-impl/src/main/java/com/rosan/dhizuku/api/Dhizuku.java", "retrieved_chunk": " DhizukuServiceConnections.unbind(requireServer(), connection);\n return true;\n } catch (RemoteException e) {\n e.printStackTrace();\n return false;\n }\n }\n @RequiresApi(Build.VERSION_CODES.O)\n public static String[] getDelegatedScopes() {\n try {", "score": 0.7981059551239014 } ]
java
(serviceConnection.isEmpty()) tokens.add(token);
package org.chelonix.dagger.client.engineconn; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveInputStream; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; import org.freedesktop.BaseDirectory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.HexFormat; import java.util.Map; class CLIDownloader { static final Logger LOG = LoggerFactory.getLogger(CLIDownloader.class); private static final File CACHE_DIR = Paths.get(BaseDirectory.get(BaseDirectory.XDG_CACHE_HOME), "dagger").toFile(); public static final String CLI_VERSION = "0.6.2"; private static final String DAGGER_CLI_BIN_PREFIX = "dagger-"; private final FileFetcher fetcher; public CLIDownloader(FileFetcher fetcher) { this.fetcher = fetcher; } public CLIDownloader() { this(url -> new URL(url).openStream()); } public String downloadCLI(String version) throws IOException { CACHE_DIR.mkdirs(); CACHE_DIR.setExecutable(true, true); CACHE_DIR.setReadable(true, true); CACHE_DIR.setWritable(true, true); String binName = DAGGER_CLI_BIN_PREFIX + version; if (isWindows()) { binName += ".exe"; } Path binPath = Paths.get(CACHE_DIR.getPath(), binName); if (!binPath.toFile().exists()) { downloadCLI(version, binPath); } return binPath.toString(); } public String downloadCLI() throws IOException { return downloadCLI(CLI_VERSION); } private void downloadCLI(String version, Path binPath) throws IOException { String binName = binPath.getFileName().toString(); Path tmpBin = Files.createTempFile(CACHE_DIR.toPath(), "tmp-" + binName, null); try { String archiveName = getDefaultCLIArchiveName(version); String expectedChecksum = expectedChecksum(version, archiveName); if (expectedChecksum == null) { throw new IOException("Could not find checksum for " + archiveName); } String actualChecksum = extractCLI(archiveName, version, tmpBin); if (!actualChecksum.equals(expectedChecksum)) { throw new IOException("Checksum validation failed"); } tmpBin.toFile().setExecutable(true); Files.move(tmpBin, binPath); } finally { Files.deleteIfExists(tmpBin); } } private String expectedChecksum(String version, String archiveName) throws IOException { Map<String, String> checksums = fetchChecksumMap(version); return checksums.get(archiveName); } private String getDefaultCLIArchiveName(String version) { String ext = isWindows() ? "zip" : "tar.gz"; return String.format("dagger_v%s_%s_%s.%s", version, getOS(), getArch(), ext); } private Map<String, String> fetchChecksumMap(String version) throws IOException { Map<String, String> checksums = new HashMap<>(); String checksumMapURL = String.format("https://dl.dagger.io/dagger/releases/%s/checksums.txt", version); try (BufferedInputStream in = new BufferedInputStream(fetcher.fetch(checksumMapURL))) { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] dataBuffer = new byte[1024]; int bytesRead; while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) { out.write(dataBuffer, 0, bytesRead); } BufferedReader reader = new BufferedReader(new StringReader(out.toString(StandardCharsets.UTF_8))); String line; while ((line = reader.readLine()) != null) { String[] arr = line.split("\\s+"); checksums.put(arr[1], arr[0]); } return checksums; } } private String extractCLI(String archiveName, String version, Path dest) throws IOException { String cliArchiveURL = String.format("https://dl.dagger.io/dagger/releases/%s/%s", version, archiveName); LOG.info("Downloading Dagger CLI from " + cliArchiveURL); MessageDigest sha256; try { sha256 = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException nsae) { throw new IOException("Could not instantiate SHA-256 digester", nsae); } LOG.info("Extracting archive..."); try (InputStream in =
new BufferedInputStream(new DigestInputStream(fetcher.fetch(cliArchiveURL), sha256))) {
if (isWindows()) { extractZip(in, dest); } else { extractTarGZ(in, dest); } byte[] checksum = sha256.digest(); return HexFormat.of().formatHex(checksum); } } private void extractZip(InputStream in, Path dest) throws IOException { try (ZipArchiveInputStream zipIn = new ZipArchiveInputStream(in)) { extractCLIBin(zipIn, "dagger.exe", dest); } } private static void extractCLIBin(ArchiveInputStream in, String binName, Path dest) throws IOException { boolean found = false; ArchiveEntry entry; while ((entry = in.getNextEntry()) != null) { if (entry.isDirectory() || !binName.equals(entry.getName())) { continue; } int count; byte[] data = new byte[4096]; FileOutputStream fos = new FileOutputStream(dest.toFile()); try (BufferedOutputStream out = new BufferedOutputStream(fos, 4096)) { while ((count = in.read(data, 0, 4096)) != -1) { out.write(data, 0, count); } } found = true; break; } if (!found) { throw new IOException("Could not find dagger binary in CLI archive"); } } private void extractTarGZ(InputStream in, Path dest) throws IOException { boolean found = false; try (GzipCompressorInputStream gzipIn = new GzipCompressorInputStream(in); TarArchiveInputStream tarIn = new TarArchiveInputStream(gzipIn)) { extractCLIBin(tarIn, "dagger", dest); } } private static boolean isWindows() { return System.getProperty("os.name").toLowerCase().contains("win"); } private static String getOS() { String os = System.getProperty("os.name").toLowerCase(); if (os.contains("win")) { return "windows"; } else if (os.contains("linux")) { return "linux"; } else if (os.contains("darwin") || os.contains("mac")) { return "darwin"; } else { return "unknown"; } } private static String getArch() { String arch = System.getProperty("os.arch").toLowerCase(); if (arch.contains("x86_64") || arch.contains("amd64")) { return "amd64"; } else if (arch.contains("x86")) { return "x86"; } else if (arch.contains("arm")) { return "armv7"; } else if (arch.contains("aarch64")) { return "arm64"; } else { return "unknown"; } } }
dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/CLIDownloader.java
jcsirot-dagger-java-sdk-366c947
[ { "filename": "dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/CLIRunner.java", "retrieved_chunk": " cliBinPath = new CLIDownloader().downloadCLI();\n }\n return cliBinPath;\n }\n public CLIRunner(String workingDir) throws IOException {\n String bin = getCLIPath();\n this.process = FluentProcess.start(bin, \"session\",\n \"--workdir\", workingDir,\n \"--label\", \"dagger.io/sdk.name:java\",\n \"--label\", \"dagger.io/sdk.version:\" + CLIDownloader.CLI_VERSION)", "score": 0.8265206813812256 }, { "filename": "dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/CLIRunner.java", "retrieved_chunk": "import java.util.concurrent.Executors;\nclass CLIRunner implements Runnable {\n static final Logger LOG = LoggerFactory.getLogger(CLIRunner.class);\n private final FluentProcess process;\n private ConnectParams params;\n private boolean failed = false;\n private final ExecutorService executorService;\n private static String getCLIPath() throws IOException {\n String cliBinPath = System.getenv(\"_EXPERIMENTAL_DAGGER_CLI_BIN\");\n if (cliBinPath == null) {", "score": 0.8098287582397461 }, { "filename": "dagger-codegen-maven-plugin/src/main/java/org/chelonix/dagger/codegen/DaggerCodegenMojo.java", "retrieved_chunk": " } else if (introspectionQuertyURL == null) {\n in = new URL(String.format(\"https://raw.githubusercontent.com/dagger/dagger/v%s/codegen/introspection/introspection.graphql\", version)).openStream();\n } else if (introspectionQuertyURL != null) {\n in = new URL(introspectionQuertyURL).openStream();\n } else {\n throw new MojoFailureException(\"Could not locate, download or generate GraphQL schema\");\n }\n ByteArrayOutputStream out = new ByteArrayOutputStream();\n FluentProcess.start(bin, \"query\")\n .withTimeout(Duration.of(60, ChronoUnit.SECONDS))", "score": 0.8007912635803223 }, { "filename": "dagger-java-samples/src/main/java/org/chelonix/dagger/sample/ReadFileInGitRepository.java", "retrieved_chunk": "package org.chelonix.dagger.sample;\nimport org.chelonix.dagger.client.Client;\nimport org.chelonix.dagger.client.Dagger;\nimport java.io.BufferedReader;\nimport java.io.StringReader;\npublic class ReadFileInGitRepository {\n public static void main(String... args) throws Exception {\n try(Client client = Dagger.connect()) {\n String readme = client.git(\"https://github.com/dagger/dagger\")\n .tag(\"v0.3.0\")", "score": 0.7982274293899536 }, { "filename": "dagger-java-samples/src/main/java/org/chelonix/dagger/sample/GetGitVersion.java", "retrieved_chunk": "package org.chelonix.dagger.sample;\nimport org.chelonix.dagger.client.*;\nimport java.util.List;\npublic class GetGitVersion {\n public static void main(String... args) throws Exception {\n try(Client client = Dagger.connect()) {\n Directory dir = client.git(\"https://github.com/dagger/dagger\").tag(\"v0.6.2\").tree();\n Container daggerImg = client.container().build(dir);\n String stdout = daggerImg.withExec(List.of(\"version\")).stdout();\n System.out.println(stdout);", "score": 0.791233241558075 } ]
java
new BufferedInputStream(new DigestInputStream(fetcher.fetch(cliArchiveURL), sha256))) {