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/main/java/com/googlecodesamples/cloud/jss/lds/service/StorageService.java", "retrieved_chunk": " }\n /**\n * Save a file to Cloud Storage.\n *\n * @param bucketName name of the bucket\n * @param fileId unique id of the file\n * @param contentType content type of the file\n * @param content content of the file\n */\n public void save(String bucketName, String fileId, String contentType, byte[] content) {", "score": 39.9069094700352 }, { "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": 38.72605416624309 }, { "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": 35.09783525575643 }, { "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": 34.33075820304271 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreService.java", "retrieved_chunk": " return convertDoc2File(documents).get(0);\n }\n /**\n * Search files with given tags.\n *\n * @param tags list of tags label the files\n * @param orderNo application defined column for referencing order\n * @param size number of files return\n * @return list of files data\n */", "score": 33.71144097989955 } ]
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": " return openTelemetryService.spanScope(this.getClass().getName(), \"updateFile\", () -> {\n log.info(\"entering updateFile()\");\n BaseFile oldFile = fileService.getFileById(fileId);\n if (oldFile == null) {\n return ResponseEntity.notFound().build();\n }\n List<String> tagList = getTagList(tags);\n BaseFile newFile = fileService.updateFile(file, tagList, oldFile);\n return ResponseEntity.ok().body(new FileResponse(newFile));\n });", "score": 40.02221349535737 }, { "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": 29.276722890010106 }, { "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": 27.242553284908457 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreService.java", "retrieved_chunk": " public List<BaseFile> getFilesByTag(List<String> tags, String orderNo, int size)\n throws InterruptedException, ExecutionException {\n ApiFuture<QuerySnapshot> future;\n Query query =\n firestore.collection(collectionName).orderBy(ORDER_NO, Query.Direction.DESCENDING);\n if (!CollectionUtils.isEmpty(tags)) {\n query = query.whereArrayContainsAny(TAGS, tags);\n }\n if (StringUtils.hasText(orderNo)) {\n query = query.startAfter(orderNo);", "score": 25.18303610945503 }, { "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": 23.003892336292076 } ]
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/main/java/com/googlecodesamples/cloud/jss/lds/controller/FileController.java", "retrieved_chunk": " return openTelemetryService.spanScope(this.getClass().getName(), \"updateFile\", () -> {\n log.info(\"entering updateFile()\");\n BaseFile oldFile = fileService.getFileById(fileId);\n if (oldFile == null) {\n return ResponseEntity.notFound().build();\n }\n List<String> tagList = getTagList(tags);\n BaseFile newFile = fileService.updateFile(file, tagList, oldFile);\n return ResponseEntity.ok().body(new FileResponse(newFile));\n });", "score": 44.83617628827383 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreService.java", "retrieved_chunk": " public List<BaseFile> getFilesByTag(List<String> tags, String orderNo, int size)\n throws InterruptedException, ExecutionException {\n ApiFuture<QuerySnapshot> future;\n Query query =\n firestore.collection(collectionName).orderBy(ORDER_NO, Query.Direction.DESCENDING);\n if (!CollectionUtils.isEmpty(tags)) {\n query = query.whereArrayContainsAny(TAGS, tags);\n }\n if (StringUtils.hasText(orderNo)) {\n query = query.startAfter(orderNo);", "score": 25.18303610945503 }, { "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": 24.825072470360304 }, { "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": 23.648400578701875 }, { "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": 23.003892336292076 } ]
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/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": 46.44538776355587 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreService.java", "retrieved_chunk": " private final Firestore firestore;\n @Value(\"${firestore.collection.name}\")\n private String collectionName;\n @Value(\"${resource.path}\")\n private String basePath;\n public FirestoreService() {\n this.firestore = FirestoreOptions.getDefaultInstance().getService();\n }\n /**\n * Save metadata of a file to Firestore.", "score": 34.714459379919724 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/util/LdsUtil.java", "retrieved_chunk": " return UUID.randomUUID().toString();\n }\n /**\n * Get file ID from the path.\n *\n * @return the ID of the file\n */\n public static String getPathId(String path) {\n String[] pathArr = path.split(String.valueOf(URL_SLASH));\n return pathArr[pathArr.length - 1];", "score": 27.76254785836969 }, { "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": 24.73659343231619 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FileService.java", "retrieved_chunk": "/** Backend service controller for Firestore and CloudStorage */\n@Service\npublic class FileService {\n private static final Logger log = LoggerFactory.getLogger(FirestoreService.class);\n private static final int THUMBNAIL_SIZE = 300;\n private final FirestoreService firestoreService;\n private final StorageService storageService;\n @Value(\"${resource.path}\")\n private String basePath;\n @Value(\"${storage.bucket.name}\")", "score": 24.524505186144328 } ]
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/controller/FileController.java", "retrieved_chunk": " * Delete all files.\n *\n * @return status NoContent\n */\n @DeleteMapping(\"/reset\")\n public ResponseEntity<?> resetFile() throws Exception {\n return openTelemetryService.spanScope(this.getClass().getName(), \"resetFile\", () -> {\n log.info(\"entering resetFile()\");\n fileService.resetFile();\n return ResponseEntity.noContent().build();", "score": 52.37030060142319 }, { "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": 45.24505947481918 }, { "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": 40.90937314830987 }, { "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": 39.328710143410675 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/controller/FileController.java", "retrieved_chunk": " log.info(\"entering deleteFile()\");\n BaseFile file = fileService.getFileById(fileId);\n if (file == null) {\n return ResponseEntity.notFound().build();\n }\n fileService.deleteFile(file);\n return ResponseEntity.noContent().build();\n });\n }\n /**", "score": 38.51309009366345 } ]
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/service/FileService.java", "retrieved_chunk": " *\n * @param fileId unique id of the file\n * @return the uploaded file\n */\n public BaseFile getFileById(String fileId) throws InterruptedException, ExecutionException {\n log.info(\"entering getFileById()\");\n return firestoreService.getFileById(fileId);\n }\n /** Delete all files from Firestore and Cloud Storage. */\n public void resetFile() throws InterruptedException, ExecutionException {", "score": 19.997479752420293 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FileService.java", "retrieved_chunk": " storageService.delete(bucketName, file.genThumbnailPath());\n String newFileId = LdsUtil.generateUuid();\n return createOrUpdateFile(newFile, tags, fileId, newFileId, newFile.getSize());\n }\n /**\n * Delete a file from Firestore and Cloud Storage.\n *\n * @param file the uploaded file\n */\n public void deleteFile(BaseFile file) throws InterruptedException, ExecutionException {", "score": 19.93279206175429 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FileService.java", "retrieved_chunk": " private String bucketName;\n public FileService(FirestoreService firestoreService, StorageService storageService) {\n this.firestoreService = firestoreService;\n this.storageService = storageService;\n }\n /**\n * Upload files to Firestore and Cloud Storage.\n *\n * @param files list of files upload to the server\n * @param tags list of tags label the files", "score": 19.546567304310166 }, { "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": 17.385461558439737 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/util/LdsUtil.java", "retrieved_chunk": " */\npublic class LdsUtil {\n private static final char URL_SLASH = '/';\n /**\n * Get base path of a file.\n *\n * @param basePath the URL without the file ID\n * @return the base path of the input URL\n */\n public static String getResourceBasePath(String basePath) {", "score": 17.139739303288746 } ]
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": 46.37378234181554 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FileService.java", "retrieved_chunk": " *\n * @param fileId unique id of the file\n * @return the uploaded file\n */\n public BaseFile getFileById(String fileId) throws InterruptedException, ExecutionException {\n log.info(\"entering getFileById()\");\n return firestoreService.getFileById(fileId);\n }\n /** Delete all files from Firestore and Cloud Storage. */\n public void resetFile() throws InterruptedException, ExecutionException {", "score": 33.30555775331741 }, { "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": 30.702725182978476 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FileService.java", "retrieved_chunk": " * @param size number of files return\n * @return list of uploaded files\n */\n public List<BaseFile> getFilesByTag(List<String> tags, String orderNo, int size)\n throws InterruptedException, ExecutionException {\n log.info(\"entering getFilesByTag()\");\n return firestoreService.getFilesByTag(tags, orderNo, size);\n }\n /**\n * Search a single file with given fileId.", "score": 25.668878460645267 }, { "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": 23.489943792429198 } ]
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/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": 34.79153572881266 }, { "filename": "src/main/java/com/google/fhir/cql/beam/CachingModelResolver.java", "retrieved_chunk": " */\npublic class CachingModelResolver extends ForwardingModelResolver {\n private final ConcurrentHashMap<String, Class<?>> typeCache = new ConcurrentHashMap<>();\n private final ConcurrentHashMap<Class<?>, Class<?>> objectTypeCache = new ConcurrentHashMap<>();\n public CachingModelResolver(ModelResolver resolver) {\n super(resolver);\n }\n @Override\n public Class<?> resolveType(String typeName) {\n return typeCache.computeIfAbsent(typeName, super::resolveType);", "score": 28.910787390535376 }, { "filename": "src/main/java/com/google/fhir/cql/beam/types/CqlEvaluationResult.java", "retrieved_chunk": " public ResultCoder() {\n super(CqlEvaluationResult.class, SCHEMA, true);\n }\n /** The schema for {@link CqlEvaluationResult}. */\n public static Schema SCHEMA = builder(CqlEvaluationResult.class.getPackageName())\n .record(CqlEvaluationResult.class.getSimpleName()).fields()\n .name(\"contextId\").type(schemaFor(ResourceTypeAndId.class)).noDefault()\n .name(\"libraryId\").type(schemaFor(CqlLibraryId.class)).noDefault()\n .name(\"evaluationTime\")\n .type(timestampMillis().addToSchema(builder().longType()))", "score": 19.717055249684986 }, { "filename": "src/test/java/com/google/fhir/cql/beam/types/CqlEvaluationResultTest.java", "retrieved_chunk": "public class CqlEvaluationResultTest {\n private static final ZonedDateTime EVALUATION_TIME_1 =\n ZonedDateTime.of(2022, 1, 1, 1, 1, 1, 1, ZoneOffset.UTC);\n private static final ZonedDateTime EVALUATION_TIME_2 =\n ZonedDateTime.of(2022, 2, 2, 2, 2, 2, 2, ZoneOffset.UTC);\n private static final ResourceTypeAndId PATIENT_1 = new ResourceTypeAndId(\"Patient\", \"1\");\n private static final VersionedIdentifier libraryBar1 =\n new VersionedIdentifier().withId(\"Bar\").withVersion(\"1\");\n private static final VersionedIdentifier libraryBar2 =\n new VersionedIdentifier().withId(\"Bar\").withVersion(\"2\");", "score": 19.453759866784328 }, { "filename": "src/main/java/com/google/fhir/cql/beam/types/CqlEvaluationResult.java", "retrieved_chunk": "@DefaultCoder(CqlEvaluationResult.ResultCoder.class)\npublic final class CqlEvaluationResult {\n /**\n * A custom {@link AvroCoder} for {@link CqlEvaluationResult} objects.\n *\n * <p>This coder uses a custom Avro schema rather than the one generated via reflection due to the\n * results map need to support nullable values, which is not possible when using Avro's reflection\n * based schema generation.\n */\n public static class ResultCoder extends AvroCoder<CqlEvaluationResult> {", "score": 18.953384391572563 } ]
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/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": 34.79153572881266 }, { "filename": "src/main/java/com/google/fhir/cql/beam/CachingModelResolver.java", "retrieved_chunk": " */\npublic class CachingModelResolver extends ForwardingModelResolver {\n private final ConcurrentHashMap<String, Class<?>> typeCache = new ConcurrentHashMap<>();\n private final ConcurrentHashMap<Class<?>, Class<?>> objectTypeCache = new ConcurrentHashMap<>();\n public CachingModelResolver(ModelResolver resolver) {\n super(resolver);\n }\n @Override\n public Class<?> resolveType(String typeName) {\n return typeCache.computeIfAbsent(typeName, super::resolveType);", "score": 34.63505780078949 }, { "filename": "src/main/java/com/google/fhir/cql/beam/types/CqlEvaluationResult.java", "retrieved_chunk": " public ResultCoder() {\n super(CqlEvaluationResult.class, SCHEMA, true);\n }\n /** The schema for {@link CqlEvaluationResult}. */\n public static Schema SCHEMA = builder(CqlEvaluationResult.class.getPackageName())\n .record(CqlEvaluationResult.class.getSimpleName()).fields()\n .name(\"contextId\").type(schemaFor(ResourceTypeAndId.class)).noDefault()\n .name(\"libraryId\").type(schemaFor(CqlLibraryId.class)).noDefault()\n .name(\"evaluationTime\")\n .type(timestampMillis().addToSchema(builder().longType()))", "score": 23.448237087947224 }, { "filename": "src/test/java/com/google/fhir/cql/beam/types/ResourceTypeAndIdTest.java", "retrieved_chunk": "import org.junit.runners.JUnit4;\n/** Unit tests for {@link ResourceTypeAndId}. */\n@RunWith(JUnit4.class)\npublic class ResourceTypeAndIdTest {\n @Test\n public void getType() {\n assertThat(new ResourceTypeAndId(\"Patient\", \"1\").getType())\n .isEqualTo(\"Patient\");\n }\n @Test", "score": 21.481836461826724 }, { "filename": "src/test/java/com/google/fhir/cql/beam/types/CqlEvaluationResultTest.java", "retrieved_chunk": "public class CqlEvaluationResultTest {\n private static final ZonedDateTime EVALUATION_TIME_1 =\n ZonedDateTime.of(2022, 1, 1, 1, 1, 1, 1, ZoneOffset.UTC);\n private static final ZonedDateTime EVALUATION_TIME_2 =\n ZonedDateTime.of(2022, 2, 2, 2, 2, 2, 2, ZoneOffset.UTC);\n private static final ResourceTypeAndId PATIENT_1 = new ResourceTypeAndId(\"Patient\", \"1\");\n private static final VersionedIdentifier libraryBar1 =\n new VersionedIdentifier().withId(\"Bar\").withVersion(\"1\");\n private static final VersionedIdentifier libraryBar2 =\n new VersionedIdentifier().withId(\"Bar\").withVersion(\"2\");", "score": 19.453759866784328 } ]
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/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": 34.79153572881266 }, { "filename": "src/main/java/com/google/fhir/cql/beam/CachingModelResolver.java", "retrieved_chunk": " */\npublic class CachingModelResolver extends ForwardingModelResolver {\n private final ConcurrentHashMap<String, Class<?>> typeCache = new ConcurrentHashMap<>();\n private final ConcurrentHashMap<Class<?>, Class<?>> objectTypeCache = new ConcurrentHashMap<>();\n public CachingModelResolver(ModelResolver resolver) {\n super(resolver);\n }\n @Override\n public Class<?> resolveType(String typeName) {\n return typeCache.computeIfAbsent(typeName, super::resolveType);", "score": 28.910787390535376 }, { "filename": "src/main/java/com/google/fhir/cql/beam/types/CqlEvaluationResult.java", "retrieved_chunk": " public ResultCoder() {\n super(CqlEvaluationResult.class, SCHEMA, true);\n }\n /** The schema for {@link CqlEvaluationResult}. */\n public static Schema SCHEMA = builder(CqlEvaluationResult.class.getPackageName())\n .record(CqlEvaluationResult.class.getSimpleName()).fields()\n .name(\"contextId\").type(schemaFor(ResourceTypeAndId.class)).noDefault()\n .name(\"libraryId\").type(schemaFor(CqlLibraryId.class)).noDefault()\n .name(\"evaluationTime\")\n .type(timestampMillis().addToSchema(builder().longType()))", "score": 19.717055249684986 }, { "filename": "src/test/java/com/google/fhir/cql/beam/types/CqlEvaluationResultTest.java", "retrieved_chunk": "public class CqlEvaluationResultTest {\n private static final ZonedDateTime EVALUATION_TIME_1 =\n ZonedDateTime.of(2022, 1, 1, 1, 1, 1, 1, ZoneOffset.UTC);\n private static final ZonedDateTime EVALUATION_TIME_2 =\n ZonedDateTime.of(2022, 2, 2, 2, 2, 2, 2, ZoneOffset.UTC);\n private static final ResourceTypeAndId PATIENT_1 = new ResourceTypeAndId(\"Patient\", \"1\");\n private static final VersionedIdentifier libraryBar1 =\n new VersionedIdentifier().withId(\"Bar\").withVersion(\"1\");\n private static final VersionedIdentifier libraryBar2 =\n new VersionedIdentifier().withId(\"Bar\").withVersion(\"2\");", "score": 19.453759866784328 }, { "filename": "src/main/java/com/google/fhir/cql/beam/types/CqlEvaluationResult.java", "retrieved_chunk": "@DefaultCoder(CqlEvaluationResult.ResultCoder.class)\npublic final class CqlEvaluationResult {\n /**\n * A custom {@link AvroCoder} for {@link CqlEvaluationResult} objects.\n *\n * <p>This coder uses a custom Avro schema rather than the one generated via reflection due to the\n * results map need to support nullable values, which is not possible when using Avro's reflection\n * based schema generation.\n */\n public static class ResultCoder extends AvroCoder<CqlEvaluationResult> {", "score": 18.953384391572563 } ]
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/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": 15.576394347618814 }, { "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": 15.576394347618814 }, { "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": 12.348945807872234 }, { "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": 11.40822714591828 }, { "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": 9.111684956325657 } ]
java
diceResult.setAmeacas(0);
/* * 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/main/java/com/google/fhir/cql/beam/EvaluateCqlForContextFn.java", "retrieved_chunk": " public void setup() {\n cqlLibraryVersionedIdentifiers =\n cqlLibraryIds.stream()\n .map(id -> new VersionedIdentifier().withId(id.getName()).withVersion(id.getVersion()))\n .collect(toImmutableSet());\n fhirContext = new FhirContext(fhirVersion);\n modelResolver = new CachingModelResolver(new R4FhirModelResolver());\n terminologyProvider = createTerminologyProvider(fhirContext, valueSetJsonResources);\n libraryLoader = new InMemoryLibraryLoader(\n cqlSources.stream()", "score": 24.61460259160849 }, { "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": 20.288742977009672 }, { "filename": "src/test/java/com/google/fhir/cql/beam/types/CqlEvaluationResultTest.java", "retrieved_chunk": "public class CqlEvaluationResultTest {\n private static final ZonedDateTime EVALUATION_TIME_1 =\n ZonedDateTime.of(2022, 1, 1, 1, 1, 1, 1, ZoneOffset.UTC);\n private static final ZonedDateTime EVALUATION_TIME_2 =\n ZonedDateTime.of(2022, 2, 2, 2, 2, 2, 2, ZoneOffset.UTC);\n private static final ResourceTypeAndId PATIENT_1 = new ResourceTypeAndId(\"Patient\", \"1\");\n private static final VersionedIdentifier libraryBar1 =\n new VersionedIdentifier().withId(\"Bar\").withVersion(\"1\");\n private static final VersionedIdentifier libraryBar2 =\n new VersionedIdentifier().withId(\"Bar\").withVersion(\"2\");", "score": 14.977767068811449 }, { "filename": "src/test/java/com/google/fhir/cql/beam/types/CqlLibraryIdTest.java", "retrieved_chunk": "import org.junit.runner.RunWith;\nimport org.junit.runners.JUnit4;\n/** Unit tests for {@link CqlLibraryId}. */\n@RunWith(JUnit4.class)\npublic class CqlLibraryIdTest {\n @Test\n public void getName() {\n assertThat(new CqlLibraryId(\"Foo\", \"1\").getName())\n .isEqualTo(\"Foo\");\n }", "score": 13.139078844707893 }, { "filename": "src/main/java/com/google/fhir/cql/beam/types/CqlLibraryId.java", "retrieved_chunk": " @Nullable\n private String version;\n // Required for AvroCoder.\n public CqlLibraryId() {}\n public CqlLibraryId(VersionedIdentifier cqlLibraryIdentifier) {\n this(cqlLibraryIdentifier.getId(), cqlLibraryIdentifier.getVersion());\n }\n @JsonCreator\n public CqlLibraryId(\n @JsonProperty(\"name\") String name,", "score": 12.72726307097469 } ]
java
(libraryIds.getVersion()), new CqlTranslatorOptions(TRANSLATOR_OPTIONS), errors);
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": 19.66658119733889 }, { "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": 14.70269974344 }, { "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": 12.69485920337561 }, { "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": 12.234015390559096 }, { "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": 12.158734312669738 } ]
java
diceResult.setFracassos(0);
/* * 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": 101.62867884531501 }, { "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": 60.17654341018316 }, { "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": 32.030297353582164 }, { "filename": "src/main/java/com/google/fhir/cql/beam/EvaluateCqlForContextFn.java", "retrieved_chunk": " public FixedContext(\n Library library, ZonedDateTime evaluationZonedDateTime, ResourceTypeAndId contextValue) {\n super(library, evaluationZonedDateTime);\n super.setContextValue(contextValue.getType(), contextValue.getId());\n super.enterContext(contextValue.getType());\n }\n @Override\n public void enterContext(String context) {\n if (!context.equals(getCurrentContext())) {\n throw new IllegalStateException(\"Context switching is not supported.\");", "score": 17.736634857543475 }, { "filename": "src/main/java/com/google/fhir/cql/beam/EvaluateCql.java", "retrieved_chunk": " @Required\n @JsonSerialize\n @JsonDeserialize\n List<CqlLibraryId> getCqlLibraries();\n void setCqlLibraries(List<CqlLibraryId> value);\n @Description(\"Path and name prefix of the file shards that will contain the pipeline output.\")\n @Required\n String getOutputFilenamePrefix();\n void setOutputFilenamePrefix(String value);\n }", "score": 16.20445479772533 } ]
java
super.resolveType(value);
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": 24.85871264654516 }, { "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": 19.894831192646272 }, { "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": 17.23436919747976 }, { "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": 15.961476694642498 }, { "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": 13.089020455783105 } ]
java
diceResult.setFracassos(failure - success);
/* * 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/main/java/com/google/fhir/cql/beam/EvaluateCqlForContextFn.java", "retrieved_chunk": " public void setup() {\n cqlLibraryVersionedIdentifiers =\n cqlLibraryIds.stream()\n .map(id -> new VersionedIdentifier().withId(id.getName()).withVersion(id.getVersion()))\n .collect(toImmutableSet());\n fhirContext = new FhirContext(fhirVersion);\n modelResolver = new CachingModelResolver(new R4FhirModelResolver());\n terminologyProvider = createTerminologyProvider(fhirContext, valueSetJsonResources);\n libraryLoader = new InMemoryLibraryLoader(\n cqlSources.stream()", "score": 24.61460259160849 }, { "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": 20.288742977009672 }, { "filename": "src/test/java/com/google/fhir/cql/beam/types/CqlEvaluationResultTest.java", "retrieved_chunk": "public class CqlEvaluationResultTest {\n private static final ZonedDateTime EVALUATION_TIME_1 =\n ZonedDateTime.of(2022, 1, 1, 1, 1, 1, 1, ZoneOffset.UTC);\n private static final ZonedDateTime EVALUATION_TIME_2 =\n ZonedDateTime.of(2022, 2, 2, 2, 2, 2, 2, ZoneOffset.UTC);\n private static final ResourceTypeAndId PATIENT_1 = new ResourceTypeAndId(\"Patient\", \"1\");\n private static final VersionedIdentifier libraryBar1 =\n new VersionedIdentifier().withId(\"Bar\").withVersion(\"1\");\n private static final VersionedIdentifier libraryBar2 =\n new VersionedIdentifier().withId(\"Bar\").withVersion(\"2\");", "score": 14.977767068811449 }, { "filename": "src/test/java/com/google/fhir/cql/beam/types/CqlLibraryIdTest.java", "retrieved_chunk": "import org.junit.runner.RunWith;\nimport org.junit.runners.JUnit4;\n/** Unit tests for {@link CqlLibraryId}. */\n@RunWith(JUnit4.class)\npublic class CqlLibraryIdTest {\n @Test\n public void getName() {\n assertThat(new CqlLibraryId(\"Foo\", \"1\").getName())\n .isEqualTo(\"Foo\");\n }", "score": 13.139078844707893 }, { "filename": "src/main/java/com/google/fhir/cql/beam/types/CqlLibraryId.java", "retrieved_chunk": " @Nullable\n private String version;\n // Required for AvroCoder.\n public CqlLibraryId() {}\n public CqlLibraryId(VersionedIdentifier cqlLibraryIdentifier) {\n this(cqlLibraryIdentifier.getId(), cqlLibraryIdentifier.getVersion());\n }\n @JsonCreator\n public CqlLibraryId(\n @JsonProperty(\"name\") String name,", "score": 12.72726307097469 } ]
java
withId(libraryIds.getName()) .withVersion(libraryIds.getVersion()), new CqlTranslatorOptions(TRANSLATOR_OPTIONS), errors);
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": 17.070515472735753 }, { "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": 12.329480467983869 }, { "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": 12.234015390559096 }, { "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": 12.106634018836864 }, { "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": 11.166066620832092 } ]
java
diceResult.setSucessos(success - failure);
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/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": 33.74377059306409 }, { "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": 17.040819214822438 }, { "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": 15.86738800637148 }, { "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": 11.786399326776126 }, { "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": 11.74225960646408 } ]
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/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": 15.576394347618814 }, { "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": 15.576394347618814 }, { "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": 12.348945807872234 }, { "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": 11.716437160583483 }, { "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": 11.40822714591828 } ]
java
diceResult.setVantagens(advantage - threat);
/* * 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": "\t * create and manage a new span in OpenTelemetry for a given instrumentation scope\n\t * and executes a callable method within it.\n\t *\n\t * @param instrumentationScopeName represents the name of the instrumentation library that is being used.\n\t * @param spanName represents the name of the span that is being created.\n\t * @param callable is a function that is to be executed within the span.\n\t * @return generic type\n\t */\n\tpublic <T> T spanScope(String instrumentationScopeName, String spanName, Callable<T> callable) throws Exception {\n\t\tTracer tracer = openTelemetrySdk.getTracer(instrumentationScopeName, INSTRUMENTATION_SCOPE_VERSION);", "score": 13.624663480496762 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/model/FileMeta.java", "retrieved_chunk": " }\n public void setId(String id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }", "score": 12.570975850857737 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/model/BaseFile.java", "retrieved_chunk": " }\n public void setUpdateTime(Date updateTime) {\n this.updateTime = updateTime;\n }\n public String genThumbnailPath() {\n return getPath() + THUMBNAIL_EXTENSION;\n }\n public boolean checkImageFileType() {\n return IMG_EXTENSIONS.stream().anyMatch(e -> getName().toLowerCase().endsWith(e));\n }", "score": 11.85827301269718 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/model/FileResponse.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.model;\n/**\n * The FileResponse is a wrapper class for the API endpoint that returns a single file as response\n */\npublic class FileResponse {", "score": 11.06664012241886 }, { "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": 10.9625809183008 } ]
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/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": 15.576394347618814 }, { "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": 15.576394347618814 }, { "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": 12.348945807872234 }, { "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": 11.40822714591828 }, { "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": 9.111684956325657 } ]
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": "shared/src/main/java/org/geysermc/hydraulic/block/Materials.java", "retrieved_chunk": " /**\n * Get a material by its identifier.\n *\n * @param identifier the identifier of the material\n * @return the material\n */\n @Nullable\n public Material material(@NotNull String identifier) {\n return this.materials.get(identifier);\n }", "score": 38.82818280295243 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/block/Materials.java", "retrieved_chunk": " private final Map<String, Material> materials = new HashMap<>();\n /**\n * Add a material to the map.\n *\n * @param identifier the identifier of the material\n * @param material the material\n */\n public void addMaterial(@NotNull String identifier, @NotNull Material material) {\n this.materials.put(identifier, material);\n }", "score": 29.586604075771913 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/block/BlockPackModule.java", "retrieved_chunk": " return null;\n }\n private static String getTextureName(@NotNull String modelName) {\n if (modelName.startsWith(Key.MINECRAFT_NAMESPACE)) {\n String modelValue = modelName.split(\":\")[1];\n String type = modelValue.substring(0, modelValue.indexOf(\"/\"));\n String value = modelValue.substring(modelValue.indexOf(\"/\") + 1);\n // Need to use the Bedrock value for vanilla textures\n Map<String, String> textures = TextureMappings.textureMappings().textures(type);\n if (textures != null) {", "score": 22.214662624389938 }, { "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": 19.252766289077343 }, { "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": 19.198606809589982 } ]
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/pack/PackManager.java", "retrieved_chunk": " LOGGER.error(\"Failed to convert mod {} to pack\", mod.id(), ex);\n return false;\n }\n // Now export the pack\n try {\n converter.pack();\n } catch (IOException ex) {\n LOGGER.error(\"Failed to export pack for mod {}\", mod.id(), ex);\n }\n return true;", "score": 42.753056801329755 }, { "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": 42.46165780370673 }, { "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": 29.047814083467227 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/pack/PackListener.java", "retrieved_chunk": " continue;\n }\n Path packPath = packsPath.resolve(mod.id() + \".zip\");\n if (!event.resourcePacks().contains(packPath)) {\n packsToLoad.put(mod.id(), Pair.of(mod, packPath));\n }\n }\n if (packsToLoad.isEmpty()) {\n return;\n }", "score": 28.283744640092632 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/pack/PackManager.java", "retrieved_chunk": " // TODO Add a default icon?\n if (!mod.iconPath().isEmpty()) {\n try {\n pack.icon(Files.readAllBytes(mod.modPath().resolve(mod.iconPath())));\n } catch (IOException ignored) { }\n }\n });\n try {\n converter.convert();\n } catch (IOException ex) {", "score": 27.56962073981376 } ]
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/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": 10.419349661575172 }, { "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": 7.564135706995117 }, { "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": 6.423154394433828 }, { "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": 5.673266989224265 }, { "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": 5.475283661019484 } ]
java
forceResult.setLuz(light);
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/pack/TexturePackModule.java", "retrieved_chunk": " super(TextureConversionData.class);\n }\n /**\n * Gets the output location of the given key.\n *\n * @param packContext the pack context\n * @param key the key\n * @return the output location\n */\n protected static <T extends PackModule<T>> String getOutputFromModel(@NotNull PackContext<T> packContext, @NotNull Key key) {", "score": 38.15878957328549 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/platform/HydraulicBootstrap.java", "retrieved_chunk": " * @param modName the name of the mod to get\n * @return the mod with the specified name\n */\n @Nullable\n ModInfo mod(@NotNull String modName);\n /**\n * Gets the data folder directory of this platform.\n *\n * @return the data folder directory\n */", "score": 36.58946277600287 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/HydraulicImpl.java", "retrieved_chunk": " }\n /**\n * Gets the mod with the specified name, or null if not found.\n *\n * @param modName the name of the mod to get\n * @return the mod with the specified name\n */\n @Nullable\n public ModInfo mod(@NotNull String modName) {\n return this.bootstrap.mod(modName);", "score": 35.0269980131305 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/pack/PackModule.java", "retrieved_chunk": "import java.util.List;\nimport java.util.Map;\nimport java.util.function.Consumer;\n/**\n * Represents a pack module.\n * <p>\n * Pack modules handle converting data from the Minecraft\n * server into a pack that the Bedrock client can understand.\n * <p>\n * These are split up based on each specific aspect of the pack,", "score": 32.63455149535383 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/pack/context/PackEventContext.java", "retrieved_chunk": " * @return the event that this context is part of\n */\n @NotNull\n public E event() {\n return this.event;\n }\n}", "score": 31.688964383255428 } ]
java
this.hydraulic.server().registryAccess().registryOrThrow(key);
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/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": 8.979104590258002 }, { "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": 7.564135706995117 }, { "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": 6.423154394433828 }, { "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": 4.35147450300049 }, { "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": 4.2056994865792605 } ]
java
forceResult.setNegro(dark);
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/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": 28.142030989157337 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/pack/PackModule.java", "retrieved_chunk": "import java.util.List;\nimport java.util.Map;\nimport java.util.function.Consumer;\n/**\n * Represents a pack module.\n * <p>\n * Pack modules handle converting data from the Minecraft\n * server into a pack that the Bedrock client can understand.\n * <p>\n * These are split up based on each specific aspect of the pack,", "score": 27.05400315487366 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/pack/context/PackContext.java", "retrieved_chunk": " @NotNull\n public <V> List<V> registryValues(@NotNull ResourceKey<Registry<V>> key) {\n Registry<V> registry = this.hydraulic.server().registryAccess().registryOrThrow(key);\n return registry.entrySet().stream()\n .filter(entry -> entry.getKey().location().getNamespace().equals(this.mod.id()))\n .map(Map.Entry::getValue)\n .toList();\n }\n}", "score": 25.999073968762666 }, { "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": 20.211807892685066 }, { "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": 13.187614034412478 } ]
java
.packManager.initialize();
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": " 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": 35.96370981556448 }, { "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": 18.812393294188887 }, { "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": 16.244744651229833 }, { "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": 15.522903580128528 }, { "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": 15.38772075334805 } ]
java
result = boostDice.roll();
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": 76.20953599326386 }, { "filename": "fabric/src/main/java/org/geysermc/hydraulic/fabric/platform/HydraulicFabricBootstrap.java", "retrieved_chunk": " )\n ).collect(Collectors.toUnmodifiableSet());\n }\n /**\n * Ignore mods that are not built in or sub-mods.\n *\n * @param container the mod container\n * @return whether to ignore the mod\n */\n private boolean ignoreMod(ModContainer container) {", "score": 24.281526126731958 }, { "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": 21.65738986500939 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/pack/PackManager.java", "retrieved_chunk": " }\n private void callEvents(@NotNull Event event) {\n for (ModInfo mod : this.hydraulic.mods()) {\n if (IGNORED_MODS.contains(mod.id())) {\n continue;\n }\n this.callEvent(mod, event);\n }\n }\n @SuppressWarnings({ \"rawtypes\", \"unchecked\" })", "score": 20.76304797298551 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/block/Materials.java", "retrieved_chunk": " /**\n * Gets all the materials.\n *\n * @return all the materials\n */\n @NotNull\n public Map<String, Material> materials() {\n return Collections.unmodifiableMap(this.materials);\n }\n public static class Material {", "score": 20.61776218348937 } ]
java
this.bootstrap.mods();
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/Chat.java", "retrieved_chunk": " * @author heartalborada-del\n */\n public Chat(String defaultCookie, String locale, String tone) {\n c = new DefaultClient(defaultCookie).getClient().newBuilder();\n this.locale = locale;\n this.tone = tone;\n this.logger = new Logger() {\n @Override\n public void Info(String log) {\n }", "score": 33.79031415539775 }, { "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": 33.270219239648256 }, { "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": 33.09234797910644 }, { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/Chat.java", "retrieved_chunk": " */\n public Chat(String defaultCookie, Logger logger, String locale, String tone) {\n c = new DefaultClient(defaultCookie).getClient().newBuilder();\n this.locale = locale;\n this.logger = logger;\n this.tone = tone;\n }\n public Chat setProxy(Proxy proxy) {\n c.proxy(proxy);\n return this;", "score": 29.790809683081207 }, { "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": 28.191875848926326 } ]
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/utils/DefaultClient.java", "retrieved_chunk": " /**\n * Intercepts the outgoing request and sets the required headers.\n *\n * @param chain the interceptor chain.\n * @return the response received after processing the request.\n * @throws IOException if an error occurs while processing the request.\n */\n @NotNull\n @Override\n public Response intercept(@NotNull Chain chain) throws IOException {", "score": 29.25836234839986 }, { "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": 25.610919735009656 }, { "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": 23.339323803438077 }, { "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": 19.94173920313691 }, { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/Chat.java", "retrieved_chunk": " @Override\n public void Error(String log) {\n }\n @Override\n public void Warn(String log) {\n }\n @Override\n public void Debug(String log) {\n }\n };", "score": 16.446030414561363 } ]
java
logger.Debug(String.format("[%s] [%s] client send message [%s]", conversationSignature, question, data));
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": 51.95111420732531 }, { "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": 40.035174350611626 }, { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/utils/DefaultClient.java", "retrieved_chunk": " /**\n * Intercepts the outgoing request and sets the required headers.\n *\n * @param chain the interceptor chain.\n * @return the response received after processing the request.\n * @throws IOException if an error occurs while processing the request.\n */\n @NotNull\n @Override\n public Response intercept(@NotNull Chain chain) throws IOException {", "score": 35.18951883998893 }, { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/Chat.java", "retrieved_chunk": " @Override\n public void Error(String log) {\n }\n @Override\n public void Warn(String log) {\n }\n @Override\n public void Debug(String log) {\n }\n };", "score": 31.05483983202963 }, { "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": 30.33237991446903 } ]
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": " 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": 40.526884223748354 }, { "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": 36.50332373150172 }, { "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": 32.429582056761646 }, { "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": 31.847541666179268 }, { "filename": "android/src/main/java/com/phonenumberinput/CountryClickListener.java", "retrieved_chunk": "package com.phonenumberinput;\npublic interface CountryClickListener {\n void onCountryClick(int position);\n}", "score": 21.79188137942325 } ]
java
(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": " 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": 40.526884223748354 }, { "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": 36.50332373150172 }, { "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": 32.429582056761646 }, { "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": 31.847541666179268 }, { "filename": "android/src/main/java/com/phonenumberinput/CountryClickListener.java", "retrieved_chunk": "package com.phonenumberinput;\npublic interface CountryClickListener {\n void onCountryClick(int position);\n}", "score": 21.79188137942325 } ]
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": " 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": 42.119678199682326 }, { "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": 38.02437159020684 }, { "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": 35.86116486410855 }, { "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": 27.093815929902775 }, { "filename": "android/src/main/java/com/phonenumberinput/CountryPickerListItem.java", "retrieved_chunk": " return country.getCode();\n }\n };\n }\n}", "score": 24.973484331409917 } ]
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/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": 18.242014112222655 }, { "filename": "android/src/main/java/com/phonenumberinput/CountryPickerAdapter.java", "retrieved_chunk": " @Override\n public CountryPickerListItem onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {\n View view = inflater.inflate(R.layout.country_picker_list_item, parent, false);\n return new CountryPickerListItem(view, this::onCountryClick);\n }\n @Override\n public void onBindViewHolder(@NonNull CountryPickerListItem holder, int position) {\n Country country = countries.get(position);\n // Set the country flag, country name, and calling code for the current list item\n holder.countryName.setText(String.format(\"%s %s\", country.getEmoji(), country.getName()));", "score": 12.88413894795739 }, { "filename": "android/src/main/java/com/phonenumberinput/Country.java", "retrieved_chunk": " this.callingCode = callingCode;\n }\n public String getName() {\n return name;\n }\n public String getCode() {\n return code;\n }\n public String getEmoji() {\n return emoji;", "score": 12.309534800990075 }, { "filename": "android/src/main/java/com/phonenumberinput/PhoneNumberToolbarViewManager.java", "retrieved_chunk": " @NonNull\n @Override\n public String getName() {\n return NAME;\n }\n @Override\n public PhoneNumberToolbarView createViewInstance(ThemedReactContext context) {\n return new PhoneNumberToolbarView(context);\n }\n @Override", "score": 11.998294974171495 }, { "filename": "android/src/main/java/com/phonenumberinput/CountryPickerAdapter.java", "retrieved_chunk": " public int getItemCount() {\n return countries.size();\n }\n public void setSelectedIndex(int selectedIndex) {\n defaultCountry = selectedIndex;\n if (selectionTracker == null) {\n return;\n }\n if (selectedIndex >= 0 && selectedIndex < countries.size()) {\n String countryCode = countries.get(selectedIndex).getCode();", "score": 11.402876002047407 } ]
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": " 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": 42.02295155129056 }, { "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": 40.776125989826085 }, { "filename": "src/com/android/traceur/SearchProvider.java", "retrieved_chunk": " }\n @Override\n public Cursor queryRawData(String[] projection) {\n MatrixCursor cursor = new MatrixCursor(INDEXABLES_RAW_COLUMNS);\n Context context = getContext();\n Object[] ref = new Object[INDEXABLES_RAW_COLUMNS.length];\n ref[COLUMN_INDEX_RAW_KEY] = context.getString(R.string.system_tracing);\n ref[COLUMN_INDEX_RAW_TITLE] = context.getString(R.string.system_tracing);\n ref[COLUMN_INDEX_RAW_SUMMARY_ON] = context.getString(R.string.record_system_activity);\n ref[COLUMN_INDEX_RAW_KEYWORDS] = context.getString(R.string.keywords);", "score": 26.083897143013996 }, { "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": 24.6163099571111 }, { "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": 22.857204267857636 } ]
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": " new Logger(\"traceService:stderr\", process.getErrorStream());\n if (logOutput) {\n new Logger(\"traceService:stdout\", process.getInputStream());\n }\n return process;\n }\n // Returns the Process if the command terminated on time and null if not.\n public static Process execWithTimeout(String cmd, String tmpdir, long timeout)\n throws IOException {\n Process process = exec(cmd, tmpdir, true);", "score": 55.76556336963084 }, { "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": 55.4747128263608 }, { "filename": "src/com/android/traceur/TraceUtils.java", "retrieved_chunk": " }\n public static Process exec(String cmd, String tmpdir) throws IOException {\n return exec(cmd, tmpdir, true);\n }\n public static Process exec(String cmd, String tmpdir, boolean logOutput) throws IOException {\n String[] cmdarray = {\"sh\", \"-c\", cmd};\n String[] envp = {\"TMPDIR=\" + tmpdir};\n envp = tmpdir == null ? null : envp;\n Log.v(TAG, \"exec: \" + Arrays.toString(envp) + \" \" + Arrays.toString(cmdarray));\n Process process = RUNTIME.exec(cmdarray, envp);", "score": 51.76849438281241 }, { "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": 46.41521687001 }, { "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": 43.07347571907368 } ]
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": " 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": 57.88054368702237 }, { "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": 53.155492449734375 }, { "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": 50.41972934110975 }, { "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": 47.16996451572239 }, { "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": 45.118032745521525 } ]
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/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": 61.49141230374431 }, { "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": 60.93512650666407 }, { "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": 58.2337260888553 }, { "filename": "src/com/android/traceur/TraceService.java", "retrieved_chunk": " notificationManager.cancel(TRACE_NOTIFICATION);\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n prefs.edit().putBoolean(context.getString(\n R.string.pref_key_tracing_on), false).commit();\n TraceUtils.traceStop();\n }\n public TraceService() {\n this(\"TraceService\");\n }\n protected TraceService(String name) {", "score": 53.23650687446194 }, { "filename": "src/com/android/traceur/TraceService.java", "retrieved_chunk": " private void startTracingInternal(Collection<String> tags, int bufferSizeKb, boolean appTracing,\n boolean longTrace, int maxLongTraceSizeMb, int maxLongTraceDurationMinutes) {\n Context context = getApplicationContext();\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n Intent stopIntent = new Intent(Receiver.STOP_ACTION,\n null, context, Receiver.class);\n stopIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);\n String title = context.getString(R.string.trace_is_being_recorded);\n String msg = context.getString(R.string.tap_to_stop_tracing);\n boolean attachToBugreport =", "score": 45.90589675867676 } ]
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": 69.67017477154762 }, { "filename": "src/com/android/traceur/FileSender.java", "retrieved_chunk": " .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 NotificationManager.from(context).notify(file.getName(), 0, builder.build());\n }\n public static void send(Context context, File file) {\n // Files are kept on private storage, so turn into Uris that we can", "score": 60.022324470345424 }, { "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": 28.97440331403395 }, { "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": 27.25847336872676 }, { "filename": "src/com/android/traceur/PerfettoUtils.java", "retrieved_chunk": " private static final String WEBVIEW_TAG = \"webview\";\n public String getName() {\n return NAME;\n }\n public String getOutputExtension() {\n return OUTPUT_EXTENSION;\n }\n public boolean traceStart(Collection<String> tags, int bufferSizeKb, boolean apps,\n boolean attachToBugreport, boolean longTrace, int maxLongTraceSizeMb,\n int maxLongTraceDurationMinutes) {", "score": 25.458967501552404 } ]
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": 85.02958361697674 }, { "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": 47.75430960631816 }, { "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": 38.9794961983681 }, { "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": 36.59538471989164 }, { "filename": "src/com/android/traceur/TraceUtils.java", "retrieved_chunk": " }\n public static Process exec(String cmd, String tmpdir) throws IOException {\n return exec(cmd, tmpdir, true);\n }\n public static Process exec(String cmd, String tmpdir, boolean logOutput) throws IOException {\n String[] cmdarray = {\"sh\", \"-c\", cmd};\n String[] envp = {\"TMPDIR=\" + tmpdir};\n envp = tmpdir == null ? null : envp;\n Log.v(TAG, \"exec: \" + Arrays.toString(envp) + \" \" + Arrays.toString(cmdarray));\n Process process = RUNTIME.exec(cmdarray, envp);", "score": 34.134180096160954 } ]
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": " 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": 84.56537636996453 }, { "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": 77.47545173903768 }, { "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": 61.16369960156325 }, { "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": 50.85271843938223 }, { "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": 47.13537766008512 } ]
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": " } 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": 45.498970587769655 }, { "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": 41.01015703685518 }, { "filename": "src/com/android/traceur/TraceUtils.java", "retrieved_chunk": " new Logger(\"traceService:stderr\", process.getErrorStream());\n if (logOutput) {\n new Logger(\"traceService:stdout\", process.getInputStream());\n }\n return process;\n }\n // Returns the Process if the command terminated on time and null if not.\n public static Process execWithTimeout(String cmd, String tmpdir, long timeout)\n throws IOException {\n Process process = exec(cmd, tmpdir, true);", "score": 33.78924575723433 }, { "filename": "src/com/android/traceur/TraceUtils.java", "retrieved_chunk": " }\n public static Process exec(String cmd, String tmpdir) throws IOException {\n return exec(cmd, tmpdir, true);\n }\n public static Process exec(String cmd, String tmpdir, boolean logOutput) throws IOException {\n String[] cmdarray = {\"sh\", \"-c\", cmd};\n String[] envp = {\"TMPDIR=\" + tmpdir};\n envp = tmpdir == null ? null : envp;\n Log.v(TAG, \"exec: \" + Arrays.toString(envp) + \" \" + Arrays.toString(cmdarray));\n Process process = RUNTIME.exec(cmdarray, envp);", "score": 31.078635533187835 }, { "filename": "src/com/android/traceur/TraceUtils.java", "retrieved_chunk": " try {\n if (!process.waitFor(timeout, TimeUnit.MILLISECONDS)) {\n Log.e(TAG, \"Command '\" + cmd + \"' has timed out after \" + timeout + \" ms.\");\n process.destroyForcibly();\n // Return null to signal a timeout and that the Process was destroyed.\n return null;\n }\n } catch (Exception e) {\n throw new RuntimeException(e);\n }", "score": 31.021977527341672 } ]
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/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": 73.86245534943534 }, { "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": 61.591110877119974 }, { "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": 59.30751430029053 }, { "filename": "src/com/android/traceur/TraceUtils.java", "retrieved_chunk": " }\n public static Process exec(String cmd, String tmpdir) throws IOException {\n return exec(cmd, tmpdir, true);\n }\n public static Process exec(String cmd, String tmpdir, boolean logOutput) throws IOException {\n String[] cmdarray = {\"sh\", \"-c\", cmd};\n String[] envp = {\"TMPDIR=\" + tmpdir};\n envp = tmpdir == null ? null : envp;\n Log.v(TAG, \"exec: \" + Arrays.toString(envp) + \" \" + Arrays.toString(cmdarray));\n Process process = RUNTIME.exec(cmdarray, envp);", "score": 58.829312563528234 }, { "filename": "src/com/android/traceur/PerfettoUtils.java", "retrieved_chunk": " public static TreeMap<String,String> perfettoListCategories() {\n String cmd = \"perfetto --query-raw\";\n Log.v(TAG, \"Listing tags: \" + cmd);\n try {\n TreeMap<String, String> result = new TreeMap<>();\n // execWithTimeout() cannot be used because stdout must be consumed before the process\n // is terminated.\n Process perfetto = TraceUtils.exec(cmd, null, false);\n TracingServiceState serviceState =\n TracingServiceState.parseFrom(perfetto.getInputStream());", "score": 51.0050811958575 } ]
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/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": 56.0946168451414 }, { "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": 48.85229694833188 }, { "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": 44.22062688519047 }, { "filename": "src/com/android/traceur/TraceService.java", "retrieved_chunk": " notificationManager.cancel(TRACE_NOTIFICATION);\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n prefs.edit().putBoolean(context.getString(\n R.string.pref_key_tracing_on), false).commit();\n TraceUtils.traceStop();\n }\n public TraceService() {\n this(\"TraceService\");\n }\n protected TraceService(String name) {", "score": 41.03551134185255 }, { "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": 37.12532603240359 } ]
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/UserConsentActivityDialog.java", "retrieved_chunk": " params.mPositiveButtonText = getString(R.string.share);\n params.mNegativeButtonText = getString(android.R.string.cancel);\n params.mPositiveButtonListener = this;\n params.mNegativeButtonListener = this;\n mDontShowAgain = (CheckBox) params.mView.findViewById(android.R.id.checkbox);\n setupAlert();\n }\n @Override\n public void onClick(DialogInterface dialog, int which) {\n if (which == AlertDialog.BUTTON_POSITIVE) {", "score": 50.27207853492208 }, { "filename": "src/com/android/traceur/SearchProvider.java", "retrieved_chunk": " }\n @Override\n public Cursor queryRawData(String[] projection) {\n MatrixCursor cursor = new MatrixCursor(INDEXABLES_RAW_COLUMNS);\n Context context = getContext();\n Object[] ref = new Object[INDEXABLES_RAW_COLUMNS.length];\n ref[COLUMN_INDEX_RAW_KEY] = context.getString(R.string.system_tracing);\n ref[COLUMN_INDEX_RAW_TITLE] = context.getString(R.string.system_tracing);\n ref[COLUMN_INDEX_RAW_SUMMARY_ON] = context.getString(R.string.record_system_activity);\n ref[COLUMN_INDEX_RAW_KEYWORDS] = context.getString(R.string.keywords);", "score": 28.163549412333712 }, { "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": 25.340553410689864 }, { "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": 23.053192953304382 }, { "filename": "src/com/android/traceur/TraceService.java", "retrieved_chunk": " private void startTracingInternal(Collection<String> tags, int bufferSizeKb, boolean appTracing,\n boolean longTrace, int maxLongTraceSizeMb, int maxLongTraceDurationMinutes) {\n Context context = getApplicationContext();\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n Intent stopIntent = new Intent(Receiver.STOP_ACTION,\n null, context, Receiver.class);\n stopIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);\n String title = context.getString(R.string.trace_is_being_recorded);\n String msg = context.getString(R.string.tap_to_stop_tracing);\n boolean attachToBugreport =", "score": 22.745798320572423 } ]
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": 56.12340303674657 }, { "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": 43.94014654889198 }, { "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": 35.415111849170366 }, { "filename": "src/com/android/traceur/TraceUtils.java", "retrieved_chunk": " }\n public static Process exec(String cmd, String tmpdir) throws IOException {\n return exec(cmd, tmpdir, true);\n }\n public static Process exec(String cmd, String tmpdir, boolean logOutput) throws IOException {\n String[] cmdarray = {\"sh\", \"-c\", cmd};\n String[] envp = {\"TMPDIR=\" + tmpdir};\n envp = tmpdir == null ? null : envp;\n Log.v(TAG, \"exec: \" + Arrays.toString(envp) + \" \" + Arrays.toString(cmdarray));\n Process process = RUNTIME.exec(cmdarray, envp);", "score": 34.484605911918806 }, { "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": 34.171237808155695 } ]
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/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": 40.53001897746282 }, { "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": 39.45672293885948 }, { "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": 36.9472267346632 }, { "filename": "src/main/java/ho/artisan/lib/recipe/mixin/SmithingRecipeAccessor.java", "retrieved_chunk": "@Mixin(SmithingRecipe.class)\npublic interface SmithingRecipeAccessor {\n\t@Accessor\n\tIngredient getBase();\n\t@Accessor\n\tIngredient getAddition();\n}", "score": 28.268158001813475 }, { "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": 23.649012549243718 } ]
java
), accessor.getAddition(), recipe.getOutput().getItem(), null, null ).toJson();
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": "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": 28.824602888472185 }, { "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": 23.451990672583502 }, { "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": 14.909016878984483 }, { "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": 14.728800322792242 }, { "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": 13.890528612699645 } ]
java
innerMsg.free();
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": 72.11223800784438 }, { "filename": "src/main/java/com/HiWord9/RPRenames/configGeneration/CEMConfig.java", "retrieved_chunk": " Rename alreadyExist = ConfigManager.configRead(currentFile);\n String[] ae = alreadyExist.getName();\n if (!Arrays.stream(ae).toList().contains(name)) {\n int AEsize = ae.length;\n String[] newConfig = new String[AEsize + 1];\n int h = 0;\n while (h < AEsize) {\n newConfig[h] = ae[h];\n h++;\n }", "score": 70.30501153166489 }, { "filename": "src/main/java/com/HiWord9/RPRenames/mixin/AnvilScreenMixin.java", "retrieved_chunk": "\t\t\t\tif (open) {\n\t\t\t\t\tscreenUpdate(page);\n\t\t\t\t}\n\t\t\t});\n\t\t\tremoveFromFavorite = new TexturedButtonWidget(this.width / 2 + config.favoritePosX, this.height / 2 + config.favoritePosY, favoriteButtonWidth, favoriteButtonHeight, 0, 0, 0, FAVORITE_BUTTON_TEXTURE, favoriteButtonTextureWidth, favoriteButtonTextureHeight, button -> {\n\t\t\t\tString favoriteName = nameField.getText();\n\t\t\t\tString item = cutTranslationKey(currentItem);\n\t\t\t\tFile currentFile = new File(RPRenames.configPathFavorite + item + \".json\");\n\t\t\t\tRename alreadyExist = ConfigManager.configRead(currentFile);\n\t\t\t\tArrayList<String> alreadyExistList = new ArrayList<>(Arrays.stream(alreadyExist.getName()).toList());", "score": 64.2106050707334 }, { "filename": "src/main/java/com/HiWord9/RPRenames/mixin/AnvilScreenMixin.java", "retrieved_chunk": "\t\t\t\t\tRename alreadyExist = ConfigManager.configRead(currentFile);\n\t\t\t\t\tnameExist = Arrays.stream(alreadyExist.getName()).toList().contains(favoriteName);\n\t\t\t\t\tif (!nameExist) {\n\t\t\t\t\t\tString[] newConfig = new String[alreadyExist.getName().length + 1];\n\t\t\t\t\t\tint h = 0;\n\t\t\t\t\t\twhile (h < alreadyExist.getName().length) {\n\t\t\t\t\t\t\tnewConfig[h] = alreadyExist.getName()[h];\n\t\t\t\t\t\t\th++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tnewConfig[h] = favoriteName;", "score": 55.79378898514231 }, { "filename": "src/main/java/com/HiWord9/RPRenames/RenameButton.java", "retrieved_chunk": " public static boolean calcFavorite(String item, String name) {\n File file = new File(RPRenames.configPathFavorite + item + \".json\");\n if (file.exists()) {\n String[] favoriteList = ConfigManager.configRead(file).getName();\n for (String s : favoriteList) {\n if (name.equals(s)) {\n return true;\n }\n }\n }", "score": 40.762154991098924 } ]
java
).contains(ConfigManager.getFirstName(p.getProperty("nbt.display.Name")))) {
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": 54.72771452997879 }, { "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": 20.337963154069445 }, { "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": 17.813560026011555 }, { "filename": "lint-rpc-demo/lint-rpc-demo-provide1/src/main/java/com/lint/rpc/demo/provide/service/ProvideEatImpl.java", "retrieved_chunk": " return \"[ eta -> \"+f+\" And drink -> \"+d+\"]\";\n }else {\n return food[random.nextInt(food.length)];\n }\n }\n}", "score": 16.42494158164636 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ClientPool.java", "retrieved_chunk": " groupSet = servicePool.computeIfAbsent(serviceName, k -> new LinkedHashSet<>());\n }\n NettyConf conf = nc.getConf();\n String groupName = getGroupName(conf.getAddress());\n Set<NettyClient> nettyClientSet = groupPool.get(groupName);\n if(null == nettyClientSet){\n rLock.lock();\n lockCount++;\n nettyClientSet = groupPool.computeIfAbsent(groupName, k -> new LinkedHashSet<>());\n }", "score": 15.221218286901106 } ]
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/balance/RandomLoadBalance.java", "retrieved_chunk": " @Override\n public int getClientIndex(int size) {\n if(size <= 0){\n return -1;\n }\n return size != 1\n // random bound 上界不包括 需要+1\n ? random.nextInt(size+1)\n : size;\n }", "score": 22.1307172613434 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/balance/RoundLoadBalance.java", "retrieved_chunk": " @Override\n public int getClientIndex(int size) {\n if(size <= 0){\n return -1;\n }\n return size != 1\n // random bound 上界不包括 需要+1\n ? loopFlag.incrementAndGet() % size\n : size;\n }", "score": 22.06615626308536 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/balance/ILoadBalancePolicy.java", "retrieved_chunk": " */\n int getClientIndex(int size);\n}", "score": 16.21424221212049 }, { "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": 14.319034880590074 }, { "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": 13.774998873272837 } ]
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": 21.053244359239116 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/balance/RoundLoadBalance.java", "retrieved_chunk": "// System.out.println(index + \"----\" + i);\n// flag = true;\n// }\n// if(i > 0 && flag ){\n// System.out.println(index + \"----\" + i);\n// flag = false;\n// }\n// }\n// }\n}", "score": 12.80497214541338 }, { "filename": "lint-rpc-demo/lint-rpc-demo-provide1/src/main/java/com/lint/rpc/demo/provide/service/ProvideEatImpl.java", "retrieved_chunk": " return \"[ eta -> \"+f+\" And drink -> \"+d+\"]\";\n }else {\n return food[random.nextInt(food.length)];\n }\n }\n}", "score": 10.327767786958114 }, { "filename": "lint-rpc-demo/lint-rpc-demo-consumer/src/main/java/com/lint/rpc/demo/consumer/ConsumerApplication.java", "retrieved_chunk": " }\n try {\n c.await();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n System.out.println(\"线程执行完毕\");\n }, 0,20, TimeUnit.SECONDS); // 3s 之后执行\n System.in.read();\n }", "score": 10.104685237079872 }, { "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": 9.514597071491496 } ]
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/RoundLoadBalance.java", "retrieved_chunk": " @Override\n public int getClientIndex(int size) {\n if(size <= 0){\n return -1;\n }\n return size != 1\n // random bound 上界不包括 需要+1\n ? loopFlag.incrementAndGet() % size\n : size;\n }", "score": 25.145336725218257 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/balance/RandomLoadBalance.java", "retrieved_chunk": " @Override\n public int getClientIndex(int size) {\n if(size <= 0){\n return -1;\n }\n return size != 1\n // random bound 上界不包括 需要+1\n ? random.nextInt(size+1)\n : size;\n }", "score": 24.897514347151876 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/balance/ILoadBalancePolicy.java", "retrieved_chunk": " */\n int getClientIndex(int size);\n}", "score": 22.485414223480102 }, { "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": 17.374969723954628 }, { "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": 17.069214423664185 } ]
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": " 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": 20.469788587748475 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ClientPool.java", "retrieved_chunk": " groupSet = servicePool.computeIfAbsent(serviceName, k -> new LinkedHashSet<>());\n }\n NettyConf conf = nc.getConf();\n String groupName = getGroupName(conf.getAddress());\n Set<NettyClient> nettyClientSet = groupPool.get(groupName);\n if(null == nettyClientSet){\n rLock.lock();\n lockCount++;\n nettyClientSet = groupPool.computeIfAbsent(groupName, k -> new LinkedHashSet<>());\n }", "score": 19.79538040077941 }, { "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": 18.90411249455903 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/util/ByteUtil.java", "retrieved_chunk": " oos.close();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n return bytes;\n }\n private ByteUtil(){}\n}", "score": 17.282485701689417 }, { "filename": "lint-rpc-demo/lint-rpc-demo-consumer/src/main/java/com/lint/rpc/demo/consumer/ConsumerApplication.java", "retrieved_chunk": " }\n try {\n c.await();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n System.out.println(\"线程执行完毕\");\n }, 0,20, TimeUnit.SECONDS); // 3s 之后执行\n System.in.read();\n }", "score": 16.597839546190347 } ]
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": "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": 25.374208871440594 }, { "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": 20.048791724262557 }, { "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": 14.728800322792242 }, { "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": 10.932619447855515 }, { "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": 10.5681506457795 } ]
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/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": 38.90216992673021 }, { "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": 33.34117184807313 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/protocol/RequestContent.java", "retrieved_chunk": " public void setRequestBody(RequestBody requestBody) {\n this.requestBody = requestBody;\n }\n public void free() {\n requestHeader = null;\n requestBody = null;\n }\n}", "score": 30.033520365650098 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/protocol/RequestBody.java", "retrieved_chunk": " public void setArgs(Object[] args) {\n this.args = args;\n }\n public Object getRes() {\n return res;\n }\n public void setRes(Object res) {\n this.res = res;\n }\n}", "score": 26.74199124860337 }, { "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": 24.66818626640771 } ]
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": " 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": 28.45011232430199 }, { "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": 23.410277289491066 }, { "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": 17.374479711253787 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ClientPool.java", "retrieved_chunk": " groupSet = servicePool.computeIfAbsent(serviceName, k -> new LinkedHashSet<>());\n }\n NettyConf conf = nc.getConf();\n String groupName = getGroupName(conf.getAddress());\n Set<NettyClient> nettyClientSet = groupPool.get(groupName);\n if(null == nettyClientSet){\n rLock.lock();\n lockCount++;\n nettyClientSet = groupPool.computeIfAbsent(groupName, k -> new LinkedHashSet<>());\n }", "score": 13.786126821192152 }, { "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": 13.194032303573122 } ]
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": 74.84031468105282 }, { "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": 22.260600950653018 }, { "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": 16.774553376476458 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ClientPool.java", "retrieved_chunk": " if(ncSet.size() < lintConf.getClientMaxConnCount()){\n try {\n rLock.lock();\n if(ncSet.size() < lintConf.getClientMaxConnCount()){\n String[] address = groupName.split(\":\");\n InetSocketAddress inetSocketAddress = new InetSocketAddress(\n address[0], Integer.parseInt(address[1]));\n ch = createClient(serviceName, inetSocketAddress);\n return put(serviceName, ch);\n }", "score": 12.326183322958654 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ClientPool.java", "retrieved_chunk": " boolean contains = groupNameSet.contains(groupName);\n if(!contains){\n break;\n }\n }\n ch = createClient(serviceName, address);\n if(ch != null){\n return put(serviceName, ch);\n }\n }", "score": 11.853666737565279 } ]
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": 39.227077284228024 }, { "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": 32.21044317044985 }, { "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": 29.550519899926368 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/protocol/RequestContent.java", "retrieved_chunk": " public void setRequestBody(RequestBody requestBody) {\n this.requestBody = requestBody;\n }\n public void free() {\n requestHeader = null;\n requestBody = null;\n }\n}", "score": 27.485640091000462 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/protocol/RequestBody.java", "retrieved_chunk": " public void setArgs(Object[] args) {\n this.args = args;\n }\n public Object getRes() {\n return res;\n }\n public void setRes(Object res) {\n this.res = res;\n }\n}", "score": 26.13604834914196 } ]
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": 48.43874161395056 }, { "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": 28.609941347486178 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ClientPool.java", "retrieved_chunk": " groupSet = servicePool.computeIfAbsent(serviceName, k -> new LinkedHashSet<>());\n }\n NettyConf conf = nc.getConf();\n String groupName = getGroupName(conf.getAddress());\n Set<NettyClient> nettyClientSet = groupPool.get(groupName);\n if(null == nettyClientSet){\n rLock.lock();\n lockCount++;\n nettyClientSet = groupPool.computeIfAbsent(groupName, k -> new LinkedHashSet<>());\n }", "score": 23.396078851803583 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/bootstrap/LintRpcServerApplication.java", "retrieved_chunk": " * Lint RPC 启动器\n */\npublic class LintRpcServerApplication {\n public static void run(int port, LintConf conf, Class<?> baseClazz){\n if (null == conf\n || null == conf.getProvideSpiType() || \"\".equals(conf.getProvideSpiType())){\n throw new RpcException(RpcMsg.EXCEPTION_NOT_SET_CONF);\n }\n // 1. 加载全局配置\n ConfPool confPool = ConfPool.getInstance();", "score": 20.59766131814671 }, { "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": 20.06763430768081 } ]
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 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": 31.424149802362805 }, { "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": 24.394375117732785 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/service/ProvideSpi.java", "retrieved_chunk": " if(null == provideService || null == provideService.getProvide()){\n return null;\n }\n return provideService.getProvide().get(serviceName);\n }\n private static class LazyHolder {\n private static final ProvideSpi INSTANCE = new ProvideSpi();\n }\n public static ProvideSpi getInstance() {\n return ProvideSpi.LazyHolder.INSTANCE;", "score": 23.65299810772189 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ConfPool.java", "retrieved_chunk": " private static final AtomicReference<LintConf> LINT_CONF_ATOMIC_REFERENCE = new AtomicReference<>();\n public LintConf init(final LintConf conf){\n if(null == LINT_CONF_ATOMIC_REFERENCE.get()){\n synchronized(ConfPool.class) {\n if (null == LINT_CONF_ATOMIC_REFERENCE.get()) {\n return LINT_CONF_ATOMIC_REFERENCE.getAndSet(conf);\n }\n }\n }\n return LINT_CONF_ATOMIC_REFERENCE.get();", "score": 20.328696950722914 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/balance/RoundLoadBalance.java", "retrieved_chunk": " @Override\n public int getClientIndex(int size) {\n if(size <= 0){\n return -1;\n }\n return size != 1\n // random bound 上界不包括 需要+1\n ? loopFlag.incrementAndGet() % size\n : size;\n }", "score": 18.43581599485276 } ]
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/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": 19.466297065014196 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/ClientFactory.java", "retrieved_chunk": "package com.lint.rpc.common.transport;\n/**\n * 获取 client\n *\n * @author 周鹏程\n * @date 2023-05-26 3:59 PM\n **/\npublic class ClientFactory {\n public NettyClient create(NettyConf nettyConf){\n return new NettyClient(nettyConf);", "score": 8.31880366951011 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/service/ProvideSpi.java", "retrieved_chunk": " if(null == provideService || null == provideService.getProvide()){\n return null;\n }\n return provideService.getProvide().get(serviceName);\n }\n private static class LazyHolder {\n private static final ProvideSpi INSTANCE = new ProvideSpi();\n }\n public static ProvideSpi getInstance() {\n return ProvideSpi.LazyHolder.INSTANCE;", "score": 6.7760431251164945 }, { "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": 6.217167401318705 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/util/ByteUtil.java", "retrieved_chunk": " oos.writeObject(obj);\n bytes = out.toByteArray();\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n try {\n out.reset();\n out.close();\n if(null != oos){\n oos.reset();", "score": 6.092174133848783 } ]
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/ILoadBalancePolicy.java", "retrieved_chunk": " */\n int getClientIndex(int size);\n}", "score": 16.21424221212049 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/balance/RoundLoadBalance.java", "retrieved_chunk": " @Override\n public int getClientIndex(int size) {\n if(size <= 0){\n return -1;\n }\n return size != 1\n // random bound 上界不包括 需要+1\n ? loopFlag.incrementAndGet() % size\n : size;\n }", "score": 15.642087337668677 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/balance/RandomLoadBalance.java", "retrieved_chunk": " @Override\n public int getClientIndex(int size) {\n if(size <= 0){\n return -1;\n }\n return size != 1\n // random bound 上界不包括 需要+1\n ? random.nextInt(size+1)\n : size;\n }", "score": 15.478153596372982 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyClient.java", "retrieved_chunk": " }\n }\n }\n if(ch == null){\n return false;\n }\n try {\n ch.writeAndFlush(msg).sync();\n return true;\n } catch (InterruptedException e) {", "score": 13.976564792659294 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyClient.java", "retrieved_chunk": " private final NettyConf conf;\n private volatile NioSocketChannel ch;\n public NettyClient(NettyConf conf){\n this.conf = conf;\n }\n public boolean sendMsg(Object msg){\n if(ch == null){\n synchronized (this){\n if(ch == null){\n this.connect();", "score": 12.903194644744797 } ]
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": " @Override\n public Integer getCode() {\n return this.code;\n }\n @Override\n public String getMessage() {\n return this.message;\n }\n}", "score": 41.068640611573656 }, { "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": 32.00785319549149 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyClient.java", "retrieved_chunk": " private final NettyConf conf;\n private volatile NioSocketChannel ch;\n public NettyClient(NettyConf conf){\n this.conf = conf;\n }\n public boolean sendMsg(Object msg){\n if(ch == null){\n synchronized (this){\n if(ch == null){\n this.connect();", "score": 17.93629187617278 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/LintConf.java", "retrieved_chunk": " return this;\n }\n public String getProvideSpiType() {\n return provideSpiType;\n }\n public LintConf setProvideSpiType(String provideSpiType) {\n this.provideSpiType = provideSpiType;\n return this;\n }\n public int getRequestWaitTimeBySeconds() {", "score": 14.79582821165925 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyClient.java", "retrieved_chunk": " }\n }\n }\n if(ch == null){\n return false;\n }\n try {\n ch.writeAndFlush(msg).sync();\n return true;\n } catch (InterruptedException e) {", "score": 14.519112878483899 } ]
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/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": 20.97433224622056 }, { "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": 19.318630378521064 }, { "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": 19.31208118354151 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/util/ByteUtil.java", "retrieved_chunk": " oos.close();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n return bytes;\n }\n private ByteUtil(){}\n}", "score": 19.180687832278743 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/util/ByteUtil.java", "retrieved_chunk": " oos.writeObject(obj);\n bytes = out.toByteArray();\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n try {\n out.reset();\n out.close();\n if(null != oos){\n oos.reset();", "score": 18.783029764047047 } ]
java
requestHeader.getLength()){
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/Base.java", "retrieved_chunk": " {\n return this.threadName;\n }\n public Boolean isForum()\n {\n return this.threadName != null;\n }\n @Override\n public Boolean build() {\n if (this.getAvatar() != null && !Loader.getInstance().isValidUrl(this.getAvatar())) return false;", "score": 28.37865408897582 }, { "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": 27.904813003542444 }, { "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": 24.28510589895403 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/EmbedManager.java", "retrieved_chunk": " }\n public EmbedManager setThumbnail(Thumbnail thumbnail) {\n if (!thumbnail.build()) {\n throw new BodyException(\"Thumbnail is invalid: \" + thumbnail);\n } else this.thumbnail = thumbnail;\n return this;\n }\n public EmbedManager removeThumbnail() {\n this.thumbnail = null;\n return this;", "score": 23.709919013691152 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/EmbedManager.java", "retrieved_chunk": " }\n public EmbedManager setAuthor(Author author) {\n if (!author.build()) {\n throw new BodyException( \"Author is invalid: \" + author);\n } else this.author = author;\n return this;\n }\n public EmbedManager removeAuthor() {\n this.author = null;\n return this;", "score": 23.709919013691152 } ]
java
()) && this.getBody().build()) {
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/service/ProvideSpi.java", "retrieved_chunk": " public void init(){\n if(!isInit){\n synchronized (this){\n if(!isInit){\n ConfPool confPool = ConfPool.getInstance();\n LintConf lintConf = confPool.get();\n ServiceLoader<IProvideService> loader = ServiceLoader.load(IProvideService.class);\n for (IProvideService ps : loader) {\n if (!lintConf.getProvideSpiType().equals(ps.getType())) {\n continue;", "score": 37.63721040558879 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ClientPool.java", "retrieved_chunk": " // 连接池\n private final Map<String, LinkedHashSet<NettyClient>> groupPool = new ConcurrentHashMap<>();\n private final Map<String, LinkedHashSet<String>> servicePool = new ConcurrentHashMap<>();\n private final ReentrantLock rLock = new ReentrantLock();\n public NettyClient get(String serviceName, ILoadBalancePolicy loadBalancePolicy){\n ConfPool confPool = ConfPool.getInstance();\n LintConf lintConf = confPool.get();\n ProvideSpi provideSpi = ProvideSpi.getInstance();\n LinkedHashSet<InetSocketAddress> addressSet =\n provideSpi.getAddressByServiceName(serviceName);", "score": 26.767082685811896 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/bootstrap/LintRpcClientApplication.java", "retrieved_chunk": " public static void run(LintConf conf, Class<?> baseClazz){\n if (null == conf\n || null == conf.getProvideSpiType() || \"\".equals(conf.getProvideSpiType())){\n throw new RpcException(RpcMsg.EXCEPTION_NOT_SET_CONF);\n }\n // 1. 加载全局配置\n ConfPool confPool = ConfPool.getInstance();\n confPool.init(conf);\n // 2. 加载SPI 并初始化\n ProvideSpi provideSpi = ProvideSpi.getInstance();", "score": 24.44538006742375 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/bootstrap/LintRpcServerApplication.java", "retrieved_chunk": " * Lint RPC 启动器\n */\npublic class LintRpcServerApplication {\n public static void run(int port, LintConf conf, Class<?> baseClazz){\n if (null == conf\n || null == conf.getProvideSpiType() || \"\".equals(conf.getProvideSpiType())){\n throw new RpcException(RpcMsg.EXCEPTION_NOT_SET_CONF);\n }\n // 1. 加载全局配置\n ConfPool confPool = ConfPool.getInstance();", "score": 21.122193360207774 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ConfPool.java", "retrieved_chunk": " }\n public LintConf get(){\n return LINT_CONF_ATOMIC_REFERENCE.get();\n }\n private static class LazyHolder {\n private static final ConfPool INSTANCE = new ConfPool();\n }\n public static ConfPool getInstance() {\n return ConfPool.LazyHolder.INSTANCE;\n }", "score": 18.895133950706878 } ]
java
.getRequestId(), lintConf.getRequestWaitTimeBySeconds());
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": " 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": 17.56225367705057 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/components/Thumbnail.java", "retrieved_chunk": "package com.ialdrich23xx.libasynwebhook.api.discord.body.embed.components;\nimport com.ialdrich23xx.libasynwebhook.api.discord.body.embed.base.Structure;\nimport com.ialdrich23xx.libasynwebhook.api.discord.body.embed.base.URL;\nimport java.util.Map;\npublic class Thumbnail extends Structure implements URL {\n public Thumbnail(String url) {\n this.setUrl(url);\n }\n public static Thumbnail make(String url) {\n return new Thumbnail(url);", "score": 15.968573539470423 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/components/Image.java", "retrieved_chunk": "package com.ialdrich23xx.libasynwebhook.api.discord.body.embed.components;\nimport com.ialdrich23xx.libasynwebhook.api.discord.body.embed.base.Structure;\nimport com.ialdrich23xx.libasynwebhook.api.discord.body.embed.base.URL;\nimport java.util.Map;\npublic class Image extends Structure implements URL {\n public Image(String url) {\n this.setUrl(url);\n }\n public static Image make(String url) {\n return new Image(url);", "score": 15.968573539470423 }, { "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": 14.512608817966244 }, { "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": 14.511967246041854 } ]
java
.getBody().toJson().getBytes());
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": 75.71475605471068 }, { "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": 58.02990773683456 }, { "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": 54.137051242599306 }, { "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": 51.488220269518735 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/base/Structure.java", "retrieved_chunk": " }\n public String getIcon() {\n if (!(this instanceof IconURL)) throw new BodyException(\"Error this class not implements IconURL\");\n return this.icon;\n }\n public Map<String, Object> iconToArray() {\n if (!(this instanceof IconURL)) throw new BodyException(\"Error this class not implements IconURL\");\n Map<String, Object> result = new HashMap<>();\n result.put(\"icon_url\", this.getIcon());\n return result;", "score": 46.4955836988325 } ]
java
(embed.toArray().entrySet())));
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": 75.68298026672753 }, { "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": 75.68298026672753 }, { "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": 75.68298026672753 }, { "filename": "src/main/java/com/utils/InteractionApi/TileObjectInteraction.java", "retrieved_chunk": "\t\treturn TileObjects.search().withName(name).first().flatMap(tileObject ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tObjectPackets.queueObjectAction(tileObject, false, 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{\n\t\treturn TileObjects.search().withId(id).first().flatMap(tileObject ->", "score": 58.0002711929717 }, { "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": 56.909406861291785 } ]
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/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": 100.40458632803521 }, { "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": 100.40458632803521 }, { "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": 75.68240658868916 }, { "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": 74.57061174238274 }, { "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": 74.57061174238274 } ]
java
return Bank.search().indexIs(index).first().flatMap(item -> {
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": 29.46207280857805 }, { "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": 25.78864489180156 }, { "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": 25.78864489180156 }, { "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": 25.78864489180156 }, { "filename": "src/main/java/org/easycontactforms/core/services/MailingService.java", "retrieved_chunk": " if(resendOnlyNotSendMails){\n List<ContactForm> forms = contactFormService.getContactForms(true);\n for (ContactForm contactForm : forms){\n MailSendThread thread = new MailSendThread(contactFormService, this, contactForm);\n thread.start();\n }\n }\n }\n}", "score": 23.29172075599507 } ]
java
return repository.findByEmailSent(false);
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": 85.42850681691166 }, { "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": 80.44964678055327 }, { "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": 80.44964678055327 }, { "filename": "src/main/java/com/utils/InteractionApi/BankInteraction.java", "retrieved_chunk": "\t\treturn Bank.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 Bank.search().filter(predicate).first().flatMap(item ->", "score": 80.44964678055327 }, { "filename": "src/main/java/com/utils/InteractionApi/TileObjectInteraction.java", "retrieved_chunk": "\t\treturn TileObjects.search().withName(name).first().flatMap(tileObject ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tObjectPackets.queueObjectAction(tileObject, false, 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{\n\t\treturn TileObjects.search().withId(id).first().flatMap(tileObject ->", "score": 61.85154604288516 } ]
java
Players.search().filter(predicate).first().flatMap(Player -> {
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": " * reloads all plugins from source\n */\n private void reloadPlugins(){\n String pluginsPath = \"plugins\";\n EasyContactFormsApplication.loadPlugins(pluginsPath);\n plugins = priorities();\n //Starts all plugins\n for (String key : PluginStore.instance.plugins.keySet()) {\n PluginStore.instance.plugins.get(key).onStartup();\n }", "score": 42.231626257416956 }, { "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": 25.985711005905692 }, { "filename": "src/main/java/org/easycontactforms/core/pluginloader/PluginLoader.java", "retrieved_chunk": "import java.util.*;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport static java.util.Objects.requireNonNull;\n/**\n * Initial Loader for Plugins\n */\n@Slf4j\npublic class PluginLoader {\n private final Map<String, PluginFactory> fooFactoryMap = new HashMap<>();\n private final File pluginsDir;", "score": 24.842063226334503 }, { "filename": "src/main/java/org/easycontactforms/core/pluginloader/PluginLoader.java", "retrieved_chunk": " private final AtomicBoolean loading = new AtomicBoolean();\n public PluginLoader(final File pluginsDir) {\n this.pluginsDir = pluginsDir;\n }\n public void loadPlugins() {\n if (!pluginsDir.exists() || !pluginsDir.isDirectory()) {\n log.error(\"Skipping Plugin Loading. Plugin dir not found: \" + pluginsDir);\n return;\n }\n if (loading.compareAndSet(false, true)) {", "score": 22.726316059764 }, { "filename": "src/main/java/org/easycontactforms/core/pluginloader/PluginLoader.java", "retrieved_chunk": " }\n }\n public PluginFactory getPluginFactory(String name) {\n return fooFactoryMap.get(name);\n }\n public Map<String,PluginFactory> getPluginFactories() {\n return fooFactoryMap;\n }\n}", "score": 22.421926300772686 } ]
java
= pluginLoader.getPluginFactories();
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/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": 100.40458632803521 }, { "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": 100.40458632803521 }, { "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": 75.68240658868916 }, { "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": 74.57061174238274 }, { "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": 74.57061174238274 } ]
java
BankInventory.search().indexIs(index).first().flatMap(item -> {
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": " CommandHandler handler = new CommandHandler(null, null);\n boolean result = handler.onCommand(\"shutdown\", \"shutdown\",\"asdf\");\n Assertions.assertTrue(result);\n }\n @Test\n public void testInvalidCommand(){\n CommandHandler handler = new CommandHandler(null, null);\n boolean result = handler.onCommand(\"asdfa\", \"asdfa\",\"asdf\");\n Assertions.assertFalse(result);\n }", "score": 40.208390020214324 }, { "filename": "src/main/java/org/easycontactforms/core/commandhandler/CommandHandler.java", "retrieved_chunk": " }\n /**\n * executes basic internal commands from command line\n * @param command executed command\n * @param args command line arguments\n * @return true if command is internal, else false\n */\n private boolean internalCommands(String command, String... args) {\n if (command.equalsIgnoreCase(\"stop\")) {\n System.exit(0);", "score": 33.893467731312896 }, { "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": 33.15680274079448 }, { "filename": "PluginAPI/src/main/java/org/easycontactforms/api/Plugin.java", "retrieved_chunk": " * @return true if processing is finished and other plugins can access;\n */\n boolean onMailSent(ContactForm contactForm);\n /**\n * Is executed if a command on the command line interface could not be recognized as internal command\n * @param command command entered (args[0])\n * @param args all arguments including the command\n * @return true if command could be processed by the method, this blocks following plugins from processing it.\n */\n boolean onCommand(String command, String... args);", "score": 32.17274869357421 }, { "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": 30.067945268048263 } ]
java
handler.onCommand(command, arguments);
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\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": 80.96167394219046 }, { "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": 80.96167394219046 }, { "filename": "src/main/java/com/utils/InteractionApi/BankInteraction.java", "retrieved_chunk": "\t\treturn Bank.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 Bank.search().filter(predicate).first().flatMap(item ->", "score": 80.96167394219046 }, { "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": 80.7092788385093 }, { "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": 68.63933998777155 } ]
java
NPCs.search().filter(predicate).first().flatMap(npc -> {
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": "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": 30.694858072239487 }, { "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": 23.62653661081239 }, { "filename": "PluginAPI/src/main/java/org/easycontactforms/api/Plugin.java", "retrieved_chunk": " /**\n * Executed on Startup of Server\n * @return true if successful; false on error\n */\n boolean onStartup();\n /**\n * Executed when all plugins are loaded\n * @return true if successful; false on error\n */\n boolean onLoad();", "score": 15.211679069085775 }, { "filename": "PluginAPI/src/main/java/org/easycontactforms/api/Plugin.java", "retrieved_chunk": " * @return true if processing is finished and other plugins can access;\n */\n boolean onMailSent(ContactForm contactForm);\n /**\n * Is executed if a command on the command line interface could not be recognized as internal command\n * @param command command entered (args[0])\n * @param args all arguments including the command\n * @return true if command could be processed by the method, this blocks following plugins from processing it.\n */\n boolean onCommand(String command, String... args);", "score": 13.171222130531977 }, { "filename": "PluginAPI/src/main/java/org/easycontactforms/api/Plugin.java", "retrieved_chunk": " /**\n * Executed before stopping the server\n * @return true if successful; false on error\n */\n boolean onTeardown();\n /**\n * Is called before any processing happens\n * @param contactForm the contact form sent\n * @return true if processing is finished and other plugins can access; false cancels all other plugin executions after this plugin\n */", "score": 12.654687921535894 } ]
java
EasyContactFormsApplication.loadPlugins(pluginsPath);
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": "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": 35.10261071987851 }, { "filename": "src/main/java/com/utils/HypsApiPlugin/EquipmentItemQuery.java", "retrieved_chunk": "\tpublic EquipmentItemQuery matchesWildCardNoCase(String input)\n\t{\n\t\titems =\n\t\t\t\titems.stream().\n\t\t\t\t\t\tfilter(item -> WildcardMatcher.matches(input.toLowerCase(), Text.removeTags(item.getName().toLowerCase()))).\n\t\t\t\t\t\tcollect(Collectors.toList());\n\t\treturn this;\n\t}\n\tpublic boolean empty()\n\t{", "score": 21.46548300727234 }, { "filename": "src/main/java/com/utils/HypsApiPlugin/EquipmentItemWidget.java", "retrieved_chunk": "\t}\n\t@Override\n\tpublic Object[] getOnVarTransmitListener()\n\t{\n\t\treturn new Object[0];\n\t}\n\t@Override\n\tpublic void setOnVarTransmitListener(Object... args)\n\t{\n\t}", "score": 19.876346128803856 }, { "filename": "src/main/java/com/utils/HypsApiPlugin/EquipmentItemWidget.java", "retrieved_chunk": "\tpublic void setOnReleaseListener(Object... args)\n\t{\n\t}\n\t@Override\n\tpublic void setOnDragCompleteListener(Object... args)\n\t{\n\t}\n\t@Override\n\tpublic void setOnDragListener(Object... args)\n\t{", "score": 19.160305143335083 }, { "filename": "src/main/java/com/utils/HypsApiPlugin/EquipmentItemWidget.java", "retrieved_chunk": "\tpublic void setOnOpListener(Object... args)\n\t{\n\t}\n\t@Override\n\tpublic void setOnDialogAbortListener(Object... args)\n\t{\n\t}\n\t@Override\n\tpublic void setOnKeyListener(Object... args)\n\t{", "score": 19.160305143335083 } ]
java
BufferMethods.du(buffer, (Integer) input);
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": 33.15034170030831 }, { "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": 31.919550464560277 }, { "filename": "src/main/java/org/easycontactforms/core/services/MailSendThread.java", "retrieved_chunk": " for (String key : PluginStore.instance.plugins.keySet()) {\n PluginStore.instance.plugins.get(key).onMailSent(new org.easycontactforms.api.models.ContactForm(contactForm.getId(), contactForm.getName(), contactForm.getEmail(), contactForm.getSubject(), contactForm.getMessage()));\n }\n }\n}", "score": 28.72551374179114 }, { "filename": "src/main/java/org/easycontactforms/core/commandhandler/CommandHandler.java", "retrieved_chunk": " return true;\n } else if (command.equalsIgnoreCase(\"reloadplugins\")) {\n reloadPlugins();\n return true;\n } else if (command.equalsIgnoreCase(\"reloadspring\")) {\n SpringApplication.exit(context);\n this.context = SpringApplication.run(EasyContactFormsApplication.class, this.baseArgs);\n return true;\n } else if (command.equalsIgnoreCase(\"reload\")) {\n SpringApplication.exit(context);", "score": 26.47483136494544 }, { "filename": "src/main/java/org/easycontactforms/core/services/ContactFormService.java", "retrieved_chunk": " /**\n * updates single instance in database\n * @param contactForm changed object\n * @return result from database\n */\n public ContactForm updateContactForm(ContactForm contactForm){\n repository.save(contactForm);\n return contactForm;\n }\n public List<ContactForm> getContactForms(boolean onlyNotSendEmails){", "score": 26.29143809313944 } ]
java
<ContactForm> forms = contactFormService.getContactForms(true);
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": " 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": 37.186350845181664 }, { "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": 34.379104149451884 }, { "filename": "common/src/main/java/com/blamejared/searchables/lang/SLParser.java", "retrieved_chunk": " }\n }\n if(match(TokenType.IDENTIFIER)) {\n Token previous = previous();\n if(check(TokenType.COLON)) {\n return new ComponentExpression(new LiteralExpression(previous.literal(), previous.lexeme()), advance(), literal());\n }\n return new LiteralExpression(previous.literal(), previous.lexeme());\n }\n if(match(TokenType.STRING)) {", "score": 34.06570711407013 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/TokenRange.java", "retrieved_chunk": " }\n @Override\n public int compareTo(@NotNull final TokenRange o) {\n return Integer.compare(this.start(), o.start());\n }\n @NotNull\n @Override\n public Iterator<TokenRange> iterator() {\n return this.subRanges().iterator();\n }", "score": 30.73693461908523 }, { "filename": "common/src/main/java/com/blamejared/searchables/lang/SLParser.java", "retrieved_chunk": " Token previous = previous();\n return new LiteralExpression(previous.literal(), previous.lexeme());\n }\n return new LiteralExpression(\"\", \"\");\n }\n private boolean match(final TokenType... types) {\n for(TokenType type : types) {\n if(check(type)) {\n advance();\n return true;", "score": 30.434527108015985 } ]
java
lastRange.covers(previous)) {
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/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": 46.7027738245923 }, { "filename": "src/main/java/com/utils/AutoTele/AutoTele.java", "retrieved_chunk": "\t\t\trowEquipment = client.getItemContainer(InventoryID.EQUIPMENT).getItem(EquipmentInventorySlot.RING.getSlotIdx());\n\t\t}\n\t\tif ((rowEquipment != null && !RING_OF_WEALTH_ITEM_IDS.contains(rowEquipment.getId())))\n\t\t{\n\t\t\trowEquipment = null;\n\t\t}\n\t\tif (level > -1)\n\t\t{\n\t\t\tif (previousLevel == -1)\n\t\t\t{", "score": 32.896263457108425 }, { "filename": "src/main/java/com/utils/HypsApiPlugin/BankInventory.java", "retrieved_chunk": "//\t\t\t\t\t\t{\n//\t\t\t\t\t\t\tif (HypsApiPlugin.testBit(client.getVarps()[262], 5))\n//\t\t\t\t\t\t\t{\n//\t\t\t\t\t\t\t\tdefaultAction = \"Fill\";\n//\t\t\t\t\t\t\t}\n//\t\t\t\t\t\t}\n//\t\t\t\t\t\telse if (HypsApiPlugin.testBit(client.getVarps()[262], counter))\n//\t\t\t\t\t\t{\n//\t\t\t\t\t\t\tInteger tempActionIndex = StaticItemInfo.extraActionIndex.get(item.getId());\n//\t\t\t\t\t\t\tif (tempActionIndex != null)", "score": 30.60160752739069 }, { "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": 29.188827816043762 }, { "filename": "src/main/java/com/utils/HypsApiPlugin/BankInventory.java", "retrieved_chunk": "//\t\t\t\t\t\t}\n//\t\t\t\t\t\telse if (item.getId() == ItemID.MEDIUM_POUCH || item.getId() == ItemID.MEDIUM_POUCH_5511)\n//\t\t\t\t\t\t{\n//\t\t\t\t\t\t\tif (HypsApiPlugin.testBit(client.getVarps()[261], 1))\n//\t\t\t\t\t\t\t{\n//\t\t\t\t\t\t\t\tdefaultAction = \"Empty\";\n//\t\t\t\t\t\t\t}\n//\t\t\t\t\t\t}\n//\t\t\t\t\t\telse if (item.getId() == ItemID.LARGE_POUCH || item.getId() == ItemID.LARGE_POUCH_5513)\n//\t\t\t\t\t\t{", "score": 29.06055763115007 } ]
java
Widget bow = HypsApiPlugin.getItem("*bow*");
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": " 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": 44.57464324581734 }, { "filename": "common/src/main/java/com/blamejared/searchables/lang/SLParser.java", "retrieved_chunk": " }\n }\n if(match(TokenType.IDENTIFIER)) {\n Token previous = previous();\n if(check(TokenType.COLON)) {\n return new ComponentExpression(new LiteralExpression(previous.literal(), previous.lexeme()), advance(), literal());\n }\n return new LiteralExpression(previous.literal(), previous.lexeme());\n }\n if(match(TokenType.STRING)) {", "score": 41.23380974922495 }, { "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": 39.09238244899971 }, { "filename": "common/src/main/java/com/blamejared/searchables/lang/SLParser.java", "retrieved_chunk": " Token previous = previous();\n return new LiteralExpression(previous.literal(), previous.lexeme());\n }\n return new LiteralExpression(\"\", \"\");\n }\n private boolean match(final TokenType... types) {\n for(TokenType type : types) {\n if(check(type)) {\n advance();\n return true;", "score": 37.15942017129672 }, { "filename": "common/src/main/java/com/blamejared/searchables/lang/SLParser.java", "retrieved_chunk": " return tokens.get(current);\n }\n private Token previous() {\n return tokens.get(current - 1);\n }\n}", "score": 35.24976229377346 } ]
java
lastRange.addRange(previous);
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/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": 52.47507614514972 }, { "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": 52.324887841402486 }, { "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": 50.30176901081002 }, { "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": 39.76221339571743 }, { "filename": "src/main/java/com/utils/InteractionApi/BankInteraction.java", "retrieved_chunk": "\t\treturn Bank.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 Bank.search().filter(predicate).first().flatMap(item ->", "score": 39.76221339571743 } ]
java
<Widget> ring_of_wealth = Inventory.search().nameContains("Ring of wealth (").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": " .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": 73.88939374557492 }, { "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": 65.22567328532884 }, { "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": 63.68189021859928 }, { "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": 57.92441299829278 }, { "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": 48.24342392716155 } ]
java
tokens.add(range.recalculate());
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/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": 26.98592930725699 }, { "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": 26.382684118152188 }, { "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": 25.362609212252956 }, { "filename": "src/main/java/com/utils/HypsApiPlugin/ItemQuery.java", "retrieved_chunk": "\t\treturn items;\n\t}\n\tpublic Optional<Widget> first() {\n\t\tWidget returnWidget = null;\n\t\tif (items.size() == 0) {\n\t\t\treturn Optional.ofNullable(null);\n\t\t}\n\t\treturn Optional.ofNullable(items.get(0));\n\t}\n\t@SneakyThrows", "score": 20.662039295934797 }, { "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": 20.62949793254084 } ]
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/lang/StringSearcher.java", "retrieved_chunk": " .map(expression -> expression.accept(visitor, context))\n .map(t -> visitor.postVisit(t, context));\n }\n /**\n * Parses the string and returns and optional {@link Expression}\n *\n * @param search The string to search.\n *\n * @return The string as an optional {@link Expression}\n */", "score": 33.76397382848509 }, { "filename": "common/src/main/java/com/blamejared/searchables/lang/StringSearcher.java", "retrieved_chunk": " * @param visitor The visitor to visit.\n *\n * @return The optional result of the visitor.\n */\n public static <T> Optional<T> search(final String search, final Visitor<T> visitor) {\n SLParser slParser = new SLParser(new SLScanner(search).scanTokens());\n return slParser.parse().map(expression -> expression.accept(visitor)).map(visitor::postVisit);\n }\n /**\n * Parses the string and visits the given visitor with context.", "score": 32.978592626417985 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/SearchableComponent.java", "retrieved_chunk": " /**\n * Creates a component from the given values.\n *\n * @param key The key for this term.\n * @param toString a {@link Function} to convert a given {@code T} to an {@link Optional<String>}, used to display the \"name\" of an element for auto-complete\n * @param filter a {@link BiPredicate} to filter the element ({@code T}) and the given search String\n * @param <T> The type of element that this {@link SearchableComponent<T>} handles.\n *\n * @return a new {@link SearchableComponent<T>} from the given values.\n */", "score": 32.909643741974115 }, { "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": 32.77836495651975 }, { "filename": "common/src/main/java/com/blamejared/searchables/lang/StringSearcher.java", "retrieved_chunk": " *\n * @param search The string to search.\n * @param visitor The visitor to visit.\n * @param context The extra context for the visitor.\n *\n * @return The optional result of the visitor.\n */\n public static <T, C> Optional<T> search(final String search, final ContextAwareVisitor<T, C> visitor, final C context) {\n SLParser slParser = new SLParser(new SLScanner(search).scanTokens());\n return slParser.parse()", "score": 31.39972197273133 } ]
java
StringSearcher.search(search, this);
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/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": 31.869835974917265 }, { "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": 26.382684118152188 }, { "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": 25.51340460020112 }, { "filename": "src/main/java/com/utils/InteractionApi/BankInteraction.java", "retrieved_chunk": "\t\treturn Bank.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 Bank.search().filter(predicate).first().flatMap(item ->", "score": 25.51340460020112 }, { "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": 25.362609212252956 } ]
java
> widget = Inventory.search().withId(ItemID.ROYAL_SEED_POD).first();
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/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": 30.025040187237668 }, { "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": 25.873169619311795 }, { "filename": "src/main/java/com/jessetzh/parameters/SdParameter.java", "retrieved_chunk": "\tpublic SdParameter(String url) {\n\t\tthis.basicParameter = new BasicParameter(url);\n\t}\n}", "score": 24.070021316632058 }, { "filename": "src/main/java/com/jessetzh/parameters/SdParameter.java", "retrieved_chunk": "\t\tthis.basicParameter = basicParameter;\n\t}\n\tpublic String getPrompt() {\n\t\treturn prompt;\n\t}\n\tpublic void setPrompt(String prompt) {\n\t\tthis.prompt = prompt;\n\t}\n\tpublic SdParameter() {\n\t}", "score": 22.408098626167124 }, { "filename": "src/main/java/com/jessetzh/parameters/SdParameter.java", "retrieved_chunk": "\tpublic String getNegativePrompt() {\n\t\treturn negativePrompt;\n\t}\n\tpublic void setNegativePrompt(String negativePrompt) {\n\t\tthis.negativePrompt = negativePrompt;\n\t}\n\tpublic BasicParameter getBasicParameter() {\n\t\treturn basicParameter;\n\t}\n\tpublic void setBasicParameter(BasicParameter basicParameter) {", "score": 21.12831010288068 } ]
java
basicParameter.getApiUrl() == null) {
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": 35.07486119947328 }, { "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": 29.566189145893333 }, { "filename": "dagger-java-sdk/src/test/java/org/chelonix/dagger/client/engineconn/ConnectionTest.java", "retrieved_chunk": "import static org.mockito.Mockito.*;\n@ExtendWith(SystemStubsExtension.class)\npublic class ConnectionTest {\n @SystemStub\n private EnvironmentVariables environmentVariables;\n @Test\n public void should_return_from_env_connection() throws Exception {\n environmentVariables.set(\"DAGGER_SESSION_PORT\", \"52037\");\n environmentVariables.set(\"DAGGER_SESSION_TOKEN\", \"189de95f-07df-415d-b42a-7851c731359d\");\n Optional<Connection> conn = Connection.fromEnv();", "score": 26.975049469877423 }, { "filename": "dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/CLIRunner.java", "retrieved_chunk": " });\n } catch (RuntimeException e) {\n if (!(e.getCause() instanceof IOException\n && \"Stream closed\".equals(e.getCause().getMessage()))) {\n LOG.error(e.getMessage(), e);\n setFailed();\n throw e;\n }\n }\n }", "score": 24.218382915723712 }, { "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": 23.927252967719035 } ]
java
cliRunner.start();
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/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": 64.5848874871132 }, { "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": 62.27498407673196 }, { "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": 59.8671491408529 }, { "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": 51.87202473768092 }, { "filename": "src/main/java/com/utils/InteractionApi/BankInteraction.java", "retrieved_chunk": "\t\treturn Bank.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 Bank.search().filter(predicate).first().flatMap(item ->", "score": 51.87202473768092 } ]
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": 28.471889321923417 }, { "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": 24.26645541680707 }, { "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": 21.001915340060012 }, { "filename": "dagger-java-sdk/src/main/java/org/chelonix/dagger/client/Dagger.java", "retrieved_chunk": "package org.chelonix.dagger.client;\nimport org.chelonix.dagger.client.engineconn.Connection;\nimport java.io.IOException;\npublic class Dagger {\n /**\n * Opens connection with a Dagger engine.\n * @return The Dagger API entrypoint\n * @throws IOException\n */\n public static Client connect() throws IOException {", "score": 20.789398520717327 }, { "filename": "dagger-java-sdk/src/main/java/org/chelonix/dagger/client/Dagger.java", "retrieved_chunk": " return connect(System.getProperty(\"user.dir\"));\n }\n /**\n * Opens connection with a Dagger engine.\n * @param workingDir the host working directory\n * @return The Dagger API entrypoint\n * @throws IOException\n */\n public static Client connect(String workingDir) throws IOException {\n return new Client(Connection.get(workingDir));", "score": 20.288920569797163 } ]
java
connectParams = cliRunner.getConnectionParams();
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-codegen-maven-plugin/src/main/java/org/chelonix/dagger/codegen/DaggerCodegenMojo.java", "retrieved_chunk": " throw new MojoFailureException(String.format(\"GraphQL schema not available for version %s\", version));\n }\n return in;\n }\n if (introspectionQuertyPath != null) {\n return new FileInputStream(introspectionQuertyPath);\n }\n InputStream in;\n if (introspectionQuertyPath != null) {\n return new FileInputStream(introspectionQuertyPath);", "score": 44.13324100872903 }, { "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": 36.60459581258687 }, { "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": 34.130417234172356 }, { "filename": "dagger-java-samples/src/main/java/org/chelonix/dagger/sample/RunContainer.java", "retrieved_chunk": " .withExec(List.of(\"mvn\", \"--version\"));\n String version = container.stdout();\n System.out.println(\"Hello from Dagger and \" + version);\n }\n }\n}", "score": 26.737730171803967 }, { "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": 26.299983246644928 } ]
java
(BufferedInputStream in = new BufferedInputStream(fetcher.fetch(checksumMapURL))) {
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/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": 28.734653426727487 }, { "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": 28.734653426727487 }, { "filename": "src/main/java/com/jessetzh/handler/BasicParameterHandler.java", "retrieved_chunk": " * Basic parameter validation.\n */\npublic class BasicParameterHandler {\n public static void check(BasicParameter basicParameter, HttpClientBuilder builder) {\n if (basicParameter.isAuthEnable()) {\n if (basicParameter.getUser() == null || basicParameter.getPassword() == null) {\n throw new StableDiffusionException(\"The username and password cannot be empty when authentication is enabled!\");\n }\n // Identity verification information\n CredentialsProvider provider = new BasicCredentialsProvider();", "score": 13.38352754394766 }, { "filename": "src/main/java/com/jessetzh/parameters/SdParameter.java", "retrieved_chunk": "\t}\n\tpublic void setSamplerName(String samplerName) {\n\t\tthis.samplerName = samplerName;\n\t}\n\tpublic int getSteps() {\n\t\treturn steps;\n\t}\n\tpublic void setSteps(int steps) {\n\t\tthis.steps = steps;\n\t}", "score": 9.484478761611847 }, { "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": 5.991611030034307 } ]
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": 21.63125957157821 }, { "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": 18.797776722572866 }, { "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": 12.801664021581677 }, { "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": 10.030903101808718 }, { "filename": "src/main/java/com/jessetzh/handler/BasicParameterHandler.java", "retrieved_chunk": " * Basic parameter validation.\n */\npublic class BasicParameterHandler {\n public static void check(BasicParameter basicParameter, HttpClientBuilder builder) {\n if (basicParameter.isAuthEnable()) {\n if (basicParameter.getUser() == null || basicParameter.getPassword() == null) {\n throw new StableDiffusionException(\"The username and password cannot be empty when authentication is enabled!\");\n }\n // Identity verification information\n CredentialsProvider provider = new BasicCredentialsProvider();", "score": 9.641561661915594 } ]
java
parameter.setDenoisingStrength(new BigDecimal("0.55"));
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": 29.00304660724599 }, { "filename": "dagger-java-sdk/src/main/java/org/chelonix/dagger/client/Dagger.java", "retrieved_chunk": "package org.chelonix.dagger.client;\nimport org.chelonix.dagger.client.engineconn.Connection;\nimport java.io.IOException;\npublic class Dagger {\n /**\n * Opens connection with a Dagger engine.\n * @return The Dagger API entrypoint\n * @throws IOException\n */\n public static Client connect() throws IOException {", "score": 24.168938061015087 }, { "filename": "dagger-java-sdk/src/main/java/org/chelonix/dagger/client/Dagger.java", "retrieved_chunk": " return connect(System.getProperty(\"user.dir\"));\n }\n /**\n * Opens connection with a Dagger engine.\n * @param workingDir the host working directory\n * @return The Dagger API entrypoint\n * @throws IOException\n */\n public static Client connect(String workingDir) throws IOException {\n return new Client(Connection.get(workingDir));", "score": 23.374305815879712 }, { "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": 22.339999687669952 }, { "filename": "dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/CLIRunner.java", "retrieved_chunk": " .withAllowedExitCodes(137);\n this.executorService = Executors.newSingleThreadExecutor(r -> new Thread(r, \"dagger-runner\"));\n }\n synchronized ConnectParams getConnectionParams() throws IOException {\n while (params == null) {\n try {\n if (failed) {\n throw new IOException(\"Could not connect to Dagger engine\");\n }\n wait();", "score": 20.80805721142408 } ]
java
cliRunner.shutdown();
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": " .withAllowedExitCodes(137);\n this.executorService = Executors.newSingleThreadExecutor(r -> new Thread(r, \"dagger-runner\"));\n }\n synchronized ConnectParams getConnectionParams() throws IOException {\n while (params == null) {\n try {\n if (failed) {\n throw new IOException(\"Could not connect to Dagger engine\");\n }\n wait();", "score": 24.424004513428656 }, { "filename": "dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/Connection.java", "retrieved_chunk": " LOG.error(\"DAGGER_SESSION_TOKEN is required when using DAGGER_SESSION_PORT\");\n } else if (sessionToken == null) {\n LOG.error(\"DAGGER_SESSION_PORT is required when using DAGGER_SESSION_TOKEN\");\n }\n return Optional.empty();\n }\n static Connection fromCLI(CLIRunner cliRunner) throws IOException {\n LOG.info(\"Trying initializing connection with engine from automatic provisioning...\");\n try {\n cliRunner.start();", "score": 23.573636975573407 }, { "filename": "dagger-codegen-maven-plugin/src/main/java/org/chelonix/dagger/codegen/DaggerCodegenMojo.java", "retrieved_chunk": " @Override\n public void visitEnum(Type type) {\n getLog().info(String.format(\"Generating enum %s\", type.getName()));\n codegen.visitEnum(type);\n }\n });\n } catch (IOException ioe) {\n throw new MojoFailureException(ioe);\n } catch (InterruptedException ie) {\n throw new MojoFailureException(ie);", "score": 22.00231941785701 }, { "filename": "dagger-codegen-maven-plugin/src/main/java/org/chelonix/dagger/codegen/DaggerCodegenMojo.java", "retrieved_chunk": " Path dest = outputDir.toPath();\n try (InputStream in = daggerSchema()) {\n Schema schema = Schema.initialize(in);\n SchemaVisitor codegen = new CodegenVisitor(schema, dest, Charset.forName(outputEncoding));\n schema.visit(new SchemaVisitor() {\n @Override\n public void visitScalar(Type type) {\n getLog().info(String.format(\"Generating scala %s\", type.getName()));\n codegen.visitScalar(type);\n }", "score": 21.400638785518275 }, { "filename": "dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/CLIRunner.java", "retrieved_chunk": " if (line.isStdout() && line.line().contains(\"session_token\")) {\n try (JsonReader reader = Json.createReader(new StringReader(line.line()))) {\n JsonObject obj = reader.readObject();\n int port = obj.getInt(\"port\");\n String sessionToken = obj.getString(\"session_token\");\n setParams(new ConnectParams(port, sessionToken));\n }\n } else {\n LOG.info(line.line());\n }", "score": 20.519805000825965 } ]
java
new BufferedInputStream(new DigestInputStream(fetcher.fetch(cliArchiveURL), sha256))) {
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": 31.865117180832435 }, { "filename": "demo-user_service/src/main/java/com/rosan/dhizuku/demo/UserService.java", "retrieved_chunk": " if (!url.isEmpty()) {\n if (url.startsWith(\"http\") || url.startsWith(\"https\")) {\n Uri uri = Uri.parse(url);\n proxy = ProxyInfo.buildPacProxy(uri);\n } else {\n String[] urlElements = url.split(\":\");\n if (urlElements.length != 2) return;\n proxy = ProxyInfo.buildDirectProxy(urlElements[0], Integer.parseInt(urlElements[1]));\n }\n }", "score": 8.94248473325901 }, { "filename": "demo-user_service/src/main/java/com/rosan/dhizuku/demo/MainActivity.java", "retrieved_chunk": " Toast.makeText(this, join(objects), Toast.LENGTH_SHORT).show();\n });\n }\n String join(List<Object> objects) {\n String sep = \" \";\n StringBuilder builder = new StringBuilder();\n int count = 0;\n for (Object element : objects) {\n if (++count > 1) builder.append(\" \");\n builder.append(element == null ? \"null\" : element);", "score": 8.527107516497296 }, { "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": 8.14651360337112 }, { "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": 7.88163688662933 } ]
java
(serviceConnection.isEmpty()) tokens.add(token);