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/model/BaseFile.java", "retrieved_chunk": " public BaseFile() {\n }\n public BaseFile(QueryDocumentSnapshot document, String resourceBasePath) {\n BaseFile file = document.toObject(BaseFile.class);\n BeanUtils.copyProperties(file, this);\n this.setUrl(resourceBasePath + file.getPath());\n this.setThumbUrl(resourceBasePath + file.genThumbnailPath());\n this.setCreateTime(document.getCreateTime().toDate());\n this.setUpdateTime(document.getUpdateTime().toDate());\n }", "score": 0.7812572717666626 }, { "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": 0.7684783935546875 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreService.java", "retrieved_chunk": " *\n * @param fileMeta metadata of the file\n */\n public void save(FileMeta fileMeta) throws InterruptedException, ExecutionException {\n DocumentReference docRef = firestore.collection(collectionName).document(fileMeta.getId());\n docRef.set(fileMeta).get();\n }\n /**\n * Search a file with given fileId.\n *", "score": 0.7672351002693176 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/StorageService.java", "retrieved_chunk": " BlobInfo blobInfo = BlobInfo.newBuilder(bucketName, fileId).setContentType(contentType).build();\n storage.create(blobInfo, content);\n }\n /**\n * Delete a file with given fileId.\n *\n * @param bucketName name of the bucket\n * @param fileId unique id of a file\n */\n public void delete(String bucketName, String fileId) {", "score": 0.7583318948745728 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreService.java", "retrieved_chunk": " * @param fileId unique id of the file\n * @return file data\n */\n public BaseFile getFileById(String fileId) throws InterruptedException, ExecutionException {\n ApiFuture<QuerySnapshot> future =\n firestore.collection(collectionName).whereEqualTo(FieldPath.documentId(), fileId).get();\n List<QueryDocumentSnapshot> documents = future.get().getDocuments();\n if (documents.isEmpty()) {\n return null;\n }", "score": 0.7374258637428284 } ]
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.service; import com.googlecodesamples.cloud.jss.lds.model.BaseFile; import com.googlecodesamples.cloud.jss.lds.model.FileMeta; import com.googlecodesamples.cloud.jss.lds.util.LdsUtil; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import net.coobird.thumbnailator.Thumbnails; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; /** Backend service controller for Firestore and CloudStorage */ @Service public class FileService { private static final Logger log = LoggerFactory.getLogger(FirestoreService.class); private static final int THUMBNAIL_SIZE = 300; private final FirestoreService firestoreService; private final StorageService storageService; @Value("${resource.path}") private String basePath; @Value("${storage.bucket.name}") private String bucketName; public FileService(FirestoreService firestoreService, StorageService storageService) { this.firestoreService = firestoreService; this.storageService = storageService; } /** * Upload files to Firestore and Cloud Storage. * * @param files list of files upload to the server * @param tags list of tags label the files * @return list of uploaded files */ public List<BaseFile> uploadFiles(List<MultipartFile> files, List<String> tags) throws InterruptedException, ExecutionException, IOException { log.info("entering uploadFiles()"); List<BaseFile> fileList = new ArrayList<>(); for (MultipartFile file : files) { String fileId = LdsUtil.generateUuid(); BaseFile newFile = createOrUpdateFile(file, tags, fileId, fileId, file.getSize()); fileList.add(newFile); } return fileList; } /** * Update a file to Firestore and Cloud Storage. * * @param newFile new file upload to the server * @param tags list of tags label the new file * @param file previously uploaded file * @return the updated file */ public BaseFile updateFile(MultipartFile newFile, List<String> tags, BaseFile file) throws InterruptedException, ExecutionException, IOException { log.info("entering updateFile()"); String fileId = file.getId(); if (newFile == null) { String pathId = LdsUtil.getPathId(file.getPath()); return createOrUpdateFileMeta(tags, fileId, pathId, file.getName(), file.getSize()); } storageService.delete(bucketName, file.getPath()); storageService.delete(bucketName, file.genThumbnailPath()); String newFileId = LdsUtil.generateUuid(); return createOrUpdateFile(newFile, tags, fileId, newFileId, newFile.getSize()); } /** * Delete a file from Firestore and Cloud Storage. * * @param file the uploaded file */ public void deleteFile(BaseFile file) throws InterruptedException, ExecutionException { log.info("entering deleteFile()"); firestoreService.delete(file.getId()); storageService.delete(bucketName, file.getPath()); storageService.delete(bucketName, file.genThumbnailPath()); } /** * Search files with given tags. * * @param tags list of tags label the files * @param orderNo application defined column for referencing order * @param size number of files return * @return list of uploaded files */ public List<BaseFile> getFilesByTag(List<String> tags, String orderNo, int size) throws InterruptedException, ExecutionException { log.info("entering getFilesByTag()"); return firestoreService.getFilesByTag(tags, orderNo, size); } /** * Search a single file with given fileId. * * @param fileId unique id of the file * @return the uploaded file */ public BaseFile getFileById(String fileId) throws InterruptedException, ExecutionException { log.info("entering getFileById()"); return firestoreService.getFileById(fileId); } /** Delete all files from Firestore and Cloud Storage. */ public void resetFile() throws InterruptedException, ExecutionException { log.info("entering resetFile()"); firestoreService.deleteCollection(); storageService.batchDelete(bucketName); } /** * Create or update a file in Cloud Storage with the given fileId. * * @param file file upload to the server * @param tags list of tags label the file * @param fileId unique ID of the file * @param newFileId unique ID of the new file (for referencing Cloud Storage) * @param size size of the file * @return file data */ private BaseFile createOrUpdateFile( MultipartFile file, List<String> tags, String fileId, String newFileId, long size) throws InterruptedException, ExecutionException, IOException { BaseFile newFile = createOrUpdateFileMeta(tags, fileId, newFileId, file.getOriginalFilename(), size); storageService.save(bucketName, newFile.getPath(), file.getContentType(), file.getBytes()); if
(newFile.checkImageFileType()) {
createThumbnail(file, newFile.genThumbnailPath()); } return newFile; } /** * Create or update the metadata of a file in Firestore with the given fileId. * * @param tags list of tags label the file * @param fileId unique id of the file * @param newFileId unique id of the new file (for referencing Cloud Storage) * @param fileName name of the file * @param size size of the file * @return file data */ private BaseFile createOrUpdateFileMeta( List<String> tags, String fileId, String newFileId, String fileName, long size) throws InterruptedException, ExecutionException { String fileBucketPath = LdsUtil.getFileBucketPath(basePath, newFileId); FileMeta fileMeta = new FileMeta(fileId, fileBucketPath, fileName, tags, size); firestoreService.save(fileMeta); return getFileById(fileId); } /** * Create a thumbnail of the given file. * * @param file file to create thumbnail * @param thumbnailId unique id of the thumbnail file */ private void createThumbnail(MultipartFile file, String thumbnailId) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Thumbnails.of(file.getInputStream()) .size(THUMBNAIL_SIZE, THUMBNAIL_SIZE) .keepAspectRatio(false) .toOutputStream(byteArrayOutputStream); storageService.save( bucketName, thumbnailId, file.getContentType(), byteArrayOutputStream.toByteArray()); } }
api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FileService.java
GoogleCloudPlatform-app-large-data-sharing-java-fd21141
[ { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreService.java", "retrieved_chunk": " *\n * @param fileMeta metadata of the file\n */\n public void save(FileMeta fileMeta) throws InterruptedException, ExecutionException {\n DocumentReference docRef = firestore.collection(collectionName).document(fileMeta.getId());\n docRef.set(fileMeta).get();\n }\n /**\n * Search a file with given fileId.\n *", "score": 0.8026434183120728 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/StorageService.java", "retrieved_chunk": " BlobInfo blobInfo = BlobInfo.newBuilder(bucketName, fileId).setContentType(contentType).build();\n storage.create(blobInfo, content);\n }\n /**\n * Delete a file with given fileId.\n *\n * @param bucketName name of the bucket\n * @param fileId unique id of a file\n */\n public void delete(String bucketName, String fileId) {", "score": 0.7952708601951599 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/controller/FileController.java", "retrieved_chunk": " * @param fileId unique ID of the file\n * @param file new file to be uploaded to the server\n * @param tags list of tags (separated by space) label the new file\n * @return file data\n */\n @PutMapping(\"/files/{id}\")\n public ResponseEntity<?> updateFile(\n @PathVariable(\"id\") String fileId,\n @RequestParam(required = false) MultipartFile file,\n @RequestParam String tags) throws Exception {", "score": 0.7783534526824951 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/model/BaseFile.java", "retrieved_chunk": " public BaseFile() {\n }\n public BaseFile(QueryDocumentSnapshot document, String resourceBasePath) {\n BaseFile file = document.toObject(BaseFile.class);\n BeanUtils.copyProperties(file, this);\n this.setUrl(resourceBasePath + file.getPath());\n this.setThumbUrl(resourceBasePath + file.genThumbnailPath());\n this.setCreateTime(document.getCreateTime().toDate());\n this.setUpdateTime(document.getUpdateTime().toDate());\n }", "score": 0.7699484825134277 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreService.java", "retrieved_chunk": " * @param fileId unique id of the file\n * @return file data\n */\n public BaseFile getFileById(String fileId) throws InterruptedException, ExecutionException {\n ApiFuture<QuerySnapshot> future =\n firestore.collection(collectionName).whereEqualTo(FieldPath.documentId(), fileId).get();\n List<QueryDocumentSnapshot> documents = future.get().getDocuments();\n if (documents.isEmpty()) {\n return null;\n }", "score": 0.7685577273368835 } ]
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/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": 0.9006263613700867 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/StorageService.java", "retrieved_chunk": " BlobInfo blobInfo = BlobInfo.newBuilder(bucketName, fileId).setContentType(contentType).build();\n storage.create(blobInfo, content);\n }\n /**\n * Delete a file with given fileId.\n *\n * @param bucketName name of the bucket\n * @param fileId unique id of a file\n */\n public void delete(String bucketName, String fileId) {", "score": 0.8858948945999146 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/util/LdsUtil.java", "retrieved_chunk": " String bucketBasePath = StringUtils.trimLeadingCharacter(basePath, URL_SLASH);\n return basePath.substring(0, basePath.length() - bucketBasePath.length());\n }\n /**\n * Get relative path of a file from the base.\n *\n * @param basePath the URL without the file ID\n * @param fileId the ID of the file\n * @return the full URL of the file\n */", "score": 0.8765695095062256 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/controller/FileController.java", "retrieved_chunk": " * @param fileId unique ID of the file\n * @param file new file to be uploaded to the server\n * @param tags list of tags (separated by space) label the new file\n * @return file data\n */\n @PutMapping(\"/files/{id}\")\n public ResponseEntity<?> updateFile(\n @PathVariable(\"id\") String fileId,\n @RequestParam(required = false) MultipartFile file,\n @RequestParam String tags) throws Exception {", "score": 0.8723894357681274 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/StorageService.java", "retrieved_chunk": " storage.delete(bucketName, fileId);\n }\n /**\n * Delete all files in the bucket.\n *\n * @param bucketName name of the bucket\n */\n public void batchDelete(String bucketName) {\n Page<Blob> blobs = storage.list(bucketName);\n if (!blobs.getValues().iterator().hasNext()) {", "score": 0.8590332269668579 } ]
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.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": 0.8093022108078003 }, { "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": 0.7912207841873169 }, { "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": 0.7797397971153259 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FileService.java", "retrieved_chunk": " * @param newFileId unique ID of the new file (for referencing Cloud Storage)\n * @param size size of the file\n * @return file data\n */\n private BaseFile createOrUpdateFile(\n MultipartFile file, List<String> tags, String fileId, String newFileId, long size)\n throws InterruptedException, ExecutionException, IOException {\n BaseFile newFile =\n createOrUpdateFileMeta(tags, fileId, newFileId, file.getOriginalFilename(), size);\n storageService.save(bucketName, newFile.getPath(), file.getContentType(), file.getBytes());", "score": 0.7786922454833984 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FileService.java", "retrieved_chunk": " */\n public BaseFile updateFile(MultipartFile newFile, List<String> tags, BaseFile file)\n throws InterruptedException, ExecutionException, IOException {\n log.info(\"entering updateFile()\");\n String fileId = file.getId();\n if (newFile == null) {\n String pathId = LdsUtil.getPathId(file.getPath());\n return createOrUpdateFileMeta(tags, fileId, pathId, file.getName(), file.getSize());\n }\n storageService.delete(bucketName, file.getPath());", "score": 0.7733883857727051 } ]
java
.orderNo = System.currentTimeMillis() + "-" + LdsUtil.getPathId(path);
/* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.googlecodesamples.cloud.jss.lds.service; import com.googlecodesamples.cloud.jss.lds.model.BaseFile; import com.googlecodesamples.cloud.jss.lds.model.FileMeta; import com.googlecodesamples.cloud.jss.lds.util.LdsUtil; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import net.coobird.thumbnailator.Thumbnails; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; /** Backend service controller for Firestore and CloudStorage */ @Service public class FileService { private static final Logger log = LoggerFactory.getLogger(FirestoreService.class); private static final int THUMBNAIL_SIZE = 300; private final FirestoreService firestoreService; private final StorageService storageService; @Value("${resource.path}") private String basePath; @Value("${storage.bucket.name}") private String bucketName; public FileService(FirestoreService firestoreService, StorageService storageService) { this.firestoreService = firestoreService; this.storageService = storageService; } /** * Upload files to Firestore and Cloud Storage. * * @param files list of files upload to the server * @param tags list of tags label the files * @return list of uploaded files */ public List<BaseFile> uploadFiles(List<MultipartFile> files, List<String> tags) throws InterruptedException, ExecutionException, IOException { log.info("entering uploadFiles()"); List<BaseFile> fileList = new ArrayList<>(); for (MultipartFile file : files) { String fileId = LdsUtil.generateUuid(); BaseFile newFile = createOrUpdateFile(file, tags, fileId, fileId, file.getSize()); fileList.add(newFile); } return fileList; } /** * Update a file to Firestore and Cloud Storage. * * @param newFile new file upload to the server * @param tags list of tags label the new file * @param file previously uploaded file * @return the updated file */ public BaseFile updateFile(MultipartFile newFile, List<String> tags, BaseFile file) throws InterruptedException, ExecutionException, IOException { log.info("entering updateFile()"); String fileId = file.getId(); if (newFile == null) { String pathId = LdsUtil.getPathId(file.getPath()); return createOrUpdateFileMeta(tags, fileId, pathId, file.getName(), file.getSize()); } storageService.delete(bucketName, file.getPath()); storageService.delete(bucketName, file.genThumbnailPath()); String newFileId = LdsUtil.generateUuid(); return createOrUpdateFile(newFile, tags, fileId, newFileId, newFile.getSize()); } /** * Delete a file from Firestore and Cloud Storage. * * @param file the uploaded file */ public void deleteFile(BaseFile file) throws InterruptedException, ExecutionException { log.info("entering deleteFile()"); firestoreService.delete(file.getId()); storageService.delete(bucketName, file.getPath()); storageService.delete(bucketName, file.genThumbnailPath()); } /** * Search files with given tags. * * @param tags list of tags label the files * @param orderNo application defined column for referencing order * @param size number of files return * @return list of uploaded files */ public List<BaseFile> getFilesByTag(List<String> tags, String orderNo, int size) throws InterruptedException, ExecutionException { log.info("entering getFilesByTag()"); return firestoreService.getFilesByTag(tags, orderNo, size); } /** * Search a single file with given fileId. * * @param fileId unique id of the file * @return the uploaded file */ public BaseFile getFileById(String fileId) throws InterruptedException, ExecutionException { log.info("entering getFileById()"); return firestoreService.getFileById(fileId); } /** Delete all files from Firestore and Cloud Storage. */ public void resetFile() throws InterruptedException, ExecutionException { log.info("entering resetFile()"); firestoreService.deleteCollection();
storageService.batchDelete(bucketName);
} /** * Create or update a file in Cloud Storage with the given fileId. * * @param file file upload to the server * @param tags list of tags label the file * @param fileId unique ID of the file * @param newFileId unique ID of the new file (for referencing Cloud Storage) * @param size size of the file * @return file data */ private BaseFile createOrUpdateFile( MultipartFile file, List<String> tags, String fileId, String newFileId, long size) throws InterruptedException, ExecutionException, IOException { BaseFile newFile = createOrUpdateFileMeta(tags, fileId, newFileId, file.getOriginalFilename(), size); storageService.save(bucketName, newFile.getPath(), file.getContentType(), file.getBytes()); if (newFile.checkImageFileType()) { createThumbnail(file, newFile.genThumbnailPath()); } return newFile; } /** * Create or update the metadata of a file in Firestore with the given fileId. * * @param tags list of tags label the file * @param fileId unique id of the file * @param newFileId unique id of the new file (for referencing Cloud Storage) * @param fileName name of the file * @param size size of the file * @return file data */ private BaseFile createOrUpdateFileMeta( List<String> tags, String fileId, String newFileId, String fileName, long size) throws InterruptedException, ExecutionException { String fileBucketPath = LdsUtil.getFileBucketPath(basePath, newFileId); FileMeta fileMeta = new FileMeta(fileId, fileBucketPath, fileName, tags, size); firestoreService.save(fileMeta); return getFileById(fileId); } /** * Create a thumbnail of the given file. * * @param file file to create thumbnail * @param thumbnailId unique id of the thumbnail file */ private void createThumbnail(MultipartFile file, String thumbnailId) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Thumbnails.of(file.getInputStream()) .size(THUMBNAIL_SIZE, THUMBNAIL_SIZE) .keepAspectRatio(false) .toOutputStream(byteArrayOutputStream); storageService.save( bucketName, thumbnailId, file.getContentType(), byteArrayOutputStream.toByteArray()); } }
api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FileService.java
GoogleCloudPlatform-app-large-data-sharing-java-fd21141
[ { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreService.java", "retrieved_chunk": " public void delete(String fileId) throws InterruptedException, ExecutionException {\n firestore.collection(collectionName).document(fileId).delete().get();\n }\n /** Delete a collection in Firestore. */\n public void deleteCollection() throws InterruptedException, ExecutionException {\n firestore.recursiveDelete(firestore.collection(collectionName)).get();\n }\n /**\n * Convert documents retrieved from Firestore to BaseFile object.\n *", "score": 0.8803215026855469 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreService.java", "retrieved_chunk": " *\n * @param fileMeta metadata of the file\n */\n public void save(FileMeta fileMeta) throws InterruptedException, ExecutionException {\n DocumentReference docRef = firestore.collection(collectionName).document(fileMeta.getId());\n docRef.set(fileMeta).get();\n }\n /**\n * Search a file with given fileId.\n *", "score": 0.8281105756759644 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreService.java", "retrieved_chunk": " * @param fileId unique id of the file\n * @return file data\n */\n public BaseFile getFileById(String fileId) throws InterruptedException, ExecutionException {\n ApiFuture<QuerySnapshot> future =\n firestore.collection(collectionName).whereEqualTo(FieldPath.documentId(), fileId).get();\n List<QueryDocumentSnapshot> documents = future.get().getDocuments();\n if (documents.isEmpty()) {\n return null;\n }", "score": 0.8240176439285278 }, { "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": 0.804966926574707 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FirestoreService.java", "retrieved_chunk": " }\n future = query.limit(size).get();\n List<QueryDocumentSnapshot> documents = future.get().getDocuments();\n return convertDoc2File(documents);\n }\n /**\n * Delete a file from Firestore with given fileId.\n *\n * @param fileId unique id of the file\n */", "score": 0.8003243207931519 } ]
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": " 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": 0.8351813554763794 }, { "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": 0.8345898985862732 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FileService.java", "retrieved_chunk": " }\n return fileList;\n }\n /**\n * Update a file to Firestore and Cloud Storage.\n *\n * @param newFile new file upload to the server\n * @param tags list of tags label the new file\n * @param file previously uploaded file\n * @return the updated file", "score": 0.8278367519378662 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FileService.java", "retrieved_chunk": " * @param newFileId unique id of the new file (for referencing Cloud Storage)\n * @param fileName name of the file\n * @param size size of the file\n * @return file data\n */\n private BaseFile createOrUpdateFileMeta(\n List<String> tags, String fileId, String newFileId, String fileName, long size)\n throws InterruptedException, ExecutionException {\n String fileBucketPath = LdsUtil.getFileBucketPath(basePath, newFileId);\n FileMeta fileMeta = new FileMeta(fileId, fileBucketPath, fileName, tags, size);", "score": 0.8270746469497681 }, { "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": 0.8244836330413818 } ]
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": " * @return list of uploaded files\n */\n public List<BaseFile> uploadFiles(List<MultipartFile> files, List<String> tags)\n throws InterruptedException, ExecutionException, IOException {\n log.info(\"entering uploadFiles()\");\n List<BaseFile> fileList = new ArrayList<>();\n for (MultipartFile file : files) {\n String fileId = LdsUtil.generateUuid();\n BaseFile newFile = createOrUpdateFile(file, tags, fileId, fileId, file.getSize());\n fileList.add(newFile);", "score": 0.7777899503707886 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FileService.java", "retrieved_chunk": " */\n public BaseFile updateFile(MultipartFile newFile, List<String> tags, BaseFile file)\n throws InterruptedException, ExecutionException, IOException {\n log.info(\"entering updateFile()\");\n String fileId = file.getId();\n if (newFile == null) {\n String pathId = LdsUtil.getPathId(file.getPath());\n return createOrUpdateFileMeta(tags, fileId, pathId, file.getName(), file.getSize());\n }\n storageService.delete(bucketName, file.getPath());", "score": 0.7766797542572021 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FileService.java", "retrieved_chunk": " * @param newFileId unique ID of the new file (for referencing Cloud Storage)\n * @param size size of the file\n * @return file data\n */\n private BaseFile createOrUpdateFile(\n MultipartFile file, List<String> tags, String fileId, String newFileId, long size)\n throws InterruptedException, ExecutionException, IOException {\n BaseFile newFile =\n createOrUpdateFileMeta(tags, fileId, newFileId, file.getOriginalFilename(), size);\n storageService.save(bucketName, newFile.getPath(), file.getContentType(), file.getBytes());", "score": 0.7623813152313232 }, { "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": 0.7428831458091736 }, { "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": 0.7319819927215576 } ]
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/types/CqlEvaluationResult.java", "retrieved_chunk": " @Nullable private String error;\n @Nullable private Map<String, Boolean> results;\n // Required for AvroCoder.\n public CqlEvaluationResult() {}\n public CqlEvaluationResult(\n VersionedIdentifier cqlLibraryIdentifier,\n ResourceTypeAndId contextId,\n ZonedDateTime evaluationDateTime,\n Map<String, Boolean> results) {\n this.libraryId = new CqlLibraryId(cqlLibraryIdentifier);", "score": 0.8688112497329712 }, { "filename": "src/main/java/com/google/fhir/cql/beam/types/CqlEvaluationResult.java", "retrieved_chunk": " this.contextId = checkNotNull(contextId);\n this.evaluationTime = evaluationDateTime.toInstant().toEpochMilli();\n this.results = Collections.unmodifiableMap(new HashMap<>(results));\n }\n public CqlEvaluationResult(\n VersionedIdentifier cqlLibraryIdentifier,\n ResourceTypeAndId contextId,\n ZonedDateTime evaluationDateTime,\n Exception exception) {\n this.libraryId = new CqlLibraryId(cqlLibraryIdentifier);", "score": 0.8372048139572144 }, { "filename": "src/main/java/com/google/fhir/cql/beam/types/CqlEvaluationResult.java", "retrieved_chunk": " this.contextId = checkNotNull(contextId);\n this.evaluationTime = evaluationDateTime.toInstant().toEpochMilli();\n this.error = exception.getMessage();\n }\n public CqlLibraryId getLibraryId() {\n return libraryId;\n }\n public ResourceTypeAndId getContexId() {\n return contextId;\n }", "score": 0.8075003623962402 }, { "filename": "src/main/java/com/google/fhir/cql/beam/KeyForContextFn.java", "retrieved_chunk": "public final class KeyForContextFn extends DoFn<String, KV<ResourceTypeAndId, String>> {\n private static final Pattern REFERENCE_PATTERN = Pattern.compile(\"([^/]+)/([^/]+)\");\n private static final String REFERENCE_FIELD_NAME = \"reference\";\n private static final String SUBJECT_FIELD_NAME = \"subject\";\n private static final String PATIENT_FIELD_NAME = \"patient\";\n private final String context;\n private final ImmutableSetMultimap<String, String> relatedKeyElementByType;\n public KeyForContextFn(String context, ModelInfo modelInfo) {\n this.context = checkNotNull(context);\n this.relatedKeyElementByType = createRelatedKeyElementByTypeMap(context, modelInfo);", "score": 0.7939553260803223 }, { "filename": "src/main/java/com/google/fhir/cql/beam/types/CqlEvaluationResult.java", "retrieved_chunk": " return builder(clazz.getPackageName()).type(AvroCoder.of(clazz).getSchema());\n }\n @SuppressWarnings(\"unchecked\")\n public static CoderProvider getCoderProvider() {\n return new CoderProvider() {\n @Override\n public <T> Coder<T> coderFor(\n TypeDescriptor<T> typeDescriptor, List<? extends Coder<?>> componentCoders)\n throws CannotProvideCoderException {\n if (typeDescriptor.getRawType() != CqlEvaluationResult.class) {", "score": 0.7899690866470337 } ]
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/types/CqlEvaluationResult.java", "retrieved_chunk": " @Nullable private String error;\n @Nullable private Map<String, Boolean> results;\n // Required for AvroCoder.\n public CqlEvaluationResult() {}\n public CqlEvaluationResult(\n VersionedIdentifier cqlLibraryIdentifier,\n ResourceTypeAndId contextId,\n ZonedDateTime evaluationDateTime,\n Map<String, Boolean> results) {\n this.libraryId = new CqlLibraryId(cqlLibraryIdentifier);", "score": 0.8660732507705688 }, { "filename": "src/main/java/com/google/fhir/cql/beam/types/CqlEvaluationResult.java", "retrieved_chunk": " this.contextId = checkNotNull(contextId);\n this.evaluationTime = evaluationDateTime.toInstant().toEpochMilli();\n this.results = Collections.unmodifiableMap(new HashMap<>(results));\n }\n public CqlEvaluationResult(\n VersionedIdentifier cqlLibraryIdentifier,\n ResourceTypeAndId contextId,\n ZonedDateTime evaluationDateTime,\n Exception exception) {\n this.libraryId = new CqlLibraryId(cqlLibraryIdentifier);", "score": 0.8482130765914917 }, { "filename": "src/main/java/com/google/fhir/cql/beam/types/CqlEvaluationResult.java", "retrieved_chunk": " this.contextId = checkNotNull(contextId);\n this.evaluationTime = evaluationDateTime.toInstant().toEpochMilli();\n this.error = exception.getMessage();\n }\n public CqlLibraryId getLibraryId() {\n return libraryId;\n }\n public ResourceTypeAndId getContexId() {\n return contextId;\n }", "score": 0.8161718845367432 }, { "filename": "src/main/java/com/google/fhir/cql/beam/KeyForContextFn.java", "retrieved_chunk": "public final class KeyForContextFn extends DoFn<String, KV<ResourceTypeAndId, String>> {\n private static final Pattern REFERENCE_PATTERN = Pattern.compile(\"([^/]+)/([^/]+)\");\n private static final String REFERENCE_FIELD_NAME = \"reference\";\n private static final String SUBJECT_FIELD_NAME = \"subject\";\n private static final String PATIENT_FIELD_NAME = \"patient\";\n private final String context;\n private final ImmutableSetMultimap<String, String> relatedKeyElementByType;\n public KeyForContextFn(String context, ModelInfo modelInfo) {\n this.context = checkNotNull(context);\n this.relatedKeyElementByType = createRelatedKeyElementByTypeMap(context, modelInfo);", "score": 0.793867826461792 }, { "filename": "src/main/java/com/google/fhir/cql/beam/types/CqlEvaluationResult.java", "retrieved_chunk": " return builder(clazz.getPackageName()).type(AvroCoder.of(clazz).getSchema());\n }\n @SuppressWarnings(\"unchecked\")\n public static CoderProvider getCoderProvider() {\n return new CoderProvider() {\n @Override\n public <T> Coder<T> coderFor(\n TypeDescriptor<T> typeDescriptor, List<? extends Coder<?>> componentCoders)\n throws CannotProvideCoderException {\n if (typeDescriptor.getRawType() != CqlEvaluationResult.class) {", "score": 0.7857850790023804 } ]
java
enterContext(contextValue.getType());
package com.dice.service; import com.dice.DTO.DiceSwDTO; import com.dice.DTO.ResultadoSwDTO; import com.dice.DTO.ResultadoSwForceDTO; import com.dice.model.Dice; import org.springframework.stereotype.Service; @Service public class StarWarsService { public StarWarsService() {} public ResultadoSwDTO rollSwDice(DiceSwDTO dice) { int success = 0; int triumph = 0; int advantage = 0; int failure = 0; int despair = 0; int threat = 0; // Obter os valores para cada tipo de dado. int boost = dice.getAmpliacao(); int ability = dice.getHabilidade(); int proficiency = dice.getProficiencia(); int setback = dice.getContratempo(); int difficulty = dice.getDificuldade(); int challenge = dice.getDesafio(); // Calcular os resultados dos dados. for (int i = 0; i < boost; i++) { Dice boostDice = new Dice(6); int result = boostDice.roll(); if (result == 1 || result == 2 ) { // Do nothing } else if (result == 3) { success += 1; } else if (result == 4) { success += 1; advantage += 1; } else if (result == 5) { advantage += 2; } else if (result == 6) { advantage += 1; } } for (int i = 0; i < ability; i++) { Dice abilityDice = new Dice(8); int result = abilityDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4) { success += 2; } else if (result == 5 || result == 6) { advantage += 1; } else if (result == 7) { success += 1; advantage += 1; } else if (result == 8) { advantage += 2; } } for (int i = 0; i < proficiency; i++) { Dice proficiencyDice = new Dice(12); int result = proficiencyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4 || result == 5) { success += 2; } else if (result == 6) { advantage += 1; } else if (result == 7 || result == 8 || result == 9) { success += 1; advantage += 1; } else if (result == 10 || result == 11) { advantage += 2; } else if (result == 12) { triumph += 1; } } for (int i = 0; i < setback; i++) { Dice setbackDice = new Dice(6); int result = setbackDice.roll(); if (result == 1 || result == 2) { // Do nothing } else if (result == 3 || result == 4) { failure += 1; } else if (result == 5 || result == 6) { threat += 1; } } for (int i = 0; i < difficulty; i++) { Dice difficultyDice = new Dice(8); int result = difficultyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2) { failure += 1; } else if (result == 3) { failure += 2; } else if (result == 4 || result == 5 || result == 6) { threat += 1; } else if (result == 7) { threat += 2; } else if (result == 8) { failure += 1; threat += 1; } } for (int i = 0; i < challenge; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { failure += 1; } else if (result == 4 || result == 5) { failure += 2; } else if (result == 6 || result == 7) { threat += 1; } else if (result == 8 || result == 9) { failure += 1; threat += 1; } else if (result == 10 || result == 11) { threat += 2; } else if (result == 12) { despair += 1; } } return getResultSwDice(success, triumph, advantage, failure, despair, threat); } private ResultadoSwDTO getResultSwDice(int success, int triumph, int advantage, int failure, int despair, int threat) { ResultadoSwDTO diceResult = new ResultadoSwDTO(); if (success - failure > 0) { diceResult.setSucessos(success - failure);
diceResult.setFracassos(0);
} else if (success - failure < 0) { diceResult.setSucessos(0); diceResult.setFracassos(failure - success); } else { diceResult.setSucessos(0); diceResult.setFracassos(0); } if (advantage - threat > 0) { diceResult.setVantagens(advantage - threat); diceResult.setAmeacas(0); } else if (advantage - threat < 0) { diceResult.setVantagens(0); diceResult.setAmeacas(threat - advantage); } else { diceResult.setVantagens(0); diceResult.setAmeacas(0); } if (triumph - despair > 0) { diceResult.setTriunfos(triumph - despair); diceResult.setDesesperos(0); } else if (triumph - despair < 0) { diceResult.setTriunfos(0); diceResult.setDesesperos(despair - triumph); } else { diceResult.setTriunfos(0); diceResult.setDesesperos(0); } return diceResult; } public ResultadoSwForceDTO rollForce(int quantity) { int light = 0; int dark = 0; for (int i = 0; i < quantity; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1 || result == 2 || result == 3 || result == 4 || result == 5 || result == 6) { dark += 1; } else if (result == 7) { dark += 2; } else if (result == 8 || result == 9) { light += 1; } else if (result == 10 || result == 11 || result == 12) { light += 2; } } ResultadoSwForceDTO forceResult = new ResultadoSwForceDTO(); forceResult.setLuz(light); forceResult.setNegro(dark); return forceResult; } }
src/main/java/com/dice/service/StarWarsService.java
grcreutzberg-dice-api-d58bb3d
[ { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class ResultadoSwDTO {\n private int sucessos = 0;\n private int triunfos = 0;\n private int vantagens = 0;\n private int fracassos = 0;\n private int desesperos = 0;\n private int ameacas = 0;\n public int getSucessos() {\n return sucessos;", "score": 0.7616332769393921 }, { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " }\n int diceX = new Dice(dice).roll();\n int diceY = new Dice(dice).roll();\n int resultDice = new Dice(dice).roll();\n if (type.equalsIgnoreCase(\"Advantage\")) {\n return resultDice + Math.max(diceX, diceY); //Retorna Dado + Vantagem\n }\n return resultDice - Math.min(diceX, diceY); //Retorna Dado - Desvantagem\n }\n}", "score": 0.7538564205169678 }, { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " int[] results = new int[numberOfDice];\n Dice dice = new Dice(faces);\n for (int i = 0; i < numberOfDice; i++) {\n results[i] = dice.roll();\n }\n return results;\n }\n public int rollDisVantage(String type, int dice) {\n if (dice <= 0) {\n throw new IllegalArgumentException(\"O dado deve ser maior que zero.\");", "score": 0.7298766374588013 }, { "filename": "src/main/java/com/dice/DTO/DiceSwDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class DiceSwDTO {\n private int habilidade = 0;\n private int proficiencia = 0;\n private int dificuldade = 0;\n private int desafio = 0;\n private int ampliacao = 0;\n private int contratempo = 0;\n public int getHabilidade() {\n return habilidade;", "score": 0.7243728637695312 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwForceDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class ResultadoSwForceDTO {\n private int luz = 0;\n private int negro = 0;\n public int getLuz() {\n return luz;\n }\n public void setLuz(final int luz) {\n this.luz = luz;\n }", "score": 0.721919059753418 } ]
java
diceResult.setFracassos(0);
package com.dice.service; import com.dice.DTO.DiceSwDTO; import com.dice.DTO.ResultadoSwDTO; import com.dice.DTO.ResultadoSwForceDTO; import com.dice.model.Dice; import org.springframework.stereotype.Service; @Service public class StarWarsService { public StarWarsService() {} public ResultadoSwDTO rollSwDice(DiceSwDTO dice) { int success = 0; int triumph = 0; int advantage = 0; int failure = 0; int despair = 0; int threat = 0; // Obter os valores para cada tipo de dado. int boost = dice.getAmpliacao(); int ability = dice.getHabilidade(); int proficiency = dice.getProficiencia(); int setback = dice.getContratempo(); int difficulty = dice.getDificuldade(); int challenge = dice.getDesafio(); // Calcular os resultados dos dados. for (int i = 0; i < boost; i++) { Dice boostDice = new Dice(6); int result = boostDice.roll(); if (result == 1 || result == 2 ) { // Do nothing } else if (result == 3) { success += 1; } else if (result == 4) { success += 1; advantage += 1; } else if (result == 5) { advantage += 2; } else if (result == 6) { advantage += 1; } } for (int i = 0; i < ability; i++) { Dice abilityDice = new Dice(8); int result = abilityDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4) { success += 2; } else if (result == 5 || result == 6) { advantage += 1; } else if (result == 7) { success += 1; advantage += 1; } else if (result == 8) { advantage += 2; } } for (int i = 0; i < proficiency; i++) { Dice proficiencyDice = new Dice(12); int result = proficiencyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4 || result == 5) { success += 2; } else if (result == 6) { advantage += 1; } else if (result == 7 || result == 8 || result == 9) { success += 1; advantage += 1; } else if (result == 10 || result == 11) { advantage += 2; } else if (result == 12) { triumph += 1; } } for (int i = 0; i < setback; i++) { Dice setbackDice = new Dice(6); int result = setbackDice.roll(); if (result == 1 || result == 2) { // Do nothing } else if (result == 3 || result == 4) { failure += 1; } else if (result == 5 || result == 6) { threat += 1; } } for (int i = 0; i < difficulty; i++) { Dice difficultyDice = new Dice(8); int result = difficultyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2) { failure += 1; } else if (result == 3) { failure += 2; } else if (result == 4 || result == 5 || result == 6) { threat += 1; } else if (result == 7) { threat += 2; } else if (result == 8) { failure += 1; threat += 1; } } for (int i = 0; i < challenge; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { failure += 1; } else if (result == 4 || result == 5) { failure += 2; } else if (result == 6 || result == 7) { threat += 1; } else if (result == 8 || result == 9) { failure += 1; threat += 1; } else if (result == 10 || result == 11) { threat += 2; } else if (result == 12) { despair += 1; } } return getResultSwDice(success, triumph, advantage, failure, despair, threat); } private ResultadoSwDTO getResultSwDice(int success, int triumph, int advantage, int failure, int despair, int threat) { ResultadoSwDTO diceResult = new ResultadoSwDTO(); if (success - failure > 0) { diceResult.setSucessos(success - failure); diceResult.setFracassos(0); } else if (success - failure < 0) { diceResult.setSucessos(0); diceResult.setFracassos(failure - success); } else { diceResult.setSucessos(0); diceResult.setFracassos(0); } if (advantage - threat > 0) { diceResult.setVantagens(advantage - threat);
diceResult.setAmeacas(0);
} else if (advantage - threat < 0) { diceResult.setVantagens(0); diceResult.setAmeacas(threat - advantage); } else { diceResult.setVantagens(0); diceResult.setAmeacas(0); } if (triumph - despair > 0) { diceResult.setTriunfos(triumph - despair); diceResult.setDesesperos(0); } else if (triumph - despair < 0) { diceResult.setTriunfos(0); diceResult.setDesesperos(despair - triumph); } else { diceResult.setTriunfos(0); diceResult.setDesesperos(0); } return diceResult; } public ResultadoSwForceDTO rollForce(int quantity) { int light = 0; int dark = 0; for (int i = 0; i < quantity; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1 || result == 2 || result == 3 || result == 4 || result == 5 || result == 6) { dark += 1; } else if (result == 7) { dark += 2; } else if (result == 8 || result == 9) { light += 1; } else if (result == 10 || result == 11 || result == 12) { light += 2; } } ResultadoSwForceDTO forceResult = new ResultadoSwForceDTO(); forceResult.setLuz(light); forceResult.setNegro(dark); return forceResult; } }
src/main/java/com/dice/service/StarWarsService.java
grcreutzberg-dice-api-d58bb3d
[ { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " }\n int diceX = new Dice(dice).roll();\n int diceY = new Dice(dice).roll();\n int resultDice = new Dice(dice).roll();\n if (type.equalsIgnoreCase(\"Advantage\")) {\n return resultDice + Math.max(diceX, diceY); //Retorna Dado + Vantagem\n }\n return resultDice - Math.min(diceX, diceY); //Retorna Dado - Desvantagem\n }\n}", "score": 0.7316624522209167 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": " public int getVantagens() {\n return vantagens;\n }\n public void setVantagens(final int vantagens) {\n this.vantagens = vantagens;\n }\n public int getFracassos() {\n return fracassos;\n }\n public void setFracassos(final int fracassos) {", "score": 0.6890560984611511 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": " this.fracassos = fracassos;\n }\n public int getDesesperos() {\n return desesperos;\n }\n public void setDesesperos(final int desesperos) {\n this.desesperos = desesperos;\n }\n public int getAmeacas() {\n return ameacas;", "score": 0.6816904544830322 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": " }\n public void setSucessos(final int sucessos) {\n this.sucessos = sucessos;\n }\n public int getTriunfos() {\n return triunfos;\n }\n public void setTriunfos(final int triunfos) {\n this.triunfos = triunfos;\n }", "score": 0.6728973388671875 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class ResultadoSwDTO {\n private int sucessos = 0;\n private int triunfos = 0;\n private int vantagens = 0;\n private int fracassos = 0;\n private int desesperos = 0;\n private int ameacas = 0;\n public int getSucessos() {\n return sucessos;", "score": 0.6619280576705933 } ]
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.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/types/CqlEvaluationResult.java", "retrieved_chunk": " @Nullable private String error;\n @Nullable private Map<String, Boolean> results;\n // Required for AvroCoder.\n public CqlEvaluationResult() {}\n public CqlEvaluationResult(\n VersionedIdentifier cqlLibraryIdentifier,\n ResourceTypeAndId contextId,\n ZonedDateTime evaluationDateTime,\n Map<String, Boolean> results) {\n this.libraryId = new CqlLibraryId(cqlLibraryIdentifier);", "score": 0.871296226978302 }, { "filename": "src/main/java/com/google/fhir/cql/beam/types/CqlEvaluationResult.java", "retrieved_chunk": " this.contextId = checkNotNull(contextId);\n this.evaluationTime = evaluationDateTime.toInstant().toEpochMilli();\n this.results = Collections.unmodifiableMap(new HashMap<>(results));\n }\n public CqlEvaluationResult(\n VersionedIdentifier cqlLibraryIdentifier,\n ResourceTypeAndId contextId,\n ZonedDateTime evaluationDateTime,\n Exception exception) {\n this.libraryId = new CqlLibraryId(cqlLibraryIdentifier);", "score": 0.8383299708366394 }, { "filename": "src/main/java/com/google/fhir/cql/beam/types/CqlEvaluationResult.java", "retrieved_chunk": " this.contextId = checkNotNull(contextId);\n this.evaluationTime = evaluationDateTime.toInstant().toEpochMilli();\n this.error = exception.getMessage();\n }\n public CqlLibraryId getLibraryId() {\n return libraryId;\n }\n public ResourceTypeAndId getContexId() {\n return contextId;\n }", "score": 0.8104188442230225 }, { "filename": "src/main/java/com/google/fhir/cql/beam/KeyForContextFn.java", "retrieved_chunk": "public final class KeyForContextFn extends DoFn<String, KV<ResourceTypeAndId, String>> {\n private static final Pattern REFERENCE_PATTERN = Pattern.compile(\"([^/]+)/([^/]+)\");\n private static final String REFERENCE_FIELD_NAME = \"reference\";\n private static final String SUBJECT_FIELD_NAME = \"subject\";\n private static final String PATIENT_FIELD_NAME = \"patient\";\n private final String context;\n private final ImmutableSetMultimap<String, String> relatedKeyElementByType;\n public KeyForContextFn(String context, ModelInfo modelInfo) {\n this.context = checkNotNull(context);\n this.relatedKeyElementByType = createRelatedKeyElementByTypeMap(context, modelInfo);", "score": 0.7997115850448608 }, { "filename": "src/main/java/com/google/fhir/cql/beam/types/CqlEvaluationResult.java", "retrieved_chunk": " return builder(clazz.getPackageName()).type(AvroCoder.of(clazz).getSchema());\n }\n @SuppressWarnings(\"unchecked\")\n public static CoderProvider getCoderProvider() {\n return new CoderProvider() {\n @Override\n public <T> Coder<T> coderFor(\n TypeDescriptor<T> typeDescriptor, List<? extends Coder<?>> componentCoders)\n throws CannotProvideCoderException {\n if (typeDescriptor.getRawType() != CqlEvaluationResult.class) {", "score": 0.7921870946884155 } ]
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": 0.7605841159820557 }, { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " }\n int diceX = new Dice(dice).roll();\n int diceY = new Dice(dice).roll();\n int resultDice = new Dice(dice).roll();\n if (type.equalsIgnoreCase(\"Advantage\")) {\n return resultDice + Math.max(diceX, diceY); //Retorna Dado + Vantagem\n }\n return resultDice - Math.min(diceX, diceY); //Retorna Dado - Desvantagem\n }\n}", "score": 0.7531786561012268 }, { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " int[] results = new int[numberOfDice];\n Dice dice = new Dice(faces);\n for (int i = 0; i < numberOfDice; i++) {\n results[i] = dice.roll();\n }\n return results;\n }\n public int rollDisVantage(String type, int dice) {\n if (dice <= 0) {\n throw new IllegalArgumentException(\"O dado deve ser maior que zero.\");", "score": 0.7506609559059143 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwForceDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class ResultadoSwForceDTO {\n private int luz = 0;\n private int negro = 0;\n public int getLuz() {\n return luz;\n }\n public void setLuz(final int luz) {\n this.luz = luz;\n }", "score": 0.7372675538063049 }, { "filename": "src/main/java/com/dice/DTO/DiceSwDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class DiceSwDTO {\n private int habilidade = 0;\n private int proficiencia = 0;\n private int dificuldade = 0;\n private int desafio = 0;\n private int ampliacao = 0;\n private int contratempo = 0;\n public int getHabilidade() {\n return habilidade;", "score": 0.7304520010948181 } ]
java
diceResult.setSucessos(success - failure);
package com.dice.service; import com.dice.DTO.DiceSwDTO; import com.dice.DTO.ResultadoSwDTO; import com.dice.DTO.ResultadoSwForceDTO; import com.dice.model.Dice; import org.springframework.stereotype.Service; @Service public class StarWarsService { public StarWarsService() {} public ResultadoSwDTO rollSwDice(DiceSwDTO dice) { int success = 0; int triumph = 0; int advantage = 0; int failure = 0; int despair = 0; int threat = 0; // Obter os valores para cada tipo de dado. int boost = dice.getAmpliacao(); int ability = dice.getHabilidade(); int proficiency = dice.getProficiencia(); int setback = dice.getContratempo(); int difficulty = dice.getDificuldade(); int challenge = dice.getDesafio(); // Calcular os resultados dos dados. for (int i = 0; i < boost; i++) { Dice boostDice = new Dice(6); int result = boostDice.roll(); if (result == 1 || result == 2 ) { // Do nothing } else if (result == 3) { success += 1; } else if (result == 4) { success += 1; advantage += 1; } else if (result == 5) { advantage += 2; } else if (result == 6) { advantage += 1; } } for (int i = 0; i < ability; i++) { Dice abilityDice = new Dice(8); int result = abilityDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4) { success += 2; } else if (result == 5 || result == 6) { advantage += 1; } else if (result == 7) { success += 1; advantage += 1; } else if (result == 8) { advantage += 2; } } for (int i = 0; i < proficiency; i++) { Dice proficiencyDice = new Dice(12); int result = proficiencyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4 || result == 5) { success += 2; } else if (result == 6) { advantage += 1; } else if (result == 7 || result == 8 || result == 9) { success += 1; advantage += 1; } else if (result == 10 || result == 11) { advantage += 2; } else if (result == 12) { triumph += 1; } } for (int i = 0; i < setback; i++) { Dice setbackDice = new Dice(6); int result = setbackDice.roll(); if (result == 1 || result == 2) { // Do nothing } else if (result == 3 || result == 4) { failure += 1; } else if (result == 5 || result == 6) { threat += 1; } } for (int i = 0; i < difficulty; i++) { Dice difficultyDice = new Dice(8); int result = difficultyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2) { failure += 1; } else if (result == 3) { failure += 2; } else if (result == 4 || result == 5 || result == 6) { threat += 1; } else if (result == 7) { threat += 2; } else if (result == 8) { failure += 1; threat += 1; } } for (int i = 0; i < challenge; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { failure += 1; } else if (result == 4 || result == 5) { failure += 2; } else if (result == 6 || result == 7) { threat += 1; } else if (result == 8 || result == 9) { failure += 1; threat += 1; } else if (result == 10 || result == 11) { threat += 2; } else if (result == 12) { despair += 1; } } return getResultSwDice(success, triumph, advantage, failure, despair, threat); } private ResultadoSwDTO getResultSwDice(int success, int triumph, int advantage, int failure, int despair, int threat) { ResultadoSwDTO diceResult = new ResultadoSwDTO(); if (success - failure > 0) { diceResult.setSucessos(success - failure); diceResult.setFracassos(0); } else if (success - failure < 0) { diceResult.setSucessos(0);
diceResult.setFracassos(failure - success);
} else { diceResult.setSucessos(0); diceResult.setFracassos(0); } if (advantage - threat > 0) { diceResult.setVantagens(advantage - threat); diceResult.setAmeacas(0); } else if (advantage - threat < 0) { diceResult.setVantagens(0); diceResult.setAmeacas(threat - advantage); } else { diceResult.setVantagens(0); diceResult.setAmeacas(0); } if (triumph - despair > 0) { diceResult.setTriunfos(triumph - despair); diceResult.setDesesperos(0); } else if (triumph - despair < 0) { diceResult.setTriunfos(0); diceResult.setDesesperos(despair - triumph); } else { diceResult.setTriunfos(0); diceResult.setDesesperos(0); } return diceResult; } public ResultadoSwForceDTO rollForce(int quantity) { int light = 0; int dark = 0; for (int i = 0; i < quantity; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1 || result == 2 || result == 3 || result == 4 || result == 5 || result == 6) { dark += 1; } else if (result == 7) { dark += 2; } else if (result == 8 || result == 9) { light += 1; } else if (result == 10 || result == 11 || result == 12) { light += 2; } } ResultadoSwForceDTO forceResult = new ResultadoSwForceDTO(); forceResult.setLuz(light); forceResult.setNegro(dark); return forceResult; } }
src/main/java/com/dice/service/StarWarsService.java
grcreutzberg-dice-api-d58bb3d
[ { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class ResultadoSwDTO {\n private int sucessos = 0;\n private int triunfos = 0;\n private int vantagens = 0;\n private int fracassos = 0;\n private int desesperos = 0;\n private int ameacas = 0;\n public int getSucessos() {\n return sucessos;", "score": 0.7528813481330872 }, { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " }\n int diceX = new Dice(dice).roll();\n int diceY = new Dice(dice).roll();\n int resultDice = new Dice(dice).roll();\n if (type.equalsIgnoreCase(\"Advantage\")) {\n return resultDice + Math.max(diceX, diceY); //Retorna Dado + Vantagem\n }\n return resultDice - Math.min(diceX, diceY); //Retorna Dado - Desvantagem\n }\n}", "score": 0.7430555820465088 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": " }\n public void setSucessos(final int sucessos) {\n this.sucessos = sucessos;\n }\n public int getTriunfos() {\n return triunfos;\n }\n public void setTriunfos(final int triunfos) {\n this.triunfos = triunfos;\n }", "score": 0.7343820929527283 }, { "filename": "src/main/java/com/dice/DTO/DiceSwDTO.java", "retrieved_chunk": " public int getDificuldade() {\n return dificuldade;\n }\n public void setDificuldade(final int dificuldade) {\n this.dificuldade = dificuldade;\n }\n public int getDesafio() {\n return desafio;\n }\n public void setDesafio(final int desafio) {", "score": 0.709012508392334 }, { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " int[] results = new int[numberOfDice];\n Dice dice = new Dice(faces);\n for (int i = 0; i < numberOfDice; i++) {\n results[i] = dice.roll();\n }\n return results;\n }\n public int rollDisVantage(String type, int dice) {\n if (dice <= 0) {\n throw new IllegalArgumentException(\"O dado deve ser maior que zero.\");", "score": 0.7022874355316162 } ]
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/test/java/com/google/fhir/cql/beam/EvaluateCqlForContextFnTest.java", "retrieved_chunk": " private static VersionedIdentifier versionedIdentifier(String id, String version) {\n VersionedIdentifier versionedIdentifier = new VersionedIdentifier();\n versionedIdentifier.setId(id);\n versionedIdentifier.setVersion(version);\n return versionedIdentifier;\n }\n private static Collection<Library> cqlToLibraries(String... cqlStrings) {\n ModelManager modelManager = new ModelManager();\n CqlCompiler compiler = new CqlCompiler(modelManager, new LibraryManager(modelManager));\n Collection<Library> libraries = new ArrayList<>();", "score": 0.8268795609474182 }, { "filename": "src/main/java/com/google/fhir/cql/beam/EvaluateCqlForContextFn.java", "retrieved_chunk": " .map(SerializableLibraryWrapper::getLibrary)\n .collect(Collectors.toList()));\n }\n @ProcessElement\n public void processElement(\n @Element KV<ResourceTypeAndId, Iterable<String>> contextResources,\n OutputReceiver<CqlEvaluationResult> out) {\n RetrieveProvider retrieveProvider = createRetrieveProvider(contextResources.getValue());\n for (VersionedIdentifier cqlLibraryId : cqlLibraryVersionedIdentifiers) {\n Library library = libraryLoader.load(cqlLibraryId);", "score": 0.8019924759864807 }, { "filename": "src/main/java/com/google/fhir/cql/beam/types/CqlEvaluationResult.java", "retrieved_chunk": " this.contextId = checkNotNull(contextId);\n this.evaluationTime = evaluationDateTime.toInstant().toEpochMilli();\n this.results = Collections.unmodifiableMap(new HashMap<>(results));\n }\n public CqlEvaluationResult(\n VersionedIdentifier cqlLibraryIdentifier,\n ResourceTypeAndId contextId,\n ZonedDateTime evaluationDateTime,\n Exception exception) {\n this.libraryId = new CqlLibraryId(cqlLibraryIdentifier);", "score": 0.7856219410896301 }, { "filename": "src/test/java/com/google/fhir/cql/beam/EvaluateCqlForContextFnTest.java", "retrieved_chunk": " try {\n for (String cql : cqlStrings) {\n libraries.add(LibraryMapper.INSTANCE.map(compiler.run(\n cql, Options.EnableResultTypes, Options.EnableLocators)));\n assertThat(compiler.getExceptions()).isEmpty();\n }\n return libraries;\n } catch (IOException e) {\n throw new RuntimeException(e);\n }", "score": 0.7812000513076782 }, { "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": 0.7764194011688232 } ]
java
(libraryIds.getVersion()), new CqlTranslatorOptions(TRANSLATOR_OPTIONS), errors);
/* * Copyright (C) 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.fhir.cql.beam; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.ImmutableList.toImmutableList; import ca.uhn.fhir.context.FhirVersionEnum; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.fhir.cql.beam.types.CqlEvaluationResult; import com.google.fhir.cql.beam.types.CqlLibraryId; import com.google.fhir.cql.beam.types.ResourceTypeAndId; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Path; import java.nio.file.Paths; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.function.Function; import java.util.function.Predicate; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.extensions.avro.io.AvroIO; import org.apache.beam.sdk.io.TextIO; import org.apache.beam.sdk.options.Description; import org.apache.beam.sdk.options.PipelineOptions; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.apache.beam.sdk.options.Validation.Required; import org.apache.beam.sdk.transforms.GroupByKey; import org.apache.beam.sdk.transforms.ParDo; import org.cqframework.cql.cql2elm.CqlCompilerException; import org.cqframework.cql.cql2elm.CqlCompilerException.ErrorSeverity; import org.cqframework.cql.cql2elm.CqlTranslatorOptions; import org.cqframework.cql.cql2elm.CqlTranslatorOptions.Options; import org.cqframework.cql.cql2elm.LibraryManager; import org.cqframework.cql.cql2elm.ModelManager; import org.cqframework.cql.cql2elm.model.CompiledLibrary; import org.cqframework.cql.elm.execution.Library; import org.opencds.cqf.cql.evaluator.cql2elm.content.InMemoryLibrarySourceProvider; import org.opencds.cqf.cql.evaluator.engine.elm.LibraryMapper; /** * Main entry point for evaluating CQL libraries over a set of FHIR records with Apache Beam. * * <p>See README.md for additional information. */ public final class EvaluateCql { /** * Options supported by {@link EvaluateCql}. */ public interface EvaluateCqlOptions extends PipelineOptions { @Description( "The file pattern of the NDJSON FHIR files to read. Follows the conventions of " + "https://docs.oracle.com/javase/tutorial/essential/io/fileOps.html#glob.") @Required String getNdjsonFhirFilePattern(); void setNdjsonFhirFilePattern(String value); @Description( "Path to a folder that contains ValueSet FHIR records. Each file must contain exactly one " + "ValueSet FHIR record. Subfolders and their content are ignored.") @Required String getValueSetFolder(); void setValueSetFolder(String value); @Description( "Path to a folder that contains CQL libraries. Subfolders and their content are ignored.") @Required String getCqlFolder(); void setCqlFolder(String value); @Description( "A list of CQL library IDs and, optionally, versions that will be evaluated " + "against the provided FHIR. Format: " + "[{\"name\": \"ColorectalCancerScreeningsFHIR\"}, " + "{\"name\": \"ControllingHighBloodPressureFHIR\" \"version\": \"0.0.002\"}]") @Required @JsonSerialize @JsonDeserialize List<CqlLibraryId> getCqlLibraries(); void setCqlLibraries(List<CqlLibraryId> value); @Description("Path and name prefix of the file shards that will contain the pipeline output.") @Required String getOutputFilenamePrefix(); void setOutputFilenamePrefix(String value); } private static ImmutableList<String> loadFilesInDirectory( Path directory, Predicate<Path> pathFilter) { try { return FileLoader.loadFilesInDirectory(directory, pathFilter); } catch (IOException e) { throw new RuntimeException("Failed to read files in " + directory, e); } } private static Path toPath(String directory) { try { URI directoryUri = new URI(directory); if (new URI(directory).getScheme() != null) { return Paths.get(directoryUri); } } catch (URISyntaxException e) { // Fall through and treat as a file:// directory. } return new File(directory).toPath(); } private static final Options[] TRANSLATOR_OPTIONS = { Options.DisableListPromotion, Options.DisableListDemotion, Options.EnableResultTypes, Options.EnableLocators }; private static ImmutableList<Library> loadLibraries( Path cqlFolder, Collection<CqlLibraryId> cqlLibraryIds) { LibraryManager libraryManager = new LibraryManager(new ModelManager()); libraryManager .getLibrarySourceLoader() .registerProvider( new InMemoryLibrarySourceProvider( loadFilesInDirectory(cqlFolder, (path) -> path.toString().endsWith(".cql")))); libraryManager.enableCache(); for (CqlLibraryId libraryIds : cqlLibraryIds) { List<CqlCompilerException> errors = new ArrayList<>(); libraryManager.resolveLibrary( new org.hl7.elm.r1.VersionedIdentifier() .
withId(libraryIds.getName()) .withVersion(libraryIds.getVersion()), new CqlTranslatorOptions(TRANSLATOR_OPTIONS), errors);
if (errors.stream().filter(error -> error.getSeverity().equals(ErrorSeverity.Error)).count() > 0) { throw new RuntimeException( "Errors encountered while compiling CQL. " + errors.toString()); } } return libraryManager.getCompiledLibraries().values().stream() .map(CompiledLibrary::getLibrary) .map(LibraryMapper.INSTANCE::map) .collect(toImmutableList()); } private static void assemblePipeline( Pipeline pipeline, EvaluateCqlOptions options, ZonedDateTime evaluationDateTime) { checkArgument( !options.getCqlLibraries().isEmpty(), "At least one CQL library must be specified."); pipeline .apply("ReadNDJSON", TextIO.read().from(options.getNdjsonFhirFilePattern())) .apply("KeyForContext", ParDo.of(new KeyForContextFn( "Patient", new ModelManager().resolveModel("FHIR", "4.0.1").getModelInfo()))) .apply("GroupByContext", GroupByKey.<ResourceTypeAndId, String>create()) .apply( "EvaluateCql", ParDo.of( new EvaluateCqlForContextFn( loadLibraries(toPath(options.getCqlFolder()), options.getCqlLibraries()), ImmutableSet.copyOf(options.getCqlLibraries()), loadFilesInDirectory( toPath(options.getValueSetFolder()), (path) -> path.toString().endsWith(".json")), evaluationDateTime, FhirVersionEnum.R4))) .apply( "WriteCqlOutput", AvroIO.write(CqlEvaluationResult.class) .withSchema(CqlEvaluationResult.ResultCoder.SCHEMA) .to(options.getOutputFilenamePrefix()) .withSuffix(".avro")); } @VisibleForTesting static void runPipeline( Function<EvaluateCqlOptions, Pipeline> pipelineCreator, String[] args, ZonedDateTime evaluationDateTime) { EvaluateCqlOptions options = PipelineOptionsFactory.fromArgs(args).withValidation().as(EvaluateCqlOptions.class); Pipeline pipeline = pipelineCreator.apply(options); assemblePipeline(pipeline, options, evaluationDateTime); pipeline.run().waitUntilFinish(); } public static void main(String[] args) { runPipeline(Pipeline::create, args, ZonedDateTime.now()); } }
src/main/java/com/google/fhir/cql/beam/EvaluateCql.java
google-cql-on-beam-82f1c68
[ { "filename": "src/test/java/com/google/fhir/cql/beam/EvaluateCqlForContextFnTest.java", "retrieved_chunk": " private static VersionedIdentifier versionedIdentifier(String id, String version) {\n VersionedIdentifier versionedIdentifier = new VersionedIdentifier();\n versionedIdentifier.setId(id);\n versionedIdentifier.setVersion(version);\n return versionedIdentifier;\n }\n private static Collection<Library> cqlToLibraries(String... cqlStrings) {\n ModelManager modelManager = new ModelManager();\n CqlCompiler compiler = new CqlCompiler(modelManager, new LibraryManager(modelManager));\n Collection<Library> libraries = new ArrayList<>();", "score": 0.8252361416816711 }, { "filename": "src/main/java/com/google/fhir/cql/beam/EvaluateCqlForContextFn.java", "retrieved_chunk": " .map(SerializableLibraryWrapper::getLibrary)\n .collect(Collectors.toList()));\n }\n @ProcessElement\n public void processElement(\n @Element KV<ResourceTypeAndId, Iterable<String>> contextResources,\n OutputReceiver<CqlEvaluationResult> out) {\n RetrieveProvider retrieveProvider = createRetrieveProvider(contextResources.getValue());\n for (VersionedIdentifier cqlLibraryId : cqlLibraryVersionedIdentifiers) {\n Library library = libraryLoader.load(cqlLibraryId);", "score": 0.7999535202980042 }, { "filename": "src/main/java/com/google/fhir/cql/beam/types/CqlEvaluationResult.java", "retrieved_chunk": " this.contextId = checkNotNull(contextId);\n this.evaluationTime = evaluationDateTime.toInstant().toEpochMilli();\n this.results = Collections.unmodifiableMap(new HashMap<>(results));\n }\n public CqlEvaluationResult(\n VersionedIdentifier cqlLibraryIdentifier,\n ResourceTypeAndId contextId,\n ZonedDateTime evaluationDateTime,\n Exception exception) {\n this.libraryId = new CqlLibraryId(cqlLibraryIdentifier);", "score": 0.7834909558296204 }, { "filename": "src/test/java/com/google/fhir/cql/beam/EvaluateCqlForContextFnTest.java", "retrieved_chunk": " try {\n for (String cql : cqlStrings) {\n libraries.add(LibraryMapper.INSTANCE.map(compiler.run(\n cql, Options.EnableResultTypes, Options.EnableLocators)));\n assertThat(compiler.getExceptions()).isEmpty();\n }\n return libraries;\n } catch (IOException e) {\n throw new RuntimeException(e);\n }", "score": 0.7786368131637573 }, { "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": 0.7746924161911011 } ]
java
withId(libraryIds.getName()) .withVersion(libraryIds.getVersion()), new CqlTranslatorOptions(TRANSLATOR_OPTIONS), errors);
/* * Copyright (C) 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.fhir.cql.beam; import java.util.concurrent.ConcurrentHashMap; import org.opencds.cqf.cql.engine.model.ModelResolver; /** * A {@link ModelResolver} that caches the results of calls to {@link ModelResolver#resolveType}. */ public class CachingModelResolver extends ForwardingModelResolver { private final ConcurrentHashMap<String, Class<?>> typeCache = new ConcurrentHashMap<>(); private final ConcurrentHashMap<Class<?>, Class<?>> objectTypeCache = new ConcurrentHashMap<>(); public CachingModelResolver(ModelResolver resolver) { super(resolver); } @Override public Class<?> resolveType(String typeName) { return typeCache.computeIfAbsent(typeName, super::resolveType); } @Override public Class<?> resolveType(Object value) { return objectTypeCache.computeIfAbsent( value.getClass(), (key) -> { return
super.resolveType(value);
}); } }
src/main/java/com/google/fhir/cql/beam/CachingModelResolver.java
google-cql-on-beam-82f1c68
[ { "filename": "src/main/java/com/google/fhir/cql/beam/ForwardingModelResolver.java", "retrieved_chunk": " }\n @Override\n public Class<?> resolveType(String typeName) {\n return resolver.resolveType(typeName);\n }\n @Override\n public Class<?> resolveType(Object value) {\n return resolver.resolveType(value);\n }\n @Override", "score": 0.9192953705787659 }, { "filename": "src/main/java/com/google/fhir/cql/beam/ForwardingModelResolver.java", "retrieved_chunk": " public Boolean is(Object value, Class<?> type) {\n return resolver.is(value, type);\n }\n @Override\n public Object as(Object value, Class<?> type, boolean isStrict) {\n return resolver.as(value, type, isStrict);\n }\n @Override\n public Object createInstance(String typeName) {\n return resolver.createInstance(typeName);", "score": 0.8816280961036682 }, { "filename": "src/main/java/com/google/fhir/cql/beam/ForwardingModelResolver.java", "retrieved_chunk": " public void setPackageName(String packageName) {\n resolver.setPackageName(packageName);\n }\n @Override\n public Object resolvePath(Object target, String path) {\n return resolver.resolvePath(target, path);\n }\n @Override\n public Object getContextPath(String contextType, String targetType) {\n return resolver.getContextPath(contextType, targetType);", "score": 0.8519132137298584 }, { "filename": "src/main/java/com/google/fhir/cql/beam/ForwardingModelResolver.java", "retrieved_chunk": " }\n @Override\n public void setValue(Object target, String path, Object value) {\n resolver.setValue(target, path, value);\n }\n @Override\n public Boolean objectEqual(Object left, Object right) {\n return resolver.objectEqual(left, right);\n }\n @Override", "score": 0.8225723505020142 }, { "filename": "src/main/java/com/google/fhir/cql/beam/types/ResourceTypeAndId.java", "retrieved_chunk": " public ResourceTypeAndId() {}\n public ResourceTypeAndId(String type, String id) {\n this.type = checkNotNull(type);\n this.id = checkNotNull(id);\n }\n /**\n * Returns the resource's type as a string (e.g. \"Patient\").\n */\n public String getType() {\n return type;", "score": 0.8168129920959473 } ]
java
super.resolveType(value);
package com.dice.controller; import com.dice.service.DiceRollService; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/v1/dice") public class DiceRollController { private final DiceRollService service; public DiceRollController(DiceRollService diceRollService) { this.service = diceRollService; } @GetMapping("/roll") public int[] rollDice( @RequestParam(name = "quantity", defaultValue = "1") int quantity, @RequestParam(name = "faces", defaultValue = "20") int faces ) { return service.rollDice(quantity, faces); } @GetMapping("/advantage") public int rollAdvantage( @RequestParam(name = "dice", defaultValue = "20") int dice ) { return
service.rollDisVantage("Advantage", dice);
} @GetMapping("/disadvantage") public int rollDisadvantage( @RequestParam(name = "dice", defaultValue = "20") int dice ) { return service.rollDisVantage("Disadvantage", dice); } }
src/main/java/com/dice/controller/DiceRollController.java
grcreutzberg-dice-api-d58bb3d
[ { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " int[] results = new int[numberOfDice];\n Dice dice = new Dice(faces);\n for (int i = 0; i < numberOfDice; i++) {\n results[i] = dice.roll();\n }\n return results;\n }\n public int rollDisVantage(String type, int dice) {\n if (dice <= 0) {\n throw new IllegalArgumentException(\"O dado deve ser maior que zero.\");", "score": 0.7968248724937439 }, { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": "package com.dice.service;\nimport com.dice.model.Dice;\nimport org.springframework.stereotype.Service;\n@Service\npublic class DiceRollService {\n public DiceRollService() {}\n public int[] rollDice(int numberOfDice, int faces) {\n if (numberOfDice <= 0) {\n throw new IllegalArgumentException(\"A quantidade de dados deve ser maior que zero.\");\n }", "score": 0.7879697680473328 }, { "filename": "src/main/java/com/dice/model/Dice.java", "retrieved_chunk": "package com.dice.model;\npublic class Dice {\n private int nFaces;\n public Dice(int nFaces) {\n if (nFaces < 2) {\n throw new IllegalArgumentException(\"O dado deve ter pelo menos duas faces.\");\n }\n this.nFaces = nFaces;\n }\n public int roll() {", "score": 0.7712380886077881 }, { "filename": "src/main/java/com/dice/controller/StarWarsController.java", "retrieved_chunk": "public class StarWarsController {\n private final StarWarsService service;\n public StarWarsController(StarWarsService starWarsService) {\n this.service = starWarsService;\n }\n @GetMapping(\"/force\")\n public ResponseEntity<ResultadoSwForceDTO> rollForce(\n @RequestParam(name = \"quantity\", defaultValue = \"1\") int quantity\n ) {\n return new ResponseEntity<ResultadoSwForceDTO>(service.rollForce(quantity), HttpStatus.OK);", "score": 0.767518162727356 }, { "filename": "src/main/java/com/dice/service/StarWarsService.java", "retrieved_chunk": " }\n return diceResult;\n }\n public ResultadoSwForceDTO rollForce(int quantity) {\n int light = 0;\n int dark = 0;\n for (int i = 0; i < quantity; i++) {\n Dice challengeDice = new Dice(12);\n int result = challengeDice.roll();\n if (result == 1 || result == 2 || result == 3 || result == 4 || result == 5 || result == 6) {", "score": 0.7398202419281006 } ]
java
service.rollDisVantage("Advantage", dice);
package com.dice.service; import com.dice.DTO.DiceSwDTO; import com.dice.DTO.ResultadoSwDTO; import com.dice.DTO.ResultadoSwForceDTO; import com.dice.model.Dice; import org.springframework.stereotype.Service; @Service public class StarWarsService { public StarWarsService() {} public ResultadoSwDTO rollSwDice(DiceSwDTO dice) { int success = 0; int triumph = 0; int advantage = 0; int failure = 0; int despair = 0; int threat = 0; // Obter os valores para cada tipo de dado. int boost = dice.getAmpliacao(); int ability = dice.getHabilidade(); int proficiency = dice.getProficiencia(); int setback = dice.getContratempo(); int difficulty = dice.getDificuldade(); int challenge = dice.getDesafio(); // Calcular os resultados dos dados. for (int i = 0; i < boost; i++) { Dice boostDice = new Dice(6); int result = boostDice.roll(); if (result == 1 || result == 2 ) { // Do nothing } else if (result == 3) { success += 1; } else if (result == 4) { success += 1; advantage += 1; } else if (result == 5) { advantage += 2; } else if (result == 6) { advantage += 1; } } for (int i = 0; i < ability; i++) { Dice abilityDice = new Dice(8); int result = abilityDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4) { success += 2; } else if (result == 5 || result == 6) { advantage += 1; } else if (result == 7) { success += 1; advantage += 1; } else if (result == 8) { advantage += 2; } } for (int i = 0; i < proficiency; i++) { Dice proficiencyDice = new Dice(12); int result = proficiencyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4 || result == 5) { success += 2; } else if (result == 6) { advantage += 1; } else if (result == 7 || result == 8 || result == 9) { success += 1; advantage += 1; } else if (result == 10 || result == 11) { advantage += 2; } else if (result == 12) { triumph += 1; } } for (int i = 0; i < setback; i++) { Dice setbackDice = new Dice(6); int result = setbackDice.roll(); if (result == 1 || result == 2) { // Do nothing } else if (result == 3 || result == 4) { failure += 1; } else if (result == 5 || result == 6) { threat += 1; } } for (int i = 0; i < difficulty; i++) { Dice difficultyDice = new Dice(8); int result = difficultyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2) { failure += 1; } else if (result == 3) { failure += 2; } else if (result == 4 || result == 5 || result == 6) { threat += 1; } else if (result == 7) { threat += 2; } else if (result == 8) { failure += 1; threat += 1; } } for (int i = 0; i < challenge; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { failure += 1; } else if (result == 4 || result == 5) { failure += 2; } else if (result == 6 || result == 7) { threat += 1; } else if (result == 8 || result == 9) { failure += 1; threat += 1; } else if (result == 10 || result == 11) { threat += 2; } else if (result == 12) { despair += 1; } } return getResultSwDice(success, triumph, advantage, failure, despair, threat); } private ResultadoSwDTO getResultSwDice(int success, int triumph, int advantage, int failure, int despair, int threat) { ResultadoSwDTO diceResult = new ResultadoSwDTO(); if (success - failure > 0) { diceResult.setSucessos(success - failure); diceResult.setFracassos(0); } else if (success - failure < 0) { diceResult.setSucessos(0); diceResult.setFracassos(failure - success); } else { diceResult.setSucessos(0); diceResult.setFracassos(0); } if (advantage - threat > 0) {
diceResult.setVantagens(advantage - threat);
diceResult.setAmeacas(0); } else if (advantage - threat < 0) { diceResult.setVantagens(0); diceResult.setAmeacas(threat - advantage); } else { diceResult.setVantagens(0); diceResult.setAmeacas(0); } if (triumph - despair > 0) { diceResult.setTriunfos(triumph - despair); diceResult.setDesesperos(0); } else if (triumph - despair < 0) { diceResult.setTriunfos(0); diceResult.setDesesperos(despair - triumph); } else { diceResult.setTriunfos(0); diceResult.setDesesperos(0); } return diceResult; } public ResultadoSwForceDTO rollForce(int quantity) { int light = 0; int dark = 0; for (int i = 0; i < quantity; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1 || result == 2 || result == 3 || result == 4 || result == 5 || result == 6) { dark += 1; } else if (result == 7) { dark += 2; } else if (result == 8 || result == 9) { light += 1; } else if (result == 10 || result == 11 || result == 12) { light += 2; } } ResultadoSwForceDTO forceResult = new ResultadoSwForceDTO(); forceResult.setLuz(light); forceResult.setNegro(dark); return forceResult; } }
src/main/java/com/dice/service/StarWarsService.java
grcreutzberg-dice-api-d58bb3d
[ { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " }\n int diceX = new Dice(dice).roll();\n int diceY = new Dice(dice).roll();\n int resultDice = new Dice(dice).roll();\n if (type.equalsIgnoreCase(\"Advantage\")) {\n return resultDice + Math.max(diceX, diceY); //Retorna Dado + Vantagem\n }\n return resultDice - Math.min(diceX, diceY); //Retorna Dado - Desvantagem\n }\n}", "score": 0.7351658940315247 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": " public int getVantagens() {\n return vantagens;\n }\n public void setVantagens(final int vantagens) {\n this.vantagens = vantagens;\n }\n public int getFracassos() {\n return fracassos;\n }\n public void setFracassos(final int fracassos) {", "score": 0.7135113477706909 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": " }\n public void setSucessos(final int sucessos) {\n this.sucessos = sucessos;\n }\n public int getTriunfos() {\n return triunfos;\n }\n public void setTriunfos(final int triunfos) {\n this.triunfos = triunfos;\n }", "score": 0.6995606422424316 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": " this.fracassos = fracassos;\n }\n public int getDesesperos() {\n return desesperos;\n }\n public void setDesesperos(final int desesperos) {\n this.desesperos = desesperos;\n }\n public int getAmeacas() {\n return ameacas;", "score": 0.6896039247512817 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class ResultadoSwDTO {\n private int sucessos = 0;\n private int triunfos = 0;\n private int vantagens = 0;\n private int fracassos = 0;\n private int desesperos = 0;\n private int ameacas = 0;\n public int getSucessos() {\n return sucessos;", "score": 0.6690404415130615 } ]
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": 0.8188952207565308 }, { "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": 0.7819503545761108 }, { "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": 0.7742164134979248 }, { "filename": "api/src/main/java/com/googlecodesamples/cloud/jss/lds/service/FileService.java", "retrieved_chunk": " firestoreService.save(fileMeta);\n return getFileById(fileId);\n }\n /**\n * Create a thumbnail of the given file.\n *\n * @param file file to create thumbnail\n * @param thumbnailId unique id of the thumbnail file\n */\n private void createThumbnail(MultipartFile file, String thumbnailId) throws IOException {", "score": 0.7662663459777832 }, { "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": 0.7585543990135193 } ]
java
return openTelemetryService.spanScope(this.getClass().getName(), "healthCheck", () -> {
package org.geysermc.hydraulic.mixin.ext; import com.github.steveice10.opennbt.tag.builtin.CompoundTag; import com.github.steveice10.opennbt.tag.builtin.ListTag; import com.github.steveice10.opennbt.tag.builtin.StringTag; import org.cloudburstmc.protocol.bedrock.data.inventory.ItemData; import org.geysermc.geyser.item.type.Item; import org.geysermc.geyser.registry.type.ItemMapping; import org.geysermc.geyser.session.GeyserSession; import org.geysermc.geyser.translator.inventory.item.ItemTranslator; import org.geysermc.hydraulic.HydraulicImpl; import org.geysermc.hydraulic.platform.mod.ModInfo; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.ModifyVariable; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; @Mixin(value = ItemTranslator.class, remap = false) public class ItemTranslatorMixin { @Inject( method = "translateDisplayProperties(Lorg/geysermc/geyser/session/GeyserSession;Lcom/github/steveice10/opennbt/tag/builtin/CompoundTag;Lorg/geysermc/geyser/registry/type/ItemMapping;C)Lcom/github/steveice10/opennbt/tag/builtin/CompoundTag;", at = @At("RETURN"), cancellable = true ) private static void translateDisplayProperties(GeyserSession session, CompoundTag tag, ItemMapping mapping, char translationColor, CallbackInfoReturnable<CompoundTag> ci) { CompoundTag newNbt = tag; if (newNbt == null) { newNbt = new CompoundTag("nbt"); CompoundTag display = new CompoundTag("display"); display.put(new ListTag("Lore")); newNbt.put(display); } CompoundTag compoundTag = newNbt.get("display"); if (compoundTag == null) { compoundTag = new CompoundTag("display"); } ListTag listTag = compoundTag.get("Lore"); if (listTag == null) { listTag = new ListTag("Lore"); } String identifier = mapping.getJavaItem().javaIdentifier(); // Get the mod name from the identifier String modId = identifier.substring(0, identifier.indexOf(":")); ModInfo mod
= HydraulicImpl.instance().mod(modId);
String modName = "Minecraft"; if (mod != null) { modName = mod.name(); } listTag.add(new StringTag("", "§r§9§o" + modName)); compoundTag.put(listTag); newNbt.put(compoundTag); ci.setReturnValue(newNbt); } }
shared/src/main/java/org/geysermc/hydraulic/mixin/ext/ItemTranslatorMixin.java
GeyserMC-Hydraulic-80cb8ab
[ { "filename": "forge/src/main/java/org/geysermc/hydraulic/forge/platform/HydraulicForgeBootstrap.java", "retrieved_chunk": " )\n ).collect(Collectors.toUnmodifiableSet());\n }\n @Override\n public @Nullable ModInfo mod(@NotNull String modName) {\n return ModList.get().getModContainerById(modName).map(container ->\n new ModInfo(\n container.getModId(),\n container.getModInfo().getVersion().toString(),\n container.getModInfo().getDisplayName(),", "score": 0.7369805574417114 }, { "filename": "forge/src/main/java/org/geysermc/hydraulic/forge/platform/HydraulicForgeBootstrap.java", "retrieved_chunk": "public class HydraulicForgeBootstrap implements HydraulicBootstrap {\n @Override\n public @NotNull Set<ModInfo> mods() {\n return ModList.get().getMods().stream().map(modInfo ->\n new ModInfo(\n modInfo.getModId(),\n modInfo.getVersion().toString(),\n modInfo.getDisplayName(),\n modInfo.getOwningFile().getFile().getFilePath(),\n modInfo.getLogoFile().orElse(\"\")", "score": 0.7257542014122009 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/pack/PackManager.java", "retrieved_chunk": " PackPostProcessContext context = new PackPostProcessContext(this.hydraulic, mod, module, converter, pack, packPath);\n if (!module.test(context)) {\n continue;\n }\n module.postProcess0(context);\n }\n // Set the pack name and description\n pack.manifest().header().name(mod.name().trim() + \" Resource Pack\");\n pack.manifest().header().description(\"Resource pack for mod \" + mod.name().trim());\n // Copy the icon if it exists", "score": 0.7083398103713989 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/pack/PackManager.java", "retrieved_chunk": " continue;\n }\n if (module.hasPreProcessors()) {\n try {\n ResourcePack pack = MinecraftResourcePackReader.minecraft().read(NioDirectoryFileTreeReader.read(mod.modPath()));\n PackPreProcessContext context = new PackPreProcessContext(this.hydraulic, mod, module, pack);\n module.preProcess0(context);\n } catch (Throwable t) {\n LOGGER.error(\"Failed to pre-process mod {} for module {}\", mod.id(), module.getClass().getSimpleName(), t);\n }", "score": 0.7032086253166199 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/util/PackUtil.java", "retrieved_chunk": " */\n public static BedrockResourcePack initializeForMod(@NotNull ModInfo mod, @NotNull Path packPack) {\n Manifest manifest = new Manifest();\n manifest.formatVersion(FORMAT_VERSION);\n Header header = new Header();\n header.description(\"Resource pack for mod \" + mod.name());\n header.name(mod.name() + \" Resource Pack\");\n header.version(new float[] { 1, 0, 0 });\n header.minEngineVersion(new float[] { 1, 16, 0 });\n header.uuid(UUID.randomUUID().toString());", "score": 0.6971637010574341 } ]
java
= HydraulicImpl.instance().mod(modId);
package com.dice.service; import com.dice.DTO.DiceSwDTO; import com.dice.DTO.ResultadoSwDTO; import com.dice.DTO.ResultadoSwForceDTO; import com.dice.model.Dice; import org.springframework.stereotype.Service; @Service public class StarWarsService { public StarWarsService() {} public ResultadoSwDTO rollSwDice(DiceSwDTO dice) { int success = 0; int triumph = 0; int advantage = 0; int failure = 0; int despair = 0; int threat = 0; // Obter os valores para cada tipo de dado. int boost = dice.getAmpliacao(); int ability = dice.getHabilidade(); int proficiency = dice.getProficiencia(); int setback = dice.getContratempo(); int difficulty = dice.getDificuldade(); int challenge = dice.getDesafio(); // Calcular os resultados dos dados. for (int i = 0; i < boost; i++) { Dice boostDice = new Dice(6); int result = boostDice.roll(); if (result == 1 || result == 2 ) { // Do nothing } else if (result == 3) { success += 1; } else if (result == 4) { success += 1; advantage += 1; } else if (result == 5) { advantage += 2; } else if (result == 6) { advantage += 1; } } for (int i = 0; i < ability; i++) { Dice abilityDice = new Dice(8); int result = abilityDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4) { success += 2; } else if (result == 5 || result == 6) { advantage += 1; } else if (result == 7) { success += 1; advantage += 1; } else if (result == 8) { advantage += 2; } } for (int i = 0; i < proficiency; i++) { Dice proficiencyDice = new Dice(12); int result = proficiencyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4 || result == 5) { success += 2; } else if (result == 6) { advantage += 1; } else if (result == 7 || result == 8 || result == 9) { success += 1; advantage += 1; } else if (result == 10 || result == 11) { advantage += 2; } else if (result == 12) { triumph += 1; } } for (int i = 0; i < setback; i++) { Dice setbackDice = new Dice(6); int result = setbackDice.roll(); if (result == 1 || result == 2) { // Do nothing } else if (result == 3 || result == 4) { failure += 1; } else if (result == 5 || result == 6) { threat += 1; } } for (int i = 0; i < difficulty; i++) { Dice difficultyDice = new Dice(8); int result = difficultyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2) { failure += 1; } else if (result == 3) { failure += 2; } else if (result == 4 || result == 5 || result == 6) { threat += 1; } else if (result == 7) { threat += 2; } else if (result == 8) { failure += 1; threat += 1; } } for (int i = 0; i < challenge; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { failure += 1; } else if (result == 4 || result == 5) { failure += 2; } else if (result == 6 || result == 7) { threat += 1; } else if (result == 8 || result == 9) { failure += 1; threat += 1; } else if (result == 10 || result == 11) { threat += 2; } else if (result == 12) { despair += 1; } } return getResultSwDice(success, triumph, advantage, failure, despair, threat); } private ResultadoSwDTO getResultSwDice(int success, int triumph, int advantage, int failure, int despair, int threat) { ResultadoSwDTO diceResult = new ResultadoSwDTO(); if (success - failure > 0) { diceResult.setSucessos(success - failure); diceResult.setFracassos(0); } else if (success - failure < 0) { diceResult.setSucessos(0); diceResult.setFracassos(failure - success); } else { diceResult.setSucessos(0); diceResult.setFracassos(0); } if (advantage - threat > 0) { diceResult.setVantagens(advantage - threat); diceResult.setAmeacas(0); } else if (advantage - threat < 0) { diceResult.setVantagens(0); diceResult.setAmeacas(threat - advantage); } else { diceResult.setVantagens(0); diceResult.setAmeacas(0); } if (triumph - despair > 0) { diceResult.setTriunfos(triumph - despair);
diceResult.setDesesperos(0);
} else if (triumph - despair < 0) { diceResult.setTriunfos(0); diceResult.setDesesperos(despair - triumph); } else { diceResult.setTriunfos(0); diceResult.setDesesperos(0); } return diceResult; } public ResultadoSwForceDTO rollForce(int quantity) { int light = 0; int dark = 0; for (int i = 0; i < quantity; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1 || result == 2 || result == 3 || result == 4 || result == 5 || result == 6) { dark += 1; } else if (result == 7) { dark += 2; } else if (result == 8 || result == 9) { light += 1; } else if (result == 10 || result == 11 || result == 12) { light += 2; } } ResultadoSwForceDTO forceResult = new ResultadoSwForceDTO(); forceResult.setLuz(light); forceResult.setNegro(dark); return forceResult; } }
src/main/java/com/dice/service/StarWarsService.java
grcreutzberg-dice-api-d58bb3d
[ { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " }\n int diceX = new Dice(dice).roll();\n int diceY = new Dice(dice).roll();\n int resultDice = new Dice(dice).roll();\n if (type.equalsIgnoreCase(\"Advantage\")) {\n return resultDice + Math.max(diceX, diceY); //Retorna Dado + Vantagem\n }\n return resultDice - Math.min(diceX, diceY); //Retorna Dado - Desvantagem\n }\n}", "score": 0.7490615844726562 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": " this.fracassos = fracassos;\n }\n public int getDesesperos() {\n return desesperos;\n }\n public void setDesesperos(final int desesperos) {\n this.desesperos = desesperos;\n }\n public int getAmeacas() {\n return ameacas;", "score": 0.7271242141723633 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": " public int getVantagens() {\n return vantagens;\n }\n public void setVantagens(final int vantagens) {\n this.vantagens = vantagens;\n }\n public int getFracassos() {\n return fracassos;\n }\n public void setFracassos(final int fracassos) {", "score": 0.6986997127532959 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": " }\n public void setSucessos(final int sucessos) {\n this.sucessos = sucessos;\n }\n public int getTriunfos() {\n return triunfos;\n }\n public void setTriunfos(final int triunfos) {\n this.triunfos = triunfos;\n }", "score": 0.6901016235351562 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class ResultadoSwDTO {\n private int sucessos = 0;\n private int triunfos = 0;\n private int vantagens = 0;\n private int fracassos = 0;\n private int desesperos = 0;\n private int ameacas = 0;\n public int getSucessos() {\n return sucessos;", "score": 0.6542172431945801 } ]
java
diceResult.setDesesperos(0);
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": "forge/src/main/java/org/geysermc/hydraulic/forge/platform/HydraulicForgeBootstrap.java", "retrieved_chunk": " container.getModInfo().getOwningFile().getFile().getFilePath(),\n container.getModInfo().getLogoFile().orElse(\"\")\n )\n ).orElse(null);\n }\n @Override\n public @NotNull Path dataFolder(@NotNull String modId) {\n return FMLPaths.CONFIGDIR.get().resolve(modId);\n }\n}", "score": 0.8375484943389893 }, { "filename": "fabric/src/main/java/org/geysermc/hydraulic/fabric/platform/HydraulicFabricBootstrap.java", "retrieved_chunk": " container.getMetadata().getVersion().getFriendlyString(),\n container.getMetadata().getName(),\n container.getRootPaths().get(0), // TODO: Multi-path support\n container.getMetadata().getIconPath(256).orElse(\"\")\n )\n ).orElse(null);\n }\n @Override\n public @NotNull Path dataFolder(@NotNull String modId) {\n return FabricLoader.getInstance().getConfigDir().resolve(modId);", "score": 0.8371845483779907 }, { "filename": "fabric/src/main/java/org/geysermc/hydraulic/fabric/platform/HydraulicFabricBootstrap.java", "retrieved_chunk": "public class HydraulicFabricBootstrap implements HydraulicBootstrap {\n @Override\n public @NotNull Set<ModInfo> mods() {\n return FabricLoader.getInstance().getAllMods().stream().filter(container -> !ignoreMod(container)).map(container ->\n new ModInfo(\n container.getMetadata().getId(),\n container.getMetadata().getVersion().getFriendlyString(),\n container.getMetadata().getName(),\n container.getRootPaths().get(0), // TODO: Multi-path support\n container.getMetadata().getIconPath(256).orElse(\"\")", "score": 0.7886561155319214 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/pack/PackListener.java", "retrieved_chunk": " this.hydraulic = hydraulic;\n this.manager = manager;\n }\n @Subscribe\n public void onLoadResourcePacks(GeyserLoadResourcePacksEvent event) {\n // TODO: Add this to Geyser API\n Path packsPath = GeyserImpl.getInstance().getBootstrap().getConfigFolder().resolve(\"packs\");\n Map<String, Pair<ModInfo, Path>> packsToLoad = new HashMap<>();\n for (ModInfo mod : this.hydraulic.mods()) {\n if (PackManager.IGNORED_MODS.contains(mod.id())) {", "score": 0.7800650000572205 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/pack/PackManager.java", "retrieved_chunk": " * @return {@code true} if the pack was created, {@code false} otherwise\n */\n @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n boolean createPack(@NotNull ModInfo mod, @NotNull Path packPath) {\n PackConverter converter = new PackConverter()\n .logListener(new PackLogListener(LOGGER))\n .converters(Converters.defaultConverters())\n .input(mod.modPath(), false)\n .output(packPath)\n .textureSubdirectory(mod.id());", "score": 0.7740527391433716 } ]
java
return HydraulicImpl.instance().dataFolder(Constants.MOD_ID) .resolve("storage") .resolve(mod.id());
package com.dice.service; import com.dice.DTO.DiceSwDTO; import com.dice.DTO.ResultadoSwDTO; import com.dice.DTO.ResultadoSwForceDTO; import com.dice.model.Dice; import org.springframework.stereotype.Service; @Service public class StarWarsService { public StarWarsService() {} public ResultadoSwDTO rollSwDice(DiceSwDTO dice) { int success = 0; int triumph = 0; int advantage = 0; int failure = 0; int despair = 0; int threat = 0; // Obter os valores para cada tipo de dado. int boost = dice.getAmpliacao(); int ability = dice.getHabilidade(); int proficiency = dice.getProficiencia(); int setback = dice.getContratempo(); int difficulty = dice.getDificuldade(); int challenge = dice.getDesafio(); // Calcular os resultados dos dados. for (int i = 0; i < boost; i++) { Dice boostDice = new Dice(6); int result = boostDice.roll(); if (result == 1 || result == 2 ) { // Do nothing } else if (result == 3) { success += 1; } else if (result == 4) { success += 1; advantage += 1; } else if (result == 5) { advantage += 2; } else if (result == 6) { advantage += 1; } } for (int i = 0; i < ability; i++) { Dice abilityDice = new Dice(8); int result = abilityDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4) { success += 2; } else if (result == 5 || result == 6) { advantage += 1; } else if (result == 7) { success += 1; advantage += 1; } else if (result == 8) { advantage += 2; } } for (int i = 0; i < proficiency; i++) { Dice proficiencyDice = new Dice(12); int result = proficiencyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4 || result == 5) { success += 2; } else if (result == 6) { advantage += 1; } else if (result == 7 || result == 8 || result == 9) { success += 1; advantage += 1; } else if (result == 10 || result == 11) { advantage += 2; } else if (result == 12) { triumph += 1; } } for (int i = 0; i < setback; i++) { Dice setbackDice = new Dice(6); int result = setbackDice.roll(); if (result == 1 || result == 2) { // Do nothing } else if (result == 3 || result == 4) { failure += 1; } else if (result == 5 || result == 6) { threat += 1; } } for (int i = 0; i < difficulty; i++) { Dice difficultyDice = new Dice(8); int result = difficultyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2) { failure += 1; } else if (result == 3) { failure += 2; } else if (result == 4 || result == 5 || result == 6) { threat += 1; } else if (result == 7) { threat += 2; } else if (result == 8) { failure += 1; threat += 1; } } for (int i = 0; i < challenge; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { failure += 1; } else if (result == 4 || result == 5) { failure += 2; } else if (result == 6 || result == 7) { threat += 1; } else if (result == 8 || result == 9) { failure += 1; threat += 1; } else if (result == 10 || result == 11) { threat += 2; } else if (result == 12) { despair += 1; } } return getResultSwDice(success, triumph, advantage, failure, despair, threat); } private ResultadoSwDTO getResultSwDice(int success, int triumph, int advantage, int failure, int despair, int threat) { ResultadoSwDTO diceResult = new ResultadoSwDTO(); if (success - failure > 0) { diceResult.setSucessos(success - failure); diceResult.setFracassos(0); } else if (success - failure < 0) { diceResult.setSucessos(0); diceResult.setFracassos(failure - success); } else { diceResult.setSucessos(0); diceResult.setFracassos(0); } if (advantage - threat > 0) { diceResult.setVantagens(advantage - threat); diceResult.setAmeacas(0); } else if (advantage - threat < 0) { diceResult.setVantagens(0); diceResult.setAmeacas(threat - advantage); } else { diceResult.setVantagens(0); diceResult.setAmeacas(0); } if (triumph - despair > 0) { diceResult.setTriunfos(triumph - despair); diceResult.setDesesperos(0); } else if (triumph - despair < 0) { diceResult.setTriunfos(0); diceResult.setDesesperos(despair - triumph); } else { diceResult.setTriunfos(0); diceResult.setDesesperos(0); } return diceResult; } public ResultadoSwForceDTO rollForce(int quantity) { int light = 0; int dark = 0; for (int i = 0; i < quantity; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1 || result == 2 || result == 3 || result == 4 || result == 5 || result == 6) { dark += 1; } else if (result == 7) { dark += 2; } else if (result == 8 || result == 9) { light += 1; } else if (result == 10 || result == 11 || result == 12) { light += 2; } } ResultadoSwForceDTO forceResult = new ResultadoSwForceDTO(); forceResult.setLuz(light);
forceResult.setNegro(dark);
return forceResult; } }
src/main/java/com/dice/service/StarWarsService.java
grcreutzberg-dice-api-d58bb3d
[ { "filename": "src/main/java/com/dice/DTO/ResultadoSwForceDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class ResultadoSwForceDTO {\n private int luz = 0;\n private int negro = 0;\n public int getLuz() {\n return luz;\n }\n public void setLuz(final int luz) {\n this.luz = luz;\n }", "score": 0.7300664186477661 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class ResultadoSwDTO {\n private int sucessos = 0;\n private int triunfos = 0;\n private int vantagens = 0;\n private int fracassos = 0;\n private int desesperos = 0;\n private int ameacas = 0;\n public int getSucessos() {\n return sucessos;", "score": 0.7162171602249146 }, { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " }\n int diceX = new Dice(dice).roll();\n int diceY = new Dice(dice).roll();\n int resultDice = new Dice(dice).roll();\n if (type.equalsIgnoreCase(\"Advantage\")) {\n return resultDice + Math.max(diceX, diceY); //Retorna Dado + Vantagem\n }\n return resultDice - Math.min(diceX, diceY); //Retorna Dado - Desvantagem\n }\n}", "score": 0.7129231095314026 }, { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " int[] results = new int[numberOfDice];\n Dice dice = new Dice(faces);\n for (int i = 0; i < numberOfDice; i++) {\n results[i] = dice.roll();\n }\n return results;\n }\n public int rollDisVantage(String type, int dice) {\n if (dice <= 0) {\n throw new IllegalArgumentException(\"O dado deve ser maior que zero.\");", "score": 0.7110439538955688 }, { "filename": "src/main/java/com/dice/DTO/DiceSwDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class DiceSwDTO {\n private int habilidade = 0;\n private int proficiencia = 0;\n private int dificuldade = 0;\n private int desafio = 0;\n private int ampliacao = 0;\n private int contratempo = 0;\n public int getHabilidade() {\n return habilidade;", "score": 0.7045066356658936 } ]
java
forceResult.setNegro(dark);
package com.dice.service; import com.dice.DTO.DiceSwDTO; import com.dice.DTO.ResultadoSwDTO; import com.dice.DTO.ResultadoSwForceDTO; import com.dice.model.Dice; import org.springframework.stereotype.Service; @Service public class StarWarsService { public StarWarsService() {} public ResultadoSwDTO rollSwDice(DiceSwDTO dice) { int success = 0; int triumph = 0; int advantage = 0; int failure = 0; int despair = 0; int threat = 0; // Obter os valores para cada tipo de dado. int boost = dice.getAmpliacao(); int ability = dice.getHabilidade(); int proficiency = dice.getProficiencia(); int setback = dice.getContratempo(); int difficulty = dice.getDificuldade(); int challenge = dice.getDesafio(); // Calcular os resultados dos dados. for (int i = 0; i < boost; i++) { Dice boostDice = new Dice(6); int result = boostDice.roll(); if (result == 1 || result == 2 ) { // Do nothing } else if (result == 3) { success += 1; } else if (result == 4) { success += 1; advantage += 1; } else if (result == 5) { advantage += 2; } else if (result == 6) { advantage += 1; } } for (int i = 0; i < ability; i++) { Dice abilityDice = new Dice(8); int result = abilityDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4) { success += 2; } else if (result == 5 || result == 6) { advantage += 1; } else if (result == 7) { success += 1; advantage += 1; } else if (result == 8) { advantage += 2; } } for (int i = 0; i < proficiency; i++) { Dice proficiencyDice = new Dice(12); int result = proficiencyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4 || result == 5) { success += 2; } else if (result == 6) { advantage += 1; } else if (result == 7 || result == 8 || result == 9) { success += 1; advantage += 1; } else if (result == 10 || result == 11) { advantage += 2; } else if (result == 12) { triumph += 1; } } for (int i = 0; i < setback; i++) { Dice setbackDice = new Dice(6); int result = setbackDice.roll(); if (result == 1 || result == 2) { // Do nothing } else if (result == 3 || result == 4) { failure += 1; } else if (result == 5 || result == 6) { threat += 1; } } for (int i = 0; i < difficulty; i++) { Dice difficultyDice = new Dice(8); int result = difficultyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2) { failure += 1; } else if (result == 3) { failure += 2; } else if (result == 4 || result == 5 || result == 6) { threat += 1; } else if (result == 7) { threat += 2; } else if (result == 8) { failure += 1; threat += 1; } } for (int i = 0; i < challenge; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { failure += 1; } else if (result == 4 || result == 5) { failure += 2; } else if (result == 6 || result == 7) { threat += 1; } else if (result == 8 || result == 9) { failure += 1; threat += 1; } else if (result == 10 || result == 11) { threat += 2; } else if (result == 12) { despair += 1; } } return getResultSwDice(success, triumph, advantage, failure, despair, threat); } private ResultadoSwDTO getResultSwDice(int success, int triumph, int advantage, int failure, int despair, int threat) { ResultadoSwDTO diceResult = new ResultadoSwDTO(); if (success - failure > 0) { diceResult.setSucessos(success - failure); diceResult.setFracassos(0); } else if (success - failure < 0) { diceResult.setSucessos(0); diceResult.setFracassos(failure - success); } else { diceResult.setSucessos(0); diceResult.setFracassos(0); } if (advantage - threat > 0) { diceResult.setVantagens(advantage - threat); diceResult.setAmeacas(0); } else if (advantage - threat < 0) { diceResult.setVantagens(0); diceResult.setAmeacas(threat - advantage); } else { diceResult.setVantagens(0); diceResult.setAmeacas(0); } if (triumph - despair > 0) { diceResult.setTriunfos(triumph - despair); diceResult.setDesesperos(0); } else if (triumph - despair < 0) { diceResult.setTriunfos(0); diceResult.setDesesperos(despair - triumph); } else { diceResult.setTriunfos(0); diceResult.setDesesperos(0); } return diceResult; } public ResultadoSwForceDTO rollForce(int quantity) { int light = 0; int dark = 0; for (int i = 0; i < quantity; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1 || result == 2 || result == 3 || result == 4 || result == 5 || result == 6) { dark += 1; } else if (result == 7) { dark += 2; } else if (result == 8 || result == 9) { light += 1; } else if (result == 10 || result == 11 || result == 12) { light += 2; } } ResultadoSwForceDTO forceResult = new ResultadoSwForceDTO();
forceResult.setLuz(light);
forceResult.setNegro(dark); return forceResult; } }
src/main/java/com/dice/service/StarWarsService.java
grcreutzberg-dice-api-d58bb3d
[ { "filename": "src/main/java/com/dice/DTO/ResultadoSwDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class ResultadoSwDTO {\n private int sucessos = 0;\n private int triunfos = 0;\n private int vantagens = 0;\n private int fracassos = 0;\n private int desesperos = 0;\n private int ameacas = 0;\n public int getSucessos() {\n return sucessos;", "score": 0.7459172606468201 }, { "filename": "src/main/java/com/dice/DTO/DiceSwDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class DiceSwDTO {\n private int habilidade = 0;\n private int proficiencia = 0;\n private int dificuldade = 0;\n private int desafio = 0;\n private int ampliacao = 0;\n private int contratempo = 0;\n public int getHabilidade() {\n return habilidade;", "score": 0.7396546006202698 }, { "filename": "src/main/java/com/dice/DTO/ResultadoSwForceDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class ResultadoSwForceDTO {\n private int luz = 0;\n private int negro = 0;\n public int getLuz() {\n return luz;\n }\n public void setLuz(final int luz) {\n this.luz = luz;\n }", "score": 0.7387437224388123 }, { "filename": "src/main/java/com/dice/model/Dice.java", "retrieved_chunk": "package com.dice.model;\npublic class Dice {\n private int nFaces;\n public Dice(int nFaces) {\n if (nFaces < 2) {\n throw new IllegalArgumentException(\"O dado deve ter pelo menos duas faces.\");\n }\n this.nFaces = nFaces;\n }\n public int roll() {", "score": 0.7365142107009888 }, { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " int[] results = new int[numberOfDice];\n Dice dice = new Dice(faces);\n for (int i = 0; i < numberOfDice; i++) {\n results[i] = dice.roll();\n }\n return results;\n }\n public int rollDisVantage(String type, int dice) {\n if (dice <= 0) {\n throw new IllegalArgumentException(\"O dado deve ser maior que zero.\");", "score": 0.7359122037887573 } ]
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/HydraulicImpl.java", "retrieved_chunk": " * Gets the mod storage for the specified mod.\n *\n * @param mod the mod\n * @return the mod storage\n */\n @NotNull\n public ModStorage modStorage(@NotNull ModInfo mod) {\n return this.modStorage.computeIfAbsent(mod.id(), e -> ModStorage.load(mod));\n }\n /**", "score": 0.8673240542411804 }, { "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": 0.8636891841888428 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/HydraulicImpl.java", "retrieved_chunk": " /**\n * Gets the data folder directory of this platform.\n *\n * @return the data folder directory\n */\n @NotNull\n public Path dataFolder(@NotNull String modId) {\n return this.bootstrap.dataFolder(modId);\n }\n /**", "score": 0.8611742258071899 }, { "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": 0.8598616123199463 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/HydraulicImpl.java", "retrieved_chunk": " this.packManager.initialize();\n }\n /**\n * Gets all the mods loaded on this platform.\n *\n * @return the mods loaded on this platform\n */\n @NotNull\n public Set<ModInfo> mods() {\n return this.bootstrap.mods();", "score": 0.8547341227531433 } ]
java
this.hydraulic.server().registryAccess().registryOrThrow(key);
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/PackModule.java", "retrieved_chunk": " *\n * @param context the context of the pack\n * @return if this pack module should be used\n */\n public boolean test(@NotNull PackPostProcessContext<T> context) {\n return true;\n }\n /**\n * Listens on the given {@link Event event}.\n *", "score": 0.8555737733840942 }, { "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": 0.8282527327537537 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/pack/context/PackContext.java", "retrieved_chunk": " this.hydraulic = hydraulic;\n this.mod = mod;\n this.module = module;\n }\n /**\n * Gets the mod that owns this pack.\n *\n * @return the mod that owns this pack\n */\n @NotNull", "score": 0.8276219367980957 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/pack/context/PackContext.java", "retrieved_chunk": " return this.hydraulic.modStorage(this.mod);\n }\n /**\n * Gets the module that this context is part of.\n *\n * @return the module that this context is part of\n */\n @NotNull\n public T module() {\n return this.module;", "score": 0.8253840208053589 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/pack/PackModule.java", "retrieved_chunk": " /**\n * Adds a post processor to this pack module.\n *\n * @param postProcessor the post processor\n */\n public final void postProcess(@NotNull Consumer<PackPostProcessContext<T>> postProcessor) {\n this.postProcessors.add(postProcessor);\n }\n /**\n * Tests if this pack module should be used.", "score": 0.8233339190483093 } ]
java
.packManager.initialize();
package org.geysermc.hydraulic; import net.minecraft.server.MinecraftServer; import org.geysermc.geyser.api.event.EventRegistrar; import org.geysermc.hydraulic.pack.PackManager; import org.geysermc.hydraulic.platform.HydraulicBootstrap; import org.geysermc.hydraulic.platform.HydraulicPlatform; import org.geysermc.hydraulic.platform.mod.ModInfo; import org.geysermc.hydraulic.storage.ModStorage; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Main class of the Hydraulic mod. */ public class HydraulicImpl implements EventRegistrar { private static final Logger LOGGER = LoggerFactory.getLogger("Hydraulic"); private static HydraulicImpl instance; private final HydraulicPlatform platform; private final HydraulicBootstrap bootstrap; private final PackManager packManager; private final Map<String, ModStorage> modStorage = new HashMap<>(); private MinecraftServer server; private HydraulicImpl(HydraulicPlatform platform, HydraulicBootstrap bootstrap) { instance = this; this.platform = platform; this.bootstrap = bootstrap; this.packManager = new PackManager(this); } /** * Called when the server is starting. * * @param server the Minecraft server instance */ public void onServerStarting(@NotNull MinecraftServer server) { this.server = server; this.packManager.initialize(); } /** * Gets all the mods loaded on this platform. * * @return the mods loaded on this platform */ @NotNull public Set<ModInfo> mods() { return
this.bootstrap.mods();
} /** * Gets the mod with the specified name, or null if not found. * * @param modName the name of the mod to get * @return the mod with the specified name */ @Nullable public ModInfo mod(@NotNull String modName) { return this.bootstrap.mod(modName); } /** * Gets the Minecraft server instance. * * @return the Minecraft server instance */ @NotNull public MinecraftServer server() { return this.server; } /** * Gets the data folder directory of this platform. * * @return the data folder directory */ @NotNull public Path dataFolder(@NotNull String modId) { return this.bootstrap.dataFolder(modId); } /** * Gets the mod storage for the specified mod. * * @param mod the mod * @return the mod storage */ @NotNull public ModStorage modStorage(@NotNull ModInfo mod) { return this.modStorage.computeIfAbsent(mod.id(), e -> ModStorage.load(mod)); } /** * Loads Hydraulic. * * @param platform the platform Hydraulic is running on * @param bootstrap the Hydraulic platform bootstrap * @return the loaded Hydraulic instance */ @NotNull public static HydraulicImpl load(@NotNull HydraulicPlatform platform, @NotNull HydraulicBootstrap bootstrap) { if (instance != null) { throw new IllegalStateException("Singleton HydraulicImpl has already been loaded!"); } return new HydraulicImpl(platform, bootstrap); } /** * Gets the Hydraulic instance. * * @return the Hydraulic instance */ @NotNull public static HydraulicImpl instance() { if (instance == null) { throw new IllegalStateException("Hydraulic has not been loaded!"); } return instance; } }
shared/src/main/java/org/geysermc/hydraulic/HydraulicImpl.java
GeyserMC-Hydraulic-80cb8ab
[ { "filename": "shared/src/main/java/org/geysermc/hydraulic/platform/HydraulicBootstrap.java", "retrieved_chunk": " /**\n * Gets all the mods loaded on this platform.\n *\n * @return the mods loaded on this platform\n */\n @NotNull\n Set<ModInfo> mods();\n /**\n * Gets the mod with the specified name, or null if not found.\n *", "score": 0.970001220703125 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/storage/ModStorage.java", "retrieved_chunk": " private ModStorage(@NotNull ModInfo mod) {\n this.mod = mod;\n }\n /**\n * Gets the materials for this mod.\n *\n * @return the materials\n */\n @NotNull\n public Materials materials() {", "score": 0.9230008721351624 }, { "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": 0.9210701584815979 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/pack/context/PackContext.java", "retrieved_chunk": " public ModInfo mod() {\n return this.mod;\n }\n /**\n * Gets the storage for the mod that owns this pack.\n *\n * @return the storage for the mod that owns this pack\n */\n @NotNull\n public ModStorage storage() {", "score": 0.9136794209480286 }, { "filename": "shared/src/main/java/org/geysermc/hydraulic/pack/context/PackPostProcessContext.java", "retrieved_chunk": " return this.pack;\n }\n /**\n * Gets the path to the pack.\n *\n * @return the path to the pack\n */\n @NotNull\n public Path path() {\n return this.path;", "score": 0.8977458477020264 } ]
java
this.bootstrap.mods();
package com.dice.service; import com.dice.DTO.DiceSwDTO; import com.dice.DTO.ResultadoSwDTO; import com.dice.DTO.ResultadoSwForceDTO; import com.dice.model.Dice; import org.springframework.stereotype.Service; @Service public class StarWarsService { public StarWarsService() {} public ResultadoSwDTO rollSwDice(DiceSwDTO dice) { int success = 0; int triumph = 0; int advantage = 0; int failure = 0; int despair = 0; int threat = 0; // Obter os valores para cada tipo de dado. int boost = dice.getAmpliacao(); int ability = dice.getHabilidade(); int proficiency = dice.getProficiencia(); int setback = dice.getContratempo(); int difficulty = dice.getDificuldade(); int challenge = dice.getDesafio(); // Calcular os resultados dos dados. for (int i = 0; i < boost; i++) { Dice boostDice = new Dice(6); int
result = boostDice.roll();
if (result == 1 || result == 2 ) { // Do nothing } else if (result == 3) { success += 1; } else if (result == 4) { success += 1; advantage += 1; } else if (result == 5) { advantage += 2; } else if (result == 6) { advantage += 1; } } for (int i = 0; i < ability; i++) { Dice abilityDice = new Dice(8); int result = abilityDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4) { success += 2; } else if (result == 5 || result == 6) { advantage += 1; } else if (result == 7) { success += 1; advantage += 1; } else if (result == 8) { advantage += 2; } } for (int i = 0; i < proficiency; i++) { Dice proficiencyDice = new Dice(12); int result = proficiencyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { success += 1; } else if (result == 4 || result == 5) { success += 2; } else if (result == 6) { advantage += 1; } else if (result == 7 || result == 8 || result == 9) { success += 1; advantage += 1; } else if (result == 10 || result == 11) { advantage += 2; } else if (result == 12) { triumph += 1; } } for (int i = 0; i < setback; i++) { Dice setbackDice = new Dice(6); int result = setbackDice.roll(); if (result == 1 || result == 2) { // Do nothing } else if (result == 3 || result == 4) { failure += 1; } else if (result == 5 || result == 6) { threat += 1; } } for (int i = 0; i < difficulty; i++) { Dice difficultyDice = new Dice(8); int result = difficultyDice.roll(); if (result == 1) { // Do nothing } else if (result == 2) { failure += 1; } else if (result == 3) { failure += 2; } else if (result == 4 || result == 5 || result == 6) { threat += 1; } else if (result == 7) { threat += 2; } else if (result == 8) { failure += 1; threat += 1; } } for (int i = 0; i < challenge; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1) { // Do nothing } else if (result == 2 || result == 3) { failure += 1; } else if (result == 4 || result == 5) { failure += 2; } else if (result == 6 || result == 7) { threat += 1; } else if (result == 8 || result == 9) { failure += 1; threat += 1; } else if (result == 10 || result == 11) { threat += 2; } else if (result == 12) { despair += 1; } } return getResultSwDice(success, triumph, advantage, failure, despair, threat); } private ResultadoSwDTO getResultSwDice(int success, int triumph, int advantage, int failure, int despair, int threat) { ResultadoSwDTO diceResult = new ResultadoSwDTO(); if (success - failure > 0) { diceResult.setSucessos(success - failure); diceResult.setFracassos(0); } else if (success - failure < 0) { diceResult.setSucessos(0); diceResult.setFracassos(failure - success); } else { diceResult.setSucessos(0); diceResult.setFracassos(0); } if (advantage - threat > 0) { diceResult.setVantagens(advantage - threat); diceResult.setAmeacas(0); } else if (advantage - threat < 0) { diceResult.setVantagens(0); diceResult.setAmeacas(threat - advantage); } else { diceResult.setVantagens(0); diceResult.setAmeacas(0); } if (triumph - despair > 0) { diceResult.setTriunfos(triumph - despair); diceResult.setDesesperos(0); } else if (triumph - despair < 0) { diceResult.setTriunfos(0); diceResult.setDesesperos(despair - triumph); } else { diceResult.setTriunfos(0); diceResult.setDesesperos(0); } return diceResult; } public ResultadoSwForceDTO rollForce(int quantity) { int light = 0; int dark = 0; for (int i = 0; i < quantity; i++) { Dice challengeDice = new Dice(12); int result = challengeDice.roll(); if (result == 1 || result == 2 || result == 3 || result == 4 || result == 5 || result == 6) { dark += 1; } else if (result == 7) { dark += 2; } else if (result == 8 || result == 9) { light += 1; } else if (result == 10 || result == 11 || result == 12) { light += 2; } } ResultadoSwForceDTO forceResult = new ResultadoSwForceDTO(); forceResult.setLuz(light); forceResult.setNegro(dark); return forceResult; } }
src/main/java/com/dice/service/StarWarsService.java
grcreutzberg-dice-api-d58bb3d
[ { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " }\n int diceX = new Dice(dice).roll();\n int diceY = new Dice(dice).roll();\n int resultDice = new Dice(dice).roll();\n if (type.equalsIgnoreCase(\"Advantage\")) {\n return resultDice + Math.max(diceX, diceY); //Retorna Dado + Vantagem\n }\n return resultDice - Math.min(diceX, diceY); //Retorna Dado - Desvantagem\n }\n}", "score": 0.7779366970062256 }, { "filename": "src/main/java/com/dice/DTO/DiceSwDTO.java", "retrieved_chunk": "package com.dice.DTO;\npublic class DiceSwDTO {\n private int habilidade = 0;\n private int proficiencia = 0;\n private int dificuldade = 0;\n private int desafio = 0;\n private int ampliacao = 0;\n private int contratempo = 0;\n public int getHabilidade() {\n return habilidade;", "score": 0.7567176222801208 }, { "filename": "src/main/java/com/dice/service/DiceRollService.java", "retrieved_chunk": " int[] results = new int[numberOfDice];\n Dice dice = new Dice(faces);\n for (int i = 0; i < numberOfDice; i++) {\n results[i] = dice.roll();\n }\n return results;\n }\n public int rollDisVantage(String type, int dice) {\n if (dice <= 0) {\n throw new IllegalArgumentException(\"O dado deve ser maior que zero.\");", "score": 0.7555180788040161 }, { "filename": "src/main/java/com/dice/DTO/DiceSwDTO.java", "retrieved_chunk": " }\n public void setHabilidade(final int habilidade) {\n this.habilidade = habilidade;\n }\n public int getProficiencia() {\n return proficiencia;\n }\n public void setProficiencia(final int proficiencia) {\n this.proficiencia = proficiencia;\n }", "score": 0.74153733253479 }, { "filename": "src/main/java/com/dice/DTO/DiceSwDTO.java", "retrieved_chunk": " public int getDificuldade() {\n return dificuldade;\n }\n public void setDificuldade(final int dificuldade) {\n this.dificuldade = dificuldade;\n }\n public int getDesafio() {\n return desafio;\n }\n public void setDesafio(final int desafio) {", "score": 0.7288504242897034 } ]
java
result = boostDice.roll();
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": 0.8320986032485962 }, { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/types/chat/Argument.java", "retrieved_chunk": " private final String conversationId;\n private final PreviousMessages[] previousMessages;\n private final String tone;\n public Argument(String traceId, boolean isStartOfSession, Message message, String conversationSignature, Participant participant, String conversationId, PreviousMessages[] previousMessages, String tone) {\n this.traceId = traceId;\n this.isStartOfSession = isStartOfSession;\n this.message = message;\n this.conversationSignature = conversationSignature;\n this.participant = participant;\n this.conversationId = conversationId;", "score": 0.8263520002365112 }, { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/Chat.java", "retrieved_chunk": " public Chat(String defaultCookie, String tone) {\n this.tone = tone;\n c = new DefaultClient(defaultCookie).getClient().newBuilder();\n this.locale = \"zh-CN\";\n this.logger = new Logger() {\n @Override\n public void Info(String log) {\n }\n @Override\n public void Error(String log) {", "score": 0.8101651668548584 }, { "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": 0.8094769716262817 }, { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/types/chat/Message.java", "retrieved_chunk": " private final String text;\n private final String messageType = \"Chat\";\n public Message(String locale, String market, String region, String location, LocationHints locationHints, String timestamp, String text) {\n this.locale = locale;\n this.market = market;\n this.region = region;\n this.location = location;\n this.locationHints = locationHints;\n this.timestamp = timestamp;\n this.text = text;", "score": 0.7850857973098755 } ]
java
logger.Info(String.format("[%s] [%s] websocket is closed", conversationSignature, question));
package io.github.heartalborada_del.newBingAPI.utils; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import io.github.heartalborada_del.newBingAPI.interfaces.Callback; import io.github.heartalborada_del.newBingAPI.interfaces.Logger; import io.github.heartalborada_del.newBingAPI.types.ChatWebsocketJson; import io.github.heartalborada_del.newBingAPI.types.chat.Argument; import io.github.heartalborada_del.newBingAPI.types.chat.Message; import io.github.heartalborada_del.newBingAPI.types.chat.Participant; import okhttp3.Response; import okhttp3.WebSocket; import okhttp3.WebSocketListener; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class ConversationWebsocket extends WebSocketListener { private final char TerminalChar = '\u001e'; private final String conversationId; private final String clientId; private final String conversationSignature; private final String question; private final String invocationID; private final Callback callback; private final Logger logger; private final String locale; private final String tone; public ConversationWebsocket(String ConversationId, String ClientId, String ConversationSignature, String question, short invocationID, Callback callback, Logger logger, String locale, String tone) { conversationId = ConversationId; clientId = ClientId; conversationSignature = ConversationSignature; this.question = question; this.invocationID = String.valueOf(invocationID); this.callback = callback; this.logger = logger; this.locale = locale; this.tone = tone; } @Override public void onClosed(@NotNull WebSocket webSocket, int code, @NotNull String reason) { logger.Info(String.format("[%s] [%s] websocket is closed", conversationSignature, question)); super.onClosed(webSocket, code, reason); } @Override public void onClosing(@NotNull WebSocket webSocket, int code, @NotNull String reason) { logger.Info(String.format("[%s] [%s] websocket is closing", conversationSignature, question)); super.onClosing(webSocket, code, reason); } @Override public void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, @Nullable Response response) { //logger.Error(String.format("[%s] [%s] websocket is failed, reason: [%s]",conversationSignature,question, t.getCause())); webSocket.close(1000, String.valueOf(TerminalChar)); super.onFailure(webSocket, t, response); } @Override public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) { for (String textSpited : text.split(String.valueOf(TerminalChar))) { logger.Debug(String.format("[%s] [%s] websocket is received new message [%s]", conversationSignature, question, textSpited)); JsonObject json = JsonParser.parseString(textSpited).getAsJsonObject(); if (json.isEmpty()) { sendData(webSocket, "{\"type\":6}"); String s = new GsonBuilder().disableHtmlEscaping().create().toJson( new ChatWebsocketJson(new Argument[]{ new Argument( Utils.randomString(32).toLowerCase(), invocationID.equals("0"), new Message( locale, locale, null, null, null, Utils.getNowTime(), question ), conversationSignature, new Participant(clientId), conversationId, null, tone) }, invocationID) ); sendData(webSocket, s); } else if (json.has("type")) { int type = json.getAsJsonPrimitive("type").getAsInt(); if (type == 3) { //end webSocket.close(1000, String.valueOf(TerminalChar)); } else if (type == 6) { //resend packet sendData(webSocket, "{\"type\":6}"); } else if (type == 2) { if (json.getAsJsonObject("item").has("result") && !json.getAsJsonObject("item").getAsJsonObject("result").getAsJsonPrimitive("value").getAsString().equals("Success")) { callback.onFailure(json, json.getAsJsonObject("item").getAsJsonObject("result").getAsJsonPrimitive("message").getAsString()); } else { callback.onSuccess(json); } } else if (type == 1) { callback.onUpdate(json); } else if (type == 7) { callback.onFailure(json, json.getAsJsonPrimitive("error").getAsString()); webSocket.close(1000, String.valueOf(TerminalChar)); } } else if (json.has("error")) { callback.onFailure(json, json.getAsJsonPrimitive("error").getAsString()); webSocket.close(1000, String.valueOf(TerminalChar)); } } super.onMessage(webSocket, text); } @Override public void onOpen(@NotNull WebSocket webSocket, @NotNull Response response) { super.onOpen(webSocket, response); sendData(webSocket, "{\"protocol\":\"json\",\"version\":1}"); } private void sendData(@NotNull WebSocket ws, @NotNull String data) {
logger.Debug(String.format("[%s] [%s] client send message [%s]", conversationSignature, question, data));
ws.send(data + TerminalChar); } }
src/main/java/io/github/heartalborada_del/newBingAPI/utils/ConversationWebsocket.java
heartalborada-del-newbingAPI-1102bfb
[ { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/instances/ChatInstance.java", "retrieved_chunk": " public void onFailure(JsonObject rawData, String cause) {\n callback.onFailure(rawData, cause);\n }\n @Override\n public void onUpdate(JsonObject rawData) {\n callback.onUpdate(rawData);\n }\n };\n Request request = new Request.Builder().get().url(\"wss://sydney.bing.com/sydney/ChatHub\").build();\n logger.Debug(String.format(\"Add a question [%s] to the queue,the current length of the queue is %d\", question, client.dispatcher().runningCallsCount()));", "score": 0.7992863655090332 }, { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/types/chat/Argument.java", "retrieved_chunk": " private final String conversationId;\n private final PreviousMessages[] previousMessages;\n private final String tone;\n public Argument(String traceId, boolean isStartOfSession, Message message, String conversationSignature, Participant participant, String conversationId, PreviousMessages[] previousMessages, String tone) {\n this.traceId = traceId;\n this.isStartOfSession = isStartOfSession;\n this.message = message;\n this.conversationSignature = conversationSignature;\n this.participant = participant;\n this.conversationId = conversationId;", "score": 0.7552093267440796 }, { "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": 0.7387446165084839 }, { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/Chat.java", "retrieved_chunk": " public Chat(String defaultCookie, String tone) {\n this.tone = tone;\n c = new DefaultClient(defaultCookie).getClient().newBuilder();\n this.locale = \"zh-CN\";\n this.logger = new Logger() {\n @Override\n public void Info(String log) {\n }\n @Override\n public void Error(String log) {", "score": 0.7384697794914246 }, { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/types/chat/Argument.java", "retrieved_chunk": " \"0310wlthrot\",\n \"302blocklist\",\n \"308disbing\",\n \"314glprompts0\"\n };\n private final String traceId;\n private final boolean isStartOfSession;\n private final Message message;\n private final String conversationSignature;\n private final Participant participant;", "score": 0.7301940321922302 } ]
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": 0.8029606342315674 }, { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/types/chat/Argument.java", "retrieved_chunk": " private final String conversationId;\n private final PreviousMessages[] previousMessages;\n private final String tone;\n public Argument(String traceId, boolean isStartOfSession, Message message, String conversationSignature, Participant participant, String conversationId, PreviousMessages[] previousMessages, String tone) {\n this.traceId = traceId;\n this.isStartOfSession = isStartOfSession;\n this.message = message;\n this.conversationSignature = conversationSignature;\n this.participant = participant;\n this.conversationId = conversationId;", "score": 0.7438406944274902 }, { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/Chat.java", "retrieved_chunk": " public Chat(String defaultCookie, String tone) {\n this.tone = tone;\n c = new DefaultClient(defaultCookie).getClient().newBuilder();\n this.locale = \"zh-CN\";\n this.logger = new Logger() {\n @Override\n public void Info(String log) {\n }\n @Override\n public void Error(String log) {", "score": 0.7318882942199707 }, { "filename": "src/main/java/io/github/heartalborada_del/newBingAPI/exceptions/ConversationException.java", "retrieved_chunk": "package io.github.heartalborada_del.newBingAPI.exceptions;\npublic class ConversationException extends Exception {\n //private static final long serialVersionUID = -7041169491254546905L;\n public ConversationException(String message) {\n super(message);\n }\n public ConversationException(String message, Throwable throwable) {\n super(message, throwable);\n }\n}", "score": 0.7240253686904907 }, { "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": 0.7210900783538818 } ]
java
logger.Debug(String.format("[%s] [%s] websocket is received new message [%s]", conversationSignature, question, textSpited));
package com.phonenumberinput; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Color; import android.os.Build; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.recyclerview.selection.SelectionTracker; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.util.List; public class CountryPickerAdapter extends RecyclerView.Adapter<CountryPickerListItem> { private List<Country> countries; private final LayoutInflater inflater; private boolean darkMode; private SelectionTracker<String> selectionTracker; private int defaultCountry; private final LinearLayoutManager layoutManager; public CountryPickerAdapter(Context context, List<Country> countries, LinearLayoutManager layoutManager) { this.countries = countries; this.inflater = LayoutInflater.from(context); this.layoutManager = layoutManager; } public void onCountryClick(int index) { setSelectedIndex(index); notifyItemChanged(index); } public void setSelectionTracker(SelectionTracker<String> selectionTracker) { this.selectionTracker = selectionTracker; if (defaultCountry >= 0 && defaultCountry < countries.size()) { String countryCode = countries.get(defaultCountry).getCode(); selectionTracker.select(countryCode); } else { selectionTracker.clearSelection(); } } public void setCountries(List<Country> countries) { this.countries = countries; if (selectionTracker == null) { return; } if (defaultCountry >= 0 && defaultCountry < countries.size()) { String countryCode = countries.get(defaultCountry).getCode(); selectionTracker.select(countryCode); } else { selectionTracker.clearSelection(); } } @SuppressLint("NotifyDataSetChanged") public void setDarkMode(boolean darkMode) { this.darkMode = darkMode; notifyDataSetChanged(); } @RequiresApi(api = Build.VERSION_CODES.N) @NonNull @Override public CountryPickerListItem onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = inflater.inflate(R.layout.country_picker_list_item, parent, false); return new CountryPickerListItem(view, this::onCountryClick); } @Override public void onBindViewHolder(@NonNull CountryPickerListItem holder, int position) { Country country = countries.get(position); // Set the country flag, country name, and calling code for the current list item holder.countryName.setText
(String.format("%s %s", country.getEmoji(), country.getName()));
holder.callingCode.setText(country.getCallingCode()); int textColor = darkMode ? Color.parseColor("#FFFFFF") : Color.parseColor("#000000"); holder.countryName.setTextColor(textColor); holder.callingCode.setTextColor(textColor); holder.bind(country); boolean isSelected = selectionTracker.isSelected(country.getCode()); holder.itemView.setActivated(isSelected); holder.highlight(isSelected, darkMode); } @Override public int getItemCount() { return countries.size(); } public void setSelectedIndex(int selectedIndex) { defaultCountry = selectedIndex; if (selectionTracker == null) { return; } if (selectedIndex >= 0 && selectedIndex < countries.size()) { String countryCode = countries.get(selectedIndex).getCode(); selectionTracker.select(countryCode); layoutManager.scrollToPosition(selectedIndex); } else { selectionTracker.clearSelection(); } } }
android/src/main/java/com/phonenumberinput/CountryPickerAdapter.java
gtomitsuka-rn-phone-number-input-2f2e43b
[ { "filename": "android/src/main/java/com/phonenumberinput/CountryPickerListItem.java", "retrieved_chunk": "import java.util.function.Consumer;\npublic class CountryPickerListItem extends RecyclerView.ViewHolder {\n TextView countryName; // includes emoji\n TextView callingCode;\n Country country;\n @RequiresApi(api = Build.VERSION_CODES.N)\n public CountryPickerListItem(@NonNull View itemView, Consumer<Integer> countryClickListener) {\n super(itemView);\n countryName = itemView.findViewById(R.id.country_name);\n callingCode = itemView.findViewById(R.id.calling_code);", "score": 0.8934308886528015 }, { "filename": "android/src/main/java/com/phonenumberinput/CountryDetailsLookup.java", "retrieved_chunk": " public CountryDetailsLookup(RecyclerView recyclerView) {\n this.recyclerView = recyclerView;\n }\n @Nullable\n @Override\n public ItemDetails<String> getItemDetails(@NonNull MotionEvent e) {\n View view = recyclerView.findChildViewUnder(e.getX(), e.getY());\n if (view != null) {\n RecyclerView.ViewHolder viewHolder = recyclerView.getChildViewHolder(view);\n if (viewHolder instanceof CountryPickerListItem) {", "score": 0.855722188949585 }, { "filename": "android/src/main/java/com/phonenumberinput/CountryPickerListItem.java", "retrieved_chunk": " itemView.setOnClickListener(l -> {\n System.out.println(\"called\");\n int position = getBindingAdapterPosition();\n if (position != RecyclerView.NO_POSITION) {\n countryClickListener.accept(position);\n }\n });\n }\n public void bind(Country country) {\n this.country = country;", "score": 0.8533580303192139 }, { "filename": "android/src/main/java/com/phonenumberinput/PhoneNumberInputViewManager.java", "retrieved_chunk": " CountryPickerAdapter adapter = new CountryPickerAdapter(view.getContext(), new ArrayList<>(), layoutManager);\n view.setAdapter(adapter);\n return view;\n }\n @Override\n @ReactProp(name = \"items\")\n public void setItems(PhoneNumberInputView view, @Nullable ReadableArray a) {\n List<Country> countries = new ArrayList<>();\n if (a != null) {\n for (int i = 0; i < a.size(); i++) {", "score": 0.8364500403404236 }, { "filename": "android/src/main/java/com/phonenumberinput/PhoneNumberInputViewManager.java", "retrieved_chunk": " }\n @Override\n @ReactProp(name = \"selectedIndex\")\n public void setSelectedIndex(PhoneNumberInputView view, int index) {\n CountryPickerAdapter adapter = (CountryPickerAdapter)view.getAdapter();\n if (adapter != null) {\n adapter.setSelectedIndex(index);\n }\n }\n}", "score": 0.8224766850471497 } ]
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": "import java.util.function.Consumer;\npublic class CountryPickerListItem extends RecyclerView.ViewHolder {\n TextView countryName; // includes emoji\n TextView callingCode;\n Country country;\n @RequiresApi(api = Build.VERSION_CODES.N)\n public CountryPickerListItem(@NonNull View itemView, Consumer<Integer> countryClickListener) {\n super(itemView);\n countryName = itemView.findViewById(R.id.country_name);\n callingCode = itemView.findViewById(R.id.calling_code);", "score": 0.8941665291786194 }, { "filename": "android/src/main/java/com/phonenumberinput/CountryDetailsLookup.java", "retrieved_chunk": " public CountryDetailsLookup(RecyclerView recyclerView) {\n this.recyclerView = recyclerView;\n }\n @Nullable\n @Override\n public ItemDetails<String> getItemDetails(@NonNull MotionEvent e) {\n View view = recyclerView.findChildViewUnder(e.getX(), e.getY());\n if (view != null) {\n RecyclerView.ViewHolder viewHolder = recyclerView.getChildViewHolder(view);\n if (viewHolder instanceof CountryPickerListItem) {", "score": 0.8538212180137634 }, { "filename": "android/src/main/java/com/phonenumberinput/CountryPickerListItem.java", "retrieved_chunk": " itemView.setOnClickListener(l -> {\n System.out.println(\"called\");\n int position = getBindingAdapterPosition();\n if (position != RecyclerView.NO_POSITION) {\n countryClickListener.accept(position);\n }\n });\n }\n public void bind(Country country) {\n this.country = country;", "score": 0.8529726266860962 }, { "filename": "android/src/main/java/com/phonenumberinput/PhoneNumberInputViewManager.java", "retrieved_chunk": " CountryPickerAdapter adapter = new CountryPickerAdapter(view.getContext(), new ArrayList<>(), layoutManager);\n view.setAdapter(adapter);\n return view;\n }\n @Override\n @ReactProp(name = \"items\")\n public void setItems(PhoneNumberInputView view, @Nullable ReadableArray a) {\n List<Country> countries = new ArrayList<>();\n if (a != null) {\n for (int i = 0; i < a.size(); i++) {", "score": 0.836005687713623 }, { "filename": "android/src/main/java/com/phonenumberinput/PhoneNumberInputViewManager.java", "retrieved_chunk": " }\n @Override\n @ReactProp(name = \"selectedIndex\")\n public void setSelectedIndex(PhoneNumberInputView view, int index) {\n CountryPickerAdapter adapter = (CountryPickerAdapter)view.getAdapter();\n if (adapter != null) {\n adapter.setSelectedIndex(index);\n }\n }\n}", "score": 0.8220874071121216 } ]
java
setText(String.format("%s %s", country.getEmoji(), country.getName()));
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": 0.8838759064674377 }, { "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": 0.8508263826370239 }, { "filename": "android/src/main/java/com/phonenumberinput/PhoneNumberInputViewManager.java", "retrieved_chunk": " CountryPickerAdapter adapter = new CountryPickerAdapter(view.getContext(), new ArrayList<>(), layoutManager);\n view.setAdapter(adapter);\n return view;\n }\n @Override\n @ReactProp(name = \"items\")\n public void setItems(PhoneNumberInputView view, @Nullable ReadableArray a) {\n List<Country> countries = new ArrayList<>();\n if (a != null) {\n for (int i = 0; i < a.size(); i++) {", "score": 0.8281400799751282 }, { "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": 0.825358510017395 }, { "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": 0.8170416355133057 } ]
java
country.getCode();
package com.phonenumberinput; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Color; import android.os.Build; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.recyclerview.selection.SelectionTracker; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.util.List; public class CountryPickerAdapter extends RecyclerView.Adapter<CountryPickerListItem> { private List<Country> countries; private final LayoutInflater inflater; private boolean darkMode; private SelectionTracker<String> selectionTracker; private int defaultCountry; private final LinearLayoutManager layoutManager; public CountryPickerAdapter(Context context, List<Country> countries, LinearLayoutManager layoutManager) { this.countries = countries; this.inflater = LayoutInflater.from(context); this.layoutManager = layoutManager; } public void onCountryClick(int index) { setSelectedIndex(index); notifyItemChanged(index); } public void setSelectionTracker(SelectionTracker<String> selectionTracker) { this.selectionTracker = selectionTracker; if (defaultCountry >= 0 && defaultCountry < countries.size()) { String countryCode = countries.get(defaultCountry).getCode(); selectionTracker.select(countryCode); } else { selectionTracker.clearSelection(); } } public void setCountries(List<Country> countries) { this.countries = countries; if (selectionTracker == null) { return; } if (defaultCountry >= 0 && defaultCountry < countries.size()) { String countryCode = countries.get(defaultCountry).getCode(); selectionTracker.select(countryCode); } else { selectionTracker.clearSelection(); } } @SuppressLint("NotifyDataSetChanged") public void setDarkMode(boolean darkMode) { this.darkMode = darkMode; notifyDataSetChanged(); } @RequiresApi(api = Build.VERSION_CODES.N) @NonNull @Override public CountryPickerListItem onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = inflater.inflate(R.layout.country_picker_list_item, parent, false); return new CountryPickerListItem(view, this::onCountryClick); } @Override public void onBindViewHolder(@NonNull CountryPickerListItem holder, int position) { Country country = countries.get(position); // Set the country flag, country name, and calling code for the current list item holder.countryName.setText(String.format("%s %s", country.getEmoji(), country.getName())); holder.callingCode.setText
(country.getCallingCode());
int textColor = darkMode ? Color.parseColor("#FFFFFF") : Color.parseColor("#000000"); holder.countryName.setTextColor(textColor); holder.callingCode.setTextColor(textColor); holder.bind(country); boolean isSelected = selectionTracker.isSelected(country.getCode()); holder.itemView.setActivated(isSelected); holder.highlight(isSelected, darkMode); } @Override public int getItemCount() { return countries.size(); } public void setSelectedIndex(int selectedIndex) { defaultCountry = selectedIndex; if (selectionTracker == null) { return; } if (selectedIndex >= 0 && selectedIndex < countries.size()) { String countryCode = countries.get(selectedIndex).getCode(); selectionTracker.select(countryCode); layoutManager.scrollToPosition(selectedIndex); } else { selectionTracker.clearSelection(); } } }
android/src/main/java/com/phonenumberinput/CountryPickerAdapter.java
gtomitsuka-rn-phone-number-input-2f2e43b
[ { "filename": "android/src/main/java/com/phonenumberinput/CountryPickerListItem.java", "retrieved_chunk": "import java.util.function.Consumer;\npublic class CountryPickerListItem extends RecyclerView.ViewHolder {\n TextView countryName; // includes emoji\n TextView callingCode;\n Country country;\n @RequiresApi(api = Build.VERSION_CODES.N)\n public CountryPickerListItem(@NonNull View itemView, Consumer<Integer> countryClickListener) {\n super(itemView);\n countryName = itemView.findViewById(R.id.country_name);\n callingCode = itemView.findViewById(R.id.calling_code);", "score": 0.8947408199310303 }, { "filename": "android/src/main/java/com/phonenumberinput/CountryPickerListItem.java", "retrieved_chunk": " itemView.setOnClickListener(l -> {\n System.out.println(\"called\");\n int position = getBindingAdapterPosition();\n if (position != RecyclerView.NO_POSITION) {\n countryClickListener.accept(position);\n }\n });\n }\n public void bind(Country country) {\n this.country = country;", "score": 0.8330968618392944 }, { "filename": "android/src/main/java/com/phonenumberinput/PhoneNumberInputViewManager.java", "retrieved_chunk": " ReadableMap map = a.getMap(i);\n String countryName = map.getString(\"name\");\n String countryEmoji = map.getString(\"emoji\");\n String countryCode = map.getString(\"code\");\n String callingCode = map.getString(\"tel\");\n Country country = new Country(countryName, countryCode, countryEmoji, callingCode);\n countries.add(country);\n }\n }\n CountryPickerAdapter adapter = (CountryPickerAdapter) view.getAdapter();", "score": 0.8127471208572388 }, { "filename": "android/src/main/java/com/phonenumberinput/CountryDetailsLookup.java", "retrieved_chunk": " public CountryDetailsLookup(RecyclerView recyclerView) {\n this.recyclerView = recyclerView;\n }\n @Nullable\n @Override\n public ItemDetails<String> getItemDetails(@NonNull MotionEvent e) {\n View view = recyclerView.findChildViewUnder(e.getX(), e.getY());\n if (view != null) {\n RecyclerView.ViewHolder viewHolder = recyclerView.getChildViewHolder(view);\n if (viewHolder instanceof CountryPickerListItem) {", "score": 0.8026416897773743 }, { "filename": "android/src/main/java/com/phonenumberinput/PhoneNumberInputViewManager.java", "retrieved_chunk": " }\n @Override\n @ReactProp(name = \"selectedIndex\")\n public void setSelectedIndex(PhoneNumberInputView view, int index) {\n CountryPickerAdapter adapter = (CountryPickerAdapter)view.getAdapter();\n if (adapter != null) {\n adapter.setSelectedIndex(index);\n }\n }\n}", "score": 0.8026177287101746 } ]
java
(country.getCallingCode());
/* * 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": " notificationManager.createNotificationChannel(saveTraceChannel);\n }\n public static Set<String> getActiveTags(Context context, SharedPreferences prefs, boolean onlyAvailable) {\n Set<String> tags = prefs.getStringSet(context.getString(R.string.pref_key_tags),\n getDefaultTagList());\n Set<String> available = TraceUtils.listCategories().keySet();\n if (onlyAvailable) {\n tags.retainAll(available);\n }\n Log.v(TAG, \"getActiveTags(onlyAvailable=\" + onlyAvailable + \") = \\\"\" + tags.toString() + \"\\\"\");", "score": 0.8486030101776123 }, { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " */\n static void updateDeveloperOptionsWatcher(Context context) {\n if (mDeveloperOptionsObserver == null) {\n Uri settingUri = Settings.Global.getUriFor(\n Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);\n mDeveloperOptionsObserver =\n new ContentObserver(new Handler()) {\n @Override\n public void onChange(boolean selfChange) {\n super.onChange(selfChange);", "score": 0.8275530338287354 }, { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " return tags;\n }\n public static Set<String> getActiveUnavailableTags(Context context, SharedPreferences prefs) {\n Set<String> tags = prefs.getStringSet(context.getString(R.string.pref_key_tags),\n getDefaultTagList());\n Set<String> available = TraceUtils.listCategories().keySet();\n tags.removeAll(available);\n Log.v(TAG, \"getActiveUnavailableTags() = \\\"\" + tags.toString() + \"\\\"\");\n return tags;\n }", "score": 0.8249534964561462 }, { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " }\n public static void updateTracing(Context context, boolean assumeTracingIsOff) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n boolean prefsTracingOn =\n prefs.getBoolean(context.getString(R.string.pref_key_tracing_on), false);\n boolean traceUtilsTracingOn = assumeTracingIsOff ? false : TraceUtils.isTracingOn();\n if (prefsTracingOn != traceUtilsTracingOn) {\n if (prefsTracingOn) {\n // Show notification if the tags in preferences are not all actually available.\n Set<String> activeAvailableTags = getActiveTags(context, prefs, true);", "score": 0.8232439160346985 }, { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " private static final String BETTERBUG_PACKAGE_NAME =\n \"com.google.android.apps.internal.betterbug\";\n private static Set<String> mDefaultTagList = null;\n private static ContentObserver mDeveloperOptionsObserver;\n @Override\n public void onReceive(Context context, Intent intent) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {\n Log.i(TAG, \"Received BOOT_COMPLETE\");\n createNotificationChannels(context);", "score": 0.8144880533218384 } ]
java
, String> available = TraceUtils.listCategories();
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.android.traceur; import android.system.Os; import android.util.Log; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Collection; import java.util.List; import java.util.TreeMap; import java.util.concurrent.TimeUnit; import perfetto.protos.DataSourceDescriptorOuterClass.DataSourceDescriptor; import perfetto.protos.FtraceDescriptorOuterClass.FtraceDescriptor.AtraceCategory; import perfetto.protos.TracingServiceStateOuterClass.TracingServiceState; import perfetto.protos.TracingServiceStateOuterClass.TracingServiceState.DataSource; /** * Utility functions for calling Perfetto */ public class PerfettoUtils implements TraceUtils.TraceEngine { static final String TAG = "Traceur"; public static final String NAME = "PERFETTO"; private static final String OUTPUT_EXTENSION = "perfetto-trace"; private static final String TEMP_DIR= "/data/local/traces/"; private static final String TEMP_TRACE_LOCATION = "/data/local/traces/.trace-in-progress.trace"; private static final String PERFETTO_TAG = "traceur"; private static final String MARKER = "PERFETTO_ARGUMENTS"; private static final int LIST_TIMEOUT_MS = 10000; private static final int STARTUP_TIMEOUT_MS = 10000; private static final int STOP_TIMEOUT_MS = 30000; private static final long MEGABYTES_TO_BYTES = 1024L * 1024L; private static final long MINUTES_TO_MILLISECONDS = 60L * 1000L; private static final String CAMERA_TAG = "camera"; private static final String GFX_TAG = "gfx"; private static final String MEMORY_TAG = "memory"; private static final String POWER_TAG = "power"; private static final String SCHED_TAG = "sched"; private static final String WEBVIEW_TAG = "webview"; public String getName() { return NAME; } public String getOutputExtension() { return OUTPUT_EXTENSION; } public boolean traceStart(Collection<String> tags, int bufferSizeKb, boolean apps, boolean attachToBugreport, boolean longTrace, int maxLongTraceSizeMb, int maxLongTraceDurationMinutes) { if (isTracingOn()) { Log.e(TAG, "Attempting to start perfetto trace but trace is already in progress"); return false; } else { // Ensure the temporary trace file is cleared. try { Files.deleteIfExists(Paths.get(TEMP_TRACE_LOCATION)); } catch (Exception e) { throw new RuntimeException(e); } } // The user chooses a per-CPU buffer size due to atrace limitations. // So we use this to ensure that we reserve the correctly-sized buffer. int numCpus = Runtime.getRuntime().availableProcessors(); // Build the perfetto config that will be passed on the command line. StringBuilder config = new StringBuilder() .append("write_into_file: true\n") // Ensure that we flush ftrace data every 30s even if cpus are idle. .append("flush_period_ms: 30000\n"); // If the user has flagged that in-progress trace sessions should be grabbed // during bugreports, and BetterBug is present. if (attachToBugreport) { config.append("bugreport_score: 500\n"); } // Indicates that perfetto should notify Traceur if the tracing session's status // changes. config.append("notify_traceur: true\n"); if (longTrace) { if (maxLongTraceSizeMb != 0) { config.append("max_file_size_bytes: " + (maxLongTraceSizeMb * MEGABYTES_TO_BYTES) + "\n"); } if (maxLongTraceDurationMinutes != 0) { config.append("duration_ms: " + (maxLongTraceDurationMinutes * MINUTES_TO_MILLISECONDS) + "\n"); } // Default value for long traces to write to file. config.append("file_write_period_ms: 1000\n"); } else { // For short traces, we don't write to the file. // So, always use the maximum value here: 7 days. config.append("file_write_period_ms: 604800000\n"); } config.append("incremental_state_config {\n") .append(" clear_period_ms: 15000\n") .append("} \n") // This is target_buffer: 0, which is used for ftrace and the ftrace-derived // android.gpu.memory. .append("buffers {\n") .append(" size_kb: " + bufferSizeKb * numCpus + "\n") .append(" fill_policy: RING_BUFFER\n") .append("} \n") // This is target_buffer: 1, which is used for additional data sources. .append("buffers {\n") .append(" size_kb: 2048\n") .append(" fill_policy: RING_BUFFER\n") .append("} \n") .append("data_sources {\n") .append(" config {\n") .append(" name: \"linux.ftrace\"\n") .append(" target_buffer: 0\n") .append(" ftrace_config {\n") .append(" symbolize_ksyms: true\n"); for (String tag : tags) { // Tags are expected to be only letters, numbers, and underscores. String cleanTag = tag.replaceAll("[^a-zA-Z0-9_]", ""); if (!cleanTag.equals(tag)) { Log.w(TAG, "Attempting to use an invalid tag: " + tag); } config.append(" atrace_categories: \"" + cleanTag + "\"\n"); } if (apps) { config.append(" atrace_apps: \"*\"\n"); } // Request a dense encoding of the common sched events (sched_switch, sched_waking). if (tags.contains(SCHED_TAG)) { config.append(" compact_sched {\n"); config.append(" enabled: true\n"); config.append(" }\n"); } // These parameters affect only the kernel trace buffer size and how // frequently it gets moved into the userspace buffer defined above. config.append(" buffer_size_kb: 8192\n") .append(" drain_period_ms: 1000\n") .append(" }\n") .append(" }\n") .append("}\n") .append(" \n"); // Captures initial counter values, updates are captured in ftrace. if (tags.contains(MEMORY_TAG) || tags.contains(GFX_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.gpu.memory\"\n") .append(" target_buffer: 0\n") .append(" }\n") .append("}\n"); } // For process association. If the memory tag is enabled, // poll periodically instead of just once at the beginning. config.append("data_sources {\n") .append(" config {\n") .append(" name: \"linux.process_stats\"\n") .append(" target_buffer: 1\n"); if (tags.contains(MEMORY_TAG)) { config.append(" process_stats_config {\n") .append(" proc_stats_poll_ms: 60000\n") .append(" }\n"); } config.append(" }\n") .append("} \n"); if (tags.contains(POWER_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.power\"\n") .append(" target_buffer: 1\n") .append(" android_power_config {\n"); if (longTrace) { config.append(" battery_poll_ms: 5000\n"); } else { config.append(" battery_poll_ms: 1000\n"); } config.append(" collect_power_rails: true\n") .append(" battery_counters: BATTERY_COUNTER_CAPACITY_PERCENT\n") .append(" battery_counters: BATTERY_COUNTER_CHARGE\n") .append(" battery_counters: BATTERY_COUNTER_CURRENT\n") .append(" }\n") .append(" }\n") .append("}\n"); } if (tags.contains(MEMORY_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.sys_stats\"\n") .append(" target_buffer: 1\n") .append(" sys_stats_config {\n") .append(" vmstat_period_ms: 1000\n") .append(" }\n") .append(" }\n") .append("}\n"); } if (tags.contains(GFX_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.surfaceflinger.frametimeline\"\n") .append(" }\n") .append("}\n"); } if (tags.contains(CAMERA_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.hardware.camera\"\n") .append(" target_buffer: 1\n") .append(" }\n") .append("}\n"); } // Also enable Chrome events when the WebView tag is enabled. if (tags.contains(WEBVIEW_TAG)) { String chromeTraceConfig = "{" + "\\\"record_mode\\\":\\\"record-continuously\\\"," + "\\\"included_categories\\\":[\\\"*\\\"]" + "}"; config.append("data_sources: {\n") .append(" config {\n") .append(" name: \"org.chromium.trace_event\"\n") .append(" chrome_config {\n") .append(" trace_config: \"" + chromeTraceConfig + "\"\n") .append(" }\n") .append(" }\n") .append("}\n") .append("data_sources: {\n") .append(" config {\n") .append(" name: \"org.chromium.trace_metadata\"\n") .append(" chrome_config {\n") .append(" trace_config: \"" + chromeTraceConfig + "\"\n") .append(" }\n") .append(" }\n") .append("}\n"); } String configString = config.toString(); // If the here-doc ends early, within the config string, exit immediately. // This should never happen. if (configString.contains(MARKER)) { throw new RuntimeException("The arguments to the Perfetto command are malformed."); } String cmd = "perfetto --detach=" + PERFETTO_TAG + " -o " + TEMP_TRACE_LOCATION + " -c - --txt" + " <<" + MARKER +"\n" + configString + "\n" + MARKER; Log.v(TAG, "Starting perfetto trace."); try { Process process = TraceUtils.execWithTimeout(cmd, TEMP_DIR, STARTUP_TIMEOUT_MS); if (process == null) { return false; } else if (process.exitValue() != 0) { Log.e(TAG, "perfetto traceStart failed with: " + process.exitValue()); return false; } } catch (Exception e) { throw new RuntimeException(e); } Log.v(TAG, "perfetto traceStart succeeded!"); return true; } public void traceStop() { Log.v(TAG, "Stopping perfetto trace."); if (!isTracingOn()) { Log.w(TAG, "No trace appears to be in progress. Stopping perfetto trace may not work."); } String cmd = "perfetto --stop --attach=" + PERFETTO_TAG; try { Process process = TraceUtils.execWithTimeout(cmd, null, STOP_TIMEOUT_MS); if (process != null && process.exitValue() != 0) { Log.e(TAG, "perfetto traceStop failed with: " + process.exitValue()); } } catch (Exception e) { throw new RuntimeException(e); } } public boolean traceDump(File outFile) { traceStop(); // Short-circuit if a trace was not stopped. if (isTracingOn()) { Log.e(TAG, "Trace was not stopped successfully, aborting trace dump."); return false; } // Short-circuit if the file we're trying to dump to doesn't exist. if (!Files.exists(Paths.get(TEMP_TRACE_LOCATION))) { Log.e(TAG, "In-progress trace file doesn't exist, aborting trace dump."); return false; } Log.v(TAG, "Saving perfetto trace to " + outFile); try { Os.rename(TEMP_TRACE_LOCATION, outFile.getCanonicalPath()); } catch (Exception e) { throw new RuntimeException(e); } outFile.setReadable(true, false); // (readable, ownerOnly) outFile.setWritable(true, false); // (readable, ownerOnly) return true; } public boolean isTracingOn() { String cmd = "perfetto --is_detached=" + PERFETTO_TAG; try { Process process = TraceUtils.exec(cmd); // 0 represents a detached process exists with this name // 2 represents no detached process with this name // 1 (or other error code) represents an error int result = process.waitFor(); if (result == 0) { return true; } else if (result == 2) { return false; } else { throw new RuntimeException("Perfetto error: " + result); } } catch (Exception e) { throw new RuntimeException(e); } } public static TreeMap<String,String> perfettoListCategories() { String cmd = "perfetto --query-raw"; Log.v(TAG, "Listing tags: " + cmd); try { TreeMap<String, String> result = new TreeMap<>(); // execWithTimeout() cannot be used because stdout must be consumed before the process // is terminated.
Process perfetto = TraceUtils.exec(cmd, null, false);
TracingServiceState serviceState = TracingServiceState.parseFrom(perfetto.getInputStream()); // Destroy the perfetto process if it times out. if (!perfetto.waitFor(LIST_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { Log.e(TAG, "perfettoListCategories timed out after " + LIST_TIMEOUT_MS + " ms."); perfetto.destroyForcibly(); return result; } // The perfetto process completed and failed, but does not need to be destroyed. if (perfetto.exitValue() != 0) { Log.e(TAG, "perfettoListCategories failed with: " + perfetto.exitValue()); } List<AtraceCategory> categories = null; for (DataSource dataSource : serviceState.getDataSourcesList()) { DataSourceDescriptor dataSrcDescriptor = dataSource.getDsDescriptor(); if (dataSrcDescriptor.getName().equals("linux.ftrace")){ categories = dataSrcDescriptor.getFtraceDescriptor().getAtraceCategoriesList(); break; } } if (categories != null) { for (AtraceCategory category : categories) { result.put(category.getName(), category.getDescription()); } } return result; } catch (Exception e) { throw new RuntimeException(e); } } }
src/com/android/traceur/PerfettoUtils.java
GrapheneOS-Archive-platform_packages_apps_Traceur-2e6c52a
[ { "filename": "src/com/android/traceur/TraceUtils.java", "retrieved_chunk": " public static boolean isTracingOn() {\n return mTraceEngine.isTracingOn();\n }\n public static TreeMap<String, String> listCategories() {\n return PerfettoUtils.perfettoListCategories();\n }\n public static void clearSavedTraces() {\n String cmd = \"rm -f \" + TRACE_DIRECTORY + \"trace-*.*trace\";\n Log.v(TAG, \"Clearing trace directory: \" + cmd);\n try {", "score": 0.8813933730125427 }, { "filename": "src/com/android/traceur/AtraceUtils.java", "retrieved_chunk": " } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n public boolean traceDump(File outFile) {\n String cmd = \"atrace --async_stop -z -c -o \" + outFile;\n Log.v(TAG, \"Dumping async atrace: \" + cmd);\n try {\n Process atrace = TraceUtils.exec(cmd);\n if (atrace.waitFor() != 0) {", "score": 0.8768800497055054 }, { "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": 0.8505141139030457 }, { "filename": "src/com/android/traceur/TraceUtils.java", "retrieved_chunk": " Process rm = exec(cmd);\n if (rm.waitFor() != 0) {\n Log.e(TAG, \"clearSavedTraces failed with: \" + rm.exitValue());\n }\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n public static Process exec(String cmd) throws IOException {\n return exec(cmd, null);", "score": 0.846474826335907 }, { "filename": "src/com/android/traceur/AtraceUtils.java", "retrieved_chunk": " return true;\n }\n public void traceStop() {\n String cmd = \"atrace --async_stop > /dev/null\";\n Log.v(TAG, \"Stopping async atrace: \" + cmd);\n try {\n Process atrace = TraceUtils.exec(cmd);\n if (atrace.waitFor() != 0) {\n Log.e(TAG, \"atraceStop failed with: \" + atrace.exitValue());\n }", "score": 0.8401757478713989 } ]
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": 0.9170659780502319 }, { "filename": "src/com/android/traceur/StopTraceService.java", "retrieved_chunk": " SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n boolean prefsTracingOn =\n prefs.getBoolean(context.getString(R.string.pref_key_tracing_on), false);\n // If the user thinks tracing is off and the trace processor agrees, we have no work to do.\n // We must still start a foreground service, but let's log as an FYI.\n if (!prefsTracingOn && !TraceUtils.isTracingOn()) {\n Log.i(TAG, \"StopTraceService does not see a trace to stop.\");\n }\n PreferenceManager.getDefaultSharedPreferences(context)\n .edit().putBoolean(context.getString(R.string.pref_key_tracing_on),", "score": 0.906833291053772 }, { "filename": "src/com/android/traceur/InternalReceiver.java", "retrieved_chunk": "import android.preference.PreferenceManager;\npublic class InternalReceiver extends BroadcastReceiver {\n public static final String START_ACTION = \"com.android.traceur.START\";\n @Override\n public void onReceive(Context context, Intent intent) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n if (START_ACTION.equals(intent.getAction())) {\n prefs.edit().putBoolean(\n context.getString(R.string.pref_key_tracing_on), true).commit();\n Receiver.updateTracing(context);", "score": 0.9045590162277222 }, { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " }\n public static void updateTracing(Context context, boolean assumeTracingIsOff) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n boolean prefsTracingOn =\n prefs.getBoolean(context.getString(R.string.pref_key_tracing_on), false);\n boolean traceUtilsTracingOn = assumeTracingIsOff ? false : TraceUtils.isTracingOn();\n if (prefsTracingOn != traceUtilsTracingOn) {\n if (prefsTracingOn) {\n // Show notification if the tags in preferences are not all actually available.\n Set<String> activeAvailableTags = getActiveTags(context, prefs, true);", "score": 0.8920966386795044 }, { "filename": "src/com/android/traceur/QsService.java", "retrieved_chunk": " * If tracing is being turned off, dump and offer to share. */\n @Override\n public void onClick() {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);\n boolean newTracingState = !prefs.getBoolean(getString(R.string.pref_key_tracing_on), false);\n prefs.edit().putBoolean(getString(R.string.pref_key_tracing_on), newTracingState).commit();\n Receiver.updateTracing(this);\n }\n}", "score": 0.8693112730979919 } ]
java
TraceUtils.traceStop();
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.android.traceur; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.database.ContentObserver; import android.net.Uri; import android.os.Build; import android.os.Handler; import android.os.RemoteException; import android.os.ServiceManager; import android.os.UserManager; import android.preference.PreferenceManager; import android.provider.Settings; import android.text.TextUtils; import android.util.ArraySet; import android.util.Log; import com.android.internal.statusbar.IStatusBarService; import java.util.Arrays; import java.util.List; import java.util.Set; public class Receiver extends BroadcastReceiver { public static final String STOP_ACTION = "com.android.traceur.STOP"; public static final String OPEN_ACTION = "com.android.traceur.OPEN"; public static final String BUGREPORT_STARTED = "com.android.internal.intent.action.BUGREPORT_STARTED"; public static final String NOTIFICATION_CHANNEL_TRACING = "trace-is-being-recorded"; public static final String NOTIFICATION_CHANNEL_OTHER = "system-tracing"; private static final List<String> TRACE_TAGS = Arrays.asList( "aidl", "am", "binder_driver", "camera", "dalvik", "disk", "freq", "gfx", "hal", "idle", "input", "memory", "memreclaim", "network", "power", "res", "sched", "sync", "thermal", "view", "webview", "wm", "workq"); /* The user list doesn't include workq or sync, because the user builds don't have * permissions for them. */ private static final List<String> TRACE_TAGS_USER = Arrays.asList( "aidl", "am", "binder_driver", "camera", "dalvik", "disk", "freq", "gfx", "hal", "idle", "input", "memory", "memreclaim", "network", "power", "res", "sched", "thermal", "view", "webview", "wm"); private static final String TAG = "Traceur"; private static final String BETTERBUG_PACKAGE_NAME = "com.google.android.apps.internal.betterbug"; private static Set<String> mDefaultTagList = null; private static ContentObserver mDeveloperOptionsObserver; @Override public void onReceive(Context context, Intent intent) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { Log.i(TAG, "Received BOOT_COMPLETE"); createNotificationChannels(context); updateDeveloperOptionsWatcher(context); // We know that Perfetto won't be tracing already at boot, so pass the // tracingIsOff argument to avoid the Perfetto check. updateTracing(context, /* assumeTracingIsOff= */ true); } else if (Intent.ACTION_USER_FOREGROUND.equals(intent.getAction())) { boolean developerOptionsEnabled = (1 == Settings.Global.getInt(context.getContentResolver(), Settings.Global.DEVELOPMENT_SETTINGS_ENABLED , 0)); UserManager userManager = context.getSystemService(UserManager.class); boolean isAdminUser = userManager.isAdminUser(); boolean debuggingDisallowed = userManager.hasUserRestriction( UserManager.DISALLOW_DEBUGGING_FEATURES); updateStorageProvider(context, developerOptionsEnabled && isAdminUser && !debuggingDisallowed); } else if (STOP_ACTION.equals(intent.getAction())) { prefs.edit().putBoolean( context.getString(R.string.pref_key_tracing_on), false).commit(); updateTracing(context); } else if (OPEN_ACTION.equals(intent.getAction())) { context.sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); context.startActivity(new Intent(context, MainActivity.class) .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); } else if (BUGREPORT_STARTED.equals(intent.getAction())) { // If stop_on_bugreport is set and attach_to_bugreport is not, stop tracing. // Otherwise, if attach_to_bugreport is set perfetto will end the session, // and we should not take action on the Traceur side. if (prefs.getBoolean(context.getString(R.string.pref_key_stop_on_bugreport), false) && !prefs.getBoolean(context.getString( R.string.pref_key_attach_to_bugreport), true)) { Log.d(TAG, "Bugreport started, ending trace."); prefs.edit().putBoolean(context.getString(R.string.pref_key_tracing_on), false).commit(); updateTracing(context); } } } /* * Updates the current tracing state based on the current state of preferences. */ public static void updateTracing(Context context) { updateTracing(context, false); } public static void updateTracing(Context context, boolean assumeTracingIsOff) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); boolean prefsTracingOn = prefs.getBoolean(context.getString(R.string.pref_key_tracing_on), false); boolean traceUtilsTracingOn = assumeTracingIsOff ?
false : TraceUtils.isTracingOn();
if (prefsTracingOn != traceUtilsTracingOn) { if (prefsTracingOn) { // Show notification if the tags in preferences are not all actually available. Set<String> activeAvailableTags = getActiveTags(context, prefs, true); Set<String> activeTags = getActiveTags(context, prefs, false); if (!activeAvailableTags.equals(activeTags)) { postCategoryNotification(context, prefs); } int bufferSize = Integer.parseInt( prefs.getString(context.getString(R.string.pref_key_buffer_size), context.getString(R.string.default_buffer_size))); boolean appTracing = prefs.getBoolean(context.getString(R.string.pref_key_apps), true); boolean longTrace = prefs.getBoolean(context.getString(R.string.pref_key_long_traces), true); int maxLongTraceSize = Integer.parseInt( prefs.getString(context.getString(R.string.pref_key_max_long_trace_size), context.getString(R.string.default_long_trace_size))); int maxLongTraceDuration = Integer.parseInt( prefs.getString(context.getString(R.string.pref_key_max_long_trace_duration), context.getString(R.string.default_long_trace_duration))); TraceService.startTracing(context, activeAvailableTags, bufferSize, appTracing, longTrace, maxLongTraceSize, maxLongTraceDuration); } else { TraceService.stopTracing(context); } } // Update the main UI and the QS tile. context.sendBroadcast(new Intent(MainFragment.ACTION_REFRESH_TAGS)); QsService.updateTile(); } /* * Updates the current Quick Settings tile state based on the current state * of preferences. */ public static void updateQuickSettings(Context context) { boolean quickSettingsEnabled = PreferenceManager.getDefaultSharedPreferences(context) .getBoolean(context.getString(R.string.pref_key_quick_setting), false); ComponentName name = new ComponentName(context, QsService.class); context.getPackageManager().setComponentEnabledSetting(name, quickSettingsEnabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); IStatusBarService statusBarService = IStatusBarService.Stub.asInterface( ServiceManager.checkService(Context.STATUS_BAR_SERVICE)); try { if (statusBarService != null) { if (quickSettingsEnabled) { statusBarService.addTile(name); } else { statusBarService.remTile(name); } } } catch (RemoteException e) { Log.e(TAG, "Failed to modify QS tile for Traceur.", e); } QsService.updateTile(); } /* * When Developer Options are toggled, also toggle the Storage Provider that * shows "System traces" in Files. * When Developer Options are turned off, reset the Show Quick Settings Tile * preference to false to hide the tile. The user will need to re-enable the * preference if they decide to turn Developer Options back on again. */ static void updateDeveloperOptionsWatcher(Context context) { if (mDeveloperOptionsObserver == null) { Uri settingUri = Settings.Global.getUriFor( Settings.Global.DEVELOPMENT_SETTINGS_ENABLED); mDeveloperOptionsObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { super.onChange(selfChange); boolean developerOptionsEnabled = (1 == Settings.Global.getInt(context.getContentResolver(), Settings.Global.DEVELOPMENT_SETTINGS_ENABLED , 0)); UserManager userManager = context.getSystemService(UserManager.class); boolean isAdminUser = userManager.isAdminUser(); boolean debuggingDisallowed = userManager.hasUserRestriction( UserManager.DISALLOW_DEBUGGING_FEATURES); updateStorageProvider(context, developerOptionsEnabled && isAdminUser && !debuggingDisallowed); if (!developerOptionsEnabled) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); prefs.edit().putBoolean( context.getString(R.string.pref_key_quick_setting), false) .commit(); updateQuickSettings(context); // Stop an ongoing trace if one exists. if (TraceUtils.isTracingOn()) { TraceService.stopTracingWithoutSaving(context); } } } }; context.getContentResolver().registerContentObserver(settingUri, false, mDeveloperOptionsObserver); mDeveloperOptionsObserver.onChange(true); } } // Enables/disables the System Traces storage component. enableProvider should be true iff // developer options are enabled and the current user is an admin user. static void updateStorageProvider(Context context, boolean enableProvider) { ComponentName name = new ComponentName(context, StorageProvider.class); context.getPackageManager().setComponentEnabledSetting(name, enableProvider ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); } private static void postCategoryNotification(Context context, SharedPreferences prefs) { Intent sendIntent = new Intent(context, MainActivity.class); String title = context.getString(R.string.tracing_categories_unavailable); String msg = TextUtils.join(", ", getActiveUnavailableTags(context, prefs)); final Notification.Builder builder = new Notification.Builder(context, NOTIFICATION_CHANNEL_OTHER) .setSmallIcon(R.drawable.bugfood_icon) .setContentTitle(title) .setTicker(title) .setContentText(msg) .setContentIntent(PendingIntent.getActivity( context, 0, sendIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE)) .setAutoCancel(true) .setLocalOnly(true) .setColor(context.getColor( com.android.internal.R.color.system_notification_accent_color)); if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LEANBACK)) { builder.extend(new Notification.TvExtender()); } context.getSystemService(NotificationManager.class) .notify(Receiver.class.getName(), 0, builder.build()); } private static void createNotificationChannels(Context context) { NotificationChannel tracingChannel = new NotificationChannel( NOTIFICATION_CHANNEL_TRACING, context.getString(R.string.trace_is_being_recorded), NotificationManager.IMPORTANCE_HIGH); tracingChannel.setBypassDnd(true); tracingChannel.enableVibration(true); tracingChannel.setSound(null, null); NotificationChannel saveTraceChannel = new NotificationChannel( NOTIFICATION_CHANNEL_OTHER, context.getString(R.string.saving_trace), NotificationManager.IMPORTANCE_HIGH); saveTraceChannel.setBypassDnd(true); saveTraceChannel.enableVibration(true); saveTraceChannel.setSound(null, null); NotificationManager notificationManager = context.getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(tracingChannel); notificationManager.createNotificationChannel(saveTraceChannel); } public static Set<String> getActiveTags(Context context, SharedPreferences prefs, boolean onlyAvailable) { Set<String> tags = prefs.getStringSet(context.getString(R.string.pref_key_tags), getDefaultTagList()); Set<String> available = TraceUtils.listCategories().keySet(); if (onlyAvailable) { tags.retainAll(available); } Log.v(TAG, "getActiveTags(onlyAvailable=" + onlyAvailable + ") = \"" + tags.toString() + "\""); return tags; } public static Set<String> getActiveUnavailableTags(Context context, SharedPreferences prefs) { Set<String> tags = prefs.getStringSet(context.getString(R.string.pref_key_tags), getDefaultTagList()); Set<String> available = TraceUtils.listCategories().keySet(); tags.removeAll(available); Log.v(TAG, "getActiveUnavailableTags() = \"" + tags.toString() + "\""); return tags; } public static Set<String> getDefaultTagList() { if (mDefaultTagList == null) { mDefaultTagList = new ArraySet<String>(Build.TYPE.equals("user") ? TRACE_TAGS_USER : TRACE_TAGS); } return mDefaultTagList; } }
src/com/android/traceur/Receiver.java
GrapheneOS-Archive-platform_packages_apps_Traceur-2e6c52a
[ { "filename": "src/com/android/traceur/StopTraceService.java", "retrieved_chunk": " SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n boolean prefsTracingOn =\n prefs.getBoolean(context.getString(R.string.pref_key_tracing_on), false);\n // If the user thinks tracing is off and the trace processor agrees, we have no work to do.\n // We must still start a foreground service, but let's log as an FYI.\n if (!prefsTracingOn && !TraceUtils.isTracingOn()) {\n Log.i(TAG, \"StopTraceService does not see a trace to stop.\");\n }\n PreferenceManager.getDefaultSharedPreferences(context)\n .edit().putBoolean(context.getString(R.string.pref_key_tracing_on),", "score": 0.9016065001487732 }, { "filename": "src/com/android/traceur/MainFragment.java", "retrieved_chunk": " * system.\n */\n private void refreshUi(boolean restoreDefaultTags) {\n Context context = getContext();\n // Make sure the Record Trace toggle matches the preference value.\n mTracingOn.setChecked(mTracingOn.getPreferenceManager().getSharedPreferences().getBoolean(\n mTracingOn.getKey(), false));\n SwitchPreference stopOnReport =\n (SwitchPreference) findPreference(getString(R.string.pref_key_stop_on_bugreport));\n stopOnReport.setChecked(mPrefs.getBoolean(stopOnReport.getKey(), false));", "score": 0.8897242546081543 }, { "filename": "src/com/android/traceur/QsService.java", "retrieved_chunk": " * If tracing is being turned off, dump and offer to share. */\n @Override\n public void onClick() {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);\n boolean newTracingState = !prefs.getBoolean(getString(R.string.pref_key_tracing_on), false);\n prefs.edit().putBoolean(getString(R.string.pref_key_tracing_on), newTracingState).commit();\n Receiver.updateTracing(this);\n }\n}", "score": 0.8798108696937561 }, { "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": 0.8774623870849609 }, { "filename": "src/com/android/traceur/InternalReceiver.java", "retrieved_chunk": "import android.preference.PreferenceManager;\npublic class InternalReceiver extends BroadcastReceiver {\n public static final String START_ACTION = \"com.android.traceur.START\";\n @Override\n public void onReceive(Context context, Intent intent) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n if (START_ACTION.equals(intent.getAction())) {\n prefs.edit().putBoolean(\n context.getString(R.string.pref_key_tracing_on), true).commit();\n Receiver.updateTracing(context);", "score": 0.874183177947998 } ]
java
false : TraceUtils.isTracingOn();
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.android.traceur; import android.app.IntentService; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.UserManager; import android.preference.PreferenceManager; import android.provider.Settings; import android.text.format.DateUtils; import android.util.EventLog; import android.util.Log; import java.io.File; import java.util.ArrayList; import java.util.Collection; public class TraceService extends IntentService { /* Indicates Perfetto has stopped tracing due to either the supplied long trace limitations * or limited storage capacity. */ static String INTENT_ACTION_NOTIFY_SESSION_STOPPED = "com.android.traceur.NOTIFY_SESSION_STOPPED"; /* Indicates a Traceur-associated tracing session has been attached to a bug report */ static String INTENT_ACTION_NOTIFY_SESSION_STOLEN = "com.android.traceur.NOTIFY_SESSION_STOLEN"; private static String INTENT_ACTION_STOP_TRACING = "com.android.traceur.STOP_TRACING"; private static String INTENT_ACTION_START_TRACING = "com.android.traceur.START_TRACING"; private static String INTENT_EXTRA_TAGS= "tags"; private static String INTENT_EXTRA_BUFFER = "buffer"; private static String INTENT_EXTRA_APPS = "apps"; private static String INTENT_EXTRA_LONG_TRACE = "long_trace"; private static String INTENT_EXTRA_LONG_TRACE_SIZE = "long_trace_size"; private static String INTENT_EXTRA_LONG_TRACE_DURATION = "long_trace_duration"; private static String BETTERBUG_PACKAGE_NAME = "com.google.android.apps.internal.betterbug"; private static int TRACE_NOTIFICATION = 1; private static int SAVING_TRACE_NOTIFICATION = 2; private static final int MIN_KEEP_COUNT = 3; private static final long MIN_KEEP_AGE = 4 * DateUtils.WEEK_IN_MILLIS; public static void startTracing(final Context context, Collection<String> tags, int bufferSizeKb, boolean apps, boolean longTrace, int maxLongTraceSizeMb, int maxLongTraceDurationMinutes) { Intent intent = new Intent(context, TraceService.class); intent.setAction(INTENT_ACTION_START_TRACING); intent.putExtra(INTENT_EXTRA_TAGS, new ArrayList(tags)); intent.putExtra(INTENT_EXTRA_BUFFER, bufferSizeKb); intent.putExtra(INTENT_EXTRA_APPS, apps); intent.putExtra(INTENT_EXTRA_LONG_TRACE, longTrace); intent.putExtra(INTENT_EXTRA_LONG_TRACE_SIZE, maxLongTraceSizeMb); intent.putExtra(INTENT_EXTRA_LONG_TRACE_DURATION, maxLongTraceDurationMinutes); context.startForegroundService(intent); } public static void stopTracing(final Context context) { Intent intent = new Intent(context, TraceService.class); intent.setAction(INTENT_ACTION_STOP_TRACING); context.startForegroundService(intent); } // Silently stops a trace without saving it. This is intended to be called when tracing is no // longer allowed, i.e. if developer options are turned off while tracing. The usual method of // stopping a trace via intent, stopTracing(), will not work because intents cannot be received // when developer options are disabled. static void stopTracingWithoutSaving(final Context context) { NotificationManager notificationManager = context.getSystemService(NotificationManager.class); notificationManager.cancel(TRACE_NOTIFICATION); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); prefs.edit().putBoolean(context.getString( R.string.pref_key_tracing_on), false).commit(); TraceUtils.traceStop(); } public TraceService() { this("TraceService"); } protected TraceService(String name) { super(name); setIntentRedelivery(true); } @Override public void onHandleIntent(Intent intent) { Context context = getApplicationContext(); // Checks that developer options are enabled and the user is an admin before continuing. boolean developerOptionsEnabled = Settings.Global.getInt(context.getContentResolver(), Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) != 0; if (!developerOptionsEnabled) { // Refer to b/204992293. EventLog.writeEvent(0x534e4554, "204992293", -1, ""); return; } UserManager userManager = context.getSystemService(UserManager.class); boolean isAdminUser = userManager.isAdminUser(); boolean debuggingDisallowed = userManager.hasUserRestriction( UserManager.DISALLOW_DEBUGGING_FEATURES); if (!isAdminUser || debuggingDisallowed) { return; } if (intent.getAction().equals(INTENT_ACTION_START_TRACING)) { startTracingInternal(intent.getStringArrayListExtra(INTENT_EXTRA_TAGS), intent.getIntExtra(INTENT_EXTRA_BUFFER, Integer.parseInt(context.getString(R.string.default_buffer_size))), intent.getBooleanExtra(INTENT_EXTRA_APPS, false), intent.getBooleanExtra(INTENT_EXTRA_LONG_TRACE, false), intent.getIntExtra(INTENT_EXTRA_LONG_TRACE_SIZE, Integer.parseInt(context.getString(R.string.default_long_trace_size))), intent.getIntExtra(INTENT_EXTRA_LONG_TRACE_DURATION, Integer.parseInt(context.getString(R.string.default_long_trace_duration)))); } else if (intent.getAction().equals(INTENT_ACTION_STOP_TRACING)) { stopTracingInternal(TraceUtils.getOutputFilename(), false, false); } else if (intent.getAction().equals(INTENT_ACTION_NOTIFY_SESSION_STOPPED)) { stopTracingInternal(TraceUtils.getOutputFilename(), true, false); } else if (intent.getAction().equals(INTENT_ACTION_NOTIFY_SESSION_STOLEN)) { stopTracingInternal("", false, true); } } private void startTracingInternal(Collection<String> tags, int bufferSizeKb, boolean appTracing, boolean longTrace, int maxLongTraceSizeMb, int maxLongTraceDurationMinutes) { Context context = getApplicationContext(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); Intent stopIntent = new Intent(Receiver.STOP_ACTION, null, context, Receiver.class); stopIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); String title = context.getString(R.string.trace_is_being_recorded); String msg = context.getString(R.string.tap_to_stop_tracing); boolean attachToBugreport = prefs.getBoolean(context.getString(R.string.pref_key_attach_to_bugreport), true); Notification.Builder notification = new Notification.Builder(context, Receiver.NOTIFICATION_CHANNEL_TRACING) .setSmallIcon(R.drawable.bugfood_icon) .setContentTitle(title) .setTicker(title) .setContentText(msg) .setContentIntent( PendingIntent.getBroadcast(context, 0, stopIntent, PendingIntent.FLAG_IMMUTABLE)) .setOngoing(true) .setLocalOnly(true) .setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE) .setColor(getColor( com.android.internal.R.color.system_notification_accent_color)); if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LEANBACK)) { notification.extend(new Notification.TvExtender()); } startForeground(TRACE_NOTIFICATION, notification.build()); if
(TraceUtils.traceStart(tags, bufferSizeKb, appTracing, longTrace, attachToBugreport, maxLongTraceSizeMb, maxLongTraceDurationMinutes)) {
stopForeground(Service.STOP_FOREGROUND_DETACH); } else { // Starting the trace was unsuccessful, so ensure that tracing // is stopped and the preference is reset. TraceUtils.traceStop(); prefs.edit().putBoolean(context.getString(R.string.pref_key_tracing_on), false).commit(); QsService.updateTile(); stopForeground(Service.STOP_FOREGROUND_REMOVE); } } private void stopTracingInternal(String outputFilename, boolean forceStop, boolean sessionStolen) { Context context = getApplicationContext(); NotificationManager notificationManager = getSystemService(NotificationManager.class); Notification.Builder notification; if (sessionStolen) { notification = getBaseTraceurNotification() .setContentTitle(getString(R.string.attaching_to_report)) .setTicker(getString(R.string.attaching_to_report)) .setProgress(1, 0, true); } else { notification = getBaseTraceurNotification() .setContentTitle(getString(R.string.saving_trace)) .setTicker(getString(R.string.saving_trace)) .setProgress(1, 0, true); } startForeground(SAVING_TRACE_NOTIFICATION, notification.build()); notificationManager.cancel(TRACE_NOTIFICATION); if (sessionStolen) { Notification.Builder notificationAttached = getBaseTraceurNotification() .setContentTitle(getString(R.string.attached_to_report)) .setTicker(getString(R.string.attached_to_report)) .setAutoCancel(true); Intent openIntent = getPackageManager().getLaunchIntentForPackage(BETTERBUG_PACKAGE_NAME); if (openIntent != null) { // Add "Tap to open BetterBug" to notification only if intent is non-null. notificationAttached.setContentText(getString( R.string.attached_to_report_summary)); notificationAttached.setContentIntent(PendingIntent.getActivity( context, 0, openIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE)); } // Adds an action button to the notification for starting a new trace. Intent restartIntent = new Intent(context, InternalReceiver.class); restartIntent.setAction(InternalReceiver.START_ACTION); PendingIntent restartPendingIntent = PendingIntent.getBroadcast(context, 0, restartIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE); Notification.Action action = new Notification.Action.Builder( R.drawable.bugfood_icon, context.getString(R.string.start_new_trace), restartPendingIntent).build(); notificationAttached.addAction(action); NotificationManager.from(context).notify(0, notificationAttached.build()); } else { File file = TraceUtils.getOutputFile(outputFilename); if (TraceUtils.traceDump(file)) { FileSender.postNotification(getApplicationContext(), file); } } stopForeground(Service.STOP_FOREGROUND_REMOVE); TraceUtils.cleanupOlderFiles(MIN_KEEP_COUNT, MIN_KEEP_AGE); } private Notification.Builder getBaseTraceurNotification() { Context context = getApplicationContext(); Notification.Builder notification = new Notification.Builder(this, Receiver.NOTIFICATION_CHANNEL_OTHER) .setSmallIcon(R.drawable.bugfood_icon) .setLocalOnly(true) .setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE) .setColor(context.getColor( com.android.internal.R.color.system_notification_accent_color)); if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LEANBACK)) { notification.extend(new Notification.TvExtender()); } return notification; } }
src/com/android/traceur/TraceService.java
GrapheneOS-Archive-platform_packages_apps_Traceur-2e6c52a
[ { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " | PendingIntent.FLAG_CANCEL_CURRENT\n | PendingIntent.FLAG_IMMUTABLE))\n .setAutoCancel(true)\n .setLocalOnly(true)\n .setColor(context.getColor(\n com.android.internal.R.color.system_notification_accent_color));\n if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {\n builder.extend(new Notification.TvExtender());\n }\n context.getSystemService(NotificationManager.class)", "score": 0.8874279260635376 }, { "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": 0.8727195262908936 }, { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " NotificationChannel saveTraceChannel = new NotificationChannel(\n NOTIFICATION_CHANNEL_OTHER,\n context.getString(R.string.saving_trace),\n NotificationManager.IMPORTANCE_HIGH);\n saveTraceChannel.setBypassDnd(true);\n saveTraceChannel.enableVibration(true);\n saveTraceChannel.setSound(null, null);\n NotificationManager notificationManager =\n context.getSystemService(NotificationManager.class);\n notificationManager.createNotificationChannel(tracingChannel);", "score": 0.8353922367095947 }, { "filename": "src/com/android/traceur/FileSender.java", "retrieved_chunk": " new Notification.Builder(context, Receiver.NOTIFICATION_CHANNEL_OTHER)\n .setSmallIcon(R.drawable.bugfood_icon)\n .setContentTitle(context.getString(R.string.trace_saved))\n .setTicker(context.getString(R.string.trace_saved))\n .setContentText(context.getString(R.string.tap_to_share))\n .setContentIntent(PendingIntent.getActivity(\n context, traceUri.hashCode(), intent, PendingIntent.FLAG_ONE_SHOT\n | PendingIntent.FLAG_CANCEL_CURRENT\n | PendingIntent.FLAG_IMMUTABLE))\n .setAutoCancel(true)", "score": 0.8238461017608643 }, { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " .notify(Receiver.class.getName(), 0, builder.build());\n }\n private static void createNotificationChannels(Context context) {\n NotificationChannel tracingChannel = new NotificationChannel(\n NOTIFICATION_CHANNEL_TRACING,\n context.getString(R.string.trace_is_being_recorded),\n NotificationManager.IMPORTANCE_HIGH);\n tracingChannel.setBypassDnd(true);\n tracingChannel.enableVibration(true);\n tracingChannel.setSound(null, null);", "score": 0.8196300268173218 } ]
java
(TraceUtils.traceStart(tags, bufferSizeKb, appTracing, longTrace, attachToBugreport, maxLongTraceSizeMb, maxLongTraceDurationMinutes)) {
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.android.traceur; import android.system.Os; import android.util.Log; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Collection; import java.util.List; import java.util.TreeMap; import java.util.concurrent.TimeUnit; import perfetto.protos.DataSourceDescriptorOuterClass.DataSourceDescriptor; import perfetto.protos.FtraceDescriptorOuterClass.FtraceDescriptor.AtraceCategory; import perfetto.protos.TracingServiceStateOuterClass.TracingServiceState; import perfetto.protos.TracingServiceStateOuterClass.TracingServiceState.DataSource; /** * Utility functions for calling Perfetto */ public class PerfettoUtils implements TraceUtils.TraceEngine { static final String TAG = "Traceur"; public static final String NAME = "PERFETTO"; private static final String OUTPUT_EXTENSION = "perfetto-trace"; private static final String TEMP_DIR= "/data/local/traces/"; private static final String TEMP_TRACE_LOCATION = "/data/local/traces/.trace-in-progress.trace"; private static final String PERFETTO_TAG = "traceur"; private static final String MARKER = "PERFETTO_ARGUMENTS"; private static final int LIST_TIMEOUT_MS = 10000; private static final int STARTUP_TIMEOUT_MS = 10000; private static final int STOP_TIMEOUT_MS = 30000; private static final long MEGABYTES_TO_BYTES = 1024L * 1024L; private static final long MINUTES_TO_MILLISECONDS = 60L * 1000L; private static final String CAMERA_TAG = "camera"; private static final String GFX_TAG = "gfx"; private static final String MEMORY_TAG = "memory"; private static final String POWER_TAG = "power"; private static final String SCHED_TAG = "sched"; private static final String WEBVIEW_TAG = "webview"; public String getName() { return NAME; } public String getOutputExtension() { return OUTPUT_EXTENSION; } public boolean traceStart(Collection<String> tags, int bufferSizeKb, boolean apps, boolean attachToBugreport, boolean longTrace, int maxLongTraceSizeMb, int maxLongTraceDurationMinutes) { if (isTracingOn()) { Log.e(TAG, "Attempting to start perfetto trace but trace is already in progress"); return false; } else { // Ensure the temporary trace file is cleared. try { Files.deleteIfExists(Paths.get(TEMP_TRACE_LOCATION)); } catch (Exception e) { throw new RuntimeException(e); } } // The user chooses a per-CPU buffer size due to atrace limitations. // So we use this to ensure that we reserve the correctly-sized buffer. int numCpus = Runtime.getRuntime().availableProcessors(); // Build the perfetto config that will be passed on the command line. StringBuilder config = new StringBuilder() .append("write_into_file: true\n") // Ensure that we flush ftrace data every 30s even if cpus are idle. .append("flush_period_ms: 30000\n"); // If the user has flagged that in-progress trace sessions should be grabbed // during bugreports, and BetterBug is present. if (attachToBugreport) { config.append("bugreport_score: 500\n"); } // Indicates that perfetto should notify Traceur if the tracing session's status // changes. config.append("notify_traceur: true\n"); if (longTrace) { if (maxLongTraceSizeMb != 0) { config.append("max_file_size_bytes: " + (maxLongTraceSizeMb * MEGABYTES_TO_BYTES) + "\n"); } if (maxLongTraceDurationMinutes != 0) { config.append("duration_ms: " + (maxLongTraceDurationMinutes * MINUTES_TO_MILLISECONDS) + "\n"); } // Default value for long traces to write to file. config.append("file_write_period_ms: 1000\n"); } else { // For short traces, we don't write to the file. // So, always use the maximum value here: 7 days. config.append("file_write_period_ms: 604800000\n"); } config.append("incremental_state_config {\n") .append(" clear_period_ms: 15000\n") .append("} \n") // This is target_buffer: 0, which is used for ftrace and the ftrace-derived // android.gpu.memory. .append("buffers {\n") .append(" size_kb: " + bufferSizeKb * numCpus + "\n") .append(" fill_policy: RING_BUFFER\n") .append("} \n") // This is target_buffer: 1, which is used for additional data sources. .append("buffers {\n") .append(" size_kb: 2048\n") .append(" fill_policy: RING_BUFFER\n") .append("} \n") .append("data_sources {\n") .append(" config {\n") .append(" name: \"linux.ftrace\"\n") .append(" target_buffer: 0\n") .append(" ftrace_config {\n") .append(" symbolize_ksyms: true\n"); for (String tag : tags) { // Tags are expected to be only letters, numbers, and underscores. String cleanTag = tag.replaceAll("[^a-zA-Z0-9_]", ""); if (!cleanTag.equals(tag)) { Log.w(TAG, "Attempting to use an invalid tag: " + tag); } config.append(" atrace_categories: \"" + cleanTag + "\"\n"); } if (apps) { config.append(" atrace_apps: \"*\"\n"); } // Request a dense encoding of the common sched events (sched_switch, sched_waking). if (tags.contains(SCHED_TAG)) { config.append(" compact_sched {\n"); config.append(" enabled: true\n"); config.append(" }\n"); } // These parameters affect only the kernel trace buffer size and how // frequently it gets moved into the userspace buffer defined above. config.append(" buffer_size_kb: 8192\n") .append(" drain_period_ms: 1000\n") .append(" }\n") .append(" }\n") .append("}\n") .append(" \n"); // Captures initial counter values, updates are captured in ftrace. if (tags.contains(MEMORY_TAG) || tags.contains(GFX_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.gpu.memory\"\n") .append(" target_buffer: 0\n") .append(" }\n") .append("}\n"); } // For process association. If the memory tag is enabled, // poll periodically instead of just once at the beginning. config.append("data_sources {\n") .append(" config {\n") .append(" name: \"linux.process_stats\"\n") .append(" target_buffer: 1\n"); if (tags.contains(MEMORY_TAG)) { config.append(" process_stats_config {\n") .append(" proc_stats_poll_ms: 60000\n") .append(" }\n"); } config.append(" }\n") .append("} \n"); if (tags.contains(POWER_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.power\"\n") .append(" target_buffer: 1\n") .append(" android_power_config {\n"); if (longTrace) { config.append(" battery_poll_ms: 5000\n"); } else { config.append(" battery_poll_ms: 1000\n"); } config.append(" collect_power_rails: true\n") .append(" battery_counters: BATTERY_COUNTER_CAPACITY_PERCENT\n") .append(" battery_counters: BATTERY_COUNTER_CHARGE\n") .append(" battery_counters: BATTERY_COUNTER_CURRENT\n") .append(" }\n") .append(" }\n") .append("}\n"); } if (tags.contains(MEMORY_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.sys_stats\"\n") .append(" target_buffer: 1\n") .append(" sys_stats_config {\n") .append(" vmstat_period_ms: 1000\n") .append(" }\n") .append(" }\n") .append("}\n"); } if (tags.contains(GFX_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.surfaceflinger.frametimeline\"\n") .append(" }\n") .append("}\n"); } if (tags.contains(CAMERA_TAG)) { config.append("data_sources: {\n") .append(" config { \n") .append(" name: \"android.hardware.camera\"\n") .append(" target_buffer: 1\n") .append(" }\n") .append("}\n"); } // Also enable Chrome events when the WebView tag is enabled. if (tags.contains(WEBVIEW_TAG)) { String chromeTraceConfig = "{" + "\\\"record_mode\\\":\\\"record-continuously\\\"," + "\\\"included_categories\\\":[\\\"*\\\"]" + "}"; config.append("data_sources: {\n") .append(" config {\n") .append(" name: \"org.chromium.trace_event\"\n") .append(" chrome_config {\n") .append(" trace_config: \"" + chromeTraceConfig + "\"\n") .append(" }\n") .append(" }\n") .append("}\n") .append("data_sources: {\n") .append(" config {\n") .append(" name: \"org.chromium.trace_metadata\"\n") .append(" chrome_config {\n") .append(" trace_config: \"" + chromeTraceConfig + "\"\n") .append(" }\n") .append(" }\n") .append("}\n"); } String configString = config.toString(); // If the here-doc ends early, within the config string, exit immediately. // This should never happen. if (configString.contains(MARKER)) { throw new RuntimeException("The arguments to the Perfetto command are malformed."); } String cmd = "perfetto --detach=" + PERFETTO_TAG + " -o " + TEMP_TRACE_LOCATION + " -c - --txt" + " <<" + MARKER +"\n" + configString + "\n" + MARKER; Log.v(TAG, "Starting perfetto trace."); try { Process process = TraceUtils.execWithTimeout(cmd, TEMP_DIR, STARTUP_TIMEOUT_MS); if (process == null) { return false; } else if (process.exitValue() != 0) { Log.e(TAG, "perfetto traceStart failed with: " + process.exitValue()); return false; } } catch (Exception e) { throw new RuntimeException(e); } Log.v(TAG, "perfetto traceStart succeeded!"); return true; } public void traceStop() { Log.v(TAG, "Stopping perfetto trace."); if (!isTracingOn()) { Log.w(TAG, "No trace appears to be in progress. Stopping perfetto trace may not work."); } String cmd = "perfetto --stop --attach=" + PERFETTO_TAG; try { Process process = TraceUtils.execWithTimeout(cmd, null, STOP_TIMEOUT_MS); if (process != null && process.exitValue() != 0) { Log.e(TAG, "perfetto traceStop failed with: " + process.exitValue()); } } catch (Exception e) { throw new RuntimeException(e); } } public boolean traceDump(File outFile) { traceStop(); // Short-circuit if a trace was not stopped. if (isTracingOn()) { Log.e(TAG, "Trace was not stopped successfully, aborting trace dump."); return false; } // Short-circuit if the file we're trying to dump to doesn't exist. if (!Files.exists(Paths.get(TEMP_TRACE_LOCATION))) { Log.e(TAG, "In-progress trace file doesn't exist, aborting trace dump."); return false; } Log.v(TAG, "Saving perfetto trace to " + outFile); try { Os.rename(TEMP_TRACE_LOCATION, outFile.getCanonicalPath()); } catch (Exception e) { throw new RuntimeException(e); } outFile.setReadable(true, false); // (readable, ownerOnly) outFile.setWritable(true, false); // (readable, ownerOnly) return true; } public boolean isTracingOn() { String cmd = "perfetto --is_detached=" + PERFETTO_TAG; try {
Process process = TraceUtils.exec(cmd);
// 0 represents a detached process exists with this name // 2 represents no detached process with this name // 1 (or other error code) represents an error int result = process.waitFor(); if (result == 0) { return true; } else if (result == 2) { return false; } else { throw new RuntimeException("Perfetto error: " + result); } } catch (Exception e) { throw new RuntimeException(e); } } public static TreeMap<String,String> perfettoListCategories() { String cmd = "perfetto --query-raw"; Log.v(TAG, "Listing tags: " + cmd); try { TreeMap<String, String> result = new TreeMap<>(); // execWithTimeout() cannot be used because stdout must be consumed before the process // is terminated. Process perfetto = TraceUtils.exec(cmd, null, false); TracingServiceState serviceState = TracingServiceState.parseFrom(perfetto.getInputStream()); // Destroy the perfetto process if it times out. if (!perfetto.waitFor(LIST_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { Log.e(TAG, "perfettoListCategories timed out after " + LIST_TIMEOUT_MS + " ms."); perfetto.destroyForcibly(); return result; } // The perfetto process completed and failed, but does not need to be destroyed. if (perfetto.exitValue() != 0) { Log.e(TAG, "perfettoListCategories failed with: " + perfetto.exitValue()); } List<AtraceCategory> categories = null; for (DataSource dataSource : serviceState.getDataSourcesList()) { DataSourceDescriptor dataSrcDescriptor = dataSource.getDsDescriptor(); if (dataSrcDescriptor.getName().equals("linux.ftrace")){ categories = dataSrcDescriptor.getFtraceDescriptor().getAtraceCategoriesList(); break; } } if (categories != null) { for (AtraceCategory category : categories) { result.put(category.getName(), category.getDescription()); } } return result; } catch (Exception e) { throw new RuntimeException(e); } } }
src/com/android/traceur/PerfettoUtils.java
GrapheneOS-Archive-platform_packages_apps_Traceur-2e6c52a
[ { "filename": "src/com/android/traceur/AtraceUtils.java", "retrieved_chunk": " // Set the new file world readable to allow it to be adb pulled.\n outFile.setReadable(true, false); // (readable, ownerOnly)\n outFile.setWritable(true, false); // (readable, ownerOnly)\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n return true;\n }\n public boolean isTracingOn() {\n boolean userInitiatedTracingFlag =", "score": 0.888396680355072 }, { "filename": "src/com/android/traceur/AtraceUtils.java", "retrieved_chunk": " } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n public boolean traceDump(File outFile) {\n String cmd = \"atrace --async_stop -z -c -o \" + outFile;\n Log.v(TAG, \"Dumping async atrace: \" + cmd);\n try {\n Process atrace = TraceUtils.exec(cmd);\n if (atrace.waitFor() != 0) {", "score": 0.8315310478210449 }, { "filename": "src/com/android/traceur/AtraceUtils.java", "retrieved_chunk": " Log.e(TAG, \"atraceDump failed with: \" + atrace.exitValue());\n return false;\n }\n Process ps = TraceUtils.exec(\"ps -AT\", null, false);\n new Streamer(\"atraceDump:ps:stdout\",\n ps.getInputStream(), new FileOutputStream(outFile, true /* append */));\n if (ps.waitFor() != 0) {\n Log.e(TAG, \"atraceDump:ps failed with: \" + ps.exitValue());\n return false;\n }", "score": 0.7947582006454468 }, { "filename": "src/com/android/traceur/AtraceUtils.java", "retrieved_chunk": " return true;\n }\n public void traceStop() {\n String cmd = \"atrace --async_stop > /dev/null\";\n Log.v(TAG, \"Stopping async atrace: \" + cmd);\n try {\n Process atrace = TraceUtils.exec(cmd);\n if (atrace.waitFor() != 0) {\n Log.e(TAG, \"atraceStop failed with: \" + atrace.exitValue());\n }", "score": 0.7842453122138977 }, { "filename": "src/com/android/traceur/TraceUtils.java", "retrieved_chunk": " public static boolean isTracingOn() {\n return mTraceEngine.isTracingOn();\n }\n public static TreeMap<String, String> listCategories() {\n return PerfettoUtils.perfettoListCategories();\n }\n public static void clearSavedTraces() {\n String cmd = \"rm -f \" + TRACE_DIRECTORY + \"trace-*.*trace\";\n Log.v(TAG, \"Clearing trace directory: \" + cmd);\n try {", "score": 0.782002329826355 } ]
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.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": 0.8079102039337158 }, { "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": 0.7937235832214355 }, { "filename": "src/com/android/traceur/TraceUtils.java", "retrieved_chunk": " public static boolean isTracingOn() {\n return mTraceEngine.isTracingOn();\n }\n public static TreeMap<String, String> listCategories() {\n return PerfettoUtils.perfettoListCategories();\n }\n public static void clearSavedTraces() {\n String cmd = \"rm -f \" + TRACE_DIRECTORY + \"trace-*.*trace\";\n Log.v(TAG, \"Clearing trace directory: \" + cmd);\n try {", "score": 0.7913944125175476 }, { "filename": "src/com/android/traceur/AtraceUtils.java", "retrieved_chunk": " Log.e(TAG, \"atraceDump failed with: \" + atrace.exitValue());\n return false;\n }\n Process ps = TraceUtils.exec(\"ps -AT\", null, false);\n new Streamer(\"atraceDump:ps:stdout\",\n ps.getInputStream(), new FileOutputStream(outFile, true /* append */));\n if (ps.waitFor() != 0) {\n Log.e(TAG, \"atraceDump:ps failed with: \" + ps.exitValue());\n return false;\n }", "score": 0.7855703234672546 }, { "filename": "src/com/android/traceur/AtraceUtils.java", "retrieved_chunk": " return true;\n }\n public void traceStop() {\n String cmd = \"atrace --async_stop > /dev/null\";\n Log.v(TAG, \"Stopping async atrace: \" + cmd);\n try {\n Process atrace = TraceUtils.exec(cmd);\n if (atrace.waitFor() != 0) {\n Log.e(TAG, \"atraceStop failed with: \" + atrace.exitValue());\n }", "score": 0.7720451354980469 } ]
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.app.IntentService; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.UserManager; import android.preference.PreferenceManager; import android.provider.Settings; import android.text.format.DateUtils; import android.util.EventLog; import android.util.Log; import java.io.File; import java.util.ArrayList; import java.util.Collection; public class TraceService extends IntentService { /* Indicates Perfetto has stopped tracing due to either the supplied long trace limitations * or limited storage capacity. */ static String INTENT_ACTION_NOTIFY_SESSION_STOPPED = "com.android.traceur.NOTIFY_SESSION_STOPPED"; /* Indicates a Traceur-associated tracing session has been attached to a bug report */ static String INTENT_ACTION_NOTIFY_SESSION_STOLEN = "com.android.traceur.NOTIFY_SESSION_STOLEN"; private static String INTENT_ACTION_STOP_TRACING = "com.android.traceur.STOP_TRACING"; private static String INTENT_ACTION_START_TRACING = "com.android.traceur.START_TRACING"; private static String INTENT_EXTRA_TAGS= "tags"; private static String INTENT_EXTRA_BUFFER = "buffer"; private static String INTENT_EXTRA_APPS = "apps"; private static String INTENT_EXTRA_LONG_TRACE = "long_trace"; private static String INTENT_EXTRA_LONG_TRACE_SIZE = "long_trace_size"; private static String INTENT_EXTRA_LONG_TRACE_DURATION = "long_trace_duration"; private static String BETTERBUG_PACKAGE_NAME = "com.google.android.apps.internal.betterbug"; private static int TRACE_NOTIFICATION = 1; private static int SAVING_TRACE_NOTIFICATION = 2; private static final int MIN_KEEP_COUNT = 3; private static final long MIN_KEEP_AGE = 4 * DateUtils.WEEK_IN_MILLIS; public static void startTracing(final Context context, Collection<String> tags, int bufferSizeKb, boolean apps, boolean longTrace, int maxLongTraceSizeMb, int maxLongTraceDurationMinutes) { Intent intent = new Intent(context, TraceService.class); intent.setAction(INTENT_ACTION_START_TRACING); intent.putExtra(INTENT_EXTRA_TAGS, new ArrayList(tags)); intent.putExtra(INTENT_EXTRA_BUFFER, bufferSizeKb); intent.putExtra(INTENT_EXTRA_APPS, apps); intent.putExtra(INTENT_EXTRA_LONG_TRACE, longTrace); intent.putExtra(INTENT_EXTRA_LONG_TRACE_SIZE, maxLongTraceSizeMb); intent.putExtra(INTENT_EXTRA_LONG_TRACE_DURATION, maxLongTraceDurationMinutes); context.startForegroundService(intent); } public static void stopTracing(final Context context) { Intent intent = new Intent(context, TraceService.class); intent.setAction(INTENT_ACTION_STOP_TRACING); context.startForegroundService(intent); } // Silently stops a trace without saving it. This is intended to be called when tracing is no // longer allowed, i.e. if developer options are turned off while tracing. The usual method of // stopping a trace via intent, stopTracing(), will not work because intents cannot be received // when developer options are disabled. static void stopTracingWithoutSaving(final Context context) { NotificationManager notificationManager = context.getSystemService(NotificationManager.class); notificationManager.cancel(TRACE_NOTIFICATION); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); prefs.edit().putBoolean(context.getString( R.string.pref_key_tracing_on), false).commit(); TraceUtils.traceStop(); } public TraceService() { this("TraceService"); } protected TraceService(String name) { super(name); setIntentRedelivery(true); } @Override public void onHandleIntent(Intent intent) { Context context = getApplicationContext(); // Checks that developer options are enabled and the user is an admin before continuing. boolean developerOptionsEnabled = Settings.Global.getInt(context.getContentResolver(), Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) != 0; if (!developerOptionsEnabled) { // Refer to b/204992293. EventLog.writeEvent(0x534e4554, "204992293", -1, ""); return; } UserManager userManager = context.getSystemService(UserManager.class); boolean isAdminUser = userManager.isAdminUser(); boolean debuggingDisallowed = userManager.hasUserRestriction( UserManager.DISALLOW_DEBUGGING_FEATURES); if (!isAdminUser || debuggingDisallowed) { return; } if (intent.getAction().equals(INTENT_ACTION_START_TRACING)) { startTracingInternal(intent.getStringArrayListExtra(INTENT_EXTRA_TAGS), intent.getIntExtra(INTENT_EXTRA_BUFFER, Integer.parseInt(context.getString(R.string.default_buffer_size))), intent.getBooleanExtra(INTENT_EXTRA_APPS, false), intent.getBooleanExtra(INTENT_EXTRA_LONG_TRACE, false), intent.getIntExtra(INTENT_EXTRA_LONG_TRACE_SIZE, Integer.parseInt(context.getString(R.string.default_long_trace_size))), intent.getIntExtra(INTENT_EXTRA_LONG_TRACE_DURATION, Integer.parseInt(context.getString(R.string.default_long_trace_duration)))); } else if (intent.getAction().equals(INTENT_ACTION_STOP_TRACING)) { stopTracingInternal
(TraceUtils.getOutputFilename(), false, false);
} else if (intent.getAction().equals(INTENT_ACTION_NOTIFY_SESSION_STOPPED)) { stopTracingInternal(TraceUtils.getOutputFilename(), true, false); } else if (intent.getAction().equals(INTENT_ACTION_NOTIFY_SESSION_STOLEN)) { stopTracingInternal("", false, true); } } private void startTracingInternal(Collection<String> tags, int bufferSizeKb, boolean appTracing, boolean longTrace, int maxLongTraceSizeMb, int maxLongTraceDurationMinutes) { Context context = getApplicationContext(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); Intent stopIntent = new Intent(Receiver.STOP_ACTION, null, context, Receiver.class); stopIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); String title = context.getString(R.string.trace_is_being_recorded); String msg = context.getString(R.string.tap_to_stop_tracing); boolean attachToBugreport = prefs.getBoolean(context.getString(R.string.pref_key_attach_to_bugreport), true); Notification.Builder notification = new Notification.Builder(context, Receiver.NOTIFICATION_CHANNEL_TRACING) .setSmallIcon(R.drawable.bugfood_icon) .setContentTitle(title) .setTicker(title) .setContentText(msg) .setContentIntent( PendingIntent.getBroadcast(context, 0, stopIntent, PendingIntent.FLAG_IMMUTABLE)) .setOngoing(true) .setLocalOnly(true) .setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE) .setColor(getColor( com.android.internal.R.color.system_notification_accent_color)); if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LEANBACK)) { notification.extend(new Notification.TvExtender()); } startForeground(TRACE_NOTIFICATION, notification.build()); if (TraceUtils.traceStart(tags, bufferSizeKb, appTracing, longTrace, attachToBugreport, maxLongTraceSizeMb, maxLongTraceDurationMinutes)) { stopForeground(Service.STOP_FOREGROUND_DETACH); } else { // Starting the trace was unsuccessful, so ensure that tracing // is stopped and the preference is reset. TraceUtils.traceStop(); prefs.edit().putBoolean(context.getString(R.string.pref_key_tracing_on), false).commit(); QsService.updateTile(); stopForeground(Service.STOP_FOREGROUND_REMOVE); } } private void stopTracingInternal(String outputFilename, boolean forceStop, boolean sessionStolen) { Context context = getApplicationContext(); NotificationManager notificationManager = getSystemService(NotificationManager.class); Notification.Builder notification; if (sessionStolen) { notification = getBaseTraceurNotification() .setContentTitle(getString(R.string.attaching_to_report)) .setTicker(getString(R.string.attaching_to_report)) .setProgress(1, 0, true); } else { notification = getBaseTraceurNotification() .setContentTitle(getString(R.string.saving_trace)) .setTicker(getString(R.string.saving_trace)) .setProgress(1, 0, true); } startForeground(SAVING_TRACE_NOTIFICATION, notification.build()); notificationManager.cancel(TRACE_NOTIFICATION); if (sessionStolen) { Notification.Builder notificationAttached = getBaseTraceurNotification() .setContentTitle(getString(R.string.attached_to_report)) .setTicker(getString(R.string.attached_to_report)) .setAutoCancel(true); Intent openIntent = getPackageManager().getLaunchIntentForPackage(BETTERBUG_PACKAGE_NAME); if (openIntent != null) { // Add "Tap to open BetterBug" to notification only if intent is non-null. notificationAttached.setContentText(getString( R.string.attached_to_report_summary)); notificationAttached.setContentIntent(PendingIntent.getActivity( context, 0, openIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE)); } // Adds an action button to the notification for starting a new trace. Intent restartIntent = new Intent(context, InternalReceiver.class); restartIntent.setAction(InternalReceiver.START_ACTION); PendingIntent restartPendingIntent = PendingIntent.getBroadcast(context, 0, restartIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE); Notification.Action action = new Notification.Action.Builder( R.drawable.bugfood_icon, context.getString(R.string.start_new_trace), restartPendingIntent).build(); notificationAttached.addAction(action); NotificationManager.from(context).notify(0, notificationAttached.build()); } else { File file = TraceUtils.getOutputFile(outputFilename); if (TraceUtils.traceDump(file)) { FileSender.postNotification(getApplicationContext(), file); } } stopForeground(Service.STOP_FOREGROUND_REMOVE); TraceUtils.cleanupOlderFiles(MIN_KEEP_COUNT, MIN_KEEP_AGE); } private Notification.Builder getBaseTraceurNotification() { Context context = getApplicationContext(); Notification.Builder notification = new Notification.Builder(this, Receiver.NOTIFICATION_CHANNEL_OTHER) .setSmallIcon(R.drawable.bugfood_icon) .setLocalOnly(true) .setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE) .setColor(context.getColor( com.android.internal.R.color.system_notification_accent_color)); if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LEANBACK)) { notification.extend(new Notification.TvExtender()); } return notification; } }
src/com/android/traceur/TraceService.java
GrapheneOS-Archive-platform_packages_apps_Traceur-2e6c52a
[ { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " prefs.getString(context.getString(R.string.pref_key_max_long_trace_size),\n context.getString(R.string.default_long_trace_size)));\n int maxLongTraceDuration = Integer.parseInt(\n prefs.getString(context.getString(R.string.pref_key_max_long_trace_duration),\n context.getString(R.string.default_long_trace_duration)));\n TraceService.startTracing(context, activeAvailableTags, bufferSize,\n appTracing, longTrace, maxLongTraceSize, maxLongTraceDuration);\n } else {\n TraceService.stopTracing(context);\n }", "score": 0.8325464725494385 }, { "filename": "src/com/android/traceur/FileSender.java", "retrieved_chunk": " new Notification.Builder(context, Receiver.NOTIFICATION_CHANNEL_OTHER)\n .setSmallIcon(R.drawable.bugfood_icon)\n .setContentTitle(context.getString(R.string.trace_saved))\n .setTicker(context.getString(R.string.trace_saved))\n .setContentText(context.getString(R.string.tap_to_share))\n .setContentIntent(PendingIntent.getActivity(\n context, traceUri.hashCode(), intent, PendingIntent.FLAG_ONE_SHOT\n | PendingIntent.FLAG_CANCEL_CURRENT\n | PendingIntent.FLAG_IMMUTABLE))\n .setAutoCancel(true)", "score": 0.8040153980255127 }, { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " Set<String> activeTags = getActiveTags(context, prefs, false);\n if (!activeAvailableTags.equals(activeTags)) {\n postCategoryNotification(context, prefs);\n }\n int bufferSize = Integer.parseInt(\n prefs.getString(context.getString(R.string.pref_key_buffer_size),\n context.getString(R.string.default_buffer_size)));\n boolean appTracing = prefs.getBoolean(context.getString(R.string.pref_key_apps), true);\n boolean longTrace = prefs.getBoolean(context.getString(R.string.pref_key_long_traces), true);\n int maxLongTraceSize = Integer.parseInt(", "score": 0.7979469299316406 }, { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " boolean debuggingDisallowed = userManager.hasUserRestriction(\n UserManager.DISALLOW_DEBUGGING_FEATURES);\n updateStorageProvider(context,\n developerOptionsEnabled && isAdminUser && !debuggingDisallowed);\n } else if (STOP_ACTION.equals(intent.getAction())) {\n prefs.edit().putBoolean(\n context.getString(R.string.pref_key_tracing_on), false).commit();\n updateTracing(context);\n } else if (OPEN_ACTION.equals(intent.getAction())) {\n context.sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));", "score": 0.7801678776741028 }, { "filename": "src/com/android/traceur/MainFragment.java", "retrieved_chunk": " bufferSize.setSummary(bufferSize.getEntry());\n // If we are not using the Perfetto trace backend,\n // hide the unsupported preferences.\n if (TraceUtils.currentTraceEngine().equals(PerfettoUtils.NAME)) {\n ListPreference maxLongTraceSize = (ListPreference)findPreference(\n context.getString(R.string.pref_key_max_long_trace_size));\n maxLongTraceSize.setSummary(maxLongTraceSize.getEntry());\n ListPreference maxLongTraceDuration = (ListPreference)findPreference(\n context.getString(R.string.pref_key_max_long_trace_duration));\n maxLongTraceDuration.setSummary(maxLongTraceDuration.getEntry());", "score": 0.7719478607177734 } ]
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.sysprop.TraceProperties; import android.text.TextUtils; import android.util.Log; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collection; import java.util.List; import com.android.traceur.TraceUtils.Streamer; /** * Utility functions for calling atrace */ public class AtraceUtils implements TraceUtils.TraceEngine { static final String TAG = "Traceur"; private static final String DEBUG_TRACING_FILE = "/sys/kernel/debug/tracing/tracing_on"; private static final String TRACING_FILE = "/sys/kernel/tracing/tracing_on"; public static String NAME = "ATRACE"; private static String OUTPUT_EXTENSION = "ctrace"; public String getName() { return NAME; } public String getOutputExtension() { return OUTPUT_EXTENSION; } /* Note: attachToBugreport, longTrace, maxLongTrace* parameters are ignored in atrace mode. */ public boolean traceStart(Collection<String> tags, int bufferSizeKb, boolean apps, boolean attachToBugreport, boolean longTrace, int maxLongTraceSizeMb, int maxLongTraceDurationMinutes) { String appParameter = apps ? "-a '*' " : ""; String cmd = "atrace --async_start -c -b " + bufferSizeKb + " " + appParameter + TextUtils.join(" ", tags); Log.v(TAG, "Starting async atrace: " + cmd); try { Process atrace = TraceUtils.exec(cmd); if (atrace.waitFor() != 0) { Log.e(TAG, "atraceStart failed with: " + atrace.exitValue()); return false; } } catch (Exception e) { throw new RuntimeException(e); } return true; } public void traceStop() { String cmd = "atrace --async_stop > /dev/null"; Log.v(TAG, "Stopping async atrace: " + cmd); try { Process atrace = TraceUtils.exec(cmd); if (atrace.waitFor() != 0) { Log.e(TAG, "atraceStop failed with: " + atrace.exitValue()); } } catch (Exception e) { throw new RuntimeException(e); } } public boolean traceDump(File outFile) { String cmd = "atrace --async_stop -z -c -o " + outFile; Log.v(TAG, "Dumping async atrace: " + cmd); try { Process atrace = TraceUtils.exec(cmd); if (atrace.waitFor() != 0) { Log.e(TAG, "atraceDump failed with: " + atrace.exitValue()); return false; } Process
ps = TraceUtils.exec("ps -AT", null, false);
new Streamer("atraceDump:ps:stdout", ps.getInputStream(), new FileOutputStream(outFile, true /* append */)); if (ps.waitFor() != 0) { Log.e(TAG, "atraceDump:ps failed with: " + ps.exitValue()); return false; } // Set the new file world readable to allow it to be adb pulled. outFile.setReadable(true, false); // (readable, ownerOnly) outFile.setWritable(true, false); // (readable, ownerOnly) } catch (Exception e) { throw new RuntimeException(e); } return true; } public boolean isTracingOn() { boolean userInitiatedTracingFlag = TraceProperties.user_initiated().orElse(false); if (!userInitiatedTracingFlag) { return false; } boolean tracingOnFlag = false; try { List<String> tracingOnContents; Path debugTracingOnPath = Paths.get(DEBUG_TRACING_FILE); Path tracingOnPath = Paths.get(TRACING_FILE); if (Files.isReadable(debugTracingOnPath)) { tracingOnContents = Files.readAllLines(debugTracingOnPath); } else if (Files.isReadable(tracingOnPath)) { tracingOnContents = Files.readAllLines(tracingOnPath); } else { return false; } tracingOnFlag = !tracingOnContents.get(0).equals("0"); } catch (IOException e) { throw new RuntimeException(e); } return userInitiatedTracingFlag && tracingOnFlag; } }
src/com/android/traceur/AtraceUtils.java
GrapheneOS-Archive-platform_packages_apps_Traceur-2e6c52a
[ { "filename": "src/com/android/traceur/PerfettoUtils.java", "retrieved_chunk": " try {\n Process process = TraceUtils.execWithTimeout(cmd, TEMP_DIR, STARTUP_TIMEOUT_MS);\n if (process == null) {\n return false;\n } else if (process.exitValue() != 0) {\n Log.e(TAG, \"perfetto traceStart failed with: \" + process.exitValue());\n return false;\n }\n } catch (Exception e) {\n throw new RuntimeException(e);", "score": 0.8512715697288513 }, { "filename": "src/com/android/traceur/PerfettoUtils.java", "retrieved_chunk": " try {\n Process process = TraceUtils.execWithTimeout(cmd, null, STOP_TIMEOUT_MS);\n if (process != null && process.exitValue() != 0) {\n Log.e(TAG, \"perfetto traceStop failed with: \" + process.exitValue());\n }\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n public boolean traceDump(File outFile) {", "score": 0.8441208600997925 }, { "filename": "src/com/android/traceur/PerfettoUtils.java", "retrieved_chunk": " }\n Log.v(TAG, \"perfetto traceStart succeeded!\");\n return true;\n }\n public void traceStop() {\n Log.v(TAG, \"Stopping perfetto trace.\");\n if (!isTracingOn()) {\n Log.w(TAG, \"No trace appears to be in progress. Stopping perfetto trace may not work.\");\n }\n String cmd = \"perfetto --stop --attach=\" + PERFETTO_TAG;", "score": 0.8096097707748413 }, { "filename": "src/com/android/traceur/TraceUtils.java", "retrieved_chunk": " Process rm = exec(cmd);\n if (rm.waitFor() != 0) {\n Log.e(TAG, \"clearSavedTraces failed with: \" + rm.exitValue());\n }\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n public static Process exec(String cmd) throws IOException {\n return exec(cmd, null);", "score": 0.8068389892578125 }, { "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": 0.7979133129119873 } ]
java
ps = TraceUtils.exec("ps -AT", null, false);
/* * Copyright 2022 QuiltMC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ho.artisan.lib.recipe.mixin; import com.google.gson.JsonObject; import ho.artisan.lib.recipe.api.serializer.FabricRecipeSerializer; import org.spongepowered.asm.mixin.Mixin; import net.minecraft.data.server.recipe.SmithingRecipeJsonBuilder; import net.minecraft.recipe.SmithingRecipe; import ho.artisan.lib.recipe.api.serializer.FabricRecipeSerializer; @Mixin(SmithingRecipe.Serializer.class) public abstract class SmithingRecipeSerializerMixin implements FabricRecipeSerializer<SmithingRecipe> { @Override public JsonObject toJson(SmithingRecipe recipe) { var accessor = (SmithingRecipeAccessor) recipe; return new SmithingRecipeJsonBuilder.SmithingRecipeJsonProvider( recipe.getId(), this, accessor.getBase(
), accessor.getAddition(), recipe.getOutput().getItem(), null, null ).toJson();
} }
src/main/java/ho/artisan/lib/recipe/mixin/SmithingRecipeSerializerMixin.java
HO-Artisan-RecipeInProgramming-09cc072
[ { "filename": "src/main/java/ho/artisan/lib/recipe/mixin/CookingRecipeSerializerMixin.java", "retrieved_chunk": "import net.minecraft.recipe.CookingRecipeSerializer;\nimport ho.artisan.lib.recipe.api.serializer.FabricRecipeSerializer;\n@Mixin(CookingRecipeSerializer.class)\npublic abstract class CookingRecipeSerializerMixin<T extends AbstractCookingRecipe> implements FabricRecipeSerializer<T> {\n\t@Override\n\tpublic JsonObject toJson(T recipe) {\n\t\treturn new CookingRecipeJsonBuilder.CookingRecipeJsonProvider(recipe.getId(), recipe.getGroup(),\n\t\t\t\trecipe.getIngredients().get(0), recipe.getOutput().getItem(),\n\t\t\t\trecipe.getExperience(), recipe.getCookTime(), null, null, this)\n\t\t\t\t.toJson();", "score": 0.8154294490814209 }, { "filename": "src/main/java/ho/artisan/lib/recipe/mixin/CuttingRecipeSerializerMixin.java", "retrieved_chunk": "import ho.artisan.lib.recipe.api.serializer.FabricRecipeSerializer;\n@Mixin(CuttingRecipe.Serializer.class)\npublic abstract class CuttingRecipeSerializerMixin<T extends CuttingRecipe> implements FabricRecipeSerializer<T> {\n\t@Override\n\tpublic JsonObject toJson(T recipe) {\n\t\treturn new SingleItemRecipeJsonBuilder.SingleItemRecipeJsonProvider(recipe.getId(), this, recipe.getGroup(),\n\t\t\t\trecipe.getIngredients().get(0), recipe.getOutput().getItem(), recipe.getOutput().getCount(),\n\t\t\t\tnull, null)\n\t\t\t\t.toJson();\n\t}", "score": 0.8152464628219604 }, { "filename": "src/main/java/ho/artisan/lib/recipe/mixin/ShapelessRecipeSerializerMixin.java", "retrieved_chunk": "import ho.artisan.lib.recipe.api.serializer.FabricRecipeSerializer;\n@Mixin(ShapelessRecipe.Serializer.class)\npublic abstract class ShapelessRecipeSerializerMixin implements FabricRecipeSerializer<ShapelessRecipe> {\n\t@Override\n\tpublic JsonObject toJson(ShapelessRecipe recipe) {\n\t\treturn new ShapelessRecipeJsonBuilder.ShapelessRecipeJsonProvider(recipe.getId(),\n\t\t\t\trecipe.getOutput().getItem(), recipe.getOutput().getCount(),\n\t\t\t\trecipe.getGroup(), recipe.getIngredients(), null, null)\n\t\t\t\t.toJson();\n\t}", "score": 0.8052384257316589 }, { "filename": "src/main/java/ho/artisan/lib/recipe/mixin/ShapedRecipeSerializerMixin.java", "retrieved_chunk": "\t\t\tpatternLine.append(ingredients.getChar(ingredient));\n\t\t}\n\t\tpattern.add(patternLine.toString());\n\t\treturn new ShapedRecipeJsonBuilder.ShapedRecipeJsonProvider(\n\t\t\t\trecipe.getId(),\n\t\t\t\trecipe.getOutput().getItem(),\n\t\t\t\trecipe.getOutput().getCount(),\n\t\t\t\trecipe.getGroup(),\n\t\t\t\tpattern,\n\t\t\t\tinputs,", "score": 0.7767436504364014 }, { "filename": "src/main/java/ho/artisan/lib/recipe/mixin/RecipeManagerMixin.java", "retrieved_chunk": "\tprivate void onReloadEnd(Map<Identifier, JsonElement> map, ResourceManager resourceManager, Profiler profiler,\n\t\t\tCallbackInfo ci,\n\t\t\tMap<RecipeType<?>, ImmutableMap.Builder<Identifier, Recipe<?>>> builderMap,\n\t\t\tImmutableMap.Builder<Identifier, Recipe<?>> globalRecipeMapBuilder) {\n\t\tMap<Identifier, Recipe<?>> globalRecipes = ImmutableMapBuilderUtil.specialBuild(globalRecipeMapBuilder);\n\t\tRecipeManagerImpl.applyModifications((RecipeManager) (Object) this, this.recipes, globalRecipes);\n\t\tthis.recipesById = Collections.unmodifiableMap(globalRecipes);\n\t}\n}", "score": 0.7227864265441895 } ]
java
), accessor.getAddition(), recipe.getOutput().getItem(), null, null ).toJson();
/* * 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": 0.8173264861106873 }, { "filename": "src/com/android/traceur/InternalReceiver.java", "retrieved_chunk": "import android.preference.PreferenceManager;\npublic class InternalReceiver extends BroadcastReceiver {\n public static final String START_ACTION = \"com.android.traceur.START\";\n @Override\n public void onReceive(Context context, Intent intent) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n if (START_ACTION.equals(intent.getAction())) {\n prefs.edit().putBoolean(\n context.getString(R.string.pref_key_tracing_on), true).commit();\n Receiver.updateTracing(context);", "score": 0.7770820260047913 }, { "filename": "src/com/android/traceur/QsService.java", "retrieved_chunk": " * If tracing is being turned off, dump and offer to share. */\n @Override\n public void onClick() {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);\n boolean newTracingState = !prefs.getBoolean(getString(R.string.pref_key_tracing_on), false);\n prefs.edit().putBoolean(getString(R.string.pref_key_tracing_on), newTracingState).commit();\n Receiver.updateTracing(this);\n }\n}", "score": 0.7696605920791626 }, { "filename": "src/com/android/traceur/TraceService.java", "retrieved_chunk": " restartIntent, PendingIntent.FLAG_ONE_SHOT\n | PendingIntent.FLAG_CANCEL_CURRENT\n | PendingIntent.FLAG_IMMUTABLE);\n Notification.Action action = new Notification.Action.Builder(\n R.drawable.bugfood_icon, context.getString(R.string.start_new_trace),\n restartPendingIntent).build();\n notificationAttached.addAction(action);\n NotificationManager.from(context).notify(0, notificationAttached.build());\n } else {\n File file = TraceUtils.getOutputFile(outputFilename);", "score": 0.7684859037399292 }, { "filename": "src/com/android/traceur/UserConsentActivityDialog.java", "retrieved_chunk": " // go ahead and start the target intent and finish this activity.\n if (getShowDialogState(this) == PREF_STATE_HIDE) {\n startActivity(mNextIntent);\n finish();\n }\n final AlertController.AlertParams params = mAlertParams;\n params.mView = LayoutInflater.from(this).inflate(\n R.layout.consent_dialog_checkbox, null);\n params.mTitle = getString(R.string.share_trace);\n params.mMessage = getString(R.string.system_trace_sensitive_data);", "score": 0.7670629620552063 } ]
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": " } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n public boolean traceDump(File outFile) {\n String cmd = \"atrace --async_stop -z -c -o \" + outFile;\n Log.v(TAG, \"Dumping async atrace: \" + cmd);\n try {\n Process atrace = TraceUtils.exec(cmd);\n if (atrace.waitFor() != 0) {", "score": 0.8914215564727783 }, { "filename": "src/com/android/traceur/AtraceUtils.java", "retrieved_chunk": " return true;\n }\n public void traceStop() {\n String cmd = \"atrace --async_stop > /dev/null\";\n Log.v(TAG, \"Stopping async atrace: \" + cmd);\n try {\n Process atrace = TraceUtils.exec(cmd);\n if (atrace.waitFor() != 0) {\n Log.e(TAG, \"atraceStop failed with: \" + atrace.exitValue());\n }", "score": 0.8847931623458862 }, { "filename": "src/com/android/traceur/TraceUtils.java", "retrieved_chunk": " public static boolean isTracingOn() {\n return mTraceEngine.isTracingOn();\n }\n public static TreeMap<String, String> listCategories() {\n return PerfettoUtils.perfettoListCategories();\n }\n public static void clearSavedTraces() {\n String cmd = \"rm -f \" + TRACE_DIRECTORY + \"trace-*.*trace\";\n Log.v(TAG, \"Clearing trace directory: \" + cmd);\n try {", "score": 0.8555930256843567 }, { "filename": "src/com/android/traceur/AtraceUtils.java", "retrieved_chunk": " Log.v(TAG, \"Starting async atrace: \" + cmd);\n try {\n Process atrace = TraceUtils.exec(cmd);\n if (atrace.waitFor() != 0) {\n Log.e(TAG, \"atraceStart failed with: \" + atrace.exitValue());\n return false;\n }\n } catch (Exception e) {\n throw new RuntimeException(e);\n }", "score": 0.8545948266983032 }, { "filename": "src/com/android/traceur/StopTraceService.java", "retrieved_chunk": " SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n boolean prefsTracingOn =\n prefs.getBoolean(context.getString(R.string.pref_key_tracing_on), false);\n // If the user thinks tracing is off and the trace processor agrees, we have no work to do.\n // We must still start a foreground service, but let's log as an FYI.\n if (!prefsTracingOn && !TraceUtils.isTracingOn()) {\n Log.i(TAG, \"StopTraceService does not see a trace to stop.\");\n }\n PreferenceManager.getDefaultSharedPreferences(context)\n .edit().putBoolean(context.getString(R.string.pref_key_tracing_on),", "score": 0.8170676827430725 } ]
java
process = TraceUtils.execWithTimeout(cmd, null, STOP_TIMEOUT_MS);
package com.HiWord9.RPRenames.configGeneration; import com.HiWord9.RPRenames.RPRenames; import com.HiWord9.RPRenames.Rename; import com.google.gson.Gson; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Objects; import java.util.Properties; public class CITConfig { public static void propertiesToJson(Properties p, String outputPath) { String items = p.getProperty("matchItems"); if (items == null) { items = p.getProperty("items"); } if (items != null) { while (items.endsWith(" ")) { items = items.substring(0, items.length() - 1); } String item = null; boolean finish = false; while (!finish) { int i = 0; while (i < items.length()) { if (String.valueOf(items.charAt(i)).equals(" ")) { item = items.substring(0, i); items = items.substring(i + 1); finish = false; break; } i++; finish = true; } if (finish) { item = items; } item = Objects.requireNonNull(item).replace("minecraft:", ""); File currentFile = new File(outputPath + item + ".json"); if (currentFile.exists() && p.getProperty("nbt.display.Name") != null) { Rename alreadyExist = ConfigManager.configRead(currentFile); String[] ae = alreadyExist.getName(); if (!Arrays.stream(ae).toList(
).contains(ConfigManager.getFirstName(p.getProperty("nbt.display.Name")))) {
int AEsize = ae.length; String[] newConfig = new String[AEsize + 1]; int h = 0; while (h < AEsize) { newConfig[h] = ae[h]; h++; } newConfig[h] = ConfigManager.getFirstName(p.getProperty("nbt.display.Name")); Rename newRename = new Rename(newConfig); ArrayList<Rename> listFiles = new ArrayList<>(); listFiles.add(newRename); try { FileWriter fileWriter = new FileWriter(currentFile); Gson gson = new Gson(); gson.toJson(listFiles, fileWriter); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } else { if (p.getProperty("nbt.display.Name") != null) { new File(outputPath).mkdirs(); try { RPRenames.LOGGER.info("Created new file for config: " + outputPath + item + ".json"); ArrayList<Rename> listNames = new ArrayList<>(); Rename name1 = new Rename(new String[]{ConfigManager.getFirstName(p.getProperty("nbt.display.Name"))}); listNames.add(name1); FileWriter fileWriter = new FileWriter(currentFile); Gson gson = new Gson(); gson.toJson(listNames, fileWriter); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } } } } }
src/main/java/com/HiWord9/RPRenames/configGeneration/CITConfig.java
HiWord9-RPRenames-fabric-046f2f8
[ { "filename": "src/main/java/com/HiWord9/RPRenames/configGeneration/CEMConfig.java", "retrieved_chunk": " File currentFile = new File(outputPath + fileName + \".json\");\n if (currentFile.exists()) {\n List<String> namesValues = p.stringPropertyNames().stream().toList();\n ArrayList<String> skins = new ArrayList<>();\n for (String s : namesValues) {\n if (s.startsWith(\"name.\")) {\n if (!skins.contains(p.getProperty(\"skins.\" + s.substring(5)))) {\n skins.add(p.getProperty(\"skins.\" + s.substring(5)));\n String name = ConfigManager.getFirstName(p.getProperty(s));\n if (currentFile.exists() && name != null) {", "score": 0.8184772729873657 }, { "filename": "src/main/java/com/HiWord9/RPRenames/configGeneration/ConfigManager.java", "retrieved_chunk": " Properties p = new Properties();\n p.load(bufferedReader);\n CITConfig.propertiesToJson(p, outputPath + RPRenames.configPathNameCIT + \"/\");\n } else if (currentFolder.endsWith(\"/cem/\")) {\n String fileName = propertiesFile.getFileName().toString();\n if (Arrays.stream(CEMList.models).toList().contains(fileName.substring(0, propertiesFile.getFileName().toString().length() - 4))) {\n CEMConfig.startPropToJsonModels(filePath, outputPath + RPRenames.configPathNameCEM + \"/\");\n }\n }\n } catch (IOException ignored) {}", "score": 0.8126314878463745 }, { "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": 0.8018127679824829 }, { "filename": "src/main/java/com/HiWord9/RPRenames/configGeneration/CEMConfig.java", "retrieved_chunk": " ArrayList<String> jpmList = getParamListFromObj(obj, \"model=\");\n for (String jpmFileName : jpmList) {\n if (jpmFileName != null && jpmFileName.endsWith(\".jpm\")) {\n String jpmObj = getObjFromBF(new File(rpPath + cemPath + jpmFileName).toPath()).toString();\n String textureName = getPropPathInRandom(Objects.requireNonNull(getParamListFromObj(jpmObj, \"texture=\").get(0)));\n File propertiesFile = new File(rpPath + randomEntityPath + textureName + \".properties\");\n if (propertiesFile.exists()) {\n try {\n checked.add(propertiesFile.getPath());\n InputStream inputStream = Files.newInputStream(propertiesFile.toPath());", "score": 0.788632869720459 }, { "filename": "src/main/java/com/HiWord9/RPRenames/configGeneration/CEMConfig.java", "retrieved_chunk": " propertiesToJsonModels(p, CEMList.mobs[fc].getUntranslatedName(), outputPath);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n });\n Files.walk(currentPath, new java.nio.file.FileVisitOption[0]).filter(path -> path.toString().equals(randomEntityPath + getLastPathPart(CEMList.textures[fc]) + \".properties\")).forEach(propFile -> {\n if (!checked.contains(String.valueOf(propFile))) {\n try {\n InputStream inputStream = Files.newInputStream(propFile);", "score": 0.7874987125396729 } ]
java
).contains(ConfigManager.getFirstName(p.getProperty("nbt.display.Name")))) {
/* * 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": 0.9140304923057556 }, { "filename": "src/com/android/traceur/TraceService.java", "retrieved_chunk": " intent.setAction(INTENT_ACTION_STOP_TRACING);\n context.startForegroundService(intent);\n }\n // Silently stops a trace without saving it. This is intended to be called when tracing is no\n // longer allowed, i.e. if developer options are turned off while tracing. The usual method of\n // stopping a trace via intent, stopTracing(), will not work because intents cannot be received\n // when developer options are disabled.\n static void stopTracingWithoutSaving(final Context context) {\n NotificationManager notificationManager =\n context.getSystemService(NotificationManager.class);", "score": 0.9069608449935913 }, { "filename": "src/com/android/traceur/TraceService.java", "retrieved_chunk": " stopForeground(Service.STOP_FOREGROUND_DETACH);\n } else {\n // Starting the trace was unsuccessful, so ensure that tracing\n // is stopped and the preference is reset.\n TraceUtils.traceStop();\n prefs.edit().putBoolean(context.getString(R.string.pref_key_tracing_on),\n false).commit();\n QsService.updateTile();\n stopForeground(Service.STOP_FOREGROUND_REMOVE);\n }", "score": 0.8849694132804871 }, { "filename": "src/com/android/traceur/Receiver.java", "retrieved_chunk": " updateDeveloperOptionsWatcher(context);\n // We know that Perfetto won't be tracing already at boot, so pass the\n // tracingIsOff argument to avoid the Perfetto check.\n updateTracing(context, /* assumeTracingIsOff= */ true);\n } else if (Intent.ACTION_USER_FOREGROUND.equals(intent.getAction())) {\n boolean developerOptionsEnabled = (1 ==\n Settings.Global.getInt(context.getContentResolver(),\n Settings.Global.DEVELOPMENT_SETTINGS_ENABLED , 0));\n UserManager userManager = context.getSystemService(UserManager.class);\n boolean isAdminUser = userManager.isAdminUser();", "score": 0.883854329586029 }, { "filename": "src/com/android/traceur/PerfettoUtils.java", "retrieved_chunk": " if (isTracingOn()) {\n Log.e(TAG, \"Attempting to start perfetto trace but trace is already in progress\");\n return false;\n } else {\n // Ensure the temporary trace file is cleared.\n try {\n Files.deleteIfExists(Paths.get(TEMP_TRACE_LOCATION));\n } catch (Exception e) {\n throw new RuntimeException(e);\n }", "score": 0.8694454431533813 } ]
java
prefsTracingOn && !TraceUtils.isTracingOn()) {
package com.lint.rpc.common.transport; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import java.net.InetSocketAddress; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.concurrent.Future; import java.util.function.Consumer; /** * Netty 客户端 * * @author 周鹏程 * @date 2023-05-26 12:45 PM **/ public class NettyClient { private final NettyConf conf; private volatile NioSocketChannel ch; public NettyClient(NettyConf conf){ this.conf = conf; } public boolean sendMsg(Object msg){ if(ch == null){ synchronized (this){ if(ch == null){ this.connect(); } } } if(ch == null){ return false; } try { ch.writeAndFlush(msg).sync(); return true; } catch (InterruptedException e) { e.printStackTrace(); } return false; } public NettyConf getConf() { return conf; } private void connect(){ if(null == conf.getAddress()){ return; } NioEventLoopGroup workGroup = new NioEventLoopGroup(); Bootstrap bs = new Bootstrap(); bs.group(workGroup) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<NioSocketChannel>() { @Override protected void initChannel(NioSocketChannel ch) { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new InternalServerMsgCodec()); pipeline.addLast(new ClientChannelHandler()); } }); try { ChannelFuture f = bs.connect(conf.getAddress()).sync(); if (!f.isSuccess()) { return; } ch = (NioSocketChannel) f.channel(); ch.closeFuture().addListener(this::onLoseConnect);
System.out.println(">>> 连接到业务服务器成功! "+conf.getAddress()+" <<<");
} catch (InterruptedException e) { e.printStackTrace(); } } /** * 当失去连接时 * * @param f 预期 */ private void onLoseConnect(Future<?> f) { System.out.println("系统通知 - 注意: 服务器连接关闭! >>> " + conf.getAddress()); this.ch = null; final Consumer<NettyClient> closeCallback = conf.getCloseCallback(); if(null != closeCallback){ closeCallback.accept(this); } } @Override public int hashCode() { return Objects.hash(conf.getAddress().getHostName(), conf.getAddress().getPort()); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()){ return false; } NettyConf selfConf = this.getConf(); NettyClient client = (NettyClient) obj; NettyConf clientConf = client.getConf(); return selfConf.getAddress().getHostName().equals(clientConf.getAddress().getHostName()) && selfConf.getAddress().getPort() == clientConf.getAddress().getPort(); } }
lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyClient.java
hiparker-lint-rpc-framework-e64aac0
[ { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyServer.java", "retrieved_chunk": " try {\n System.out.println(\"Lint Server port: \" + conf.getPort());\n ChannelFuture f = bind.sync();\n if (!f.isSuccess()) {\n throw new RpcException(RpcMsg.EXCEPTION_SERVICE_NOT_STARTED);\n }\n bind.channel().closeFuture().sync();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }", "score": 0.7871092557907104 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyServer.java", "retrieved_chunk": " .group(bossGroup, workerGroup)\n .childHandler(new ChannelInitializer<NioSocketChannel>() {\n @Override\n protected void initChannel(NioSocketChannel ch) {\n ChannelPipeline p = ch.pipeline();\n p.addLast(new InternalServerMsgCodec());\n p.addLast(new ServerChannelHandler());\n }\n })\n .bind(conf.getPort());", "score": 0.7328121066093445 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/ServerChannelHandler.java", "retrieved_chunk": " }catch (Exception e){\n e.printStackTrace();\n }\n requestHeader.setLength(requestBody.toBytesArray().length);\n ctx.channel().writeAndFlush(content);\n // 转多线程处理\n// ExecuteThread et = ExecuteThread.getInstance();\n// et.execute(()->{\n// ProvideServiceSpi spi = ProvideServiceSpi.getInstance();\n// LintService service = spi.getService(requestBody.getName(), requestHeader.getVersion());", "score": 0.710516095161438 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ClientPool.java", "retrieved_chunk": " }\n }\n }\n return nc;\n }\n private NettyClient createClient(String serviceName, InetSocketAddress address){\n NettyConf conf = new NettyConf();\n conf.setAddress(address);\n conf.setCloseCallback((c)->{\n try {", "score": 0.7060022354125977 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/proxy/RpcInvocationHandler.java", "retrieved_chunk": " requestContent.setRequestHeader(requestHeader);\n requestContent.setRequestBody(requestBody);\n LoadBalancePolicyFactory loadBalancePolicyFactory = LoadBalancePolicyFactory.getInstance();\n NettyClient nc = loadBalancePolicyFactory\n .getClient(interfaceInfo);\n Object responseMsg = null;\n try {\n boolean sendFlag = nc.sendMsg(requestContent);\n if(!sendFlag){\n // 无法建立连接", "score": 0.704814612865448 } ]
java
System.out.println(">>> 连接到业务服务器成功! "+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": 0.8369930982589722 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/ClientChannelHandler.java", "retrieved_chunk": " public void channelRead(ChannelHandlerContext ctx, Object msg) {\n if(!(msg instanceof RequestContent)){\n return;\n }\n //System.out.println(\"客户端处理数据......\");\n RequestContent content = (RequestContent) msg;\n RequestHeader requestHeader = content.getRequestHeader();\n RequestBody requestBody = content.getRequestBody();\n MsgPool.put(requestHeader.getRequestId(), requestBody.getRes());\n CountDownLatchPool.countDown(requestHeader.getRequestId());", "score": 0.8263747096061707 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/proxy/RpcInvocationHandler.java", "retrieved_chunk": " requestContent.setRequestHeader(requestHeader);\n requestContent.setRequestBody(requestBody);\n LoadBalancePolicyFactory loadBalancePolicyFactory = LoadBalancePolicyFactory.getInstance();\n NettyClient nc = loadBalancePolicyFactory\n .getClient(interfaceInfo);\n Object responseMsg = null;\n try {\n boolean sendFlag = nc.sendMsg(requestContent);\n if(!sendFlag){\n // 无法建立连接", "score": 0.7038388252258301 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/ServerChannelHandler.java", "retrieved_chunk": " }catch (Exception e){\n e.printStackTrace();\n }\n requestHeader.setLength(requestBody.toBytesArray().length);\n ctx.channel().writeAndFlush(content);\n // 转多线程处理\n// ExecuteThread et = ExecuteThread.getInstance();\n// et.execute(()->{\n// ProvideServiceSpi spi = ProvideServiceSpi.getInstance();\n// LintService service = spi.getService(requestBody.getName(), requestHeader.getVersion());", "score": 0.7018601894378662 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyServer.java", "retrieved_chunk": " .group(bossGroup, workerGroup)\n .childHandler(new ChannelInitializer<NioSocketChannel>() {\n @Override\n protected void initChannel(NioSocketChannel ch) {\n ChannelPipeline p = ch.pipeline();\n p.addLast(new InternalServerMsgCodec());\n p.addLast(new ServerChannelHandler());\n }\n })\n .bind(conf.getPort());", "score": 0.697401762008667 } ]
java
innerMsg.free();
package com.lint.rpc.common.pool; import com.lint.rpc.common.LintConf; import com.lint.rpc.common.balance.ILoadBalancePolicy; import com.lint.rpc.common.service.ProvideSpi; import com.lint.rpc.common.transport.ClientFactory; import com.lint.rpc.common.transport.NettyClient; import com.lint.rpc.common.transport.NettyConf; import java.net.InetSocketAddress; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; /** * 客户端连接池 * * @author 周鹏程 * @date 2023-05-26 7:38 PM **/ public final class ClientPool { // serviceName 为服务名 // hostname+port 为组名 // 连接池 private final Map<String, LinkedHashSet<NettyClient>> groupPool = new ConcurrentHashMap<>(); private final Map<String, LinkedHashSet<String>> servicePool = new ConcurrentHashMap<>(); private final ReentrantLock rLock = new ReentrantLock(); public NettyClient get(String serviceName, ILoadBalancePolicy loadBalancePolicy){ ConfPool confPool = ConfPool.getInstance(); LintConf lintConf = confPool.get(); ProvideSpi provideSpi = ProvideSpi.getInstance(); LinkedHashSet<InetSocketAddress> addressSet = provideSpi.getAddressByServiceName(serviceName); if(null == addressSet){ return null; } LinkedHashSet<String> groupNameSet = servicePool.get(serviceName); if(null == groupNameSet || groupNameSet.isEmpty()){ try { rLock.lock(); groupNameSet = servicePool.get(serviceName); if(null == groupNameSet || groupNameSet.isEmpty()){ int clientIndex = loadBalancePolicy.getClientIndex(addressSet.size()); InetSocketAddress inetSocketAddress = linkedHashSetGetByIndex(addressSet, clientIndex); NettyClient ch = createClient(serviceName, inetSocketAddress); return put(serviceName, ch); } }finally { rLock.unlock(); } } NettyClient ch = null; // 如果不相等 优先使用为开辟的新链接 if(groupNameSet.size() != addressSet.size()){ try { rLock.lock(); if(groupNameSet.size() != addressSet.size()) { InetSocketAddress address = null; Iterator<InetSocketAddress> iterator = addressSet.stream().iterator(); while (iterator.hasNext()){ address = iterator.next(); String groupName = getGroupName(address); boolean contains = groupNameSet.contains(groupName); if(!contains){ break; } } ch = createClient(serviceName, address); if(ch != null){ return put(serviceName, ch); } } }finally { rLock.unlock(); } } // 如果上述操作 ch == null 或者 group相等 那就准备 从现有队列中选择一位连接 int groupIndex = loadBalancePolicy.getClientIndex(groupNameSet.size()); String groupName = linkedHashSetGetByIndex(groupNameSet, groupIndex); LinkedHashSet<NettyClient> ncSet = groupPool.get(groupName); if(null != ncSet){ // 如果当前开辟的连接数 还未达到自定义配置的最大值 则继续开辟连接 if(ncSet.size() < lintConf.getClientMaxConnCount()){ try { rLock.lock(); if(ncSet.size() < lintConf.getClientMaxConnCount()){ String[] address = groupName.split(":"); InetSocketAddress inetSocketAddress = new InetSocketAddress( address[0], Integer.parseInt(address[1])); ch = createClient(serviceName, inetSocketAddress); return put(serviceName, ch); } }finally { rLock.unlock(); } } int
chIndex = loadBalancePolicy.getClientIndex(groupNameSet.size());
ch = linkedHashSetGetByIndex(ncSet, chIndex); } return ch; } private NettyClient put( String serviceName, NettyClient nc){ if(null == nc){ return null; } int lockCount = 0; try { Set<String> groupSet = servicePool.get(serviceName); if(null == groupSet){ rLock.lock(); lockCount++; groupSet = servicePool.computeIfAbsent(serviceName, k -> new LinkedHashSet<>()); } NettyConf conf = nc.getConf(); String groupName = getGroupName(conf.getAddress()); Set<NettyClient> nettyClientSet = groupPool.get(groupName); if(null == nettyClientSet){ rLock.lock(); lockCount++; nettyClientSet = groupPool.computeIfAbsent(groupName, k -> new LinkedHashSet<>()); } rLock.lock(); lockCount++; if(nettyClientSet.isEmpty()){ groupSet.add(groupName); } nettyClientSet.add(nc); }finally { if(lockCount > 0){ for (int i = 0; i < lockCount; i++) { rLock.unlock(); } } } return nc; } private NettyClient createClient(String serviceName, InetSocketAddress address){ NettyConf conf = new NettyConf(); conf.setAddress(address); conf.setCloseCallback((c)->{ try { rLock.lock(); String groupName = getGroupName(address); Set<NettyClient> nettyClients = groupPool.get(groupName); nettyClients.remove(c); if(nettyClients.isEmpty()){ groupPool.remove(groupName); Set<String> groupSet = servicePool.get(serviceName); groupSet.remove(groupName); if(groupSet.isEmpty()){ servicePool.remove(serviceName); } } }finally { rLock.unlock(); } }); ClientFactory factory = ClientFactory.getInstance(); return factory.create(conf); } private String getGroupName(InetSocketAddress address){ String hostName = address.getHostName(); int port = address.getPort(); return hostName+":"+port; } private <T> T linkedHashSetGetByIndex(LinkedHashSet<T> linkedHashSet, int index){ if(null == linkedHashSet){ return null; } T t = null; int chCurrIndex = 0; Iterator<T> chIterator = linkedHashSet.stream().iterator(); while (chIterator.hasNext() && chCurrIndex++ <= index){ t = chIterator.next(); } return t; } private static class LazyHolder { private static final ClientPool INSTANCE = new ClientPool(); } public static ClientPool getInstance() { return ClientPool.LazyHolder.INSTANCE; } private ClientPool(){} }
lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ClientPool.java
hiparker-lint-rpc-framework-e64aac0
[ { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/service/ProvideSpi.java", "retrieved_chunk": " }\n provideService = ps;\n break;\n }\n isInit = true;\n }\n }\n }\n }\n public LinkedHashSet<InetSocketAddress> getAddressByServiceName(String serviceName){", "score": 0.7859777808189392 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/service/ProvideServiceSpi.java", "retrieved_chunk": " continue;\n }\n serviceMap.putIfAbsent(annotation.name()+\":\"+annotation.version(), ls);\n }\n isInit = true;\n }\n }\n }\n }\n public LintService getService(String serviceName, short version){", "score": 0.7547585964202881 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/balance/LoadBalancePolicyFactory.java", "retrieved_chunk": " loadBalancePolicyMap.putIfAbsent(loadBalancePolicyClazz, loadBalancePolicy);\n }catch (Exception e){\n e.printStackTrace();\n }\n return loadBalancePolicy;\n }\n }\n private LoadBalancePolicyFactory(){}\n private static class LazyHolder {\n private static final LoadBalancePolicyFactory INSTANCE = new LoadBalancePolicyFactory();", "score": 0.7368015050888062 }, { "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": 0.7302433252334595 }, { "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": 0.7230696678161621 } ]
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/pool/ClientPool.java", "retrieved_chunk": "import java.util.concurrent.locks.ReentrantLock;\n/**\n * 客户端连接池\n *\n * @author 周鹏程\n * @date 2023-05-26 7:38 PM\n **/\npublic final class ClientPool {\n // serviceName 为服务名\n // hostname+port 为组名", "score": 0.8110661506652832 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/proxy/RpcInvocationHandler.java", "retrieved_chunk": " throw new RpcException(RpcMsg.EXCEPTION_NOT_CONNECTION);\n }\n // 如果无返回值 则直接退出\n if(method.getReturnType().equals(Void.TYPE)){\n return responseMsg;\n }\n ConfPool confPool = ConfPool.getInstance();\n LintConf lintConf = confPool.get();\n // 锁定线程 并等待 60秒,如果有结果会直接返回\n CountDownLatchPool.await(", "score": 0.8025693893432617 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/proxy/RpcInvocationHandler.java", "retrieved_chunk": " requestHeader.getRequestId(), lintConf.getRequestWaitTimeBySeconds());\n // 消息池查询数据 如果查到则序列化返回 ,超时则返回超时 或者 调用兜底补偿\n responseMsg = MsgPool.getAndRemove(requestHeader.getRequestId());\n if(null == responseMsg){\n // 请求超时\n throw new RpcException(RpcMsg.EXCEPTION_TIMEOUT);\n }\n }catch (RpcException re){\n re.printStackTrace();\n }finally {", "score": 0.7795455455780029 }, { "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": 0.7782600522041321 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/balance/ILoadBalancePolicy.java", "retrieved_chunk": "package com.lint.rpc.common.balance;\n/**\n * 负载策略\n *\n * @author 周鹏程\n * @date 2023-05-26 10:10 AM\n **/\npublic interface ILoadBalancePolicy {\n /**\n * 获取客户端", "score": 0.7775256633758545 } ]
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/proxy/RpcInvocationHandler.java", "retrieved_chunk": " requestHeader.getRequestId(), lintConf.getRequestWaitTimeBySeconds());\n // 消息池查询数据 如果查到则序列化返回 ,超时则返回超时 或者 调用兜底补偿\n responseMsg = MsgPool.getAndRemove(requestHeader.getRequestId());\n if(null == responseMsg){\n // 请求超时\n throw new RpcException(RpcMsg.EXCEPTION_TIMEOUT);\n }\n }catch (RpcException re){\n re.printStackTrace();\n }finally {", "score": 0.7396680116653442 }, { "filename": "lint-rpc-demo/lint-rpc-demo-consumer/src/main/java/com/lint/rpc/demo/consumer/ConsumerApplication.java", "retrieved_chunk": " CountDownLatch c = new CountDownLatch(20);\n // 拟并发请求\n for (int i = 0; i < c.getCount(); i++) {\n new Thread(()->{\n // 调用链路1 生产者1 -> 生产者2 , 输出合并结果\n ProvideEatInterfaceSpi provide1 =\n ProxyPool.getProxyGet(ProvideEatInterfaceSpi.class);\n // 调用链路2 生产这2 ,输出一个List集合\n ProvideDrinkInterfaceSpi provide2 =\n ProxyPool.getProxyGet(ProvideDrinkInterfaceSpi.class);", "score": 0.7240468263626099 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyClient.java", "retrieved_chunk": " private void onLoseConnect(Future<?> f) {\n System.out.println(\"系统通知 - 注意: 服务器连接关闭! >>> \" + conf.getAddress());\n this.ch = null;\n final Consumer<NettyClient> closeCallback = conf.getCloseCallback();\n if(null != closeCallback){\n closeCallback.accept(this);\n }\n }\n @Override\n public int hashCode() {", "score": 0.7192302346229553 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/proxy/RpcInvocationHandler.java", "retrieved_chunk": " requestContent.setRequestHeader(requestHeader);\n requestContent.setRequestBody(requestBody);\n LoadBalancePolicyFactory loadBalancePolicyFactory = LoadBalancePolicyFactory.getInstance();\n NettyClient nc = loadBalancePolicyFactory\n .getClient(interfaceInfo);\n Object responseMsg = null;\n try {\n boolean sendFlag = nc.sendMsg(requestContent);\n if(!sendFlag){\n // 无法建立连接", "score": 0.7157477140426636 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/proxy/RpcInvocationHandler.java", "retrieved_chunk": " throw new RpcException(RpcMsg.EXCEPTION_NOT_CONNECTION);\n }\n // 如果无返回值 则直接退出\n if(method.getReturnType().equals(Void.TYPE)){\n return responseMsg;\n }\n ConfPool confPool = ConfPool.getInstance();\n LintConf lintConf = confPool.get();\n // 锁定线程 并等待 60秒,如果有结果会直接返回\n CountDownLatchPool.await(", "score": 0.7150809168815613 } ]
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/pool/ClientPool.java", "retrieved_chunk": " }\n }\n }finally {\n rLock.unlock();\n }\n });\n ClientFactory factory = ClientFactory.getInstance();\n return factory.create(conf);\n }\n private String getGroupName(InetSocketAddress address){", "score": 0.8283488750457764 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ClientPool.java", "retrieved_chunk": " }\n }\n }\n return nc;\n }\n private NettyClient createClient(String serviceName, InetSocketAddress address){\n NettyConf conf = new NettyConf();\n conf.setAddress(address);\n conf.setCloseCallback((c)->{\n try {", "score": 0.8209024667739868 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyServerConf.java", "retrieved_chunk": "package com.lint.rpc.common.transport;\npublic class NettyServerConf {\n private int port;\n public int getPort() {\n return port;\n }\n public void setPort(int port) {\n this.port = port;\n }\n}", "score": 0.819480299949646 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/thread/ExecuteThread.java", "retrieved_chunk": " public static class ThreadWrapper implements Runnable {\n private final Runnable r;\n public ThreadWrapper(Runnable r){\n this.r = r;\n }\n @Override\n public void run() {\n try {\n r.run();\n }catch (Exception e){", "score": 0.8100688457489014 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/enums/RpcMsg.java", "retrieved_chunk": " @Override\n public Integer getCode() {\n return this.code;\n }\n @Override\n public String getMessage() {\n return this.message;\n }\n}", "score": 0.8089847564697266 } ]
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": 0.8312809467315674 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/ClientChannelHandler.java", "retrieved_chunk": " public void channelRead(ChannelHandlerContext ctx, Object msg) {\n if(!(msg instanceof RequestContent)){\n return;\n }\n //System.out.println(\"客户端处理数据......\");\n RequestContent content = (RequestContent) msg;\n RequestHeader requestHeader = content.getRequestHeader();\n RequestBody requestBody = content.getRequestBody();\n MsgPool.put(requestHeader.getRequestId(), requestBody.getRes());\n CountDownLatchPool.countDown(requestHeader.getRequestId());", "score": 0.7720136046409607 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/protocol/RequestHeader.java", "retrieved_chunk": "public class RequestHeader implements Serializable {\n /** 标识 */\n private int flag;\n /** 请求ID */\n private long requestId;\n /** 长度 */\n private int length;\n public RequestHeader(byte[] requestBodyBytes){\n requestId = Math.abs(UUID.randomUUID().getLeastSignificantBits());\n length = requestBodyBytes.length;", "score": 0.7630300521850586 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyServer.java", "retrieved_chunk": "/**\n * Netty 服务端\n *\n * @author 周鹏程\n * @date 2023-05-26 12:45 PM\n **/\npublic class NettyServer {\n private final NettyServerConf conf;\n public NettyServer(NettyServerConf conf){\n this.conf = conf;", "score": 0.7385382056236267 }, { "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": 0.7288744449615479 } ]
java
.writeBytes(innerMsg.getRequestHeader().toBytesArray());
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/proxy/RpcInvocationHandler.java", "retrieved_chunk": " throw new RpcException(RpcMsg.EXCEPTION_NOT_CONNECTION);\n }\n // 如果无返回值 则直接退出\n if(method.getReturnType().equals(Void.TYPE)){\n return responseMsg;\n }\n ConfPool confPool = ConfPool.getInstance();\n LintConf lintConf = confPool.get();\n // 锁定线程 并等待 60秒,如果有结果会直接返回\n CountDownLatchPool.await(", "score": 0.8063335418701172 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyServer.java", "retrieved_chunk": "/**\n * Netty 服务端\n *\n * @author 周鹏程\n * @date 2023-05-26 12:45 PM\n **/\npublic class NettyServer {\n private final NettyServerConf conf;\n public NettyServer(NettyServerConf conf){\n this.conf = conf;", "score": 0.7843883037567139 }, { "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": 0.784121036529541 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/proxy/RpcInvocationHandler.java", "retrieved_chunk": " requestHeader.getRequestId(), lintConf.getRequestWaitTimeBySeconds());\n // 消息池查询数据 如果查到则序列化返回 ,超时则返回超时 或者 调用兜底补偿\n responseMsg = MsgPool.getAndRemove(requestHeader.getRequestId());\n if(null == responseMsg){\n // 请求超时\n throw new RpcException(RpcMsg.EXCEPTION_TIMEOUT);\n }\n }catch (RpcException re){\n re.printStackTrace();\n }finally {", "score": 0.7683887481689453 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ClientPool.java", "retrieved_chunk": "import java.util.concurrent.locks.ReentrantLock;\n/**\n * 客户端连接池\n *\n * @author 周鹏程\n * @date 2023-05-26 7:38 PM\n **/\npublic final class ClientPool {\n // serviceName 为服务名\n // hostname+port 为组名", "score": 0.7639706134796143 } ]
java
NettyClient> closeCallback = conf.getCloseCallback();
package com.lint.rpc.common.transport; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import java.net.InetSocketAddress; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.concurrent.Future; import java.util.function.Consumer; /** * Netty 客户端 * * @author 周鹏程 * @date 2023-05-26 12:45 PM **/ public class NettyClient { private final NettyConf conf; private volatile NioSocketChannel ch; public NettyClient(NettyConf conf){ this.conf = conf; } public boolean sendMsg(Object msg){ if(ch == null){ synchronized (this){ if(ch == null){ this.connect(); } } } if(ch == null){ return false; } try { ch.writeAndFlush(msg).sync(); return true; } catch (InterruptedException e) { e.printStackTrace(); } return false; } public NettyConf getConf() { return conf; } private void connect(){ if(null == conf.getAddress()){ return; } NioEventLoopGroup workGroup = new NioEventLoopGroup(); Bootstrap bs = new Bootstrap(); bs.group(workGroup) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<NioSocketChannel>() { @Override protected void initChannel(NioSocketChannel ch) { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new InternalServerMsgCodec()); pipeline.addLast(new ClientChannelHandler()); } }); try { ChannelFuture f =
bs.connect(conf.getAddress()).sync();
if (!f.isSuccess()) { return; } ch = (NioSocketChannel) f.channel(); ch.closeFuture().addListener(this::onLoseConnect); System.out.println(">>> 连接到业务服务器成功! "+conf.getAddress()+" <<<"); } catch (InterruptedException e) { e.printStackTrace(); } } /** * 当失去连接时 * * @param f 预期 */ private void onLoseConnect(Future<?> f) { System.out.println("系统通知 - 注意: 服务器连接关闭! >>> " + conf.getAddress()); this.ch = null; final Consumer<NettyClient> closeCallback = conf.getCloseCallback(); if(null != closeCallback){ closeCallback.accept(this); } } @Override public int hashCode() { return Objects.hash(conf.getAddress().getHostName(), conf.getAddress().getPort()); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()){ return false; } NettyConf selfConf = this.getConf(); NettyClient client = (NettyClient) obj; NettyConf clientConf = client.getConf(); return selfConf.getAddress().getHostName().equals(clientConf.getAddress().getHostName()) && selfConf.getAddress().getPort() == clientConf.getAddress().getPort(); } }
lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyClient.java
hiparker-lint-rpc-framework-e64aac0
[ { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyServer.java", "retrieved_chunk": " .group(bossGroup, workerGroup)\n .childHandler(new ChannelInitializer<NioSocketChannel>() {\n @Override\n protected void initChannel(NioSocketChannel ch) {\n ChannelPipeline p = ch.pipeline();\n p.addLast(new InternalServerMsgCodec());\n p.addLast(new ServerChannelHandler());\n }\n })\n .bind(conf.getPort());", "score": 0.9224708676338196 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ClientPool.java", "retrieved_chunk": " }\n }\n }\n return nc;\n }\n private NettyClient createClient(String serviceName, InetSocketAddress address){\n NettyConf conf = new NettyConf();\n conf.setAddress(address);\n conf.setCloseCallback((c)->{\n try {", "score": 0.79582279920578 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyServer.java", "retrieved_chunk": " }\n public NettyServerConf getConf() {\n return conf;\n }\n public void init(){\n int cpuCount = Runtime.getRuntime().availableProcessors();\n NioEventLoopGroup bossGroup = new NioEventLoopGroup();\n NioEventLoopGroup workerGroup = new NioEventLoopGroup(getThreadMaxCount(cpuCount));\n ServerBootstrap bs = new ServerBootstrap();\n ChannelFuture bind = bs.channel(NioServerSocketChannel.class)", "score": 0.7921826839447021 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/ServerChannelHandler.java", "retrieved_chunk": "public class ServerChannelHandler extends ChannelInboundHandlerAdapter {\n @Override\n public void channelRead(ChannelHandlerContext ctx, Object msg) {\n if(!(msg instanceof RequestContent)){\n return;\n }\n //System.out.println(Thread.currentThread().getName() + \" 服务端处理数据......\");\n RequestContent content = (RequestContent) msg;\n RequestHeader requestHeader = content.getRequestHeader();\n RequestBody requestBody = content.getRequestBody();", "score": 0.7521495819091797 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ClientPool.java", "retrieved_chunk": " InetSocketAddress inetSocketAddress =\n linkedHashSetGetByIndex(addressSet, clientIndex);\n NettyClient ch = createClient(serviceName, inetSocketAddress);\n return put(serviceName, ch);\n }\n }finally {\n rLock.unlock();\n }\n }\n NettyClient ch = null;", "score": 0.7515822052955627 } ]
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": " requestContent.setRequestHeader(requestHeader);\n requestContent.setRequestBody(requestBody);\n LoadBalancePolicyFactory loadBalancePolicyFactory = LoadBalancePolicyFactory.getInstance();\n NettyClient nc = loadBalancePolicyFactory\n .getClient(interfaceInfo);\n Object responseMsg = null;\n try {\n boolean sendFlag = nc.sendMsg(requestContent);\n if(!sendFlag){\n // 无法建立连接", "score": 0.8050135374069214 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/bootstrap/LintRpcServerApplication.java", "retrieved_chunk": " confPool.init(conf);\n // 2. 加载SPI 并初始化\n ProvideSpi provideSpi = ProvideSpi.getInstance();\n provideSpi.init();\n // 3. 加载服务端SPI\n ProvideServiceSpi provideServiceSpi = ProvideServiceSpi.getInstance();\n provideServiceSpi.init();\n // TODO baseClazz 后序扩展一下\n // 4. 启动服务端\n NettyServerConf nettyServerConf = new NettyServerConf();", "score": 0.8011543154716492 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/proxy/RpcInvocationHandler.java", "retrieved_chunk": " throw new RpcException(RpcMsg.EXCEPTION_NOT_CONNECTION);\n }\n // 如果无返回值 则直接退出\n if(method.getReturnType().equals(Void.TYPE)){\n return responseMsg;\n }\n ConfPool confPool = ConfPool.getInstance();\n LintConf lintConf = confPool.get();\n // 锁定线程 并等待 60秒,如果有结果会直接返回\n CountDownLatchPool.await(", "score": 0.7761573195457458 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/service/ProvideServiceSpi.java", "retrieved_chunk": " if(!isInit){\n synchronized (this){\n if(!isInit){\n ServiceLoader<LintService> loader = ServiceLoader.load(LintService.class);\n for (LintService ls : loader) {\n RpcService annotation = ls.getClass().getAnnotation(RpcService.class);\n if(null == annotation){\n System.out.println(\n \"warning spi class not found @RpcService >>> \" +\n ls.getClass().getName());", "score": 0.7749540209770203 }, { "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": 0.768667459487915 } ]
java
requestBody.setRes(res);
package com.lint.rpc.common.transport; import com.lint.rpc.common.protocol.RequestBody; import com.lint.rpc.common.protocol.RequestContent; import com.lint.rpc.common.protocol.RequestHeader; import com.lint.rpc.common.service.ProvideServiceSpi; import com.lint.rpc.common.spi.LintService; import com.lint.rpc.common.thread.ExecuteThread; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import java.lang.reflect.Method; public class ServerChannelHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if(!(msg instanceof RequestContent)){ return; } //System.out.println(Thread.currentThread().getName() + " 服务端处理数据......"); RequestContent content = (RequestContent) msg; RequestHeader requestHeader = content.getRequestHeader(); RequestBody requestBody = content.getRequestBody(); // 本身可以受到 NettyEventLoop线程 进行多线程执行 ProvideServiceSpi spi = ProvideServiceSpi.getInstance(); LintService service = spi.getService(requestBody.getName(), requestHeader.getVersion()); if(null == service){ return; } try { Method method = service.getClass().getMethod(requestBody.getMethodName()); Object res = method.invoke(service, requestBody.getArgs()); requestBody.setRes(res); }catch (Exception e){ e.printStackTrace(); } requestHeader
.setLength(requestBody.toBytesArray().length);
ctx.channel().writeAndFlush(content); // 转多线程处理 // ExecuteThread et = ExecuteThread.getInstance(); // et.execute(()->{ // ProvideServiceSpi spi = ProvideServiceSpi.getInstance(); // LintService service = spi.getService(requestBody.getName(), requestHeader.getVersion()); // if(null == service){ // return; // } // // try { // Method method = service.getClass().getMethod(requestBody.getMethodName()); // Object res = method.invoke(service, requestBody.getArgs()); // requestBody.setRes(res); // }catch (Exception e){ // e.printStackTrace(); // } // // requestHeader.setLength(requestBody.toBytesArray().length); // ctx.channel().writeAndFlush(content); // }); } }
lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/ServerChannelHandler.java
hiparker-lint-rpc-framework-e64aac0
[ { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/proxy/RpcInvocationHandler.java", "retrieved_chunk": " String methodName = method.getName();\n Class<?>[] parameterTypes = method.getParameterTypes();\n RequestBody requestBody = new RequestBody();\n requestBody.setName(annotation.name());\n requestBody.setMethodName(methodName);\n requestBody.setParameterTypes(parameterTypes);\n requestBody.setArgs(args);\n RequestHeader requestHeader = new RequestHeader(requestBody.toBytesArray());\n requestHeader.setVersion(annotation.version());\n RequestContent requestContent = new RequestContent();", "score": 0.7861983776092529 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/InternalServerMsgCodec.java", "retrieved_chunk": "// \", bodyName = \"+requestBody.getName()+\n// \", bodyMethodName = \"+requestBody.getMethodName());\n RequestContent requestContent = new RequestContent();\n requestContent.setRequestHeader(requestHeader);\n requestContent.setRequestBody(requestBody);\n // 出发消息读取事件\n ctx.fireChannelRead(requestContent);\n }\n }\n /**", "score": 0.7626532316207886 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/InternalServerMsgCodec.java", "retrieved_chunk": " ObjectInputStream ois = new ObjectInputStream(in);\n ) {\n requestBody = (RequestBody) ois.readObject();\n } catch (IOException | ClassNotFoundException e) {\n e.printStackTrace();\n requestBody = new RequestBody();\n }\n// System.out.println(\"收到消息 => \" +\n// \"requestId = \"+requestHeader.getRequestId() +\n// \", flag = \"+requestHeader.getFlag()+", "score": 0.7518253326416016 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/ClientChannelHandler.java", "retrieved_chunk": " public void channelRead(ChannelHandlerContext ctx, Object msg) {\n if(!(msg instanceof RequestContent)){\n return;\n }\n //System.out.println(\"客户端处理数据......\");\n RequestContent content = (RequestContent) msg;\n RequestHeader requestHeader = content.getRequestHeader();\n RequestBody requestBody = content.getRequestBody();\n MsgPool.put(requestHeader.getRequestId(), requestBody.getRes());\n CountDownLatchPool.countDown(requestHeader.getRequestId());", "score": 0.7199946641921997 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/InternalServerMsgCodec.java", "retrieved_chunk": " RequestHeader requestHeader = null;\n try(ByteArrayInputStream in = new ByteArrayInputStream(headByteArray);\n ObjectInputStream ois = new ObjectInputStream(in);\n ) {\n requestHeader = (RequestHeader) ois.readObject();\n } catch (IOException | ClassNotFoundException e) {\n e.printStackTrace();\n }\n // 如果消息体长度不够 直接退出\n if(null == requestHeader ||", "score": 0.7066170573234558 } ]
java
.setLength(requestBody.toBytesArray().length);
package com.lint.rpc.common.transport; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import java.net.InetSocketAddress; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.concurrent.Future; import java.util.function.Consumer; /** * Netty 客户端 * * @author 周鹏程 * @date 2023-05-26 12:45 PM **/ public class NettyClient { private final NettyConf conf; private volatile NioSocketChannel ch; public NettyClient(NettyConf conf){ this.conf = conf; } public boolean sendMsg(Object msg){ if(ch == null){ synchronized (this){ if(ch == null){ this.connect(); } } } if(ch == null){ return false; } try { ch.writeAndFlush(msg).sync(); return true; } catch (InterruptedException e) { e.printStackTrace(); } return false; } public NettyConf getConf() { return conf; } private void connect(){ if(null == conf.getAddress()){ return; } NioEventLoopGroup workGroup = new NioEventLoopGroup(); Bootstrap bs = new Bootstrap(); bs.group(workGroup) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<NioSocketChannel>() { @Override protected void initChannel(NioSocketChannel ch) { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new InternalServerMsgCodec()); pipeline.addLast(new ClientChannelHandler()); } }); try { ChannelFuture f = bs.connect(conf.getAddress()).sync(); if (!f.isSuccess()) { return; } ch = (NioSocketChannel) f.channel(); ch.closeFuture().addListener(this::onLoseConnect); System.out.println(">>> 连接到业务服务器成功! "+conf.getAddress()+" <<<"); } catch (InterruptedException e) { e.printStackTrace(); } } /** * 当失去连接时 * * @param f 预期 */ private void onLoseConnect(Future<?> f) { System.out.println("系统通知 - 注意: 服务器连接关闭! >>> " + conf.getAddress()); this.ch = null; final Consumer<NettyClient> closeCallback = conf.getCloseCallback(); if(null != closeCallback){ closeCallback.accept(this); } } @Override public int hashCode() { return
Objects.hash(conf.getAddress().getHostName(), conf.getAddress().getPort());
} @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()){ return false; } NettyConf selfConf = this.getConf(); NettyClient client = (NettyClient) obj; NettyConf clientConf = client.getConf(); return selfConf.getAddress().getHostName().equals(clientConf.getAddress().getHostName()) && selfConf.getAddress().getPort() == clientConf.getAddress().getPort(); } }
lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyClient.java
hiparker-lint-rpc-framework-e64aac0
[ { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyConf.java", "retrieved_chunk": " this.address = address;\n }\n public Consumer<NettyClient> getCloseCallback() {\n return closeCallback;\n }\n public void setCloseCallback(Consumer<NettyClient> closeCallback) {\n this.closeCallback = closeCallback;\n }\n}", "score": 0.8668304681777954 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ClientPool.java", "retrieved_chunk": " }\n }\n }\n return nc;\n }\n private NettyClient createClient(String serviceName, InetSocketAddress address){\n NettyConf conf = new NettyConf();\n conf.setAddress(address);\n conf.setCloseCallback((c)->{\n try {", "score": 0.8602890968322754 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ClientPool.java", "retrieved_chunk": " }\n }\n }finally {\n rLock.unlock();\n }\n });\n ClientFactory factory = ClientFactory.getInstance();\n return factory.create(conf);\n }\n private String getGroupName(InetSocketAddress address){", "score": 0.8130263090133667 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/NettyConf.java", "retrieved_chunk": "package com.lint.rpc.common.transport;\nimport java.net.InetSocketAddress;\nimport java.util.function.Consumer;\npublic class NettyConf {\n private InetSocketAddress address;\n private Consumer<NettyClient> closeCallback;\n public InetSocketAddress getAddress() {\n return address;\n }\n public void setAddress(InetSocketAddress address) {", "score": 0.8103721141815186 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/ClientPool.java", "retrieved_chunk": " InetSocketAddress inetSocketAddress =\n linkedHashSetGetByIndex(addressSet, clientIndex);\n NettyClient ch = createClient(serviceName, inetSocketAddress);\n return put(serviceName, ch);\n }\n }finally {\n rLock.unlock();\n }\n }\n NettyClient ch = null;", "score": 0.7959027290344238 } ]
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": 0.7223787307739258 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/balance/LoadBalancePolicyFactory.java", "retrieved_chunk": " return null;\n }\n ClientPool pool = ClientPool.getInstance();\n // 选择客户端\n return pool.get(rpcClientAnnotation.name(), loadBalancePolicy);\n }\n private ILoadBalancePolicy getLoadBalancePolicy(\n Class<? extends ILoadBalancePolicy> loadBalancePolicyClazz){\n ILoadBalancePolicy loadBalancePolicy = loadBalancePolicyMap.get(loadBalancePolicyClazz);\n if(null != loadBalancePolicy){", "score": 0.7185183763504028 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/proxy/RpcInvocationHandler.java", "retrieved_chunk": " requestContent.setRequestHeader(requestHeader);\n requestContent.setRequestBody(requestBody);\n LoadBalancePolicyFactory loadBalancePolicyFactory = LoadBalancePolicyFactory.getInstance();\n NettyClient nc = loadBalancePolicyFactory\n .getClient(interfaceInfo);\n Object responseMsg = null;\n try {\n boolean sendFlag = nc.sendMsg(requestContent);\n if(!sendFlag){\n // 无法建立连接", "score": 0.7123787999153137 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/balance/LoadBalancePolicyFactory.java", "retrieved_chunk": " * @date 2023-05-26 10:53 AM\n **/\npublic class LoadBalancePolicyFactory {\n private final Object lock = new Object();\n private final Map<Class<? extends ILoadBalancePolicy>, ILoadBalancePolicy>\n loadBalancePolicyMap = new ConcurrentHashMap<>();\n public NettyClient getClient(Class<?> interfaceClazz) {\n RpcClient rpcClientAnnotation = interfaceClazz.getAnnotation(RpcClient.class);\n ILoadBalancePolicy loadBalancePolicy = getLoadBalancePolicy(rpcClientAnnotation.loadBalancePolicy());\n if(null == loadBalancePolicy){", "score": 0.700416624546051 }, { "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": 0.6938662528991699 } ]
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/service/ProvideSpi.java", "retrieved_chunk": " }\n provideService = ps;\n break;\n }\n isInit = true;\n }\n }\n }\n }\n public LinkedHashSet<InetSocketAddress> getAddressByServiceName(String serviceName){", "score": 0.8243374228477478 }, { "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": 0.8117369413375854 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/service/ProvideServiceSpi.java", "retrieved_chunk": " continue;\n }\n serviceMap.putIfAbsent(annotation.name()+\":\"+annotation.version(), ls);\n }\n isInit = true;\n }\n }\n }\n }\n public LintService getService(String serviceName, short version){", "score": 0.7897422313690186 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/balance/LoadBalancePolicyFactory.java", "retrieved_chunk": " loadBalancePolicyMap.putIfAbsent(loadBalancePolicyClazz, loadBalancePolicy);\n }catch (Exception e){\n e.printStackTrace();\n }\n return loadBalancePolicy;\n }\n }\n private LoadBalancePolicyFactory(){}\n private static class LazyHolder {\n private static final LoadBalancePolicyFactory INSTANCE = new LoadBalancePolicyFactory();", "score": 0.7830765843391418 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/CountDownLatchPool.java", "retrieved_chunk": " timeoutSeconds = 0;\n }\n CountDownLatch countDownLatch = new CountDownLatch(1);\n // 超时自动释放\n MSG_POOL_MAP.putIfAbsent(requestId, countDownLatch);\n countDownLatch.await(timeoutSeconds, TimeUnit.SECONDS);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }", "score": 0.757611095905304 } ]
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/transport/NettyClient.java", "retrieved_chunk": " System.out.println(\">>> 连接到业务服务器成功! \"+conf.getAddress()+\" <<<\");\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n /**\n * 当失去连接时\n *\n * @param f 预期\n */", "score": 0.8035653829574585 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/proxy/RpcInvocationHandler.java", "retrieved_chunk": " requestHeader.getRequestId(), lintConf.getRequestWaitTimeBySeconds());\n // 消息池查询数据 如果查到则序列化返回 ,超时则返回超时 或者 调用兜底补偿\n responseMsg = MsgPool.getAndRemove(requestHeader.getRequestId());\n if(null == responseMsg){\n // 请求超时\n throw new RpcException(RpcMsg.EXCEPTION_TIMEOUT);\n }\n }catch (RpcException re){\n re.printStackTrace();\n }finally {", "score": 0.773470938205719 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/proxy/RpcInvocationHandler.java", "retrieved_chunk": " throw new RpcException(RpcMsg.EXCEPTION_NOT_CONNECTION);\n }\n // 如果无返回值 则直接退出\n if(method.getReturnType().equals(Void.TYPE)){\n return responseMsg;\n }\n ConfPool confPool = ConfPool.getInstance();\n LintConf lintConf = confPool.get();\n // 锁定线程 并等待 60秒,如果有结果会直接返回\n CountDownLatchPool.await(", "score": 0.7618805766105652 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/bootstrap/LintRpcClientApplication.java", "retrieved_chunk": " provideSpi.init();\n // TODO baseClazz 后序扩展一下\n }\n}", "score": 0.7325804829597473 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/service/ProvideSpi.java", "retrieved_chunk": " }\n provideService = ps;\n break;\n }\n isInit = true;\n }\n }\n }\n }\n public LinkedHashSet<InetSocketAddress> getAddressByServiceName(String serviceName){", "score": 0.7302194833755493 } ]
java
groupIndex = loadBalancePolicy.getClientIndex(groupNameSet.size());
package com.lint.rpc.common.exception; import com.lint.rpc.common.enums.BaseMsg; /** * 框架服务异常 * * @author Parker * @date 2020-09-13 19:41 */ public class RpcException extends RuntimeException{ private Integer code; private String errorMessage; public RpcException(Integer code, String errorMessage) { super(errorMessage); this.code = code; this.errorMessage = errorMessage; } public RpcException(Integer code, String errorMessage, Throwable e) { super(errorMessage, e); this.code = code; this.errorMessage = errorMessage; } public RpcException(BaseMsg msg) { super(
msg.getMessage());
this.code = msg.getCode(); this.errorMessage = msg.getMessage(); } public RpcException(BaseMsg msg, Throwable e) { super(msg.getMessage(), e); this.code = msg.getCode(); this.errorMessage = msg.getMessage(); } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } }
lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/exception/RpcException.java
hiparker-lint-rpc-framework-e64aac0
[ { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/enums/RpcMsg.java", "retrieved_chunk": " EXCEPTION_NOT_CONNECTION(501,\"Unable to establish connection\"),\n /** 请求错误 */\n EXCEPTION_ERROR(500,\"Request error\"),\n ;\n private final int code;\n private final String message;\n RpcMsg(int code, String message){\n this.code = code;\n this.message = message;\n }", "score": 0.8739181756973267 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/enums/RpcMsg.java", "retrieved_chunk": " @Override\n public Integer getCode() {\n return this.code;\n }\n @Override\n public String getMessage() {\n return this.message;\n }\n}", "score": 0.8419505953788757 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/protocol/RequestBody.java", "retrieved_chunk": " return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getMethodName() {\n return methodName;\n }\n public void setMethodName(String methodName) {\n this.methodName = methodName;", "score": 0.8150101900100708 }, { "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": 0.8085179328918457 }, { "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": 0.8032462000846863 } ]
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/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": 0.7836784720420837 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/proxy/RpcInvocationHandler.java", "retrieved_chunk": " requestHeader.getRequestId(), lintConf.getRequestWaitTimeBySeconds());\n // 消息池查询数据 如果查到则序列化返回 ,超时则返回超时 或者 调用兜底补偿\n responseMsg = MsgPool.getAndRemove(requestHeader.getRequestId());\n if(null == responseMsg){\n // 请求超时\n throw new RpcException(RpcMsg.EXCEPTION_TIMEOUT);\n }\n }catch (RpcException re){\n re.printStackTrace();\n }finally {", "score": 0.7821940779685974 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/util/ByteUtil.java", "retrieved_chunk": "public final class ByteUtil {\n public static byte[] toByteArray(Object obj){\n if(obj == null){\n return new byte[0];\n }\n ObjectOutputStream oos = null;\n ByteArrayOutputStream out = new ByteArrayOutputStream();\n byte[] bytes = null;\n try {\n oos = new ObjectOutputStream(out);", "score": 0.7706907987594604 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/transport/ServerChannelHandler.java", "retrieved_chunk": "public class ServerChannelHandler extends ChannelInboundHandlerAdapter {\n @Override\n public void channelRead(ChannelHandlerContext ctx, Object msg) {\n if(!(msg instanceof RequestContent)){\n return;\n }\n //System.out.println(Thread.currentThread().getName() + \" 服务端处理数据......\");\n RequestContent content = (RequestContent) msg;\n RequestHeader requestHeader = content.getRequestHeader();\n RequestBody requestBody = content.getRequestBody();", "score": 0.7619078159332275 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/proxy/RpcInvocationHandler.java", "retrieved_chunk": " requestContent.setRequestHeader(requestHeader);\n requestContent.setRequestBody(requestBody);\n LoadBalancePolicyFactory loadBalancePolicyFactory = LoadBalancePolicyFactory.getInstance();\n NettyClient nc = loadBalancePolicyFactory\n .getClient(interfaceInfo);\n Object responseMsg = null;\n try {\n boolean sendFlag = nc.sendMsg(requestContent);\n if(!sendFlag){\n // 无法建立连接", "score": 0.7545627355575562 } ]
java
requestHeader.getLength()){
package com.utils.InteractionApi; import com.utils.HypsApiPlugin.NPCs; import com.utils.Packets.MousePackets; import com.utils.Packets.NPCPackets; import net.runelite.api.NPC; import java.util.Optional; import java.util.function.Predicate; public class NPCInteraction { public static boolean interact(String name, String... actions) { return NPCs.search().withName(name).first().flatMap(npc -> { MousePackets.queueClickPacket(); NPCPackets.queueNPCAction(npc, actions); return Optional.of(true); }).orElse(false); } public static boolean interact(int id, String... actions) { return NPCs.search().withId(id).first().flatMap(npc -> { MousePackets.queueClickPacket(); NPCPackets.queueNPCAction(npc, actions); return Optional.of(true); }).orElse(false); } public static boolean interact(Predicate<? super NPC> predicate, String... actions) { return NPCs.search().filter(predicate).first().flatMap(npc -> { MousePackets.queueClickPacket(); NPCPackets.queueNPCAction(npc, actions); return Optional.of(true); }).orElse(false); } public static boolean interactIndex(int index, String... actions) { return
NPCs.search().indexIs(index).first().flatMap(npc -> {
MousePackets.queueClickPacket(); NPCPackets.queueNPCAction(npc, actions); return Optional.of(true); }).orElse(false); } public static boolean interact(NPC npc, String... actions) { if (npc == null) { return false; } MousePackets.queueClickPacket(); NPCPackets.queueNPCAction(npc, actions); return true; } }
src/main/java/com/utils/InteractionApi/NPCInteraction.java
Hypsster-hUtils-d265b4f
[ { "filename": "src/main/java/com/utils/InteractionApi/PlayerInteractionHelper.java", "retrieved_chunk": "\t{\n\t\treturn Players.search().withName(name).first().flatMap(Player ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tPlayerPackets.queuePlayerAction(Player, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean interact(Predicate<? super Player> predicate, String... actions)\n\t{", "score": 0.8879780769348145 }, { "filename": "src/main/java/com/utils/InteractionApi/InventoryInteraction.java", "retrieved_chunk": "\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItemIndex(int index, String... actions)\n\t{\n\t\treturn Inventory.search().indexIs(index).first().flatMap(item ->\n\t\t{", "score": 0.8856368064880371 }, { "filename": "src/main/java/com/utils/InteractionApi/BankInteraction.java", "retrieved_chunk": "\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItemIndex(int index, String... actions)\n\t{\n\t\treturn Bank.search().indexIs(index).first().flatMap(item ->\n\t\t{", "score": 0.877144992351532 }, { "filename": "src/main/java/com/utils/InteractionApi/BankInventoryInteraction.java", "retrieved_chunk": "\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItemIndex(int index, String... actions)\n\t{\n\t\treturn BankInventory.search().indexIs(index).first().flatMap(item ->\n\t\t{", "score": 0.8741521239280701 }, { "filename": "src/main/java/com/utils/InteractionApi/InventoryInteraction.java", "retrieved_chunk": "\t{\n\t\treturn Inventory.search().withName(name).first().flatMap(item ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItem(int id, String... actions)\n\t{", "score": 0.8602467775344849 } ]
java
NPCs.search().indexIs(index).first().flatMap(npc -> {
package com.utils.InteractionApi; import com.utils.HypsApiPlugin.Bank; import com.utils.Packets.MousePackets; import com.utils.Packets.WidgetPackets; import net.runelite.api.widgets.Widget; import java.util.Optional; import java.util.function.Predicate; public class BankInteraction { public static boolean useItem(String name, String... actions) { return Bank.search().withName(name).first().flatMap(item -> { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(item, actions); return Optional.of(true); }).orElse(false); } public static boolean useItem(int id, String... actions) { return Bank.search().withId(id).first().flatMap(item -> { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(item, actions); return Optional.of(true); }).orElse(false); } public static boolean useItem(Predicate<? super Widget> predicate, String... actions) { return Bank.search().filter(predicate).first().flatMap(item -> { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(item, actions); return Optional.of(true); }).orElse(false); } public static boolean useItemIndex(int index, String... actions) {
return Bank.search().indexIs(index).first().flatMap(item -> {
MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(item, actions); return Optional.of(true); }).orElse(false); } public static boolean useItem(Widget item, String... actions) { if (item == null) { return false; } MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(item, actions); return true; } }
src/main/java/com/utils/InteractionApi/BankInteraction.java
Hypsster-hUtils-d265b4f
[ { "filename": "src/main/java/com/utils/InteractionApi/BankInventoryInteraction.java", "retrieved_chunk": "\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItemIndex(int index, String... actions)\n\t{\n\t\treturn BankInventory.search().indexIs(index).first().flatMap(item ->\n\t\t{", "score": 0.992361843585968 }, { "filename": "src/main/java/com/utils/InteractionApi/InventoryInteraction.java", "retrieved_chunk": "\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItemIndex(int index, String... actions)\n\t{\n\t\treturn Inventory.search().indexIs(index).first().flatMap(item ->\n\t\t{", "score": 0.9798908233642578 }, { "filename": "src/main/java/com/utils/InteractionApi/BankInventoryInteraction.java", "retrieved_chunk": "\t{\n\t\treturn BankInventory.search().withName(name).first().flatMap(item ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItem(int id, String... actions)\n\t{", "score": 0.9487862586975098 }, { "filename": "src/main/java/com/utils/InteractionApi/BankInventoryInteraction.java", "retrieved_chunk": "\t\treturn BankInventory.search().withId(id).first().flatMap(item ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItem(Predicate<? super Widget> predicate, String... actions)\n\t{\n\t\treturn BankInventory.search().filter(predicate).first().flatMap(item ->", "score": 0.9463683366775513 }, { "filename": "src/main/java/com/utils/InteractionApi/InventoryInteraction.java", "retrieved_chunk": "\t{\n\t\treturn Inventory.search().withName(name).first().flatMap(item ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItem(int id, String... actions)\n\t{", "score": 0.9377658367156982 } ]
java
return Bank.search().indexIs(index).first().flatMap(item -> {
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/transport/ServerChannelHandler.java", "retrieved_chunk": " // 本身可以受到 NettyEventLoop线程 进行多线程执行\n ProvideServiceSpi spi = ProvideServiceSpi.getInstance();\n LintService service = spi.getService(requestBody.getName(), requestHeader.getVersion());\n if(null == service){\n return;\n }\n try {\n Method method = service.getClass().getMethod(requestBody.getMethodName());\n Object res = method.invoke(service, requestBody.getArgs());\n requestBody.setRes(res);", "score": 0.8154605031013489 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/CountDownLatchPool.java", "retrieved_chunk": " timeoutSeconds = 0;\n }\n CountDownLatch countDownLatch = new CountDownLatch(1);\n // 超时自动释放\n MSG_POOL_MAP.putIfAbsent(requestId, countDownLatch);\n countDownLatch.await(timeoutSeconds, TimeUnit.SECONDS);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }", "score": 0.7974731922149658 }, { "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": 0.7879083156585693 }, { "filename": "lint-rpc-support/lint-rpc-support-common/src/main/java/com/lint/rpc/common/pool/CountDownLatchPool.java", "retrieved_chunk": " // 超时自动释放\n MSG_POOL_MAP.putIfAbsent(requestId, countDownLatch);\n countDownLatch.await(TIME_OUT, TimeUnit.SECONDS);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n public static void await(long requestId, int timeoutSeconds){\n try {\n if(timeoutSeconds < 0){", "score": 0.7813971042633057 }, { "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": 0.7751461267471313 } ]
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": " }\n public String getUrl() {\n if (!(this instanceof URL)) throw new BodyException(\"Error this class not implements URL\");\n return this.url;\n }\n public Boolean urlBuild() {\n if (this.getUrl().isEmpty()) return false;\n return Loader.getInstance().isValidUrl(this.getUrl());\n }\n public Map<String, Object> urlToArray() {", "score": 0.8721374869346619 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/EmbedManager.java", "retrieved_chunk": " }\n public Thumbnail getThumbnail() {\n return this.thumbnail;\n }\n public EmbedManager setImage(Image image) {\n if (!image.build()) {\n throw new BodyException(\"Image is invalid: \" + image);\n } else this.image = image;\n return this;\n }", "score": 0.8348023295402527 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/EmbedManager.java", "retrieved_chunk": " public EmbedManager removeImage() {\n this.image = null;\n return this;\n }\n public Image getImage() {\n return this.image;\n }\n public EmbedManager setTimestamp(Timestamp timestamp) {\n if (!timestamp.build()) {\n throw new BodyException(\"Image is invalid: \" + timestamp);", "score": 0.8330712914466858 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/base/Structure.java", "retrieved_chunk": " if (!(this instanceof IconURL)) {\n throw new BodyException(\"Error this class not implements IconURL\");\n } else {\n this.icon = newIcon;\n }\n return this;\n }\n public Boolean iconBuild() {\n if (this.getIcon().isEmpty()) return false;\n return Loader.getInstance().isValidUrl(this.getIcon());", "score": 0.823355495929718 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/EmbedManager.java", "retrieved_chunk": " }\n public Author getAuthor() {\n return this.author;\n }\n public EmbedManager addField(Field field) {\n if (!field.build()) {\n throw new BodyException(\"Field is invalid: \" + field);\n } else this.fields.add(field);\n return this;\n }", "score": 0.8224219083786011 } ]
java
()) && this.getBody().build()) {
package com.ialdrich23xx.libasynwebhook.api.discord; import com.ialdrich23xx.libasynwebhook.api.Loader; import com.ialdrich23xx.libasynwebhook.api.discord.body.Base; import com.ialdrich23xx.libasynwebhook.api.discord.body.embed.base.BodyException; import javax.net.ssl.HttpsURLConnection; import java.io.OutputStream; import java.net.URL; import java.util.concurrent.CompletableFuture; public class WebHook { private final String url; private Base body; public WebHook(String url, Base body) { this.url = url; this.body = body; } public static WebHook make(String url, Base body) { return new WebHook(url, body); } public String getUrl() { return this.url; } public Base getBody() { return this.body; } public WebHook setBody(Base body) { this.body = body; return this; } public void send() { if (this.getBody() == null) throw new BodyException("Body of webhook is null"); if (Loader.getInstance().isValidUrl(this.getUrl()) && this.getBody().build()) { CompletableFuture.runAsync(() -> { try { URL url = new URL(this.url); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.addRequestProperty("Content-Type", "application/json"); connection.addRequestProperty("User-Agent", "CloverCube"); connection.setDoOutput(true); connection.setRequestMethod("POST"); OutputStream stream = connection.getOutputStream(); stream.write(this
.getBody().toJson().getBytes());
stream.flush(); stream.close(); connection.getInputStream().close(); //I'm not sure why, but it doesn't work without getting the InputStream connection.disconnect(); } catch (Exception e) { System.out.println(e.getMessage()); } }); } else throw new BodyException("Url not valid: " + this.getUrl()); } }
libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/WebHook.java
iAldrich23xX-libasynWebhook-52a1773
[ { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/EmbedManager.java", "retrieved_chunk": " if (this.getAuthor() != null) result.put(\"author\", this.getAuthor().toArray());\n if (this.getFooter() != null) result.put(\"footer\", this.getFooter().toArray());\n if (this.getThumbnail() != null) result.put(\"thumbnail\", this.getThumbnail().toArray());\n if (this.getImage() != null) result.put(\"image\", this.getImage().toArray());\n if (this.getTimestamp() != null) result.put(\"timestamp\", this.getTimestamp().getFormat().format(this.getTimestamp().getDate()));\n List<Object> fieldList = new ArrayList<>();\n this.getFields().forEach(field -> fieldList.add(Loader.getInstance().formatToJson(field.toArray().entrySet())));\n if (!fieldList.isEmpty()) {\n result.put(\"fields\", fieldList.toArray());\n }", "score": 0.6155070662498474 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/Base.java", "retrieved_chunk": " if (this.getAvatar() != null) result.put(\"avatar_url\", this.getAvatar());\n List<Object> embedList = new ArrayList<>();\n this.getEmbeds().forEach(embed -> embedList.add(Loader.getInstance().formatToJson(embed.toArray().entrySet())));\n if (!embedList.isEmpty()) {\n result.put(\"embeds\", embedList.toArray());\n }\n if (this.isForum()) result.put(\"thread_name\", this.getForumTitle());\n return result;\n }\n @Override", "score": 0.5904334783554077 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/Base.java", "retrieved_chunk": " if (this.getContent() == null && this.getEmbeds().isEmpty()) return false;\n if (this.getContent() != null && this.getContent().length() == 0) return false;\n return true;\n }\n @Override\n public Map<String, Object> toArray() {\n Map<String, Object> result = new HashMap<>();\n result.put(\"tts\", this.isTextToSpeech());\n if (this.getContent() != null) result.put(\"content\", this.getContent());\n if (this.getUsername() != null) result.put(\"username\", this.getUsername());", "score": 0.5799596309661865 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/Loader.java", "retrieved_chunk": " }\n public String formatToJson(Set<Map.Entry<String, Object>> format) {\n StringBuilder builder = new StringBuilder();\n builder.append(\"{\");\n int i = 0;\n for (Map.Entry<String, Object> entry : format) {\n Object value = entry.getValue();\n builder.append(quote(entry.getKey())).append(\":\");\n if (value instanceof String) {\n builder.append(quote(String.valueOf(value)));", "score": 0.5586725473403931 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/base/URL.java", "retrieved_chunk": "package com.ialdrich23xx.libasynwebhook.api.discord.body.embed.base;\nimport java.util.Map;\npublic interface URL {\n Structure setUrl(String url);\n String getUrl();\n Boolean urlBuild();\n Map<String, Object> urlToArray();\n String urlToString();\n}", "score": 0.5278652906417847 } ]
java
.getBody().toJson().getBytes());
package com.utils.InteractionApi; import com.utils.HypsApiPlugin.BankInventory; import com.utils.Packets.MousePackets; import com.utils.Packets.WidgetPackets; import net.runelite.api.widgets.Widget; import java.util.Optional; import java.util.function.Predicate; public class BankInventoryInteraction { public static boolean useItem(String name, String... actions) { return BankInventory.search().withName(name).first().flatMap(item -> { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(item, actions); return Optional.of(true); }).orElse(false); } public static boolean useItem(int id, String... actions) { return BankInventory.search().withId(id).first().flatMap(item -> { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(item, actions); return Optional.of(true); }).orElse(false); } public static boolean useItem(Predicate<? super Widget> predicate, String... actions) { return BankInventory.search().filter(predicate).first().flatMap(item -> { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(item, actions); return Optional.of(true); }).orElse(false); } public static boolean useItemIndex(int index, String... actions) { return
BankInventory.search().indexIs(index).first().flatMap(item -> {
MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(item, actions); return Optional.of(true); }).orElse(false); } public static boolean useItem(Widget item, String... actions) { if (item == null) { return false; } MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(item, actions); return true; } }
src/main/java/com/utils/InteractionApi/BankInventoryInteraction.java
Hypsster-hUtils-d265b4f
[ { "filename": "src/main/java/com/utils/InteractionApi/BankInteraction.java", "retrieved_chunk": "\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItemIndex(int index, String... actions)\n\t{\n\t\treturn Bank.search().indexIs(index).first().flatMap(item ->\n\t\t{", "score": 0.9781491756439209 }, { "filename": "src/main/java/com/utils/InteractionApi/InventoryInteraction.java", "retrieved_chunk": "\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItemIndex(int index, String... actions)\n\t{\n\t\treturn Inventory.search().indexIs(index).first().flatMap(item ->\n\t\t{", "score": 0.9687298536300659 }, { "filename": "src/main/java/com/utils/InteractionApi/BankInteraction.java", "retrieved_chunk": "\t{\n\t\treturn Bank.search().withName(name).first().flatMap(item ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItem(int id, String... actions)\n\t{", "score": 0.9342743158340454 }, { "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": 0.9308480620384216 }, { "filename": "src/main/java/com/utils/InteractionApi/InventoryInteraction.java", "retrieved_chunk": "\t{\n\t\treturn Inventory.search().withName(name).first().flatMap(item ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItem(int id, String... actions)\n\t{", "score": 0.9245378375053406 } ]
java
BankInventory.search().indexIs(index).first().flatMap(item -> {
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\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tNPCPackets.queueNPCAction(npc, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean interactIndex(int index, String... actions)\n\t{\n\t\treturn NPCs.search().indexIs(index).first().flatMap(npc ->\n\t\t{", "score": 0.9103167057037354 }, { "filename": "src/main/java/com/utils/InteractionApi/NPCInteraction.java", "retrieved_chunk": "\t\treturn NPCs.search().withId(id).first().flatMap(npc ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tNPCPackets.queueNPCAction(npc, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean interact(Predicate<? super NPC> predicate, String... actions)\n\t{\n\t\treturn NPCs.search().filter(predicate).first().flatMap(npc ->", "score": 0.9035360813140869 }, { "filename": "src/main/java/com/utils/InteractionApi/InventoryInteraction.java", "retrieved_chunk": "\t\treturn Inventory.search().withId(id).first().flatMap(item ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItem(Predicate<? super Widget> predicate, String... actions)\n\t{\n\t\treturn Inventory.search().filter(predicate).first().flatMap(item ->", "score": 0.8932099342346191 }, { "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": 0.890785813331604 }, { "filename": "src/main/java/com/utils/InteractionApi/NPCInteraction.java", "retrieved_chunk": "\t{\n\t\treturn NPCs.search().withName(name).first().flatMap(npc ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tNPCPackets.queueNPCAction(npc, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean interact(int id, String... actions)\n\t{", "score": 0.8884341716766357 } ]
java
Players.search().filter(predicate).first().flatMap(Player -> {
package com.utils.InteractionApi; import com.utils.HypsApiPlugin.NPCs; import com.utils.Packets.MousePackets; import com.utils.Packets.NPCPackets; import net.runelite.api.NPC; import java.util.Optional; import java.util.function.Predicate; public class NPCInteraction { public static boolean interact(String name, String... actions) { return NPCs.search().withName(name).first().flatMap(npc -> { MousePackets.queueClickPacket(); NPCPackets.queueNPCAction(npc, actions); return Optional.of(true); }).orElse(false); } public static boolean interact(int id, String... actions) { return NPCs.search().withId(id).first().flatMap(npc -> { MousePackets.queueClickPacket(); NPCPackets.queueNPCAction(npc, actions); return Optional.of(true); }).orElse(false); } public static boolean interact(Predicate<? super NPC> predicate, String... actions) { return
NPCs.search().filter(predicate).first().flatMap(npc -> {
MousePackets.queueClickPacket(); NPCPackets.queueNPCAction(npc, actions); return Optional.of(true); }).orElse(false); } public static boolean interactIndex(int index, String... actions) { return NPCs.search().indexIs(index).first().flatMap(npc -> { MousePackets.queueClickPacket(); NPCPackets.queueNPCAction(npc, actions); return Optional.of(true); }).orElse(false); } public static boolean interact(NPC npc, String... actions) { if (npc == null) { return false; } MousePackets.queueClickPacket(); NPCPackets.queueNPCAction(npc, actions); return true; } }
src/main/java/com/utils/InteractionApi/NPCInteraction.java
Hypsster-hUtils-d265b4f
[ { "filename": "src/main/java/com/utils/InteractionApi/PlayerInteractionHelper.java", "retrieved_chunk": "\t{\n\t\treturn Players.search().withName(name).first().flatMap(Player ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tPlayerPackets.queuePlayerAction(Player, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean interact(Predicate<? super Player> predicate, String... actions)\n\t{", "score": 0.9015371799468994 }, { "filename": "src/main/java/com/utils/InteractionApi/InventoryInteraction.java", "retrieved_chunk": "\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItemIndex(int index, String... actions)\n\t{\n\t\treturn Inventory.search().indexIs(index).first().flatMap(item ->\n\t\t{", "score": 0.8512193560600281 }, { "filename": "src/main/java/com/utils/InteractionApi/InventoryInteraction.java", "retrieved_chunk": "\t\treturn Inventory.search().withId(id).first().flatMap(item ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItem(Predicate<? super Widget> predicate, String... actions)\n\t{\n\t\treturn Inventory.search().filter(predicate).first().flatMap(item ->", "score": 0.8487545251846313 }, { "filename": "src/main/java/com/utils/InteractionApi/InventoryInteraction.java", "retrieved_chunk": "\t{\n\t\treturn Inventory.search().withName(name).first().flatMap(item ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItem(int id, String... actions)\n\t{", "score": 0.8438100814819336 }, { "filename": "src/main/java/com/utils/InteractionApi/BankInteraction.java", "retrieved_chunk": "\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItemIndex(int index, String... actions)\n\t{\n\t\treturn Bank.search().indexIs(index).first().flatMap(item ->\n\t\t{", "score": 0.8411391377449036 } ]
java
NPCs.search().filter(predicate).first().flatMap(npc -> {
package com.utils; import com.utils.PacketType; import com.utils.Packets.BufferMethods; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import net.runelite.api.Client; import javax.inject.Inject; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @Slf4j public class PacketReflection { public static Class classWithgetPacketBufferNode = null; public static Method getPacketBufferNode = null; public static Class ClientPacket = null; public static Class isaacClass = null; public static Class PacketBufferNode = null; public static Field PACKETWRITER = null; public static Object isaac = null; public static Field mouseHandlerLastPressedTime = null; public static Field clientMouseLastLastPressedTimeMillis = null; @Inject Client clientInstance; public static Client client = null; @SneakyThrows public boolean LoadPackets() { try { client = clientInstance; classWithgetPacketBufferNode = clientInstance.getClass().getClassLoader().loadClass(ObfuscatedNames.classContainingGetPacketBufferNodeName); ClientPacket = clientInstance.getClass().getClassLoader().loadClass(ObfuscatedNames.clientPacketClassName); PACKETWRITER = clientInstance.getClass().getDeclaredField(ObfuscatedNames.packetWriterFieldName); PacketBufferNode = clientInstance.getClass().getClassLoader().loadClass(ObfuscatedNames.packetBufferNodeClassName); PACKETWRITER.setAccessible(true); Field isaac2 = PACKETWRITER.get(null).getClass().getDeclaredField(ObfuscatedNames.isaacCipherFieldName); isaac2.setAccessible(true); isaac = isaac2.get(PACKETWRITER.get(null)); isaac2.setAccessible(false); PACKETWRITER.setAccessible(false); isaacClass = isaac.getClass(); getPacketBufferNode = Arrays.stream(classWithgetPacketBufferNode.getDeclaredMethods()).filter(m -> m.getReturnType().equals(PacketBufferNode)).collect(Collectors.toList()).get(0); mouseHandlerLastPressedTime = clientInstance.getClass().getClassLoader().loadClass(ObfuscatedNames.MouseHandler_lastPressedTimeMillisClass).getDeclaredField(ObfuscatedNames.MouseHandler_lastPressedTimeMillisField); clientMouseLastLastPressedTimeMillis = clientInstance.getClass().getDeclaredField(ObfuscatedNames.clientMouseLastLastPressedTimeMillis); } catch (Exception e) { e.printStackTrace(); log.warn("Failed to load Packets Into Client"); return false; } return true; } @SneakyThrows public static void writeObject(String obfname, Object buffer, Object input) { switch (obfname) { case "du":
BufferMethods.du(buffer, (Integer) input);
break; case "bu": BufferMethods.bu(buffer, (Integer) input); break; case "dh": BufferMethods.dh(buffer, (Integer) input); break; case "bf": BufferMethods.bf(buffer, (Integer) input); break; case "dy": BufferMethods.dy(buffer, (Integer) input); break; case "el": BufferMethods.el(buffer, (Integer) input); break; case "dn": BufferMethods.dn(buffer, (Integer) input); break; case "dp": BufferMethods.dp(buffer, (Integer) input); break; case "eb": BufferMethods.eb(buffer, (Integer) input); break; case "ds": BufferMethods.ds(buffer, (Integer) input); break; case "ba": BufferMethods.ba(buffer, (Integer) input); break; } } @SneakyThrows public static void sendPacket(PacketDef def, Object... objects) { Object packetBufferNode = null; getPacketBufferNode.setAccessible(true); long garbageValue = Math.abs(Long.parseLong(ObfuscatedNames.getPacketBufferNodeGarbageValue)); if (garbageValue < 256) { packetBufferNode = getPacketBufferNode.invoke(null, fetchPacketField(def.name).get(ClientPacket), isaac, Byte.parseByte(ObfuscatedNames.getPacketBufferNodeGarbageValue)); } else if (garbageValue < 32768) { packetBufferNode = getPacketBufferNode.invoke(null, fetchPacketField(def.name).get(ClientPacket), isaac, Short.parseShort(ObfuscatedNames.getPacketBufferNodeGarbageValue)); } else if (garbageValue < Integer.MAX_VALUE) { packetBufferNode = getPacketBufferNode.invoke(null, fetchPacketField(def.name).get(ClientPacket), isaac, Integer.parseInt(ObfuscatedNames.getPacketBufferNodeGarbageValue)); } Object buffer = packetBufferNode.getClass().getDeclaredField(ObfuscatedNames.packetBufferFieldName).get(packetBufferNode); getPacketBufferNode.setAccessible(false); List<String> params = null; if (def.type == PacketType.RESUME_PAUSEBUTTON) { params = List.of("var0", "var1"); } if (def.type == PacketType.IF_BUTTON) { params = List.of("widgetId", "slot", "itemId"); } if (def.type == PacketType.OPLOC) { params = List.of("objectId", "worldPointX", "worldPointY", "ctrlDown"); } if (def.type == PacketType.OPNPC) { params = List.of("npcIndex", "ctrlDown"); } if (def.type == PacketType.OPPLAYER) { params = List.of("playerIndex", "ctrlDown"); } if (def.type == PacketType.OPOBJ) { params = List.of("objectId", "worldPointX", "worldPointY", "ctrlDown"); } if (def.type == PacketType.OPOBJT) { params = List.of("objectId", "worldPointX", "worldPointY", "slot", "itemId", "widgetId", "ctrlDown"); } if (def.type == PacketType.EVENT_MOUSE_CLICK) { params = List.of("mouseInfo", "mouseX", "mouseY"); } if (def.type == PacketType.MOVE_GAMECLICK) { params = List.of("worldPointX", "worldPointY", "ctrlDown", "5"); } if (def.type == PacketType.IF_BUTTONT) { params = List.of("sourceWidgetId", "sourceSlot", "sourceItemId", "destinationWidgetId", "destinationSlot", "destinationItemId"); } if (def.type == PacketType.OPLOCT) { params = List.of("objectId", "worldPointX", "worldPointY", "slot", "itemId", "widgetId", "ctrlDown"); } if (def.type == PacketType.OPPLAYERT) { params = List.of("playerIndex", "itemId", "slot", "widgetId", "ctrlDown"); } if (def.type == PacketType.OPNPCT) { params = List.of("npcIndex", "itemId", "slot", "widgetId", "ctrlDown"); } if (params != null) { for (Map.Entry<String, String> stringEntry : def.fields.entrySet()) { if (params.contains(stringEntry.getKey())) { writeObject(stringEntry.getValue(), buffer, objects[params.indexOf(stringEntry.getKey())]); } } PACKETWRITER.setAccessible(true); Method addNode = PACKETWRITER.get(null).getClass().getDeclaredMethod(ObfuscatedNames.addNodeMethodName,PACKETWRITER.get(null).getClass(),packetBufferNode.getClass(), int.class); addNode.setAccessible(true); addNode.invoke(null,PACKETWRITER.get(null),packetBufferNode, Integer.parseInt(ObfuscatedNames.addNodeGarbageValue)); addNode.setAccessible(false); PACKETWRITER.setAccessible(false); } } @SneakyThrows static Field fetchPacketField(String name) { return ClientPacket.getDeclaredField(name); } }
src/main/java/com/utils/PacketReflection.java
Hypsster-hUtils-d265b4f
[ { "filename": "src/main/java/com/utils/HypsApiPlugin/EquipmentItemWidget.java", "retrieved_chunk": "\t@Override\n\tpublic String getTargetVerb()\n\t{\n\t\treturn null;\n\t}\n\t@Override\n\tpublic void setTargetVerb(String targetVerb)\n\t{\n\t}\n\t@Override", "score": 0.7227931022644043 }, { "filename": "src/main/java/com/utils/HypsApiPlugin/HypsApiPlugin.java", "retrieved_chunk": "\t\t\treturn reachable;\n\t\t}\n\t\tpublic int getDistance()\n\t\t{\n\t\t\treturn distance;\n\t\t}\n\t}\n\t@SneakyThrows\n\tpublic static void stopPlugin(Plugin plugin)\n\t{", "score": 0.717913031578064 }, { "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": 0.7178248167037964 }, { "filename": "src/main/java/com/utils/HypsApiPlugin/HypsApiPlugin.java", "retrieved_chunk": "\t\t{\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\tpublic static boolean isQuickPrayerEnabled()\n\t{\n\t\treturn client.getVarbitValue(QUICK_PRAYER) == 1;\n\t}\n\t@SneakyThrows", "score": 0.7089359760284424 }, { "filename": "src/main/java/com/utils/HypsApiPlugin/EquipmentItemWidget.java", "retrieved_chunk": "\t{\n\t\treturn false;\n\t}\n\t@Override\n\tpublic void setNoScrollThrough(boolean noScrollThrough)\n\t{\n\t}\n\t@Override\n\tpublic void setVarTransmitTrigger(int... trigger)\n\t{", "score": 0.7065165042877197 } ]
java
BufferMethods.du(buffer, (Integer) input);
package com.utils.gauntletFlicker; import com.utils.HypsApiPlugin.HypsApiPlugin; import com.utils.HypsApiPlugin.QuickPrayer; import com.utils.InteractionApi.InteractionHelper; import com.utils.PacketUtilsPlugin; import com.utils.Packets.MousePackets; import com.utils.Packets.WidgetPackets; import lombok.extern.slf4j.Slf4j; import net.runelite.api.Client; import net.runelite.api.EquipmentInventorySlot; import net.runelite.api.GameState; import net.runelite.api.HeadIcon; import net.runelite.api.InventoryID; import net.runelite.api.Item; import net.runelite.api.ItemComposition; import net.runelite.api.NPC; import net.runelite.api.NpcID; import net.runelite.api.Skill; import net.runelite.api.events.AnimationChanged; import net.runelite.api.events.GameTick; import net.runelite.api.events.MenuOptionClicked; import net.runelite.api.widgets.Widget; import net.runelite.api.widgets.WidgetInfo; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.game.ItemManager; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDependency; import net.runelite.client.plugins.PluginDescriptor; import javax.inject.Inject; import java.util.Set; @PluginDescriptor( name = "Gauntlet Flicker and Switcher", description = "", tags = {"Hyps"} ) @PluginDependency(HypsApiPlugin.class) @PluginDependency(PacketUtilsPlugin.class) @Slf4j public class gauntletFlicker extends Plugin { @Inject Client client; @Inject ItemManager manager; String updatedWeapon = ""; boolean forceTab = false; Set<Integer> HUNLLEF_IDS = Set.of(NpcID.CORRUPTED_HUNLLEF, NpcID.CORRUPTED_HUNLLEF_9036, NpcID.CORRUPTED_HUNLLEF_9037, NpcID.CORRUPTED_HUNLLEF_9038, NpcID.CRYSTALLINE_HUNLLEF, NpcID.CRYSTALLINE_HUNLLEF_9022, NpcID.CRYSTALLINE_HUNLLEF_9023, NpcID.CRYSTALLINE_HUNLLEF_9024); boolean isRange = true; @Subscribe public void onGameTick(GameTick e) { if (client.getLocalPlayer().isDead() || client.getLocalPlayer().getHealthRatio() == 0) { forceTab = false; return; } if (client.getGameState() != GameState.LOGGED_IN) { forceTab = false; return; } Item weapon = null; try { weapon = client.getItemContainer(InventoryID.EQUIPMENT).getItem(EquipmentInventorySlot.WEAPON.getSlotIdx()); } catch (NullPointerException ex) { //todo } String name = ""; if (weapon != null) { ItemComposition itemComp = manager.getItemComposition(client.getItemContainer(InventoryID.EQUIPMENT).getItem(EquipmentInventorySlot.WEAPON.getSlotIdx()).getId()); name = itemComp.getName() == null ? "" : itemComp.getName(); } NPC hunllef = client.getNpcs().stream().filter(x -> HUNLLEF_IDS.contains(x.getId())).findFirst().orElse(null); if (client.getVarbitValue(9177) != 1) { forceTab = false; return; } if (client.getVarbitValue(9178) != 1) { isRange = true; forceTab = false; updatedWeapon = ""; return; } if (forceTab) { client.runScript(915, 3); forceTab = false; } if (client.getWidget(5046276) == null) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(client.getWidget(WidgetInfo.MINIMAP_QUICK_PRAYER_ORB), "Setup"); forceTab = true; } if (isRange && !HypsApiPlugin.isQuickPrayerActive(QuickPrayer.PROTECT_FROM_MISSILES)) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetActionPacket(1, 5046276, -1, 13); //quickPrayer range } else if (!isRange && !HypsApiPlugin.isQuickPrayerActive(QuickPrayer.PROTECT_FROM_MAGIC)) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetActionPacket(1, 5046276, -1, 12); //quickPrayer magic } if (hunllef != null) { if (HypsApiPlugin.getHeadIcon(hunllef) == HeadIcon.MAGIC && (!name.contains("bow") && !name.contains("halberd"))) {
Widget bow = HypsApiPlugin.getItem("*bow*");
Widget halberd = HypsApiPlugin.getItem("*halberd*"); if (bow != null) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(bow, "Wield"); updatedWeapon = "bow"; } else if (halberd != null) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(halberd, "Wield"); updatedWeapon = "halberd"; } } if (HypsApiPlugin.getHeadIcon(hunllef) == HeadIcon.RANGED && (!name.contains("staff") && !name.contains("halberd"))) { Widget staff = HypsApiPlugin.getItem("*staff*"); Widget halberd = HypsApiPlugin.getItem("*halberd*"); if (staff != null) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(staff, "Wield"); updatedWeapon = "staff"; } else if (halberd != null) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(halberd, "Wield"); updatedWeapon = "halberd"; } } if (HypsApiPlugin.getHeadIcon(hunllef) == HeadIcon.MELEE && (!name.contains("staff") && !name.contains("bow"))) { Widget staff = HypsApiPlugin.getItem("*staff*"); Widget bow = HypsApiPlugin.getItem("*bow*"); if (staff != null) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(staff, "Wield"); updatedWeapon = "staff"; } else if (bow != null) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetAction(bow, "Wield"); updatedWeapon = "bow"; } } String weaponTesting = updatedWeapon.isEmpty() ? name : updatedWeapon; if (weaponTesting.contains("bow")) { if (rigourUnlocked() && !HypsApiPlugin.isQuickPrayerActive(QuickPrayer.RIGOUR)) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetActionPacket(1, 5046276, -1, 24); //quickPrayer rigour } else if (!rigourUnlocked() && !HypsApiPlugin.isQuickPrayerActive(QuickPrayer.EAGLE_EYE)) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetActionPacket(1, 5046276, -1, 22); //quickPrayer eagle eye } } else if (weaponTesting.contains("staff")) { if (auguryUnlucked() && !HypsApiPlugin.isQuickPrayerActive(QuickPrayer.AUGURY)) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetActionPacket(1, 5046276, -1, 27); //quickPrayer augury } else if (!auguryUnlucked() && !HypsApiPlugin.isQuickPrayerActive(QuickPrayer.MYSTIC_MIGHT)) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetActionPacket(1, 5046276, -1, 23); //quickPrayer mystic might } } else if (weaponTesting.contains("halberd")) { if (pietyUnlocked() && !HypsApiPlugin.isQuickPrayerActive(QuickPrayer.PIETY)) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetActionPacket(1, 5046276, -1, 26); } else if (!pietyUnlocked() && !HypsApiPlugin.isQuickPrayerActive(QuickPrayer.ULTIMATE_STRENGTH)) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetActionPacket(1, 5046276, -1, 10); if (!HypsApiPlugin.isQuickPrayerActive(QuickPrayer.INCREDIBLE_REFLEXES)) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetActionPacket(1, 5046276, -1, 11); } }else if(!pietyUnlocked() && !HypsApiPlugin.isQuickPrayerActive(QuickPrayer.STEEL_SKIN)) { MousePackets.queueClickPacket(); WidgetPackets.queueWidgetActionPacket(1, 5046276, -1, QuickPrayer.STEEL_SKIN.getIndex()); } } } if (HypsApiPlugin.isQuickPrayerEnabled()) { InteractionHelper.togglePrayer(); } InteractionHelper.togglePrayer(); } public boolean rigourUnlocked() { return !(client.getVarbitValue(5451) == 0)&&client.getRealSkillLevel(Skill.PRAYER)>=74&&client.getRealSkillLevel(Skill.DEFENCE)>=70; } public boolean pietyUnlocked() { return client.getVarbitValue(3909) == 8&&client.getRealSkillLevel(Skill.PRAYER)>=70&&client.getRealSkillLevel(Skill.DEFENCE)>=70; } public boolean auguryUnlucked() { return !(client.getVarbitValue(5452) == 0)&&client.getRealSkillLevel(Skill.PRAYER)>=77&&client.getRealSkillLevel(Skill.DEFENCE)>=70; } @Subscribe public void onMenuOptionClicked(MenuOptionClicked event) { if (event.getMenuOption().toLowerCase().contains("pass")) { isRange = true; } } @Override protected void startUp() { isRange = true; forceTab = false; updatedWeapon = ""; } @Subscribe public void onAnimationChanged(AnimationChanged e) { if (e.getActor() == null) { return; } if (!(e.getActor() instanceof NPC)) { return; } NPC npc = (NPC) e.getActor(); if (!HUNLLEF_IDS.contains(npc.getId())) { return; } if (e.getActor().getAnimation() == 8754) { isRange = false; } if (e.getActor().getAnimation() == 8755) { isRange = true; } } private boolean isHunllefVarbitSet() { return client.getVarbitValue(9177) == 1; } }
src/main/java/com/utils/gauntletFlicker/gauntletFlicker.java
Hypsster-hUtils-d265b4f
[ { "filename": "src/main/java/com/utils/AutoTele/AutoTele.java", "retrieved_chunk": "\t\t\t\t}\n\t\t\t\tif (rowEquipment != null && !teleported)\n\t\t\t\t{\n\t\t\t\t\tteleported = true;\n\t\t\t\t\tMousePackets.queueClickPacket();\n\t\t\t\t\tWidgetPackets.queueWidgetActionPacket(3, 25362456, -1, -1);\n\t\t\t\t}\n\t\t\t\tif (teleported)\n\t\t\t\t{\n\t\t\t\t\tteleportedFromSkulledPlayer = HypsApiPlugin.getSkullIcon(player) != null;", "score": 0.7682740092277527 }, { "filename": "src/main/java/com/utils/InteractionApi/InteractionHelper.java", "retrieved_chunk": "\t}\n\tpublic static void togglePrayer()\n\t{\n\t\tMousePackets.queueClickPacket(0, 0);\n\t\tWidgetPackets.queueWidgetActionPacket(1, quickPrayerWidgetID, -1, -1);\n\t}\n}", "score": 0.7574138641357422 }, { "filename": "src/main/java/com/utils/AutoTele/AutoTele.java", "retrieved_chunk": "\t\t\t\t\tteleported = true;\n\t\t\t\t\tInventoryInteraction.useItem(widget.get(), \"Commune\");\n\t\t\t\t}\n\t\t\t\tOptional<Widget> row = Inventory.search().nameContains(\"Ring of wealth (\").first();\n\t\t\t\tif (row.isPresent() && !teleported)\n\t\t\t\t{\n\t\t\t\t\tteleported = true;\n\t\t\t\t\tInventoryInteraction.useItem(row.get(), \"Rub\");\n\t\t\t\t\tMousePackets.queueClickPacket();\n\t\t\t\t\tWidgetPackets.queueResumePause(14352385, 2);", "score": 0.7277258634567261 }, { "filename": "src/main/java/com/utils/InteractionApi/InteractionHelper.java", "retrieved_chunk": "\t\tMousePackets.queueClickPacket();\n\t\tWidgetPackets.queueWidgetActionPacket(1, packedWidgID, -1, -1);\n\t}\n\tpublic static void toggleNormalPrayers(List<Integer> packedWidgIDs)\n\t{\n\t\tfor (Integer packedWidgID : packedWidgIDs)\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetActionPacket(1, packedWidgID, -1, -1);\n\t\t}", "score": 0.7177678346633911 }, { "filename": "src/main/java/com/utils/SpecDamage/specDamage.java", "retrieved_chunk": "\t\t}\n\t}\n\tprivate void drop()\n\t{\n\t\tOptional<Widget> fish = Inventory.search().idInList(List.of(371, 13441)).first();\n\t\tif (fish.isPresent())\n\t\t{\n\t\t\tWidgetPackets.queueWidgetAction(fish.get(), \"Eat\");\n\t\t}\n\t}", "score": 0.7146245241165161 } ]
java
Widget bow = HypsApiPlugin.getItem("*bow*");
package com.ialdrich23xx.libasynwebhook.api.discord.body; import com.ialdrich23xx.libasynwebhook.api.Loader; import com.ialdrich23xx.libasynwebhook.api.discord.body.embed.EmbedManager; import com.ialdrich23xx.libasynwebhook.api.discord.body.embed.base.Structure; import java.util.*; public class Base extends Structure { private String content = null; private String username = null; private String avatar = null; private Boolean textToSpeech = false; private String threadName = null; private List<EmbedManager> embeds = new ArrayList<>(); public Base() {} public static Base make() { return new Base(); } public Base setContent(String content) { this.content = content; return this; } public String getContent() { return this.content; } public Base setUsername(String username) { this.username = username; return this; } public String getUsername() { return this.username; } public Base setAvatar(String avatar) { this.avatar = avatar; return this; } public String getAvatar() { return this.avatar; } public Base setTextToSpeech(Boolean textToSpeech) { this.textToSpeech = textToSpeech; return this; } public Boolean isTextToSpeech() { return this.textToSpeech; } public Base addEmbed(EmbedManager embed) { this.embeds.add(embed); return this; } public Base resetEmbeds() { this.embeds = new ArrayList<>(); return this; } public List<EmbedManager> getEmbeds() { return this.embeds; } public Base setForumTitle(String forumTitle) { this.threadName = forumTitle; return this; } public String getForumTitle() { return this.threadName; } public Boolean isForum() { return this.threadName != null; } @Override public Boolean build() { if (this.getAvatar() != null && !Loader.getInstance().isValidUrl(this.getAvatar())) return false; if (this.getContent() == null && this.getEmbeds().isEmpty()) return false; if (this.getContent() != null && this.getContent().length() == 0) return false; return true; } @Override public Map<String, Object> toArray() { Map<String, Object> result = new HashMap<>(); result.put("tts", this.isTextToSpeech()); if (this.getContent() != null) result.put("content", this.getContent()); if (this.getUsername() != null) result.put("username", this.getUsername()); if (this.getAvatar() != null) result.put("avatar_url", this.getAvatar()); List<Object> embedList = new ArrayList<>(); this.getEmbeds().forEach(embed -> embedList.add(Loader.getInstance().formatToJson
(embed.toArray().entrySet())));
if (!embedList.isEmpty()) { result.put("embeds", embedList.toArray()); } if (this.isForum()) result.put("thread_name", this.getForumTitle()); return result; } @Override public String toString() { return "Base(content=" + this.getContent() + ",username=" + this.getUsername() + ",avatar=" + this.getAvatar() + ";embeds=Array(" + this.getEmbeds().size() + ")"; } public String toJson() { return Loader.getInstance().formatToJson(this.toArray().entrySet()); } private String quote(String string) { return "\"" + string + "\""; } }
libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/Base.java
iAldrich23xX-libasynWebhook-52a1773
[ { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/EmbedManager.java", "retrieved_chunk": " if (this.getAuthor() != null) result.put(\"author\", this.getAuthor().toArray());\n if (this.getFooter() != null) result.put(\"footer\", this.getFooter().toArray());\n if (this.getThumbnail() != null) result.put(\"thumbnail\", this.getThumbnail().toArray());\n if (this.getImage() != null) result.put(\"image\", this.getImage().toArray());\n if (this.getTimestamp() != null) result.put(\"timestamp\", this.getTimestamp().getFormat().format(this.getTimestamp().getDate()));\n List<Object> fieldList = new ArrayList<>();\n this.getFields().forEach(field -> fieldList.add(Loader.getInstance().formatToJson(field.toArray().entrySet())));\n if (!fieldList.isEmpty()) {\n result.put(\"fields\", fieldList.toArray());\n }", "score": 0.8640085458755493 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/components/Author.java", "retrieved_chunk": " @Override\n public Map<String, Object> toArray() {\n Map<String, Object> result = this.nameToArray();\n if (!this.getUrl().isEmpty()) result.putAll(this.urlToArray());\n if (!this.getIcon().isEmpty()) result.putAll(this.iconToArray());\n return result;\n }\n @Override\n public String toString() {\n return \"Author(\" + this.nameToString() + \",\" + this.urlToString() + \",\" + this.iconToString() + \")\";", "score": 0.8327596187591553 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/EmbedManager.java", "retrieved_chunk": " @Override\n public Boolean build() {\n return !this.getTitle().isEmpty() && !this.getDescription().isEmpty() || !this.getFields().isEmpty();\n }\n @Override\n public Map<String, Object> toArray() {\n Map<String, Object> result = new HashMap<>();\n result.put(\"title\", this.getTitle());\n result.put(\"description\", this.getDescription());\n result.put(\"color\", this.getColor());", "score": 0.831727921962738 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/components/Field.java", "retrieved_chunk": " @Override\n public Map<String, Object> toArray() {\n Map<String, Object> result = this.nameToArray();\n result.put(\"value\", this.getName());\n result.put(\"inline\", this.getInline());\n return result;\n }\n @Override\n public String toString() {\n return \"Field(\" + this.nameToString() + \",value=\" + this.getValue() + \",inline=\" + this.getInline().toString() + \")\";", "score": 0.7768629193305969 }, { "filename": "libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/components/Footer.java", "retrieved_chunk": " Map<String, Object> result = new HashMap<>();\n result.put(\"text\", this.getText());\n if (!this.getIcon().isEmpty()) result.putAll(this.iconToArray());\n return result;\n }\n @Override\n public String toString() {\n return \"Footer(text=\" + this.getText() + \",\" + this.iconToString() + \")\";\n }\n}", "score": 0.7766748070716858 } ]
java
(embed.toArray().entrySet())));
package org.easycontactforms.core.services; import org.easycontactforms.core.dtos.ContactFormDto; import org.easycontactforms.core.models.ContactForm; import org.easycontactforms.core.repositories.ContactFormRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; /** * Service to handle processing of contact form input */ @Slf4j @Service public class ContactFormService { private final ContactFormRepository repository; private final MailingService mailingService; @Value("${redirect.mode}") private String mode; @Autowired public ContactFormService(ContactFormRepository repository, MailingService mailingService){ this.repository = repository; this.mailingService = mailingService; } /** * handles initial request * @param contactFormDto * @return */ public ContactForm saveContactForm(ContactFormDto contactFormDto){ ContactForm contactForm = repository.save(ContactForm.fromContactFormDto(contactFormDto)); if(mode.equalsIgnoreCase("email")){ log.info("Redirecting Contact Form to email"); MailSendThread thread = new MailSendThread(this, mailingService, contactForm); thread.start(); } log.info("Saved Contact Form"); return contactForm; } /** * updates single instance in database * @param contactForm changed object * @return result from database */ public ContactForm updateContactForm(ContactForm contactForm){ repository.save(contactForm); return contactForm; } public List<ContactForm> getContactForms(boolean onlyNotSendEmails){ if(!onlyNotSendEmails){ return repository.findAll(); }else {
return repository.findByEmailSent(false);
} } }
src/main/java/org/easycontactforms/core/services/ContactFormService.java
Jan222333444-EasyContactForms-a2cf723
[ { "filename": "src/main/java/org/easycontactforms/core/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": 0.8459080457687378 }, { "filename": "src/main/java/org/easycontactforms/core/controller/HTMLContactFormController.java", "retrieved_chunk": " }\n if (contactFormDto.getEmail() == null || contactFormDto.getMessage() == null) {\n throw new RuntimeException();\n }\n // processes contact form\n ContactForm contactForm = service.saveContactForm(contactFormDto);\n log.debug(\"[POST] processed data excluding plugins\");\n // Executing plugin hook contactFormProcessed\n for (String key : PluginStore.instance.plugins.keySet()) {\n PluginStore.instance.plugins.get(key).contactFormProcessed(new org.easycontactforms.api.models.ContactForm(contactForm.getId(), contactFormDto.getEmail(), contactFormDto.getName(), contactFormDto.getSubject(), contactFormDto.getMessage()));", "score": 0.7970220446586609 }, { "filename": "src/main/java/org/easycontactforms/core/services/MailSendThread.java", "retrieved_chunk": " ApplicationState.smtpAvailable = false;\n e.printStackTrace();\n return;\n }\n if(!ApplicationState.smtpAvailable && resendPolicy){\n ApplicationState.smtpAvailable = true;\n mailingService.resendMails(true, contactFormService);\n }\n contactForm.setEmailSent(true);\n contactFormService.updateContactForm(contactForm);", "score": 0.7950979471206665 }, { "filename": "src/main/java/org/easycontactforms/core/controller/ContactFormController.java", "retrieved_chunk": " * @return status and in db saved object\n */\n public ResponseEntity handleRequest(ContactFormDto contactFormDto){\n log.debug(\"[POST] Saving Contact Form\");\n for(String key : PluginStore.instance.plugins.keySet()){\n PluginStore.instance.plugins.get(key).beforeContactFormProcessing(new org.easycontactforms.api.models.ContactFormDto(contactFormDto.getEmail(), contactFormDto.getName(), contactFormDto.getSubject(), contactFormDto.getMessage()));\n }\n if (contactFormDto.getEmail() == null || contactFormDto.getMessage() == null){\n return ResponseEntity.status(400).body(new ErrorDto(400, \"Missing required attributes in request body\"));\n }", "score": 0.7895322442054749 }, { "filename": "src/main/java/org/easycontactforms/core/services/MailingService.java", "retrieved_chunk": " String[] msg = contactForm.getMessage().split(\"\\n\");\n Context context = new Context();\n context.setVariable(\"name\", contactForm.getName() == null ? \"\" : contactForm.getName());\n context.setVariable(\"subject\", contactForm.getSubject() == null ? \"\" : contactForm.getSubject());\n context.setVariable(\"message\", msg);\n context.setVariable(\"email\", contactForm.getEmail());\n context.setVariable(\"id\", contactForm.getId());\n return templateEngine.process(\"mail-template\", context);\n }\n public void resendMails(boolean resendOnlyNotSendMails, ContactFormService contactFormService){", "score": 0.781288743019104 } ]
java
return repository.findByEmailSent(false);
package org.easycontactforms.core; import jakarta.annotation.PreDestroy; import lombok.extern.slf4j.Slf4j; import org.easycontactforms.api.PluginFactory; import org.easycontactforms.core.commandhandler.CommandHandlerThread; import org.easycontactforms.core.pluginloader.PluginLoader; import org.easycontactforms.core.pluginloader.PluginStore; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.scheduling.annotation.EnableScheduling; import java.io.File; import java.util.Map; /** * Main class of application * Handles startup and teardown of Plugins and application */ @Slf4j @SpringBootApplication @EnableScheduling public class EasyContactFormsApplication { public static void main(String[] args) { String pluginsPath = "plugins"; new FirstStartupChecker().checkDirectories(); loadPlugins(pluginsPath); //Starts all plugins for (String key : PluginStore.instance.plugins.keySet()) { PluginStore.instance.plugins.get(key).onStartup(); } //Starts Spring Boot server ApplicationContext context = SpringApplication.run(EasyContactFormsApplication.class, args); //Executes on load hook for (String key : PluginStore.instance.plugins.keySet()) { PluginStore.instance.plugins.get(key).onLoad(); } CommandHandlerThread handlerThread = new CommandHandlerThread(context, System.in, args); handlerThread.start(); } public static void loadPlugins(String pluginsPath) { PluginLoader pluginLoader = new PluginLoader(new File(pluginsPath)); pluginLoader.loadPlugins(); Map<String, PluginFactory> factories
= pluginLoader.getPluginFactories();
for (String key : factories.keySet()) { PluginStore.instance.plugins.put(key, factories.get(key).build()); } } @PreDestroy public static void teardown() { for (String key : PluginStore.instance.plugins.keySet()) { PluginStore.instance.plugins.get(key).onTeardown(); } } }
src/main/java/org/easycontactforms/core/EasyContactFormsApplication.java
Jan222333444-EasyContactForms-a2cf723
[ { "filename": "src/main/java/org/easycontactforms/core/commandhandler/CommandHandler.java", "retrieved_chunk": " //Executes on load hook\n for (String key : PluginStore.instance.plugins.keySet()) {\n PluginStore.instance.plugins.get(key).onLoad();\n }\n }\n /**\n * logic for shutdown command\n * @param args command line arguments\n */\n private void shutdown(String... args){", "score": 0.834887683391571 }, { "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": 0.8332129120826721 }, { "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": 0.8153516054153442 }, { "filename": "src/main/java/org/easycontactforms/core/pluginloader/PluginLoader.java", "retrieved_chunk": " }\n private void installPlugin(final Plugin plugin) {\n log.info(\"Installing plugin: \" + plugin.getClass().getName());\n for (PluginFactory f : plugin.getPluginFactories()) {\n fooFactoryMap.put(f.getName(), f);\n }\n }\n private URLClassLoader createPluginClassLoader(File dir) {\n final URL[] urls = Arrays.stream(Optional.ofNullable(dir.listFiles()).orElse(new File[]{}))\n .sorted()", "score": 0.7981196045875549 }, { "filename": "src/main/java/org/easycontactforms/core/pluginloader/PluginLoader.java", "retrieved_chunk": " final URLClassLoader pluginClassLoader = createPluginClassLoader(pluginDir);\n final ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();\n try {\n Thread.currentThread().setContextClassLoader(pluginClassLoader);\n for (Plugin plugin : ServiceLoader.load(Plugin.class, pluginClassLoader)) {\n installPlugin(plugin);\n }\n } finally {\n Thread.currentThread().setContextClassLoader(currentClassLoader);\n }", "score": 0.7972617745399475 } ]
java
= pluginLoader.getPluginFactories();
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/main/java/org/easycontactforms/core/commandhandler/CommandHandler.java", "retrieved_chunk": " this.plugins = this.priorities();\n }\n /**\n * gets executed if new line is entered\n * @param command base command (everything before first white space)\n * @param args all command line arguments (including command)\n */\n public boolean onCommand(String command, String... args) {\n boolean internalCommand = internalCommands(command, args);\n boolean external = false;", "score": 0.8092021942138672 }, { "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": 0.7883301973342896 }, { "filename": "src/main/java/org/easycontactforms/core/commandhandler/CommandHandler.java", "retrieved_chunk": " return PluginStore.instance.plugins.values().stream().sorted(Comparator.comparingInt(plugin -> plugin.priority.value)).collect(Collectors.toList());\n }\n /**\n * executes plugin commands\n * @param command executed command\n * @param args command line arguments\n */\n private boolean onCommandPlugins(String command, String... args) {\n for (Plugin plugin : plugins) {\n try {", "score": 0.7847453951835632 }, { "filename": "src/main/java/org/easycontactforms/core/commandhandler/CommandHandler.java", "retrieved_chunk": " * JVM arguments for startup of service\n */\n private final String[] baseArgs;\n /**\n * List of all plugins ordered by priority\n */\n private List<Plugin> plugins;\n public CommandHandler(ApplicationContext context, String[] args){\n this.context = context;\n this.baseArgs = args;", "score": 0.7656799554824829 }, { "filename": "src/test/java/org/easycontactforms/unittests/testpluginclasses/Testplugin1.java", "retrieved_chunk": " }\n @Override\n public boolean onCommand(String command, String... args) {\n return command.equalsIgnoreCase(\"plugintestcommand\");\n }\n}", "score": 0.7653664946556091 } ]
java
handler.onCommand(command, arguments);
package org.easycontactforms.core.commandhandler; import lombok.extern.slf4j.Slf4j; import org.easycontactforms.api.Plugin; import org.easycontactforms.core.EasyContactFormsApplication; import org.easycontactforms.core.pluginloader.PluginStore; import org.springframework.boot.SpringApplication; import org.springframework.context.ApplicationContext; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; /** * Class for handling command line inputs */ @Slf4j public class CommandHandler { /** * Currently used Spring Application Context */ private ApplicationContext context; /** * JVM arguments for startup of service */ private final String[] baseArgs; /** * List of all plugins ordered by priority */ private List<Plugin> plugins; public CommandHandler(ApplicationContext context, String[] args){ this.context = context; this.baseArgs = args; this.plugins = this.priorities(); } /** * gets executed if new line is entered * @param command base command (everything before first white space) * @param args all command line arguments (including command) */ public boolean onCommand(String command, String... args) { boolean internalCommand = internalCommands(command, args); boolean external = false; if(!internalCommand){ external = onCommandPlugins(command, args); } return internalCommand || external; } /** * Sorts plugins by priority * @return list of all plugins loaded sorted by priority from Highest to Lowest */ private List<Plugin> priorities(){ return PluginStore.instance.plugins.values().stream().sorted(Comparator.comparingInt(plugin -> plugin.priority.value)).collect(Collectors.toList()); } /** * executes plugin commands * @param command executed command * @param args command line arguments */ private boolean onCommandPlugins(String command, String... args) { for (Plugin plugin : plugins) { try { boolean handled = plugin.onCommand(command, args); if (handled) { return true; } } catch (AbstractMethodError error) { log.warn("Plugin does not implement onCommand Method"); log.warn(error.getMessage()); } } return false; } /** * executes basic internal commands from command line * @param command executed command * @param args command line arguments * @return true if command is internal, else false */ private boolean internalCommands(String command, String... args) { if (command.equalsIgnoreCase("stop")) { System.exit(0); return true; } else if (command.equalsIgnoreCase("reloadplugins")) { reloadPlugins(); return true; } else if (command.equalsIgnoreCase("reloadspring")) { SpringApplication.exit(context); this.context = SpringApplication.run(EasyContactFormsApplication.class, this.baseArgs); return true; } else if (command.equalsIgnoreCase("reload")) { SpringApplication.exit(context); this.context = SpringApplication.run(EasyContactFormsApplication.class, this.baseArgs); reloadPlugins(); return true; } else if (command.equalsIgnoreCase("shutdown")) { shutdown(args); return true; } return false; } /** * reloads all plugins from source */ private void reloadPlugins(){ String pluginsPath = "plugins";
EasyContactFormsApplication.loadPlugins(pluginsPath);
plugins = priorities(); //Starts all plugins for (String key : PluginStore.instance.plugins.keySet()) { PluginStore.instance.plugins.get(key).onStartup(); } //Executes on load hook for (String key : PluginStore.instance.plugins.keySet()) { PluginStore.instance.plugins.get(key).onLoad(); } } /** * logic for shutdown command * @param args command line arguments */ private void shutdown(String... args){ // standard execution if(args.length == 1){ try { TimeUnit.SECONDS.sleep(10); } catch (InterruptedException e) { throw new RuntimeException(e); } System.exit(0); return; } // initiates shutdown immediately (like stop command) if(args[1].equalsIgnoreCase("now")){ System.exit(0); return; } // initiates shutdown after given delay in seconds try{ int delay = Integer.parseInt(args[1]); TimeUnit.SECONDS.sleep(delay); System.exit(0); } catch (NumberFormatException exception) { log.error("Cannot parse input. Argument 1 is not of type integer: {}", args[1]); } catch (InterruptedException e) { log.error("Something went wrong on Shutdown"); } } /** * * @return List of Plugins ordered from highest to lowest priority */ public List<Plugin> getPluginsByPriority(){ return plugins; } }
src/main/java/org/easycontactforms/core/commandhandler/CommandHandler.java
Jan222333444-EasyContactForms-a2cf723
[ { "filename": "src/main/java/org/easycontactforms/core/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": 0.8248087167739868 }, { "filename": "src/main/java/org/easycontactforms/core/EasyContactFormsApplication.java", "retrieved_chunk": " ApplicationContext context = SpringApplication.run(EasyContactFormsApplication.class, args);\n //Executes on load hook\n for (String key : PluginStore.instance.plugins.keySet()) {\n PluginStore.instance.plugins.get(key).onLoad();\n }\n CommandHandlerThread handlerThread = new CommandHandlerThread(context, System.in, args);\n handlerThread.start();\n }\n public static void loadPlugins(String pluginsPath) {\n PluginLoader pluginLoader = new PluginLoader(new File(pluginsPath));", "score": 0.8198966979980469 }, { "filename": "src/main/java/org/easycontactforms/core/EasyContactFormsApplication.java", "retrieved_chunk": "public class EasyContactFormsApplication {\n public static void main(String[] args) {\n String pluginsPath = \"plugins\";\n new FirstStartupChecker().checkDirectories();\n loadPlugins(pluginsPath);\n //Starts all plugins\n for (String key : PluginStore.instance.plugins.keySet()) {\n PluginStore.instance.plugins.get(key).onStartup();\n }\n //Starts Spring Boot server", "score": 0.811857283115387 }, { "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": 0.8048761487007141 }, { "filename": "TestPlugin/src/main/java/org/easycontactforms/testplugin/TestPlugin.java", "retrieved_chunk": " factories.add(new TestPluginFactory());\n return factories;\n }\n @Override\n public boolean onStartup() {\n System.out.println(\"Im started\");\n return true;\n }\n @Override\n public boolean onLoad() {", "score": 0.8047893047332764 } ]
java
EasyContactFormsApplication.loadPlugins(pluginsPath);
package com.utils.AutoTele; import com.utils.HypsApiPlugin.HypsApiPlugin; import com.utils.HypsApiPlugin.Inventory; import com.utils.InteractionApi.InventoryInteraction; import com.utils.PacketUtilsPlugin; import com.utils.Packets.MousePackets; import com.utils.Packets.WidgetPackets; import com.google.inject.Inject; import com.google.inject.Provides; import net.runelite.api.ChatMessageType; import net.runelite.api.Client; import net.runelite.api.EquipmentInventorySlot; import net.runelite.api.InventoryID; import net.runelite.api.Item; import net.runelite.api.ItemID; import net.runelite.api.Player; import net.runelite.api.events.AnimationChanged; import net.runelite.api.events.GameTick; import net.runelite.api.widgets.Widget; import net.runelite.api.widgets.WidgetInfo; import net.runelite.client.config.ConfigManager; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.game.ItemManager; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDependency; import net.runelite.client.plugins.PluginDescriptor; import java.util.Optional; import java.util.Set; @PluginDescriptor( name = "AutoTele", enabledByDefault = false, tags = {"Hyps"} ) @PluginDependency(HypsApiPlugin.class) @PluginDependency(PacketUtilsPlugin.class) public class AutoTele extends Plugin { @Inject Client client; int timeout; static final int RING_OF_WEALTH = 714; static final int SEED_POD = 4544; int previousLevel = -1; public static boolean teleportedFromSkulledPlayer = false; @Inject ItemManager itemManager; @Inject AutoTeleConfig config; static final Set<Integer> RING_OF_WEALTH_ITEM_IDS = Set.of(ItemID.RING_OF_WEALTH_1, ItemID.RING_OF_WEALTH_2, ItemID.RING_OF_WEALTH_3, ItemID.RING_OF_WEALTH_4, ItemID.RING_OF_WEALTH_5, ItemID.RING_OF_WEALTH_I1, ItemID.RING_OF_WEALTH_I2, ItemID.RING_OF_WEALTH_I3, ItemID.RING_OF_WEALTH_I4, ItemID.RING_OF_WEALTH_I5); @Provides public AutoTeleConfig getConfig(ConfigManager configManager) { return configManager.getConfig(AutoTeleConfig.class); } @Subscribe public void onGameTick(GameTick event) { if (timeout > 0) { timeout--; return; } Widget wildernessLevel = client.getWidget(WidgetInfo.PVP_WILDERNESS_LEVEL); int level = -1; if (wildernessLevel != null && !wildernessLevel.getText().equals("")) { try { if (wildernessLevel.getText().contains("<br>")) { String text = wildernessLevel.getText().split("<br>")[0]; level = Integer.parseInt(text.replaceAll("Level: ", "")); } else { level = Integer.parseInt(wildernessLevel.getText().replaceAll("Level: ", "")); } } catch (NumberFormatException ex) { //ignore } } if (previousLevel != -1 && level == -1) { previousLevel = -1; } Item rowEquipment = null; if (client.getItemContainer(InventoryID.EQUIPMENT) != null) { rowEquipment = client.getItemContainer(InventoryID.EQUIPMENT).getItem(EquipmentInventorySlot.RING.getSlotIdx()); } if ((rowEquipment != null && !RING_OF_WEALTH_ITEM_IDS.contains(rowEquipment.getId()))) { rowEquipment = null; } if (level > -1) { if (previousLevel == -1) { previousLevel = level; Optional<Widget
> royal_seed_pod = Inventory.search().withId(ItemID.ROYAL_SEED_POD).first();
Optional<Widget> ring_of_wealth = Inventory.search().nameContains("Ring of wealth (").first(); if (config.alert()) { if (royal_seed_pod.isPresent() || ring_of_wealth.isPresent() || (rowEquipment != null && RING_OF_WEALTH_ITEM_IDS.contains(rowEquipment.getId()))) { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "<col=7cfc00>Entering wilderness with a teleport item." + " " + "AutoTele is ready to save you", null); } else { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "<col=ff0000> Entering wilderness without a " + "supported " + "teleport possible mistake?", null); } } } } for (Player player : client.getPlayers()) { int lowRange = client.getLocalPlayer().getCombatLevel() - level; int highRange = client.getLocalPlayer().getCombatLevel() + level; if (player.equals(client.getLocalPlayer())) { continue; } if (player.getCombatLevel() >= lowRange && player.getCombatLevel() <= highRange || !config.combatrange()) { // boolean hadMage = false; // boolean skippableWeapon = false; // if (config.mageFilter()) // { // int mageBonus = 0; // for (int equipmentId : player.getPlayerComposition().getEquipmentIds()) // { // if (equipmentId == -1) // { // continue; // } // if (equipmentId == 6512) // { // continue; // } // if (equipmentId >= 512) // { // return; // } // int realId = equipmentId - 512; // ItemEquipmentStats itemStats = itemManager.getItemStats(realId, false).getEquipment(); // if (itemStats == null) // { // continue; // } // mageBonus += itemStats.getAmagic(); // } // if (mageBonus > 0) // { // hadMage = true; // } // } // if (!config.weaponFilter().equals("")) // { // List<String> filteredWeapons = getFilteredWeapons(); // for (int equipment : player.getPlayerComposition().getEquipmentIds()) // { // int equipmentId = equipment - 512; // if (equipmentId > 0) // { // ItemComposition equipmentComp = itemManager.getItemComposition(equipmentId); // if (filteredWeapons.stream().anyMatch(item -> WildcardMatcher.matches(item.toLowerCase(), // Text.removeTags(equipmentComp.getName().toLowerCase())))) // { // skippableWeapon = true; // } // } // } // } // if (skippableWeapon) // { // if (!hadMage) // { // continue; // } // } boolean teleported = false; Optional<Widget> widget = Inventory.search().withId(ItemID.ROYAL_SEED_POD).first(); if (widget.isPresent()) { teleported = true; InventoryInteraction.useItem(widget.get(), "Commune"); } Optional<Widget> row = Inventory.search().nameContains("Ring of wealth (").first(); if (row.isPresent() && !teleported) { teleported = true; InventoryInteraction.useItem(row.get(), "Rub"); MousePackets.queueClickPacket(); WidgetPackets.queueResumePause(14352385, 2); } if (rowEquipment != null && !teleported) { teleported = true; MousePackets.queueClickPacket(); WidgetPackets.queueWidgetActionPacket(3, 25362456, -1, -1); } if (teleported) { teleportedFromSkulledPlayer = HypsApiPlugin.getSkullIcon(player) != null; if (teleportedFromSkulledPlayer) { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "Teleported from skulled player", null); } else { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "Teleported from non-skulled player", null); } } return; } } } // public List<String> getFilteredWeapons() // { // List<String> itemNames = new ArrayList<>(); // for (String s : config.weaponFilter().split(",")) // { // if (StringUtils.isNumeric(s)) // { // itemNames.add(Text.removeTags(itemManager.getItemComposition(Integer.parseInt(s)).getName())); // } // else // { // itemNames.add(s); // } // } // return itemNames; // } @Subscribe public void onAnimationChanged(AnimationChanged e) { Widget wildernessLevel = client.getWidget(WidgetInfo.PVP_WILDERNESS_LEVEL); int level = -1; if (wildernessLevel != null && !wildernessLevel.getText().equals("")) { try { if (wildernessLevel.getText().contains("<br>")) { String text = wildernessLevel.getText().split("<br>")[0]; level = Integer.parseInt(text.replaceAll("Level: ", "")); } else { level = Integer.parseInt(wildernessLevel.getText().replaceAll("Level: ", "")); } } catch (NumberFormatException ex) { //ignore } } if (level > -1) { if (e.getActor() == client.getLocalPlayer()) { int animation = client.getLocalPlayer().getAnimation(); if (animation == SEED_POD || animation == RING_OF_WEALTH) { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "timeout triggered", null); timeout = 10; } } } } }
src/main/java/com/utils/AutoTele/AutoTele.java
Hypsster-hUtils-d265b4f
[ { "filename": "src/main/java/com/utils/HypsApiPlugin/Equipment.java", "retrieved_chunk": "\t\tif (e.getContainerId() == InventoryID.EQUIPMENT.getId())\n\t\t{\n\t\t\tequipment.clear();\n\t\t\tint i = -1;\n\t\t\tfor (Item item : e.getItemContainer().getItems())\n\t\t\t{\n\t\t\t\ti++;\n\t\t\t\tif (item == null)\n\t\t\t\t{\n\t\t\t\t\tcontinue;", "score": 0.7477798461914062 }, { "filename": "src/main/java/com/utils/HypsApiPlugin/HypsApiPlugin.java", "retrieved_chunk": "\t\t\tif (item != null)\n\t\t\t{\n\t\t\t\treturn item;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\tpublic int checkIfWearing(int[] ids)\n\t{\n\t\tif (client.getItemContainer(InventoryID.EQUIPMENT) != null)", "score": 0.722832977771759 }, { "filename": "src/main/java/com/utils/gauntletFlicker/gauntletFlicker.java", "retrieved_chunk": "\t\t\tforceTab = false;\n\t\t\treturn;\n\t\t}\n\t\tItem weapon = null;\n\t\ttry\n\t\t{\n\t\t\tweapon = client.getItemContainer(InventoryID.EQUIPMENT).getItem(EquipmentInventorySlot.WEAPON.getSlotIdx());\n\t\t}\n\t\tcatch (NullPointerException ex)\n\t\t{", "score": 0.7196490168571472 }, { "filename": "src/main/java/com/utils/HypsApiPlugin/EquipmentItemQuery.java", "retrieved_chunk": "\t}\n\tpublic Optional<EquipmentItemWidget> first()\n\t{\n\t\tWidget returnWidget = null;\n\t\tif (items.size() == 0)\n\t\t{\n\t\t\treturn Optional.ofNullable(null);\n\t\t}\n\t\treturn Optional.ofNullable(items.get(0));\n\t}", "score": 0.7108514308929443 }, { "filename": "src/main/java/com/utils/SpecDamage/specDamage.java", "retrieved_chunk": "\t\t}\n\t}\n\tprivate void drop()\n\t{\n\t\tOptional<Widget> fish = Inventory.search().idInList(List.of(371, 13441)).first();\n\t\tif (fish.isPresent())\n\t\t{\n\t\t\tWidgetPackets.queueWidgetAction(fish.get(), \"Eat\");\n\t\t}\n\t}", "score": 0.7102166414260864 } ]
java
> royal_seed_pod = Inventory.search().withId(ItemID.ROYAL_SEED_POD).first();
package com.utils.AutoTele; import com.utils.HypsApiPlugin.HypsApiPlugin; import com.utils.HypsApiPlugin.Inventory; import com.utils.InteractionApi.InventoryInteraction; import com.utils.PacketUtilsPlugin; import com.utils.Packets.MousePackets; import com.utils.Packets.WidgetPackets; import com.google.inject.Inject; import com.google.inject.Provides; import net.runelite.api.ChatMessageType; import net.runelite.api.Client; import net.runelite.api.EquipmentInventorySlot; import net.runelite.api.InventoryID; import net.runelite.api.Item; import net.runelite.api.ItemID; import net.runelite.api.Player; import net.runelite.api.events.AnimationChanged; import net.runelite.api.events.GameTick; import net.runelite.api.widgets.Widget; import net.runelite.api.widgets.WidgetInfo; import net.runelite.client.config.ConfigManager; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.game.ItemManager; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDependency; import net.runelite.client.plugins.PluginDescriptor; import java.util.Optional; import java.util.Set; @PluginDescriptor( name = "AutoTele", enabledByDefault = false, tags = {"Hyps"} ) @PluginDependency(HypsApiPlugin.class) @PluginDependency(PacketUtilsPlugin.class) public class AutoTele extends Plugin { @Inject Client client; int timeout; static final int RING_OF_WEALTH = 714; static final int SEED_POD = 4544; int previousLevel = -1; public static boolean teleportedFromSkulledPlayer = false; @Inject ItemManager itemManager; @Inject AutoTeleConfig config; static final Set<Integer> RING_OF_WEALTH_ITEM_IDS = Set.of(ItemID.RING_OF_WEALTH_1, ItemID.RING_OF_WEALTH_2, ItemID.RING_OF_WEALTH_3, ItemID.RING_OF_WEALTH_4, ItemID.RING_OF_WEALTH_5, ItemID.RING_OF_WEALTH_I1, ItemID.RING_OF_WEALTH_I2, ItemID.RING_OF_WEALTH_I3, ItemID.RING_OF_WEALTH_I4, ItemID.RING_OF_WEALTH_I5); @Provides public AutoTeleConfig getConfig(ConfigManager configManager) { return configManager.getConfig(AutoTeleConfig.class); } @Subscribe public void onGameTick(GameTick event) { if (timeout > 0) { timeout--; return; } Widget wildernessLevel = client.getWidget(WidgetInfo.PVP_WILDERNESS_LEVEL); int level = -1; if (wildernessLevel != null && !wildernessLevel.getText().equals("")) { try { if (wildernessLevel.getText().contains("<br>")) { String text = wildernessLevel.getText().split("<br>")[0]; level = Integer.parseInt(text.replaceAll("Level: ", "")); } else { level = Integer.parseInt(wildernessLevel.getText().replaceAll("Level: ", "")); } } catch (NumberFormatException ex) { //ignore } } if (previousLevel != -1 && level == -1) { previousLevel = -1; } Item rowEquipment = null; if (client.getItemContainer(InventoryID.EQUIPMENT) != null) { rowEquipment = client.getItemContainer(InventoryID.EQUIPMENT).getItem(EquipmentInventorySlot.RING.getSlotIdx()); } if ((rowEquipment != null && !RING_OF_WEALTH_ITEM_IDS.contains(rowEquipment.getId()))) { rowEquipment = null; } if (level > -1) { if (previousLevel == -1) { previousLevel = level; Optional<Widget> royal_seed_pod = Inventory.search().withId(ItemID.ROYAL_SEED_POD).first(); Optional
<Widget> ring_of_wealth = Inventory.search().nameContains("Ring of wealth (").first();
if (config.alert()) { if (royal_seed_pod.isPresent() || ring_of_wealth.isPresent() || (rowEquipment != null && RING_OF_WEALTH_ITEM_IDS.contains(rowEquipment.getId()))) { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "<col=7cfc00>Entering wilderness with a teleport item." + " " + "AutoTele is ready to save you", null); } else { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "<col=ff0000> Entering wilderness without a " + "supported " + "teleport possible mistake?", null); } } } } for (Player player : client.getPlayers()) { int lowRange = client.getLocalPlayer().getCombatLevel() - level; int highRange = client.getLocalPlayer().getCombatLevel() + level; if (player.equals(client.getLocalPlayer())) { continue; } if (player.getCombatLevel() >= lowRange && player.getCombatLevel() <= highRange || !config.combatrange()) { // boolean hadMage = false; // boolean skippableWeapon = false; // if (config.mageFilter()) // { // int mageBonus = 0; // for (int equipmentId : player.getPlayerComposition().getEquipmentIds()) // { // if (equipmentId == -1) // { // continue; // } // if (equipmentId == 6512) // { // continue; // } // if (equipmentId >= 512) // { // return; // } // int realId = equipmentId - 512; // ItemEquipmentStats itemStats = itemManager.getItemStats(realId, false).getEquipment(); // if (itemStats == null) // { // continue; // } // mageBonus += itemStats.getAmagic(); // } // if (mageBonus > 0) // { // hadMage = true; // } // } // if (!config.weaponFilter().equals("")) // { // List<String> filteredWeapons = getFilteredWeapons(); // for (int equipment : player.getPlayerComposition().getEquipmentIds()) // { // int equipmentId = equipment - 512; // if (equipmentId > 0) // { // ItemComposition equipmentComp = itemManager.getItemComposition(equipmentId); // if (filteredWeapons.stream().anyMatch(item -> WildcardMatcher.matches(item.toLowerCase(), // Text.removeTags(equipmentComp.getName().toLowerCase())))) // { // skippableWeapon = true; // } // } // } // } // if (skippableWeapon) // { // if (!hadMage) // { // continue; // } // } boolean teleported = false; Optional<Widget> widget = Inventory.search().withId(ItemID.ROYAL_SEED_POD).first(); if (widget.isPresent()) { teleported = true; InventoryInteraction.useItem(widget.get(), "Commune"); } Optional<Widget> row = Inventory.search().nameContains("Ring of wealth (").first(); if (row.isPresent() && !teleported) { teleported = true; InventoryInteraction.useItem(row.get(), "Rub"); MousePackets.queueClickPacket(); WidgetPackets.queueResumePause(14352385, 2); } if (rowEquipment != null && !teleported) { teleported = true; MousePackets.queueClickPacket(); WidgetPackets.queueWidgetActionPacket(3, 25362456, -1, -1); } if (teleported) { teleportedFromSkulledPlayer = HypsApiPlugin.getSkullIcon(player) != null; if (teleportedFromSkulledPlayer) { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "Teleported from skulled player", null); } else { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "Teleported from non-skulled player", null); } } return; } } } // public List<String> getFilteredWeapons() // { // List<String> itemNames = new ArrayList<>(); // for (String s : config.weaponFilter().split(",")) // { // if (StringUtils.isNumeric(s)) // { // itemNames.add(Text.removeTags(itemManager.getItemComposition(Integer.parseInt(s)).getName())); // } // else // { // itemNames.add(s); // } // } // return itemNames; // } @Subscribe public void onAnimationChanged(AnimationChanged e) { Widget wildernessLevel = client.getWidget(WidgetInfo.PVP_WILDERNESS_LEVEL); int level = -1; if (wildernessLevel != null && !wildernessLevel.getText().equals("")) { try { if (wildernessLevel.getText().contains("<br>")) { String text = wildernessLevel.getText().split("<br>")[0]; level = Integer.parseInt(text.replaceAll("Level: ", "")); } else { level = Integer.parseInt(wildernessLevel.getText().replaceAll("Level: ", "")); } } catch (NumberFormatException ex) { //ignore } } if (level > -1) { if (e.getActor() == client.getLocalPlayer()) { int animation = client.getLocalPlayer().getAnimation(); if (animation == SEED_POD || animation == RING_OF_WEALTH) { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "timeout triggered", null); timeout = 10; } } } } }
src/main/java/com/utils/AutoTele/AutoTele.java
Hypsster-hUtils-d265b4f
[ { "filename": "src/main/java/com/utils/HypsApiPlugin/DepositBox.java", "retrieved_chunk": "\t\t\t\t}\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tDepositBox.depositBoxItems =\n\t\t\t\t\t\t\tArrays.stream(client.getWidget(WidgetInfo.DEPOSIT_BOX_INVENTORY_ITEMS_CONTAINER).getDynamicChildren()).filter(Objects::nonNull).filter(x -> x.getItemId() != 6512 && x.getItemId() != -1).collect(Collectors.toList());\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcatch (NullPointerException err)\n\t\t\t\t{\n\t\t\t\t\tDepositBox.depositBoxItems.clear();", "score": 0.733518660068512 }, { "filename": "src/main/java/com/utils/SpecDamage/specDamage.java", "retrieved_chunk": "\t\t}\n\t}\n\tprivate void drop()\n\t{\n\t\tOptional<Widget> fish = Inventory.search().idInList(List.of(371, 13441)).first();\n\t\tif (fish.isPresent())\n\t\t{\n\t\t\tWidgetPackets.queueWidgetAction(fish.get(), \"Eat\");\n\t\t}\n\t}", "score": 0.7298232913017273 }, { "filename": "src/main/java/com/utils/TestPlugin/Tester.java", "retrieved_chunk": "\t{\n\t\tOptional<Widget> fish = Inventory.search().idInList(List.of(371, 13441)).first();\n\t\tif (fish.isPresent())\n\t\t{\n\t\t\tWidgetPackets.queueWidgetAction(fish.get(), \"Eat\");\n\t\t}\n\t}\n}", "score": 0.7248153686523438 }, { "filename": "src/main/java/com/utils/HypsApiPlugin/EquipmentItemQuery.java", "retrieved_chunk": "\t}\n\tpublic Optional<EquipmentItemWidget> first()\n\t{\n\t\tWidget returnWidget = null;\n\t\tif (items.size() == 0)\n\t\t{\n\t\t\treturn Optional.ofNullable(null);\n\t\t}\n\t\treturn Optional.ofNullable(items.get(0));\n\t}", "score": 0.7181642055511475 }, { "filename": "src/main/java/com/utils/HypsApiPlugin/DepositBox.java", "retrieved_chunk": "\t\t\t{\n\t\t\t\tDepositBox.depositBoxItems =\n\t\t\t\t\t\tArrays.stream(client.getWidget(WidgetInfo.DEPOSIT_BOX_INVENTORY_ITEMS_CONTAINER).getDynamicChildren()).filter(Objects::nonNull).filter(x -> x.getItemId() != 6512 && x.getItemId() != -1).collect(Collectors.toList());\n\t\t\t}\n\t\t\tcatch (NullPointerException err)\n\t\t\t{\n\t\t\t\tDepositBox.depositBoxItems.clear();\n\t\t\t}\n\t\t}\n\t}", "score": 0.7150430679321289 } ]
java
<Widget> ring_of_wealth = Inventory.search().nameContains("Ring of wealth (").first();
package com.utils.AutoTele; import com.utils.HypsApiPlugin.HypsApiPlugin; import com.utils.HypsApiPlugin.Inventory; import com.utils.InteractionApi.InventoryInteraction; import com.utils.PacketUtilsPlugin; import com.utils.Packets.MousePackets; import com.utils.Packets.WidgetPackets; import com.google.inject.Inject; import com.google.inject.Provides; import net.runelite.api.ChatMessageType; import net.runelite.api.Client; import net.runelite.api.EquipmentInventorySlot; import net.runelite.api.InventoryID; import net.runelite.api.Item; import net.runelite.api.ItemID; import net.runelite.api.Player; import net.runelite.api.events.AnimationChanged; import net.runelite.api.events.GameTick; import net.runelite.api.widgets.Widget; import net.runelite.api.widgets.WidgetInfo; import net.runelite.client.config.ConfigManager; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.game.ItemManager; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDependency; import net.runelite.client.plugins.PluginDescriptor; import java.util.Optional; import java.util.Set; @PluginDescriptor( name = "AutoTele", enabledByDefault = false, tags = {"Hyps"} ) @PluginDependency(HypsApiPlugin.class) @PluginDependency(PacketUtilsPlugin.class) public class AutoTele extends Plugin { @Inject Client client; int timeout; static final int RING_OF_WEALTH = 714; static final int SEED_POD = 4544; int previousLevel = -1; public static boolean teleportedFromSkulledPlayer = false; @Inject ItemManager itemManager; @Inject AutoTeleConfig config; static final Set<Integer> RING_OF_WEALTH_ITEM_IDS = Set.of(ItemID.RING_OF_WEALTH_1, ItemID.RING_OF_WEALTH_2, ItemID.RING_OF_WEALTH_3, ItemID.RING_OF_WEALTH_4, ItemID.RING_OF_WEALTH_5, ItemID.RING_OF_WEALTH_I1, ItemID.RING_OF_WEALTH_I2, ItemID.RING_OF_WEALTH_I3, ItemID.RING_OF_WEALTH_I4, ItemID.RING_OF_WEALTH_I5); @Provides public AutoTeleConfig getConfig(ConfigManager configManager) { return configManager.getConfig(AutoTeleConfig.class); } @Subscribe public void onGameTick(GameTick event) { if (timeout > 0) { timeout--; return; } Widget wildernessLevel = client.getWidget(WidgetInfo.PVP_WILDERNESS_LEVEL); int level = -1; if (wildernessLevel != null && !wildernessLevel.getText().equals("")) { try { if (wildernessLevel.getText().contains("<br>")) { String text = wildernessLevel.getText().split("<br>")[0]; level = Integer.parseInt(text.replaceAll("Level: ", "")); } else { level = Integer.parseInt(wildernessLevel.getText().replaceAll("Level: ", "")); } } catch (NumberFormatException ex) { //ignore } } if (previousLevel != -1 && level == -1) { previousLevel = -1; } Item rowEquipment = null; if (client.getItemContainer(InventoryID.EQUIPMENT) != null) { rowEquipment = client.getItemContainer(InventoryID.EQUIPMENT).getItem(EquipmentInventorySlot.RING.getSlotIdx()); } if ((rowEquipment != null && !RING_OF_WEALTH_ITEM_IDS.contains(rowEquipment.getId()))) { rowEquipment = null; } if (level > -1) { if (previousLevel == -1) { previousLevel = level; Optional<Widget> royal_seed_pod = Inventory.search().withId(ItemID.ROYAL_SEED_POD).first(); Optional<Widget> ring_of_wealth = Inventory.search().nameContains("Ring of wealth (").first(); if (config.alert()) { if (royal_seed_pod.isPresent() || ring_of_wealth.isPresent() || (rowEquipment != null && RING_OF_WEALTH_ITEM_IDS.contains(rowEquipment.getId()))) { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "<col=7cfc00>Entering wilderness with a teleport item." + " " + "AutoTele is ready to save you", null); } else { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "<col=ff0000> Entering wilderness without a " + "supported " + "teleport possible mistake?", null); } } } } for (Player player : client.getPlayers()) { int lowRange = client.getLocalPlayer().getCombatLevel() - level; int highRange = client.getLocalPlayer().getCombatLevel() + level; if (player.equals(client.getLocalPlayer())) { continue; } if (player.getCombatLevel() >= lowRange && player.getCombatLevel() <= highRange || !config.combatrange()) { // boolean hadMage = false; // boolean skippableWeapon = false; // if (config.mageFilter()) // { // int mageBonus = 0; // for (int equipmentId : player.getPlayerComposition().getEquipmentIds()) // { // if (equipmentId == -1) // { // continue; // } // if (equipmentId == 6512) // { // continue; // } // if (equipmentId >= 512) // { // return; // } // int realId = equipmentId - 512; // ItemEquipmentStats itemStats = itemManager.getItemStats(realId, false).getEquipment(); // if (itemStats == null) // { // continue; // } // mageBonus += itemStats.getAmagic(); // } // if (mageBonus > 0) // { // hadMage = true; // } // } // if (!config.weaponFilter().equals("")) // { // List<String> filteredWeapons = getFilteredWeapons(); // for (int equipment : player.getPlayerComposition().getEquipmentIds()) // { // int equipmentId = equipment - 512; // if (equipmentId > 0) // { // ItemComposition equipmentComp = itemManager.getItemComposition(equipmentId); // if (filteredWeapons.stream().anyMatch(item -> WildcardMatcher.matches(item.toLowerCase(), // Text.removeTags(equipmentComp.getName().toLowerCase())))) // { // skippableWeapon = true; // } // } // } // } // if (skippableWeapon) // { // if (!hadMage) // { // continue; // } // } boolean teleported = false; Optional<Widget
> widget = Inventory.search().withId(ItemID.ROYAL_SEED_POD).first();
if (widget.isPresent()) { teleported = true; InventoryInteraction.useItem(widget.get(), "Commune"); } Optional<Widget> row = Inventory.search().nameContains("Ring of wealth (").first(); if (row.isPresent() && !teleported) { teleported = true; InventoryInteraction.useItem(row.get(), "Rub"); MousePackets.queueClickPacket(); WidgetPackets.queueResumePause(14352385, 2); } if (rowEquipment != null && !teleported) { teleported = true; MousePackets.queueClickPacket(); WidgetPackets.queueWidgetActionPacket(3, 25362456, -1, -1); } if (teleported) { teleportedFromSkulledPlayer = HypsApiPlugin.getSkullIcon(player) != null; if (teleportedFromSkulledPlayer) { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "Teleported from skulled player", null); } else { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "Teleported from non-skulled player", null); } } return; } } } // public List<String> getFilteredWeapons() // { // List<String> itemNames = new ArrayList<>(); // for (String s : config.weaponFilter().split(",")) // { // if (StringUtils.isNumeric(s)) // { // itemNames.add(Text.removeTags(itemManager.getItemComposition(Integer.parseInt(s)).getName())); // } // else // { // itemNames.add(s); // } // } // return itemNames; // } @Subscribe public void onAnimationChanged(AnimationChanged e) { Widget wildernessLevel = client.getWidget(WidgetInfo.PVP_WILDERNESS_LEVEL); int level = -1; if (wildernessLevel != null && !wildernessLevel.getText().equals("")) { try { if (wildernessLevel.getText().contains("<br>")) { String text = wildernessLevel.getText().split("<br>")[0]; level = Integer.parseInt(text.replaceAll("Level: ", "")); } else { level = Integer.parseInt(wildernessLevel.getText().replaceAll("Level: ", "")); } } catch (NumberFormatException ex) { //ignore } } if (level > -1) { if (e.getActor() == client.getLocalPlayer()) { int animation = client.getLocalPlayer().getAnimation(); if (animation == SEED_POD || animation == RING_OF_WEALTH) { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "timeout triggered", null); timeout = 10; } } } } }
src/main/java/com/utils/AutoTele/AutoTele.java
Hypsster-hUtils-d265b4f
[ { "filename": "src/main/java/com/utils/HypsApiPlugin/BankInventory.java", "retrieved_chunk": "//\t\t\t\t\tcounter++;\n//\t\t\t\t}\n//\t\t\t\t//\t\t\t\tif (client.getWidget(WidgetInfo.BANK_INVENTORY_ITEMS_CONTAINER) == null)\n//\t\t\t\t//\t\t\t\t{\n//\t\t\t\t//\t\t\t\t\tBankInventory.bankIventoryItems.clear();\n//\t\t\t\t//\t\t\t\t\treturn;\n//\t\t\t\t//\t\t\t\t}\n//\t\t\t\t//\t\t\t\ttry\n//\t\t\t\t//\t\t\t\t{\n//\t\t\t\t//\t\t\t\t\tBankInventory.bankIventoryItems =", "score": 0.8069263696670532 }, { "filename": "src/main/java/com/utils/HypsApiPlugin/BankInventory.java", "retrieved_chunk": "//\t\t\t\tBankInventory.bankIventoryItems.clear();\n//\t\t\t\tint counter = 0;\n//\t\t\t\tfor (Item item : e.getItemContainer().getItems())\n//\t\t\t\t{\n//\t\t\t\t\ttry\n//\t\t\t\t\t{\n//\t\t\t\t\t\tif(item==null){\n//\t\t\t\t\t\t\tcounter++;\n//\t\t\t\t\t\t\tcontinue;\n//\t\t\t\t\t\t}", "score": 0.7772594690322876 }, { "filename": "src/main/java/com/utils/HypsApiPlugin/BankInventory.java", "retrieved_chunk": "//\t\t\t\t//\t\t\t\t\t\t\tArrays.stream(client.getWidget(WidgetInfo.BANK_INVENTORY_ITEMS_CONTAINER).getDynamicChildren()).filter(Objects::nonNull).filter(x -> x.getItemId() != 6512 && x.getItemId() != -1).collect(Collectors.toList());\n//\t\t\t\t//\t\t\t\t\tbreak;\n//\t\t\t\t//\t\t\t\t}\n//\t\t\t\t//\t\t\t\tcatch (NullPointerException err)\n//\t\t\t\t//\t\t\t\t{\n//\t\t\t\t//\t\t\t\t\tBankInventory.bankIventoryItems.clear();\n//\t\t\t\t//\t\t\t\t\tbreak;\n//\t\t\t\t//\t\t\t\t}\n//\t\t}\n//\t}", "score": 0.7700968980789185 }, { "filename": "src/main/java/com/utils/HypsApiPlugin/Bank.java", "retrieved_chunk": "//\t\t\t\tint counter = 0;\n//\t\t\t\tfor(Item item: e.getItemContainer().getItems()){\n//\t\t\t\t\tif(item==null){\n//\t\t\t\t\t\tcounter++;\n//\t\t\t\t\t\tcontinue;\n//\t\t\t\t\t}\n//\t\t\t\t\tif(item.getId() == -1){\n//\t\t\t\t\t\tcounter++;\n//\t\t\t\t\t\tcontinue;\n//\t\t\t\t\t}", "score": 0.7649335265159607 }, { "filename": "src/main/java/com/utils/HypsApiPlugin/Bank.java", "retrieved_chunk": "//\t\t\t\t\tcounter++;\n//\t\t\t\t}\n//\t\t\t\tif (client.getWidget(WidgetInfo.BANK_ITEM_CONTAINER) == null)\n//\t\t\t\t{\n//\t\t\t\t\tBank.bankItems.clear();\n//\t\t\t\t}\n//\t\t\t\ttry\n//\t\t\t\t{\n//\t\t\t\t\tBank.bankItems =\n//\t\t\t\t\t\t\tArrays.stream(client.getWidget(WidgetInfo.BANK_ITEM_CONTAINER).getDynamicChildren()).filter(Objects::nonNull).filter(x -> x.getItemId() != 6512 && x.getItemId() != -1).collect(Collectors.toList());", "score": 0.7641525864601135 } ]
java
> widget = Inventory.search().withId(ItemID.ROYAL_SEED_POD).first();
package com.utils.AutoTele; import com.utils.HypsApiPlugin.HypsApiPlugin; import com.utils.HypsApiPlugin.Inventory; import com.utils.InteractionApi.InventoryInteraction; import com.utils.PacketUtilsPlugin; import com.utils.Packets.MousePackets; import com.utils.Packets.WidgetPackets; import com.google.inject.Inject; import com.google.inject.Provides; import net.runelite.api.ChatMessageType; import net.runelite.api.Client; import net.runelite.api.EquipmentInventorySlot; import net.runelite.api.InventoryID; import net.runelite.api.Item; import net.runelite.api.ItemID; import net.runelite.api.Player; import net.runelite.api.events.AnimationChanged; import net.runelite.api.events.GameTick; import net.runelite.api.widgets.Widget; import net.runelite.api.widgets.WidgetInfo; import net.runelite.client.config.ConfigManager; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.game.ItemManager; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDependency; import net.runelite.client.plugins.PluginDescriptor; import java.util.Optional; import java.util.Set; @PluginDescriptor( name = "AutoTele", enabledByDefault = false, tags = {"Hyps"} ) @PluginDependency(HypsApiPlugin.class) @PluginDependency(PacketUtilsPlugin.class) public class AutoTele extends Plugin { @Inject Client client; int timeout; static final int RING_OF_WEALTH = 714; static final int SEED_POD = 4544; int previousLevel = -1; public static boolean teleportedFromSkulledPlayer = false; @Inject ItemManager itemManager; @Inject AutoTeleConfig config; static final Set<Integer> RING_OF_WEALTH_ITEM_IDS = Set.of(ItemID.RING_OF_WEALTH_1, ItemID.RING_OF_WEALTH_2, ItemID.RING_OF_WEALTH_3, ItemID.RING_OF_WEALTH_4, ItemID.RING_OF_WEALTH_5, ItemID.RING_OF_WEALTH_I1, ItemID.RING_OF_WEALTH_I2, ItemID.RING_OF_WEALTH_I3, ItemID.RING_OF_WEALTH_I4, ItemID.RING_OF_WEALTH_I5); @Provides public AutoTeleConfig getConfig(ConfigManager configManager) { return configManager.getConfig(AutoTeleConfig.class); } @Subscribe public void onGameTick(GameTick event) { if (timeout > 0) { timeout--; return; } Widget wildernessLevel = client.getWidget(WidgetInfo.PVP_WILDERNESS_LEVEL); int level = -1; if (wildernessLevel != null && !wildernessLevel.getText().equals("")) { try { if (wildernessLevel.getText().contains("<br>")) { String text = wildernessLevel.getText().split("<br>")[0]; level = Integer.parseInt(text.replaceAll("Level: ", "")); } else { level = Integer.parseInt(wildernessLevel.getText().replaceAll("Level: ", "")); } } catch (NumberFormatException ex) { //ignore } } if (previousLevel != -1 && level == -1) { previousLevel = -1; } Item rowEquipment = null; if (client.getItemContainer(InventoryID.EQUIPMENT) != null) { rowEquipment = client.getItemContainer(InventoryID.EQUIPMENT).getItem(EquipmentInventorySlot.RING.getSlotIdx()); } if ((rowEquipment != null && !RING_OF_WEALTH_ITEM_IDS.contains(rowEquipment.getId()))) { rowEquipment = null; } if (level > -1) { if (previousLevel == -1) { previousLevel = level; Optional<Widget> royal_seed_pod = Inventory.search().withId(ItemID.ROYAL_SEED_POD).first(); Optional<Widget> ring_of_wealth = Inventory.search().nameContains("Ring of wealth (").first(); if (config.alert()) { if (royal_seed_pod.isPresent() || ring_of_wealth.isPresent() || (rowEquipment != null && RING_OF_WEALTH_ITEM_IDS.contains(rowEquipment.getId()))) { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "<col=7cfc00>Entering wilderness with a teleport item." + " " + "AutoTele is ready to save you", null); } else { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "<col=ff0000> Entering wilderness without a " + "supported " + "teleport possible mistake?", null); } } } } for (Player player : client.getPlayers()) { int lowRange = client.getLocalPlayer().getCombatLevel() - level; int highRange = client.getLocalPlayer().getCombatLevel() + level; if (player.equals(client.getLocalPlayer())) { continue; } if (player.getCombatLevel() >= lowRange && player.getCombatLevel() <= highRange || !config.combatrange()) { // boolean hadMage = false; // boolean skippableWeapon = false; // if (config.mageFilter()) // { // int mageBonus = 0; // for (int equipmentId : player.getPlayerComposition().getEquipmentIds()) // { // if (equipmentId == -1) // { // continue; // } // if (equipmentId == 6512) // { // continue; // } // if (equipmentId >= 512) // { // return; // } // int realId = equipmentId - 512; // ItemEquipmentStats itemStats = itemManager.getItemStats(realId, false).getEquipment(); // if (itemStats == null) // { // continue; // } // mageBonus += itemStats.getAmagic(); // } // if (mageBonus > 0) // { // hadMage = true; // } // } // if (!config.weaponFilter().equals("")) // { // List<String> filteredWeapons = getFilteredWeapons(); // for (int equipment : player.getPlayerComposition().getEquipmentIds()) // { // int equipmentId = equipment - 512; // if (equipmentId > 0) // { // ItemComposition equipmentComp = itemManager.getItemComposition(equipmentId); // if (filteredWeapons.stream().anyMatch(item -> WildcardMatcher.matches(item.toLowerCase(), // Text.removeTags(equipmentComp.getName().toLowerCase())))) // { // skippableWeapon = true; // } // } // } // } // if (skippableWeapon) // { // if (!hadMage) // { // continue; // } // } boolean teleported = false; Optional<Widget> widget = Inventory.search().withId(ItemID.ROYAL_SEED_POD).first(); if (widget.isPresent()) { teleported = true; InventoryInteraction.useItem(widget.get(), "Commune"); } Optional<
Widget> row = Inventory.search().nameContains("Ring of wealth (").first();
if (row.isPresent() && !teleported) { teleported = true; InventoryInteraction.useItem(row.get(), "Rub"); MousePackets.queueClickPacket(); WidgetPackets.queueResumePause(14352385, 2); } if (rowEquipment != null && !teleported) { teleported = true; MousePackets.queueClickPacket(); WidgetPackets.queueWidgetActionPacket(3, 25362456, -1, -1); } if (teleported) { teleportedFromSkulledPlayer = HypsApiPlugin.getSkullIcon(player) != null; if (teleportedFromSkulledPlayer) { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "Teleported from skulled player", null); } else { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "Teleported from non-skulled player", null); } } return; } } } // public List<String> getFilteredWeapons() // { // List<String> itemNames = new ArrayList<>(); // for (String s : config.weaponFilter().split(",")) // { // if (StringUtils.isNumeric(s)) // { // itemNames.add(Text.removeTags(itemManager.getItemComposition(Integer.parseInt(s)).getName())); // } // else // { // itemNames.add(s); // } // } // return itemNames; // } @Subscribe public void onAnimationChanged(AnimationChanged e) { Widget wildernessLevel = client.getWidget(WidgetInfo.PVP_WILDERNESS_LEVEL); int level = -1; if (wildernessLevel != null && !wildernessLevel.getText().equals("")) { try { if (wildernessLevel.getText().contains("<br>")) { String text = wildernessLevel.getText().split("<br>")[0]; level = Integer.parseInt(text.replaceAll("Level: ", "")); } else { level = Integer.parseInt(wildernessLevel.getText().replaceAll("Level: ", "")); } } catch (NumberFormatException ex) { //ignore } } if (level > -1) { if (e.getActor() == client.getLocalPlayer()) { int animation = client.getLocalPlayer().getAnimation(); if (animation == SEED_POD || animation == RING_OF_WEALTH) { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "timeout triggered", null); timeout = 10; } } } } }
src/main/java/com/utils/AutoTele/AutoTele.java
Hypsster-hUtils-d265b4f
[ { "filename": "src/main/java/com/utils/TestPlugin/Tester.java", "retrieved_chunk": "\t{\n\t\tOptional<Widget> fish = Inventory.search().idInList(List.of(371, 13441)).first();\n\t\tif (fish.isPresent())\n\t\t{\n\t\t\tWidgetPackets.queueWidgetAction(fish.get(), \"Eat\");\n\t\t}\n\t}\n}", "score": 0.8230541944503784 }, { "filename": "src/main/java/com/utils/SpecDamage/specDamage.java", "retrieved_chunk": "\t\t}\n\t}\n\tprivate void drop()\n\t{\n\t\tOptional<Widget> fish = Inventory.search().idInList(List.of(371, 13441)).first();\n\t\tif (fish.isPresent())\n\t\t{\n\t\t\tWidgetPackets.queueWidgetAction(fish.get(), \"Eat\");\n\t\t}\n\t}", "score": 0.8173503279685974 }, { "filename": "src/main/java/com/utils/InteractionApi/BankInventoryInteraction.java", "retrieved_chunk": "\t\treturn BankInventory.search().withId(id).first().flatMap(item ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItem(Predicate<? super Widget> predicate, String... actions)\n\t{\n\t\treturn BankInventory.search().filter(predicate).first().flatMap(item ->", "score": 0.7746456861495972 }, { "filename": "src/main/java/com/utils/InteractionApi/BankInventoryInteraction.java", "retrieved_chunk": "\t{\n\t\treturn BankInventory.search().withName(name).first().flatMap(item ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItem(int id, String... actions)\n\t{", "score": 0.7724679708480835 }, { "filename": "src/main/java/com/utils/InteractionApi/InventoryInteraction.java", "retrieved_chunk": "\t{\n\t\treturn Inventory.search().withName(name).first().flatMap(item ->\n\t\t{\n\t\t\tMousePackets.queueClickPacket();\n\t\t\tWidgetPackets.queueWidgetAction(item, actions);\n\t\t\treturn Optional.of(true);\n\t\t}).orElse(false);\n\t}\n\tpublic static boolean useItem(int id, String... actions)\n\t{", "score": 0.767806887626648 } ]
java
Widget> row = Inventory.search().nameContains("Ring of wealth (").first();
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/ContactFormService.java", "retrieved_chunk": " public ContactForm saveContactForm(ContactFormDto contactFormDto){\n ContactForm contactForm = repository.save(ContactForm.fromContactFormDto(contactFormDto));\n if(mode.equalsIgnoreCase(\"email\")){\n log.info(\"Redirecting Contact Form to email\");\n MailSendThread thread = new MailSendThread(this, mailingService, contactForm);\n thread.start();\n }\n log.info(\"Saved Contact Form\");\n return contactForm;\n }", "score": 0.8344346284866333 }, { "filename": "src/main/java/org/easycontactforms/core/services/MailSendThread.java", "retrieved_chunk": " ApplicationState.smtpAvailable = false;\n e.printStackTrace();\n return;\n }\n if(!ApplicationState.smtpAvailable && resendPolicy){\n ApplicationState.smtpAvailable = true;\n mailingService.resendMails(true, contactFormService);\n }\n contactForm.setEmailSent(true);\n contactFormService.updateContactForm(contactForm);", "score": 0.831400454044342 }, { "filename": "src/main/java/org/easycontactforms/core/controller/ContactFormController.java", "retrieved_chunk": " * @return status and in db saved object\n */\n public ResponseEntity handleRequest(ContactFormDto contactFormDto){\n log.debug(\"[POST] Saving Contact Form\");\n for(String key : PluginStore.instance.plugins.keySet()){\n PluginStore.instance.plugins.get(key).beforeContactFormProcessing(new org.easycontactforms.api.models.ContactFormDto(contactFormDto.getEmail(), contactFormDto.getName(), contactFormDto.getSubject(), contactFormDto.getMessage()));\n }\n if (contactFormDto.getEmail() == null || contactFormDto.getMessage() == null){\n return ResponseEntity.status(400).body(new ErrorDto(400, \"Missing required attributes in request body\"));\n }", "score": 0.8173837661743164 }, { "filename": "src/main/java/org/easycontactforms/core/controller/HTMLContactFormController.java", "retrieved_chunk": " }\n if (contactFormDto.getEmail() == null || contactFormDto.getMessage() == null) {\n throw new RuntimeException();\n }\n // processes contact form\n ContactForm contactForm = service.saveContactForm(contactFormDto);\n log.debug(\"[POST] processed data excluding plugins\");\n // Executing plugin hook contactFormProcessed\n for (String key : PluginStore.instance.plugins.keySet()) {\n PluginStore.instance.plugins.get(key).contactFormProcessed(new org.easycontactforms.api.models.ContactForm(contactForm.getId(), contactFormDto.getEmail(), contactFormDto.getName(), contactFormDto.getSubject(), contactFormDto.getMessage()));", "score": 0.8145153522491455 }, { "filename": "src/main/java/org/easycontactforms/core/scheduled/ResendEmailsScheduler.java", "retrieved_chunk": " @Scheduled(fixedRateString = \"${redirect.mode.resend.interval}\")\n public void resendEmails(){\n if(resend) {\n log.info(\"Resending not send emails\");\n mailingService.resendMails(true, contactFormService);\n }\n }\n}", "score": 0.8089374899864197 } ]
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/TokenRange.java", "retrieved_chunk": " if(!this.contains(position)) {\n throw new IndexOutOfBoundsException();\n }\n int i = 0;\n for(TokenRange subRange : subRanges()) {\n if(!subRange.contains(position)) {\n i++;\n continue;\n }\n break;", "score": 0.8188388347625732 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/formatter/FormattingVisitor.java", "retrieved_chunk": " TokenRange rightRange = expr.second().accept(this, context);\n return TokenRange.encompassing(leftRange, rightRange);\n }\n private TokenRange getAndPushRange() {\n return getAndPushRange(1);\n }\n private TokenRange getAndPushRange(final int end) {\n TokenRange oldRange = lastRange;\n lastRange = TokenRange.between(lastRange.end(), lastRange.end() + end);\n return TokenRange.between(oldRange.end(), oldRange.end() + end);", "score": 0.8028122186660767 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/TokenRange.java", "retrieved_chunk": " }\n return i;\n }\n public TokenRange rangeAtPosition(final int position) {\n //TODO if a range is empty, it may have issues getting, but I need a repro case to test and fix.\n return subRanges.stream()\n .filter(tokenRange -> tokenRange.contains(position))\n .findFirst()\n .orElse(this);\n }", "score": 0.7811452150344849 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/TokenRange.java", "retrieved_chunk": " .map(TokenRange::end)\n .orElse(this.end());\n if(start == this.start() && end == this.end()) {\n return this;\n }\n TokenRange newRange = TokenRange.between(start, end);\n newRange.subRanges().addAll(this.subRanges());\n return newRange;\n }\n @Override", "score": 0.7751924991607666 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/formatter/FormattingVisitor.java", "retrieved_chunk": " for(Pair<TokenRange, Style> token : tokens) {\n TokenRange range = token.getFirst();\n int subEnd = Math.max(range.start() - offset, 0);\n if(subEnd >= currentString.length()) {\n break;\n }\n int subStart = Math.min(range.end() - offset, currentString.length());\n if(subStart > 0) {\n sequences.add(FormattedCharSequence.forward(currentString.substring(index, subEnd), token.getSecond()));\n sequences.add(FormattedCharSequence.forward(currentString.substring(subEnd, subStart), token.getSecond()));", "score": 0.7616583108901978 } ]
java
lastRange.covers(previous)) {
package com.blamejared.searchables.api.autcomplete; import com.blamejared.searchables.api.TokenRange; import com.blamejared.searchables.lang.StringSearcher; import com.blamejared.searchables.lang.expression.type.*; import com.blamejared.searchables.lang.expression.visitor.Visitor; import java.util.*; import java.util.function.Consumer; /** * Generates a list of TokenRanges that can be used to split a given string into parts. * Mainly used to split strings for completion purposes. */ public class CompletionVisitor implements Visitor<TokenRange>, Consumer<String> { private final List<TokenRange> tokens = new ArrayList<>(); private TokenRange lastRange = TokenRange.EMPTY; /** * Resets this visitor to a state that allows it to run again. */ public void reset() { tokens.clear(); lastRange = TokenRange.EMPTY; } /** * Reduces the tokens into their outermost parts. * For example the string {@code "shape:square color:red"} will be split into: * {@code [ * TokenRange(0, 12, [TokenRange(0, 5), TokenRange(5, 6), TokenRange(6, 12)]), * TokenRange(13, 22, [TokenRange(13, 18), TokenRange(18, 19), TokenRange(19, 22)]) * ]} */ protected void reduceTokens() { // Can this be done while visiting? ListIterator<TokenRange> iterator = tokens.listIterator(tokens.size()); TokenRange lastRange = null; while(iterator.hasPrevious()) { TokenRange previous = iterator.previous(); if(lastRange == null) { lastRange = previous; } else { if(lastRange.covers(previous)) {
lastRange.addRange(previous);
iterator.remove(); } else { lastRange = previous; } } } } /** * Gets the tokens in this visitor. * * @return The tokens in this visitor. */ public List<TokenRange> tokens() { return tokens; } /** * Gets the {@link Optional<TokenRange>} at the given position. * * @param position The current cursor position. * * @return An {@link Optional<TokenRange>} at the given position, or an empty optional if out of bounds. */ public Optional<TokenRange> tokenAt(final int position) { return tokens.stream() .filter(range -> range.contains(position)) .findFirst(); } /** * Gets the {@link TokenRange} at the given position, or {@link TokenRange#EMPTY} if out of bounds. * * @param position The current cursor position. * * @return An {@link TokenRange} at the given range, or {@link TokenRange#EMPTY} if out of bounds. */ public TokenRange rangeAt(final int position) { return tokenAt(position).orElse(TokenRange.EMPTY); } @Override public TokenRange visitGrouping(final GroupingExpression expr) { TokenRange leftRange = expr.left().accept(this); getAndPushRange(); TokenRange rightRange = expr.right().accept(this); return TokenRange.encompassing(leftRange, rightRange); } @Override public TokenRange visitComponent(final ComponentExpression expr) { TokenRange leftRange = expr.left().accept(this); addToken(getAndPushRange()); TokenRange rightRange = expr.right().accept(this); return addToken(TokenRange.encompassing(leftRange, rightRange)); } @Override public TokenRange visitLiteral(final LiteralExpression expr) { return addToken(getAndPushRange(expr.displayValue().length())); } @Override public TokenRange visitPaired(final PairedExpression expr) { TokenRange leftRange = addToken(expr.first().accept(this)); TokenRange rightRange = addToken(expr.second().accept(this)); return addToken(TokenRange.encompassing(leftRange, rightRange)); } private TokenRange addToken(final TokenRange range) { this.tokens.add(range.recalculate()); return range; } private TokenRange getAndPushRange() { return getAndPushRange(1); } private TokenRange getAndPushRange(final int end) { TokenRange oldRange = lastRange; lastRange = TokenRange.between(lastRange.end(), lastRange.end() + end); return TokenRange.between(oldRange.end(), oldRange.end() + end); } /** * Resets this visitor and compiles a list of {@link TokenRange} from the given String * * @param search The string to search */ @Override public void accept(final String search) { reset(); StringSearcher.search(search, this); } @Override public TokenRange postVisit(final TokenRange obj) { this.reduceTokens(); return Visitor.super.postVisit(obj); } }
common/src/main/java/com/blamejared/searchables/api/autcomplete/CompletionVisitor.java
jaredlll08-searchables-2cb19ff
[ { "filename": "common/src/main/java/com/blamejared/searchables/api/formatter/FormattingVisitor.java", "retrieved_chunk": " TokenRange rightRange = expr.second().accept(this, context);\n return TokenRange.encompassing(leftRange, rightRange);\n }\n private TokenRange getAndPushRange() {\n return getAndPushRange(1);\n }\n private TokenRange getAndPushRange(final int end) {\n TokenRange oldRange = lastRange;\n lastRange = TokenRange.between(lastRange.end(), lastRange.end() + end);\n return TokenRange.between(oldRange.end(), oldRange.end() + end);", "score": 0.8146324753761292 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/TokenRange.java", "retrieved_chunk": " if(!this.contains(position)) {\n throw new IndexOutOfBoundsException();\n }\n int i = 0;\n for(TokenRange subRange : subRanges()) {\n if(!subRange.contains(position)) {\n i++;\n continue;\n }\n break;", "score": 0.8050796389579773 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/TokenRange.java", "retrieved_chunk": " .map(TokenRange::end)\n .orElse(this.end());\n if(start == this.start() && end == this.end()) {\n return this;\n }\n TokenRange newRange = TokenRange.between(start, end);\n newRange.subRanges().addAll(this.subRanges());\n return newRange;\n }\n @Override", "score": 0.7863204479217529 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/formatter/FormattingVisitor.java", "retrieved_chunk": " for(Pair<TokenRange, Style> token : tokens) {\n TokenRange range = token.getFirst();\n int subEnd = Math.max(range.start() - offset, 0);\n if(subEnd >= currentString.length()) {\n break;\n }\n int subStart = Math.min(range.end() - offset, currentString.length());\n if(subStart > 0) {\n sequences.add(FormattedCharSequence.forward(currentString.substring(index, subEnd), token.getSecond()));\n sequences.add(FormattedCharSequence.forward(currentString.substring(subEnd, subStart), token.getSecond()));", "score": 0.7676626443862915 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/TokenRange.java", "retrieved_chunk": " }\n return i;\n }\n public TokenRange rangeAtPosition(final int position) {\n //TODO if a range is empty, it may have issues getting, but I need a repro case to test and fix.\n return subRanges.stream()\n .filter(tokenRange -> tokenRange.contains(position))\n .findFirst()\n .orElse(this);\n }", "score": 0.7569379210472107 } ]
java
lastRange.addRange(previous);
package com.blamejared.searchables.api.autcomplete; import com.blamejared.searchables.api.TokenRange; import com.blamejared.searchables.lang.StringSearcher; import com.blamejared.searchables.lang.expression.type.*; import com.blamejared.searchables.lang.expression.visitor.Visitor; import java.util.*; import java.util.function.Consumer; /** * Generates a list of TokenRanges that can be used to split a given string into parts. * Mainly used to split strings for completion purposes. */ public class CompletionVisitor implements Visitor<TokenRange>, Consumer<String> { private final List<TokenRange> tokens = new ArrayList<>(); private TokenRange lastRange = TokenRange.EMPTY; /** * Resets this visitor to a state that allows it to run again. */ public void reset() { tokens.clear(); lastRange = TokenRange.EMPTY; } /** * Reduces the tokens into their outermost parts. * For example the string {@code "shape:square color:red"} will be split into: * {@code [ * TokenRange(0, 12, [TokenRange(0, 5), TokenRange(5, 6), TokenRange(6, 12)]), * TokenRange(13, 22, [TokenRange(13, 18), TokenRange(18, 19), TokenRange(19, 22)]) * ]} */ protected void reduceTokens() { // Can this be done while visiting? ListIterator<TokenRange> iterator = tokens.listIterator(tokens.size()); TokenRange lastRange = null; while(iterator.hasPrevious()) { TokenRange previous = iterator.previous(); if(lastRange == null) { lastRange = previous; } else { if(lastRange.covers(previous)) { lastRange.addRange(previous); iterator.remove(); } else { lastRange = previous; } } } } /** * Gets the tokens in this visitor. * * @return The tokens in this visitor. */ public List<TokenRange> tokens() { return tokens; } /** * Gets the {@link Optional<TokenRange>} at the given position. * * @param position The current cursor position. * * @return An {@link Optional<TokenRange>} at the given position, or an empty optional if out of bounds. */ public Optional<TokenRange> tokenAt(final int position) { return tokens.stream() .filter(range -> range.contains(position)) .findFirst(); } /** * Gets the {@link TokenRange} at the given position, or {@link TokenRange#EMPTY} if out of bounds. * * @param position The current cursor position. * * @return An {@link TokenRange} at the given range, or {@link TokenRange#EMPTY} if out of bounds. */ public TokenRange rangeAt(final int position) { return tokenAt(position).orElse(TokenRange.EMPTY); } @Override public TokenRange visitGrouping(final GroupingExpression expr) { TokenRange leftRange = expr.left().accept(this); getAndPushRange(); TokenRange rightRange = expr.right().accept(this); return TokenRange.encompassing(leftRange, rightRange); } @Override public TokenRange visitComponent(final ComponentExpression expr) { TokenRange leftRange = expr.left().accept(this); addToken(getAndPushRange()); TokenRange rightRange = expr.right().accept(this); return addToken(TokenRange.encompassing(leftRange, rightRange)); } @Override public TokenRange visitLiteral(final LiteralExpression expr) { return addToken(getAndPushRange(expr.displayValue().length())); } @Override public TokenRange visitPaired(final PairedExpression expr) { TokenRange leftRange = addToken(expr.first().accept(this)); TokenRange rightRange = addToken(expr.second().accept(this)); return addToken(TokenRange.encompassing(leftRange, rightRange)); } private TokenRange addToken(final TokenRange range) { this.
tokens.add(range.recalculate());
return range; } private TokenRange getAndPushRange() { return getAndPushRange(1); } private TokenRange getAndPushRange(final int end) { TokenRange oldRange = lastRange; lastRange = TokenRange.between(lastRange.end(), lastRange.end() + end); return TokenRange.between(oldRange.end(), oldRange.end() + end); } /** * Resets this visitor and compiles a list of {@link TokenRange} from the given String * * @param search The string to search */ @Override public void accept(final String search) { reset(); StringSearcher.search(search, this); } @Override public TokenRange postVisit(final TokenRange obj) { this.reduceTokens(); return Visitor.super.postVisit(obj); } }
common/src/main/java/com/blamejared/searchables/api/autcomplete/CompletionVisitor.java
jaredlll08-searchables-2cb19ff
[ { "filename": "common/src/main/java/com/blamejared/searchables/api/formatter/FormattingVisitor.java", "retrieved_chunk": " .findFirst();\n }\n @Override\n public TokenRange visitGrouping(final GroupingExpression expr, final FormattingContext context) {\n TokenRange leftRange = expr.left().accept(this, context);\n tokens.add(Pair.of(getAndPushRange(), context.style()));\n TokenRange rightRange = expr.right().accept(this, context);\n return TokenRange.encompassing(leftRange, rightRange);\n }\n @Override", "score": 0.9064947366714478 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/formatter/FormattingVisitor.java", "retrieved_chunk": " TokenRange rightRange = expr.second().accept(this, context);\n return TokenRange.encompassing(leftRange, rightRange);\n }\n private TokenRange getAndPushRange() {\n return getAndPushRange(1);\n }\n private TokenRange getAndPushRange(final int end) {\n TokenRange oldRange = lastRange;\n lastRange = TokenRange.between(lastRange.end(), lastRange.end() + end);\n return TokenRange.between(oldRange.end(), oldRange.end() + end);", "score": 0.8791977763175964 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/formatter/FormattingVisitor.java", "retrieved_chunk": " if(!context.valid() || context.isKey() && !type.components().containsKey(expr.value())) {\n style = FormattingConstants.INVALID;\n }\n TokenRange range = getAndPushRange(expr.displayValue().length());\n tokens.add(Pair.of(range, style));\n return range;\n }\n @Override\n public TokenRange visitPaired(final PairedExpression expr, final FormattingContext context) {\n TokenRange leftRange = expr.first().accept(this, context);", "score": 0.8791155219078064 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/formatter/FormattingVisitor.java", "retrieved_chunk": " public TokenRange visitComponent(final ComponentExpression expr, final FormattingContext context) {\n boolean valid = context.valid() && expr.left() instanceof LiteralExpression && expr.right() instanceof LiteralExpression;\n TokenRange leftRange = expr.left().accept(this, FormattingContext.key(FormattingConstants.KEY, valid));\n tokens.add(Pair.of(getAndPushRange(), context.style(valid)));\n TokenRange rightRange = expr.right().accept(this, FormattingContext.literal(FormattingConstants.TERM, valid));\n return TokenRange.encompassing(leftRange, rightRange);\n }\n @Override\n public TokenRange visitLiteral(final LiteralExpression expr, final FormattingContext context) {\n Style style = context.style();", "score": 0.877243161201477 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/TokenRange.java", "retrieved_chunk": " .map(TokenRange::end)\n .orElse(this.end());\n if(start == this.start() && end == this.end()) {\n return this;\n }\n TokenRange newRange = TokenRange.between(start, end);\n newRange.subRanges().addAll(this.subRanges());\n return newRange;\n }\n @Override", "score": 0.7975203990936279 } ]
java
tokens.add(range.recalculate());
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": "package com.jessetzh.handler;\nimport org.apache.http.client.methods.CloseableHttpResponse;\nimport org.apache.http.util.EntityUtils;\nimport java.io.IOException;\npublic class SdResHandler {\n public static void process(CloseableHttpResponse response) throws IOException {\n if (response.getStatusLine().getStatusCode() != 200) {\n if (response.getStatusLine().getStatusCode() == 401) {\n throw new StableDiffusionException(\"Identity verification failed. Please check if your username and password are correct!\");\n } else if (response.getStatusLine().getStatusCode() == 500) {", "score": 0.714597225189209 }, { "filename": "src/main/java/com/jessetzh/handler/SdResHandler.java", "retrieved_chunk": " throw new StableDiffusionException(EntityUtils.toString(response.getEntity()));\n } else {\n throw new StableDiffusionException(\"Interface call error, please check if the URL is correct.\");\n }\n } else {\n if (response.getEntity() == null) {\n System.err.println(\"The result is empty!\");\n }\n }\n }", "score": 0.6934370994567871 }, { "filename": "src/main/java/com/jessetzh/parameters/BasicParameter.java", "retrieved_chunk": "\t}\n\tpublic String getProxyHost() {\n\t\treturn proxyHost;\n\t}\n\tpublic void setProxyHost(String proxyHost) {\n\t\tthis.proxyHost = proxyHost;\n\t}\n\tpublic int getProxyPort() {\n\t\treturn proxyPort;\n\t}", "score": 0.6925386190414429 }, { "filename": "src/main/java/com/jessetzh/parameters/BasicParameter.java", "retrieved_chunk": "package com.jessetzh.parameters;\npublic class BasicParameter {\n\tprivate String apiUrl;\n\tprivate boolean proxyEnable;\n\tprivate String proxyHost;\n\tprivate int proxyPort;\n\tprivate boolean authEnable;\n\tprivate String user;\n\tprivate String password;\n\tpublic String getApiUrl() {", "score": 0.6857961416244507 }, { "filename": "src/main/java/com/jessetzh/parameters/BasicParameter.java", "retrieved_chunk": "\t}\n\tpublic BasicParameter(String url) {\n\t\tthis.proxyEnable = false;\n\t\tthis.authEnable = false;\n\t\tif (url != null) {\n\t\t\tif ( url.endsWith(\"/\")) {\n\t\t\t\turl = url.substring(0, url.length() - 1);\n\t\t\t}\n\t\t}\n\t\tthis.apiUrl = url;", "score": 0.6851788759231567 } ]
java
basicParameter.getApiUrl() == null) {
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": " *\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": 0.9133552312850952 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/TokenRange.java", "retrieved_chunk": " *\n * @param range The range to add.\n */\n public void addRange(final TokenRange range) {\n this.subRanges.add(range);\n }\n /**\n * Adds a collection of ranges as subranges to this range.\n *\n * @param ranges The ranges to add.", "score": 0.9074984192848206 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/TokenRange.java", "retrieved_chunk": " *\n * @param position The position of the token.\n *\n * @return a new {@link TokenRange} at the given position\n */\n public static TokenRange at(final int position) {\n return new TokenRange(position, position);\n }\n /**\n * Creates a new {@link TokenRange} with the given start and end.", "score": 0.9044457674026489 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/autcomplete/AutoComplete.java", "retrieved_chunk": " this.lastMousePosition = new Vector2d(0, 0);\n this.lastCursorPosition = -1;\n }\n /**\n * Compiles suggestions for the given value.\n *\n * @param value the input argument\n */\n @Override\n public void accept(String value) {", "score": 0.9002968072891235 }, { "filename": "common/src/main/java/com/blamejared/searchables/api/TokenRange.java", "retrieved_chunk": " *\n * @param of The string to substring.\n * @param end The end position.\n *\n * @return The substring of the given string using this range's start and the given end.\n */\n public String substring(final String of, final int end) {\n return of.substring(this.start(), end);\n }\n /**", "score": 0.8920155763626099 } ]
java
StringSearcher.search(search, this);
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/main/java/org/chelonix/dagger/client/engineconn/CLIRunner.java", "retrieved_chunk": "import java.util.concurrent.Executors;\nclass CLIRunner implements Runnable {\n static final Logger LOG = LoggerFactory.getLogger(CLIRunner.class);\n private final FluentProcess process;\n private ConnectParams params;\n private boolean failed = false;\n private final ExecutorService executorService;\n private static String getCLIPath() throws IOException {\n String cliBinPath = System.getenv(\"_EXPERIMENTAL_DAGGER_CLI_BIN\");\n if (cliBinPath == null) {", "score": 0.8525206446647644 }, { "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": 0.8361292481422424 }, { "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": 0.8114590644836426 }, { "filename": "dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/CLIRunner.java", "retrieved_chunk": " this.params = params;\n notifyAll();\n }\n public void start() {\n executorService.execute(this);\n }\n @Override\n public void run() {\n try {\n process.streamOutputLines().forEach(line -> {", "score": 0.7812269926071167 }, { "filename": "dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/CLIDownloader.java", "retrieved_chunk": "import java.util.Map;\nclass CLIDownloader {\n static final Logger LOG = LoggerFactory.getLogger(CLIDownloader.class);\n private static final File CACHE_DIR = Paths.get(BaseDirectory.get(BaseDirectory.XDG_CACHE_HOME), \"dagger\").toFile();\n public static final String CLI_VERSION = \"0.6.2\";\n private static final String DAGGER_CLI_BIN_PREFIX = \"dagger-\";\n private final FileFetcher fetcher;\n public CLIDownloader(FileFetcher fetcher) {\n this.fetcher = fetcher;\n }", "score": 0.7700965404510498 } ]
java
connectParams = cliRunner.getConnectionParams();
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/main/java/org/chelonix/dagger/client/engineconn/CLIRunner.java", "retrieved_chunk": "import java.util.concurrent.Executors;\nclass CLIRunner implements Runnable {\n static final Logger LOG = LoggerFactory.getLogger(CLIRunner.class);\n private final FluentProcess process;\n private ConnectParams params;\n private boolean failed = false;\n private final ExecutorService executorService;\n private static String getCLIPath() throws IOException {\n String cliBinPath = System.getenv(\"_EXPERIMENTAL_DAGGER_CLI_BIN\");\n if (cliBinPath == null) {", "score": 0.8395843505859375 }, { "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": 0.8049867153167725 }, { "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": 0.8046344518661499 }, { "filename": "dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/CLIDownloader.java", "retrieved_chunk": "import java.util.Map;\nclass CLIDownloader {\n static final Logger LOG = LoggerFactory.getLogger(CLIDownloader.class);\n private static final File CACHE_DIR = Paths.get(BaseDirectory.get(BaseDirectory.XDG_CACHE_HOME), \"dagger\").toFile();\n public static final String CLI_VERSION = \"0.6.2\";\n private static final String DAGGER_CLI_BIN_PREFIX = \"dagger-\";\n private final FileFetcher fetcher;\n public CLIDownloader(FileFetcher fetcher) {\n this.fetcher = fetcher;\n }", "score": 0.7723804712295532 }, { "filename": "dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/ConnectParams.java", "retrieved_chunk": " }\n @Override\n public String toString() {\n return \"ConnectParams{\" +\n \"port=\" + port +\n \", sessionToken='\" + sessionToken + '\\'' +\n '}';\n }\n public void setPort(int port) {\n this.port = port;", "score": 0.7589908838272095 } ]
java
cliRunner.start();
package com.jessetzh.test; import com.jessetzh.parameters.Img2ImgParameter; import com.jessetzh.parameters.SamplerEnums; import com.jessetzh.parameters.Text2ImgParameter; import com.jessetzh.request.Img2Img; import com.jessetzh.request.Text2Img; import com.jessetzh.res.SdResponses; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.math.BigDecimal; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Base64; /** * */ public class GeneratorTest { //支持直接使用 gradio.live WebUI 地址调用 static final String URL = "https://xxxxxxxxxxxxx.gradio.live/"; public static void main(String[] args) throws IOException { new GeneratorTest().img2imgTest(); } private void text2ImgText() throws IOException { Text2ImgParameter parameter = new Text2ImgParameter(URL); //如需要代理则解开下列代码注释 // parameter.getBasicParameter().setProxyEnable(true); // parameter.getBasicParameter().setProxyHost("127.0.0.1"); // parameter.getBasicParameter().setProxyPort(7890); parameter.setPrompt("One Golden Retriever"); SdResponses res = Text2Img.generate(parameter); for (String image : res.getImages()) { BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(Base64.getDecoder().decode(image))); File output = new File("image.png"); ImageIO.write(bufferedImage, "png", output); } } private void img2imgTest() throws IOException { Img2ImgParameter parameter = new Img2ImgParameter(URL); //重绘幅度 parameter.setDenoisingStrength(new BigDecimal("0.55")); parameter.setSeed(-1); parameter.setSteps(30); parameter.setCfgScale(7); parameter.setWidth(512); parameter.setHeight(512); parameter.setSamplerName(SamplerEnums.DPM_2M_Karras.getInfo()); Path path = Paths.get("test.jpeg"); byte[] bytes = Files.readAllBytes(path); Base64.Encoder encoder = Base64.getEncoder(); String base64String = encoder.encodeToString(bytes);
parameter.setInit_images(new String[]{
base64String}); parameter.setPrompt("dog"); parameter.setNegativePrompt("cat"); SdResponses res = Img2Img.generate(parameter); for (String image : res.getImages()) { BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(Base64.getDecoder().decode(image))); File output = new File("image.png"); ImageIO.write(bufferedImage, "png", output); System.out.println(res.getInfo()); } } }
src/main/java/com/jessetzh/test/GeneratorTest.java
JesseTzh-stable-diffusion-java-20f5a07
[ { "filename": "src/main/java/com/jessetzh/request/Img2Img.java", "retrieved_chunk": "public class Img2Img {\n\tprivate static final String API_PATH = \"/sdapi/v1/img2img\";\n\tpublic static SdResponses generate(Img2ImgParameter parameter) throws IOException {\n\t\tHttpClientBuilder builder = HttpClients.custom();\n\t\tBasicParameterHandler.check(parameter.getBasicParameter(), builder);\n\t\tparameter.getBasicParameter().setApiUrl(parameter.getBasicParameter().getApiUrl() + API_PATH);\n\t\tHttpPost httpPost = new HttpPost(parameter.getBasicParameter().getApiUrl());\n\t\tStringEntity entity = new StringEntity(new GsonBuilder().create().toJson(parameter));\n\t\treturn RequestExecutor.execute(builder, entity, httpPost);\n\t}", "score": 0.7225788235664368 }, { "filename": "src/main/java/com/jessetzh/request/Text2Img.java", "retrieved_chunk": "public class Text2Img {\n\tprivate static final String API_PATH = \"/sdapi/v1/img2img\";\n\tpublic static SdResponses generate(Text2ImgParameter parameter) throws IOException {\n\t\tHttpClientBuilder builder = HttpClients.custom();\n\t\tBasicParameterHandler.check(parameter.getBasicParameter(), builder);\n\t\tparameter.getBasicParameter().setApiUrl(parameter.getBasicParameter().getApiUrl() + API_PATH);\n\t\tHttpPost httpPost = new HttpPost(parameter.getBasicParameter().getApiUrl());\n\t\tStringEntity entity = new StringEntity(new GsonBuilder().create().toJson(parameter));\n\t\treturn RequestExecutor.execute(builder, entity, httpPost);\n\t}", "score": 0.7180516123771667 }, { "filename": "src/main/java/com/jessetzh/res/SdResponses.java", "retrieved_chunk": "\t\tthis.images = images;\n\t}\n\tpublic SdParameter getParameters() {\n\t\treturn parameters;\n\t}\n\tpublic void setParameters(SdParameter parameters) {\n\t\tthis.parameters = parameters;\n\t}\n\t\tpublic String getInfo() {\n\t\treturn info;", "score": 0.6391387581825256 }, { "filename": "src/main/java/com/jessetzh/res/SdResponses.java", "retrieved_chunk": "\t}\n\tpublic void setInfo(String info) {\n\t\tthis.info = info;\n\t}\n\tpublic SdResponses() {\n\t}\n\tpublic SdResponses(String[] images, SdParameter parameters, String info) {\n\t\tthis.images = images;\n\t\tthis.parameters = parameters;\n\t\tthis.info = info;", "score": 0.6289917230606079 }, { "filename": "src/main/java/com/jessetzh/parameters/Text2ImgParameter.java", "retrieved_chunk": "package com.jessetzh.parameters;\npublic class Text2ImgParameter extends SdParameter{\n\tpublic Text2ImgParameter() {\n\t\tsuper();\n\t}\n\tpublic Text2ImgParameter(String url) {\n\t\tsuper(url);\n\t}\n}", "score": 0.6236740350723267 } ]
java
parameter.setInit_images(new String[]{
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": " } else if (introspectionQuertyURL == null) {\n in = new URL(String.format(\"https://raw.githubusercontent.com/dagger/dagger/v%s/codegen/introspection/introspection.graphql\", version)).openStream();\n } else if (introspectionQuertyURL != null) {\n in = new URL(introspectionQuertyURL).openStream();\n } else {\n throw new MojoFailureException(\"Could not locate, download or generate GraphQL schema\");\n }\n ByteArrayOutputStream out = new ByteArrayOutputStream();\n FluentProcess.start(bin, \"query\")\n .withTimeout(Duration.of(60, ChronoUnit.SECONDS))", "score": 0.7589929103851318 }, { "filename": "dagger-codegen-maven-plugin/src/main/java/org/chelonix/dagger/codegen/DaggerCodegenMojo.java", "retrieved_chunk": " }\n if (project != null) {\n // Tell Maven that there are some new source files underneath the output directory.\n project.addCompileSourceRoot(getOutputDirectory().getPath());\n }\n }\n private InputStream daggerSchema() throws IOException, InterruptedException, MojoFailureException {\n if (!online) {\n InputStream in = getClass().getClassLoader().getResourceAsStream(String.format(\"schemas/schema-v%s.json\", version));\n if (in == null) {", "score": 0.718583345413208 }, { "filename": "dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/CLIRunner.java", "retrieved_chunk": " cliBinPath = new CLIDownloader().downloadCLI();\n }\n return cliBinPath;\n }\n public CLIRunner(String workingDir) throws IOException {\n String bin = getCLIPath();\n this.process = FluentProcess.start(bin, \"session\",\n \"--workdir\", workingDir,\n \"--label\", \"dagger.io/sdk.name:java\",\n \"--label\", \"dagger.io/sdk.version:\" + CLIDownloader.CLI_VERSION)", "score": 0.7008307576179504 }, { "filename": "dagger-java-samples/src/main/java/org/chelonix/dagger/sample/CreateAndUseSecret.java", "retrieved_chunk": "package org.chelonix.dagger.sample;\nimport org.chelonix.dagger.client.*;\nimport java.util.List;\npublic class CreateAndUseSecret {\n public static void main(String... args) throws Exception {\n String token = System.getenv(\"GH_API_TOKEN\");\n if (token == null) {\n token = new String(System.console().readPassword(\"GithHub API token: \"));\n }\n try(Client client = Dagger.connect()) {", "score": 0.697013795375824 }, { "filename": "dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/Connection.java", "retrieved_chunk": " private static Connection getConnection(int port, String token, Optional<CLIRunner> runner) {\n Vertx vertx = Vertx.vertx();\n String encodedToken = Base64.getEncoder().encodeToString((token + \":\").getBytes(StandardCharsets.UTF_8));\n DynamicGraphQLClient dynamicGraphQLClient = new VertxDynamicGraphQLClientBuilder()\n .vertx(vertx)\n .url(String.format(\"http://127.0.0.1:%d/query\", port))\n .header(\"authorization\", \"Basic \" + encodedToken)\n .build();\n return new Connection(dynamicGraphQLClient, vertx, runner);\n }", "score": 0.6827074289321899 } ]
java
(BufferedInputStream in = new BufferedInputStream(fetcher.fetch(checksumMapURL))) {
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/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": 0.8402291536331177 }, { "filename": "dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/CLIRunner.java", "retrieved_chunk": "import java.util.concurrent.Executors;\nclass CLIRunner implements Runnable {\n static final Logger LOG = LoggerFactory.getLogger(CLIRunner.class);\n private final FluentProcess process;\n private ConnectParams params;\n private boolean failed = false;\n private final ExecutorService executorService;\n private static String getCLIPath() throws IOException {\n String cliBinPath = System.getenv(\"_EXPERIMENTAL_DAGGER_CLI_BIN\");\n if (cliBinPath == null) {", "score": 0.8076949119567871 }, { "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": 0.7712234258651733 }, { "filename": "dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/CLIRunner.java", "retrieved_chunk": " this.params = params;\n notifyAll();\n }\n public void start() {\n executorService.execute(this);\n }\n @Override\n public void run() {\n try {\n process.streamOutputLines().forEach(line -> {", "score": 0.7669262886047363 }, { "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": 0.7655652761459351 } ]
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/QueryBuilder.java", "retrieved_chunk": " Response response = executeQuery(query);\n if (Scalar.class.isAssignableFrom(klass)) {\n // FIXME scalar could be other types than String in the future\n String value = JsonPath.parse(response.getData().toString()).read(path, String.class);\n try {\n return klass.getDeclaredConstructor(String.class).newInstance(value);\n } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException nsme) {\n // FIXME - This may not happen\n throw new RuntimeException(nsme);\n }", "score": 0.7511530518531799 }, { "filename": "dagger-codegen-maven-plugin/src/main/java/org/chelonix/dagger/codegen/DaggerCodegenMojo.java", "retrieved_chunk": " } else if (introspectionQuertyURL == null) {\n in = new URL(String.format(\"https://raw.githubusercontent.com/dagger/dagger/v%s/codegen/introspection/introspection.graphql\", version)).openStream();\n } else if (introspectionQuertyURL != null) {\n in = new URL(introspectionQuertyURL).openStream();\n } else {\n throw new MojoFailureException(\"Could not locate, download or generate GraphQL schema\");\n }\n ByteArrayOutputStream out = new ByteArrayOutputStream();\n FluentProcess.start(bin, \"query\")\n .withTimeout(Duration.of(60, ChronoUnit.SECONDS))", "score": 0.7313895225524902 }, { "filename": "dagger-codegen-maven-plugin/src/main/java/org/chelonix/dagger/codegen/DaggerCodegenMojo.java", "retrieved_chunk": " }\n if (project != null) {\n // Tell Maven that there are some new source files underneath the output directory.\n project.addCompileSourceRoot(getOutputDirectory().getPath());\n }\n }\n private InputStream daggerSchema() throws IOException, InterruptedException, MojoFailureException {\n if (!online) {\n InputStream in = getClass().getClassLoader().getResourceAsStream(String.format(\"schemas/schema-v%s.json\", version));\n if (in == null) {", "score": 0.7284621000289917 }, { "filename": "dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/Connection.java", "retrieved_chunk": " String portStr = System.getenv(\"DAGGER_SESSION_PORT\");\n String sessionToken = System.getenv(\"DAGGER_SESSION_TOKEN\");\n if (portStr != null && sessionToken != null) {\n try {\n int port = Integer.parseInt(portStr);\n return Optional.of(getConnection(port, sessionToken, Optional.empty()));\n } catch (NumberFormatException nfe) {\n LOG.error(\"invalid port value in DAGGER_SESSION_PORT\", nfe);\n }\n } else if (portStr == null) {", "score": 0.725007176399231 }, { "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": 0.7233160734176636 } ]
java
new BufferedInputStream(new DigestInputStream(fetcher.fetch(cliArchiveURL), sha256))) {
package com.jessetzh.test; import com.jessetzh.parameters.Img2ImgParameter; import com.jessetzh.parameters.SamplerEnums; import com.jessetzh.parameters.Text2ImgParameter; import com.jessetzh.request.Img2Img; import com.jessetzh.request.Text2Img; import com.jessetzh.res.SdResponses; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.math.BigDecimal; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Base64; /** * */ public class GeneratorTest { //支持直接使用 gradio.live WebUI 地址调用 static final String URL = "https://xxxxxxxxxxxxx.gradio.live/"; public static void main(String[] args) throws IOException { new GeneratorTest().img2imgTest(); } private void text2ImgText() throws IOException { Text2ImgParameter parameter = new Text2ImgParameter(URL); //如需要代理则解开下列代码注释 // parameter.getBasicParameter().setProxyEnable(true); // parameter.getBasicParameter().setProxyHost("127.0.0.1"); // parameter.getBasicParameter().setProxyPort(7890); parameter.setPrompt("One Golden Retriever"); SdResponses res = Text2Img.generate(parameter); for (String image : res.getImages()) { BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(Base64.getDecoder().decode(image))); File output = new File("image.png"); ImageIO.write(bufferedImage, "png", output); } } private void img2imgTest() throws IOException { Img2ImgParameter parameter = new Img2ImgParameter(URL); //重绘幅度
parameter.setDenoisingStrength(new BigDecimal("0.55"));
parameter.setSeed(-1); parameter.setSteps(30); parameter.setCfgScale(7); parameter.setWidth(512); parameter.setHeight(512); parameter.setSamplerName(SamplerEnums.DPM_2M_Karras.getInfo()); Path path = Paths.get("test.jpeg"); byte[] bytes = Files.readAllBytes(path); Base64.Encoder encoder = Base64.getEncoder(); String base64String = encoder.encodeToString(bytes); parameter.setInit_images(new String[]{base64String}); parameter.setPrompt("dog"); parameter.setNegativePrompt("cat"); SdResponses res = Img2Img.generate(parameter); for (String image : res.getImages()) { BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(Base64.getDecoder().decode(image))); File output = new File("image.png"); ImageIO.write(bufferedImage, "png", output); System.out.println(res.getInfo()); } } }
src/main/java/com/jessetzh/test/GeneratorTest.java
JesseTzh-stable-diffusion-java-20f5a07
[ { "filename": "src/main/java/com/jessetzh/request/Img2Img.java", "retrieved_chunk": "public class Img2Img {\n\tprivate static final String API_PATH = \"/sdapi/v1/img2img\";\n\tpublic static SdResponses generate(Img2ImgParameter parameter) throws IOException {\n\t\tHttpClientBuilder builder = HttpClients.custom();\n\t\tBasicParameterHandler.check(parameter.getBasicParameter(), builder);\n\t\tparameter.getBasicParameter().setApiUrl(parameter.getBasicParameter().getApiUrl() + API_PATH);\n\t\tHttpPost httpPost = new HttpPost(parameter.getBasicParameter().getApiUrl());\n\t\tStringEntity entity = new StringEntity(new GsonBuilder().create().toJson(parameter));\n\t\treturn RequestExecutor.execute(builder, entity, httpPost);\n\t}", "score": 0.7000884413719177 }, { "filename": "src/main/java/com/jessetzh/request/Text2Img.java", "retrieved_chunk": "public class Text2Img {\n\tprivate static final String API_PATH = \"/sdapi/v1/img2img\";\n\tpublic static SdResponses generate(Text2ImgParameter parameter) throws IOException {\n\t\tHttpClientBuilder builder = HttpClients.custom();\n\t\tBasicParameterHandler.check(parameter.getBasicParameter(), builder);\n\t\tparameter.getBasicParameter().setApiUrl(parameter.getBasicParameter().getApiUrl() + API_PATH);\n\t\tHttpPost httpPost = new HttpPost(parameter.getBasicParameter().getApiUrl());\n\t\tStringEntity entity = new StringEntity(new GsonBuilder().create().toJson(parameter));\n\t\treturn RequestExecutor.execute(builder, entity, httpPost);\n\t}", "score": 0.6904401779174805 }, { "filename": "src/main/java/com/jessetzh/parameters/Text2ImgParameter.java", "retrieved_chunk": "package com.jessetzh.parameters;\npublic class Text2ImgParameter extends SdParameter{\n\tpublic Text2ImgParameter() {\n\t\tsuper();\n\t}\n\tpublic Text2ImgParameter(String url) {\n\t\tsuper(url);\n\t}\n}", "score": 0.6802958250045776 }, { "filename": "src/main/java/com/jessetzh/res/SdResponses.java", "retrieved_chunk": "\t\tthis.images = images;\n\t}\n\tpublic SdParameter getParameters() {\n\t\treturn parameters;\n\t}\n\tpublic void setParameters(SdParameter parameters) {\n\t\tthis.parameters = parameters;\n\t}\n\t\tpublic String getInfo() {\n\t\treturn info;", "score": 0.6431784629821777 }, { "filename": "src/main/java/com/jessetzh/request/RequestExecutor.java", "retrieved_chunk": "\t\ttry {\n\t\t\thttpClient = builder.build();\n\t\t\tlong startTime = System.currentTimeMillis();\n\t\t\tresponse = httpClient.execute(httpPost);\n\t\t\tSystem.out.println(\"Request duration: \" + (System.currentTimeMillis() - startTime) + \"ms\");\n\t\t\t// Process the request result.\n\t\t\tSdResHandler.process(response);\n\t\t\tGson gson = new Gson();\n\t\t\tresponses = gson.fromJson(new InputStreamReader(response.getEntity().getContent()), SdResponses.class);\n\t\t} catch (StableDiffusionException e) {", "score": 0.6264358162879944 } ]
java
parameter.setDenoisingStrength(new BigDecimal("0.55"));
package com.rosan.dhizuku.api; import android.content.ComponentName; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import androidx.annotation.NonNull; import com.rosan.dhizuku.aidl.IDhizuku; import com.rosan.dhizuku.aidl.IDhizukuUserServiceConnection; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; class DhizukuServiceConnections { static final IDhizukuUserServiceConnection iDhizukuUserServiceConnection = new IDhizukuUserServiceConnection.Stub() { @Override public void connected(Bundle bundle, IBinder service) { onServiceConnected(bundle, service); try { service.linkToDeath(() -> { died(bundle); }, 0); } catch (RemoteException ignored) { } } void onServiceConnected(Bundle bundle, IBinder service) { DhizukuUserServiceArgs args = new DhizukuUserServiceArgs(bundle); ComponentName name = args.getComponentName(); String token = name.flattenToString(); services.put(token, service); DhizukuServiceConnection serviceConnection = map.get(token); if (serviceConnection == null) return; serviceConnection.onServiceConnected(name, service); } @Override public void died(Bundle bundle) { DhizukuUserServiceArgs args = new DhizukuUserServiceArgs(bundle); ComponentName name = args.getComponentName(); String token = name.flattenToString(); services.remove(token); DhizukuServiceConnection serviceConnection = map.get(token); if (serviceConnection == null) return; serviceConnection.onServiceDisconnected(name); } }; private static final Map<String, DhizukuServiceConnection> map = new HashMap<>(); private static final Map<String, IBinder> services = new HashMap<>(); static void start(@NonNull IDhizuku dhizuku, @NonNull DhizukuUserServiceArgs args) throws RemoteException { ComponentName name = args.getComponentName(); String token = name.flattenToString(); IBinder service = services.get(token); if (service == null) dhizuku.bindUserService(iDhizukuUserServiceConnection, args.build()); } static void stop(@NonNull IDhizuku dhizuku, @NonNull DhizukuUserServiceArgs args) throws RemoteException { dhizuku.unbindUserService(args.build()); } static void bind(@NonNull IDhizuku dhizuku, @NonNull DhizukuUserServiceArgs args, @NonNull ServiceConnection connection) throws RemoteException { ComponentName name = args.getComponentName(); String token = name.flattenToString(); DhizukuServiceConnection serviceConnection = map.get(token); if (serviceConnection == null) { serviceConnection = new DhizukuServiceConnection(); map.put(token, serviceConnection); } serviceConnection.add(connection); IBinder service = services.get(token); if (service == null) dhizuku.bindUserService(iDhizukuUserServiceConnection, args.build()); else connection.onServiceConnected(name, service); } static void unbind(@NonNull IDhizuku dhizuku, @NonNull ServiceConnection connection) throws RemoteException { List<String> tokens = new ArrayList<>(); for (Map.Entry<String, DhizukuServiceConnection> entry : map.entrySet()) { String token = entry.getKey(); DhizukuServiceConnection serviceConnection = entry.getValue(); if (serviceConnection == null) { tokens.add(token); continue; } serviceConnection.remove(connection); if
(serviceConnection.isEmpty()) tokens.add(token);
} for (String token : tokens) { map.remove(token); ComponentName name = ComponentName.unflattenFromString(token); DhizukuUserServiceArgs args = new DhizukuUserServiceArgs(name); stop(dhizuku, args); } } }
dhizuku-api-impl/src/main/java/com/rosan/dhizuku/api/DhizukuServiceConnections.java
iamr0s-Dhizuku-API-009d517
[ { "filename": "dhizuku-api-impl/src/main/java/com/rosan/dhizuku/api/DhizukuServiceConnection.java", "retrieved_chunk": " for (ServiceConnection connection : connections) {\n connection.onServiceDisconnected(name);\n }\n });\n }\n void add(ServiceConnection connection) {\n connections.add(connection);\n }\n void remove(ServiceConnection connection) {\n connections.remove(connection);", "score": 0.7956676483154297 }, { "filename": "dhizuku-api-impl/src/main/java/com/rosan/dhizuku/api/DhizukuServiceConnection.java", "retrieved_chunk": " private final List<ServiceConnection> connections = new ArrayList<>();\n public void onServiceConnected(ComponentName name, IBinder service) {\n handler.post(() -> {\n for (ServiceConnection connection : connections) {\n connection.onServiceConnected(name, service);\n }\n });\n }\n public void onServiceDisconnected(ComponentName name) {\n handler.post(() -> {", "score": 0.7629654407501221 }, { "filename": "dhizuku-api-impl/src/main/java/com/rosan/dhizuku/api/DhizukuRemoteProcess.java", "retrieved_chunk": " private IDhizukuRemoteProcess remote;\n private OutputStream outputStream;\n private InputStream inputStream;\n private InputStream errorStream;\n DhizukuRemoteProcess(IDhizukuRemoteProcess remote) {\n this.remote = Objects.requireNonNull(remote);\n try {\n remote.asBinder().linkToDeath(() -> {\n DhizukuRemoteProcess.this.remote = null;\n }, 0);", "score": 0.6989141702651978 }, { "filename": "dhizuku-api-impl/src/main/java/com/rosan/dhizuku/api/Dhizuku.java", "retrieved_chunk": " e.printStackTrace();\n }\n }\n /**\n * bind a UserService.\n */\n public static boolean bindUserService(@NonNull DhizukuUserServiceArgs args, @NonNull ServiceConnection connection) {\n try {\n DhizukuServiceConnections.bind(requireServer(), args, connection);\n return true;", "score": 0.6953798532485962 }, { "filename": "dhizuku-api-impl/src/main/java/com/rosan/dhizuku/api/Dhizuku.java", "retrieved_chunk": " e.printStackTrace();\n }\n }\n /**\n * stop a UserService.\n */\n public static void stopUserService(@NonNull DhizukuUserServiceArgs args) {\n try {\n DhizukuServiceConnections.stop(requireServer(), args);\n } catch (RemoteException e) {", "score": 0.6756449937820435 } ]
java
(serviceConnection.isEmpty()) tokens.add(token);