file_id
int64
1
46.7k
content
stringlengths
14
344k
repo
stringlengths
7
109
path
stringlengths
8
171
44,566
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Asteras; /** * * @author Ηλίας */ public class LuceneConstants { public static final String CONTENTS = "fieldName"; public static final String FILE_NAME = "filename"; public static final String FILE_PATH = "filepath"; public static final int MAX_SEARCH = 10; }
IliasAlex/Asteras
src/java/Asteras/LuceneConstants.java
44,567
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Asteras; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import java.util.Collection; import java.util.Enumeration; import java.util.Map; import java.util.Scanner; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import org.jbibtex.BibTeXDatabase; import org.jbibtex.BibTeXEntry; import org.jbibtex.BibTeXParser; import org.jbibtex.ParseException; /** * * @author Ηλίας */ @MultipartConfig( fileSizeThreshold = 1024 * 1024 * 1, // 1 MB maxFileSize = 1024 * 1024 * 10, // 10 MB maxRequestSize = 1024 * 1024 * 100 // 100 MB ) public class BibFileUpload extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet BibFileUpload</title>"); out.println("</head>"); out.println("<body>"); out.println("</body>"); out.println("</html>"); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* Receive file uploaded to the Servlet from the HTML5 form */ Part filePart = request.getPart("file"); String fileName = filePart.getSubmittedFileName(); for (Part part : request.getParts()) { part.write(fileName); } File source = new File(getServletContext().getAttribute(ServletContext.TEMPDIR) + "/" + fileName); File dest = new File(System.getProperty("user.dir") + "/dit-uop-professors/" + fileName); try { ZipFile zipFile = new ZipFile(source); extractFolder(source.getAbsolutePath(), System.getProperty("user.dir") + "/dit-uop-professors/"); File zipF = new File(System.getProperty("user.dir") + "/dit-uop-professors/" + fileName); zipF.delete(); File destFolder = new File(System.getProperty("user.dir") + "/dit-uop-professors/"); for (final File fileEntry : destFolder.listFiles()) { if (fileEntry.isFile()) { parse(fileEntry.getName()); } } } catch (ZipException zipCurrupted) { copyFileUsingStream(source, dest); parse(fileName); } response.sendRedirect("http://localhost:8080/Asteras/Insert_delete"); } private void copyFileUsingStream(File source, File dest) throws IOException { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(source); os = new FileOutputStream(dest); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } } finally { is.close(); os.close(); } } private void extractFolder(String zipFile, String extractFolder) throws IOException { int BUFFER = 2048; File file = new File(zipFile); ZipFile zip = new ZipFile(file); String newPath = extractFolder; new File(newPath).mkdir(); Enumeration zipFileEntries = zip.entries(); // Process each entry while (zipFileEntries.hasMoreElements()) { // grab a zip file entry ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); String currentEntry = entry.getName(); File destFile = new File(newPath, currentEntry); //destFile = new File(newPath, destFile.getName()); File destinationParent = destFile.getParentFile(); // create the parent directory structure if needed destinationParent.mkdirs(); if (!entry.isDirectory()) { BufferedInputStream is = new BufferedInputStream(zip .getInputStream(entry)); int currentByte; // establish buffer for writing file byte data[] = new byte[BUFFER]; // write the current file to disk FileOutputStream fos = new FileOutputStream(destFile); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); // read and write until last byte is encountered while ((currentByte = is.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, currentByte); } dest.flush(); dest.close(); is.close(); } } } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> public void parse(String filename) throws IOException { File f = new File("Data/" + filename); if (f.exists() && !f.isDirectory()) { f.delete(); } try { File myObj = new File("dit-uop-professors/" + filename); FileReader myReader = new FileReader(myObj); BibTeXParser bibtexParser = new BibTeXParser(); BibTeXDatabase bib_data = bibtexParser.parse(myReader); Map<org.jbibtex.Key, org.jbibtex.BibTeXEntry> entryMap = bib_data.getEntries(); Collection<org.jbibtex.BibTeXEntry> entries = entryMap.values(); FileWriter myWriter = new FileWriter(f); for (org.jbibtex.BibTeXEntry entry : entries) { org.jbibtex.Value author = entry.getField(org.jbibtex.BibTeXEntry.KEY_AUTHOR); org.jbibtex.Value editor = entry.getField(org.jbibtex.BibTeXEntry.KEY_EDITOR); org.jbibtex.Value title = entry.getField(org.jbibtex.BibTeXEntry.KEY_TITLE); org.jbibtex.Value booktitle = entry.getField(org.jbibtex.BibTeXEntry.KEY_BOOKTITLE); org.jbibtex.Value journal = entry.getField(org.jbibtex.BibTeXEntry.KEY_JOURNAL); if (title == null) { continue; } String fname = filename.replace(".bib", ""); if( author != null && !author.toUserString().toLowerCase().contains(fname)){ continue; } if( editor != null && !editor.toUserString().toLowerCase().contains(fname)){ continue; } String title_str = title.toUserString().replaceAll("[\n\r]", " "); myWriter.write("title: " + title_str + "\n"); if (booktitle == null && journal != null) { String journal_str = journal.toUserString().replaceAll("[\n\r]", " "); myWriter.write("journal: " + journal_str + "\n"); } else if (journal == null && booktitle != null) { String booktitle_str = booktitle.toUserString().replaceAll("[\n\r]", " "); myWriter.write("booktitle: " + booktitle_str + "\n"); } } myWriter.close(); myReader.close(); } catch (ParseException e) { System.err.println(e); } } }
IliasAlex/Asteras
src/java/Asteras/BibFileUpload.java
44,578
package jenkins.plugins.http_request; import static jenkins.plugins.http_request.Registers.registerAcceptedTypeRequestChecker; import static jenkins.plugins.http_request.Registers.registerBasicAuth; import static jenkins.plugins.http_request.Registers.registerCheckBuildParameters; import static jenkins.plugins.http_request.Registers.registerCheckRequestBody; import static jenkins.plugins.http_request.Registers.registerCheckRequestBodyWithTag; import static jenkins.plugins.http_request.Registers.registerContentTypeRequestChecker; import static jenkins.plugins.http_request.Registers.registerCustomHeaders; import static jenkins.plugins.http_request.Registers.registerCustomHeadersResolved; import static jenkins.plugins.http_request.Registers.registerFileUpload; import static jenkins.plugins.http_request.Registers.registerFormAuth; import static jenkins.plugins.http_request.Registers.registerFormAuthBad; import static jenkins.plugins.http_request.Registers.registerInvalidStatusCode; import static jenkins.plugins.http_request.Registers.registerReqAction; import static jenkins.plugins.http_request.Registers.registerRequestChecker; import static jenkins.plugins.http_request.Registers.registerTimeout; import static jenkins.plugins.http_request.Registers.registerUnwrappedPutFileUpload; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.http.HttpResponse; import org.apache.http.ProtocolVersion; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicHttpResponse; import org.eclipse.jetty.server.Request; import org.junit.Assert; import org.junit.Assume; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import hudson.Functions; import hudson.model.Cause.UserIdCause; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.ParametersAction; import hudson.model.ParametersDefinitionProperty; import hudson.model.Result; import hudson.model.StringParameterDefinition; import hudson.model.StringParameterValue; import jenkins.plugins.http_request.auth.FormAuthentication; import jenkins.plugins.http_request.util.HttpRequestNameValuePair; import jenkins.plugins.http_request.util.RequestAction; /** * @author Martin d'Anjou */ public class HttpRequestTest extends HttpRequestTestBase { @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void simpleGetTest() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void quietTest() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setQuiet(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogNotContains("HttpMethod:", build); this.j.assertLogNotContains("URL:", build); this.j.assertLogNotContains("Sending request to url:", build); this.j.assertLogNotContains("Response Code:", build); } @Test public void canDetectActualContent() throws Exception { // Setup the expected pattern String findMe = ALL_IS_WELL; // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setValidResponseContent(findMe); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(findMe, build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void badContentFailsTheBuild() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setValidResponseContent("bad content"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Fail: Response doesn't contain expected content 'bad content'", build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void responseMatchAcceptedMimeType() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Expect a mime type that matches the response httpRequest.setAcceptType(MimeType.TEXT_PLAIN); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void responseDoesNotMatchAcceptedMimeTypeDoesNotFailTheBuild() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Expect a mime type that does not match the response httpRequest.setAcceptType(MimeType.TEXT_HTML); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void passBuildParametersWhenAskedAndParametersArePresent() throws Exception { // Prepare the server registerCheckBuildParameters(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/checkBuildParameters"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.addProperty(new ParametersDefinitionProperty( new StringParameterDefinition("foo", "default") )); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("foo", "value"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void replaceParametersInRequestBody() throws Exception { // Prepare the server registerCheckRequestBodyWithTag(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/checkRequestBodyWithTag"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); // Use some random body content that contains a parameter httpRequest.setRequestBody("cleanupDir=D:/continuousIntegration/deployments/Daimler/${Tag}/standalone"); // Build parameters have to be passed httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.addProperty(new ParametersDefinitionProperty( new StringParameterDefinition("Tag", "default") )); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("Tag", "trunk"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void silentlyIgnoreNonExistentBuildParameters() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters without parameters present httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void doNotPassBuildParametersWithBuildParameters() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setPassBuildParameters(false); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("foo", "value"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void passRequestBodyWhenRequestIsPostAndBodyIsPresent() throws Exception { // Prepare the server registerCheckRequestBody(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/checkRequestBody"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); httpRequest.setRequestBody("TestRequestBody"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void doNotPassRequestBodyWhenMethodIsGet() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setRequestBody("TestRequestBody"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void doAllRequestTypes() throws Exception { for (HttpMode method : HttpMode.values()) { // Prepare the server registerRequestChecker(method); doRequest(method); cleanHandlers(); } } public void doRequest(final HttpMode method) throws Exception { // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/do" + method.toString()); httpRequest.setHttpMode(method); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); if (method == HttpMode.HEAD) { return; } this.j.assertLogContains(ALL_IS_WELL, build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void invalidResponseCodeFailsTheBuild() throws Exception { // Prepare the server registerInvalidStatusCode(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/invalidStatusCode"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Throwing status 400 for test", build); this.j.assertLogContains("Fail: Status code 400 is not in the accepted range: 100:399", build); } @Test public void invalidResponseCodeIsAccepted() throws Exception { // Prepare the server registerInvalidStatusCode(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/invalidStatusCode"); httpRequest.setValidResponseCodes("100:599"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains("Throwing status 400 for test", build); this.j.assertLogContains("Success: Status code 400 is in the accepted range: 100:599", build); } @Test public void reverseRangeFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("599:100"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Interval 599:100 should be FROM less than TO", build); } @Test public void notANumberRangeValueFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("text"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Invalid number text", build); } @Test public void rangeWithTextFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("1:text"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Invalid number text", build); } @Test public void invalidRangeFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("1:2:3"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Code 1:2:3 should be an interval from:to or a single value", build); } @Test public void sendAllContentTypes() { for (MimeType mimeType : MimeType.values()) { sendContentType(mimeType); } } public void sendContentType(final MimeType mimeType) { registerContentTypeRequestChecker(mimeType, HttpMode.GET, ALL_IS_WELL); } public void sendContentType(final MimeType mimeType, String checkMessage, String body) throws Exception { // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/incoming_" + mimeType.toString()); httpRequest.setConsoleLogResponseBody(true); httpRequest.setContentType(mimeType); if (body != null) { httpRequest.setHttpMode(HttpMode.POST); httpRequest.setRequestBody(body); } // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(checkMessage, build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void sendNonAsciiRequestBody() throws Exception { registerContentTypeRequestChecker(MimeType.APPLICATION_JSON, HttpMode.POST, null); sendContentType(MimeType.APPLICATION_JSON, ALL_IS_WELL, ALL_IS_WELL); } @Test public void sendUTF8RequestBody() throws Exception { Assume.assumeFalse("TODO does not currently work on Windows", Functions.isWindows()); String notAsciiUTF8Message = "ἱερογλύφος"; registerContentTypeRequestChecker(MimeType.APPLICATION_JSON_UTF8, HttpMode.POST, null); sendContentType(MimeType.APPLICATION_JSON_UTF8, notAsciiUTF8Message, notAsciiUTF8Message); } @Test public void sendAllAcceptTypes() throws Exception { for (MimeType mimeType : MimeType.values()) { // Prepare the server registerAcceptedTypeRequestChecker(mimeType); sendAcceptType(mimeType); cleanHandlers(); } } public void sendAcceptType(final MimeType mimeType) throws Exception { // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/accept_" + mimeType.toString()); httpRequest.setConsoleLogResponseBody(true); httpRequest.setAcceptType(mimeType); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void canPutResponseInOutputFile() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setOutputFile("file.txt"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); // By default, the response is printed to the console even if an outputFile is used this.j.assertLogContains(ALL_IS_WELL, build); // The response is in the output file as well String outputFile = build.getWorkspace().child("file.txt").readToString(); Pattern p = Pattern.compile(ALL_IS_WELL); Matcher m = p.matcher(outputFile); assertTrue(m.find()); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void canPutResponseInOutputFileWhenNotSetToGoToConsole() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setOutputFile("file.txt"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); // Check that the console does NOT have the response body this.j.assertLogNotContains(ALL_IS_WELL, build); // The response is in the output file String outputFile = build.getWorkspace().child("file.txt").readToString(); Pattern p = Pattern.compile(ALL_IS_WELL); Matcher m = p.matcher(outputFile); assertTrue(m.find()); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void timeoutFailsTheBuild() throws Exception { // Prepare the server registerTimeout(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/timeout"); httpRequest.setTimeout(2); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Fail: Status code 408 is not in the accepted range: 100:399", build); } @Test public void canDoCustomHeaders() throws Exception { // Prepare the server registerCustomHeaders(); List<HttpRequestNameValuePair> customHeaders = new ArrayList<>(); customHeaders.add(new HttpRequestNameValuePair("customHeader", "value1")); customHeaders.add(new HttpRequestNameValuePair("customHeader", "value2")); HttpRequest httpRequest = new HttpRequest(baseURL() + "/customHeaders"); httpRequest.setCustomHeaders(customHeaders); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void replaceParametersInCustomHeaders() throws Exception { // Prepare the server registerCustomHeadersResolved(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/customHeadersResolved"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); // Add some custom headers List<HttpRequestNameValuePair> customHeaders = new ArrayList<>(); customHeaders.add(new HttpRequestNameValuePair("resolveCustomParam", "${Tag}")); customHeaders.add(new HttpRequestNameValuePair("resolveEnvParam", "${WORKSPACE}")); httpRequest.setCustomHeaders(customHeaders); // Activate passBuildParameters httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.addProperty(new ParametersDefinitionProperty( new StringParameterDefinition("Tag", "default"), new StringParameterDefinition("WORKSPACE", "default") )); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("Tag", "trunk"), new StringParameterValue("WORKSPACE", "C:/path/to/my/workspace"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void nonExistentBasicAuthFailsTheBuild() throws Exception { // Prepare the server registerBasicAuth(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/basicAuth"); httpRequest.setAuthentication("non-existent-key"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Authentication 'non-existent-key' doesn't exist anymore", build); } @Test public void canDoBasicDigestAuthentication() throws Exception { // Prepare the server registerBasicAuth(); // Prepare the authentication registerBasicCredential("keyname1", "username1", "password1"); registerBasicCredential("keyname2", "username2", "password2"); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/basicAuth"); httpRequest.setAuthentication("keyname1"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void testFormAuthentication() throws Exception { final String paramUsername = "username"; final String valueUsername = "user"; final String paramPassword = "password"; final String valuePassword = "pass"; final String sessionName = "VALID_SESSIONID"; registerHandler("/form-auth", HttpMode.POST, new SimpleHandler() { @Override void doHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { String username = request.getParameter(paramUsername); String password = request.getParameter(paramPassword); if (!username.equals(valueUsername) || !password.equals(valuePassword)) { response.setStatus(401); return; } response.addCookie(new Cookie(sessionName, "ok")); okAllIsWell(response); } }); registerHandler("/test-auth", HttpMode.GET, new SimpleHandler() { @Override void doHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { String jsessionValue = ""; Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { if (cookie.getName().equals(sessionName)) { jsessionValue = cookie.getValue(); break; } } if (!jsessionValue.equals("ok")) { response.setStatus(401); return; } okAllIsWell(response); } }); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<>(); params.add(new HttpRequestNameValuePair(paramUsername, valueUsername)); params.add(new HttpRequestNameValuePair(paramPassword, valuePassword)); RequestAction action = new RequestAction(new URL(baseURL() + "/form-auth"), HttpMode.POST, null, params); List<RequestAction> actions = new ArrayList<>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("Form", actions); List<FormAuthentication> formAuthList = new ArrayList<>(); formAuthList.add(formAuth); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/test-auth"); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); httpRequest.setAuthentication("Form"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void canDoFormAuthentication() throws Exception { // Prepare the server registerFormAuth(); registerReqAction(); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<>(); params.add(new HttpRequestNameValuePair("param1", "value1")); params.add(new HttpRequestNameValuePair("param2", "value2")); RequestAction action = new RequestAction(new URL(baseURL() + "/reqAction"), HttpMode.GET, null, params); List<RequestAction> actions = new ArrayList<>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname", actions); List<FormAuthentication> formAuthList = new ArrayList<>(); formAuthList.add(formAuth); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/formAuth"); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); httpRequest.setAuthentication("keyname"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void rejectedFormCredentialsFailTheBuild() throws Exception { // Prepare the server registerFormAuthBad(); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<>(); params.add(new HttpRequestNameValuePair("param1", "value1")); params.add(new HttpRequestNameValuePair("param2", "value2")); RequestAction action = new RequestAction(new URL(baseURL() + "/formAuthBad"), HttpMode.GET, null, params); List<RequestAction> actions = new ArrayList<>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname", actions); List<FormAuthentication> formAuthList = new ArrayList<>(); formAuthList.add(formAuth); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/formAuthBad"); httpRequest.setConsoleLogResponseBody(true); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); httpRequest.setAuthentication("keyname"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Error doing authentication", build); } @Test public void invalidKeyFormAuthenticationFailsTheBuild() throws Exception { // Prepare the server // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<>(); params.add(new HttpRequestNameValuePair("param1", "value1")); params.add(new HttpRequestNameValuePair("param2", "value2")); // The request action won't be sent but we need to prepare it RequestAction action = new RequestAction(new URL(baseURL() + "/non-existent"), HttpMode.GET, null, params); List<RequestAction> actions = new ArrayList<>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname", actions); List<FormAuthentication> formAuthList = new ArrayList<>(); formAuthList.add(formAuth); // Prepare HttpRequest - the actual request won't be sent HttpRequest httpRequest = new HttpRequest(baseURL() + "/non-existent"); httpRequest.setConsoleLogResponseBody(true); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); // Select a non-existent form authentication, this will error the build before any request is made httpRequest.setAuthentication("non-existent"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Authentication 'non-existent' doesn't exist anymore", build); } @Test public void responseContentSupplierHeadersFilling() throws Exception { // Prepare test context HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK"); response.setEntity(new StringEntity("TEST")); response.setHeader("Server", "Jenkins"); response.setHeader("Set-Cookie", "JSESSIONID=123456789"); response.addHeader("Set-Cookie", "JSESSIONID=abcdefghijk"); // Run test ResponseContentSupplier respSupplier = new ResponseContentSupplier(ResponseHandle.STRING, response); // Check expectations Assert.assertEquals(2, respSupplier.getHeaders().size()); Assert.assertTrue(respSupplier.getHeaders().containsKey("Server")); Assert.assertTrue(respSupplier.getHeaders().containsKey("Set-Cookie")); Assert.assertEquals(1, respSupplier.getHeaders().get("Server").size()); Assert.assertEquals(2, respSupplier.getHeaders().get("Set-Cookie").size()); Assert.assertEquals("Jenkins", respSupplier.getHeaders().get("Server").get(0)); int valuesFoundCounter = 0; for (String s : respSupplier.getHeaders().get("Set-Cookie")) { if ("JSESSIONID=123456789".equals(s)) { valuesFoundCounter++; } else if ("JSESSIONID=abcdefghijk".equals(s)) { valuesFoundCounter++; } } Assert.assertEquals(2, valuesFoundCounter); respSupplier.close(); } @Test public void responseContentSupplierHeadersCaseInsensitivity() throws Exception { // Prepare test context HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK"); response.setEntity(new StringEntity("TEST")); response.setHeader("Server", "Jenkins"); // Run test ResponseContentSupplier respSupplier = new ResponseContentSupplier(ResponseHandle.STRING, response); // Check expectations Assert.assertEquals(1, respSupplier.getHeaders().size()); Assert.assertTrue(respSupplier.getHeaders().containsKey("Server")); Assert.assertTrue(respSupplier.getHeaders().containsKey("SERVER")); Assert.assertTrue(respSupplier.getHeaders().containsKey("server")); respSupplier.close(); } @Test public void testFileUpload() throws Exception { // Prepare the server final File testFolder = folder.newFolder(); File uploadFile = File.createTempFile("upload", ".zip", testFolder); String responseText = "File upload successful!"; registerFileUpload(testFolder, uploadFile, responseText); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/uploadFile"); httpRequest.setHttpMode(HttpMode.POST); httpRequest.setValidResponseCodes("201"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setUploadFile(uploadFile.getAbsolutePath()); httpRequest.setMultipartName("file-name"); httpRequest.setContentType(MimeType.APPLICATION_ZIP); httpRequest.setAcceptType(MimeType.TEXT_PLAIN); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(responseText, build); this.j.assertLogContains("Success: Status code 201 is in the accepted range: 201", build); } @Test public void testUnwrappedPutFileUpload() throws Exception { // Prepare the server final File testFolder = folder.newFolder(); File uploadFile = File.createTempFile("upload", ".zip", testFolder); String responseText = "File upload successful!"; registerUnwrappedPutFileUpload(uploadFile, responseText); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/uploadFile/" + uploadFile.getName()); httpRequest.setHttpMode(HttpMode.PUT); httpRequest.setValidResponseCodes("201"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setUploadFile(uploadFile.getAbsolutePath()); httpRequest.setWrapAsMultipart(false); httpRequest.setContentType(MimeType.APPLICATION_ZIP); httpRequest.setAcceptType(MimeType.TEXT_PLAIN); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(responseText, build); this.j.assertLogContains("Success: Status code 201 is in the accepted range: 201", build); } @Test public void nonExistentProxyAuthFailsTheBuild() throws Exception { // Prepare the server registerBasicAuth(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/basicAuth"); httpRequest.setHttpProxy("http://proxy.example.com:8888"); httpRequest.setProxyAuthentication("non-existent-key"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Proxy authentication 'non-existent-key' doesn't exist anymore or is not a username/password credential type", build); } }
jenkinsci/http-request-plugin
src/test/java/jenkins/plugins/http_request/HttpRequestTest.java
44,579
package jenkins.plugins.http_request; import static org.junit.Assert.assertTrue; import hudson.model.FreeStyleBuild; import hudson.model.Result; import hudson.model.Cause.UserIdCause; import hudson.model.FreeStyleProject; import hudson.model.ParametersAction; import hudson.model.StringParameterValue; import java.net.URL; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import jenkins.plugins.http_request.auth.BasicDigestAuthentication; import jenkins.plugins.http_request.auth.FormAuthentication; import jenkins.plugins.http_request.util.HttpRequestNameValuePair; import jenkins.plugins.http_request.util.RequestAction; import org.apache.commons.io.FileUtils; import org.apache.http.Consts; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.ProtocolVersion; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicHttpResponse; import org.junit.Assert; import org.apache.http.entity.ContentType; import org.junit.Test; /** * @author Martin d'Anjou */ public class HttpRequestTest extends HttpRequestTestBase { @Test public void simpleGetTest() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(this.allIsWellMessage, build); } @Test public void canDetectActualContent() throws Exception { // Setup the expected pattern String findMe = this.allIsWellMessage; String findMePattern = Pattern.quote(findMe); // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL + "/doGET"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setValidResponseContent(findMe); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(findMe, build); } @Test public void badContentFailsTheBuild() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL + "/doGET"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setValidResponseContent("bad content"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); String s = FileUtils.readFileToString(build.getLogFile()); Pattern p = Pattern.compile("Fail: Response with length \\d+ doesn't contain 'bad content'"); Matcher m = p.matcher(s); assertTrue(m.find()); } @Test public void responseMatchAcceptedMimeType() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Expect a mime type that matches the response httpRequest.setAcceptType(MimeType.TEXT_PLAIN); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(this.allIsWellMessage, build); } @Test public void responseDoesNotMatchAcceptedMimeTypeDoesNotFailTheBuild() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Expect a mime type that does not match the response httpRequest.setAcceptType(MimeType.TEXT_HTML); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(this.allIsWellMessage, build); } @Test public void passBuildParametersWhenAskedAndParamtersArePresent() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL + "/checkBuildParameters"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("foo", "value"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(this.allIsWellMessage, build); } @Test public void replaceParametersInRequestBody() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL + "/checkRequestBodyWithTag"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); // Use some random body content that contains a parameter httpRequest.setRequestBody("cleanupDir=D:/continuousIntegration/deployments/Daimler/${Tag}/standalone"); // Build parameters have to be passed httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("Tag", "trunk"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(this.allIsWellMessage, build); } @Test public void silentlyIgnoreNonExistentBuildParameters() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters without parameters present httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(this.allIsWellMessage, build); } @Test public void doNotPassBuildParametersWithBuildParameters() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setPassBuildParameters(false); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("foo", "value"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(this.allIsWellMessage, build); } @Test public void passRequestBodyWhenRequestIsPostAndBodyIsPresent() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL + "/checkRequestBody"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); httpRequest.setRequestBody("TestRequestBody"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(this.allIsWellMessage, build); } @Test public void doNotPassRequestBodyWhenMethodIsGet() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setRequestBody("TestRequestBody"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(this.allIsWellMessage, build); } @Test public void doAllRequestTypes() throws Exception { for (HttpMode mode : HttpMode.values()) { doRequest(mode); } } public void doRequest(final HttpMode mode) throws Exception { // JenkinsRule doesn't support PATCH if (mode == HttpMode.PATCH) return; // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL + "/do" + mode.toString()); httpRequest.setHttpMode(mode); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); if (mode == HttpMode.HEAD) return; this.j.assertLogContains(this.allIsWellMessage, build); } @Test public void invalidResponseCodeFailsTheBuild() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL + "/invalidStatusCode"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Throwing status 400 for test", build); } @Test public void invalidResponseCodeIsAccepted() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL + "/invalidStatusCode"); httpRequest.setValidResponseCodes("100:599"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains("Throwing status 400 for test", build); } @Test public void reverseRangeFailsTheBuild() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL + "/doesNotMatter"); httpRequest.setValidResponseCodes("599:100"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void notANumberRangeValueFailsTheBuild() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL + "/doesNotMatter"); httpRequest.setValidResponseCodes("text"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void rangeWithTextFailsTheBuild() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL + "/doesNotMatter"); httpRequest.setValidResponseCodes("1:text"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void invalidRangeFailsTheBuild() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL + "/doesNotMatter"); httpRequest.setValidResponseCodes("1:2:3"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void sendAllContentTypes() throws Exception { for (MimeType mimeType : MimeType.values()) { sendContentType(mimeType); } } public void sendContentType(final MimeType mimeType) throws Exception { setupContentTypeRequestChecker(mimeType, allIsWellMessage); } public void sendContentType(final MimeType mimeType, String checkMessage, String body) throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL + "/incoming_" + mimeType.toString()); httpRequest.setConsoleLogResponseBody(true); httpRequest.setContentType(mimeType); if (body != null) { httpRequest.setHttpMode(HttpMode.POST); httpRequest.setRequestBody(body); } // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(checkMessage, build); } @Test public void sendNonAsciiRequestBody() throws Exception { setupContentTypeRequestChecker(MimeType.APPLICATION_JSON, HttpMode.POST, ""); sendContentType(MimeType.APPLICATION_JSON, allIsWellMessage, allIsWellMessage); } @Test public void sendUTF8equestBody() throws Exception { String notAsciiUTF8Message = "ἱερογλύφος"; setupContentTypeRequestChecker(MimeType.APPLICATION_JSON_UTF8, HttpMode.POST, ""); sendContentType(MimeType.APPLICATION_JSON_UTF8, notAsciiUTF8Message, notAsciiUTF8Message); } @Test public void sendAllAcceptTypes() throws Exception { for (MimeType mimeType : MimeType.values()) { sendAcceptType(mimeType); } } public void sendAcceptType(final MimeType mimeType) throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL + "/accept_" + mimeType.toString()); httpRequest.setConsoleLogResponseBody(true); httpRequest.setAcceptType(mimeType); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(this.allIsWellMessage, build); } @Test public void canPutResponseInOutputFile() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL + "/doGET"); httpRequest.setOutputFile("file.txt"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); // By default, the response is printed to the console even if an outputFile is used this.j.assertLogContains(this.allIsWellMessage, build); // The response is in the output file as well String outputFile = build.getWorkspace().child("file.txt").readToString(); Pattern p = Pattern.compile(this.allIsWellMessage); Matcher m = p.matcher(outputFile); assertTrue(m.find()); } @Test public void canPutResponseInOutputFileWhenNotSetToGoToConsole() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL + "/doGET"); httpRequest.setOutputFile("file.txt"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); // Check that the console does NOT have the response body this.j.assertLogNotContains(this.allIsWellMessage, build); // The response is in the output file String outputFile = build.getWorkspace().child("file.txt").readToString(); Pattern p = Pattern.compile(this.allIsWellMessage); Matcher m = p.matcher(outputFile); assertTrue(m.find()); } @Test public void timeoutFailsTheBuild() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL + "/timeout"); httpRequest.setTimeout(2); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void canDoCustomHeaders() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); List<HttpRequestNameValuePair> customHeaders = new ArrayList<HttpRequestNameValuePair>(); customHeaders.add(new HttpRequestNameValuePair("customHeader", "value1")); customHeaders.add(new HttpRequestNameValuePair("customHeader", "value2")); HttpRequest httpRequest = new HttpRequest(baseURL + "/customHeaders"); httpRequest.setCustomHeaders(customHeaders); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); } @Test public void replaceParametesInCustomHeaders() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL + "/customHeadersResolved"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); // Add some custom headers List<HttpRequestNameValuePair> customHeaders = new ArrayList<HttpRequestNameValuePair>(); customHeaders.add(new HttpRequestNameValuePair("resolveCustomParam", "${Tag}")); customHeaders.add(new HttpRequestNameValuePair("resolveEnvParam", "${WORKSPACE}")); httpRequest.setCustomHeaders(customHeaders); // Activate passBuildParameters httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("Tag", "trunk"), new StringParameterValue("WORKSPACE", "C:/path/to/my/workspace"))).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); this.j.assertLogContains(this.allIsWellMessage, build); } @Test public void nonExistentBasicAuthFailsTheBuild() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL + "/basicAuth"); httpRequest.setAuthentication("non-existent-key"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void canDoBasicDigestAuthentication() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare the authentication List<BasicDigestAuthentication> bda = new ArrayList<BasicDigestAuthentication>(); bda.add(new BasicDigestAuthentication("keyname1", "username1", "password1")); bda.add(new BasicDigestAuthentication("keyname2", "username2", "password2")); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL + "/basicAuth"); HttpRequestGlobalConfig.get().setBasicDigestAuthentications(bda); httpRequest.setAuthentication("keyname1"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); } @Test public void canDoFormAuthentication() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<HttpRequestNameValuePair>(); params.add(new HttpRequestNameValuePair("param1", "value1")); params.add(new HttpRequestNameValuePair("param2", "value2")); RequestAction action = new RequestAction(new URL(baseURL + "/reqAction"), HttpMode.GET, null, params); List<RequestAction> actions = new ArrayList<RequestAction>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname", actions); List<FormAuthentication> formAuthList = new ArrayList<FormAuthentication>(); formAuthList.add(formAuth); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL + "/formAuth"); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); httpRequest.setAuthentication("keyname"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); } @Test public void rejectedFormCredentialsFailTheBuild() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<HttpRequestNameValuePair>(); params.add(new HttpRequestNameValuePair("param1", "value1")); params.add(new HttpRequestNameValuePair("param2", "value2")); RequestAction action = new RequestAction(new URL(baseURL + "/formAuthBad"), HttpMode.GET, null, params); List<RequestAction> actions = new ArrayList<RequestAction>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname", actions); List<FormAuthentication> formAuthList = new ArrayList<FormAuthentication>(); formAuthList.add(formAuth); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL + "/formAuthBad"); httpRequest.setConsoleLogResponseBody(true); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); httpRequest.setAuthentication("keyname"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Error doing authentication", build); } @Test public void invalidKeyFormAuthenticationFailsTheBuild() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<HttpRequestNameValuePair>(); params.add(new HttpRequestNameValuePair("param1", "value1")); params.add(new HttpRequestNameValuePair("param2", "value2")); // The request action won't be sent but we need to prepare it RequestAction action = new RequestAction(new URL(baseURL + "/non-existent"), HttpMode.GET, null, params); List<RequestAction> actions = new ArrayList<RequestAction>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname", actions); List<FormAuthentication> formAuthList = new ArrayList<FormAuthentication>(); formAuthList.add(formAuth); // Prepare HttpRequest - the actual request won't be sent HttpRequest httpRequest = new HttpRequest(baseURL + "/non-existent"); httpRequest.setConsoleLogResponseBody(true); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); // Select a non-existent form authentication, this will error the build before any request is made httpRequest.setAuthentication("non-existent"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Authentication 'non-existent' doesn't exist anymore", build); } @Test public void responseContentSupplierHeadersFilling() throws Exception { // Prepare test context HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK"); response.setEntity(new StringEntity("TEST")); response.setHeader("Server", "Jenkins"); response.setHeader("Set-Cookie", "JSESSIONID=123456789"); response.addHeader("Set-Cookie", "JSESSIONID=abcdefghijk"); // Run test ResponseContentSupplier respSupplier = new ResponseContentSupplier(response); // Check expectations Assert.assertEquals(2, respSupplier.getHeaders().size()); Assert.assertTrue(respSupplier.getHeaders().containsKey("Server")); Assert.assertTrue(respSupplier.getHeaders().containsKey("Set-Cookie")); Assert.assertEquals(1, respSupplier.getHeaders().get("Server").size()); Assert.assertEquals(2, respSupplier.getHeaders().get("Set-Cookie").size()); Assert.assertEquals("Jenkins", respSupplier.getHeaders().get("Server").get(0)); int valuesFoundCounter = 0; for (String s : respSupplier.getHeaders().get("Set-Cookie")) { if ("JSESSIONID=123456789".equals(s)) { valuesFoundCounter++; } else if ("JSESSIONID=abcdefghijk".equals(s)) { valuesFoundCounter++; } } Assert.assertEquals(2, valuesFoundCounter); } }
mmitche/http-request-plugin
src/test/java/jenkins/plugins/http_request/HttpRequestTest.java
44,580
package jenkins.plugins.http_request; import hudson.model.Cause.UserIdCause; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.ParametersAction; import hudson.model.Result; import hudson.model.StringParameterValue; import java.net.URL; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import jenkins.plugins.http_request.auth.BasicDigestAuthentication; import jenkins.plugins.http_request.auth.FormAuthentication; import jenkins.plugins.http_request.util.HttpRequestNameValuePair; import jenkins.plugins.http_request.util.RequestAction; import org.apache.commons.io.FileUtils; import org.apache.http.Consts; import org.apache.http.HttpHost; import org.apache.http.entity.ContentType; import org.junit.Test; import static org.junit.Assert.assertTrue; /** * @author Martin d'Anjou */ public class HttpRequestTest extends HttpRequestTestBase { @Test public void simpleGetTest() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL+"/doGET"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations j.assertBuildStatusSuccess(build); j.assertLogContains(allIsWellMessage,build); } @Test public void canDetectActualContent() throws Exception { // Setup the expected pattern String findMe = allIsWellMessage; String findMePattern = Pattern.quote(findMe); // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL+"/doGET"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setValidResponseContent(findMe); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations j.assertBuildStatusSuccess(build); j.assertLogContains(findMe,build); } @Test public void badContentFailsTheBuild() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL+"/doGET"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setValidResponseContent("bad content"); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations j.assertBuildStatus(Result.FAILURE, build); String s = FileUtils.readFileToString(build.getLogFile()); Pattern p = Pattern.compile("Fail: Response with length \\d+ doesn't contain 'bad content'"); Matcher m = p.matcher(s); assertTrue(m.find()); } @Test public void responseMatchAcceptedMimeType() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL+"/doGET"); httpRequest.setConsoleLogResponseBody(true); // Expect a mime type that matches the response httpRequest.setAcceptType(MimeType.TEXT_PLAIN); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations j.assertBuildStatusSuccess(build); j.assertLogContains(allIsWellMessage,build); } @Test public void responseDoesNotMatchAcceptedMimeTypeDoesNotFailTheBuild() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL+"/doGET"); httpRequest.setConsoleLogResponseBody(true); // Expect a mime type that does not match the response httpRequest.setAcceptType(MimeType.TEXT_HTML); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations j.assertBuildStatusSuccess(build); j.assertLogContains(allIsWellMessage,build); } @Test public void passBuildParametersWhenAskedAndParamtersArePresent() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL+"/checkBuildParameters"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("foo","value")) ).get(); // Check expectations j.assertBuildStatusSuccess(build); j.assertLogContains(allIsWellMessage,build); } @Test public void replaceParametersInRequestBody() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL+"/checkRequestBodyWithTag"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); // Use some random body content that contains a parameter httpRequest.setRequestBody("cleanupDir=D:/continuousIntegration/deployments/Daimler/${Tag}/standalone"); // Build parameters have to be passed httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("Tag","trunk")) ).get(); // Check expectations j.assertBuildStatusSuccess(build); j.assertLogContains(allIsWellMessage,build); } @Test public void silentlyIgnoreNonExistentBuildParameters() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL+"/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters without parameters present httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations j.assertBuildStatusSuccess(build); j.assertLogContains(allIsWellMessage,build); } @Test public void doNotPassBuildParametersWithBuildParameters() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL+"/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setPassBuildParameters(false); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("foo","value")) ).get(); // Check expectations j.assertBuildStatusSuccess(build); j.assertLogContains(allIsWellMessage,build); } @Test public void passRequestBodyWhenRequestIsPostAndBodyIsPresent() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL+"/checkRequestBody"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); httpRequest.setRequestBody("TestRequestBody"); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations j.assertBuildStatusSuccess(build); j.assertLogContains(allIsWellMessage,build); } @Test public void doNotPassRequestBodyWhenMethodIsGet() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL+"/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setRequestBody("TestRequestBody"); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations j.assertBuildStatusSuccess(build); j.assertLogContains(allIsWellMessage,build); } @Test public void doAllRequestTypes() throws Exception { for (HttpMode mode: HttpMode.values()) { doRequest(mode); } } public void doRequest(final HttpMode mode) throws Exception { //JenkinsRule doesn't support PATCH if (mode == HttpMode.PATCH) return; // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL+"/do"+mode.toString()); httpRequest.setHttpMode(mode); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations j.assertBuildStatusSuccess(build); if (mode == HttpMode.HEAD) return; j.assertLogContains(allIsWellMessage,build); } @Test public void invalidResponseCodeFailsTheBuild() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL+"/invalidStatusCode"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations j.assertBuildStatus(Result.FAILURE, build); j.assertLogContains("Throwing status 400 for test",build); } @Test public void invalidResponseCodeIsAccepted() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL+"/invalidStatusCode"); httpRequest.setValidResponseCodes("100:599"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations j.assertBuildStatusSuccess(build); j.assertLogContains("Throwing status 400 for test",build); } @Test public void reverseRangeFailsTheBuild() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL+"/doesNotMatter"); httpRequest.setValidResponseCodes("599:100"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations j.assertBuildStatus(Result.FAILURE, build); } @Test public void notANumberRangeValueFailsTheBuild() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL+"/doesNotMatter"); httpRequest.setValidResponseCodes("text"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations j.assertBuildStatus(Result.FAILURE, build); } @Test public void rangeWithTextFailsTheBuild() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL+"/doesNotMatter"); httpRequest.setValidResponseCodes("1:text"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations j.assertBuildStatus(Result.FAILURE, build); } @Test public void invalidRangeFailsTheBuild() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL+"/doesNotMatter"); httpRequest.setValidResponseCodes("1:2:3"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations j.assertBuildStatus(Result.FAILURE, build); } @Test public void sendAllContentTypes() throws Exception { for (MimeType mimeType : MimeType.values()) { sendContentType(mimeType); } } public void sendContentType(final MimeType mimeType) throws Exception { setupContentTypeRequestChecker(mimeType, allIsWellMessage); } public void sendContentType(final MimeType mimeType, String checkMessage, String body) throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL+"/incoming_"+mimeType.toString()); httpRequest.setConsoleLogResponseBody(true); httpRequest.setContentType(mimeType); if (body != null) { httpRequest.setHttpMode(HttpMode.POST); httpRequest.setRequestBody(body); } // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations j.assertBuildStatusSuccess(build); j.assertLogContains(checkMessage,build); } @Test public void sendNonAsciiRequestBody() throws Exception { setupContentTypeRequestChecker(MimeType.APPLICATION_JSON, HttpMode.POST, ""); sendContentType(MimeType.APPLICATION_JSON, allIsWellMessage, allIsWellMessage); } @Test public void sendUTF8equestBody() throws Exception { String notAsciiUTF8Message = "ἱερογλύφος"; setupContentTypeRequestChecker(MimeType.APPLICATION_JSON_UTF8, HttpMode.POST, ""); sendContentType(MimeType.APPLICATION_JSON_UTF8, notAsciiUTF8Message, notAsciiUTF8Message); } @Test public void sendAllAcceptTypes() throws Exception { for (MimeType mimeType : MimeType.values()) { sendAcceptType(mimeType); } } public void sendAcceptType(final MimeType mimeType) throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL+"/accept_"+mimeType.toString()); httpRequest.setConsoleLogResponseBody(true); httpRequest.setAcceptType(mimeType); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations j.assertBuildStatusSuccess(build); j.assertLogContains(allIsWellMessage,build); } @Test public void canPutResponseInOutputFile() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL+"/doGET"); httpRequest.setOutputFile("file.txt"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations j.assertBuildStatusSuccess(build); // By default, the response is printed to the console even if an outputFile is used j.assertLogContains(allIsWellMessage,build); // The response is in the output file as well String outputFile = build.getWorkspace().child("file.txt").readToString(); Pattern p = Pattern.compile(allIsWellMessage); Matcher m = p.matcher(outputFile); assertTrue(m.find()); } @Test public void canPutResponseInOutputFileWhenNotSetToGoToConsole() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL+"/doGET"); httpRequest.setOutputFile("file.txt"); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations j.assertBuildStatusSuccess(build); // Check that the console does NOT have the response body j.assertLogNotContains(allIsWellMessage,build); // The response is in the output file String outputFile = build.getWorkspace().child("file.txt").readToString(); Pattern p = Pattern.compile(allIsWellMessage); Matcher m = p.matcher(outputFile); assertTrue(m.find()); } @Test public void timeoutFailsTheBuild() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL+"/timeout"); httpRequest.setTimeout(2); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations j.assertBuildStatus(Result.FAILURE, build); } @Test public void canDoCustomHeaders() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); List<HttpRequestNameValuePair> customHeaders = new ArrayList<HttpRequestNameValuePair>(); customHeaders.add(new HttpRequestNameValuePair("customHeader","value1")); customHeaders.add(new HttpRequestNameValuePair("customHeader","value2")); HttpRequest httpRequest = new HttpRequest(baseURL+"/customHeaders"); httpRequest.setCustomHeaders(customHeaders); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations j.assertBuildStatus(Result.SUCCESS, build); } @Test public void replaceParametesInCustomHeaders() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL+"/customHeadersResolved"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); // Add some custom headers List<HttpRequestNameValuePair> customHeaders = new ArrayList<HttpRequestNameValuePair>(); customHeaders.add(new HttpRequestNameValuePair("resolveCustomParam","${Tag}")); customHeaders.add(new HttpRequestNameValuePair("resolveEnvParam","${WORKSPACE}")); httpRequest.setCustomHeaders(customHeaders); // Activate passBuildParameters httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("Tag","trunk"), new StringParameterValue("WORKSPACE", "C:/path/to/my/workspace")) ).get(); // Check expectations j.assertBuildStatus(Result.SUCCESS, build); j.assertLogContains(allIsWellMessage,build); } @Test public void nonExistentBasicAuthFailsTheBuild() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL+"/basicAuth"); httpRequest.setAuthentication("non-existent-key"); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations j.assertBuildStatus(Result.FAILURE, build); } @Test public void canDoBasicDigestAuthentication() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare the authentication List<BasicDigestAuthentication> bda = new ArrayList<BasicDigestAuthentication>(); bda.add(new BasicDigestAuthentication("keyname1","username1","password1")); bda.add(new BasicDigestAuthentication("keyname2","username2","password2")); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL+"/basicAuth"); HttpRequestGlobalConfig.get().setBasicDigestAuthentications(bda); httpRequest.setAuthentication("keyname1"); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations j.assertBuildStatus(Result.SUCCESS, build); } @Test public void canDoFormAuthentication() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<HttpRequestNameValuePair>(); params.add(new HttpRequestNameValuePair("param1","value1")); params.add(new HttpRequestNameValuePair("param2","value2")); RequestAction action = new RequestAction(new URL(baseURL+"/reqAction"),HttpMode.GET,null,params); List<RequestAction> actions = new ArrayList<RequestAction>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname",actions); List<FormAuthentication> formAuthList = new ArrayList<FormAuthentication>(); formAuthList.add(formAuth); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL+"/formAuth"); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); httpRequest.setAuthentication("keyname"); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations j.assertBuildStatus(Result.SUCCESS, build); } @Test public void rejectedFormCredentialsFailTheBuild() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<HttpRequestNameValuePair>(); params.add(new HttpRequestNameValuePair("param1","value1")); params.add(new HttpRequestNameValuePair("param2","value2")); RequestAction action = new RequestAction(new URL(baseURL+"/formAuthBad"),HttpMode.GET,null,params); List<RequestAction> actions = new ArrayList<RequestAction>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname",actions); List<FormAuthentication> formAuthList = new ArrayList<FormAuthentication>(); formAuthList.add(formAuth); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL+"/formAuthBad"); httpRequest.setConsoleLogResponseBody(true); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); httpRequest.setAuthentication("keyname"); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations j.assertBuildStatus(Result.FAILURE, build); j.assertLogContains("Error doing authentication",build); } @Test public void invalidKeyFormAuthenticationFailsTheBuild() throws Exception { // Prepare the server final HttpHost target = start(); final String baseURL = "http://localhost:" + target.getPort(); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<HttpRequestNameValuePair>(); params.add(new HttpRequestNameValuePair("param1","value1")); params.add(new HttpRequestNameValuePair("param2","value2")); // The request action won't be sent but we need to prepare it RequestAction action = new RequestAction(new URL(baseURL+"/non-existent"),HttpMode.GET,null,params); List<RequestAction> actions = new ArrayList<RequestAction>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname",actions); List<FormAuthentication> formAuthList = new ArrayList<FormAuthentication>(); formAuthList.add(formAuth); // Prepare HttpRequest - the actual request won't be sent HttpRequest httpRequest = new HttpRequest(baseURL+"/non-existent"); httpRequest.setConsoleLogResponseBody(true); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); // Select a non-existent form authentication, this will error the build before any request is made httpRequest.setAuthentication("non-existent"); // Run build FreeStyleProject project = j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations j.assertBuildStatus(Result.FAILURE, build); j.assertLogContains("Authentication 'non-existent' doesn't exist anymore",build); } }
vaimr/http-request-plugin
src/test/java/jenkins/plugins/http_request/HttpRequestTest.java
44,581
package jenkins.plugins.http_request; import static jenkins.plugins.http_request.Registers.registerAcceptedTypeRequestChecker; import static jenkins.plugins.http_request.Registers.registerBasicAuth; import static jenkins.plugins.http_request.Registers.registerCheckBuildParameters; import static jenkins.plugins.http_request.Registers.registerCheckRequestBody; import static jenkins.plugins.http_request.Registers.registerCheckRequestBodyWithTag; import static jenkins.plugins.http_request.Registers.registerContentTypeRequestChecker; import static jenkins.plugins.http_request.Registers.registerCustomHeaders; import static jenkins.plugins.http_request.Registers.registerCustomHeadersResolved; import static jenkins.plugins.http_request.Registers.registerFormAuth; import static jenkins.plugins.http_request.Registers.registerFormAuthBad; import static jenkins.plugins.http_request.Registers.registerInvalidStatusCode; import static jenkins.plugins.http_request.Registers.registerReqAction; import static jenkins.plugins.http_request.Registers.registerRequestChecker; import static jenkins.plugins.http_request.Registers.registerTimeout; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.http.HttpResponse; import org.apache.http.ProtocolVersion; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicHttpResponse; import org.eclipse.jetty.server.Request; import org.junit.Assert; import org.junit.Test; import hudson.model.Cause.UserIdCause; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.ParametersAction; import hudson.model.Result; import hudson.model.StringParameterValue; import jenkins.plugins.http_request.auth.FormAuthentication; import jenkins.plugins.http_request.util.HttpRequestNameValuePair; import jenkins.plugins.http_request.util.RequestAction; /** * @author Martin d'Anjou */ public class HttpRequestTest extends HttpRequestTestBase { @Test public void simpleGetTest() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void quietTest() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setQuiet(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogNotContains("HttpMethod:", build); this.j.assertLogNotContains("URL:", build); this.j.assertLogNotContains("Sending request to url:", build); this.j.assertLogNotContains("Response Code:", build); } @Test public void canDetectActualContent() throws Exception { // Setup the expected pattern String findMe = ALL_IS_WELL; // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setValidResponseContent(findMe); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(findMe, build); } @Test public void badContentFailsTheBuild() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setValidResponseContent("bad content"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); String s = FileUtils.readFileToString(build.getLogFile()); assertTrue(s.contains("Fail: Response doesn't contain expected content 'bad content'")); } @Test public void responseMatchAcceptedMimeType() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Expect a mime type that matches the response httpRequest.setAcceptType(MimeType.TEXT_PLAIN); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void responseDoesNotMatchAcceptedMimeTypeDoesNotFailTheBuild() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Expect a mime type that does not match the response httpRequest.setAcceptType(MimeType.TEXT_HTML); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void passBuildParametersWhenAskedAndParamtersArePresent() throws Exception { // Prepare the server registerCheckBuildParameters(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/checkBuildParameters"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("foo", "value"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void replaceParametersInRequestBody() throws Exception { // Prepare the server registerCheckRequestBodyWithTag(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/checkRequestBodyWithTag"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); // Use some random body content that contains a parameter httpRequest.setRequestBody("cleanupDir=D:/continuousIntegration/deployments/Daimler/${Tag}/standalone"); // Build parameters have to be passed httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("Tag", "trunk"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void silentlyIgnoreNonExistentBuildParameters() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters without parameters present httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void doNotPassBuildParametersWithBuildParameters() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setPassBuildParameters(false); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("foo", "value"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void passRequestBodyWhenRequestIsPostAndBodyIsPresent() throws Exception { // Prepare the server registerCheckRequestBody(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/checkRequestBody"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); httpRequest.setRequestBody("TestRequestBody"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void doNotPassRequestBodyWhenMethodIsGet() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setRequestBody("TestRequestBody"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void doAllRequestTypes() throws Exception { for (HttpMode method : HttpMode.values()) { // Prepare the server registerRequestChecker(method); doRequest(method); cleanHandlers(); } } public void doRequest(final HttpMode method) throws Exception { // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/do" + method.toString()); httpRequest.setHttpMode(method); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); if (method == HttpMode.HEAD) { return; } this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void invalidResponseCodeFailsTheBuild() throws Exception { // Prepare the server registerInvalidStatusCode(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/invalidStatusCode"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Throwing status 400 for test", build); } @Test public void invalidResponseCodeIsAccepted() throws Exception { // Prepare the server registerInvalidStatusCode(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/invalidStatusCode"); httpRequest.setValidResponseCodes("100:599"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains("Throwing status 400 for test", build); } @Test public void reverseRangeFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("599:100"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void notANumberRangeValueFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("text"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void rangeWithTextFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("1:text"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void invalidRangeFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("1:2:3"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void sendAllContentTypes() throws Exception { for (MimeType mimeType : MimeType.values()) { sendContentType(mimeType); } } public void sendContentType(final MimeType mimeType) throws Exception { registerContentTypeRequestChecker(mimeType, HttpMode.GET, ALL_IS_WELL); } public void sendContentType(final MimeType mimeType, String checkMessage, String body) throws Exception { // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/incoming_" + mimeType.toString()); httpRequest.setConsoleLogResponseBody(true); httpRequest.setContentType(mimeType); if (body != null) { httpRequest.setHttpMode(HttpMode.POST); httpRequest.setRequestBody(body); } // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(checkMessage, build); } @Test public void sendNonAsciiRequestBody() throws Exception { registerContentTypeRequestChecker(MimeType.APPLICATION_JSON, HttpMode.POST, null); sendContentType(MimeType.APPLICATION_JSON, ALL_IS_WELL, ALL_IS_WELL); } @Test public void sendUTF8equestBody() throws Exception { String notAsciiUTF8Message = "ἱερογλύφος"; registerContentTypeRequestChecker(MimeType.APPLICATION_JSON_UTF8, HttpMode.POST, null); sendContentType(MimeType.APPLICATION_JSON_UTF8, notAsciiUTF8Message, notAsciiUTF8Message); } @Test public void sendAllAcceptTypes() throws Exception { for (MimeType mimeType : MimeType.values()) { // Prepare the server registerAcceptedTypeRequestChecker(mimeType); sendAcceptType(mimeType); cleanHandlers(); } } public void sendAcceptType(final MimeType mimeType) throws Exception { // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/accept_" + mimeType.toString()); httpRequest.setConsoleLogResponseBody(true); httpRequest.setAcceptType(mimeType); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void canPutResponseInOutputFile() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setOutputFile("file.txt"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); // By default, the response is printed to the console even if an outputFile is used this.j.assertLogContains(ALL_IS_WELL, build); // The response is in the output file as well String outputFile = build.getWorkspace().child("file.txt").readToString(); Pattern p = Pattern.compile(ALL_IS_WELL); Matcher m = p.matcher(outputFile); assertTrue(m.find()); } @Test public void canPutResponseInOutputFileWhenNotSetToGoToConsole() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setOutputFile("file.txt"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); // Check that the console does NOT have the response body this.j.assertLogNotContains(ALL_IS_WELL, build); // The response is in the output file String outputFile = build.getWorkspace().child("file.txt").readToString(); Pattern p = Pattern.compile(ALL_IS_WELL); Matcher m = p.matcher(outputFile); assertTrue(m.find()); } @Test public void timeoutFailsTheBuild() throws Exception { // Prepare the server registerTimeout(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/timeout"); httpRequest.setTimeout(2); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void canDoCustomHeaders() throws Exception { // Prepare the server registerCustomHeaders(); List<HttpRequestNameValuePair> customHeaders = new ArrayList<HttpRequestNameValuePair>(); customHeaders.add(new HttpRequestNameValuePair("customHeader", "value1")); customHeaders.add(new HttpRequestNameValuePair("customHeader", "value2")); HttpRequest httpRequest = new HttpRequest(baseURL() + "/customHeaders"); httpRequest.setCustomHeaders(customHeaders); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); } @Test public void replaceParametesInCustomHeaders() throws Exception { // Prepare the server registerCustomHeadersResolved(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/customHeadersResolved"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); // Add some custom headers List<HttpRequestNameValuePair> customHeaders = new ArrayList<HttpRequestNameValuePair>(); customHeaders.add(new HttpRequestNameValuePair("resolveCustomParam", "${Tag}")); customHeaders.add(new HttpRequestNameValuePair("resolveEnvParam", "${WORKSPACE}")); httpRequest.setCustomHeaders(customHeaders); // Activate passBuildParameters httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("Tag", "trunk"), new StringParameterValue("WORKSPACE", "C:/path/to/my/workspace"))).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void nonExistentBasicAuthFailsTheBuild() throws Exception { // Prepare the server registerBasicAuth(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/basicAuth"); httpRequest.setAuthentication("non-existent-key"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void canDoBasicDigestAuthentication() throws Exception { // Prepare the server registerBasicAuth(); // Prepare the authentication registerBasicCredential("keyname1", "username1", "password1"); registerBasicCredential("keyname2", "username2", "password2"); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/basicAuth"); httpRequest.setAuthentication("keyname1"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); } @Test public void testFormAuthentication() throws Exception { final String paramUsername = "username"; final String valueUsername = "user"; final String paramPassword = "password"; final String valuePassword = "pass"; final String sessionName = "VALID_SESSIONID"; registerHandler("/form-auth", HttpMode.POST, new SimpleHandler() { @Override void doHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String username = request.getParameter(paramUsername); String password = request.getParameter(paramPassword); if (!username.equals(valueUsername) || !password.equals(valuePassword)) { response.setStatus(401); return; } response.addCookie(new Cookie(sessionName, "ok")); okAllIsWell(response); } }); registerHandler("/test-auth", HttpMode.GET, new SimpleHandler() { @Override void doHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String jsessionValue = ""; Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { if (cookie.getName().equals(sessionName)) { jsessionValue = cookie.getValue(); break; } } if (!jsessionValue.equals("ok")) { response.setStatus(401); return; } okAllIsWell(response); } }); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<>(); params.add(new HttpRequestNameValuePair(paramUsername, valueUsername)); params.add(new HttpRequestNameValuePair(paramPassword, valuePassword)); RequestAction action = new RequestAction(new URL(baseURL() + "/form-auth"), HttpMode.POST, null, params); List<RequestAction> actions = new ArrayList<RequestAction>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("Form", actions); List<FormAuthentication> formAuthList = new ArrayList<FormAuthentication>(); formAuthList.add(formAuth); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/test-auth"); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); httpRequest.setAuthentication("Form"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); } @Test public void canDoFormAuthentication() throws Exception { // Prepare the server registerFormAuth(); registerReqAction(); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<HttpRequestNameValuePair>(); params.add(new HttpRequestNameValuePair("param1", "value1")); params.add(new HttpRequestNameValuePair("param2", "value2")); RequestAction action = new RequestAction(new URL(baseURL() + "/reqAction"), HttpMode.GET, null, params); List<RequestAction> actions = new ArrayList<RequestAction>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname", actions); List<FormAuthentication> formAuthList = new ArrayList<FormAuthentication>(); formAuthList.add(formAuth); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/formAuth"); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); httpRequest.setAuthentication("keyname"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); } @Test public void rejectedFormCredentialsFailTheBuild() throws Exception { // Prepare the server registerFormAuthBad(); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<HttpRequestNameValuePair>(); params.add(new HttpRequestNameValuePair("param1", "value1")); params.add(new HttpRequestNameValuePair("param2", "value2")); RequestAction action = new RequestAction(new URL(baseURL() + "/formAuthBad"), HttpMode.GET, null, params); List<RequestAction> actions = new ArrayList<RequestAction>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname", actions); List<FormAuthentication> formAuthList = new ArrayList<FormAuthentication>(); formAuthList.add(formAuth); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/formAuthBad"); httpRequest.setConsoleLogResponseBody(true); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); httpRequest.setAuthentication("keyname"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Error doing authentication", build); } @Test public void invalidKeyFormAuthenticationFailsTheBuild() throws Exception { // Prepare the server // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<HttpRequestNameValuePair>(); params.add(new HttpRequestNameValuePair("param1", "value1")); params.add(new HttpRequestNameValuePair("param2", "value2")); // The request action won't be sent but we need to prepare it RequestAction action = new RequestAction(new URL(baseURL() + "/non-existent"), HttpMode.GET, null, params); List<RequestAction> actions = new ArrayList<RequestAction>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname", actions); List<FormAuthentication> formAuthList = new ArrayList<FormAuthentication>(); formAuthList.add(formAuth); // Prepare HttpRequest - the actual request won't be sent HttpRequest httpRequest = new HttpRequest(baseURL() + "/non-existent"); httpRequest.setConsoleLogResponseBody(true); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); // Select a non-existent form authentication, this will error the build before any request is made httpRequest.setAuthentication("non-existent"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Authentication 'non-existent' doesn't exist anymore", build); } @Test public void responseContentSupplierHeadersFilling() throws Exception { // Prepare test context HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK"); response.setEntity(new StringEntity("TEST")); response.setHeader("Server", "Jenkins"); response.setHeader("Set-Cookie", "JSESSIONID=123456789"); response.addHeader("Set-Cookie", "JSESSIONID=abcdefghijk"); // Run test ResponseContentSupplier respSupplier = new ResponseContentSupplier(ResponseHandle.STRING, response); // Check expectations Assert.assertEquals(2, respSupplier.getHeaders().size()); Assert.assertTrue(respSupplier.getHeaders().containsKey("Server")); Assert.assertTrue(respSupplier.getHeaders().containsKey("Set-Cookie")); Assert.assertEquals(1, respSupplier.getHeaders().get("Server").size()); Assert.assertEquals(2, respSupplier.getHeaders().get("Set-Cookie").size()); Assert.assertEquals("Jenkins", respSupplier.getHeaders().get("Server").get(0)); int valuesFoundCounter = 0; for (String s : respSupplier.getHeaders().get("Set-Cookie")) { if ("JSESSIONID=123456789".equals(s)) { valuesFoundCounter++; } else if ("JSESSIONID=abcdefghijk".equals(s)) { valuesFoundCounter++; } } Assert.assertEquals(2, valuesFoundCounter); } }
LinuxSuRen/http-request-plugin
src/test/java/jenkins/plugins/http_request/HttpRequestTest.java
44,582
package jenkins.plugins.http_request; import static jenkins.plugins.http_request.Registers.registerFileUpload; import static jenkins.plugins.http_request.Registers.registerAcceptedTypeRequestChecker; import static jenkins.plugins.http_request.Registers.registerBasicAuth; import static jenkins.plugins.http_request.Registers.registerCheckBuildParameters; import static jenkins.plugins.http_request.Registers.registerCheckRequestBody; import static jenkins.plugins.http_request.Registers.registerCheckRequestBodyWithTag; import static jenkins.plugins.http_request.Registers.registerContentTypeRequestChecker; import static jenkins.plugins.http_request.Registers.registerCustomHeaders; import static jenkins.plugins.http_request.Registers.registerCustomHeadersResolved; import static jenkins.plugins.http_request.Registers.registerFormAuth; import static jenkins.plugins.http_request.Registers.registerFormAuthBad; import static jenkins.plugins.http_request.Registers.registerInvalidStatusCode; import static jenkins.plugins.http_request.Registers.registerReqAction; import static jenkins.plugins.http_request.Registers.registerRequestChecker; import static jenkins.plugins.http_request.Registers.registerTimeout; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.http.HttpResponse; import org.apache.http.ProtocolVersion; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicHttpResponse; import org.eclipse.jetty.server.Request; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import hudson.model.Cause.UserIdCause; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.ParametersAction; import hudson.model.ParametersDefinitionProperty; import hudson.model.Result; import hudson.model.StringParameterDefinition; import hudson.model.StringParameterValue; import jenkins.plugins.http_request.auth.FormAuthentication; import jenkins.plugins.http_request.util.HttpRequestNameValuePair; import jenkins.plugins.http_request.util.RequestAction; /** * @author Martin d'Anjou */ public class HttpRequestTest extends HttpRequestTestBase { @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void simpleGetTest() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void quietTest() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setQuiet(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogNotContains("HttpMethod:", build); this.j.assertLogNotContains("URL:", build); this.j.assertLogNotContains("Sending request to url:", build); this.j.assertLogNotContains("Response Code:", build); } @Test public void canDetectActualContent() throws Exception { // Setup the expected pattern String findMe = ALL_IS_WELL; // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setValidResponseContent(findMe); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(findMe, build); } @Test public void badContentFailsTheBuild() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setValidResponseContent("bad content"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); String s = FileUtils.readFileToString(build.getLogFile()); assertTrue(s.contains("Fail: Response doesn't contain expected content 'bad content'")); } @Test public void responseMatchAcceptedMimeType() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Expect a mime type that matches the response httpRequest.setAcceptType(MimeType.TEXT_PLAIN); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void responseDoesNotMatchAcceptedMimeTypeDoesNotFailTheBuild() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Expect a mime type that does not match the response httpRequest.setAcceptType(MimeType.TEXT_HTML); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void passBuildParametersWhenAskedAndParametersArePresent() throws Exception { // Prepare the server registerCheckBuildParameters(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/checkBuildParameters"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.addProperty(new ParametersDefinitionProperty( new StringParameterDefinition("foo", "default") )); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("foo", "value"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void replaceParametersInRequestBody() throws Exception { // Prepare the server registerCheckRequestBodyWithTag(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/checkRequestBodyWithTag"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); // Use some random body content that contains a parameter httpRequest.setRequestBody("cleanupDir=D:/continuousIntegration/deployments/Daimler/${Tag}/standalone"); // Build parameters have to be passed httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.addProperty(new ParametersDefinitionProperty( new StringParameterDefinition("Tag", "default") )); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("Tag", "trunk"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void silentlyIgnoreNonExistentBuildParameters() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters without parameters present httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void doNotPassBuildParametersWithBuildParameters() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setPassBuildParameters(false); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("foo", "value"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void passRequestBodyWhenRequestIsPostAndBodyIsPresent() throws Exception { // Prepare the server registerCheckRequestBody(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/checkRequestBody"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); httpRequest.setRequestBody("TestRequestBody"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void doNotPassRequestBodyWhenMethodIsGet() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setRequestBody("TestRequestBody"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void doAllRequestTypes() throws Exception { for (HttpMode method : HttpMode.values()) { // Prepare the server registerRequestChecker(method); doRequest(method); cleanHandlers(); } } public void doRequest(final HttpMode method) throws Exception { // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/do" + method.toString()); httpRequest.setHttpMode(method); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); if (method == HttpMode.HEAD) { return; } this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void invalidResponseCodeFailsTheBuild() throws Exception { // Prepare the server registerInvalidStatusCode(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/invalidStatusCode"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Throwing status 400 for test", build); } @Test public void invalidResponseCodeIsAccepted() throws Exception { // Prepare the server registerInvalidStatusCode(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/invalidStatusCode"); httpRequest.setValidResponseCodes("100:599"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains("Throwing status 400 for test", build); } @Test public void reverseRangeFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("599:100"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void notANumberRangeValueFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("text"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void rangeWithTextFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("1:text"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void invalidRangeFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("1:2:3"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void sendAllContentTypes() throws Exception { for (MimeType mimeType : MimeType.values()) { sendContentType(mimeType); } } public void sendContentType(final MimeType mimeType) throws Exception { registerContentTypeRequestChecker(mimeType, HttpMode.GET, ALL_IS_WELL); } public void sendContentType(final MimeType mimeType, String checkMessage, String body) throws Exception { // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/incoming_" + mimeType.toString()); httpRequest.setConsoleLogResponseBody(true); httpRequest.setContentType(mimeType); if (body != null) { httpRequest.setHttpMode(HttpMode.POST); httpRequest.setRequestBody(body); } // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(checkMessage, build); } @Test public void sendNonAsciiRequestBody() throws Exception { registerContentTypeRequestChecker(MimeType.APPLICATION_JSON, HttpMode.POST, null); sendContentType(MimeType.APPLICATION_JSON, ALL_IS_WELL, ALL_IS_WELL); } @Test public void sendUTF8RequestBody() throws Exception { String notAsciiUTF8Message = "ἱερογλύφος"; registerContentTypeRequestChecker(MimeType.APPLICATION_JSON_UTF8, HttpMode.POST, null); sendContentType(MimeType.APPLICATION_JSON_UTF8, notAsciiUTF8Message, notAsciiUTF8Message); } @Test public void sendAllAcceptTypes() throws Exception { for (MimeType mimeType : MimeType.values()) { // Prepare the server registerAcceptedTypeRequestChecker(mimeType); sendAcceptType(mimeType); cleanHandlers(); } } public void sendAcceptType(final MimeType mimeType) throws Exception { // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/accept_" + mimeType.toString()); httpRequest.setConsoleLogResponseBody(true); httpRequest.setAcceptType(mimeType); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void canPutResponseInOutputFile() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setOutputFile("file.txt"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); // By default, the response is printed to the console even if an outputFile is used this.j.assertLogContains(ALL_IS_WELL, build); // The response is in the output file as well String outputFile = build.getWorkspace().child("file.txt").readToString(); Pattern p = Pattern.compile(ALL_IS_WELL); Matcher m = p.matcher(outputFile); assertTrue(m.find()); } @Test public void canPutResponseInOutputFileWhenNotSetToGoToConsole() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setOutputFile("file.txt"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); // Check that the console does NOT have the response body this.j.assertLogNotContains(ALL_IS_WELL, build); // The response is in the output file String outputFile = build.getWorkspace().child("file.txt").readToString(); Pattern p = Pattern.compile(ALL_IS_WELL); Matcher m = p.matcher(outputFile); assertTrue(m.find()); } @Test public void timeoutFailsTheBuild() throws Exception { // Prepare the server registerTimeout(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/timeout"); httpRequest.setTimeout(2); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void canDoCustomHeaders() throws Exception { // Prepare the server registerCustomHeaders(); List<HttpRequestNameValuePair> customHeaders = new ArrayList<>(); customHeaders.add(new HttpRequestNameValuePair("customHeader", "value1")); customHeaders.add(new HttpRequestNameValuePair("customHeader", "value2")); HttpRequest httpRequest = new HttpRequest(baseURL() + "/customHeaders"); httpRequest.setCustomHeaders(customHeaders); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); } @Test public void replaceParametersInCustomHeaders() throws Exception { // Prepare the server registerCustomHeadersResolved(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/customHeadersResolved"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); // Add some custom headers List<HttpRequestNameValuePair> customHeaders = new ArrayList<>(); customHeaders.add(new HttpRequestNameValuePair("resolveCustomParam", "${Tag}")); customHeaders.add(new HttpRequestNameValuePair("resolveEnvParam", "${WORKSPACE}")); httpRequest.setCustomHeaders(customHeaders); // Activate passBuildParameters httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.addProperty(new ParametersDefinitionProperty( new StringParameterDefinition("Tag", "default"), new StringParameterDefinition("WORKSPACE", "default") )); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("Tag", "trunk"), new StringParameterValue("WORKSPACE", "C:/path/to/my/workspace"))).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void nonExistentBasicAuthFailsTheBuild() throws Exception { // Prepare the server registerBasicAuth(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/basicAuth"); httpRequest.setAuthentication("non-existent-key"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void canDoBasicDigestAuthentication() throws Exception { // Prepare the server registerBasicAuth(); // Prepare the authentication registerBasicCredential("keyname1", "username1", "password1"); registerBasicCredential("keyname2", "username2", "password2"); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/basicAuth"); httpRequest.setAuthentication("keyname1"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); } @Test public void testFormAuthentication() throws Exception { final String paramUsername = "username"; final String valueUsername = "user"; final String paramPassword = "password"; final String valuePassword = "pass"; final String sessionName = "VALID_SESSIONID"; registerHandler("/form-auth", HttpMode.POST, new SimpleHandler() { @Override void doHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String username = request.getParameter(paramUsername); String password = request.getParameter(paramPassword); if (!username.equals(valueUsername) || !password.equals(valuePassword)) { response.setStatus(401); return; } response.addCookie(new Cookie(sessionName, "ok")); okAllIsWell(response); } }); registerHandler("/test-auth", HttpMode.GET, new SimpleHandler() { @Override void doHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String jsessionValue = ""; Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { if (cookie.getName().equals(sessionName)) { jsessionValue = cookie.getValue(); break; } } if (!jsessionValue.equals("ok")) { response.setStatus(401); return; } okAllIsWell(response); } }); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<>(); params.add(new HttpRequestNameValuePair(paramUsername, valueUsername)); params.add(new HttpRequestNameValuePair(paramPassword, valuePassword)); RequestAction action = new RequestAction(new URL(baseURL() + "/form-auth"), HttpMode.POST, null, params); List<RequestAction> actions = new ArrayList<>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("Form", actions); List<FormAuthentication> formAuthList = new ArrayList<>(); formAuthList.add(formAuth); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/test-auth"); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); httpRequest.setAuthentication("Form"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); } @Test public void canDoFormAuthentication() throws Exception { // Prepare the server registerFormAuth(); registerReqAction(); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<>(); params.add(new HttpRequestNameValuePair("param1", "value1")); params.add(new HttpRequestNameValuePair("param2", "value2")); RequestAction action = new RequestAction(new URL(baseURL() + "/reqAction"), HttpMode.GET, null, params); List<RequestAction> actions = new ArrayList<>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname", actions); List<FormAuthentication> formAuthList = new ArrayList<>(); formAuthList.add(formAuth); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/formAuth"); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); httpRequest.setAuthentication("keyname"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); } @Test public void rejectedFormCredentialsFailTheBuild() throws Exception { // Prepare the server registerFormAuthBad(); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<>(); params.add(new HttpRequestNameValuePair("param1", "value1")); params.add(new HttpRequestNameValuePair("param2", "value2")); RequestAction action = new RequestAction(new URL(baseURL() + "/formAuthBad"), HttpMode.GET, null, params); List<RequestAction> actions = new ArrayList<>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname", actions); List<FormAuthentication> formAuthList = new ArrayList<>(); formAuthList.add(formAuth); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/formAuthBad"); httpRequest.setConsoleLogResponseBody(true); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); httpRequest.setAuthentication("keyname"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Error doing authentication", build); } @Test public void invalidKeyFormAuthenticationFailsTheBuild() throws Exception { // Prepare the server // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<>(); params.add(new HttpRequestNameValuePair("param1", "value1")); params.add(new HttpRequestNameValuePair("param2", "value2")); // The request action won't be sent but we need to prepare it RequestAction action = new RequestAction(new URL(baseURL() + "/non-existent"), HttpMode.GET, null, params); List<RequestAction> actions = new ArrayList<>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname", actions); List<FormAuthentication> formAuthList = new ArrayList<>(); formAuthList.add(formAuth); // Prepare HttpRequest - the actual request won't be sent HttpRequest httpRequest = new HttpRequest(baseURL() + "/non-existent"); httpRequest.setConsoleLogResponseBody(true); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); // Select a non-existent form authentication, this will error the build before any request is made httpRequest.setAuthentication("non-existent"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Authentication 'non-existent' doesn't exist anymore", build); } @Test public void responseContentSupplierHeadersFilling() throws Exception { // Prepare test context HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK"); response.setEntity(new StringEntity("TEST")); response.setHeader("Server", "Jenkins"); response.setHeader("Set-Cookie", "JSESSIONID=123456789"); response.addHeader("Set-Cookie", "JSESSIONID=abcdefghijk"); // Run test ResponseContentSupplier respSupplier = new ResponseContentSupplier(ResponseHandle.STRING, response); // Check expectations Assert.assertEquals(2, respSupplier.getHeaders().size()); Assert.assertTrue(respSupplier.getHeaders().containsKey("Server")); Assert.assertTrue(respSupplier.getHeaders().containsKey("Set-Cookie")); Assert.assertEquals(1, respSupplier.getHeaders().get("Server").size()); Assert.assertEquals(2, respSupplier.getHeaders().get("Set-Cookie").size()); Assert.assertEquals("Jenkins", respSupplier.getHeaders().get("Server").get(0)); int valuesFoundCounter = 0; for (String s : respSupplier.getHeaders().get("Set-Cookie")) { if ("JSESSIONID=123456789".equals(s)) { valuesFoundCounter++; } else if ("JSESSIONID=abcdefghijk".equals(s)) { valuesFoundCounter++; } } Assert.assertEquals(2, valuesFoundCounter); respSupplier.close(); } @Test public void testFileUpload() throws Exception { // Prepare the server final File testFolder = folder.newFolder(); File uploadFile = File.createTempFile("upload", ".zip", testFolder); String responseText = "File upload successful!"; registerFileUpload(testFolder, uploadFile, responseText); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/uploadFile"); httpRequest.setHttpMode(HttpMode.POST); httpRequest.setValidResponseCodes("201"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setUploadFile(uploadFile.getAbsolutePath()); httpRequest.setMultipartName("file-name"); httpRequest.setContentType(MimeType.APPLICATION_ZIP); httpRequest.setAcceptType(MimeType.TEXT_PLAIN); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(responseText, build); } }
hummerstudio/http-request-plugin
src/test/java/jenkins/plugins/http_request/HttpRequestTest.java
44,583
package jenkins.plugins.http_request; import static jenkins.plugins.http_request.Registers.registerAcceptedTypeRequestChecker; import static jenkins.plugins.http_request.Registers.registerBasicAuth; import static jenkins.plugins.http_request.Registers.registerCheckBuildParameters; import static jenkins.plugins.http_request.Registers.registerCheckRequestBody; import static jenkins.plugins.http_request.Registers.registerCheckRequestBodyWithTag; import static jenkins.plugins.http_request.Registers.registerContentTypeRequestChecker; import static jenkins.plugins.http_request.Registers.registerCustomHeaders; import static jenkins.plugins.http_request.Registers.registerCustomHeadersResolved; import static jenkins.plugins.http_request.Registers.registerFileUpload; import static jenkins.plugins.http_request.Registers.registerFormAuth; import static jenkins.plugins.http_request.Registers.registerFormAuthBad; import static jenkins.plugins.http_request.Registers.registerInvalidStatusCode; import static jenkins.plugins.http_request.Registers.registerReqAction; import static jenkins.plugins.http_request.Registers.registerRequestChecker; import static jenkins.plugins.http_request.Registers.registerTimeout; import static jenkins.plugins.http_request.Registers.registerUnwrappedPutFileUpload; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.http.HttpResponse; import org.apache.http.ProtocolVersion; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicHttpResponse; import org.eclipse.jetty.server.Request; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import hudson.model.Cause.UserIdCause; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.ParametersAction; import hudson.model.ParametersDefinitionProperty; import hudson.model.Result; import hudson.model.StringParameterDefinition; import hudson.model.StringParameterValue; import jenkins.plugins.http_request.auth.FormAuthentication; import jenkins.plugins.http_request.util.HttpRequestNameValuePair; import jenkins.plugins.http_request.util.RequestAction; /** * @author Martin d'Anjou */ public class HttpRequestTest extends HttpRequestTestBase { @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void simpleGetTest() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void quietTest() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setQuiet(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogNotContains("HttpMethod:", build); this.j.assertLogNotContains("URL:", build); this.j.assertLogNotContains("Sending request to url:", build); this.j.assertLogNotContains("Response Code:", build); } @Test public void canDetectActualContent() throws Exception { // Setup the expected pattern String findMe = ALL_IS_WELL; // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setValidResponseContent(findMe); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(findMe, build); } @Test public void badContentFailsTheBuild() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setValidResponseContent("bad content"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); String s = FileUtils.readFileToString(build.getLogFile()); assertTrue(s.contains("Fail: Response doesn't contain expected content 'bad content'")); } @Test public void responseMatchAcceptedMimeType() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Expect a mime type that matches the response httpRequest.setAcceptType(MimeType.TEXT_PLAIN); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void responseDoesNotMatchAcceptedMimeTypeDoesNotFailTheBuild() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Expect a mime type that does not match the response httpRequest.setAcceptType(MimeType.TEXT_HTML); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void passBuildParametersWhenAskedAndParametersArePresent() throws Exception { // Prepare the server registerCheckBuildParameters(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/checkBuildParameters"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.addProperty(new ParametersDefinitionProperty( new StringParameterDefinition("foo", "default") )); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("foo", "value"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void replaceParametersInRequestBody() throws Exception { // Prepare the server registerCheckRequestBodyWithTag(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/checkRequestBodyWithTag"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); // Use some random body content that contains a parameter httpRequest.setRequestBody("cleanupDir=D:/continuousIntegration/deployments/Daimler/${Tag}/standalone"); // Build parameters have to be passed httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.addProperty(new ParametersDefinitionProperty( new StringParameterDefinition("Tag", "default") )); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("Tag", "trunk"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void silentlyIgnoreNonExistentBuildParameters() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters without parameters present httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void doNotPassBuildParametersWithBuildParameters() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setPassBuildParameters(false); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("foo", "value"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void passRequestBodyWhenRequestIsPostAndBodyIsPresent() throws Exception { // Prepare the server registerCheckRequestBody(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/checkRequestBody"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); httpRequest.setRequestBody("TestRequestBody"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void doNotPassRequestBodyWhenMethodIsGet() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setRequestBody("TestRequestBody"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void doAllRequestTypes() throws Exception { for (HttpMode method : HttpMode.values()) { // Prepare the server registerRequestChecker(method); doRequest(method); cleanHandlers(); } } public void doRequest(final HttpMode method) throws Exception { // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/do" + method.toString()); httpRequest.setHttpMode(method); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); if (method == HttpMode.HEAD) { return; } this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void invalidResponseCodeFailsTheBuild() throws Exception { // Prepare the server registerInvalidStatusCode(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/invalidStatusCode"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Throwing status 400 for test", build); } @Test public void invalidResponseCodeIsAccepted() throws Exception { // Prepare the server registerInvalidStatusCode(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/invalidStatusCode"); httpRequest.setValidResponseCodes("100:599"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains("Throwing status 400 for test", build); } @Test public void reverseRangeFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("599:100"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void notANumberRangeValueFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("text"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void rangeWithTextFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("1:text"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void invalidRangeFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("1:2:3"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void sendAllContentTypes() throws Exception { for (MimeType mimeType : MimeType.values()) { sendContentType(mimeType); } } public void sendContentType(final MimeType mimeType) throws Exception { registerContentTypeRequestChecker(mimeType, HttpMode.GET, ALL_IS_WELL); } public void sendContentType(final MimeType mimeType, String checkMessage, String body) throws Exception { // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/incoming_" + mimeType.toString()); httpRequest.setConsoleLogResponseBody(true); httpRequest.setContentType(mimeType); if (body != null) { httpRequest.setHttpMode(HttpMode.POST); httpRequest.setRequestBody(body); } // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(checkMessage, build); } @Test public void sendNonAsciiRequestBody() throws Exception { registerContentTypeRequestChecker(MimeType.APPLICATION_JSON, HttpMode.POST, null); sendContentType(MimeType.APPLICATION_JSON, ALL_IS_WELL, ALL_IS_WELL); } @Test public void sendUTF8RequestBody() throws Exception { String notAsciiUTF8Message = "ἱερογλύφος"; registerContentTypeRequestChecker(MimeType.APPLICATION_JSON_UTF8, HttpMode.POST, null); sendContentType(MimeType.APPLICATION_JSON_UTF8, notAsciiUTF8Message, notAsciiUTF8Message); } @Test public void sendAllAcceptTypes() throws Exception { for (MimeType mimeType : MimeType.values()) { // Prepare the server registerAcceptedTypeRequestChecker(mimeType); sendAcceptType(mimeType); cleanHandlers(); } } public void sendAcceptType(final MimeType mimeType) throws Exception { // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/accept_" + mimeType.toString()); httpRequest.setConsoleLogResponseBody(true); httpRequest.setAcceptType(mimeType); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void canPutResponseInOutputFile() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setOutputFile("file.txt"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); // By default, the response is printed to the console even if an outputFile is used this.j.assertLogContains(ALL_IS_WELL, build); // The response is in the output file as well String outputFile = build.getWorkspace().child("file.txt").readToString(); Pattern p = Pattern.compile(ALL_IS_WELL); Matcher m = p.matcher(outputFile); assertTrue(m.find()); } @Test public void canPutResponseInOutputFileWhenNotSetToGoToConsole() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setOutputFile("file.txt"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); // Check that the console does NOT have the response body this.j.assertLogNotContains(ALL_IS_WELL, build); // The response is in the output file String outputFile = build.getWorkspace().child("file.txt").readToString(); Pattern p = Pattern.compile(ALL_IS_WELL); Matcher m = p.matcher(outputFile); assertTrue(m.find()); } @Test public void timeoutFailsTheBuild() throws Exception { // Prepare the server registerTimeout(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/timeout"); httpRequest.setTimeout(2); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void canDoCustomHeaders() throws Exception { // Prepare the server registerCustomHeaders(); List<HttpRequestNameValuePair> customHeaders = new ArrayList<>(); customHeaders.add(new HttpRequestNameValuePair("customHeader", "value1")); customHeaders.add(new HttpRequestNameValuePair("customHeader", "value2")); HttpRequest httpRequest = new HttpRequest(baseURL() + "/customHeaders"); httpRequest.setCustomHeaders(customHeaders); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); } @Test public void replaceParametersInCustomHeaders() throws Exception { // Prepare the server registerCustomHeadersResolved(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/customHeadersResolved"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); // Add some custom headers List<HttpRequestNameValuePair> customHeaders = new ArrayList<>(); customHeaders.add(new HttpRequestNameValuePair("resolveCustomParam", "${Tag}")); customHeaders.add(new HttpRequestNameValuePair("resolveEnvParam", "${WORKSPACE}")); httpRequest.setCustomHeaders(customHeaders); // Activate passBuildParameters httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.addProperty(new ParametersDefinitionProperty( new StringParameterDefinition("Tag", "default"), new StringParameterDefinition("WORKSPACE", "default") )); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("Tag", "trunk"), new StringParameterValue("WORKSPACE", "C:/path/to/my/workspace"))).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void nonExistentBasicAuthFailsTheBuild() throws Exception { // Prepare the server registerBasicAuth(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/basicAuth"); httpRequest.setAuthentication("non-existent-key"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void canDoBasicDigestAuthentication() throws Exception { // Prepare the server registerBasicAuth(); // Prepare the authentication registerBasicCredential("keyname1", "username1", "password1"); registerBasicCredential("keyname2", "username2", "password2"); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/basicAuth"); httpRequest.setAuthentication("keyname1"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); } @Test public void testFormAuthentication() throws Exception { final String paramUsername = "username"; final String valueUsername = "user"; final String paramPassword = "password"; final String valuePassword = "pass"; final String sessionName = "VALID_SESSIONID"; registerHandler("/form-auth", HttpMode.POST, new SimpleHandler() { @Override void doHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String username = request.getParameter(paramUsername); String password = request.getParameter(paramPassword); if (!username.equals(valueUsername) || !password.equals(valuePassword)) { response.setStatus(401); return; } response.addCookie(new Cookie(sessionName, "ok")); okAllIsWell(response); } }); registerHandler("/test-auth", HttpMode.GET, new SimpleHandler() { @Override void doHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String jsessionValue = ""; Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { if (cookie.getName().equals(sessionName)) { jsessionValue = cookie.getValue(); break; } } if (!jsessionValue.equals("ok")) { response.setStatus(401); return; } okAllIsWell(response); } }); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<>(); params.add(new HttpRequestNameValuePair(paramUsername, valueUsername)); params.add(new HttpRequestNameValuePair(paramPassword, valuePassword)); RequestAction action = new RequestAction(new URL(baseURL() + "/form-auth"), HttpMode.POST, null, params); List<RequestAction> actions = new ArrayList<>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("Form", actions); List<FormAuthentication> formAuthList = new ArrayList<>(); formAuthList.add(formAuth); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/test-auth"); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); httpRequest.setAuthentication("Form"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); } @Test public void canDoFormAuthentication() throws Exception { // Prepare the server registerFormAuth(); registerReqAction(); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<>(); params.add(new HttpRequestNameValuePair("param1", "value1")); params.add(new HttpRequestNameValuePair("param2", "value2")); RequestAction action = new RequestAction(new URL(baseURL() + "/reqAction"), HttpMode.GET, null, params); List<RequestAction> actions = new ArrayList<>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname", actions); List<FormAuthentication> formAuthList = new ArrayList<>(); formAuthList.add(formAuth); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/formAuth"); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); httpRequest.setAuthentication("keyname"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); } @Test public void rejectedFormCredentialsFailTheBuild() throws Exception { // Prepare the server registerFormAuthBad(); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<>(); params.add(new HttpRequestNameValuePair("param1", "value1")); params.add(new HttpRequestNameValuePair("param2", "value2")); RequestAction action = new RequestAction(new URL(baseURL() + "/formAuthBad"), HttpMode.GET, null, params); List<RequestAction> actions = new ArrayList<>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname", actions); List<FormAuthentication> formAuthList = new ArrayList<>(); formAuthList.add(formAuth); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/formAuthBad"); httpRequest.setConsoleLogResponseBody(true); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); httpRequest.setAuthentication("keyname"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Error doing authentication", build); } @Test public void invalidKeyFormAuthenticationFailsTheBuild() throws Exception { // Prepare the server // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<>(); params.add(new HttpRequestNameValuePair("param1", "value1")); params.add(new HttpRequestNameValuePair("param2", "value2")); // The request action won't be sent but we need to prepare it RequestAction action = new RequestAction(new URL(baseURL() + "/non-existent"), HttpMode.GET, null, params); List<RequestAction> actions = new ArrayList<>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname", actions); List<FormAuthentication> formAuthList = new ArrayList<>(); formAuthList.add(formAuth); // Prepare HttpRequest - the actual request won't be sent HttpRequest httpRequest = new HttpRequest(baseURL() + "/non-existent"); httpRequest.setConsoleLogResponseBody(true); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); // Select a non-existent form authentication, this will error the build before any request is made httpRequest.setAuthentication("non-existent"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Authentication 'non-existent' doesn't exist anymore", build); } @Test public void responseContentSupplierHeadersFilling() throws Exception { // Prepare test context HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK"); response.setEntity(new StringEntity("TEST")); response.setHeader("Server", "Jenkins"); response.setHeader("Set-Cookie", "JSESSIONID=123456789"); response.addHeader("Set-Cookie", "JSESSIONID=abcdefghijk"); // Run test ResponseContentSupplier respSupplier = new ResponseContentSupplier(ResponseHandle.STRING, response); // Check expectations Assert.assertEquals(2, respSupplier.getHeaders().size()); Assert.assertTrue(respSupplier.getHeaders().containsKey("Server")); Assert.assertTrue(respSupplier.getHeaders().containsKey("Set-Cookie")); Assert.assertEquals(1, respSupplier.getHeaders().get("Server").size()); Assert.assertEquals(2, respSupplier.getHeaders().get("Set-Cookie").size()); Assert.assertEquals("Jenkins", respSupplier.getHeaders().get("Server").get(0)); int valuesFoundCounter = 0; for (String s : respSupplier.getHeaders().get("Set-Cookie")) { if ("JSESSIONID=123456789".equals(s)) { valuesFoundCounter++; } else if ("JSESSIONID=abcdefghijk".equals(s)) { valuesFoundCounter++; } } Assert.assertEquals(2, valuesFoundCounter); respSupplier.close(); } @Test public void testFileUpload() throws Exception { // Prepare the server final File testFolder = folder.newFolder(); File uploadFile = File.createTempFile("upload", ".zip", testFolder); String responseText = "File upload successful!"; registerFileUpload(testFolder, uploadFile, responseText); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/uploadFile"); httpRequest.setHttpMode(HttpMode.POST); httpRequest.setValidResponseCodes("201"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setUploadFile(uploadFile.getAbsolutePath()); httpRequest.setMultipartName("file-name"); httpRequest.setContentType(MimeType.APPLICATION_ZIP); httpRequest.setAcceptType(MimeType.TEXT_PLAIN); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(responseText, build); } @Test public void testUnwrappedPutFileUpload() throws Exception { // Prepare the server final File testFolder = folder.newFolder(); File uploadFile = File.createTempFile("upload", ".zip", testFolder); String responseText = "File upload successful!"; registerUnwrappedPutFileUpload(uploadFile, responseText); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/uploadFile/" + uploadFile.getName()); httpRequest.setHttpMode(HttpMode.PUT); httpRequest.setValidResponseCodes("201"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setUploadFile(uploadFile.getAbsolutePath()); httpRequest.setWrapAsMultipart(false); httpRequest.setContentType(MimeType.APPLICATION_ZIP); httpRequest.setAcceptType(MimeType.TEXT_PLAIN); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(responseText, build); } }
timja/http-request-plugin
src/test/java/jenkins/plugins/http_request/HttpRequestTest.java
44,584
package jenkins.plugins.http_request; import static jenkins.plugins.http_request.Registers.registerAcceptedTypeRequestChecker; import static jenkins.plugins.http_request.Registers.registerBasicAuth; import static jenkins.plugins.http_request.Registers.registerCheckBuildParameters; import static jenkins.plugins.http_request.Registers.registerCheckRequestBody; import static jenkins.plugins.http_request.Registers.registerCheckRequestBodyWithTag; import static jenkins.plugins.http_request.Registers.registerContentTypeRequestChecker; import static jenkins.plugins.http_request.Registers.registerCustomHeaders; import static jenkins.plugins.http_request.Registers.registerCustomHeadersResolved; import static jenkins.plugins.http_request.Registers.registerFileUpload; import static jenkins.plugins.http_request.Registers.registerFormAuth; import static jenkins.plugins.http_request.Registers.registerFormAuthBad; import static jenkins.plugins.http_request.Registers.registerInvalidStatusCode; import static jenkins.plugins.http_request.Registers.registerReqAction; import static jenkins.plugins.http_request.Registers.registerRequestChecker; import static jenkins.plugins.http_request.Registers.registerTimeout; import static jenkins.plugins.http_request.Registers.registerUnwrappedPutFileUpload; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.http.HttpResponse; import org.apache.http.ProtocolVersion; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicHttpResponse; import org.eclipse.jetty.server.Request; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import hudson.model.Cause.UserIdCause; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.ParametersAction; import hudson.model.ParametersDefinitionProperty; import hudson.model.Result; import hudson.model.StringParameterDefinition; import hudson.model.StringParameterValue; import jenkins.plugins.http_request.auth.FormAuthentication; import jenkins.plugins.http_request.util.HttpRequestNameValuePair; import jenkins.plugins.http_request.util.RequestAction; /** * @author Martin d'Anjou */ public class HttpRequestTest extends HttpRequestTestBase { @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void simpleGetTest() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void quietTest() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setQuiet(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogNotContains("HttpMethod:", build); this.j.assertLogNotContains("URL:", build); this.j.assertLogNotContains("Sending request to url:", build); this.j.assertLogNotContains("Response Code:", build); } @Test public void canDetectActualContent() throws Exception { // Setup the expected pattern String findMe = ALL_IS_WELL; // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setValidResponseContent(findMe); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(findMe, build); } @Test public void badContentFailsTheBuild() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setValidResponseContent("bad content"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); String s = FileUtils.readFileToString(build.getLogFile()); assertTrue(s.contains("Fail: Response doesn't contain expected content 'bad content'")); } @Test public void responseMatchAcceptedMimeType() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Expect a mime type that matches the response httpRequest.setAcceptType(MimeType.TEXT_PLAIN); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void responseDoesNotMatchAcceptedMimeTypeDoesNotFailTheBuild() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Expect a mime type that does not match the response httpRequest.setAcceptType(MimeType.TEXT_HTML); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void passBuildParametersWhenAskedAndParametersArePresent() throws Exception { // Prepare the server registerCheckBuildParameters(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/checkBuildParameters"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.addProperty(new ParametersDefinitionProperty( new StringParameterDefinition("foo", "default") )); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("foo", "value"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void replaceParametersInRequestBody() throws Exception { // Prepare the server registerCheckRequestBodyWithTag(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/checkRequestBodyWithTag"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); // Use some random body content that contains a parameter httpRequest.setRequestBody("cleanupDir=D:/continuousIntegration/deployments/Daimler/${Tag}/standalone"); // Build parameters have to be passed httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.addProperty(new ParametersDefinitionProperty( new StringParameterDefinition("Tag", "default") )); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("Tag", "trunk"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void silentlyIgnoreNonExistentBuildParameters() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters without parameters present httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void doNotPassBuildParametersWithBuildParameters() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setPassBuildParameters(false); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("foo", "value"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void passRequestBodyWhenRequestIsPostAndBodyIsPresent() throws Exception { // Prepare the server registerCheckRequestBody(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/checkRequestBody"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); httpRequest.setRequestBody("TestRequestBody"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void doNotPassRequestBodyWhenMethodIsGet() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setRequestBody("TestRequestBody"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void doAllRequestTypes() throws Exception { for (HttpMode method : HttpMode.values()) { // Prepare the server registerRequestChecker(method); doRequest(method); cleanHandlers(); } } public void doRequest(final HttpMode method) throws Exception { // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/do" + method.toString()); httpRequest.setHttpMode(method); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); if (method == HttpMode.HEAD) { return; } this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void invalidResponseCodeFailsTheBuild() throws Exception { // Prepare the server registerInvalidStatusCode(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/invalidStatusCode"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Throwing status 400 for test", build); } @Test public void invalidResponseCodeIsAccepted() throws Exception { // Prepare the server registerInvalidStatusCode(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/invalidStatusCode"); httpRequest.setValidResponseCodes("100:599"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains("Throwing status 400 for test", build); } @Test public void reverseRangeFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("599:100"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void notANumberRangeValueFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("text"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void rangeWithTextFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("1:text"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void invalidRangeFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("1:2:3"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void sendAllContentTypes() throws Exception { for (MimeType mimeType : MimeType.values()) { sendContentType(mimeType); } } public void sendContentType(final MimeType mimeType) throws Exception { registerContentTypeRequestChecker(mimeType, HttpMode.GET, ALL_IS_WELL); } public void sendContentType(final MimeType mimeType, String checkMessage, String body) throws Exception { // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/incoming_" + mimeType.toString()); httpRequest.setConsoleLogResponseBody(true); httpRequest.setContentType(mimeType); if (body != null) { httpRequest.setHttpMode(HttpMode.POST); httpRequest.setRequestBody(body); } // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(checkMessage, build); } @Test public void sendNonAsciiRequestBody() throws Exception { registerContentTypeRequestChecker(MimeType.APPLICATION_JSON, HttpMode.POST, null); sendContentType(MimeType.APPLICATION_JSON, ALL_IS_WELL, ALL_IS_WELL); } @Test public void sendUTF8RequestBody() throws Exception { String notAsciiUTF8Message = "ἱερογλύφος"; registerContentTypeRequestChecker(MimeType.APPLICATION_JSON_UTF8, HttpMode.POST, null); sendContentType(MimeType.APPLICATION_JSON_UTF8, notAsciiUTF8Message, notAsciiUTF8Message); } @Test public void sendAllAcceptTypes() throws Exception { for (MimeType mimeType : MimeType.values()) { // Prepare the server registerAcceptedTypeRequestChecker(mimeType); sendAcceptType(mimeType); cleanHandlers(); } } public void sendAcceptType(final MimeType mimeType) throws Exception { // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/accept_" + mimeType.toString()); httpRequest.setConsoleLogResponseBody(true); httpRequest.setAcceptType(mimeType); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void canPutResponseInOutputFile() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setOutputFile("file.txt"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); // By default, the response is printed to the console even if an outputFile is used this.j.assertLogContains(ALL_IS_WELL, build); // The response is in the output file as well String outputFile = build.getWorkspace().child("file.txt").readToString(); Pattern p = Pattern.compile(ALL_IS_WELL); Matcher m = p.matcher(outputFile); assertTrue(m.find()); } @Test public void canPutResponseInOutputFileWhenNotSetToGoToConsole() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setOutputFile("file.txt"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); // Check that the console does NOT have the response body this.j.assertLogNotContains(ALL_IS_WELL, build); // The response is in the output file String outputFile = build.getWorkspace().child("file.txt").readToString(); Pattern p = Pattern.compile(ALL_IS_WELL); Matcher m = p.matcher(outputFile); assertTrue(m.find()); } @Test public void timeoutFailsTheBuild() throws Exception { // Prepare the server registerTimeout(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/timeout"); httpRequest.setTimeout(2); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void canDoCustomHeaders() throws Exception { // Prepare the server registerCustomHeaders(); List<HttpRequestNameValuePair> customHeaders = new ArrayList<>(); customHeaders.add(new HttpRequestNameValuePair("customHeader", "value1")); customHeaders.add(new HttpRequestNameValuePair("customHeader", "value2")); HttpRequest httpRequest = new HttpRequest(baseURL() + "/customHeaders"); httpRequest.setCustomHeaders(customHeaders); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); } @Test public void replaceParametersInCustomHeaders() throws Exception { // Prepare the server registerCustomHeadersResolved(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/customHeadersResolved"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); // Add some custom headers List<HttpRequestNameValuePair> customHeaders = new ArrayList<>(); customHeaders.add(new HttpRequestNameValuePair("resolveCustomParam", "${Tag}")); customHeaders.add(new HttpRequestNameValuePair("resolveEnvParam", "${WORKSPACE}")); httpRequest.setCustomHeaders(customHeaders); // Activate passBuildParameters httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.addProperty(new ParametersDefinitionProperty( new StringParameterDefinition("Tag", "default"), new StringParameterDefinition("WORKSPACE", "default") )); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("Tag", "trunk"), new StringParameterValue("WORKSPACE", "C:/path/to/my/workspace"))).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void nonExistentBasicAuthFailsTheBuild() throws Exception { // Prepare the server registerBasicAuth(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/basicAuth"); httpRequest.setAuthentication("non-existent-key"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void canDoBasicDigestAuthentication() throws Exception { // Prepare the server registerBasicAuth(); // Prepare the authentication registerBasicCredential("keyname1", "username1", "password1"); registerBasicCredential("keyname2", "username2", "password2"); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/basicAuth"); httpRequest.setAuthentication("keyname1"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); } @Test public void testFormAuthentication() throws Exception { final String paramUsername = "username"; final String valueUsername = "user"; final String paramPassword = "password"; final String valuePassword = "pass"; final String sessionName = "VALID_SESSIONID"; registerHandler("/form-auth", HttpMode.POST, new SimpleHandler() { @Override void doHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String username = request.getParameter(paramUsername); String password = request.getParameter(paramPassword); if (!username.equals(valueUsername) || !password.equals(valuePassword)) { response.setStatus(401); return; } response.addCookie(new Cookie(sessionName, "ok")); okAllIsWell(response); } }); registerHandler("/test-auth", HttpMode.GET, new SimpleHandler() { @Override void doHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String jsessionValue = ""; Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { if (cookie.getName().equals(sessionName)) { jsessionValue = cookie.getValue(); break; } } if (!jsessionValue.equals("ok")) { response.setStatus(401); return; } okAllIsWell(response); } }); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<>(); params.add(new HttpRequestNameValuePair(paramUsername, valueUsername)); params.add(new HttpRequestNameValuePair(paramPassword, valuePassword)); RequestAction action = new RequestAction(new URL(baseURL() + "/form-auth"), HttpMode.POST, null, params); List<RequestAction> actions = new ArrayList<>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("Form", actions); List<FormAuthentication> formAuthList = new ArrayList<>(); formAuthList.add(formAuth); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/test-auth"); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); httpRequest.setAuthentication("Form"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); } @Test public void canDoFormAuthentication() throws Exception { // Prepare the server registerFormAuth(); registerReqAction(); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<>(); params.add(new HttpRequestNameValuePair("param1", "value1")); params.add(new HttpRequestNameValuePair("param2", "value2")); RequestAction action = new RequestAction(new URL(baseURL() + "/reqAction"), HttpMode.GET, null, params); List<RequestAction> actions = new ArrayList<>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname", actions); List<FormAuthentication> formAuthList = new ArrayList<>(); formAuthList.add(formAuth); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/formAuth"); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); httpRequest.setAuthentication("keyname"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); } @Test public void rejectedFormCredentialsFailTheBuild() throws Exception { // Prepare the server registerFormAuthBad(); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<>(); params.add(new HttpRequestNameValuePair("param1", "value1")); params.add(new HttpRequestNameValuePair("param2", "value2")); RequestAction action = new RequestAction(new URL(baseURL() + "/formAuthBad"), HttpMode.GET, null, params); List<RequestAction> actions = new ArrayList<>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname", actions); List<FormAuthentication> formAuthList = new ArrayList<>(); formAuthList.add(formAuth); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/formAuthBad"); httpRequest.setConsoleLogResponseBody(true); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); httpRequest.setAuthentication("keyname"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Error doing authentication", build); } @Test public void invalidKeyFormAuthenticationFailsTheBuild() throws Exception { // Prepare the server // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<>(); params.add(new HttpRequestNameValuePair("param1", "value1")); params.add(new HttpRequestNameValuePair("param2", "value2")); // The request action won't be sent but we need to prepare it RequestAction action = new RequestAction(new URL(baseURL() + "/non-existent"), HttpMode.GET, null, params); List<RequestAction> actions = new ArrayList<>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname", actions); List<FormAuthentication> formAuthList = new ArrayList<>(); formAuthList.add(formAuth); // Prepare HttpRequest - the actual request won't be sent HttpRequest httpRequest = new HttpRequest(baseURL() + "/non-existent"); httpRequest.setConsoleLogResponseBody(true); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); // Select a non-existent form authentication, this will error the build before any request is made httpRequest.setAuthentication("non-existent"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Authentication 'non-existent' doesn't exist anymore", build); } @Test public void responseContentSupplierHeadersFilling() throws Exception { // Prepare test context HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK"); response.setEntity(new StringEntity("TEST")); response.setHeader("Server", "Jenkins"); response.setHeader("Set-Cookie", "JSESSIONID=123456789"); response.addHeader("Set-Cookie", "JSESSIONID=abcdefghijk"); // Run test ResponseContentSupplier respSupplier = new ResponseContentSupplier(ResponseHandle.STRING, response); // Check expectations Assert.assertEquals(2, respSupplier.getHeaders().size()); Assert.assertTrue(respSupplier.getHeaders().containsKey("Server")); Assert.assertTrue(respSupplier.getHeaders().containsKey("Set-Cookie")); Assert.assertEquals(1, respSupplier.getHeaders().get("Server").size()); Assert.assertEquals(2, respSupplier.getHeaders().get("Set-Cookie").size()); Assert.assertEquals("Jenkins", respSupplier.getHeaders().get("Server").get(0)); int valuesFoundCounter = 0; for (String s : respSupplier.getHeaders().get("Set-Cookie")) { if ("JSESSIONID=123456789".equals(s)) { valuesFoundCounter++; } else if ("JSESSIONID=abcdefghijk".equals(s)) { valuesFoundCounter++; } } Assert.assertEquals(2, valuesFoundCounter); respSupplier.close(); } @Test public void responseContentSupplierHeadersCaseInsensitivity() throws Exception { // Prepare test context HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK"); response.setEntity(new StringEntity("TEST")); response.setHeader("Server", "Jenkins"); // Run test ResponseContentSupplier respSupplier = new ResponseContentSupplier(ResponseHandle.STRING, response); // Check expectations Assert.assertEquals(1, respSupplier.getHeaders().size()); Assert.assertTrue(respSupplier.getHeaders().containsKey("Server")); Assert.assertTrue(respSupplier.getHeaders().containsKey("SERVER")); Assert.assertTrue(respSupplier.getHeaders().containsKey("server")); respSupplier.close(); } @Test public void testFileUpload() throws Exception { // Prepare the server final File testFolder = folder.newFolder(); File uploadFile = File.createTempFile("upload", ".zip", testFolder); String responseText = "File upload successful!"; registerFileUpload(testFolder, uploadFile, responseText); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/uploadFile"); httpRequest.setHttpMode(HttpMode.POST); httpRequest.setValidResponseCodes("201"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setUploadFile(uploadFile.getAbsolutePath()); httpRequest.setMultipartName("file-name"); httpRequest.setContentType(MimeType.APPLICATION_ZIP); httpRequest.setAcceptType(MimeType.TEXT_PLAIN); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(responseText, build); } @Test public void testUnwrappedPutFileUpload() throws Exception { // Prepare the server final File testFolder = folder.newFolder(); File uploadFile = File.createTempFile("upload", ".zip", testFolder); String responseText = "File upload successful!"; registerUnwrappedPutFileUpload(uploadFile, responseText); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/uploadFile/" + uploadFile.getName()); httpRequest.setHttpMode(HttpMode.PUT); httpRequest.setValidResponseCodes("201"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setUploadFile(uploadFile.getAbsolutePath()); httpRequest.setWrapAsMultipart(false); httpRequest.setContentType(MimeType.APPLICATION_ZIP); httpRequest.setAcceptType(MimeType.TEXT_PLAIN); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(responseText, build); } @Test public void nonExistentProxyAuthFailsTheBuild() throws Exception { // Prepare the server registerBasicAuth(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/basicAuth"); httpRequest.setHttpProxy("http://proxy.example.com:8888"); httpRequest.setProxyAuthentication("non-existent-key"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } }
basil/http-request-plugin
src/test/java/jenkins/plugins/http_request/HttpRequestTest.java
44,585
package jenkins.plugins.http_request; import static jenkins.plugins.http_request.Registers.registerAcceptedTypeRequestChecker; import static jenkins.plugins.http_request.Registers.registerBasicAuth; import static jenkins.plugins.http_request.Registers.registerCheckBuildParameters; import static jenkins.plugins.http_request.Registers.registerCheckRequestBody; import static jenkins.plugins.http_request.Registers.registerCheckRequestBodyWithTag; import static jenkins.plugins.http_request.Registers.registerContentTypeRequestChecker; import static jenkins.plugins.http_request.Registers.registerCustomHeaders; import static jenkins.plugins.http_request.Registers.registerCustomHeadersResolved; import static jenkins.plugins.http_request.Registers.registerFileUpload; import static jenkins.plugins.http_request.Registers.registerFormAuth; import static jenkins.plugins.http_request.Registers.registerFormAuthBad; import static jenkins.plugins.http_request.Registers.registerInvalidStatusCode; import static jenkins.plugins.http_request.Registers.registerReqAction; import static jenkins.plugins.http_request.Registers.registerRequestChecker; import static jenkins.plugins.http_request.Registers.registerTimeout; import static jenkins.plugins.http_request.Registers.registerUnwrappedPutFileUpload; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.http.HttpResponse; import org.apache.http.ProtocolVersion; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicHttpResponse; import org.eclipse.jetty.server.Request; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import hudson.model.Cause.UserIdCause; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.ParametersAction; import hudson.model.ParametersDefinitionProperty; import hudson.model.Result; import hudson.model.StringParameterDefinition; import hudson.model.StringParameterValue; import jenkins.plugins.http_request.auth.FormAuthentication; import jenkins.plugins.http_request.util.HttpRequestNameValuePair; import jenkins.plugins.http_request.util.RequestAction; /** * @author Martin d'Anjou */ public class HttpRequestTest extends HttpRequestTestBase { @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void simpleGetTest() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void quietTest() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setQuiet(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogNotContains("HttpMethod:", build); this.j.assertLogNotContains("URL:", build); this.j.assertLogNotContains("Sending request to url:", build); this.j.assertLogNotContains("Response Code:", build); } @Test public void canDetectActualContent() throws Exception { // Setup the expected pattern String findMe = ALL_IS_WELL; // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setValidResponseContent(findMe); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(findMe, build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void badContentFailsTheBuild() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setValidResponseContent("bad content"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Fail: Response doesn't contain expected content 'bad content'", build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void responseMatchAcceptedMimeType() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Expect a mime type that matches the response httpRequest.setAcceptType(MimeType.TEXT_PLAIN); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void responseDoesNotMatchAcceptedMimeTypeDoesNotFailTheBuild() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Expect a mime type that does not match the response httpRequest.setAcceptType(MimeType.TEXT_HTML); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void passBuildParametersWhenAskedAndParametersArePresent() throws Exception { // Prepare the server registerCheckBuildParameters(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/checkBuildParameters"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.addProperty(new ParametersDefinitionProperty( new StringParameterDefinition("foo", "default") )); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("foo", "value"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void replaceParametersInRequestBody() throws Exception { // Prepare the server registerCheckRequestBodyWithTag(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/checkRequestBodyWithTag"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); // Use some random body content that contains a parameter httpRequest.setRequestBody("cleanupDir=D:/continuousIntegration/deployments/Daimler/${Tag}/standalone"); // Build parameters have to be passed httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.addProperty(new ParametersDefinitionProperty( new StringParameterDefinition("Tag", "default") )); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("Tag", "trunk"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void silentlyIgnoreNonExistentBuildParameters() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters without parameters present httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void doNotPassBuildParametersWithBuildParameters() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setPassBuildParameters(false); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("foo", "value"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void passRequestBodyWhenRequestIsPostAndBodyIsPresent() throws Exception { // Prepare the server registerCheckRequestBody(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/checkRequestBody"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); httpRequest.setRequestBody("TestRequestBody"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void doNotPassRequestBodyWhenMethodIsGet() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setRequestBody("TestRequestBody"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void doAllRequestTypes() throws Exception { for (HttpMode method : HttpMode.values()) { // Prepare the server registerRequestChecker(method); doRequest(method); cleanHandlers(); } } public void doRequest(final HttpMode method) throws Exception { // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/do" + method.toString()); httpRequest.setHttpMode(method); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); if (method == HttpMode.HEAD) { return; } this.j.assertLogContains(ALL_IS_WELL, build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void invalidResponseCodeFailsTheBuild() throws Exception { // Prepare the server registerInvalidStatusCode(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/invalidStatusCode"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Throwing status 400 for test", build); this.j.assertLogContains("Fail: Status code 400 is not in the accepted range: 100:399", build); } @Test public void invalidResponseCodeIsAccepted() throws Exception { // Prepare the server registerInvalidStatusCode(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/invalidStatusCode"); httpRequest.setValidResponseCodes("100:599"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains("Throwing status 400 for test", build); this.j.assertLogContains("Success: Status code 400 is in the accepted range: 100:599", build); } @Test public void reverseRangeFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("599:100"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Interval 599:100 should be FROM less than TO", build); } @Test public void notANumberRangeValueFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("text"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Invalid number text", build); } @Test public void rangeWithTextFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("1:text"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Invalid number text", build); } @Test public void invalidRangeFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("1:2:3"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Code 1:2:3 should be an interval from:to or a single value", build); } @Test public void sendAllContentTypes() { for (MimeType mimeType : MimeType.values()) { sendContentType(mimeType); } } public void sendContentType(final MimeType mimeType) { registerContentTypeRequestChecker(mimeType, HttpMode.GET, ALL_IS_WELL); } public void sendContentType(final MimeType mimeType, String checkMessage, String body) throws Exception { // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/incoming_" + mimeType.toString()); httpRequest.setConsoleLogResponseBody(true); httpRequest.setContentType(mimeType); if (body != null) { httpRequest.setHttpMode(HttpMode.POST); httpRequest.setRequestBody(body); } // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(checkMessage, build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void sendNonAsciiRequestBody() throws Exception { registerContentTypeRequestChecker(MimeType.APPLICATION_JSON, HttpMode.POST, null); sendContentType(MimeType.APPLICATION_JSON, ALL_IS_WELL, ALL_IS_WELL); } @Test public void sendUTF8RequestBody() throws Exception { String notAsciiUTF8Message = "ἱερογλύφος"; registerContentTypeRequestChecker(MimeType.APPLICATION_JSON_UTF8, HttpMode.POST, null); sendContentType(MimeType.APPLICATION_JSON_UTF8, notAsciiUTF8Message, notAsciiUTF8Message); } @Test public void sendAllAcceptTypes() throws Exception { for (MimeType mimeType : MimeType.values()) { // Prepare the server registerAcceptedTypeRequestChecker(mimeType); sendAcceptType(mimeType); cleanHandlers(); } } public void sendAcceptType(final MimeType mimeType) throws Exception { // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/accept_" + mimeType.toString()); httpRequest.setConsoleLogResponseBody(true); httpRequest.setAcceptType(mimeType); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void canPutResponseInOutputFile() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setOutputFile("file.txt"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); // By default, the response is printed to the console even if an outputFile is used this.j.assertLogContains(ALL_IS_WELL, build); // The response is in the output file as well String outputFile = build.getWorkspace().child("file.txt").readToString(); Pattern p = Pattern.compile(ALL_IS_WELL); Matcher m = p.matcher(outputFile); assertTrue(m.find()); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void canPutResponseInOutputFileWhenNotSetToGoToConsole() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setOutputFile("file.txt"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); // Check that the console does NOT have the response body this.j.assertLogNotContains(ALL_IS_WELL, build); // The response is in the output file String outputFile = build.getWorkspace().child("file.txt").readToString(); Pattern p = Pattern.compile(ALL_IS_WELL); Matcher m = p.matcher(outputFile); assertTrue(m.find()); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void timeoutFailsTheBuild() throws Exception { // Prepare the server registerTimeout(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/timeout"); httpRequest.setTimeout(2); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Fail: Status code 408 is not in the accepted range: 100:399", build); } @Test public void canDoCustomHeaders() throws Exception { // Prepare the server registerCustomHeaders(); List<HttpRequestNameValuePair> customHeaders = new ArrayList<>(); customHeaders.add(new HttpRequestNameValuePair("customHeader", "value1")); customHeaders.add(new HttpRequestNameValuePair("customHeader", "value2")); HttpRequest httpRequest = new HttpRequest(baseURL() + "/customHeaders"); httpRequest.setCustomHeaders(customHeaders); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void replaceParametersInCustomHeaders() throws Exception { // Prepare the server registerCustomHeadersResolved(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/customHeadersResolved"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); // Add some custom headers List<HttpRequestNameValuePair> customHeaders = new ArrayList<>(); customHeaders.add(new HttpRequestNameValuePair("resolveCustomParam", "${Tag}")); customHeaders.add(new HttpRequestNameValuePair("resolveEnvParam", "${WORKSPACE}")); httpRequest.setCustomHeaders(customHeaders); // Activate passBuildParameters httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.addProperty(new ParametersDefinitionProperty( new StringParameterDefinition("Tag", "default"), new StringParameterDefinition("WORKSPACE", "default") )); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("Tag", "trunk"), new StringParameterValue("WORKSPACE", "C:/path/to/my/workspace"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void nonExistentBasicAuthFailsTheBuild() throws Exception { // Prepare the server registerBasicAuth(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/basicAuth"); httpRequest.setAuthentication("non-existent-key"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Authentication 'non-existent-key' doesn't exist anymore", build); } @Test public void canDoBasicDigestAuthentication() throws Exception { // Prepare the server registerBasicAuth(); // Prepare the authentication registerBasicCredential("keyname1", "username1", "password1"); registerBasicCredential("keyname2", "username2", "password2"); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/basicAuth"); httpRequest.setAuthentication("keyname1"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void testFormAuthentication() throws Exception { final String paramUsername = "username"; final String valueUsername = "user"; final String paramPassword = "password"; final String valuePassword = "pass"; final String sessionName = "VALID_SESSIONID"; registerHandler("/form-auth", HttpMode.POST, new SimpleHandler() { @Override void doHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { String username = request.getParameter(paramUsername); String password = request.getParameter(paramPassword); if (!username.equals(valueUsername) || !password.equals(valuePassword)) { response.setStatus(401); return; } response.addCookie(new Cookie(sessionName, "ok")); okAllIsWell(response); } }); registerHandler("/test-auth", HttpMode.GET, new SimpleHandler() { @Override void doHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { String jsessionValue = ""; Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { if (cookie.getName().equals(sessionName)) { jsessionValue = cookie.getValue(); break; } } if (!jsessionValue.equals("ok")) { response.setStatus(401); return; } okAllIsWell(response); } }); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<>(); params.add(new HttpRequestNameValuePair(paramUsername, valueUsername)); params.add(new HttpRequestNameValuePair(paramPassword, valuePassword)); RequestAction action = new RequestAction(new URL(baseURL() + "/form-auth"), HttpMode.POST, null, params); List<RequestAction> actions = new ArrayList<>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("Form", actions); List<FormAuthentication> formAuthList = new ArrayList<>(); formAuthList.add(formAuth); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/test-auth"); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); httpRequest.setAuthentication("Form"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void canDoFormAuthentication() throws Exception { // Prepare the server registerFormAuth(); registerReqAction(); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<>(); params.add(new HttpRequestNameValuePair("param1", "value1")); params.add(new HttpRequestNameValuePair("param2", "value2")); RequestAction action = new RequestAction(new URL(baseURL() + "/reqAction"), HttpMode.GET, null, params); List<RequestAction> actions = new ArrayList<>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname", actions); List<FormAuthentication> formAuthList = new ArrayList<>(); formAuthList.add(formAuth); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/formAuth"); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); httpRequest.setAuthentication("keyname"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build); } @Test public void rejectedFormCredentialsFailTheBuild() throws Exception { // Prepare the server registerFormAuthBad(); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<>(); params.add(new HttpRequestNameValuePair("param1", "value1")); params.add(new HttpRequestNameValuePair("param2", "value2")); RequestAction action = new RequestAction(new URL(baseURL() + "/formAuthBad"), HttpMode.GET, null, params); List<RequestAction> actions = new ArrayList<>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname", actions); List<FormAuthentication> formAuthList = new ArrayList<>(); formAuthList.add(formAuth); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/formAuthBad"); httpRequest.setConsoleLogResponseBody(true); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); httpRequest.setAuthentication("keyname"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Error doing authentication", build); } @Test public void invalidKeyFormAuthenticationFailsTheBuild() throws Exception { // Prepare the server // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<>(); params.add(new HttpRequestNameValuePair("param1", "value1")); params.add(new HttpRequestNameValuePair("param2", "value2")); // The request action won't be sent but we need to prepare it RequestAction action = new RequestAction(new URL(baseURL() + "/non-existent"), HttpMode.GET, null, params); List<RequestAction> actions = new ArrayList<>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname", actions); List<FormAuthentication> formAuthList = new ArrayList<>(); formAuthList.add(formAuth); // Prepare HttpRequest - the actual request won't be sent HttpRequest httpRequest = new HttpRequest(baseURL() + "/non-existent"); httpRequest.setConsoleLogResponseBody(true); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); // Select a non-existent form authentication, this will error the build before any request is made httpRequest.setAuthentication("non-existent"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Authentication 'non-existent' doesn't exist anymore", build); } @Test public void responseContentSupplierHeadersFilling() throws Exception { // Prepare test context HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK"); response.setEntity(new StringEntity("TEST")); response.setHeader("Server", "Jenkins"); response.setHeader("Set-Cookie", "JSESSIONID=123456789"); response.addHeader("Set-Cookie", "JSESSIONID=abcdefghijk"); // Run test ResponseContentSupplier respSupplier = new ResponseContentSupplier(ResponseHandle.STRING, response); // Check expectations Assert.assertEquals(2, respSupplier.getHeaders().size()); Assert.assertTrue(respSupplier.getHeaders().containsKey("Server")); Assert.assertTrue(respSupplier.getHeaders().containsKey("Set-Cookie")); Assert.assertEquals(1, respSupplier.getHeaders().get("Server").size()); Assert.assertEquals(2, respSupplier.getHeaders().get("Set-Cookie").size()); Assert.assertEquals("Jenkins", respSupplier.getHeaders().get("Server").get(0)); int valuesFoundCounter = 0; for (String s : respSupplier.getHeaders().get("Set-Cookie")) { if ("JSESSIONID=123456789".equals(s)) { valuesFoundCounter++; } else if ("JSESSIONID=abcdefghijk".equals(s)) { valuesFoundCounter++; } } Assert.assertEquals(2, valuesFoundCounter); respSupplier.close(); } @Test public void responseContentSupplierHeadersCaseInsensitivity() throws Exception { // Prepare test context HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK"); response.setEntity(new StringEntity("TEST")); response.setHeader("Server", "Jenkins"); // Run test ResponseContentSupplier respSupplier = new ResponseContentSupplier(ResponseHandle.STRING, response); // Check expectations Assert.assertEquals(1, respSupplier.getHeaders().size()); Assert.assertTrue(respSupplier.getHeaders().containsKey("Server")); Assert.assertTrue(respSupplier.getHeaders().containsKey("SERVER")); Assert.assertTrue(respSupplier.getHeaders().containsKey("server")); respSupplier.close(); } @Test public void testFileUpload() throws Exception { // Prepare the server final File testFolder = folder.newFolder(); File uploadFile = File.createTempFile("upload", ".zip", testFolder); String responseText = "File upload successful!"; registerFileUpload(testFolder, uploadFile, responseText); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/uploadFile"); httpRequest.setHttpMode(HttpMode.POST); httpRequest.setValidResponseCodes("201"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setUploadFile(uploadFile.getAbsolutePath()); httpRequest.setMultipartName("file-name"); httpRequest.setContentType(MimeType.APPLICATION_ZIP); httpRequest.setAcceptType(MimeType.TEXT_PLAIN); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(responseText, build); this.j.assertLogContains("Success: Status code 201 is in the accepted range: 201", build); } @Test public void testUnwrappedPutFileUpload() throws Exception { // Prepare the server final File testFolder = folder.newFolder(); File uploadFile = File.createTempFile("upload", ".zip", testFolder); String responseText = "File upload successful!"; registerUnwrappedPutFileUpload(uploadFile, responseText); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/uploadFile/" + uploadFile.getName()); httpRequest.setHttpMode(HttpMode.PUT); httpRequest.setValidResponseCodes("201"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setUploadFile(uploadFile.getAbsolutePath()); httpRequest.setWrapAsMultipart(false); httpRequest.setContentType(MimeType.APPLICATION_ZIP); httpRequest.setAcceptType(MimeType.TEXT_PLAIN); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(responseText, build); this.j.assertLogContains("Success: Status code 201 is in the accepted range: 201", build); } @Test public void nonExistentProxyAuthFailsTheBuild() throws Exception { // Prepare the server registerBasicAuth(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/basicAuth"); httpRequest.setHttpProxy("http://proxy.example.com:8888"); httpRequest.setProxyAuthentication("non-existent-key"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Proxy authentication 'non-existent-key' doesn't exist anymore or is not a username/password credential type", build); } }
jsearby/http-request-plugin
src/test/java/jenkins/plugins/http_request/HttpRequestTest.java
44,586
package jenkins.plugins.http_request; import static jenkins.plugins.http_request.Registers.registerAcceptedTypeRequestChecker; import static jenkins.plugins.http_request.Registers.registerBasicAuth; import static jenkins.plugins.http_request.Registers.registerCheckBuildParameters; import static jenkins.plugins.http_request.Registers.registerCheckRequestBody; import static jenkins.plugins.http_request.Registers.registerCheckRequestBodyWithTag; import static jenkins.plugins.http_request.Registers.registerContentTypeRequestChecker; import static jenkins.plugins.http_request.Registers.registerCustomHeaders; import static jenkins.plugins.http_request.Registers.registerCustomHeadersResolved; import static jenkins.plugins.http_request.Registers.registerFormAuth; import static jenkins.plugins.http_request.Registers.registerFormAuthBad; import static jenkins.plugins.http_request.Registers.registerInvalidStatusCode; import static jenkins.plugins.http_request.Registers.registerReqAction; import static jenkins.plugins.http_request.Registers.registerRequestChecker; import static jenkins.plugins.http_request.Registers.registerTimeout; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.http.HttpResponse; import org.apache.http.ProtocolVersion; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicHttpResponse; import org.eclipse.jetty.server.Request; import org.junit.Assert; import org.junit.Test; import hudson.model.Cause.UserIdCause; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.ParametersAction; import hudson.model.Result; import hudson.model.StringParameterValue; import jenkins.plugins.http_request.auth.FormAuthentication; import jenkins.plugins.http_request.util.HttpRequestNameValuePair; import jenkins.plugins.http_request.util.RequestAction; /** * @author Martin d'Anjou */ public class HttpRequestTest extends HttpRequestTestBase { @Test public void simpleGetTest() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void canDetectActualContent() throws Exception { // Setup the expected pattern String findMe = ALL_IS_WELL; // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setValidResponseContent(findMe); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(findMe, build); } @Test public void badContentFailsTheBuild() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setValidResponseContent("bad content"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); String s = FileUtils.readFileToString(build.getLogFile()); assertTrue(s.contains("Fail: Response doesn't contain expected content 'bad content'")); } @Test public void responseMatchAcceptedMimeType() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Expect a mime type that matches the response httpRequest.setAcceptType(MimeType.TEXT_PLAIN); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void responseDoesNotMatchAcceptedMimeTypeDoesNotFailTheBuild() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Expect a mime type that does not match the response httpRequest.setAcceptType(MimeType.TEXT_HTML); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void passBuildParametersWhenAskedAndParamtersArePresent() throws Exception { // Prepare the server registerCheckBuildParameters(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/checkBuildParameters"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("foo", "value"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void replaceParametersInRequestBody() throws Exception { // Prepare the server registerCheckRequestBodyWithTag(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/checkRequestBodyWithTag"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); // Use some random body content that contains a parameter httpRequest.setRequestBody("cleanupDir=D:/continuousIntegration/deployments/Daimler/${Tag}/standalone"); // Build parameters have to be passed httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("Tag", "trunk"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void silentlyIgnoreNonExistentBuildParameters() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters without parameters present httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void doNotPassBuildParametersWithBuildParameters() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setPassBuildParameters(false); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("foo", "value"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void passRequestBodyWhenRequestIsPostAndBodyIsPresent() throws Exception { // Prepare the server registerCheckRequestBody(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/checkRequestBody"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); httpRequest.setRequestBody("TestRequestBody"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void doNotPassRequestBodyWhenMethodIsGet() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setRequestBody("TestRequestBody"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void doAllRequestTypes() throws Exception { for (HttpMode method : HttpMode.values()) { // Prepare the server registerRequestChecker(method); doRequest(method); cleanHandlers(); } } public void doRequest(final HttpMode method) throws Exception { // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/do" + method.toString()); httpRequest.setHttpMode(method); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); if (method == HttpMode.HEAD) { return; } this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void invalidResponseCodeFailsTheBuild() throws Exception { // Prepare the server registerInvalidStatusCode(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/invalidStatusCode"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Throwing status 400 for test", build); } @Test public void invalidResponseCodeIsAccepted() throws Exception { // Prepare the server registerInvalidStatusCode(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/invalidStatusCode"); httpRequest.setValidResponseCodes("100:599"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains("Throwing status 400 for test", build); } @Test public void reverseRangeFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("599:100"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void notANumberRangeValueFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("text"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void rangeWithTextFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("1:text"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void invalidRangeFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("1:2:3"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void sendAllContentTypes() throws Exception { for (MimeType mimeType : MimeType.values()) { sendContentType(mimeType); } } public void sendContentType(final MimeType mimeType) throws Exception { registerContentTypeRequestChecker(mimeType, HttpMode.GET, ALL_IS_WELL); } public void sendContentType(final MimeType mimeType, String checkMessage, String body) throws Exception { // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/incoming_" + mimeType.toString()); httpRequest.setConsoleLogResponseBody(true); httpRequest.setContentType(mimeType); if (body != null) { httpRequest.setHttpMode(HttpMode.POST); httpRequest.setRequestBody(body); } // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(checkMessage, build); } @Test public void sendNonAsciiRequestBody() throws Exception { registerContentTypeRequestChecker(MimeType.APPLICATION_JSON, HttpMode.POST, null); sendContentType(MimeType.APPLICATION_JSON, ALL_IS_WELL, ALL_IS_WELL); } @Test public void sendUTF8equestBody() throws Exception { String notAsciiUTF8Message = "ἱερογλύφος"; registerContentTypeRequestChecker(MimeType.APPLICATION_JSON_UTF8, HttpMode.POST, null); sendContentType(MimeType.APPLICATION_JSON_UTF8, notAsciiUTF8Message, notAsciiUTF8Message); } @Test public void sendAllAcceptTypes() throws Exception { for (MimeType mimeType : MimeType.values()) { // Prepare the server registerAcceptedTypeRequestChecker(mimeType); sendAcceptType(mimeType); cleanHandlers(); } } public void sendAcceptType(final MimeType mimeType) throws Exception { // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/accept_" + mimeType.toString()); httpRequest.setConsoleLogResponseBody(true); httpRequest.setAcceptType(mimeType); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void canPutResponseInOutputFile() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setOutputFile("file.txt"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); // By default, the response is printed to the console even if an outputFile is used this.j.assertLogContains(ALL_IS_WELL, build); // The response is in the output file as well String outputFile = build.getWorkspace().child("file.txt").readToString(); Pattern p = Pattern.compile(ALL_IS_WELL); Matcher m = p.matcher(outputFile); assertTrue(m.find()); } @Test public void canPutResponseInOutputFileWhenNotSetToGoToConsole() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setOutputFile("file.txt"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); // Check that the console does NOT have the response body this.j.assertLogNotContains(ALL_IS_WELL, build); // The response is in the output file String outputFile = build.getWorkspace().child("file.txt").readToString(); Pattern p = Pattern.compile(ALL_IS_WELL); Matcher m = p.matcher(outputFile); assertTrue(m.find()); } @Test public void timeoutFailsTheBuild() throws Exception { // Prepare the server registerTimeout(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/timeout"); httpRequest.setTimeout(2); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void canDoCustomHeaders() throws Exception { // Prepare the server registerCustomHeaders(); List<HttpRequestNameValuePair> customHeaders = new ArrayList<HttpRequestNameValuePair>(); customHeaders.add(new HttpRequestNameValuePair("customHeader", "value1")); customHeaders.add(new HttpRequestNameValuePair("customHeader", "value2")); HttpRequest httpRequest = new HttpRequest(baseURL() + "/customHeaders"); httpRequest.setCustomHeaders(customHeaders); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); } @Test public void replaceParametesInCustomHeaders() throws Exception { // Prepare the server registerCustomHeadersResolved(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/customHeadersResolved"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); // Add some custom headers List<HttpRequestNameValuePair> customHeaders = new ArrayList<HttpRequestNameValuePair>(); customHeaders.add(new HttpRequestNameValuePair("resolveCustomParam", "${Tag}")); customHeaders.add(new HttpRequestNameValuePair("resolveEnvParam", "${WORKSPACE}")); httpRequest.setCustomHeaders(customHeaders); // Activate passBuildParameters httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("Tag", "trunk"), new StringParameterValue("WORKSPACE", "C:/path/to/my/workspace"))).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void nonExistentBasicAuthFailsTheBuild() throws Exception { // Prepare the server registerBasicAuth(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/basicAuth"); httpRequest.setAuthentication("non-existent-key"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void canDoBasicDigestAuthentication() throws Exception { // Prepare the server registerBasicAuth(); // Prepare the authentication registerBasicCredential("keyname1", "username1", "password1"); registerBasicCredential("keyname2", "username2", "password2"); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/basicAuth"); httpRequest.setAuthentication("keyname1"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); } @Test public void testFormAuthentication() throws Exception { final String paramUsername = "username"; final String valueUsername = "user"; final String paramPassword = "password"; final String valuePassword = "pass"; final String sessionName = "VALID_SESSIONID"; registerHandler("/form-auth", HttpMode.POST, new SimpleHandler() { @Override void doHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String username = request.getParameter(paramUsername); String password = request.getParameter(paramPassword); if (!username.equals(valueUsername) || !password.equals(valuePassword)) { response.setStatus(401); return; } response.addCookie(new Cookie(sessionName, "ok")); okAllIsWell(response); } }); registerHandler("/test-auth", HttpMode.GET, new SimpleHandler() { @Override void doHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String jsessionValue = ""; Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { if (cookie.getName().equals(sessionName)) { jsessionValue = cookie.getValue(); break; } } if (!jsessionValue.equals("ok")) { response.setStatus(401); return; } okAllIsWell(response); } }); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<>(); params.add(new HttpRequestNameValuePair(paramUsername, valueUsername)); params.add(new HttpRequestNameValuePair(paramPassword, valuePassword)); RequestAction action = new RequestAction(new URL(baseURL() + "/form-auth"), HttpMode.POST, null, params); List<RequestAction> actions = new ArrayList<RequestAction>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("Form", actions); List<FormAuthentication> formAuthList = new ArrayList<FormAuthentication>(); formAuthList.add(formAuth); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/test-auth"); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); httpRequest.setAuthentication("Form"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); } @Test public void canDoFormAuthentication() throws Exception { // Prepare the server registerFormAuth(); registerReqAction(); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<HttpRequestNameValuePair>(); params.add(new HttpRequestNameValuePair("param1", "value1")); params.add(new HttpRequestNameValuePair("param2", "value2")); RequestAction action = new RequestAction(new URL(baseURL() + "/reqAction"), HttpMode.GET, null, params); List<RequestAction> actions = new ArrayList<RequestAction>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname", actions); List<FormAuthentication> formAuthList = new ArrayList<FormAuthentication>(); formAuthList.add(formAuth); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/formAuth"); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); httpRequest.setAuthentication("keyname"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); } @Test public void rejectedFormCredentialsFailTheBuild() throws Exception { // Prepare the server registerFormAuthBad(); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<HttpRequestNameValuePair>(); params.add(new HttpRequestNameValuePair("param1", "value1")); params.add(new HttpRequestNameValuePair("param2", "value2")); RequestAction action = new RequestAction(new URL(baseURL() + "/formAuthBad"), HttpMode.GET, null, params); List<RequestAction> actions = new ArrayList<RequestAction>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname", actions); List<FormAuthentication> formAuthList = new ArrayList<FormAuthentication>(); formAuthList.add(formAuth); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/formAuthBad"); httpRequest.setConsoleLogResponseBody(true); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); httpRequest.setAuthentication("keyname"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Error doing authentication", build); } @Test public void invalidKeyFormAuthenticationFailsTheBuild() throws Exception { // Prepare the server // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<HttpRequestNameValuePair>(); params.add(new HttpRequestNameValuePair("param1", "value1")); params.add(new HttpRequestNameValuePair("param2", "value2")); // The request action won't be sent but we need to prepare it RequestAction action = new RequestAction(new URL(baseURL() + "/non-existent"), HttpMode.GET, null, params); List<RequestAction> actions = new ArrayList<RequestAction>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname", actions); List<FormAuthentication> formAuthList = new ArrayList<FormAuthentication>(); formAuthList.add(formAuth); // Prepare HttpRequest - the actual request won't be sent HttpRequest httpRequest = new HttpRequest(baseURL() + "/non-existent"); httpRequest.setConsoleLogResponseBody(true); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); // Select a non-existent form authentication, this will error the build before any request is made httpRequest.setAuthentication("non-existent"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Authentication 'non-existent' doesn't exist anymore", build); } @Test public void responseContentSupplierHeadersFilling() throws Exception { // Prepare test context HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK"); response.setEntity(new StringEntity("TEST")); response.setHeader("Server", "Jenkins"); response.setHeader("Set-Cookie", "JSESSIONID=123456789"); response.addHeader("Set-Cookie", "JSESSIONID=abcdefghijk"); // Run test ResponseContentSupplier respSupplier = new ResponseContentSupplier(ResponseHandle.STRING, response); // Check expectations Assert.assertEquals(2, respSupplier.getHeaders().size()); Assert.assertTrue(respSupplier.getHeaders().containsKey("Server")); Assert.assertTrue(respSupplier.getHeaders().containsKey("Set-Cookie")); Assert.assertEquals(1, respSupplier.getHeaders().get("Server").size()); Assert.assertEquals(2, respSupplier.getHeaders().get("Set-Cookie").size()); Assert.assertEquals("Jenkins", respSupplier.getHeaders().get("Server").get(0)); int valuesFoundCounter = 0; for (String s : respSupplier.getHeaders().get("Set-Cookie")) { if ("JSESSIONID=123456789".equals(s)) { valuesFoundCounter++; } else if ("JSESSIONID=abcdefghijk".equals(s)) { valuesFoundCounter++; } } Assert.assertEquals(2, valuesFoundCounter); } }
TiVo/http-request-plugin
src/test/java/jenkins/plugins/http_request/HttpRequestTest.java
44,587
package jenkins.plugins.http_request; import static jenkins.plugins.http_request.Registers.registerFileUpload; import static jenkins.plugins.http_request.Registers.registerAcceptedTypeRequestChecker; import static jenkins.plugins.http_request.Registers.registerBasicAuth; import static jenkins.plugins.http_request.Registers.registerCheckBuildParameters; import static jenkins.plugins.http_request.Registers.registerCheckRequestBody; import static jenkins.plugins.http_request.Registers.registerCheckRequestBodyWithTag; import static jenkins.plugins.http_request.Registers.registerContentTypeRequestChecker; import static jenkins.plugins.http_request.Registers.registerCustomHeaders; import static jenkins.plugins.http_request.Registers.registerCustomHeadersResolved; import static jenkins.plugins.http_request.Registers.registerFormAuth; import static jenkins.plugins.http_request.Registers.registerFormAuthBad; import static jenkins.plugins.http_request.Registers.registerInvalidStatusCode; import static jenkins.plugins.http_request.Registers.registerReqAction; import static jenkins.plugins.http_request.Registers.registerRequestChecker; import static jenkins.plugins.http_request.Registers.registerTimeout; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.http.HttpResponse; import org.apache.http.ProtocolVersion; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicHttpResponse; import org.eclipse.jetty.server.Request; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import hudson.model.Cause.UserIdCause; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.ParametersAction; import hudson.model.Result; import hudson.model.StringParameterValue; import jenkins.plugins.http_request.auth.FormAuthentication; import jenkins.plugins.http_request.util.HttpRequestNameValuePair; import jenkins.plugins.http_request.util.RequestAction; /** * @author Martin d'Anjou */ public class HttpRequestTest extends HttpRequestTestBase { @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void simpleGetTest() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void quietTest() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setQuiet(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogNotContains("HttpMethod:", build); this.j.assertLogNotContains("URL:", build); this.j.assertLogNotContains("Sending request to url:", build); this.j.assertLogNotContains("Response Code:", build); } @Test public void canDetectActualContent() throws Exception { // Setup the expected pattern String findMe = ALL_IS_WELL; // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setValidResponseContent(findMe); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(findMe, build); } @Test public void badContentFailsTheBuild() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setValidResponseContent("bad content"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); String s = FileUtils.readFileToString(build.getLogFile()); assertTrue(s.contains("Fail: Response doesn't contain expected content 'bad content'")); } @Test public void responseMatchAcceptedMimeType() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Expect a mime type that matches the response httpRequest.setAcceptType(MimeType.TEXT_PLAIN); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void responseDoesNotMatchAcceptedMimeTypeDoesNotFailTheBuild() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Expect a mime type that does not match the response httpRequest.setAcceptType(MimeType.TEXT_HTML); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void passBuildParametersWhenAskedAndParamtersArePresent() throws Exception { // Prepare the server registerCheckBuildParameters(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/checkBuildParameters"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("foo", "value"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void replaceParametersInRequestBody() throws Exception { // Prepare the server registerCheckRequestBodyWithTag(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/checkRequestBodyWithTag"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); // Use some random body content that contains a parameter httpRequest.setRequestBody("cleanupDir=D:/continuousIntegration/deployments/Daimler/${Tag}/standalone"); // Build parameters have to be passed httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("Tag", "trunk"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void silentlyIgnoreNonExistentBuildParameters() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters without parameters present httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void doNotPassBuildParametersWithBuildParameters() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setPassBuildParameters(false); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("foo", "value"))).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void passRequestBodyWhenRequestIsPostAndBodyIsPresent() throws Exception { // Prepare the server registerCheckRequestBody(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/checkRequestBody"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); httpRequest.setRequestBody("TestRequestBody"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void doNotPassRequestBodyWhenMethodIsGet() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setConsoleLogResponseBody(true); // Activate passBuildParameters httpRequest.setRequestBody("TestRequestBody"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void doAllRequestTypes() throws Exception { for (HttpMode method : HttpMode.values()) { // Prepare the server registerRequestChecker(method); doRequest(method); cleanHandlers(); } } public void doRequest(final HttpMode method) throws Exception { // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/do" + method.toString()); httpRequest.setHttpMode(method); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); if (method == HttpMode.HEAD) { return; } this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void invalidResponseCodeFailsTheBuild() throws Exception { // Prepare the server registerInvalidStatusCode(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/invalidStatusCode"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Throwing status 400 for test", build); } @Test public void invalidResponseCodeIsAccepted() throws Exception { // Prepare the server registerInvalidStatusCode(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/invalidStatusCode"); httpRequest.setValidResponseCodes("100:599"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains("Throwing status 400 for test", build); } @Test public void reverseRangeFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("599:100"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void notANumberRangeValueFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("text"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void rangeWithTextFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("1:text"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void invalidRangeFailsTheBuild() throws Exception { // Prepare the server // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doesNotMatter"); httpRequest.setValidResponseCodes("1:2:3"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void sendAllContentTypes() throws Exception { for (MimeType mimeType : MimeType.values()) { sendContentType(mimeType); } } public void sendContentType(final MimeType mimeType) throws Exception { registerContentTypeRequestChecker(mimeType, HttpMode.GET, ALL_IS_WELL); } public void sendContentType(final MimeType mimeType, String checkMessage, String body) throws Exception { // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/incoming_" + mimeType.toString()); httpRequest.setConsoleLogResponseBody(true); httpRequest.setContentType(mimeType); if (body != null) { httpRequest.setHttpMode(HttpMode.POST); httpRequest.setRequestBody(body); } // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(checkMessage, build); } @Test public void sendNonAsciiRequestBody() throws Exception { registerContentTypeRequestChecker(MimeType.APPLICATION_JSON, HttpMode.POST, null); sendContentType(MimeType.APPLICATION_JSON, ALL_IS_WELL, ALL_IS_WELL); } @Test public void sendUTF8RequestBody() throws Exception { String notAsciiUTF8Message = "ἱερογλύφος"; registerContentTypeRequestChecker(MimeType.APPLICATION_JSON_UTF8, HttpMode.POST, null); sendContentType(MimeType.APPLICATION_JSON_UTF8, notAsciiUTF8Message, notAsciiUTF8Message); } @Test public void sendAllAcceptTypes() throws Exception { for (MimeType mimeType : MimeType.values()) { // Prepare the server registerAcceptedTypeRequestChecker(mimeType); sendAcceptType(mimeType); cleanHandlers(); } } public void sendAcceptType(final MimeType mimeType) throws Exception { // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/accept_" + mimeType.toString()); httpRequest.setConsoleLogResponseBody(true); httpRequest.setAcceptType(mimeType); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void canPutResponseInOutputFile() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setOutputFile("file.txt"); httpRequest.setConsoleLogResponseBody(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); // By default, the response is printed to the console even if an outputFile is used this.j.assertLogContains(ALL_IS_WELL, build); // The response is in the output file as well String outputFile = build.getWorkspace().child("file.txt").readToString(); Pattern p = Pattern.compile(ALL_IS_WELL); Matcher m = p.matcher(outputFile); assertTrue(m.find()); } @Test public void canPutResponseInOutputFileWhenNotSetToGoToConsole() throws Exception { // Prepare the server registerRequestChecker(HttpMode.GET); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/doGET"); httpRequest.setOutputFile("file.txt"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); // Check that the console does NOT have the response body this.j.assertLogNotContains(ALL_IS_WELL, build); // The response is in the output file String outputFile = build.getWorkspace().child("file.txt").readToString(); Pattern p = Pattern.compile(ALL_IS_WELL); Matcher m = p.matcher(outputFile); assertTrue(m.find()); } @Test public void timeoutFailsTheBuild() throws Exception { // Prepare the server registerTimeout(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/timeout"); httpRequest.setTimeout(2); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void canDoCustomHeaders() throws Exception { // Prepare the server registerCustomHeaders(); List<HttpRequestNameValuePair> customHeaders = new ArrayList<HttpRequestNameValuePair>(); customHeaders.add(new HttpRequestNameValuePair("customHeader", "value1")); customHeaders.add(new HttpRequestNameValuePair("customHeader", "value2")); HttpRequest httpRequest = new HttpRequest(baseURL() + "/customHeaders"); httpRequest.setCustomHeaders(customHeaders); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); } @Test public void replaceParametesInCustomHeaders() throws Exception { // Prepare the server registerCustomHeadersResolved(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/customHeadersResolved"); httpRequest.setConsoleLogResponseBody(true); // Activate requsetBody httpRequest.setHttpMode(HttpMode.POST); // Add some custom headers List<HttpRequestNameValuePair> customHeaders = new ArrayList<HttpRequestNameValuePair>(); customHeaders.add(new HttpRequestNameValuePair("resolveCustomParam", "${Tag}")); customHeaders.add(new HttpRequestNameValuePair("resolveEnvParam", "${WORKSPACE}")); httpRequest.setCustomHeaders(customHeaders); // Activate passBuildParameters httpRequest.setPassBuildParameters(true); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("Tag", "trunk"), new StringParameterValue("WORKSPACE", "C:/path/to/my/workspace"))).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); this.j.assertLogContains(ALL_IS_WELL, build); } @Test public void nonExistentBasicAuthFailsTheBuild() throws Exception { // Prepare the server registerBasicAuth(); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/basicAuth"); httpRequest.setAuthentication("non-existent-key"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); } @Test public void canDoBasicDigestAuthentication() throws Exception { // Prepare the server registerBasicAuth(); // Prepare the authentication registerBasicCredential("keyname1", "username1", "password1"); registerBasicCredential("keyname2", "username2", "password2"); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/basicAuth"); httpRequest.setAuthentication("keyname1"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); } @Test public void testFormAuthentication() throws Exception { final String paramUsername = "username"; final String valueUsername = "user"; final String paramPassword = "password"; final String valuePassword = "pass"; final String sessionName = "VALID_SESSIONID"; registerHandler("/form-auth", HttpMode.POST, new SimpleHandler() { @Override void doHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String username = request.getParameter(paramUsername); String password = request.getParameter(paramPassword); if (!username.equals(valueUsername) || !password.equals(valuePassword)) { response.setStatus(401); return; } response.addCookie(new Cookie(sessionName, "ok")); okAllIsWell(response); } }); registerHandler("/test-auth", HttpMode.GET, new SimpleHandler() { @Override void doHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String jsessionValue = ""; Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { if (cookie.getName().equals(sessionName)) { jsessionValue = cookie.getValue(); break; } } if (!jsessionValue.equals("ok")) { response.setStatus(401); return; } okAllIsWell(response); } }); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<>(); params.add(new HttpRequestNameValuePair(paramUsername, valueUsername)); params.add(new HttpRequestNameValuePair(paramPassword, valuePassword)); RequestAction action = new RequestAction(new URL(baseURL() + "/form-auth"), HttpMode.POST, null, params); List<RequestAction> actions = new ArrayList<RequestAction>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("Form", actions); List<FormAuthentication> formAuthList = new ArrayList<FormAuthentication>(); formAuthList.add(formAuth); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/test-auth"); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); httpRequest.setAuthentication("Form"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); } @Test public void canDoFormAuthentication() throws Exception { // Prepare the server registerFormAuth(); registerReqAction(); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<HttpRequestNameValuePair>(); params.add(new HttpRequestNameValuePair("param1", "value1")); params.add(new HttpRequestNameValuePair("param2", "value2")); RequestAction action = new RequestAction(new URL(baseURL() + "/reqAction"), HttpMode.GET, null, params); List<RequestAction> actions = new ArrayList<RequestAction>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname", actions); List<FormAuthentication> formAuthList = new ArrayList<FormAuthentication>(); formAuthList.add(formAuth); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/formAuth"); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); httpRequest.setAuthentication("keyname"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.SUCCESS, build); } @Test public void rejectedFormCredentialsFailTheBuild() throws Exception { // Prepare the server registerFormAuthBad(); // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<HttpRequestNameValuePair>(); params.add(new HttpRequestNameValuePair("param1", "value1")); params.add(new HttpRequestNameValuePair("param2", "value2")); RequestAction action = new RequestAction(new URL(baseURL() + "/formAuthBad"), HttpMode.GET, null, params); List<RequestAction> actions = new ArrayList<RequestAction>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname", actions); List<FormAuthentication> formAuthList = new ArrayList<FormAuthentication>(); formAuthList.add(formAuth); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/formAuthBad"); httpRequest.setConsoleLogResponseBody(true); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); httpRequest.setAuthentication("keyname"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Error doing authentication", build); } @Test public void invalidKeyFormAuthenticationFailsTheBuild() throws Exception { // Prepare the server // Prepare the authentication List<HttpRequestNameValuePair> params = new ArrayList<HttpRequestNameValuePair>(); params.add(new HttpRequestNameValuePair("param1", "value1")); params.add(new HttpRequestNameValuePair("param2", "value2")); // The request action won't be sent but we need to prepare it RequestAction action = new RequestAction(new URL(baseURL() + "/non-existent"), HttpMode.GET, null, params); List<RequestAction> actions = new ArrayList<RequestAction>(); actions.add(action); FormAuthentication formAuth = new FormAuthentication("keyname", actions); List<FormAuthentication> formAuthList = new ArrayList<FormAuthentication>(); formAuthList.add(formAuth); // Prepare HttpRequest - the actual request won't be sent HttpRequest httpRequest = new HttpRequest(baseURL() + "/non-existent"); httpRequest.setConsoleLogResponseBody(true); HttpRequestGlobalConfig.get().setFormAuthentications(formAuthList); // Select a non-existent form authentication, this will error the build before any request is made httpRequest.setAuthentication("non-existent"); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatus(Result.FAILURE, build); this.j.assertLogContains("Authentication 'non-existent' doesn't exist anymore", build); } @Test public void responseContentSupplierHeadersFilling() throws Exception { // Prepare test context HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK"); response.setEntity(new StringEntity("TEST")); response.setHeader("Server", "Jenkins"); response.setHeader("Set-Cookie", "JSESSIONID=123456789"); response.addHeader("Set-Cookie", "JSESSIONID=abcdefghijk"); // Run test ResponseContentSupplier respSupplier = new ResponseContentSupplier(ResponseHandle.STRING, response); // Check expectations Assert.assertEquals(2, respSupplier.getHeaders().size()); Assert.assertTrue(respSupplier.getHeaders().containsKey("Server")); Assert.assertTrue(respSupplier.getHeaders().containsKey("Set-Cookie")); Assert.assertEquals(1, respSupplier.getHeaders().get("Server").size()); Assert.assertEquals(2, respSupplier.getHeaders().get("Set-Cookie").size()); Assert.assertEquals("Jenkins", respSupplier.getHeaders().get("Server").get(0)); int valuesFoundCounter = 0; for (String s : respSupplier.getHeaders().get("Set-Cookie")) { if ("JSESSIONID=123456789".equals(s)) { valuesFoundCounter++; } else if ("JSESSIONID=abcdefghijk".equals(s)) { valuesFoundCounter++; } } Assert.assertEquals(2, valuesFoundCounter); respSupplier.close(); } @Test public void testFileUpload() throws Exception { // Prepare the server final File testFolder = folder.newFolder(); File uploadFile = File.createTempFile("upload", ".zip", testFolder); String responseText = "File upload successful!"; registerFileUpload(testFolder, uploadFile, responseText); // Prepare HttpRequest HttpRequest httpRequest = new HttpRequest(baseURL() + "/uploadFile"); httpRequest.setHttpMode(HttpMode.POST); httpRequest.setValidResponseCodes("201"); httpRequest.setConsoleLogResponseBody(true); httpRequest.setUploadFile(uploadFile.getAbsolutePath()); httpRequest.setMultipartName("file-name"); httpRequest.setContentType(MimeType.APPLICATION_ZIP); httpRequest.setAcceptType(MimeType.TEXT_PLAIN); // Run build FreeStyleProject project = this.j.createFreeStyleProject(); project.getBuildersList().add(httpRequest); FreeStyleBuild build = project.scheduleBuild2(0).get(); // Check expectations this.j.assertBuildStatusSuccess(build); this.j.assertLogContains(responseText, build); } }
vfreex/http-request-plugin
src/test/java/jenkins/plugins/http_request/HttpRequestTest.java
44,636
package gui; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class PreviewPanel extends JPanel { JPanel blackBorderPanel; JPanel whiteBorderPanel; JLabel titleLabel; JLabel typeLabel; JLabel locationLabel; JLabel ratingLabel; MyButton previewButton; public PreviewPanel(String name, String type, String location, float rating) { titleLabel = new JLabel("<html>" + name + " - " + type + "</html>"); titleLabel.setFont(titleLabel.getFont().deriveFont(14.0f)); locationLabel = new JLabel("<html>" + location + "</html>"); locationLabel.setFont(locationLabel.getFont().deriveFont(12.0f)); ratingLabel = new JLabel("<html>" + "Βαθμολογία: " + (float) Math.round(rating * 100) / 100 + "</html>"); ratingLabel.setFont(ratingLabel.getFont().deriveFont(13.0f)); whiteBorderPanel = new JPanel(); whiteBorderPanel.setLayout(new BoxLayout(whiteBorderPanel, BoxLayout.PAGE_AXIS)); whiteBorderPanel.setBorder(BorderFactory.createLineBorder(getBackground(), 3)); whiteBorderPanel.add(titleLabel); whiteBorderPanel.add(locationLabel); whiteBorderPanel.add(ratingLabel); blackBorderPanel = new JPanel(); blackBorderPanel.setLayout(new BoxLayout(blackBorderPanel, BoxLayout.PAGE_AXIS)); blackBorderPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 3)); blackBorderPanel.add(whiteBorderPanel); previewButton = new MyButton(); previewButton.add(blackBorderPanel); previewButton.setLayout(new BoxLayout(previewButton, BoxLayout.PAGE_AXIS)); previewButton.setBorder(BorderFactory.createEmptyBorder()); setBorder(BorderFactory.createLineBorder(getBackground(), 3)); setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); add(previewButton); } public void addPreviewListener(ActionListener listener) { previewButton.addActionListener(listener); } public void updatePreview(String name, String type, String location, float rating) { titleLabel.setText("<html>" + name + " - " + type + "</html>"); locationLabel.setText("<html>" + location + "</html>"); ratingLabel.setText("<html>" + "Βαθμολογία: " + (float) Math.round(rating * 100) / 100 + "</html>"); revalidate(); repaint(); } }
kyrtsouv/Rental-Review
src/gui/PreviewPanel.java
44,687
/* * Vytvorte triedu Triangel, ktora bude poskytovat metody double obvod() a boolean is() * clenske premenne: sideA, sideB, sideC, -> celociselne (int) * * Modifikujte triedu Triangel tak, aby konstruktor osetril pripady ked zadavame strany netvoria trojuholnik * a + b > c * b + c > a * a + c > b * V tomto pripade konstruktor nastavi vsetky strany na 0 * * Pretazte konstruktor Trojuholnik (int firstSide), ktory bude vytvarat rovnostranne trojuholniky * * Pretazte konstruktor Trojuholnik (int firstSide, int secondSide), ktory bude vytvarat rovnoramenne trojuholnik */ import java.util.Scanner; public class Trojuholnik { int stranaA; int stranaB; int stranaC; public Trojuholnik(int stranaA, int stranaB, int stranaC) { if((stranaA + stranaB) > stranaC && (stranaA + stranaC) > stranaB && (stranaC + stranaB) > stranaA) { this.stranaA = stranaA; this.stranaB = stranaB; this.stranaC = stranaC; } else { this.stranaA = 0; this.stranaB = 0; this.stranaC = 0; } } public Trojuholnik(int stranaA, int stranaB) { if((stranaA + stranaA) > stranaB) { this.stranaA = stranaA; this.stranaB = stranaA; this.stranaC = stranaB; } else { this.stranaA = 0; this.stranaB = 0; this.stranaC = 0; } } public Trojuholnik(int stranaA) { this.stranaA = stranaA; this.stranaB = stranaA; this.stranaC = stranaA; } double obvod() { return stranaA + stranaB + stranaC; } boolean jePravouhly() { if((stranaA * stranaA) + (stranaB * stranaB) == (stranaC * stranaC) || (stranaA * stranaA) + (stranaC * stranaC) == (stranaB * stranaB) || (stranaC * stranaC) + (stranaB * stranaB) == (stranaA * stranaA)) { return true; } return false; } public static void main(String[] args) { Scanner side = new Scanner(System.in); System.out.println("Zadajte stranu A"); int sideA = side.nextInt(); System.out.println("Zadajte stranu B"); int sideB = side.nextInt(); System.out.println("Zadajte stranu C"); int sideC = side.nextInt(); Trojuholnik troj1 = new Trojuholnik(sideA); Trojuholnik troj2 = new Trojuholnik(sideA, sideB); Trojuholnik troj3 = new Trojuholnik(sideA, sideB, sideC); System.out.println("Pravouhly: " + troj1.jePravouhly() + ", Obvod: " + troj1.obvod()); System.out.println("Pravouhly: " + troj2.jePravouhly() + ", Obvod: " + troj2.obvod()); System.out.println("Pravouhly: " + troj3.jePravouhly() + ", Obvod: " + troj3.obvod()); } }
TheInventori/OBP
2024-02-19/Μπεκιάρης/Trojuholnik.java
44,753
/* *ATTENTION* *ATTENTION* *ATTENTION* *ATTENTION* * * This Japanese text to speech module is subject to the terms of the LGPL version 3.0, * which can be found here http://www.gnu.org/licenses/lgpl-3.0-standalone.html. * * In addition, if you use this module in something cool like a robot, you are kindly asked to do the following: * * - Put a Seunghee or スンヒ nametag on the robot * * - have the robot say ‘ウヤ, 今ヤめて’ ‘かあああさん, ねさん文句ばっか’, 'あかはんはそんな!?' (respectively, * ‘Jay, stop kidding’, ‘Mooom, big sis is complaining agaain’, 'R'you'kidding') * * - take a video and send it to ‘hansteffi ATSIGN gmail ANOTHERDOT com’ * * 日本で出会ったスンヒのヴァレンタイン * Copyright 2014 Seunghee Han */ package marytts.language.ja.phonemes; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class XSampa { public interface Phoneme { String getXSampaCode(); String getIpaCode(); String getName(); String getExample(); } private static ArrayList<Consonant> consonantsPrivate = new ArrayList<Consonant>(); private static ArrayList<Vowel> vowelsPrivate = new ArrayList<Vowel>(); static { consonantsPrivate.add(new Consonant(true,ConsonantPlace.Bilabial,ConsonantType.Plosive,"b","b","voiced bilabial plosive","English bed [bEd], French bon [bO~]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Bilabial,ConsonantType.Implosive,"b_<","ɓ","voiced bilabial implosive","Sindhi ɓarʊ [b_<arU]")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.Palatal,ConsonantType.Plosive,"c","c","voiceless Palatal plosive","Hungarian latyak [\"lQcQk]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Alveolar,ConsonantType.Plosive,"d","d","voiced Alveolar plosive","English dig [dIg], French doigt [dwa]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Retroflex,ConsonantType.Plosive,"d`","ɖ","voiced retroflex plosive","Swedish hord [hu:d`]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Alveolar,ConsonantType.Implosive,"d_<","ɗ","voiced Alveolar implosive","Sindhi ɗarʊ [d_<arU]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Labiodental,ConsonantType.Fricative,"f","f","voiceless Labiodental Fricative","English five [faIv], French femme [fam]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Velar,ConsonantType.Plosive,"g","g","voiced velar plosive","English game [geIm], French longue [lO~g]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Velar,ConsonantType.Implosive,"g_<","ɠ","voiced velar implosive","Sindhi ɠəro [g_<@ro]")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.Glottal,ConsonantType.Fricative,"h","h","voiceless glottal Fricative","English house [haUs]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Glottal,ConsonantType.Fricative,"h\\","ɦ","voiced glottal Fricative","Czech hrad [h\\rat]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Palatal,ConsonantType.Fricative,"j\\","ʝ","voiced Palatal Fricative","Greek γειά [j\\a]")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.Velar,ConsonantType.Plosive,"k","k","voiceless velar plosive","English scat [sk{t], Spanish carro [\"kar:o]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Alveolar,ConsonantType.LateralApproximant,"l","l","Alveolar Lateral approximant","English lay [leI], French mal [mal]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Retroflex,ConsonantType.LateralApproximant,"l`","ɭ","retroflex Lateral approximant","Svealand Swedish sorl [so:l`]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Alveolar,ConsonantType.LateralFlap,"l\\","ɺ","Alveolar Lateral flap","Japanese rakuten [l\\akM_0teN\\]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Bilabial,ConsonantType.Nasal,"m","m","bilabial nasal","English mouse [maUs], French homme [Om]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Alveolar,ConsonantType.Nasal,"n","n","Alveolar nasal","English nap [n{p], French non [nO~]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Retroflex,ConsonantType.Nasal,"n`","ɳ","retroflex nasal","Swedish hörn [h2:n`]")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.Bilabial,ConsonantType.Plosive,"p","p","voiceless bilabial plosive","English speak [spik], French pose [poz], Spanish perro [\"per:o]")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.Bilabial,ConsonantType.Fricative,"p\\","ɸ","voiceless bilabial Fricative","Japanese fuku [p\\M_0kM]")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.Uvular,ConsonantType.Plosive,"q","q","voiceless Uvular plosive","Arabic qasbah [\"qQs_Gba]")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.Alveolar,ConsonantType.Trill,"r","r","Alveolar Trill","Spanish perro [\"per:o]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Retroflex,ConsonantType.Flap,"r`","ɽ","retroflex flap"," ")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Alveolar,ConsonantType.Approximant,"r\\","ɹ","Alveolar approximant","English red [r\\Ed]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Retroflex,ConsonantType.Approximant,"r\\`","ɻ","retroflex approximant","Malayalam വഴി [\\\"v6r\\`i]")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.Alveolar,ConsonantType.Fricative,"s","s","voiceless Alveolar Fricative","English seem [si:m], French session [se\"sjO~]")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.Retroflex,ConsonantType.Fricative,"s`","ʂ","voiceless retroflex Fricative","Swedish mars [mas`]")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.AlveoloPalatal,ConsonantType.Fricative,"s\\","ɕ","voiceless alveolo-Palatal Fricative","Polish świerszcz [s\\v'erStS]")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.Alveolar,ConsonantType.Plosive,"t","t","voiceless Alveolar plosive","English stew [stju:], French raté [Ra\"te], Spanish tuyo [\"tujo]")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.Retroflex,ConsonantType.Plosive,"t`","ʈ","voiceless retroflex plosive","Swedish mört [m2t`]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Labiodental,ConsonantType.Fricative,"v","v","voiced Labiodental Fricative","English vest [vEst], French voix [vwa]")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.LabialVelar,ConsonantType.Approximant,"v\\ (or P)","ʋ","Labiodental approximant","Dutch west [v\\Est]/[PEst]")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.Labiodental,ConsonantType.Approximant,"w","w","labial-velar approximant","English west [wEst], French oui [wi]")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.Velar,ConsonantType.Fricative,"x","x","voiceless velar Fricative","Scots loch [lOx] or [5Ox]; German Buch, Dach; Spanish caja, gestión")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.PalatalVelar,ConsonantType.Fricative,"x\\","ɧ","voiceless Palatal-velar Fricative","Swedish sjal [x\\A:l]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Alveolar,ConsonantType.Fricative,"z","z","voiced Alveolar Fricative","English zoo [zu:], French azote [a\"zOt]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Retroflex,ConsonantType.Fricative,"z`","ʐ","voiced retroflex Fricative","Mandarin Chinese rang [z`aN]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.AlveoloPalatal,ConsonantType.Fricative,"z\\","ʑ","voiced alveolo-Palatal Fricative","Polish źrebak [\"z\\rEbak]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Bilabial,ConsonantType.Fricative,"B","β","voiced bilabial Fricative","Spanish lavar [la\"Ba4]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Bilabial,ConsonantType.Trill,"B\\","ʙ","bilabial Trill","Reminiscent of shivering (\"brrr\\\")")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.Palatal,ConsonantType.Fricative,"C","ç","voiceless Palatal Fricative","German ich [IC], English human [\"Cjum@n] (broad transcription uses [hj-])")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Dental,ConsonantType.Fricative,"D","ð","voiced dental Fricative","English then [DEn]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Labiodental,ConsonantType.Nasal,"F","ɱ","Labiodental nasal","English emphasis [\"EFf@sIs] (spoken quickly, otherwise uses [Emf-])")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Velar,ConsonantType.Fricative,"G","ɣ","voiced velar Fricative","Greek γωνία [Go\"nia], Danish vælge [\"vElG@]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Uvular,ConsonantType.Plosive,"G\\","ɢ","voiced Uvular plosive","Inuktitut nirivvik [niG\\ivvik]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Uvular,ConsonantType.Plosive,"G\\_<","ʛ","voiced Uvular implosive","Mam ʛa [G\\_<a]")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.Epiglottal,ConsonantType.Fricative,"H\\","ʜ","voiceless epiglottal Fricative"," ")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Palatal,ConsonantType.Nasal,"J","ɲ","Palatal nasal","Spanish año [\"aJo], English canyon [\"k{J@n] (broad transcription uses [-nj-])")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Palatal,ConsonantType.Plosive,"J\\","ɟ","voiced Palatal plosive","Hungarian egy [EJ\\]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Palatal,ConsonantType.Implosive,"J\\_<","ʄ","voiced Palatal implosive","Sindhi ʄaro [J\\_<aro]")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.Alveolar,ConsonantType.LateralFricative,"K","ɬ","voiceless Alveolar Lateral Fricative","Welsh llaw [KaU]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Alveolar,ConsonantType.LateralFricative,"K\\","ɮ","voiced Alveolar Lateral Fricative"," ")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Palatal,ConsonantType.LateralApproximant,"L","ʎ","Palatal Lateral approximant","Italian famiglia [fa\"miLLa], Castilian llamar [La\"mar], English million [\"mIL@n] (broad transcription uses [-lj-])")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Velar,ConsonantType.LateralApproximant,"L\\","ʟ","velar Lateral approximant","")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Velar,ConsonantType.Approximant,"M\\","ɰ","velar approximant","Spanish fuego [\"fweM\\o]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Velar,ConsonantType.Nasal,"N","ŋ","velar nasal","English thing [TIN]")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.Uvular,ConsonantType.Nasal,"N\\","ɴ","Uvular nasal","Japanese san [saN\\]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Labiodental,ConsonantType.Approximant,"P","ʋ","Labiodental approximant","Dutch west [PEst]/[v\\Est], allophone of English phoneme /r\\/")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Uvular,ConsonantType.Fricative,"R","ʁ","voiced Uvular Fricative","German rein [RaIn]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Uvular,ConsonantType.Trill,"R\\","ʀ","Uvular Trill","French roi [R\\wa]")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.Postalveolar,ConsonantType.Fricative,"S","ʃ","voiceless postAlveolar Fricative","English ship [SIp]")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.Dental,ConsonantType.Fricative,"T","θ","voiceless dental Fricative","English thin [TIn]")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.LabialVelar,ConsonantType.Fricative,"W","ʍ","voiceless labial-velar Fricative","Scots when [WEn]")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.Uvular,ConsonantType.Fricative,"X","χ","voiceless Uvular Fricative","Klallam sχaʔqʷaʔ [sXa?q_wa?]")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.Pharyngeal,ConsonantType.Fricative,"X\\","ħ","voiceless pharyngeal Fricative","Arabic <ح>ha’ [X\\A:]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Postalveolar,ConsonantType.Fricative,"Z","ʒ","voiced postAlveolar Fricative","English vision [\"vIZ@n]")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.Alveolar,ConsonantType.Flap,"4","ɾ","Alveolar flap","Spanish pero [\"pe4o], American English better [\"bE4@`]")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.VelarizedAlveolar,ConsonantType.LateralApproximant,"5","ɫ","velarized Alveolar Lateral approximant; also see _e","English milk [mI5k], Portuguese livro [\"5iv4u]")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.Glottal,ConsonantType.Stop,"?","ʔ","glottal stop","Danish stød [sd2?], Cockney English bottle [\"bQ?l]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Pharyngeal,ConsonantType.Fricative,"?\\","ʕ","voiced pharyngeal fricative","Arabic ع (`ayn) [?\\Ajn]")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Epiglottal,ConsonantType.Fricative,"<\\","ʢ","voiced epiglottal fricative"," ")); consonantsPrivate.add(new Consonant(true,ConsonantPlace.Epiglottal,ConsonantType.Plosive,">\\","ʡ","epiglottal plosive"," ")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.Palatal,ConsonantType.Approximant,"j","j","palatal approximant","English yes [jEs], French yeux [j2]")); consonantsPrivate.add(new Consonant(false,ConsonantPlace.LabioPalatal,ConsonantType.Approximant,"H","ɥ","labial-palatal approximant","French huit [Hit]")); for(Consonant c:consonantsPrivate) { c.preventFurtherModification(); } vowelsPrivate.add(new Vowel(false,false,false,VowelOpenness.Open,VowelPosition.Front,"a","a","open front unrounded vowel","French dame [dam], Spanish padre [\"paD4e]")); vowelsPrivate.add(new Vowel(false,false,false,VowelOpenness.CloseMid,VowelPosition.Front,"e","e","close-mid front unrounded vowel","French ses [se], English met [met] (AusE and NZE)")); vowelsPrivate.add(new Vowel(false,false,false,VowelOpenness.Close,VowelPosition.Front,"i","i","close front unrounded vowel","English be [bi:], French oui [wi], Spanish si [si]")); vowelsPrivate.add(new Vowel(false,false,true,VowelOpenness.CloseMid,VowelPosition.Back,"o","o","close-mid back rounded vowel","French gros [gRo]")); vowelsPrivate.add(new Vowel(false,false,true,VowelOpenness.Close,VowelPosition.Back,"u","u","close back rounded vowel","English boom [bu:m], Spanish su [su]")); vowelsPrivate.add(new Vowel(false,false,true,VowelOpenness.Close,VowelPosition.Front,"y","y","close front rounded vowel","French tu [ty] German über [\"y:b6]")); vowelsPrivate.add(new Vowel(false,false,false,VowelOpenness.Open,VowelPosition.Back,"A","ɑ","open back unrounded vowel","English father [\"fA:D@(r\\)] (RP and Gen.Am.)")); vowelsPrivate.add(new Vowel(false,false,false,VowelOpenness.OpenMid,VowelPosition.Front,"E","ɛ","open-mid front unrounded vowel","French même [mEm], English met [mEt] (RP and Gen.Am.)")); vowelsPrivate.add(new Vowel(false,false,false,VowelOpenness.NearClose,VowelPosition.NearFront,"I","ɪ","near-close near-front unrounded vowel","English kit [kIt]")); vowelsPrivate.add(new Vowel(false,false,true,VowelOpenness.NearClose,VowelPosition.Central,"I\\","ᵻ or ɪ̈","near-close central unrounded vowel","Polish ryba [rI\\bA] ")); vowelsPrivate.add(new Vowel(false,false,false,VowelOpenness.Close,VowelPosition.Back,"M","ɯ","close back unrounded vowel","Korean 으 (eu)")); vowelsPrivate.add(new Vowel(false,false,true,VowelOpenness.Open,VowelPosition.BackMid,"O","ɔ","open-mid back rounded vowel","RP thought [TO:t], American English off [O:f]")); vowelsPrivate.add(new Vowel(false,false,true,VowelOpenness.Open,VowelPosition.Back,"Q","ɒ","open back rounded vowel","RP lot [lQt]")); vowelsPrivate.add(new Vowel(false,false,true,VowelOpenness.NearClose,VowelPosition.NearBack,"U","ʊ","near-close near-back rounded vowel","English foot [fUt]")); vowelsPrivate.add(new Vowel(false,false,true,VowelOpenness.NearClose,VowelPosition.Central,"U\\","ᵿ or ʊ̈","near-close central rounded vowel","English euphoria [jU\\\"fO@r\\i@]")); vowelsPrivate.add(new Vowel(false,false,false,VowelOpenness.OpenMid,VowelPosition.Back,"V","ʌ","open-mid back unrounded vowel","RP English strut [str\\Vt]")); vowelsPrivate.add(new Vowel(false,false,false,VowelOpenness.NearClose,VowelPosition.NearFront,"Y","ʏ","near-close near-front rounded vowel","German hübsch [hYpS]")); vowelsPrivate.add(new Vowel(false,false,false,VowelOpenness.Mid,VowelPosition.Central,"@","ə","schwa","English arena [@\"r\\i:n@]")); vowelsPrivate.add(new Vowel(false,false,false,VowelOpenness.CloseMid,VowelPosition.Central,"@\\","ɘ","close-mid central unrounded vowel","Paicĩ kɘ̄ɾɘ [k@\\_M4@\\_M]")); vowelsPrivate.add(new Vowel(false,false,false,VowelOpenness.NearOpen,VowelPosition.Front,"{","æ","near-open front unrounded vowel","English trap [tr\\{p]")); vowelsPrivate.add(new Vowel(false,false,true,VowelOpenness.Close,VowelPosition.Central,"}","ʉ","close central rounded vowel","Swedish sju [x\\}:]; AuE/NZE boot [b}:t]")); vowelsPrivate.add(new Vowel(false,false,false,VowelOpenness.Close,VowelPosition.Central,"1","ɨ","close central unrounded vowel","Welsh tu [t1], American English rose's [\"r\\oUz1z]")); vowelsPrivate.add(new Vowel(false,false,true,VowelOpenness.CloseMid,VowelPosition.Front,"2","ø","close-mid front rounded vowel","Danish købe [\"k2:b@], French deux [d2]")); vowelsPrivate.add(new Vowel(false,false,false,VowelOpenness.OpenMid,VowelPosition.Central,"3","ɜ","open-mid central unrounded vowel","English nurse [n3:s] (RP) or [n3`s] (Gen.Am.)")); vowelsPrivate.add(new Vowel(false,false,true,VowelOpenness.Open,VowelPosition.Central,"3\\","ɞ","open-mid central rounded vowel","Irish tomhail[t3\\:l']")); vowelsPrivate.add(new Vowel(false,false,true,VowelOpenness.NearOpen,VowelPosition.Central,"6","ɐ","near-open central vowel","German besser [\"bEs6], Australian English mud [m6d]")); vowelsPrivate.add(new Vowel(false,false,false,VowelOpenness.CloseMid,VowelPosition.Back,"7","ɤ","close-mid back unrounded vowel","Estonian kõik [k7ik], Vietnamese mơ [m7_M]")); vowelsPrivate.add(new Vowel(false,false,true,VowelOpenness.CloseMid,VowelPosition.Central,"8","ɵ","close-mid central rounded vowel","Swedish buss [b8s]")); vowelsPrivate.add(new Vowel(false,false,true,VowelOpenness.OpenMid,VowelPosition.Front,"9","œ","open-mid front rounded vowel","French neuf [n9f], Danish drømme [dR9m@]")); vowelsPrivate.add(new Vowel(false,false,true,VowelOpenness.Open,VowelPosition.Front,"&","ɶ","open front rounded vowel","Swedish skörd [x\\&d`]")); for(Vowel v:vowelsPrivate) { v.preventFurtherModification(); } } public static List<Consonant> consonants = Collections.unmodifiableList(consonantsPrivate); public static List<Vowel> vowels = Collections.unmodifiableList(vowelsPrivate); public static Consonant findConsonantByIPA(String ipaCode) { for(Consonant consonant:consonants) { if(consonant.getIpaCode().equals(ipaCode)) { return consonant; } } //return null; throw new IllegalArgumentException("Unknown IPA: "+ipaCode); } public static Vowel findVowelByIPA(String ipaCode) { for(Vowel vowel:vowels) { if(vowel.getIpaCode().equals(ipaCode)) { return vowel; } } return null; } public enum ConsonantPlace { Bilabial, Labiodental, LabialVelar, Dental, VelarizedAlveolar, Alveolar, Postalveolar, Retroflex, AlveoloPalatal, Palatal, PalatalVelar, Velar, Uvular, Pharyngeal, Epiglottal, Glottal, LabioPalatal, } public enum ConsonantType { Plosive, Implosive, Fricative, LateralFricative, Approximant, LateralApproximant, Flap, LateralFlap, Nasal, Trill, Stop } public static class Consonant implements Phoneme { private boolean noModification; private boolean voiced; private ConsonantPlace place; private ConsonantType type; private String xSampaCode; private String ipaCode; private String name; private String example; public Consonant(Consonant copiedConsonant) { this.noModification = false; this.voiced = copiedConsonant.voiced; this.place = copiedConsonant.place; this.type = copiedConsonant.type; this.xSampaCode = copiedConsonant.xSampaCode; this.ipaCode = copiedConsonant.ipaCode; this.name = copiedConsonant.name; this.example = copiedConsonant.example; } public Consonant(boolean voiced, ConsonantPlace place, ConsonantType type, String xSampaCode, String ipaCode, String name, String wikipediaExample) { this.noModification = true; this.voiced = voiced; this.place = place; this.type = type; this.xSampaCode = xSampaCode; this.ipaCode = ipaCode; this.name = name; this.example = wikipediaExample; } public boolean isVoiced() { return voiced; } public ConsonantPlace getPlace() { return place; } public ConsonantType getType() { return type; } public String getXSampaCode() { return xSampaCode; } public String getIpaCode() { return ipaCode; } public String getName() { return name; } public String getExample() { return example; } public void setVoiced(boolean voiced) { if(noModification){throw new IllegalArgumentException("This consonant cannot be modified, copy it or create a new one");} this.voiced = voiced; } public void setPlace(ConsonantPlace place) { if(noModification){throw new IllegalArgumentException("This consonant cannot be modified, copy it or create a new one");} this.place = place; } public void setType(ConsonantType type) { if(noModification){throw new IllegalArgumentException("This consonant cannot be modified, copy it or create a new one");} this.type = type; } public void setXSampaCode(String xSampaCode) { if(noModification){throw new IllegalArgumentException("This consonant cannot be modified, copy it or create a new one");} this.xSampaCode = xSampaCode; } public void setIpaCode(String ipaCode) { if(noModification){throw new IllegalArgumentException("This consonant cannot be modified, copy it or create a new one");} this.ipaCode = ipaCode; } public void setName(String name) { if(noModification){throw new IllegalArgumentException("This consonant cannot be modified, copy it or create a new one");} this.name = name; } public void setExample(String example) { if(noModification){throw new IllegalArgumentException("This consonant cannot be modified, copy it or create a new one");} this.example = example; } public void preventFurtherModification() { noModification = true; } } public enum VowelOpenness { Open, NearOpen, OpenMid, Mid, CloseMid, NearClose, Close } public enum VowelPosition { Front, NearFront, FrontMid, Central, BackMid, NearBack, Back } public static class Vowel implements Phoneme { private boolean noModification; private boolean nasalized; private boolean roundedness; private VowelOpenness openness; private VowelPosition position ; private String xSampaCode; private String ipaCode; private String name; private String example; private boolean longVowel; public Vowel(Vowel copiedVowel) { this.noModification = false; this.longVowel = copiedVowel.longVowel; this.nasalized = copiedVowel.nasalized; this.roundedness = copiedVowel.roundedness; this.openness = copiedVowel.openness; this.position = copiedVowel.position; this.xSampaCode = copiedVowel.xSampaCode; this.ipaCode = copiedVowel.ipaCode; this.name = copiedVowel.name; this.example = copiedVowel.example; } public Vowel(boolean longVowel, boolean nasalized, boolean roundedness, VowelOpenness openness, VowelPosition position, String xSampaCode, String ipaCode, String name, String example) { this.noModification = false; this.longVowel = longVowel; this.nasalized = nasalized; this.roundedness = roundedness; this.openness = openness; this.position = position; this.xSampaCode = xSampaCode; this.ipaCode = ipaCode; this.name = name; this.example = example; } public boolean isLongVowel() { return longVowel; } public boolean isNasalized() { return nasalized; } public boolean isRounded() { return roundedness; } public VowelOpenness getOpenness(){ return openness; } public VowelPosition getPosition(){ return position; } public String getXSampaCode() { return xSampaCode; } public String getIpaCode() { return ipaCode; } public String getName() { return name; } public String getExample() { return example; } public void setNasalized(boolean nasalized) { if(noModification){throw new IllegalArgumentException("This vowel cannot be modified, copy it or create a new one");} this.nasalized = nasalized; } public void setRoundedness(boolean roundedness) { if(noModification){throw new IllegalArgumentException("This vowel cannot be modified, copy it or create a new one");} this.roundedness = roundedness; } public void setOpenness(VowelOpenness openness) { if(noModification){throw new IllegalArgumentException("This vowel cannot be modified, copy it or create a new one");} this.openness = openness; } public void setPosition(VowelPosition position) { if(noModification){throw new IllegalArgumentException("This vowel cannot be modified, copy it or create a new one");} this.position = position; } public void setxSampaCode(String xSampaCode) { if(noModification){throw new IllegalArgumentException("This vowel cannot be modified, copy it or create a new one");} this.xSampaCode = xSampaCode; } public void setIpaCode(String ipaCode) { if(noModification){throw new IllegalArgumentException("This vowel cannot be modified, copy it or create a new one");} this.ipaCode = ipaCode; } public void setName(String name) { if(noModification){throw new IllegalArgumentException("This vowel cannot be modified, copy it or create a new one");} this.name = name; } public void setExample(String example) { if(noModification){throw new IllegalArgumentException("This vowel cannot be modified, copy it or create a new one");} this.example = example; } public void setLongVowel(boolean longVowel) { if(noModification){throw new IllegalArgumentException("This vowel cannot be modified, copy it or create a new one");} this.longVowel = longVowel; } public void preventFurtherModification() { noModification = true; } } }
rbbb/marytts-lang-ja
src/main/java/marytts/language/ja/phonemes/XSampa.java
44,773
/** * Defines the interface for a Cache data structure * The cache stores item of type V with keys of type K. * Keys must be unique * */ public interface Cache<K, V> { /** * Look for data associated with key. * @param key the key to look for * @return The associated data or null if it is not found */ public V lookUp(K key); /** * Stores data with associated with the given key. If required, it evicts a * data record to make room for the new one * @param key the key to associate with the data * @param value the actual data */ public void store(K key, V value); /** * Returns the hit ratio, i.e. the number of times a lookup was successful divided by the number of lookup * @return the cache hit ratio */ public double getHitRatio(); /** * Returns the absolute number of cache hits, i.e. the number of times a lookup found data in the cache */ public long getHits(); /** * Returns the absolute number of cache misses, i.e. the number of times a lookup returned null */ public long getMisses(); /** * Returns the total number of lookups performed by this cache */ public long getNumberOfLookUps(); }
NIKOMAHOS/AUEB_Projects-Exercises
Data Structures with Java/Εργασία 4/src/Cache.java
44,870
404: Not Found
apache/dubbo
dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Live.java
44,871
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.index.engine; import org.apache.lucene.search.ReferenceManager; import org.apache.lucene.util.Accountable; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.RamUsageEstimator; import org.elasticsearch.common.util.concurrent.ConcurrentCollections; import org.elasticsearch.common.util.concurrent.KeyedLock; import org.elasticsearch.core.Releasable; import java.io.IOException; import java.util.Collections; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; /** Maps _uid value to its version information. */ public final class LiveVersionMap implements ReferenceManager.RefreshListener, Accountable { private final KeyedLock<BytesRef> keyedLock = new KeyedLock<>(); private final LiveVersionMapArchive archive; LiveVersionMap() { this(LiveVersionMapArchive.NOOP_ARCHIVE); } LiveVersionMap(LiveVersionMapArchive archive) { this.archive = archive; } public static final class VersionLookup { /** Tracks bytes used by current map, i.e. what is freed on refresh. For deletes, which are also added to tombstones, * we only account for the CHM entry here, and account for BytesRef/VersionValue against the tombstones, since refresh would not * clear this from RAM. */ final AtomicLong ramBytesUsed = new AtomicLong(); private static final VersionLookup EMPTY = new VersionLookup(Collections.emptyMap()); private final Map<BytesRef, VersionValue> map; // each version map has a notion of safe / unsafe which allows us to apply certain optimization in the auto-generated ID usecase // where we know that documents can't have any duplicates so we can skip the version map entirely. This reduces // the memory pressure significantly for this use-case where we often get a massive amount of small document (metrics). // if the version map is in safeAccess mode we track all version in the version map. yet if a document comes in that needs // safe access but we are not in this mode we force a refresh and make the map as safe access required. All subsequent ops will // respect that and fill the version map. The nice part here is that we are only really requiring this for a single ID and since // we hold the ID lock in the engine while we do all this it's safe to do it globally unlocked. // NOTE: these values can both be non-volatile since it's ok to read a stale value per doc ID. We serialize changes in the engine // that will prevent concurrent updates to the same document ID and therefore we can rely on the happens-before guanratee of the // map reference itself. private boolean unsafe; // minimum timestamp of delete operations that were made while this map was active. this is used to make sure they are kept in // the tombstone private final AtomicLong minDeleteTimestamp = new AtomicLong(Long.MAX_VALUE); // Modifies the map of this instance by merging with the given VersionLookup public void merge(VersionLookup versionLookup) { long existingEntriesSize = 0; for (var entry : versionLookup.map.entrySet()) { var existingValue = map.get(entry.getKey()); existingEntriesSize += existingValue == null ? 0 : mapEntryBytesUsed(entry.getKey(), existingValue); } map.putAll(versionLookup.map); adjustRamUsage(versionLookup.ramBytesUsed() - existingEntriesSize); minDeleteTimestamp.accumulateAndGet(versionLookup.minDeleteTimestamp(), Math::min); } // Visible for testing VersionLookup(Map<BytesRef, VersionValue> map) { this.map = map; } public VersionValue get(BytesRef key) { return map.get(key); } VersionValue put(BytesRef key, VersionValue value) { long ramAccounting = mapEntryBytesUsed(key, value); VersionValue previousValue = map.put(key, value); ramAccounting += previousValue == null ? 0 : -mapEntryBytesUsed(key, previousValue); adjustRamUsage(ramAccounting); return previousValue; } public boolean isEmpty() { return map.isEmpty(); } int size() { return map.size(); } public boolean isUnsafe() { return unsafe; } void markAsUnsafe() { unsafe = true; } VersionValue remove(BytesRef uid) { VersionValue previousValue = map.remove(uid); if (previousValue != null) { adjustRamUsage(-mapEntryBytesUsed(uid, previousValue)); } return previousValue; } public void updateMinDeletedTimestamp(DeleteVersionValue delete) { minDeleteTimestamp.accumulateAndGet(delete.time, Math::min); } public long minDeleteTimestamp() { return minDeleteTimestamp.get(); } void adjustRamUsage(long value) { if (value != 0) { long v = ramBytesUsed.addAndGet(value); assert v >= 0 : "bytes=" + v; } } public long ramBytesUsed() { return ramBytesUsed.get(); } public static long mapEntryBytesUsed(BytesRef key, VersionValue value) { return (BASE_BYTES_PER_BYTESREF + key.bytes.length) + (BASE_BYTES_PER_CHM_ENTRY + value.ramBytesUsed()); } // Used only for testing Map<BytesRef, VersionValue> getMap() { return map; } } private static final class Maps { // All writes (adds and deletes) go into here: final VersionLookup current; // Used while refresh is running, and to hold adds/deletes until refresh finishes. We read from both current and old on lookup: final VersionLookup old; // this is not volatile since we don't need to maintain a happens before relationship across doc IDs so it's enough to // have the volatile read of the Maps reference to make it visible even across threads. boolean needsSafeAccess; final boolean previousMapsNeededSafeAccess; Maps(VersionLookup current, VersionLookup old, boolean previousMapsNeededSafeAccess) { this.current = current; this.old = old; this.previousMapsNeededSafeAccess = previousMapsNeededSafeAccess; } Maps() { this(new VersionLookup(ConcurrentCollections.newConcurrentMapWithAggressiveConcurrency()), VersionLookup.EMPTY, false); } boolean isSafeAccessMode() { return needsSafeAccess || previousMapsNeededSafeAccess; } boolean shouldInheritSafeAccess() { final boolean mapHasNotSeenAnyOperations = current.isEmpty() && current.isUnsafe() == false; return needsSafeAccess // we haven't seen any ops and map before needed it so we maintain it || (mapHasNotSeenAnyOperations && previousMapsNeededSafeAccess); } /** * Builds a new map for the refresh transition this should be called in beforeRefresh() */ Maps buildTransitionMap() { return new Maps( new VersionLookup(ConcurrentCollections.newConcurrentMapWithAggressiveConcurrency(current.size())), current, shouldInheritSafeAccess() ); } /** * similar to `invalidateOldMap` but used only for the `unsafeKeysMap` used for assertions */ Maps invalidateOldMapForAssert() { return new Maps(current, VersionLookup.EMPTY, previousMapsNeededSafeAccess); } /** * builds a new map that invalidates the old map but maintains the current. This should be called in afterRefresh() */ Maps invalidateOldMap(LiveVersionMapArchive archive) { archive.afterRefresh(old); return new Maps(current, VersionLookup.EMPTY, previousMapsNeededSafeAccess); } void put(BytesRef uid, VersionValue version) { current.put(uid, version); } void remove(BytesRef uid, DeleteVersionValue deleted) { current.remove(uid); current.updateMinDeletedTimestamp(deleted); if (old != VersionLookup.EMPTY) { // we also need to remove it from the old map here to make sure we don't read this stale value while // we are in the middle of a refresh. Most of the time the old map is an empty map so we can skip it there. old.remove(uid); } } long getMinDeleteTimestamp() { return Math.min(current.minDeleteTimestamp.get(), old.minDeleteTimestamp.get()); } long ramBytesUsed() { return current.ramBytesUsed.get() + old.ramBytesUsed.get(); } } // All deletes also go here, and delete "tombstones" are retained after refresh: private final Map<BytesRef, DeleteVersionValue> tombstones = ConcurrentCollections.newConcurrentMapWithAggressiveConcurrency(); private volatile Maps maps = new Maps(); // we maintain a second map that only receives the updates that we skip on the actual map (unsafe ops) // this map is only maintained if assertions are enabled private volatile Maps unsafeKeysMap = new Maps(); /** * Bytes consumed for each BytesRef UID: * In this base value, we account for the {@link BytesRef} object itself as * well as the header of the byte[] array it holds, and some lost bytes due * to object alignment. So consumers of this constant just have to add the * length of the byte[] (assuming it is not shared between multiple * instances). */ private static final long BASE_BYTES_PER_BYTESREF = // shallow memory usage of the BytesRef object RamUsageEstimator.shallowSizeOfInstance(BytesRef.class) + // header of the byte[] array RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + // with an alignment size (-XX:ObjectAlignmentInBytes) of 8 (default), // there could be between 0 and 7 lost bytes, so we account for 3 // lost bytes on average 3; /** * Bytes used by having CHM point to a key/value. */ private static final long BASE_BYTES_PER_CHM_ENTRY; static { // use the same impl as the Maps does Map<Integer, Integer> map = ConcurrentCollections.newConcurrentMapWithAggressiveConcurrency(); map.put(0, 0); long chmEntryShallowSize = RamUsageEstimator.shallowSizeOf(map.entrySet().iterator().next()); // assume a load factor of 50% // for each entry, we need two object refs, one for the entry itself // and one for the free space that is due to the fact hash tables can // not be fully loaded BASE_BYTES_PER_CHM_ENTRY = chmEntryShallowSize + 2 * RamUsageEstimator.NUM_BYTES_OBJECT_REF; } /** * Tracks bytes used by tombstones (deletes) */ private final AtomicLong ramBytesUsedForTombstones = new AtomicLong(); @Override public void beforeRefresh() throws IOException { // Start sending all updates after this point to the new // map. While reopen is running, any lookup will first // try this new map, then fallback to old, then to the // current searcher: maps = maps.buildTransitionMap(); assert (unsafeKeysMap = unsafeKeysMap.buildTransitionMap()) != null; // This is not 100% correct, since concurrent indexing ops can change these counters in between our execution of the previous // line and this one, but that should be minor, and the error won't accumulate over time: } @Override public void afterRefresh(boolean didRefresh) throws IOException { // We can now drop old because these operations are now visible via the newly opened searcher. Even if didRefresh is false, which // means Lucene did not actually open a new reader because it detected no changes, it's possible old has some entries in it, which // is fine: it means they were actually already included in the previously opened reader, so we can still safely drop them in that // case. This is because we assign new maps (in beforeRefresh) slightly before Lucene actually flushes any segments for the // reopen, and so any concurrent indexing requests can still sneak in a few additions to that current map that are in fact // reflected in the previous reader. We don't touch tombstones here: they expire on their own index.gc_deletes timeframe: maps = maps.invalidateOldMap(archive); assert (unsafeKeysMap = unsafeKeysMap.invalidateOldMapForAssert()) != null; } /** * Returns the live version (add or delete) for this uid. */ VersionValue getUnderLock(final BytesRef uid) { return getUnderLock(uid, maps); } private VersionValue getUnderLock(final BytesRef uid, Maps currentMaps) { assert assertKeyedLockHeldByCurrentThread(uid); // First try to get the "live" value: VersionValue value = currentMaps.current.get(uid); if (value != null) { return value; } value = currentMaps.old.get(uid); if (value != null) { return value; } // We first check the tombstone then the archive since the archive accumulates ids from the old map, and we // makes sure in `putDeleteUnderLock` the old map does not hold an entry that is in tombstone, archive also wouldn't have them. value = tombstones.get(uid); if (value != null) { return value; } return archive.get(uid); } VersionValue getVersionForAssert(final BytesRef uid) { VersionValue value = getUnderLock(uid, maps); if (value == null) { value = getUnderLock(uid, unsafeKeysMap); } return value; } boolean isUnsafe() { return maps.current.isUnsafe() || maps.old.isUnsafe() || archive.isUnsafe(); } void enforceSafeAccess() { maps.needsSafeAccess = true; } boolean isSafeAccessRequired() { return maps.isSafeAccessMode(); } /** * Adds this uid/version to the pending adds map iff the map needs safe access. */ void maybePutIndexUnderLock(BytesRef uid, IndexVersionValue version) { assert assertKeyedLockHeldByCurrentThread(uid); Maps maps = this.maps; if (maps.isSafeAccessMode()) { putIndexUnderLock(uid, version); } else { // Even though we don't store a record of the indexing operation (and mark as unsafe), // we should still remove any previous delete for this uuid (avoid accidental accesses). // Not this should not hurt performance because the tombstone is small (or empty) when unsafe is relevant. removeTombstoneUnderLock(uid); maps.current.markAsUnsafe(); assert putAssertionMap(uid, version); } } void putIndexUnderLock(BytesRef uid, IndexVersionValue version) { assert assertKeyedLockHeldByCurrentThread(uid); assert uid.bytes.length == uid.length : "Oversized _uid! UID length: " + uid.length + ", bytes length: " + uid.bytes.length; maps.put(uid, version); removeTombstoneUnderLock(uid); } private boolean putAssertionMap(BytesRef uid, IndexVersionValue version) { assert assertKeyedLockHeldByCurrentThread(uid); assert uid.bytes.length == uid.length : "Oversized _uid! UID length: " + uid.length + ", bytes length: " + uid.bytes.length; unsafeKeysMap.put(uid, version); return true; } void putDeleteUnderLock(BytesRef uid, DeleteVersionValue version) { assert assertKeyedLockHeldByCurrentThread(uid); assert uid.bytes.length == uid.length : "Oversized _uid! UID length: " + uid.length + ", bytes length: " + uid.bytes.length; putTombstone(uid, version); maps.remove(uid, version); } private void putTombstone(BytesRef uid, DeleteVersionValue version) { long uidRamBytesUsed = BASE_BYTES_PER_BYTESREF + uid.bytes.length; // Also enroll the delete into tombstones, and account for its RAM usage too: final VersionValue prevTombstone = tombstones.put(uid, version); long ramBytes = (BASE_BYTES_PER_CHM_ENTRY + version.ramBytesUsed() + uidRamBytesUsed); // Deduct tombstones bytes used for the version we just removed or replaced: if (prevTombstone != null) { ramBytes -= (BASE_BYTES_PER_CHM_ENTRY + prevTombstone.ramBytesUsed() + uidRamBytesUsed); } if (ramBytes != 0) { long v = ramBytesUsedForTombstones.addAndGet(ramBytes); assert v >= 0 : "bytes=" + v; } } /** * Removes this uid from the pending deletes map. */ void removeTombstoneUnderLock(BytesRef uid) { assert assertKeyedLockHeldByCurrentThread(uid); long uidRamBytesUsed = BASE_BYTES_PER_BYTESREF + uid.bytes.length; final VersionValue prev = tombstones.remove(uid); if (prev != null) { assert prev.isDelete(); long v = ramBytesUsedForTombstones.addAndGet(-(BASE_BYTES_PER_CHM_ENTRY + prev.ramBytesUsed() + uidRamBytesUsed)); assert v >= 0 : "bytes=" + v; } } private boolean canRemoveTombstone(long maxTimestampToPrune, long maxSeqNoToPrune, DeleteVersionValue versionValue) { // check if the value is old enough and safe to be removed final boolean isTooOld = versionValue.time < maxTimestampToPrune; final boolean isSafeToPrune = versionValue.seqNo <= maxSeqNoToPrune; // version value can't be removed it's // not yet flushed to lucene ie. it's part of this current maps object final boolean isNotTrackedByCurrentMaps = versionValue.time < maps.getMinDeleteTimestamp(); final boolean isNotTrackedByArchive = versionValue.time < archive.getMinDeleteTimestamp(); return isTooOld && isSafeToPrune && isNotTrackedByCurrentMaps & isNotTrackedByArchive; } /** * Try to prune tombstones whose timestamp is less than maxTimestampToPrune and seqno at most the maxSeqNoToPrune. */ void pruneTombstones(long maxTimestampToPrune, long maxSeqNoToPrune) { for (Map.Entry<BytesRef, DeleteVersionValue> entry : tombstones.entrySet()) { // we do check before we actually lock the key - this way we don't need to acquire the lock for tombstones that are not // prune-able. If the tombstone changes concurrently we will re-read and step out below since if we can't collect it now w // we won't collect the tombstone below since it must be newer than this one. if (canRemoveTombstone(maxTimestampToPrune, maxSeqNoToPrune, entry.getValue())) { final BytesRef uid = entry.getKey(); try (Releasable lock = keyedLock.tryAcquire(uid)) { // we use tryAcquire here since this is a best effort and we try to be least disruptive // this method is also called under lock in the engine under certain situations such that this can lead to deadlocks // if we do use a blocking acquire. see #28714 if (lock != null) { // did we get the lock? // Must re-get it here, vs using entry.getValue(), in case the uid was indexed/deleted since we pulled the iterator: final DeleteVersionValue versionValue = tombstones.get(uid); if (versionValue != null) { if (canRemoveTombstone(maxTimestampToPrune, maxSeqNoToPrune, versionValue)) { removeTombstoneUnderLock(uid); } } } } } } } /** * Called when this index is closed. */ synchronized void clear() { maps = new Maps(); tombstones.clear(); // NOTE: we can't zero this here, because a refresh thread could be calling InternalEngine.pruneDeletedTombstones at the same time, // and this will lead to an assert trip. Presumably it's fine if our ramBytesUsedForTombstones is non-zero after clear since the // index is being closed: // ramBytesUsedForTombstones.set(0); } @Override public long ramBytesUsed() { return maps.ramBytesUsed() + ramBytesUsedForTombstones.get() + ramBytesUsedForArchive(); } /** * Returns how much RAM is used by refresh. This is the RAM usage of the current and old version maps, and the RAM usage of the * archive, if any. */ long ramBytesUsedForRefresh() { return maps.ramBytesUsed() + archive.getRamBytesUsed(); } /** * Returns how much RAM could be reclaimed from the version map. * <p> * In stateful, this is the RAM usage of the current version map, and could be reclaimed by refreshing. It doesn't include tombstones * since they don't get cleared on refresh, nor the old version map that is being reclaimed. * <p> * In stateless, this is the RAM usage of current and old version map plus the RAM usage of the parts of the archive that require * a new unpromotable refresh. To reclaim all three components we need to refresh AND flush. */ long reclaimableRefreshRamBytes() { return archive == LiveVersionMapArchive.NOOP_ARCHIVE ? maps.current.ramBytesUsed.get() : maps.ramBytesUsed() + archive.getReclaimableRamBytes(); } /** * Returns how much RAM would be freed up by cleaning out the LiveVersionMapArchive. */ long ramBytesUsedForArchive() { return archive.getRamBytesUsed(); } /** * Returns how much RAM is current being freed up by refreshing. In Stateful, this is the RAM usage of the previous version map * that needs to stay around until operations are safely recorded in the Lucene index. In Stateless, this is the RAM usage of a * fraction of the Archive entries that are kept around until an ongoing unpromotable refresh is finished. */ long getRefreshingBytes() { return archive == LiveVersionMapArchive.NOOP_ARCHIVE ? maps.old.ramBytesUsed.get() : archive.getRefreshingRamBytes(); } /** * Returns the current internal versions as a point in time snapshot */ Map<BytesRef, VersionValue> getAllCurrent() { return maps.current.map; } /** Iterates over all deleted versions, including new ones (not yet exposed via reader) and old ones * (exposed via reader but not yet GC'd). */ Map<BytesRef, DeleteVersionValue> getAllTombstones() { return tombstones; } /** * Acquires a releaseable lock for the given uId. All *UnderLock methods require * this lock to be hold by the caller otherwise the visibility guarantees of this version * map are broken. We assert on this lock to be hold when calling these methods. * @see KeyedLock */ Releasable acquireLock(BytesRef uid) { return keyedLock.acquire(uid); } boolean assertKeyedLockHeldByCurrentThread(BytesRef uid) { assert keyedLock.isHeldByCurrentThread(uid) : "Thread [" + Thread.currentThread().getName() + "], uid [" + uid.utf8ToString() + "]"; return true; } // visible for testing purposes only LiveVersionMapArchive getArchive() { return archive; } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/index/engine/LiveVersionMap.java
44,872
/* * Copyright 2017 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.util.internal; import io.netty.util.concurrent.FastThreadLocalThread; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import static io.netty.util.internal.SystemPropertyUtil.getInt; import static java.lang.Math.max; /** * Allows a way to register some {@link Runnable} that will executed once there are no references to an {@link Object} * anymore. */ public final class ObjectCleaner { private static final int REFERENCE_QUEUE_POLL_TIMEOUT_MS = max(500, getInt("io.netty.util.internal.ObjectCleaner.refQueuePollTimeout", 10000)); // Package-private for testing static final String CLEANER_THREAD_NAME = ObjectCleaner.class.getSimpleName() + "Thread"; // This will hold a reference to the AutomaticCleanerReference which will be removed once we called cleanup() private static final Set<AutomaticCleanerReference> LIVE_SET = new ConcurrentSet<AutomaticCleanerReference>(); private static final ReferenceQueue<Object> REFERENCE_QUEUE = new ReferenceQueue<Object>(); private static final AtomicBoolean CLEANER_RUNNING = new AtomicBoolean(false); private static final Runnable CLEANER_TASK = new Runnable() { @Override public void run() { boolean interrupted = false; for (;;) { // Keep on processing as long as the LIVE_SET is not empty and once it becomes empty // See if we can let this thread complete. while (!LIVE_SET.isEmpty()) { final AutomaticCleanerReference reference; try { reference = (AutomaticCleanerReference) REFERENCE_QUEUE.remove(REFERENCE_QUEUE_POLL_TIMEOUT_MS); } catch (InterruptedException ex) { // Just consume and move on interrupted = true; continue; } if (reference != null) { try { reference.cleanup(); } catch (Throwable ignored) { // ignore exceptions, and don't log in case the logger throws an exception, blocks, or has // other unexpected side effects. } LIVE_SET.remove(reference); } } CLEANER_RUNNING.set(false); // Its important to first access the LIVE_SET and then CLEANER_RUNNING to ensure correct // behavior in multi-threaded environments. if (LIVE_SET.isEmpty() || !CLEANER_RUNNING.compareAndSet(false, true)) { // There was nothing added after we set STARTED to false or some other cleanup Thread // was started already so its safe to let this Thread complete now. break; } } if (interrupted) { // As we caught the InterruptedException above we should mark the Thread as interrupted. Thread.currentThread().interrupt(); } } }; /** * Register the given {@link Object} for which the {@link Runnable} will be executed once there are no references * to the object anymore. * * This should only be used if there are no other ways to execute some cleanup once the Object is not reachable * anymore because it is not a cheap way to handle the cleanup. */ public static void register(Object object, Runnable cleanupTask) { AutomaticCleanerReference reference = new AutomaticCleanerReference(object, ObjectUtil.checkNotNull(cleanupTask, "cleanupTask")); // Its important to add the reference to the LIVE_SET before we access CLEANER_RUNNING to ensure correct // behavior in multi-threaded environments. LIVE_SET.add(reference); // Check if there is already a cleaner running. if (CLEANER_RUNNING.compareAndSet(false, true)) { final Thread cleanupThread = new FastThreadLocalThread(CLEANER_TASK); cleanupThread.setPriority(Thread.MIN_PRIORITY); // Set to null to ensure we not create classloader leaks by holding a strong reference to the inherited // classloader. // See: // - https://github.com/netty/netty/issues/7290 // - https://bugs.openjdk.java.net/browse/JDK-7008595 AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { cleanupThread.setContextClassLoader(null); return null; } }); cleanupThread.setName(CLEANER_THREAD_NAME); // Mark this as a daemon thread to ensure that we the JVM can exit if this is the only thread that is // running. cleanupThread.setDaemon(true); cleanupThread.start(); } } public static int getLiveSetCount() { return LIVE_SET.size(); } private ObjectCleaner() { // Only contains a static method. } private static final class AutomaticCleanerReference extends WeakReference<Object> { private final Runnable cleanupTask; AutomaticCleanerReference(Object referent, Runnable cleanupTask) { super(referent, REFERENCE_QUEUE); this.cleanupTask = cleanupTask; } void cleanup() { cleanupTask.run(); } @Override public Thread get() { return null; } @Override public void clear() { LIVE_SET.remove(this); super.clear(); } } }
netty/netty
common/src/main/java/io/netty/util/internal/ObjectCleaner.java
44,873
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under both the GPLv2 (found in the // COPYING file in the root directory) and Apache 2.0 License // (found in the LICENSE.Apache file in the root directory). package org.rocksdb; /** * The full set of metadata associated with each SST file. */ public class LiveFileMetaData extends SstFileMetaData { private final byte[] columnFamilyName; private final int level; /** * Called from JNI C++ */ private LiveFileMetaData( final byte[] columnFamilyName, final int level, final String fileName, final String path, final long size, final long smallestSeqno, final long largestSeqno, final byte[] smallestKey, final byte[] largestKey, final long numReadsSampled, final boolean beingCompacted, final long numEntries, final long numDeletions) { super(fileName, path, size, smallestSeqno, largestSeqno, smallestKey, largestKey, numReadsSampled, beingCompacted, numEntries, numDeletions); this.columnFamilyName = columnFamilyName; this.level = level; } /** * Get the name of the column family. * * @return the name of the column family */ public byte[] columnFamilyName() { return columnFamilyName; } /** * Get the level at which this file resides. * * @return the level at which the file resides. */ public int level() { return level; } }
facebook/rocksdb
java/src/main/java/org/rocksdb/LiveFileMetaData.java
44,874
package org.signal.paging; import androidx.annotation.AnyThread; import androidx.annotation.NonNull; import androidx.lifecycle.LiveData; import java.util.List; /** * An implementation of {@link PagedData} that will provide data as a {@link LiveData}. */ public class LivePagedData<Key, Data> extends PagedData<Key> { private final LiveData<List<Data>> data; LivePagedData(@NonNull LiveData<List<Data>> data, @NonNull PagingController<Key> controller) { super(controller); this.data = data; } @AnyThread public @NonNull LiveData<List<Data>> getData() { return data; } }
signalapp/Signal-Android
paging/lib/src/main/java/org/signal/paging/LivePagedData.java
44,875
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.jms.support; import jakarta.jms.Message; import org.springframework.lang.Nullable; /** * Gather the Quality-of-Service settings that can be used when sending a message. * * @author Stephane Nicoll * @since 5.0 */ public class QosSettings { private int deliveryMode; private int priority; private long timeToLive; /** * Create a new instance with the default settings. * @see Message#DEFAULT_DELIVERY_MODE * @see Message#DEFAULT_PRIORITY * @see Message#DEFAULT_TIME_TO_LIVE */ public QosSettings() { this(Message.DEFAULT_DELIVERY_MODE, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE); } /** * Create a new instance with the specified settings. */ public QosSettings(int deliveryMode, int priority, long timeToLive) { this.deliveryMode = deliveryMode; this.priority = priority; this.timeToLive = timeToLive; } /** * Set the delivery mode to use when sending a message. * Default is the JMS Message default: "PERSISTENT". * @param deliveryMode the delivery mode to use * @see jakarta.jms.DeliveryMode#PERSISTENT * @see jakarta.jms.DeliveryMode#NON_PERSISTENT * @see jakarta.jms.Message#DEFAULT_DELIVERY_MODE * @see jakarta.jms.MessageProducer#send(jakarta.jms.Message, int, int, long) */ public void setDeliveryMode(int deliveryMode) { this.deliveryMode = deliveryMode; } /** * Return the delivery mode to use when sending a message. */ public int getDeliveryMode() { return this.deliveryMode; } /** * Set the priority of a message when sending. * @see jakarta.jms.Message#DEFAULT_PRIORITY * @see jakarta.jms.MessageProducer#send(jakarta.jms.Message, int, int, long) */ public void setPriority(int priority) { this.priority = priority; } /** * Return the priority of a message when sending. */ public int getPriority() { return this.priority; } /** * Set the time-to-live of the message when sending. * @param timeToLive the message's lifetime (in milliseconds) * @see jakarta.jms.Message#DEFAULT_TIME_TO_LIVE * @see jakarta.jms.MessageProducer#send(jakarta.jms.Message, int, int, long) */ public void setTimeToLive(long timeToLive) { this.timeToLive = timeToLive; } /** * Return the time-to-live of the message when sending. */ public long getTimeToLive() { return this.timeToLive; } @Override public boolean equals(@Nullable Object other) { return (this == other || (other instanceof QosSettings that && this.deliveryMode == that.deliveryMode && this.priority == that.priority && this.timeToLive == that.timeToLive)); } @Override public int hashCode() { return this.deliveryMode * 31 + this.priority; } @Override public String toString() { return "QosSettings{" + "deliveryMode=" + this.deliveryMode + ", priority=" + this.priority + ", timeToLive=" + this.timeToLive + '}'; } }
spring-projects/spring-framework
spring-jms/src/main/java/org/springframework/jms/support/QosSettings.java
44,877
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.ui; import static org.telegram.messenger.AndroidUtilities.dp; import android.Manifest; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.StateListAnimator; import android.animation.ValueAnimator; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Outline; import android.graphics.Paint; import android.graphics.Point; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.drawable.Drawable; import android.location.Location; import android.location.LocationManager; import android.net.Uri; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.os.Build; import android.text.TextUtils; import android.util.TypedValue; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewOutlineProvider; import android.view.WindowManager; import android.view.animation.OvershootInterpolator; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import androidx.collection.LongSparseArray; import androidx.core.graphics.ColorUtils; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.BuildVars; import org.telegram.messenger.ChatObject; import org.telegram.messenger.DialogObject; import org.telegram.messenger.FileLog; import org.telegram.messenger.IMapsProvider; import org.telegram.messenger.LocaleController; import org.telegram.messenger.LocationController; import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessagesController; import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.UserObject; import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.ActionBar; import org.telegram.ui.ActionBar.ActionBarMenu; import org.telegram.ui.ActionBar.ActionBarMenuItem; import org.telegram.ui.ActionBar.ActionBarMenuSubItem; import org.telegram.ui.ActionBar.ActionBarPopupWindow; import org.telegram.ui.ActionBar.AlertDialog; import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.ActionBar.ThemeDescription; import org.telegram.ui.Adapters.LocationActivityAdapter; import org.telegram.ui.Adapters.LocationActivitySearchAdapter; import org.telegram.ui.Cells.HeaderCell; import org.telegram.ui.Cells.LocationCell; import org.telegram.ui.Cells.LocationDirectionCell; import org.telegram.ui.Cells.LocationLoadingCell; import org.telegram.ui.Cells.LocationPoweredCell; import org.telegram.ui.Cells.SendLocationCell; import org.telegram.ui.Cells.ShadowSectionCell; import org.telegram.ui.Cells.SharingLiveLocationCell; import org.telegram.ui.Components.AlertsCreator; import org.telegram.ui.Components.AvatarDrawable; import org.telegram.ui.Components.BackupImageView; import org.telegram.ui.Components.ChatAttachAlert; import org.telegram.ui.Components.ChatAttachAlertLocationLayout; import org.telegram.ui.Components.CombinedDrawable; import org.telegram.ui.Components.CubicBezierInterpolator; import org.telegram.ui.Components.EditTextBoldCursor; import org.telegram.ui.Components.HintView; import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.MapPlaceholderDrawable; import org.telegram.ui.Components.ProximitySheet; import org.telegram.ui.Components.RecyclerListView; import org.telegram.ui.Components.UndoView; import org.telegram.ui.Stories.recorder.HintView2; import java.io.File; import java.net.URLEncoder; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Locale; public class LocationActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate { private ImageView locationButton; private ImageView proximityButton; private ActionBarMenuItem mapTypeButton; private SearchButton searchAreaButton; private LinearLayout emptyView; private ImageView emptyImageView; private TextView emptyTitleTextView; private TextView emptySubtitleTextView; private Drawable shadowDrawable; private View shadow; private ActionBarMenuItem searchItem; private MapOverlayView overlayView; private HintView2 hintView; private UndoView[] undoView = new UndoView[2]; private boolean canUndo; private boolean proximityAnimationInProgress; private IMapsProvider.IMap map; private IMapsProvider.ICameraUpdate moveToBounds; private IMapsProvider.IMapView mapView; private IMapsProvider.ICameraUpdate forceUpdate; private boolean hasScreenshot; private float yOffset; private IMapsProvider.ICircle proximityCircle; private double previousRadius; private boolean scrolling; private ProximitySheet proximitySheet; private FrameLayout mapViewClip; private LocationActivityAdapter adapter; private RecyclerListView listView; private RecyclerListView searchListView; private LocationActivitySearchAdapter searchAdapter; private View markerImageView; private LinearLayoutManager layoutManager; private AvatarDrawable avatarDrawable; private ActionBarMenuItem otherItem; private ChatActivity parentFragment; private boolean currentMapStyleDark; private boolean checkGpsEnabled = true; private boolean locationDenied = false; private boolean isFirstLocation = true; private long dialogId; private boolean firstFocus = true; private Runnable updateRunnable; private ArrayList<LiveLocation> markers = new ArrayList<>(); private LongSparseArray<LiveLocation> markersMap = new LongSparseArray<>(); private long selectedMarkerId = -1; private ArrayList<VenueLocation> placeMarkers = new ArrayList<>(); private AnimatorSet animatorSet; private IMapsProvider.IMarker lastPressedMarker; private VenueLocation lastPressedVenue; private FrameLayout lastPressedMarkerView; private boolean checkPermission = true; private boolean checkBackgroundPermission = true; private int askWithRadius; private boolean searching; private boolean searchWas; private boolean searchInProgress; private boolean wasResults; private boolean mapsInitialized; private boolean onResumeCalled; private Location myLocation; private Location userLocation; private int markerTop; private TLRPC.TL_channelLocation chatLocation; private TLRPC.TL_channelLocation initialLocation; private MessageObject messageObject; private boolean userLocationMoved; private boolean searchedForCustomLocations; private boolean firstWas; private LocationActivityDelegate delegate; private int locationType; private int overScrollHeight = AndroidUtilities.displaySize.x - ActionBar.getCurrentActionBarHeight() - dp(66); private final static int open_in = 1; private final static int share_live_location = 5; private final static int get_directions = 6; private final static int map_list_menu_map = 2; private final static int map_list_menu_satellite = 3; private final static int map_list_menu_hybrid = 4; public final static int LOCATION_TYPE_SEND = 0; public final static int LOCATION_TYPE_SEND_WITH_LIVE = 1; public final static int LOCATION_TYPE_LIVE = 2; public final static int LOCATION_TYPE_GROUP = 4; public final static int LOCATION_TYPE_GROUP_VIEW = 5; public final static int LOCATION_TYPE_LIVE_VIEW = 6; private ActionBarPopupWindow popupWindow; private Runnable markAsReadRunnable; public static class VenueLocation { public int num; public IMapsProvider.IMarker marker; public TLRPC.TL_messageMediaVenue venue; } public static class LiveLocation { public long id; public TLRPC.Message object; public TLRPC.User user; public TLRPC.Chat chat; public IMapsProvider.IMarker marker; public IMapsProvider.IMarker directionMarker; public boolean hasRotation; } private static class SearchButton extends TextView { private float additionanTranslationY; private float currentTranslationY; public SearchButton(Context context) { super(context); } @Override public float getTranslationX() { return additionanTranslationY; } @Override public void setTranslationX(float translationX) { additionanTranslationY = translationX; updateTranslationY(); } public void setTranslation(float value) { currentTranslationY = value; updateTranslationY(); } private void updateTranslationY() { setTranslationY(currentTranslationY + additionanTranslationY); } } public class MapOverlayView extends FrameLayout { private HashMap<IMapsProvider.IMarker, View> views = new HashMap<>(); public MapOverlayView(Context context) { super(context); } public void addInfoView(IMapsProvider.IMarker marker) { VenueLocation location = (VenueLocation) marker.getTag(); if (location == null || lastPressedVenue == location) { return; } showSearchPlacesButton(false); if (lastPressedMarker != null) { removeInfoView(lastPressedMarker); lastPressedMarker = null; } lastPressedVenue = location; lastPressedMarker = marker; Context context = getContext(); FrameLayout frameLayout = new FrameLayout(context); addView(frameLayout, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 114)); lastPressedMarkerView = new FrameLayout(context); lastPressedMarkerView.setBackgroundResource(R.drawable.venue_tooltip); lastPressedMarkerView.getBackground().setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogBackground), PorterDuff.Mode.MULTIPLY)); frameLayout.addView(lastPressedMarkerView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 71)); lastPressedMarkerView.setAlpha(0.0f); lastPressedMarkerView.setOnClickListener(v -> { if (parentFragment != null && parentFragment.isInScheduleMode()) { AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), parentFragment.getDialogId(), (notify, scheduleDate) -> { delegate.didSelectLocation(location.venue, locationType, notify, scheduleDate); finishFragment(); }); } else { delegate.didSelectLocation(location.venue, locationType, true, 0); finishFragment(); } }); TextView nameTextView = new TextView(context); nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); nameTextView.setMaxLines(1); nameTextView.setEllipsize(TextUtils.TruncateAt.END); nameTextView.setSingleLine(true); nameTextView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteBlackText)); nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); nameTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); lastPressedMarkerView.addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), 18, 10, 18, 0)); TextView addressTextView = new TextView(context); addressTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); addressTextView.setMaxLines(1); addressTextView.setEllipsize(TextUtils.TruncateAt.END); addressTextView.setSingleLine(true); addressTextView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText3)); addressTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); lastPressedMarkerView.addView(addressTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), 18, 32, 18, 0)); nameTextView.setText(location.venue.title); addressTextView.setText(LocaleController.getString("TapToSendLocation", R.string.TapToSendLocation)); FrameLayout iconLayout = new FrameLayout(context); iconLayout.setBackground(Theme.createCircleDrawable(dp(36), LocationCell.getColorForIndex(location.num))); frameLayout.addView(iconLayout, LayoutHelper.createFrame(36, 36, Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 0, 0, 4)); BackupImageView imageView = new BackupImageView(context); imageView.setImage("https://ss3.4sqi.net/img/categories_v2/" + location.venue.venue_type + "_64.png", null, null); iconLayout.addView(imageView, LayoutHelper.createFrame(30, 30, Gravity.CENTER)); ValueAnimator animator = ValueAnimator.ofFloat(0.0f, 1.0f); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { private boolean startedInner; private final float[] animatorValues = new float[]{0.0f, 1.0f}; @Override public void onAnimationUpdate(ValueAnimator animation) { float value = AndroidUtilities.lerp(animatorValues, animation.getAnimatedFraction()); if (value >= 0.7f && !startedInner && lastPressedMarkerView != null) { AnimatorSet animatorSet1 = new AnimatorSet(); animatorSet1.playTogether( ObjectAnimator.ofFloat(lastPressedMarkerView, View.SCALE_X, 0.0f, 1.0f), ObjectAnimator.ofFloat(lastPressedMarkerView, View.SCALE_Y, 0.0f, 1.0f), ObjectAnimator.ofFloat(lastPressedMarkerView, View.ALPHA, 0.0f, 1.0f)); animatorSet1.setInterpolator(new OvershootInterpolator(1.02f)); animatorSet1.setDuration(250); animatorSet1.start(); startedInner = true; } float scale; if (value <= 0.5f) { scale = 1.1f * CubicBezierInterpolator.EASE_OUT.getInterpolation(value / 0.5f); } else if (value <= 0.75f) { value -= 0.5f; scale = 1.1f - 0.2f * CubicBezierInterpolator.EASE_OUT.getInterpolation(value / 0.25f); } else { value -= 0.75f; scale = 0.9f + 0.1f * CubicBezierInterpolator.EASE_OUT.getInterpolation(value / 0.25f); } iconLayout.setScaleX(scale); iconLayout.setScaleY(scale); } }); animator.setDuration(360); animator.start(); views.put(marker, frameLayout); map.animateCamera(ApplicationLoader.getMapsProvider().newCameraUpdateLatLng(marker.getPosition()), 300, null); } public void removeInfoView(IMapsProvider.IMarker marker) { View view = views.get(marker); if (view != null) { removeView(view); views.remove(marker); } } public void updatePositions() { if (map == null) { return; } IMapsProvider.IProjection projection = map.getProjection(); for (HashMap.Entry<IMapsProvider.IMarker, View> entry : views.entrySet()) { IMapsProvider.IMarker marker = entry.getKey(); View view = entry.getValue(); Point point = projection.toScreenLocation(marker.getPosition()); view.setTranslationX(point.x - view.getMeasuredWidth() / 2); view.setTranslationY(point.y - view.getMeasuredHeight() + dp(22)); } } } public interface LocationActivityDelegate { void didSelectLocation(TLRPC.MessageMedia location, int live, boolean notify, int scheduleDate); } public LocationActivity(int type) { super(); locationType = type; AndroidUtilities.fixGoogleMapsBug(); } private boolean initialMaxZoom; public void setInitialMaxZoom(boolean initialMaxZoom) { this.initialMaxZoom = initialMaxZoom; } @Override public boolean onFragmentCreate() { super.onFragmentCreate(); getNotificationCenter().addObserver(this, NotificationCenter.closeChats); NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.locationPermissionGranted); NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.locationPermissionDenied); NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.liveLocationsChanged); if (messageObject != null && messageObject.isLiveLocation()) { getNotificationCenter().addObserver(this, NotificationCenter.didReceiveNewMessages); getNotificationCenter().addObserver(this, NotificationCenter.replaceMessagesObjects); } return true; } @Override public void onFragmentDestroy() { super.onFragmentDestroy(); NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.locationPermissionGranted); NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.locationPermissionDenied); NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.liveLocationsChanged); getNotificationCenter().removeObserver(this, NotificationCenter.closeChats); getNotificationCenter().removeObserver(this, NotificationCenter.didReceiveNewMessages); getNotificationCenter().removeObserver(this, NotificationCenter.replaceMessagesObjects); try { if (map != null) { map.setMyLocationEnabled(false); } } catch (Exception e) { FileLog.e(e); } try { if (mapView != null) { mapView.onDestroy(); } } catch (Exception e) { FileLog.e(e); } if (undoView[0] != null) { undoView[0].hide(true, 0); } if (adapter != null) { adapter.destroy(); } if (searchAdapter != null) { searchAdapter.destroy(); } if (updateRunnable != null) { AndroidUtilities.cancelRunOnUIThread(updateRunnable); updateRunnable = null; } if (markAsReadRunnable != null) { AndroidUtilities.cancelRunOnUIThread(markAsReadRunnable); markAsReadRunnable = null; } } private UndoView getUndoView() { if (undoView[0].getVisibility() == View.VISIBLE) { UndoView old = undoView[0]; undoView[0] = undoView[1]; undoView[1] = old; old.hide(true, 2); mapViewClip.removeView(undoView[0]); mapViewClip.addView(undoView[0]); } return undoView[0]; } private boolean isSharingAllowed = true; public void setSharingAllowed(boolean allowed) { isSharingAllowed = allowed; } @Override public boolean isSwipeBackEnabled(MotionEvent event) { return false; } @Override public View createView(Context context) { searchWas = false; searching = false; searchInProgress = false; if (adapter != null) { adapter.destroy(); } if (searchAdapter != null) { searchAdapter.destroy(); } if (chatLocation != null) { userLocation = new Location("network"); userLocation.setLatitude(chatLocation.geo_point.lat); userLocation.setLongitude(chatLocation.geo_point._long); } else if (messageObject != null) { userLocation = new Location("network"); userLocation.setLatitude(messageObject.messageOwner.media.geo.lat); userLocation.setLongitude(messageObject.messageOwner.media.geo._long); } locationDenied = Build.VERSION.SDK_INT >= 23 && getParentActivity() != null && getParentActivity().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED; actionBar.setBackgroundColor(getThemedColor(Theme.key_dialogBackground)); actionBar.setTitleColor(getThemedColor(Theme.key_dialogTextBlack)); actionBar.setItemsColor(getThemedColor(Theme.key_dialogTextBlack), false); actionBar.setItemsBackgroundColor(getThemedColor(Theme.key_dialogButtonSelector), false); actionBar.setBackButtonImage(R.drawable.ic_ab_back); actionBar.setAllowOverlayTitle(true); if (AndroidUtilities.isTablet()) { actionBar.setOccupyStatusBar(false); } actionBar.setAddToContainer(false); actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { @Override public void onItemClick(int id) { if (id == -1) { finishFragment(); } else if (id == open_in) { try { double lat = messageObject.messageOwner.media.geo.lat; double lon = messageObject.messageOwner.media.geo._long; getParentActivity().startActivity(new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("geo:" + lat + "," + lon + "?q=" + lat + "," + lon))); } catch (Exception e) { FileLog.e(e); } } else if (id == share_live_location) { openShareLiveLocation(false, 0); } else if (id == get_directions) { openDirections(null); } } }); ActionBarMenu menu = actionBar.createMenu(); if (chatLocation != null) { actionBar.setTitle(LocaleController.getString("ChatLocation", R.string.ChatLocation)); } else if (messageObject != null) { if (messageObject.isLiveLocation()) { actionBar.setTitle(LocaleController.getString("AttachLiveLocation", R.string.AttachLiveLocation)); otherItem = menu.addItem(0, R.drawable.ic_ab_other, getResourceProvider()); otherItem.addSubItem(get_directions, R.drawable.filled_directions, LocaleController.getString("GetDirections", R.string.GetDirections)); } else { if (messageObject.messageOwner.media.title != null && messageObject.messageOwner.media.title.length() > 0) { actionBar.setTitle(LocaleController.getString("SharedPlace", R.string.SharedPlace)); } else { actionBar.setTitle(LocaleController.getString("ChatLocation", R.string.ChatLocation)); } if (locationType != 3) { otherItem = menu.addItem(0, R.drawable.ic_ab_other, getResourceProvider()); otherItem.addSubItem(open_in, R.drawable.msg_openin, LocaleController.getString("OpenInExternalApp", R.string.OpenInExternalApp)); if (!getLocationController().isSharingLocation(dialogId) && isSharingAllowed) { otherItem.addSubItem(share_live_location, R.drawable.msg_location, LocaleController.getString("SendLiveLocationMenu", R.string.SendLiveLocationMenu)); } otherItem.setContentDescription(LocaleController.getString("AccDescrMoreOptions", R.string.AccDescrMoreOptions)); } } } else { actionBar.setTitle(LocaleController.getString("ShareLocation", R.string.ShareLocation)); if (locationType != LOCATION_TYPE_GROUP) { overlayView = new MapOverlayView(context); searchItem = menu.addItem(0, R.drawable.ic_ab_search, getResourceProvider()).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() { @Override public void onSearchExpand() { searching = true; } @Override public void onSearchCollapse() { searching = false; searchWas = false; searchAdapter.searchDelayed(null, null); updateEmptyView(); if (locationType == ChatAttachAlertLocationLayout.LOCATION_TYPE_BIZ) { if (otherItem != null) { otherItem.setVisibility(View.VISIBLE); } listView.setVisibility(View.VISIBLE); mapViewClip.setVisibility(View.VISIBLE); searchListView.setAdapter(null); searchListView.setVisibility(View.GONE); } } @Override public void onTextChanged(EditText editText) { if (searchAdapter == null) { return; } String text = editText.getText().toString(); if (text.length() != 0) { searchWas = true; searchItem.setShowSearchProgress(true); if (otherItem != null) { otherItem.setVisibility(View.GONE); } listView.setVisibility(View.GONE); mapViewClip.setVisibility(View.GONE); if (searchListView.getAdapter() != searchAdapter) { searchListView.setAdapter(searchAdapter); } searchListView.setVisibility(View.VISIBLE); searchInProgress = searchAdapter.getItemCount() == 0; } else { if (otherItem != null) { otherItem.setVisibility(View.VISIBLE); } listView.setVisibility(View.VISIBLE); mapViewClip.setVisibility(View.VISIBLE); searchListView.setAdapter(null); searchListView.setVisibility(View.GONE); } updateEmptyView(); searchAdapter.searchDelayed(text, userLocation); } }); searchItem.setSearchFieldHint(LocaleController.getString("Search", R.string.Search)); searchItem.setContentDescription(LocaleController.getString("Search", R.string.Search)); EditTextBoldCursor editText = searchItem.getSearchField(); editText.setTextColor(getThemedColor(Theme.key_dialogTextBlack)); editText.setCursorColor(getThemedColor(Theme.key_dialogTextBlack)); editText.setHintTextColor(getThemedColor(Theme.key_chat_messagePanelHint)); } } fragmentView = new FrameLayout(context) { private boolean first = true; @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (changed) { fixLayoutInternal(first); first = false; } else { updateClipView(true); } } @Override protected boolean drawChild(Canvas canvas, View child, long drawingTime) { boolean result = super.drawChild(canvas, child, drawingTime); if (child == actionBar && parentLayout != null) { parentLayout.drawHeaderShadow(canvas, actionBar.getMeasuredHeight()); } return result; } }; FrameLayout frameLayout = (FrameLayout) fragmentView; fragmentView.setBackgroundColor(getThemedColor(Theme.key_dialogBackground)); shadowDrawable = context.getResources().getDrawable(R.drawable.sheet_shadow_round).mutate(); shadowDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogBackground), PorterDuff.Mode.MULTIPLY)); Rect padding = new Rect(); shadowDrawable.getPadding(padding); FrameLayout.LayoutParams layoutParams; if (locationType == LOCATION_TYPE_SEND || locationType == LOCATION_TYPE_SEND_WITH_LIVE) { layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(21) + padding.top); } else { layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(6) + padding.top); } layoutParams.gravity = Gravity.LEFT | Gravity.BOTTOM; mapViewClip = new FrameLayout(context) { @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (overlayView != null) { overlayView.updatePositions(); } } }; mapViewClip.setBackgroundDrawable(new MapPlaceholderDrawable(isActiveThemeDark())); if (messageObject == null && (locationType == LOCATION_TYPE_SEND || locationType == LOCATION_TYPE_SEND_WITH_LIVE) || messageObject != null && locationType == 3) { searchAreaButton = new SearchButton(context); searchAreaButton.setTranslationX(-dp(80)); Drawable drawable = Theme.createSimpleSelectorRoundRectDrawable(dp(40), getThemedColor(Theme.key_location_actionBackground), getThemedColor(Theme.key_location_actionPressedBackground)); if (Build.VERSION.SDK_INT < 21) { Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.places_btn).mutate(); shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY)); CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, dp(2), dp(2)); combinedDrawable.setFullsize(true); drawable = combinedDrawable; } else { StateListAnimator animator = new StateListAnimator(); animator.addState(new int[]{android.R.attr.state_pressed}, ObjectAnimator.ofFloat(searchAreaButton, View.TRANSLATION_Z, dp(2), dp(4)).setDuration(200)); animator.addState(new int[]{}, ObjectAnimator.ofFloat(searchAreaButton, View.TRANSLATION_Z, dp(4), dp(2)).setDuration(200)); searchAreaButton.setStateListAnimator(animator); searchAreaButton.setOutlineProvider(new ViewOutlineProvider() { @SuppressLint("NewApi") @Override public void getOutline(View view, Outline outline) { outline.setRoundRect(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight(), view.getMeasuredHeight() / 2); } }); } searchAreaButton.setBackgroundDrawable(drawable); searchAreaButton.setTextColor(getThemedColor(Theme.key_location_actionActiveIcon)); searchAreaButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); searchAreaButton.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); searchAreaButton.setGravity(Gravity.CENTER); searchAreaButton.setPadding(dp(20), 0, dp(20), 0); mapViewClip.addView(searchAreaButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, Build.VERSION.SDK_INT >= 21 ? 40 : 44, Gravity.CENTER_HORIZONTAL | Gravity.TOP, 80, 12, 80, 0)); if (locationType == 3) { searchAreaButton.setText(LocaleController.getString(R.string.OpenInMaps)); searchAreaButton.setOnClickListener(v -> { try { double lat = messageObject.messageOwner.media.geo.lat; double lon = messageObject.messageOwner.media.geo._long; getParentActivity().startActivity(new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("geo:" + lat + "," + lon + "?q=" + lat + "," + lon))); } catch (Exception e) { FileLog.e(e); } }); searchAreaButton.setTranslationX(0); } else { searchAreaButton.setText(LocaleController.getString(R.string.PlacesInThisArea)); searchAreaButton.setOnClickListener(v -> { showSearchPlacesButton(false); adapter.searchPlacesWithQuery(null, userLocation, true, true); searchedForCustomLocations = true; showResults(); }); } } mapTypeButton = new ActionBarMenuItem(context, null, 0, getThemedColor(Theme.key_location_actionIcon), getResourceProvider()); mapTypeButton.setClickable(true); mapTypeButton.setSubMenuOpenSide(2); mapTypeButton.setAdditionalXOffset(dp(10)); mapTypeButton.setAdditionalYOffset(-dp(10)); mapTypeButton.addSubItem(map_list_menu_map, R.drawable.msg_map, LocaleController.getString("Map", R.string.Map), getResourceProvider()); mapTypeButton.addSubItem(map_list_menu_satellite, R.drawable.msg_satellite, LocaleController.getString("Satellite", R.string.Satellite), getResourceProvider()); mapTypeButton.addSubItem(map_list_menu_hybrid, R.drawable.msg_hybrid, LocaleController.getString("Hybrid", R.string.Hybrid), getResourceProvider()); mapTypeButton.setContentDescription(LocaleController.getString("AccDescrMoreOptions", R.string.AccDescrMoreOptions)); Drawable drawable = Theme.createSimpleSelectorCircleDrawable(dp(40), getThemedColor(Theme.key_location_actionBackground), getThemedColor(Theme.key_location_actionPressedBackground)); if (Build.VERSION.SDK_INT < 21) { Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow_profile).mutate(); shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY)); CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0); combinedDrawable.setIconSize(dp(40), dp(40)); drawable = combinedDrawable; } else { StateListAnimator animator = new StateListAnimator(); animator.addState(new int[]{android.R.attr.state_pressed}, ObjectAnimator.ofFloat(mapTypeButton, View.TRANSLATION_Z, dp(2), dp(4)).setDuration(200)); animator.addState(new int[]{}, ObjectAnimator.ofFloat(mapTypeButton, View.TRANSLATION_Z, dp(4), dp(2)).setDuration(200)); mapTypeButton.setStateListAnimator(animator); mapTypeButton.setOutlineProvider(new ViewOutlineProvider() { @SuppressLint("NewApi") @Override public void getOutline(View view, Outline outline) { outline.setOval(0, 0, dp(40), dp(40)); } }); } mapTypeButton.setBackgroundDrawable(drawable); mapTypeButton.setIcon(R.drawable.msg_map_type); mapViewClip.addView(mapTypeButton, LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 40 : 44, Build.VERSION.SDK_INT >= 21 ? 40 : 44, Gravity.RIGHT | Gravity.TOP, 0, 12, 12, 0)); mapTypeButton.setOnClickListener(v -> mapTypeButton.toggleSubMenu()); mapTypeButton.setDelegate(id -> { if (map == null) { return; } if (id == map_list_menu_map) { map.setMapType(IMapsProvider.MAP_TYPE_NORMAL); } else if (id == map_list_menu_satellite) { map.setMapType(IMapsProvider.MAP_TYPE_SATELLITE); } else if (id == map_list_menu_hybrid) { map.setMapType(IMapsProvider.MAP_TYPE_HYBRID); } }); locationButton = new ImageView(context); drawable = Theme.createSimpleSelectorCircleDrawable(dp(40), getThemedColor(Theme.key_location_actionBackground), getThemedColor(Theme.key_location_actionPressedBackground)); if (Build.VERSION.SDK_INT < 21) { Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow_profile).mutate(); shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY)); CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0); combinedDrawable.setIconSize(dp(40), dp(40)); drawable = combinedDrawable; } else { StateListAnimator animator = new StateListAnimator(); animator.addState(new int[]{android.R.attr.state_pressed}, ObjectAnimator.ofFloat(locationButton, View.TRANSLATION_Z, dp(2), dp(4)).setDuration(200)); animator.addState(new int[]{}, ObjectAnimator.ofFloat(locationButton, View.TRANSLATION_Z, dp(4), dp(2)).setDuration(200)); locationButton.setStateListAnimator(animator); locationButton.setOutlineProvider(new ViewOutlineProvider() { @SuppressLint("NewApi") @Override public void getOutline(View view, Outline outline) { outline.setOval(0, 0, dp(40), dp(40)); } }); } locationButton.setBackgroundDrawable(drawable); locationButton.setImageResource(R.drawable.msg_current_location); locationButton.setScaleType(ImageView.ScaleType.CENTER); locationButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_location_actionActiveIcon), PorterDuff.Mode.MULTIPLY)); locationButton.setTag(Theme.key_location_actionActiveIcon); locationButton.setContentDescription(LocaleController.getString("AccDescrMyLocation", R.string.AccDescrMyLocation)); FrameLayout.LayoutParams layoutParams1 = LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 40 : 44, Build.VERSION.SDK_INT >= 21 ? 40 : 44, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, 12, 12); layoutParams1.bottomMargin += layoutParams.height - padding.top; mapViewClip.addView(locationButton, layoutParams1); locationButton.setOnClickListener(v -> { if (Build.VERSION.SDK_INT >= 23) { Activity activity = getParentActivity(); if (activity != null) { if (activity.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { showPermissionAlert(false); return; } } } if (!checkGpsEnabled() && locationType != 3) { return; } if (messageObject != null && locationType != 3 || chatLocation != null) { if (myLocation != null && map != null) { map.animateCamera(ApplicationLoader.getMapsProvider().newCameraUpdateLatLngZoom(new IMapsProvider.LatLng(myLocation.getLatitude(), myLocation.getLongitude()), map.getMaxZoomLevel() - 4)); } } else { if (myLocation != null && map != null) { locationButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_location_actionActiveIcon), PorterDuff.Mode.MULTIPLY)); locationButton.setTag(Theme.key_location_actionActiveIcon); adapter.setCustomLocation(null); userLocationMoved = false; showSearchPlacesButton(false); map.animateCamera(ApplicationLoader.getMapsProvider().newCameraUpdateLatLng(new IMapsProvider.LatLng(myLocation.getLatitude(), myLocation.getLongitude()))); if (searchedForCustomLocations && locationType != ChatAttachAlertLocationLayout.LOCATION_TYPE_BIZ) { if (myLocation != null) { adapter.searchPlacesWithQuery(null, myLocation, true, true); } searchedForCustomLocations = false; showResults(); } } } removeInfoView(); }); proximityButton = new ImageView(context); drawable = Theme.createSimpleSelectorCircleDrawable(dp(40), getThemedColor(Theme.key_location_actionBackground), getThemedColor(Theme.key_location_actionPressedBackground)); if (Build.VERSION.SDK_INT < 21) { Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow_profile).mutate(); shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY)); CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0); combinedDrawable.setIconSize(dp(40), dp(40)); drawable = combinedDrawable; } else { StateListAnimator animator = new StateListAnimator(); animator.addState(new int[]{android.R.attr.state_pressed}, ObjectAnimator.ofFloat(proximityButton, View.TRANSLATION_Z, dp(2), dp(4)).setDuration(200)); animator.addState(new int[]{}, ObjectAnimator.ofFloat(proximityButton, View.TRANSLATION_Z, dp(4), dp(2)).setDuration(200)); proximityButton.setStateListAnimator(animator); proximityButton.setOutlineProvider(new ViewOutlineProvider() { @SuppressLint("NewApi") @Override public void getOutline(View view, Outline outline) { outline.setOval(0, 0, dp(40), dp(40)); } }); } proximityButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_location_actionIcon), PorterDuff.Mode.MULTIPLY)); proximityButton.setBackgroundDrawable(drawable); proximityButton.setScaleType(ImageView.ScaleType.CENTER); proximityButton.setContentDescription(LocaleController.getString("AccDescrLocationNotify", R.string.AccDescrLocationNotify)); mapViewClip.addView(proximityButton, LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 40 : 44, Build.VERSION.SDK_INT >= 21 ? 40 : 44, Gravity.RIGHT | Gravity.TOP, 0, 12 + 50, 12, 0)); proximityButton.setOnClickListener(v -> { if (getParentActivity() == null || myLocation == null || !checkGpsEnabled() || map == null) { return; } if (hintView != null) { hintView.hide(); } SharedPreferences preferences = MessagesController.getGlobalMainSettings(); preferences.edit().putInt("proximityhint", 3).commit(); LocationController.SharingLocationInfo info = getLocationController().getSharingLocationInfo(dialogId); if (canUndo) { undoView[0].hide(true, 1); } if (info != null && info.proximityMeters > 0) { proximityButton.setImageResource(R.drawable.msg_location_alert); if (proximityCircle != null) { proximityCircle.remove(); proximityCircle = null; } canUndo = true; getUndoView().showWithAction(0, UndoView.ACTION_PROXIMITY_REMOVED, 0, null, () -> { getLocationController().setProximityLocation(dialogId, 0, true); canUndo = false; }, () -> { proximityButton.setImageResource(R.drawable.msg_location_alert2); createCircle(info.proximityMeters); canUndo = false; }); return; } openProximityAlert(); }); TLRPC.Chat chat = null; if (DialogObject.isChatDialog(dialogId)) { chat = getMessagesController().getChat(-dialogId); } if (messageObject == null || !messageObject.isLiveLocation() || messageObject.isExpiredLiveLocation(getConnectionsManager().getCurrentTime()) || ChatObject.isChannel(chat) && !chat.megagroup) { proximityButton.setVisibility(View.GONE); proximityButton.setImageResource(R.drawable.msg_location_alert); } else { LocationController.SharingLocationInfo myInfo = getLocationController().getSharingLocationInfo(dialogId); if (myInfo != null && myInfo.proximityMeters > 0) { proximityButton.setImageResource(R.drawable.msg_location_alert2); } else { if (DialogObject.isUserDialog(dialogId) && messageObject.getFromChatId() == getUserConfig().getClientUserId()) { proximityButton.setVisibility(View.INVISIBLE); proximityButton.setAlpha(0.0f); proximityButton.setScaleX(0.4f); proximityButton.setScaleY(0.4f); } proximityButton.setImageResource(R.drawable.msg_location_alert); } } hintView = new HintView2(context, HintView2.DIRECTION_TOP); hintView.setLayerType(View.LAYER_TYPE_HARDWARE, null); hintView.setDuration(4000); hintView.setJoint(1, -(12 + 13)); hintView.setPadding(0, dp(4), 0, 0); mapViewClip.addView(hintView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 8, 12 + 50 + 44, 8, 0)); emptyView = new LinearLayout(context); emptyView.setOrientation(LinearLayout.VERTICAL); emptyView.setGravity(Gravity.CENTER_HORIZONTAL); emptyView.setPadding(0, dp(60 + 100), 0, 0); emptyView.setVisibility(View.GONE); frameLayout.addView(emptyView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); emptyView.setOnTouchListener((v, event) -> true); emptyImageView = new ImageView(context); emptyImageView.setImageResource(R.drawable.location_empty); emptyImageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogEmptyImage), PorterDuff.Mode.MULTIPLY)); emptyView.addView(emptyImageView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT)); emptyTitleTextView = new TextView(context); emptyTitleTextView.setTextColor(getThemedColor(Theme.key_dialogEmptyText)); emptyTitleTextView.setGravity(Gravity.CENTER); emptyTitleTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); emptyTitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17); emptyTitleTextView.setText(LocaleController.getString("NoPlacesFound", R.string.NoPlacesFound)); emptyView.addView(emptyTitleTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 11, 0, 0)); emptySubtitleTextView = new TextView(context); emptySubtitleTextView.setTextColor(getThemedColor(Theme.key_dialogEmptyText)); emptySubtitleTextView.setGravity(Gravity.CENTER); emptySubtitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); emptySubtitleTextView.setPadding(dp(40), 0, dp(40), 0); emptyView.addView(emptySubtitleTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 6, 0, 0)); listView = new RecyclerListView(context); listView.setAdapter(adapter = new LocationActivityAdapter(context, locationType, dialogId, false, getResourceProvider(), false, locationType == ChatAttachAlertLocationLayout.LOCATION_TYPE_BIZ) { @Override protected void onDirectionClick() { openDirections(null); } private boolean firstSet = true; @Override public void setLiveLocations(ArrayList<LiveLocation> liveLocations) { if (messageObject != null && messageObject.isLiveLocation()) { int otherPeopleLocations = 0; if (liveLocations != null) { for (int i = 0; i < liveLocations.size(); ++i) { LiveLocation loc = liveLocations.get(i); if (loc != null && !UserObject.isUserSelf(loc.user)) { otherPeopleLocations++; } } } if (firstSet && otherPeopleLocations == 1) { selectedMarkerId = liveLocations.get(0).id; } firstSet = false; otherItem.setVisibility(otherPeopleLocations == 1 ? View.VISIBLE : View.GONE); } super.setLiveLocations(liveLocations); } }); adapter.setMyLocationDenied(locationDenied, false); adapter.setUpdateRunnable(() -> updateClipView(false)); listView.setVerticalScrollBarEnabled(false); listView.setLayoutManager(layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)); frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP)); if (messageObject != null && messageObject.messageOwner != null && messageObject.messageOwner.media != null && !TextUtils.isEmpty(messageObject.messageOwner.media.address)) { adapter.setAddressNameOverride(messageObject.messageOwner.media.address); } listView.setOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { scrolling = newState != RecyclerView.SCROLL_STATE_IDLE; if (!scrolling && forceUpdate != null) { forceUpdate = null; } } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { updateClipView(false); if (forceUpdate != null) { yOffset += dy; } } }); ((DefaultItemAnimator) listView.getItemAnimator()).setDelayAnimations(false); listView.setOnItemLongClickListener((view, position) -> { if (locationType == LOCATION_TYPE_LIVE) { Object object = adapter.getItem(position); if (object instanceof LiveLocation) { final LiveLocation location = (LiveLocation) object; ActionBarPopupWindow.ActionBarPopupWindowLayout popupLayout = new ActionBarPopupWindow.ActionBarPopupWindowLayout(context); ActionBarMenuSubItem cell = new ActionBarMenuSubItem(getParentActivity(), true, true, getResourceProvider()); cell.setMinimumWidth(dp(200)); cell.setTextAndIcon(LocaleController.getString("GetDirections", R.string.GetDirections), R.drawable.filled_directions); cell.setOnClickListener(e -> { openDirections(location); if (popupWindow != null) { popupWindow.dismiss(); } }); popupLayout.addView(cell); popupWindow = new ActionBarPopupWindow(popupLayout, LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT) { @Override public void dismiss() { super.dismiss(); popupWindow = null; } }; popupWindow.setOutsideTouchable(true); popupWindow.setClippingEnabled(true); popupWindow.setInputMethodMode(ActionBarPopupWindow.INPUT_METHOD_NOT_NEEDED); popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED); int[] loc = new int[2]; view.getLocationInWindow(loc); popupWindow.showAtLocation(view, Gravity.TOP, 0, loc[1] - dp(48 + 4)); popupWindow.dimBehind(); return true; } } return false; }); listView.setOnItemClickListener((view, position) -> { selectedMarkerId = -1; if (locationType == LOCATION_TYPE_GROUP) { if (position == 1) { TLRPC.TL_messageMediaVenue venue = (TLRPC.TL_messageMediaVenue) adapter.getItem(position); if (venue == null) { return; } if (dialogId == 0) { delegate.didSelectLocation(venue, LOCATION_TYPE_GROUP, true, 0); finishFragment(); } else { final AlertDialog[] progressDialog = new AlertDialog[]{new AlertDialog(getParentActivity(), AlertDialog.ALERT_TYPE_SPINNER)}; TLRPC.TL_channels_editLocation req = new TLRPC.TL_channels_editLocation(); req.address = venue.address; req.channel = getMessagesController().getInputChannel(-dialogId); req.geo_point = new TLRPC.TL_inputGeoPoint(); req.geo_point.lat = venue.geo.lat; req.geo_point._long = venue.geo._long; int requestId = getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { try { progressDialog[0].dismiss(); } catch (Throwable ignore) { } progressDialog[0] = null; delegate.didSelectLocation(venue, LOCATION_TYPE_GROUP, true, 0); finishFragment(); })); progressDialog[0].setOnCancelListener(dialog -> getConnectionsManager().cancelRequest(requestId, true)); showDialog(progressDialog[0]); } } } else if (locationType == LOCATION_TYPE_GROUP_VIEW) { if (map != null) { map.animateCamera(ApplicationLoader.getMapsProvider().newCameraUpdateLatLngZoom(new IMapsProvider.LatLng(chatLocation.geo_point.lat, chatLocation.geo_point._long), map.getMaxZoomLevel() - 4)); } } else if (position == 1 && messageObject != null && (!messageObject.isLiveLocation() || locationType == LOCATION_TYPE_LIVE_VIEW)) { if (map != null) { map.animateCamera(ApplicationLoader.getMapsProvider().newCameraUpdateLatLngZoom(new IMapsProvider.LatLng(messageObject.messageOwner.media.geo.lat, messageObject.messageOwner.media.geo._long), map.getMaxZoomLevel() - 4)); } } else if (position == 1 && locationType != 2) { if (delegate != null && userLocation != null) { if (lastPressedMarkerView != null) { lastPressedMarkerView.callOnClick(); } else { TLRPC.TL_messageMediaGeo location = new TLRPC.TL_messageMediaGeo(); location.geo = new TLRPC.TL_geoPoint(); location.geo.lat = AndroidUtilities.fixLocationCoord(userLocation.getLatitude()); location.geo._long = AndroidUtilities.fixLocationCoord(userLocation.getLongitude()); if (parentFragment != null && parentFragment.isInScheduleMode()) { AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), parentFragment.getDialogId(), (notify, scheduleDate) -> { delegate.didSelectLocation(location, locationType, notify, scheduleDate); finishFragment(); }); } else { delegate.didSelectLocation(location, locationType, true, 0); finishFragment(); } } } } else if (locationType == LOCATION_TYPE_LIVE && getLocationController().isSharingLocation(dialogId) && adapter.getItemViewType(position) == LocationActivityAdapter.VIEW_TYPE_DELETE_LIVE_LOCATION) { getLocationController().removeSharingLocation(dialogId); adapter.notifyDataSetChanged(); finishFragment(); } else if (locationType == LOCATION_TYPE_LIVE && getLocationController().isSharingLocation(dialogId) && adapter.getItemViewType(position) == LocationActivityAdapter.VIEW_TYPE_LIVE_LOCATION) { openShareLiveLocation(getLocationController().getSharingLocationInfo(dialogId).period != 0x7FFFFFFF, 0); } else if (position == 2 && locationType == 1 || position == 1 && locationType == 2 || position == 3 && locationType == 3) { if (getLocationController().isSharingLocation(dialogId)) { getLocationController().removeSharingLocation(dialogId); adapter.notifyDataSetChanged(); finishFragment(); } else { openShareLiveLocation(false, 0); } } else { Object object = adapter.getItem(position); if (object instanceof TLRPC.TL_messageMediaVenue) { if (parentFragment != null && parentFragment.isInScheduleMode()) { AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), parentFragment.getDialogId(), (notify, scheduleDate) -> { delegate.didSelectLocation((TLRPC.TL_messageMediaVenue) object, locationType, notify, scheduleDate); finishFragment(); }); } else { delegate.didSelectLocation((TLRPC.TL_messageMediaVenue) object, locationType, true, 0); finishFragment(); } } else if (object instanceof LiveLocation) { LiveLocation liveLocation = (LiveLocation) object; selectedMarkerId = liveLocation.id; map.animateCamera(ApplicationLoader.getMapsProvider().newCameraUpdateLatLngZoom(liveLocation.marker.getPosition(), map.getMaxZoomLevel() - 4)); } } }); adapter.setDelegate(dialogId, this::updatePlacesMarkers); adapter.setOverScrollHeight(overScrollHeight); frameLayout.addView(mapViewClip, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP)); mapView = ApplicationLoader.getMapsProvider().onCreateMapView(context); mapView.getView().setAlpha(0f); mapView.setOnDispatchTouchEventInterceptor((ev, origMethod) -> { MotionEvent eventToRecycle = null; if (yOffset != 0) { ev = eventToRecycle = MotionEvent.obtain(ev); eventToRecycle.offsetLocation(0, -yOffset / 2); } boolean result = origMethod.call(ev); if (eventToRecycle != null) { eventToRecycle.recycle(); } return result; }); mapView.setOnInterceptTouchEventInterceptor((ev, origMethod) -> { if (messageObject == null && chatLocation == null) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { if (animatorSet != null) { animatorSet.cancel(); } animatorSet = new AnimatorSet(); animatorSet.setDuration(200); animatorSet.playTogether(ObjectAnimator.ofFloat(markerImageView, View.TRANSLATION_Y, markerTop - dp(10))); animatorSet.start(); } else if (ev.getAction() == MotionEvent.ACTION_UP) { if (animatorSet != null) { animatorSet.cancel(); } yOffset = 0; animatorSet = new AnimatorSet(); animatorSet.setDuration(200); animatorSet.playTogether(ObjectAnimator.ofFloat(markerImageView, View.TRANSLATION_Y, markerTop)); animatorSet.start(); adapter.fetchLocationAddress(); } if (ev.getAction() == MotionEvent.ACTION_MOVE) { if (!userLocationMoved) { locationButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_location_actionIcon), PorterDuff.Mode.MULTIPLY)); locationButton.setTag(Theme.key_location_actionIcon); userLocationMoved = true; } if (map != null) { if (userLocation != null) { userLocation.setLatitude(map.getCameraPosition().target.latitude); userLocation.setLongitude(map.getCameraPosition().target.longitude); } } adapter.setCustomLocation(userLocation); } } return origMethod.call(ev); }); mapView.setOnLayoutListener(()-> AndroidUtilities.runOnUIThread(() -> { if (moveToBounds != null) { map.moveCamera(moveToBounds); moveToBounds = null; } })); IMapsProvider.IMapView map = mapView; new Thread(() -> { try { map.onCreate(null); } catch (Exception e) { //this will cause exception, but will preload google maps? } AndroidUtilities.runOnUIThread(() -> { if (mapView != null && getParentActivity() != null) { try { map.onCreate(null); ApplicationLoader.getMapsProvider().initializeMaps(ApplicationLoader.applicationContext); mapView.getMapAsync(map1 -> { this.map = map1; int themeResId = getMapThemeResId(); if (themeResId != 0) { currentMapStyleDark = true; IMapsProvider.IMapStyleOptions style = ApplicationLoader.getMapsProvider().loadRawResourceStyle(ApplicationLoader.applicationContext, themeResId); this.map.setMapStyle(style); } this.map.setPadding(dp(70), 0, dp(70), dp(10)); onMapInit(); }); mapsInitialized = true; if (onResumeCalled) { mapView.onResume(); } } catch (Exception e) { FileLog.e(e); } } }); }).start(); if (messageObject == null && chatLocation == null) { if (chat != null && locationType == LOCATION_TYPE_GROUP && dialogId != 0) { FrameLayout frameLayout1 = new FrameLayout(context); frameLayout1.setBackgroundResource(R.drawable.livepin); mapViewClip.addView(frameLayout1, LayoutHelper.createFrame(62, 76, Gravity.TOP | Gravity.CENTER_HORIZONTAL)); BackupImageView backupImageView = new BackupImageView(context); backupImageView.setRoundRadius(dp(26)); backupImageView.setForUserOrChat(chat, new AvatarDrawable(chat)); frameLayout1.addView(backupImageView, LayoutHelper.createFrame(52, 52, Gravity.LEFT | Gravity.TOP, 5, 5, 0, 0)); markerImageView = frameLayout1; markerImageView.setTag(1); } if (markerImageView == null) { ImageView imageView = new ImageView(context); imageView.setImageResource(R.drawable.map_pin2); mapViewClip.addView(imageView, LayoutHelper.createFrame(28, 48, Gravity.TOP | Gravity.CENTER_HORIZONTAL)); markerImageView = imageView; } searchListView = new RecyclerListView(context); searchListView.setVisibility(View.GONE); searchListView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)); searchAdapter = new LocationActivitySearchAdapter(context, getResourceProvider(), false, locationType == ChatAttachAlertLocationLayout.LOCATION_TYPE_BIZ) { @Override public void notifyDataSetChanged() { if (searchItem != null) { searchItem.setShowSearchProgress(searchAdapter.isSearching()); } if (emptySubtitleTextView != null) { emptySubtitleTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("NoPlacesFoundInfo", R.string.NoPlacesFoundInfo, searchAdapter.getLastSearchString()))); } super.notifyDataSetChanged(); } }; searchAdapter.setDelegate(0, places -> { searchInProgress = false; updateEmptyView(); }); frameLayout.addView(searchListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP)); searchListView.setOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { if (newState == RecyclerView.SCROLL_STATE_DRAGGING && searching && searchWas) { AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus()); } } }); searchListView.setOnItemClickListener((view, position) -> { TLRPC.TL_messageMediaVenue object = searchAdapter.getItem(position); if (object != null && object.icon != null && locationType == ChatAttachAlertLocationLayout.LOCATION_TYPE_BIZ && this.map != null) { userLocationMoved = true; menu.closeSearchField(true); final float zoom = "pin".equals(object.icon) ? this.map.getMaxZoomLevel() - 4 : this.map.getMaxZoomLevel() - 9; this.map.animateCamera(ApplicationLoader.getMapsProvider().newCameraUpdateLatLngZoom(new IMapsProvider.LatLng(object.geo.lat, object.geo._long), zoom)); if (userLocation != null) { userLocation.setLatitude(object.geo.lat); userLocation.setLongitude(object.geo._long); } adapter.setCustomLocation(userLocation); } else if (object != null && delegate != null) { if (parentFragment != null && parentFragment.isInScheduleMode()) { AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), parentFragment.getDialogId(), (notify, scheduleDate) -> { delegate.didSelectLocation(object, locationType, notify, scheduleDate); finishFragment(); }); } else { delegate.didSelectLocation(object, locationType, true, 0); finishFragment(); } } }); } else if (messageObject != null && !messageObject.isLiveLocation() || chatLocation != null) { if (chatLocation != null) { adapter.setChatLocation(chatLocation); } else if (messageObject != null) { adapter.setMessageObject(messageObject); } } if (messageObject != null && locationType == LOCATION_TYPE_LIVE_VIEW) { adapter.setMessageObject(messageObject); } for (int a = 0; a < 2; a++) { undoView[a] = new UndoView(context); undoView[a].setAdditionalTranslationY(dp(10)); if (Build.VERSION.SDK_INT >= 21) { undoView[a].setTranslationZ(dp(5)); } mapViewClip.addView(undoView[a], LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 8, 0, 8, 8)); } shadow = new View(context) { private RectF rect = new RectF(); @Override protected void onDraw(Canvas canvas) { shadowDrawable.setBounds(-padding.left, 0, getMeasuredWidth() + padding.right, getMeasuredHeight()); shadowDrawable.draw(canvas); if (locationType == LOCATION_TYPE_SEND || locationType == LOCATION_TYPE_SEND_WITH_LIVE) { int w = dp(36); int y = padding.top + dp(10); rect.set((getMeasuredWidth() - w) / 2, y, (getMeasuredWidth() + w) / 2, y + dp(4)); int color = getThemedColor(Theme.key_sheet_scrollUp); int alpha = Color.alpha(color); Theme.dialogs_onlineCirclePaint.setColor(color); canvas.drawRoundRect(rect, dp(2), dp(2), Theme.dialogs_onlineCirclePaint); } } }; if (Build.VERSION.SDK_INT >= 21) { shadow.setTranslationZ(dp(6)); } mapViewClip.addView(shadow, layoutParams); if (messageObject == null && chatLocation == null && initialLocation != null) { userLocationMoved = true; locationButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_location_actionIcon), PorterDuff.Mode.MULTIPLY)); locationButton.setTag(Theme.key_location_actionIcon); } frameLayout.addView(actionBar); updateEmptyView(); return fragmentView; } private boolean isActiveThemeDark() { if (getResourceProvider() == null) { Theme.ThemeInfo info = Theme.getActiveTheme(); if (info.isDark()) { return true; } } int color = getThemedColor(Theme.key_windowBackgroundWhite); return AndroidUtilities.computePerceivedBrightness(color) < 0.721f; } private int getMapThemeResId() { int color = getThemedColor(Theme.key_windowBackgroundWhite); if (AndroidUtilities.computePerceivedBrightness(color) < 0.721f) { // if (Color.blue(color) - 3 > Color.red(color) && Color.blue(color) - 3 > Color.green(color)) { // return R.raw.mapstyle_night; // } else { // return R.raw.mapstyle_dark; // } return R.raw.mapstyle_night; } return 0; } private void openDirections(LiveLocation location) { double daddrLat, daddrLong; if (location != null && location.object != null) { daddrLat = location.object.media.geo.lat; daddrLong = location.object.media.geo._long; } else if (messageObject != null) { daddrLat = messageObject.messageOwner.media.geo.lat; daddrLong = messageObject.messageOwner.media.geo._long; } else { daddrLat = chatLocation.geo_point.lat; daddrLong = chatLocation.geo_point._long; } String domain; if (BuildVars.isHuaweiStoreApp()) { domain = "mapapp://navigation"; } else { domain = "http://maps.google.com/maps"; } if (myLocation != null) { try { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format(Locale.US, domain + "?saddr=%f,%f&daddr=%f,%f", myLocation.getLatitude(), myLocation.getLongitude(), daddrLat, daddrLong))); getParentActivity().startActivity(intent); } catch (Exception e) { FileLog.e(e); } } else { try { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format(Locale.US, domain + "?saddr=&daddr=%f,%f", daddrLat, daddrLong))); getParentActivity().startActivity(intent); } catch (Exception e) { FileLog.e(e); } } } private void updateEmptyView() { if (searching) { if (searchInProgress) { searchListView.setEmptyView(null); emptyView.setVisibility(View.GONE); searchListView.setVisibility(View.GONE); } else { searchListView.setEmptyView(emptyView); } } else { emptyView.setVisibility(View.GONE); } } private void showSearchPlacesButton(boolean show) { if (locationType == 3) { show = true; } if (show && searchAreaButton != null && searchAreaButton.getTag() == null) { if (myLocation == null || userLocation == null || userLocation.distanceTo(myLocation) < 300) { show = false; } } if (searchAreaButton == null || show && searchAreaButton.getTag() != null || !show && searchAreaButton.getTag() == null) { return; } searchAreaButton.setTag(show ? 1 : null); AnimatorSet animatorSet = new AnimatorSet(); animatorSet.playTogether(ObjectAnimator.ofFloat(searchAreaButton, View.TRANSLATION_X, show ? 0 : -dp(80))); animatorSet.setDuration(180); animatorSet.setInterpolator(CubicBezierInterpolator.EASE_OUT); animatorSet.start(); } private Bitmap createUserBitmap(LiveLocation liveLocation) { Bitmap result = null; try { TLRPC.FileLocation photo = null; if (liveLocation.user != null && liveLocation.user.photo != null) { photo = liveLocation.user.photo.photo_small; } else if (liveLocation.chat != null && liveLocation.chat.photo != null) { photo = liveLocation.chat.photo.photo_small; } result = Bitmap.createBitmap(dp(62), dp(85), Bitmap.Config.ARGB_8888); result.eraseColor(Color.TRANSPARENT); Canvas canvas = new Canvas(result); Drawable drawable = ApplicationLoader.applicationContext.getResources().getDrawable(R.drawable.map_pin_photo); drawable.setBounds(0, 0, dp(62), dp(85)); drawable.draw(canvas); Paint roundPaint = new Paint(Paint.ANTI_ALIAS_FLAG); RectF bitmapRect = new RectF(); canvas.save(); if (photo != null) { File path = getFileLoader().getPathToAttach(photo, true); Bitmap bitmap = BitmapFactory.decodeFile(path.toString()); if (bitmap != null) { BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); Matrix matrix = new Matrix(); float scale = dp(50) / (float) bitmap.getWidth(); matrix.postTranslate(dp(6), dp(6)); matrix.postScale(scale, scale); roundPaint.setShader(shader); shader.setLocalMatrix(matrix); bitmapRect.set(dp(6), dp(6), dp(50 + 6), dp(50 + 6)); canvas.drawRoundRect(bitmapRect, dp(25), dp(25), roundPaint); } } else { AvatarDrawable avatarDrawable = new AvatarDrawable(); if (liveLocation.user != null) { avatarDrawable.setInfo(currentAccount, liveLocation.user); } else if (liveLocation.chat != null) { avatarDrawable.setInfo(currentAccount, liveLocation.chat); } canvas.translate(dp(6), dp(6)); avatarDrawable.setBounds(0, 0, dp(50), dp(50)); avatarDrawable.draw(canvas); } canvas.restore(); try { canvas.setBitmap(null); } catch (Exception e) { //don't promt, this will crash on 2.x } } catch (Throwable e) { FileLog.e(e); } return result; } private long getMessageId(TLRPC.Message message) { if (message.from_id != null) { return MessageObject.getFromChatId(message); } else { return MessageObject.getDialogId(message); } } private void openProximityAlert() { if (proximityCircle == null) { createCircle(500); } else { previousRadius = proximityCircle.getRadius(); } TLRPC.User user; if (DialogObject.isUserDialog(dialogId)) { user = getMessagesController().getUser(dialogId); } else { user = null; } proximitySheet = new ProximitySheet(getParentActivity(), user, (move, radius) -> { if (proximityCircle != null) { proximityCircle.setRadius(radius); if (move) { moveToBounds(radius, true, true); } } if (DialogObject.isChatDialog(dialogId)) { return true; } for (int a = 0, N = markers.size(); a < N; a++) { LiveLocation location = markers.get(a); if (location.object == null || UserObject.isUserSelf(location.user)) { continue; } TLRPC.GeoPoint point = location.object.media.geo; Location loc = new Location("network"); loc.setLatitude(point.lat); loc.setLongitude(point._long); if (myLocation.distanceTo(loc) > radius) { return true; } } return false; }, (move, radius) -> { LocationController.SharingLocationInfo info = getLocationController().getSharingLocationInfo(dialogId); if (info == null) { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("ShareLocationAlertTitle", R.string.ShareLocationAlertTitle)); builder.setMessage(LocaleController.getString("ShareLocationAlertText", R.string.ShareLocationAlertText)); builder.setPositiveButton(LocaleController.getString("ShareLocationAlertButton", R.string.ShareLocationAlertButton), (dialog, id) -> shareLiveLocation(user, 900, radius)); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showDialog(builder.create()); return false; } proximitySheet.setRadiusSet(); proximityButton.setImageResource(R.drawable.msg_location_alert2); getUndoView().showWithAction(0, UndoView.ACTION_PROXIMITY_SET, radius, user, null, null); getLocationController().setProximityLocation(dialogId, radius, true); return true; }, () -> { if (map != null) { map.setPadding(dp(70), 0, dp(70), dp(10)); } if (!proximitySheet.getRadiusSet()) { if (previousRadius > 0) { proximityCircle.setRadius(previousRadius); } else if (proximityCircle != null) { proximityCircle.remove(); proximityCircle = null; } } proximitySheet = null; }); FrameLayout frameLayout = (FrameLayout) fragmentView; frameLayout.addView(proximitySheet, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); proximitySheet.show(); } private void openShareLiveLocation(boolean expand, int proximityRadius) { if (delegate == null || disablePermissionCheck() || getParentActivity() == null || myLocation == null || !checkGpsEnabled()) { return; } if (checkBackgroundPermission && Build.VERSION.SDK_INT >= 29) { Activity activity = getParentActivity(); if (activity != null) { askWithRadius = proximityRadius; checkBackgroundPermission = false; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); int lastTime = preferences.getInt("backgroundloc", 0); if (Math.abs(System.currentTimeMillis() / 1000 - lastTime) > 24 * 60 * 60 && activity.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) != PackageManager.PERMISSION_GRANTED) { preferences.edit().putInt("backgroundloc", (int) (System.currentTimeMillis() / 1000)).commit(); AlertsCreator.createBackgroundLocationPermissionDialog(activity, getMessagesController().getUser(getUserConfig().getClientUserId()), () -> openShareLiveLocation(expand, askWithRadius), null).show(); return; } } } TLRPC.User user; if (DialogObject.isUserDialog(dialogId)) { user = getMessagesController().getUser(dialogId); } else { user = null; } showDialog(AlertsCreator.createLocationUpdateDialog(getParentActivity(), expand, user, param -> { if (expand) { LocationController.SharingLocationInfo info = getLocationController().getSharingLocationInfo(dialogId); if (info != null) { TLRPC.TL_messages_editMessage req = new TLRPC.TL_messages_editMessage(); req.peer = getMessagesController().getInputPeer(info.did); req.id = info.mid; req.flags |= 16384; req.media = new TLRPC.TL_inputMediaGeoLive(); req.media.stopped = false; req.media.geo_point = new TLRPC.TL_inputGeoPoint(); Location lastKnownLocation = LocationController.getInstance(currentAccount).getLastKnownLocation(); req.media.geo_point.lat = AndroidUtilities.fixLocationCoord(lastKnownLocation.getLatitude()); req.media.geo_point._long = AndroidUtilities.fixLocationCoord(lastKnownLocation.getLongitude()); req.media.geo_point.accuracy_radius = (int) lastKnownLocation.getAccuracy(); if (req.media.geo_point.accuracy_radius != 0) { req.media.geo_point.flags |= 1; } if (info.lastSentProximityMeters != info.proximityMeters) { req.media.proximity_notification_radius = info.proximityMeters; req.media.flags |= 8; } req.media.heading = LocationController.getHeading(lastKnownLocation); req.media.flags |= 4; req.media.period = info.period = param == 0x7FFFFFFF ? 0x7FFFFFFF : info.period + param; info.stopTime = param == 0x7FFFFFFF ? Integer.MAX_VALUE : info.stopTime + param; req.media.flags |= 2; if (info.messageObject != null && info.messageObject.messageOwner != null && info.messageObject.messageOwner.media != null) { info.messageObject.messageOwner.media.period = info.period; // ArrayList<TLRPC.Message> messages = new ArrayList<>(); // messages.add(info.messageObject.messageOwner); getMessagesStorage().replaceMessageIfExists(info.messageObject.messageOwner, null, null, true); } getConnectionsManager().sendRequest(req, null); NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.liveLocationsChanged); } return; } shareLiveLocation(user, param, proximityRadius); }, null)); } private void shareLiveLocation(TLRPC.User user, int period, int radius) { TLRPC.TL_messageMediaGeoLive location = new TLRPC.TL_messageMediaGeoLive(); location.geo = new TLRPC.TL_geoPoint(); location.geo.lat = AndroidUtilities.fixLocationCoord(myLocation.getLatitude()); location.geo._long = AndroidUtilities.fixLocationCoord(myLocation.getLongitude()); location.heading = LocationController.getHeading(myLocation); location.flags |= 1; location.period = period; location.proximity_notification_radius = radius; location.flags |= 8; delegate.didSelectLocation(location, locationType, true, 0); if (radius > 0) { proximitySheet.setRadiusSet(); proximityButton.setImageResource(R.drawable.msg_location_alert2); if (proximitySheet != null) { proximitySheet.dismiss(); } getUndoView().showWithAction(0, UndoView.ACTION_PROXIMITY_SET, radius, user, null, null); } else { finishFragment(); } } private Bitmap[] bitmapCache = new Bitmap[7]; private Bitmap createPlaceBitmap(int num) { if (bitmapCache[num % 7] != null) { return bitmapCache[num % 7]; } try { Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(0xffffffff); Bitmap bitmap = Bitmap.createBitmap(dp(12), dp(12), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); canvas.drawCircle(dp(6), dp(6), dp(6), paint); paint.setColor(LocationCell.getColorForIndex(num)); canvas.drawCircle(dp(6), dp(6), dp(5), paint); canvas.setBitmap(null); return bitmapCache[num % 7] = bitmap; } catch (Throwable e) { FileLog.e(e); } return null; } private void updatePlacesMarkers(ArrayList<TLRPC.TL_messageMediaVenue> places) { if (places == null) { return; } for (int a = 0, N = placeMarkers.size(); a < N; a++) { placeMarkers.get(a).marker.remove(); } placeMarkers.clear(); for (int a = 0, N = places.size(); a < N; a++) { TLRPC.TL_messageMediaVenue venue = places.get(a); try { IMapsProvider.IMarkerOptions options = ApplicationLoader.getMapsProvider().onCreateMarkerOptions().position(new IMapsProvider.LatLng(venue.geo.lat, venue.geo._long)); options.icon(createPlaceBitmap(a)); options.anchor(0.5f, 0.5f); options.title(venue.title); options.snippet(venue.address); VenueLocation venueLocation = new VenueLocation(); venueLocation.num = a; venueLocation.marker = map.addMarker(options); venueLocation.venue = venue; venueLocation.marker.setTag(venueLocation); placeMarkers.add(venueLocation); } catch (Exception e) { FileLog.e(e); } } } private LiveLocation addUserMarker(TLRPC.Message message) { LiveLocation liveLocation; IMapsProvider.LatLng latLng = new IMapsProvider.LatLng(message.media.geo.lat, message.media.geo._long); if ((liveLocation = markersMap.get(MessageObject.getFromChatId(message))) == null) { liveLocation = new LiveLocation(); liveLocation.object = message; if (liveLocation.object.from_id instanceof TLRPC.TL_peerUser) { liveLocation.user = getMessagesController().getUser(liveLocation.object.from_id.user_id); liveLocation.id = liveLocation.object.from_id.user_id; } else { long did = MessageObject.getDialogId(message); if (DialogObject.isUserDialog(did)) { liveLocation.user = getMessagesController().getUser(did); } else { liveLocation.chat = getMessagesController().getChat(-did); } liveLocation.id = did; } try { IMapsProvider.IMarkerOptions options = ApplicationLoader.getMapsProvider().onCreateMarkerOptions().position(latLng); Bitmap bitmap = createUserBitmap(liveLocation); if (bitmap != null) { options.icon(bitmap); options.anchor(0.5f, 0.907f); liveLocation.marker = map.addMarker(options); if (!UserObject.isUserSelf(liveLocation.user)) { IMapsProvider.IMarkerOptions dirOptions = ApplicationLoader.getMapsProvider().onCreateMarkerOptions().position(latLng).flat(true); dirOptions.anchor(0.5f, 0.5f); liveLocation.directionMarker = map.addMarker(dirOptions); if (message.media.heading != 0) { liveLocation.directionMarker.setRotation(message.media.heading); liveLocation.directionMarker.setIcon(R.drawable.map_pin_cone2); liveLocation.hasRotation = true; } else { liveLocation.directionMarker.setRotation(0); liveLocation.directionMarker.setIcon(R.drawable.map_pin_circle); liveLocation.hasRotation = false; } } markers.add(liveLocation); markersMap.put(liveLocation.id, liveLocation); LocationController.SharingLocationInfo myInfo = getLocationController().getSharingLocationInfo(dialogId); if (liveLocation.id == getUserConfig().getClientUserId() && myInfo != null && liveLocation.object.id == myInfo.mid && myLocation != null) { IMapsProvider.LatLng latLng1 = new IMapsProvider.LatLng(myLocation.getLatitude(), myLocation.getLongitude()); liveLocation.marker.setPosition(latLng1); } } } catch (Exception e) { FileLog.e(e); } } else { liveLocation.object = message; liveLocation.marker.setPosition(latLng); if (selectedMarkerId == liveLocation.id) { map.animateCamera(ApplicationLoader.getMapsProvider().newCameraUpdateLatLng(liveLocation.marker.getPosition())); } } if (proximitySheet != null) { proximitySheet.updateText(true, true); } return liveLocation; } private LiveLocation addUserMarker(TLRPC.TL_channelLocation location) { IMapsProvider.LatLng latLng = new IMapsProvider.LatLng(location.geo_point.lat, location.geo_point._long); LiveLocation liveLocation = new LiveLocation(); if (DialogObject.isUserDialog(dialogId)) { liveLocation.user = getMessagesController().getUser(dialogId); } else { liveLocation.chat = getMessagesController().getChat(-dialogId); } liveLocation.id = dialogId; try { IMapsProvider.IMarkerOptions options = ApplicationLoader.getMapsProvider().onCreateMarkerOptions().position(latLng); Bitmap bitmap = createUserBitmap(liveLocation); if (bitmap != null) { options.icon(bitmap); options.anchor(0.5f, 0.907f); liveLocation.marker = map.addMarker(options); if (!UserObject.isUserSelf(liveLocation.user)) { IMapsProvider.IMarkerOptions dirOptions = ApplicationLoader.getMapsProvider().onCreateMarkerOptions().position(latLng).flat(true); dirOptions.icon(R.drawable.map_pin_circle); dirOptions.anchor(0.5f, 0.5f); liveLocation.directionMarker = map.addMarker(dirOptions); } markers.add(liveLocation); markersMap.put(liveLocation.id, liveLocation); } } catch (Exception e) { FileLog.e(e); } return liveLocation; } private void onMapInit() { if (map == null) { return; } mapView.getView().animate().alpha(1).setStartDelay(200).setDuration(100).start(); final float zoom = initialMaxZoom ? map.getMinZoomLevel() + 4 : map.getMaxZoomLevel() - 4; if (chatLocation != null) { LiveLocation liveLocation = addUserMarker(chatLocation); map.moveCamera(ApplicationLoader.getMapsProvider().newCameraUpdateLatLngZoom(liveLocation.marker.getPosition(), zoom)); } else if (messageObject != null) { if (messageObject.isLiveLocation()) { LiveLocation liveLocation = addUserMarker(messageObject.messageOwner); if (!getRecentLocations()) { map.moveCamera(ApplicationLoader.getMapsProvider().newCameraUpdateLatLngZoom(liveLocation.marker.getPosition(), zoom)); } } else { IMapsProvider.LatLng latLng = new IMapsProvider.LatLng(userLocation.getLatitude(), userLocation.getLongitude()); try { map.addMarker(ApplicationLoader.getMapsProvider().onCreateMarkerOptions().position(latLng).icon(R.drawable.map_pin2)); } catch (Exception e) { FileLog.e(e); } IMapsProvider.ICameraUpdate position = ApplicationLoader.getMapsProvider().newCameraUpdateLatLngZoom(latLng, zoom); map.moveCamera(position); firstFocus = false; getRecentLocations(); } } else { userLocation = new Location("network"); if (initialLocation != null) { IMapsProvider.LatLng latLng = new IMapsProvider.LatLng(initialLocation.geo_point.lat, initialLocation.geo_point._long); map.moveCamera(ApplicationLoader.getMapsProvider().newCameraUpdateLatLngZoom(latLng, zoom)); userLocation.setLatitude(initialLocation.geo_point.lat); userLocation.setLongitude(initialLocation.geo_point._long); userLocation.setAccuracy(initialLocation.geo_point.accuracy_radius); adapter.setCustomLocation(userLocation); } else { userLocation.setLatitude(20.659322); userLocation.setLongitude(-11.406250); } } try { map.setMyLocationEnabled(true); } catch (Exception e) { FileLog.e(e, false); } map.getUiSettings().setMyLocationButtonEnabled(false); map.getUiSettings().setZoomControlsEnabled(false); map.getUiSettings().setCompassEnabled(false); map.setOnCameraMoveStartedListener(reason -> { if (reason == IMapsProvider.OnCameraMoveStartedListener.REASON_GESTURE) { showSearchPlacesButton(true); removeInfoView(); selectedMarkerId = -1; if (!scrolling && (locationType == LOCATION_TYPE_SEND || locationType == LOCATION_TYPE_SEND_WITH_LIVE) && listView.getChildCount() > 0) { View view = listView.getChildAt(0); if (view != null) { RecyclerView.ViewHolder holder = listView.findContainingViewHolder(view); if (holder != null && holder.getAdapterPosition() == 0) { int min = locationType == LOCATION_TYPE_SEND ? 0 : dp(66); int top = view.getTop(); if (top < -min) { IMapsProvider.CameraPosition cameraPosition = map.getCameraPosition(); forceUpdate = ApplicationLoader.getMapsProvider().newCameraUpdateLatLngZoom(cameraPosition.target, cameraPosition.zoom); listView.smoothScrollBy(0, top + min); } } } } } }); map.setOnMyLocationChangeListener(location -> { positionMarker(location); getLocationController().setMapLocation(location, isFirstLocation); isFirstLocation = false; }); map.setOnMarkerClickListener(marker -> { if (!(marker.getTag() instanceof VenueLocation)) { return true; } markerImageView.setVisibility(View.INVISIBLE); if (!userLocationMoved) { locationButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_location_actionIcon), PorterDuff.Mode.MULTIPLY)); locationButton.setTag(Theme.key_location_actionIcon); userLocationMoved = true; } for (int i = 0; i < markers.size(); ++i) { LiveLocation loc = markers.get(i); if (loc != null && loc.marker == marker) { selectedMarkerId = loc.id; map.animateCamera(ApplicationLoader.getMapsProvider().newCameraUpdateLatLngZoom(loc.marker.getPosition(), zoom)); break; } } overlayView.addInfoView(marker); return true; }); map.setOnCameraMoveListener(() -> { if (overlayView != null) { overlayView.updatePositions(); } }); positionMarker(myLocation = getLastLocation()); if (checkGpsEnabled && getParentActivity() != null) { checkGpsEnabled = false; checkGpsEnabled(); } if (proximityButton != null && proximityButton.getVisibility() == View.VISIBLE) { LocationController.SharingLocationInfo myInfo = getLocationController().getSharingLocationInfo(dialogId); if (myInfo != null && myInfo.proximityMeters > 0) { createCircle(myInfo.proximityMeters); } } } private boolean checkGpsEnabled() { if (disablePermissionCheck()) { return false; } if (!getParentActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS)) { return true; } try { LocationManager lm = (LocationManager) ApplicationLoader.applicationContext.getSystemService(Context.LOCATION_SERVICE); if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTopAnimation(R.raw.permission_request_location, AlertsCreator.PERMISSIONS_REQUEST_TOP_ICON_SIZE, false, getThemedColor(Theme.key_dialogTopBackground)); builder.setMessage(LocaleController.getString("GpsDisabledAlertText", R.string.GpsDisabledAlertText)); builder.setPositiveButton(LocaleController.getString("ConnectingToProxyEnable", R.string.ConnectingToProxyEnable), (dialog, id) -> { if (getParentActivity() == null) { return; } try { getParentActivity().startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); } catch (Exception ignore) { } }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showDialog(builder.create()); return false; } } catch (Exception e) { FileLog.e(e); } return true; } private void createCircle(int meters) { if (map == null) { return; } List<IMapsProvider.PatternItem> PATTERN_POLYGON_ALPHA = Arrays.asList(new IMapsProvider.PatternItem.Gap(20), new IMapsProvider.PatternItem.Dash(20)); IMapsProvider.ICircleOptions circleOptions = ApplicationLoader.getMapsProvider().onCreateCircleOptions(); circleOptions.center(new IMapsProvider.LatLng(myLocation.getLatitude(), myLocation.getLongitude())); circleOptions.radius(meters); if (isActiveThemeDark()) { circleOptions.strokeColor(0x9666A3D7); circleOptions.fillColor(0x1c66A3D7); } else { circleOptions.strokeColor(0x964286F5); circleOptions.fillColor(0x1c4286F5); } circleOptions.strokePattern(PATTERN_POLYGON_ALPHA); circleOptions.strokeWidth(2); proximityCircle = map.addCircle(circleOptions); } private void removeInfoView() { if (lastPressedMarker != null) { markerImageView.setVisibility(View.VISIBLE); overlayView.removeInfoView(lastPressedMarker); lastPressedMarker = null; lastPressedVenue = null; lastPressedMarkerView = null; } } private void showPermissionAlert(boolean byButton) { if (getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTopAnimation(R.raw.permission_request_location, AlertsCreator.PERMISSIONS_REQUEST_TOP_ICON_SIZE, false, getThemedColor(Theme.key_dialogTopBackground)); if (byButton) { builder.setMessage(AndroidUtilities.replaceTags(LocaleController.getString("PermissionNoLocationNavigation", R.string.PermissionNoLocationNavigation))); } else { builder.setMessage(AndroidUtilities.replaceTags(LocaleController.getString("PermissionNoLocationFriends", R.string.PermissionNoLocationFriends))); } builder.setNegativeButton(LocaleController.getString("PermissionOpenSettings", R.string.PermissionOpenSettings), (dialog, which) -> { if (getParentActivity() == null) { return; } try { Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS); intent.setData(Uri.parse("package:" + ApplicationLoader.applicationContext.getPackageName())); getParentActivity().startActivity(intent); } catch (Exception e) { FileLog.e(e); } }); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); showDialog(builder.create()); } @Override public void onTransitionAnimationEnd(boolean isOpen, boolean backward) { if (isOpen && !backward) { try { if (mapView.getView().getParent() instanceof ViewGroup) { ViewGroup viewGroup = (ViewGroup) mapView.getView().getParent(); viewGroup.removeView(mapView.getView()); } } catch (Exception ignore) { } if (mapViewClip != null) { mapViewClip.addView(mapView.getView(), 0, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, overScrollHeight + dp(10), Gravity.TOP | Gravity.LEFT)); if (overlayView != null) { try { if (overlayView.getParent() instanceof ViewGroup) { ViewGroup viewGroup = (ViewGroup) overlayView.getParent(); viewGroup.removeView(overlayView); } } catch (Exception ignore) { } mapViewClip.addView(overlayView, 1, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, overScrollHeight + dp(10), Gravity.TOP | Gravity.LEFT)); } updateClipView(false); maybeShowProximityHint(); } else if (fragmentView != null) { ((FrameLayout) fragmentView).addView(mapView.getView(), 0, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT)); } } } private void maybeShowProximityHint() { if (proximityButton == null || proximityButton.getVisibility() != View.VISIBLE || proximityAnimationInProgress) { return; } SharedPreferences preferences = MessagesController.getGlobalMainSettings(); int val = preferences.getInt("proximityhint", 0); if (val < 3) { preferences.edit().putInt("proximityhint", ++val).commit(); if (DialogObject.isUserDialog(dialogId)) { TLRPC.User user = getMessagesController().getUser(dialogId); hintView.setText(LocaleController.formatString("ProximityTooltioUser", R.string.ProximityTooltioUser, UserObject.getFirstName(user))); } else { hintView.setText(LocaleController.getString("ProximityTooltioGroup", R.string.ProximityTooltioGroup)); } hintView.show(); } } private void showResults() { if (adapter.getItemCount() == 0) { return; } int position = layoutManager.findFirstVisibleItemPosition(); if (position != 0) { return; } View child = listView.getChildAt(0); int offset = dp(258) + child.getTop(); if (offset < 0 || offset > dp(258)) { return; } listView.smoothScrollBy(0, offset); } private void updateClipView(boolean fromLayout) { int height = 0; int top; RecyclerView.ViewHolder holder = listView.findViewHolderForAdapterPosition(0); if (holder != null) { top = (int) holder.itemView.getY(); height = overScrollHeight + (Math.min(top, 0)); } else { top = -mapViewClip.getMeasuredHeight(); } FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mapViewClip.getLayoutParams(); if (layoutParams != null) { if (height <= 0) { if (mapView.getView().getVisibility() == View.VISIBLE) { mapView.getView().setVisibility(View.INVISIBLE); mapViewClip.setVisibility(View.INVISIBLE); if (overlayView != null) { overlayView.setVisibility(View.INVISIBLE); } } } else { if (mapView.getView().getVisibility() == View.INVISIBLE) { mapView.getView().setVisibility(View.VISIBLE); mapViewClip.setVisibility(View.VISIBLE); if (overlayView != null) { overlayView.setVisibility(View.VISIBLE); } } } mapViewClip.setTranslationY(Math.min(0, top)); mapView.getView().setTranslationY(Math.max(0, -top / 2)); if (overlayView != null) { overlayView.setTranslationY(Math.max(0, -top / 2)); } float translationY = Math.min(overScrollHeight - mapTypeButton.getMeasuredHeight() - dp(64 + (locationType == LOCATION_TYPE_SEND || locationType == LOCATION_TYPE_SEND_WITH_LIVE ? 30 : 10)), -top); mapTypeButton.setTranslationY(translationY); proximityButton.setTranslationY(translationY); if (hintView != null) { hintView.setTranslationY(translationY); } if (searchAreaButton != null) { searchAreaButton.setTranslation(translationY); } if (markerImageView != null) { markerImageView.setTranslationY(markerTop = -top - dp(markerImageView.getTag() == null ? 48 : 69) + height / 2); } if (!fromLayout) { layoutParams = (FrameLayout.LayoutParams) mapView.getView().getLayoutParams(); if (layoutParams != null && layoutParams.height != overScrollHeight + dp(10)) { layoutParams.height = overScrollHeight + dp(10); if (map != null) { map.setPadding(dp(70), 0, dp(70), dp(10)); } mapView.getView().setLayoutParams(layoutParams); } if (overlayView != null) { layoutParams = (FrameLayout.LayoutParams) overlayView.getLayoutParams(); if (layoutParams != null && layoutParams.height != overScrollHeight + dp(10)) { layoutParams.height = overScrollHeight + dp(10); overlayView.setLayoutParams(layoutParams); } } } } } private void fixLayoutInternal(final boolean resume) { if (listView != null) { int height = (actionBar.getOccupyStatusBar() ? AndroidUtilities.statusBarHeight : 0) + ActionBar.getCurrentActionBarHeight(); int viewHeight = fragmentView.getMeasuredHeight(); if (viewHeight == 0) { return; } if (locationType == LOCATION_TYPE_LIVE_VIEW) { overScrollHeight = viewHeight - dp(66) - height; } else if (locationType == 2) { overScrollHeight = viewHeight - dp(66 + 7) - height; } else { overScrollHeight = viewHeight - dp(66) - height; } FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); layoutParams.topMargin = height; listView.setLayoutParams(layoutParams); layoutParams = (FrameLayout.LayoutParams) mapViewClip.getLayoutParams(); layoutParams.topMargin = height; layoutParams.height = overScrollHeight; mapViewClip.setLayoutParams(layoutParams); if (searchListView != null) { layoutParams = (FrameLayout.LayoutParams) searchListView.getLayoutParams(); layoutParams.topMargin = height; searchListView.setLayoutParams(layoutParams); } adapter.setOverScrollHeight(overScrollHeight); layoutParams = (FrameLayout.LayoutParams) mapView.getView().getLayoutParams(); if (layoutParams != null) { layoutParams.height = overScrollHeight + dp(10); if (map != null) { map.setPadding(dp(70), 0, dp(70), dp(10)); } mapView.getView().setLayoutParams(layoutParams); } if (overlayView != null) { layoutParams = (FrameLayout.LayoutParams) overlayView.getLayoutParams(); if (layoutParams != null) { layoutParams.height = overScrollHeight + dp(10); overlayView.setLayoutParams(layoutParams); } } adapter.notifyDataSetChanged(); if (resume) { int top; if (locationType == 3) { top = 73; } else if (locationType == 1 || locationType == 2) { top = 66; } else { top = 0; } layoutManager.scrollToPositionWithOffset(0, -dp(top)); updateClipView(false); listView.post(() -> { layoutManager.scrollToPositionWithOffset(0, -dp(top)); updateClipView(false); }); } else { updateClipView(false); } } } @SuppressLint("MissingPermission") private Location getLastLocation() { LocationManager lm = (LocationManager) ApplicationLoader.applicationContext.getSystemService(Context.LOCATION_SERVICE); List<String> providers = lm.getProviders(true); Location l = null; for (int i = providers.size() - 1; i >= 0; i--) { l = lm.getLastKnownLocation(providers.get(i)); if (l != null) { break; } } return l; } private void positionMarker(Location location) { if (location == null) { return; } myLocation = new Location(location); LiveLocation liveLocation = markersMap.get(getUserConfig().getClientUserId()); LocationController.SharingLocationInfo myInfo = getLocationController().getSharingLocationInfo(dialogId); if (liveLocation != null && myInfo != null && liveLocation.object.id == myInfo.mid) { IMapsProvider.LatLng latLng = new IMapsProvider.LatLng(location.getLatitude(), location.getLongitude()); liveLocation.marker.setPosition(latLng); if (liveLocation.directionMarker != null) { liveLocation.directionMarker.setPosition(latLng); } if (selectedMarkerId == liveLocation.id) { map.animateCamera(ApplicationLoader.getMapsProvider().newCameraUpdateLatLng(liveLocation.marker.getPosition())); } } if (messageObject == null && chatLocation == null && map != null) { IMapsProvider.LatLng latLng = new IMapsProvider.LatLng(location.getLatitude(), location.getLongitude()); if (adapter != null) { if (!searchedForCustomLocations && locationType != LOCATION_TYPE_GROUP && locationType != ChatAttachAlertLocationLayout.LOCATION_TYPE_BIZ) { adapter.searchPlacesWithQuery(null, myLocation, true); } adapter.setGpsLocation(myLocation); } if (!userLocationMoved) { userLocation = new Location(location); if (firstWas) { IMapsProvider.ICameraUpdate position = ApplicationLoader.getMapsProvider().newCameraUpdateLatLng(latLng); map.animateCamera(position); } else { firstWas = true; IMapsProvider.ICameraUpdate position = ApplicationLoader.getMapsProvider().newCameraUpdateLatLngZoom(latLng, map.getMaxZoomLevel() - 4); map.moveCamera(position); } } } else { adapter.setGpsLocation(myLocation); } if (proximitySheet != null) { proximitySheet.updateText(true, true); } if (proximityCircle != null) { proximityCircle.setCenter(new IMapsProvider.LatLng(myLocation.getLatitude(), myLocation.getLongitude())); } } public void setMessageObject(MessageObject message) { messageObject = message; dialogId = messageObject.getDialogId(); } public void setChatLocation(long chatId, TLRPC.TL_channelLocation location) { dialogId = -chatId; chatLocation = location; } public void setDialogId(long did) { dialogId = did; } public void setInitialLocation(TLRPC.TL_channelLocation location) { initialLocation = location; } private static final double EARTHRADIUS = 6366198; private static IMapsProvider.LatLng move(IMapsProvider.LatLng startLL, double toNorth, double toEast) { double lonDiff = meterToLongitude(toEast, startLL.latitude); double latDiff = meterToLatitude(toNorth); return new IMapsProvider.LatLng(startLL.latitude + latDiff, startLL.longitude + lonDiff); } private static double meterToLongitude(double meterToEast, double latitude) { double latArc = Math.toRadians(latitude); double radius = Math.cos(latArc) * EARTHRADIUS; double rad = meterToEast / radius; return Math.toDegrees(rad); } private static double meterToLatitude(double meterToNorth) { double rad = meterToNorth / EARTHRADIUS; return Math.toDegrees(rad); } private void fetchRecentLocations(ArrayList<TLRPC.Message> messages) { IMapsProvider.ILatLngBoundsBuilder builder = null; if (firstFocus) { builder = ApplicationLoader.getMapsProvider().onCreateLatLngBoundsBuilder(); } int date = getConnectionsManager().getCurrentTime(); for (int a = 0; a < messages.size(); a++) { TLRPC.Message message = messages.get(a); if (message.date + message.media.period > date) { if (builder != null) { IMapsProvider.LatLng latLng = new IMapsProvider.LatLng(message.media.geo.lat, message.media.geo._long); builder.include(latLng); } addUserMarker(message); if (proximityButton.getVisibility() != View.GONE && MessageObject.getFromChatId(message) != getUserConfig().getClientUserId()) { proximityButton.setVisibility(View.VISIBLE); proximityAnimationInProgress = true; proximityButton.animate().alpha(1.0f).scaleX(1.0f).scaleY(1.0f).setDuration(180).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { proximityAnimationInProgress = false; maybeShowProximityHint(); } }).start(); } } } if (builder != null) { if (firstFocus) { listView.smoothScrollBy(0, dp(66 * 1.5f)); } firstFocus = false; adapter.setLiveLocations(markers); if (messageObject.isLiveLocation()) { try { IMapsProvider.ILatLngBounds bounds = builder.build(); IMapsProvider.LatLng center = bounds.getCenter(); IMapsProvider.LatLng northEast = move(center, 100, 100); IMapsProvider.LatLng southWest = move(center, -100, -100); builder.include(southWest); builder.include(northEast); bounds = builder.build(); if (messages.size() > 1) { try { moveToBounds = ApplicationLoader.getMapsProvider().newCameraUpdateLatLngBounds(bounds, dp(80 + 33)); map.moveCamera(moveToBounds); moveToBounds = null; } catch (Exception e) { FileLog.e(e); } } } catch (Exception ignore) { } } } } private void moveToBounds(int radius, boolean self, boolean animated) { IMapsProvider.ILatLngBoundsBuilder builder = ApplicationLoader.getMapsProvider().onCreateLatLngBoundsBuilder(); builder.include(new IMapsProvider.LatLng(myLocation.getLatitude(), myLocation.getLongitude())); if (self) { try { radius = Math.max(radius, 250); IMapsProvider.ILatLngBounds bounds = builder.build(); IMapsProvider.LatLng center = bounds.getCenter(); IMapsProvider.LatLng northEast = move(center, radius, radius); IMapsProvider.LatLng southWest = move(center, -radius, -radius); builder.include(southWest); builder.include(northEast); bounds = builder.build(); try { int height = (int) (proximitySheet.getCustomView().getMeasuredHeight() - dp(40) + mapViewClip.getTranslationY()); map.setPadding(dp(70), 0, dp(70), height); if (animated) { map.animateCamera(ApplicationLoader.getMapsProvider().newCameraUpdateLatLngBounds(bounds, 0), 500, null); } else { map.moveCamera(ApplicationLoader.getMapsProvider().newCameraUpdateLatLngBounds(bounds, 0)); } } catch (Exception e) { FileLog.e(e); } } catch (Exception ignore) { } } else { int date = getConnectionsManager().getCurrentTime(); for (int a = 0, N = markers.size(); a < N; a++) { TLRPC.Message message = markers.get(a).object; if (message.date + message.media.period > date) { IMapsProvider.LatLng latLng = new IMapsProvider.LatLng(message.media.geo.lat, message.media.geo._long); builder.include(latLng); } } try { IMapsProvider.ILatLngBounds bounds = builder.build(); IMapsProvider.LatLng center = bounds.getCenter(); IMapsProvider.LatLng northEast = move(center, 100, 100); IMapsProvider.LatLng southWest = move(center, -100, -100); builder.include(southWest); builder.include(northEast); bounds = builder.build(); try { int height = proximitySheet.getCustomView().getMeasuredHeight() - dp(100); map.setPadding(dp(70), 0, dp(70), height); map.moveCamera(ApplicationLoader.getMapsProvider().newCameraUpdateLatLngBounds(bounds, 0)); } catch (Exception e) { FileLog.e(e); } } catch (Exception ignore) { } } } private boolean getRecentLocations() { ArrayList<TLRPC.Message> messages = getLocationController().locationsCache.get(messageObject.getDialogId()); if (messages != null && messages.isEmpty()) { fetchRecentLocations(messages); } else { messages = null; } if (DialogObject.isChatDialog(dialogId)) { TLRPC.Chat chat = getMessagesController().getChat(-dialogId); if (ChatObject.isChannel(chat) && !chat.megagroup) { return false; } } TLRPC.TL_messages_getRecentLocations req = new TLRPC.TL_messages_getRecentLocations(); final long dialog_id = messageObject.getDialogId(); req.peer = getMessagesController().getInputPeer(dialog_id); req.limit = 100; getConnectionsManager().sendRequest(req, (response, error) -> { if (response != null) { AndroidUtilities.runOnUIThread(() -> { if (map == null) { return; } TLRPC.messages_Messages res = (TLRPC.messages_Messages) response; for (int a = 0; a < res.messages.size(); a++) { if (!(res.messages.get(a).media instanceof TLRPC.TL_messageMediaGeoLive)) { res.messages.remove(a); a--; } } getMessagesStorage().putUsersAndChats(res.users, res.chats, true, true); getMessagesController().putUsers(res.users, false); getMessagesController().putChats(res.chats, false); getLocationController().locationsCache.put(dialog_id, res.messages); getNotificationCenter().postNotificationName(NotificationCenter.liveLocationsCacheChanged, dialog_id); fetchRecentLocations(res.messages); getLocationController().markLiveLoactionsAsRead(dialogId); if (markAsReadRunnable == null) { markAsReadRunnable = () -> { getLocationController().markLiveLoactionsAsRead(dialogId); if (isPaused || markAsReadRunnable == null) { return; } AndroidUtilities.runOnUIThread(markAsReadRunnable, 5000); }; AndroidUtilities.runOnUIThread(markAsReadRunnable, 5000); } }); } }); return messages != null; } private double bearingBetweenLocations(IMapsProvider.LatLng latLng1, IMapsProvider.LatLng latLng2) { double lat1 = latLng1.latitude * Math.PI / 180; double long1 = latLng1.longitude * Math.PI / 180; double lat2 = latLng2.latitude * Math.PI / 180; double long2 = latLng2.longitude * Math.PI / 180; double dLon = (long2 - long1); double y = Math.sin(dLon) * Math.cos(lat2); double x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon); double brng = Math.atan2(y, x); brng = Math.toDegrees(brng); brng = (brng + 360) % 360; return brng; } @SuppressWarnings("unchecked") @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.closeChats) { removeSelfFromStack(true); } else if (id == NotificationCenter.locationPermissionGranted) { locationDenied = false; if (adapter != null) { adapter.setMyLocationDenied(locationDenied, false); } if (map != null) { try { map.setMyLocationEnabled(true); } catch (Exception e) { FileLog.e(e); } } } else if (id == NotificationCenter.locationPermissionDenied) { locationDenied = true; if (adapter != null) { adapter.setMyLocationDenied(locationDenied, false); } } else if (id == NotificationCenter.liveLocationsChanged) { if (adapter != null) { adapter.notifyDataSetChanged(); adapter.updateLiveLocationCell(); } } else if (id == NotificationCenter.didReceiveNewMessages) { boolean scheduled = (Boolean) args[2]; if (scheduled) { return; } long did = (Long) args[0]; if (did != dialogId || messageObject == null) { return; } ArrayList<MessageObject> arr = (ArrayList<MessageObject>) args[1]; boolean added = false; for (int a = 0; a < arr.size(); a++) { MessageObject messageObject = arr.get(a); if (messageObject.isLiveLocation()) { addUserMarker(messageObject.messageOwner); added = true; } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionGeoProximityReached) { if (DialogObject.isUserDialog(messageObject.getDialogId())) { proximityButton.setImageResource(R.drawable.msg_location_alert); if (proximityCircle != null) { proximityCircle.remove(); proximityCircle = null; } } } } if (added && adapter != null) { adapter.setLiveLocations(markers); } } else if (id == NotificationCenter.replaceMessagesObjects) { long did = (long) args[0]; if (did != dialogId || messageObject == null) { return; } boolean updated = false; ArrayList<MessageObject> messageObjects = (ArrayList<MessageObject>) args[1]; for (int a = 0; a < messageObjects.size(); a++) { MessageObject messageObject = messageObjects.get(a); if (!messageObject.isLiveLocation()) { continue; } LiveLocation liveLocation = markersMap.get(getMessageId(messageObject.messageOwner)); if (liveLocation != null) { LocationController.SharingLocationInfo myInfo = getLocationController().getSharingLocationInfo(did); if (myInfo == null || myInfo.mid != messageObject.getId()) { liveLocation.object = messageObject.messageOwner; IMapsProvider.LatLng latLng = new IMapsProvider.LatLng(messageObject.messageOwner.media.geo.lat, messageObject.messageOwner.media.geo._long); liveLocation.marker.setPosition(latLng); if (selectedMarkerId == liveLocation.id) { map.animateCamera(ApplicationLoader.getMapsProvider().newCameraUpdateLatLng(liveLocation.marker.getPosition())); } if (liveLocation.directionMarker != null) { IMapsProvider.LatLng oldLocation = liveLocation.directionMarker.getPosition(); liveLocation.directionMarker.setPosition(latLng); if (messageObject.messageOwner.media.heading != 0) { liveLocation.directionMarker.setRotation(messageObject.messageOwner.media.heading); if (!liveLocation.hasRotation) { liveLocation.directionMarker.setIcon(R.drawable.map_pin_cone2); liveLocation.hasRotation = true; } } else { if (liveLocation.hasRotation) { liveLocation.directionMarker.setRotation(0); liveLocation.directionMarker.setIcon(R.drawable.map_pin_circle); liveLocation.hasRotation = false; } } } } updated = true; } } if (updated && adapter != null) { adapter.updateLiveLocations(); if (proximitySheet != null) { proximitySheet.updateText(true, true); } } } } @Override public void onPause() { super.onPause(); if (mapView != null && mapsInitialized) { try { mapView.onPause(); } catch (Exception e) { FileLog.e(e); } } if (undoView[0] != null) { undoView[0].hide(true, 0); } onResumeCalled = false; } @Override public boolean onBackPressed() { if (proximitySheet != null) { proximitySheet.dismiss(); return false; } if (onCheckGlScreenshot()) { return false; } return super.onBackPressed(); } @Override public boolean finishFragment(boolean animated) { if (onCheckGlScreenshot()) { return false; } return super.finishFragment(animated); } private boolean onCheckGlScreenshot() { if (mapView != null && mapView.getGlSurfaceView() != null && !hasScreenshot) { GLSurfaceView glSurfaceView = mapView.getGlSurfaceView(); glSurfaceView.queueEvent(() -> { if (glSurfaceView.getWidth() == 0 || glSurfaceView.getHeight() == 0) { return; } ByteBuffer buffer = ByteBuffer.allocateDirect(glSurfaceView.getWidth() * glSurfaceView.getHeight() * 4); GLES20.glReadPixels(0, 0, glSurfaceView.getWidth(), glSurfaceView.getHeight(), GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, buffer); Bitmap bitmap = Bitmap.createBitmap(glSurfaceView.getWidth(), glSurfaceView.getHeight(), Bitmap.Config.ARGB_8888); bitmap.copyPixelsFromBuffer(buffer); Matrix flipVertically = new Matrix(); flipVertically.preScale(1, -1); Bitmap flippedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), flipVertically, false); bitmap.recycle(); AndroidUtilities.runOnUIThread(()->{ ImageView snapshotView = new ImageView(getContext()); snapshotView.setImageBitmap(flippedBitmap); ViewGroup parent = (ViewGroup) glSurfaceView.getParent(); try { parent.addView(snapshotView, parent.indexOfChild(glSurfaceView)); } catch (Exception e) { FileLog.e(e); } AndroidUtilities.runOnUIThread(()->{ try { parent.removeView(glSurfaceView); } catch (Exception e) { FileLog.e(e); } hasScreenshot = true; finishFragment(); }, 100); }); }); return true; } return false; } @Override public void onBecomeFullyHidden() { if (undoView[0] != null) { undoView[0].hide(true, 0); } } @Override public void onResume() { super.onResume(); AndroidUtilities.requestAdjustResize(getParentActivity(), classGuid); AndroidUtilities.removeAdjustResize(getParentActivity(), classGuid); if (mapView != null && mapsInitialized) { try { mapView.onResume(); } catch (Throwable e) { FileLog.e(e); } } onResumeCalled = true; if (map != null) { try { map.setMyLocationEnabled(true); } catch (Exception e) { FileLog.e(e); } } fixLayoutInternal(true); if (disablePermissionCheck()) { checkPermission = false; } else if (checkPermission && Build.VERSION.SDK_INT >= 23) { Activity activity = getParentActivity(); if (activity != null) { checkPermission = false; if (activity.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { activity.requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 2); } } } if (markAsReadRunnable != null) { AndroidUtilities.cancelRunOnUIThread(markAsReadRunnable); AndroidUtilities.runOnUIThread(markAsReadRunnable, 5000); } } protected boolean disablePermissionCheck() { return false; } @Override public void onRequestPermissionsResultFragment(int requestCode, String[] permissions, int[] grantResults) { if (requestCode == 30) { openShareLiveLocation(false, askWithRadius); } } @Override public void onLowMemory() { super.onLowMemory(); if (mapView != null && mapsInitialized) { mapView.onLowMemory(); } } public void setDelegate(LocationActivityDelegate delegate) { this.delegate = delegate; } public void setChatActivity(ChatActivity chatActivity) { parentFragment = chatActivity; } private void updateSearchInterface() { if (adapter != null) { adapter.notifyDataSetChanged(); } } @Override public ArrayList<ThemeDescription> getThemeDescriptions() { ArrayList<ThemeDescription> themeDescriptions = new ArrayList<>(); ThemeDescription.ThemeDescriptionDelegate cellDelegate = () -> { mapTypeButton.setIconColor(getThemedColor(Theme.key_location_actionIcon)); mapTypeButton.redrawPopup(getThemedColor(Theme.key_actionBarDefaultSubmenuBackground)); mapTypeButton.setPopupItemsColor(getThemedColor(Theme.key_actionBarDefaultSubmenuItemIcon), true); mapTypeButton.setPopupItemsColor(getThemedColor(Theme.key_actionBarDefaultSubmenuItem), false); shadowDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogBackground), PorterDuff.Mode.MULTIPLY)); shadow.invalidate(); if (map != null) { int themeResId = getMapThemeResId(); if (themeResId != 0) { if (!currentMapStyleDark) { currentMapStyleDark = true; IMapsProvider.IMapStyleOptions style = ApplicationLoader.getMapsProvider().loadRawResourceStyle(ApplicationLoader.applicationContext, themeResId); map.setMapStyle(style); if (proximityCircle != null) { proximityCircle.setStrokeColor(0xffffffff); proximityCircle.setFillColor(0x20ffffff); } } } else { if (currentMapStyleDark) { currentMapStyleDark = false; map.setMapStyle(null); if (proximityCircle != null) { proximityCircle.setStrokeColor(0xff000000); proximityCircle.setFillColor(0x20000000); } } } } }; for (int a = 0; a < undoView.length; a++) { themeDescriptions.add(new ThemeDescription(undoView[a], ThemeDescription.FLAG_BACKGROUNDFILTER, null, null, null, null, Theme.key_undo_background)); themeDescriptions.add(new ThemeDescription(undoView[a], 0, new Class[]{UndoView.class}, new String[]{"undoImageView"}, null, null, null, Theme.key_undo_cancelColor)); themeDescriptions.add(new ThemeDescription(undoView[a], 0, new Class[]{UndoView.class}, new String[]{"undoTextView"}, null, null, null, Theme.key_undo_cancelColor)); themeDescriptions.add(new ThemeDescription(undoView[a], 0, new Class[]{UndoView.class}, new String[]{"infoTextView"}, null, null, null, Theme.key_undo_infoColor)); themeDescriptions.add(new ThemeDescription(undoView[a], 0, new Class[]{UndoView.class}, new String[]{"subinfoTextView"}, null, null, null, Theme.key_undo_infoColor)); themeDescriptions.add(new ThemeDescription(undoView[a], 0, new Class[]{UndoView.class}, new String[]{"textPaint"}, null, null, null, Theme.key_undo_infoColor)); themeDescriptions.add(new ThemeDescription(undoView[a], 0, new Class[]{UndoView.class}, new String[]{"progressPaint"}, null, null, null, Theme.key_undo_infoColor)); themeDescriptions.add(new ThemeDescription(undoView[a], 0, new Class[]{UndoView.class}, new String[]{"leftImageView"}, "BODY", Theme.key_undo_background)); themeDescriptions.add(new ThemeDescription(undoView[a], 0, new Class[]{UndoView.class}, new String[]{"leftImageView"}, "Wibe Big", Theme.key_undo_background)); themeDescriptions.add(new ThemeDescription(undoView[a], 0, new Class[]{UndoView.class}, new String[]{"leftImageView"}, "Wibe Big 3", Theme.key_undo_infoColor)); themeDescriptions.add(new ThemeDescription(undoView[a], 0, new Class[]{UndoView.class}, new String[]{"leftImageView"}, "Wibe Small", Theme.key_undo_infoColor)); themeDescriptions.add(new ThemeDescription(undoView[a], 0, new Class[]{UndoView.class}, new String[]{"leftImageView"}, "Body Main.**", Theme.key_undo_infoColor)); themeDescriptions.add(new ThemeDescription(undoView[a], 0, new Class[]{UndoView.class}, new String[]{"leftImageView"}, "Body Top.**", Theme.key_undo_infoColor)); themeDescriptions.add(new ThemeDescription(undoView[a], 0, new Class[]{UndoView.class}, new String[]{"leftImageView"}, "Line.**", Theme.key_undo_infoColor)); themeDescriptions.add(new ThemeDescription(undoView[a], 0, new Class[]{UndoView.class}, new String[]{"leftImageView"}, "Curve Big.**", Theme.key_undo_infoColor)); themeDescriptions.add(new ThemeDescription(undoView[a], 0, new Class[]{UndoView.class}, new String[]{"leftImageView"}, "Curve Small.**", Theme.key_undo_infoColor)); } themeDescriptions.add(new ThemeDescription(fragmentView, ThemeDescription.FLAG_BACKGROUND, null, null, null, cellDelegate, Theme.key_dialogBackground)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_dialogBackground)); themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_LISTGLOWCOLOR, null, null, null, null, Theme.key_dialogBackground)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_ITEMSCOLOR, null, null, null, null, Theme.key_dialogTextBlack)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_TITLECOLOR, null, null, null, null, Theme.key_dialogTextBlack)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SELECTORCOLOR, null, null, null, null, Theme.key_dialogButtonSelector)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SEARCH, null, null, null, null, Theme.key_dialogTextBlack)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SEARCHPLACEHOLDER, null, null, null, null, Theme.key_chat_messagePanelHint)); themeDescriptions.add(new ThemeDescription(searchItem != null ? searchItem.getSearchField() : null, ThemeDescription.FLAG_CURSORCOLOR, null, null, null, null, Theme.key_dialogTextBlack)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SUBMENUBACKGROUND, null, null, null, cellDelegate, Theme.key_actionBarDefaultSubmenuBackground)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SUBMENUITEM, null, null, null, cellDelegate, Theme.key_actionBarDefaultSubmenuItem)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SUBMENUITEM | ThemeDescription.FLAG_IMAGECOLOR, null, null, null, cellDelegate, Theme.key_actionBarDefaultSubmenuItemIcon)); themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_SELECTOR, null, null, null, null, Theme.key_listSelector)); themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{View.class}, Theme.dividerPaint, null, null, Theme.key_divider)); themeDescriptions.add(new ThemeDescription(emptyImageView, ThemeDescription.FLAG_IMAGECOLOR, null, null, null, null, Theme.key_dialogEmptyImage)); themeDescriptions.add(new ThemeDescription(emptyTitleTextView, ThemeDescription.FLAG_TEXTCOLOR, null, null, null, null, Theme.key_dialogEmptyText)); themeDescriptions.add(new ThemeDescription(emptySubtitleTextView, ThemeDescription.FLAG_TEXTCOLOR, null, null, null, null, Theme.key_dialogEmptyText)); themeDescriptions.add(new ThemeDescription(shadow, 0, null, null, null, null, Theme.key_sheet_scrollUp)); themeDescriptions.add(new ThemeDescription(locationButton, ThemeDescription.FLAG_IMAGECOLOR | ThemeDescription.FLAG_CHECKTAG, null, null, null, null, Theme.key_location_actionIcon)); themeDescriptions.add(new ThemeDescription(locationButton, ThemeDescription.FLAG_IMAGECOLOR | ThemeDescription.FLAG_CHECKTAG, null, null, null, null, Theme.key_location_actionActiveIcon)); themeDescriptions.add(new ThemeDescription(locationButton, ThemeDescription.FLAG_BACKGROUNDFILTER, null, null, null, null, Theme.key_location_actionBackground)); themeDescriptions.add(new ThemeDescription(locationButton, ThemeDescription.FLAG_BACKGROUNDFILTER | ThemeDescription.FLAG_DRAWABLESELECTEDSTATE, null, null, null, null, Theme.key_location_actionPressedBackground)); themeDescriptions.add(new ThemeDescription(mapTypeButton, 0, null, null, null, cellDelegate, Theme.key_location_actionIcon)); themeDescriptions.add(new ThemeDescription(mapTypeButton, ThemeDescription.FLAG_BACKGROUNDFILTER, null, null, null, null, Theme.key_location_actionBackground)); themeDescriptions.add(new ThemeDescription(mapTypeButton, ThemeDescription.FLAG_BACKGROUNDFILTER | ThemeDescription.FLAG_DRAWABLESELECTEDSTATE, null, null, null, null, Theme.key_location_actionPressedBackground)); themeDescriptions.add(new ThemeDescription(proximityButton, 0, null, null, null, cellDelegate, Theme.key_location_actionIcon)); themeDescriptions.add(new ThemeDescription(proximityButton, ThemeDescription.FLAG_BACKGROUNDFILTER, null, null, null, null, Theme.key_location_actionBackground)); themeDescriptions.add(new ThemeDescription(proximityButton, ThemeDescription.FLAG_BACKGROUNDFILTER | ThemeDescription.FLAG_DRAWABLESELECTEDSTATE, null, null, null, null, Theme.key_location_actionPressedBackground)); themeDescriptions.add(new ThemeDescription(searchAreaButton, ThemeDescription.FLAG_TEXTCOLOR, null, null, null, null, Theme.key_location_actionActiveIcon)); themeDescriptions.add(new ThemeDescription(searchAreaButton, ThemeDescription.FLAG_BACKGROUNDFILTER, null, null, null, null, Theme.key_location_actionBackground)); themeDescriptions.add(new ThemeDescription(searchAreaButton, ThemeDescription.FLAG_BACKGROUNDFILTER | ThemeDescription.FLAG_DRAWABLESELECTEDSTATE, null, null, null, null, Theme.key_location_actionPressedBackground)); themeDescriptions.add(new ThemeDescription(null, 0, null, null, Theme.avatarDrawables, cellDelegate, Theme.key_avatar_text)); themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, cellDelegate, Theme.key_avatar_backgroundRed)); themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, cellDelegate, Theme.key_avatar_backgroundOrange)); themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, cellDelegate, Theme.key_avatar_backgroundViolet)); themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, cellDelegate, Theme.key_avatar_backgroundGreen)); themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, cellDelegate, Theme.key_avatar_backgroundCyan)); themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, cellDelegate, Theme.key_avatar_backgroundBlue)); themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, cellDelegate, Theme.key_avatar_backgroundPink)); themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, null, Theme.key_location_liveLocationProgress)); themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, null, Theme.key_location_placeLocationBackground)); themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, null, Theme.key_dialog_liveLocationProgress)); themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_USEBACKGROUNDDRAWABLE | ThemeDescription.FLAG_CHECKTAG, new Class[]{SendLocationCell.class}, new String[]{"imageView"}, null, null, null, Theme.key_location_sendLocationIcon)); themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_USEBACKGROUNDDRAWABLE | ThemeDescription.FLAG_CHECKTAG, new Class[]{SendLocationCell.class}, new String[]{"imageView"}, null, null, null, Theme.key_location_sendLiveLocationIcon)); themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_BACKGROUNDFILTER | ThemeDescription.FLAG_USEBACKGROUNDDRAWABLE | ThemeDescription.FLAG_CHECKTAG, new Class[]{SendLocationCell.class}, new String[]{"imageView"}, null, null, null, Theme.key_location_sendLocationBackground)); themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_BACKGROUNDFILTER | ThemeDescription.FLAG_USEBACKGROUNDDRAWABLE | ThemeDescription.FLAG_CHECKTAG, new Class[]{SendLocationCell.class}, new String[]{"imageView"}, null, null, null, Theme.key_location_sendLiveLocationBackground)); themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{SendLocationCell.class}, new String[]{"accurateTextView"}, null, null, null, Theme.key_windowBackgroundWhiteGrayText3)); themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_CHECKTAG, new Class[]{SendLocationCell.class}, new String[]{"titleTextView"}, null, null, null, Theme.key_location_sendLiveLocationText)); themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_CHECKTAG, new Class[]{SendLocationCell.class}, new String[]{"titleTextView"}, null, null, null, Theme.key_location_sendLocationText)); themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{LocationDirectionCell.class}, new String[]{"buttonTextView"}, null, null, null, Theme.key_featuredStickers_buttonText)); themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_USEBACKGROUNDDRAWABLE, new Class[]{LocationDirectionCell.class}, new String[]{"frameLayout"}, null, null, null, Theme.key_featuredStickers_addButton)); themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_USEBACKGROUNDDRAWABLE | ThemeDescription.FLAG_DRAWABLESELECTEDSTATE, new Class[]{LocationDirectionCell.class}, new String[]{"frameLayout"}, null, null, null, Theme.key_featuredStickers_addButtonPressed)); themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_BACKGROUNDFILTER, new Class[]{ShadowSectionCell.class}, null, null, null, Theme.key_windowBackgroundGrayShadow)); themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_BACKGROUNDFILTER | ThemeDescription.FLAG_CELLBACKGROUNDCOLOR, new Class[]{ShadowSectionCell.class}, null, null, null, Theme.key_windowBackgroundGray)); themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{HeaderCell.class}, new String[]{"textView"}, null, null, null, Theme.key_dialogTextBlue2)); themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_BACKGROUNDFILTER, new Class[]{LocationCell.class}, new String[]{"imageView"}, null, null, null, Theme.key_windowBackgroundWhiteGrayText3)); themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{LocationCell.class}, new String[]{"nameTextView"}, null, null, null, Theme.key_windowBackgroundWhiteBlackText)); themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{LocationCell.class}, new String[]{"addressTextView"}, null, null, null, Theme.key_windowBackgroundWhiteGrayText3)); themeDescriptions.add(new ThemeDescription(searchListView, ThemeDescription.FLAG_BACKGROUNDFILTER, new Class[]{LocationCell.class}, new String[]{"imageView"}, null, null, null, Theme.key_windowBackgroundWhiteGrayText3)); themeDescriptions.add(new ThemeDescription(searchListView, 0, new Class[]{LocationCell.class}, new String[]{"nameTextView"}, null, null, null, Theme.key_windowBackgroundWhiteBlackText)); themeDescriptions.add(new ThemeDescription(searchListView, 0, new Class[]{LocationCell.class}, new String[]{"addressTextView"}, null, null, null, Theme.key_windowBackgroundWhiteGrayText3)); themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{SharingLiveLocationCell.class}, new String[]{"nameTextView"}, null, null, null, Theme.key_windowBackgroundWhiteBlackText)); themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{SharingLiveLocationCell.class}, new String[]{"distanceTextView"}, null, null, null, Theme.key_windowBackgroundWhiteGrayText3)); themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{LocationLoadingCell.class}, new String[]{"progressBar"}, null, null, null, Theme.key_progressCircle)); themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{LocationLoadingCell.class}, new String[]{"textView"}, null, null, null, Theme.key_windowBackgroundWhiteGrayText3)); themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{LocationLoadingCell.class}, new String[]{"imageView"}, null, null, null, Theme.key_windowBackgroundWhiteGrayText3)); themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{LocationPoweredCell.class}, new String[]{"textView"}, null, null, null, Theme.key_windowBackgroundWhiteGrayText3)); themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_IMAGECOLOR, new Class[]{LocationPoweredCell.class}, new String[]{"imageView"}, null, null, null, Theme.key_dialogEmptyImage)); themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{LocationPoweredCell.class}, new String[]{"textView2"}, null, null, null, Theme.key_dialogEmptyText)); return themeDescriptions; } public String getAddressName() { return adapter != null ? adapter.getAddressName() : null; } @Override public boolean isLightStatusBar() { return ColorUtils.calculateLuminance(getThemedColor(Theme.key_windowBackgroundWhite)) > 0.7f; } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/ui/LocationActivity.java
44,879
package jadx.gui.ui; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.DisplayMode; import java.awt.Font; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Rectangle; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTarget; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.AffineTransform; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Locale; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JCheckBox; import javax.swing.JCheckBoxMenuItem; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JToggleButton; import javax.swing.JToolBar; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.ToolTipManager; import javax.swing.WindowConstants; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeWillExpandListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.Theme; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.qos.logback.classic.Level; import jadx.api.JadxArgs; import jadx.api.JadxDecompiler; import jadx.api.JavaClass; import jadx.api.JavaNode; import jadx.api.ResourceFile; import jadx.api.plugins.events.IJadxEvents; import jadx.api.plugins.events.JadxEvents; import jadx.api.plugins.events.types.ReloadProject; import jadx.api.plugins.utils.CommonFileUtils; import jadx.core.Jadx; import jadx.core.export.TemplateFile; import jadx.core.plugins.events.JadxEventsImpl; import jadx.core.utils.ListUtils; import jadx.core.utils.StringUtils; import jadx.core.utils.android.AndroidManifestParser; import jadx.core.utils.android.AppAttribute; import jadx.core.utils.android.ApplicationParams; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.core.utils.files.FileUtils; import jadx.gui.JadxWrapper; import jadx.gui.cache.manager.CacheManager; import jadx.gui.device.debugger.BreakpointManager; import jadx.gui.events.services.RenameService; import jadx.gui.jobs.BackgroundExecutor; import jadx.gui.jobs.DecompileTask; import jadx.gui.jobs.ExportTask; import jadx.gui.jobs.TaskStatus; import jadx.gui.logs.LogCollector; import jadx.gui.logs.LogOptions; import jadx.gui.logs.LogPanel; import jadx.gui.plugins.mappings.RenameMappingsGui; import jadx.gui.plugins.quark.QuarkDialog; import jadx.gui.settings.JadxProject; import jadx.gui.settings.JadxSettings; import jadx.gui.settings.ui.JadxSettingsWindow; import jadx.gui.settings.ui.plugins.PluginSettings; import jadx.gui.treemodel.ApkSignature; import jadx.gui.treemodel.JClass; import jadx.gui.treemodel.JLoadableNode; import jadx.gui.treemodel.JNode; import jadx.gui.treemodel.JPackage; import jadx.gui.treemodel.JResource; import jadx.gui.treemodel.JRoot; import jadx.gui.ui.action.ActionModel; import jadx.gui.ui.action.JadxGuiAction; import jadx.gui.ui.codearea.AbstractCodeArea; import jadx.gui.ui.codearea.AbstractCodeContentPanel; import jadx.gui.ui.codearea.EditorTheme; import jadx.gui.ui.codearea.EditorViewState; import jadx.gui.ui.dialog.ADBDialog; import jadx.gui.ui.dialog.AboutDialog; import jadx.gui.ui.dialog.LogViewerDialog; import jadx.gui.ui.dialog.SearchDialog; import jadx.gui.ui.filedialog.FileDialogWrapper; import jadx.gui.ui.filedialog.FileOpenMode; import jadx.gui.ui.menu.HiddenMenuItem; import jadx.gui.ui.menu.JadxMenu; import jadx.gui.ui.menu.JadxMenuBar; import jadx.gui.ui.panel.ContentPanel; import jadx.gui.ui.panel.IssuesPanel; import jadx.gui.ui.panel.JDebuggerPanel; import jadx.gui.ui.panel.ProgressPanel; import jadx.gui.ui.popupmenu.RecentProjectsMenuListener; import jadx.gui.ui.tab.TabbedPane; import jadx.gui.ui.tab.dnd.TabDndController; import jadx.gui.ui.treenodes.StartPageNode; import jadx.gui.ui.treenodes.SummaryNode; import jadx.gui.update.JadxUpdate; import jadx.gui.update.JadxUpdate.IUpdateCallback; import jadx.gui.update.data.Release; import jadx.gui.utils.CacheObject; import jadx.gui.utils.FontUtils; import jadx.gui.utils.ILoadListener; import jadx.gui.utils.LafManager; import jadx.gui.utils.Link; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; import jadx.gui.utils.fileswatcher.LiveReloadWorker; import jadx.gui.utils.shortcut.ShortcutsController; import jadx.gui.utils.ui.ActionHandler; import jadx.gui.utils.ui.NodeLabel; import static io.reactivex.internal.functions.Functions.EMPTY_RUNNABLE; public class MainWindow extends JFrame { private static final Logger LOG = LoggerFactory.getLogger(MainWindow.class); private static final String DEFAULT_TITLE = "jadx-gui"; private static final double BORDER_RATIO = 0.15; private static final double WINDOW_RATIO = 1 - BORDER_RATIO * 2; public static final double SPLIT_PANE_RESIZE_WEIGHT = 0.15; private static final ImageIcon ICON_ADD_FILES = UiUtils.openSvgIcon("ui/addFile"); private static final ImageIcon ICON_RELOAD = UiUtils.openSvgIcon("ui/refresh"); private static final ImageIcon ICON_EXPORT = UiUtils.openSvgIcon("ui/export"); private static final ImageIcon ICON_EXIT = UiUtils.openSvgIcon("ui/exit"); private static final ImageIcon ICON_SYNC = UiUtils.openSvgIcon("ui/pagination"); private static final ImageIcon ICON_FLAT_PKG = UiUtils.openSvgIcon("ui/moduleGroup"); private static final ImageIcon ICON_SEARCH = UiUtils.openSvgIcon("ui/find"); private static final ImageIcon ICON_FIND = UiUtils.openSvgIcon("ui/ejbFinderMethod"); private static final ImageIcon ICON_COMMENT_SEARCH = UiUtils.openSvgIcon("ui/usagesFinder"); private static final ImageIcon ICON_MAIN_ACTIVITY = UiUtils.openSvgIcon("ui/home"); private static final ImageIcon ICON_BACK = UiUtils.openSvgIcon("ui/left"); private static final ImageIcon ICON_FORWARD = UiUtils.openSvgIcon("ui/right"); private static final ImageIcon ICON_QUARK = UiUtils.openSvgIcon("ui/quark"); private static final ImageIcon ICON_PREF = UiUtils.openSvgIcon("ui/settings"); private static final ImageIcon ICON_DEOBF = UiUtils.openSvgIcon("ui/helmChartLock"); private static final ImageIcon ICON_DECOMPILE_ALL = UiUtils.openSvgIcon("ui/runAll"); private static final ImageIcon ICON_LOG = UiUtils.openSvgIcon("ui/logVerbose"); private static final ImageIcon ICON_INFO = UiUtils.openSvgIcon("ui/showInfos"); private static final ImageIcon ICON_DEBUGGER = UiUtils.openSvgIcon("ui/startDebugger"); private final transient JadxWrapper wrapper; private final transient JadxSettings settings; private final transient CacheObject cacheObject; private final transient CacheManager cacheManager; private final transient BackgroundExecutor backgroundExecutor; private transient @NotNull JadxProject project; private transient JadxGuiAction newProjectAction; private transient JadxGuiAction saveProjectAction; private transient JPanel mainPanel; private transient JSplitPane treeSplitPane; private transient JSplitPane rightSplitPane; private transient JSplitPane bottomSplitPane; private JTree tree; private DefaultTreeModel treeModel; private JRoot treeRoot; private TabbedPane tabbedPane; private HeapUsageBar heapUsageBar; private transient boolean treeReloading; private boolean isFlattenPackage; private JToggleButton flatPkgButton; private JCheckBoxMenuItem flatPkgMenuItem; private JToggleButton deobfToggleBtn; private JCheckBoxMenuItem deobfMenuItem; private JCheckBoxMenuItem liveReloadMenuItem; private final LiveReloadWorker liveReloadWorker; private transient Link updateLink; private transient ProgressPanel progressPane; private transient Theme editorTheme; private transient IssuesPanel issuesPanel; private transient @Nullable LogPanel logPanel; private transient @Nullable JDebuggerPanel debuggerPanel; private final List<ILoadListener> loadListeners = new ArrayList<>(); private final List<Consumer<JRoot>> treeUpdateListener = new ArrayList<>(); private boolean loaded; private boolean settingsOpen = false; private ShortcutsController shortcutsController; private JadxMenuBar menuBar; private JMenu pluginsMenu; private final transient RenameMappingsGui renameMappings; public MainWindow(JadxSettings settings) { this.settings = settings; this.cacheObject = new CacheObject(); this.project = new JadxProject(this); this.wrapper = new JadxWrapper(this); this.liveReloadWorker = new LiveReloadWorker(this); this.renameMappings = new RenameMappingsGui(this); this.cacheManager = new CacheManager(settings); this.shortcutsController = new ShortcutsController(settings); resetCache(); FontUtils.registerBundledFonts(); setEditorTheme(settings.getEditorThemePath()); initUI(); this.backgroundExecutor = new BackgroundExecutor(settings, progressPane); initMenuAndToolbar(); UiUtils.setWindowIcons(this); shortcutsController.registerMouseEventListener(this); loadSettings(); update(); checkForUpdate(); } public void init() { pack(); setLocationAndPosition(); treeSplitPane.setDividerLocation(settings.getTreeWidth()); heapUsageBar.setVisible(settings.isShowHeapUsageBar()); setVisible(true); setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { closeWindow(); } }); processCommandLineArgs(); } private void processCommandLineArgs() { if (settings.getFiles().isEmpty()) { tabbedPane.showNode(new StartPageNode()); } else { open(FileUtils.fileNamesToPaths(settings.getFiles()), this::handleSelectClassOption); } } private void handleSelectClassOption() { if (settings.getCmdSelectClass() != null) { JavaNode javaNode = wrapper.searchJavaClassByFullAlias(settings.getCmdSelectClass()); if (javaNode == null) { javaNode = wrapper.searchJavaClassByOrigClassName(settings.getCmdSelectClass()); } if (javaNode == null) { JOptionPane.showMessageDialog(this, NLS.str("msg.cmd_select_class_error", settings.getCmdSelectClass()), NLS.str("error_dialog.title"), JOptionPane.ERROR_MESSAGE); return; } tabbedPane.codeJump(cacheObject.getNodeCache().makeFrom(javaNode)); } } private void checkForUpdate() { if (!settings.isCheckForUpdates()) { return; } JadxUpdate.check(new IUpdateCallback() { @Override public void onUpdate(Release r) { SwingUtilities.invokeLater(() -> { updateLink.setText(NLS.str("menu.update_label", r.getName())); updateLink.setVisible(true); }); } }); } public void openFileDialog() { showOpenDialog(FileOpenMode.OPEN); } public void openProjectDialog() { showOpenDialog(FileOpenMode.OPEN_PROJECT); } private void showOpenDialog(FileOpenMode mode) { saveAll(); if (!ensureProjectIsSaved()) { return; } FileDialogWrapper fileDialog = new FileDialogWrapper(this, mode); List<Path> openPaths = fileDialog.show(); if (!openPaths.isEmpty()) { settings.setLastOpenFilePath(fileDialog.getCurrentDir()); open(openPaths); } } public void addFiles() { FileDialogWrapper fileDialog = new FileDialogWrapper(this, FileOpenMode.ADD); List<Path> addPaths = fileDialog.show(); if (!addPaths.isEmpty()) { addFiles(addPaths); } } public void addFiles(List<Path> addPaths) { project.setFilePaths(ListUtils.distinctMergeSortedLists(addPaths, project.getFilePaths())); reopen(); } private void newProject() { saveAll(); if (!ensureProjectIsSaved()) { return; } closeAll(); updateProject(new JadxProject(this)); } private void saveProject() { if (!project.isSaveFileSelected()) { saveProjectAs(); } else { project.save(); update(); } } private void saveProjectAs() { FileDialogWrapper fileDialog = new FileDialogWrapper(this, FileOpenMode.SAVE_PROJECT); if (project.getFilePaths().size() == 1) { // If there is only one file loaded we suggest saving the jadx project file next to the loaded file Path projectPath = getProjectPathForFile(this.project.getFilePaths().get(0)); fileDialog.setSelectedFile(projectPath); } List<Path> saveFiles = fileDialog.show(); if (saveFiles.isEmpty()) { return; } settings.setLastSaveProjectPath(fileDialog.getCurrentDir()); Path savePath = saveFiles.get(0); if (!savePath.getFileName().toString().toLowerCase(Locale.ROOT).endsWith(JadxProject.PROJECT_EXTENSION)) { savePath = savePath.resolveSibling(savePath.getFileName() + "." + JadxProject.PROJECT_EXTENSION); } if (Files.exists(savePath)) { int res = JOptionPane.showConfirmDialog( this, NLS.str("confirm.save_as_message", savePath.getFileName()), NLS.str("confirm.save_as_title"), JOptionPane.YES_NO_OPTION); if (res == JOptionPane.NO_OPTION) { return; } } project.saveAs(savePath); settings.addRecentProject(savePath); update(); } public void addNewScript() { FileDialogWrapper fileDialog = new FileDialogWrapper(this, FileOpenMode.CUSTOM_SAVE); fileDialog.setTitle(NLS.str("file.save")); Path workingDir = project.getWorkingDir(); Path baseDir = workingDir != null ? workingDir : settings.getLastSaveFilePath(); fileDialog.setSelectedFile(baseDir.resolve("script.jadx.kts")); fileDialog.setFileExtList(Collections.singletonList("jadx.kts")); fileDialog.setSelectionMode(JFileChooser.FILES_ONLY); List<Path> paths = fileDialog.show(); if (paths.size() != 1) { return; } Path scriptFile = paths.get(0); try { TemplateFile tmpl = TemplateFile.fromResources("/files/script.jadx.kts.tmpl"); FileUtils.writeFile(scriptFile, tmpl.build()); } catch (Exception e) { LOG.error("Failed to save new script file: {}", scriptFile, e); } List<Path> inputs = project.getFilePaths(); inputs.add(scriptFile); project.setFilePaths(inputs); project.save(); reopen(); } public void removeInput(Path file) { List<Path> inputs = project.getFilePaths(); inputs.remove(file); project.setFilePaths(inputs); project.save(); reopen(); } public void open(Path path) { open(Collections.singletonList(path), EMPTY_RUNNABLE); } public void open(List<Path> paths) { open(paths, EMPTY_RUNNABLE); } private void open(List<Path> paths, Runnable onFinish) { saveAll(); closeAll(); if (paths.size() == 1 && openSingleFile(paths.get(0), onFinish)) { return; } // start new project project = new JadxProject(this); project.setFilePaths(paths); loadFiles(onFinish); } private boolean openSingleFile(Path singleFile, Runnable onFinish) { if (singleFile.getFileName() == null) { return false; } String fileExtension = CommonFileUtils.getFileExtension(singleFile.getFileName().toString()); if (fileExtension != null && fileExtension.equalsIgnoreCase(JadxProject.PROJECT_EXTENSION)) { openProject(singleFile, onFinish); return true; } // check if project file already saved with default name Path projectPath = getProjectPathForFile(singleFile); if (Files.exists(projectPath)) { openProject(projectPath, onFinish); return true; } return false; } private static Path getProjectPathForFile(Path loadedFile) { String fileName = loadedFile.getFileName() + "." + JadxProject.PROJECT_EXTENSION; return loadedFile.resolveSibling(fileName); } public void reopen() { synchronized (ReloadProject.EVENT) { saveAll(); closeAll(); loadFiles(EMPTY_RUNNABLE); menuBar.reloadShortcuts(); } } private void openProject(Path path, Runnable onFinish) { LOG.debug("Loading project: {}", path); JadxProject jadxProject = JadxProject.load(this, path); if (jadxProject == null) { JOptionPane.showMessageDialog( this, NLS.str("msg.project_error"), NLS.str("msg.project_error_title"), JOptionPane.INFORMATION_MESSAGE); jadxProject = new JadxProject(this); } settings.addRecentProject(path); project = jadxProject; loadFiles(onFinish); } private void loadFiles(Runnable onFinish) { if (project.getFilePaths().isEmpty()) { tabbedPane.showNode(new StartPageNode()); return; } AtomicReference<Exception> wrapperException = new AtomicReference<>(); backgroundExecutor.execute(NLS.str("progress.load"), () -> { try { wrapper.open(); } catch (Exception e) { wrapperException.set(e); } }, status -> { if (wrapperException.get() != null) { closeAll(); Exception e = wrapperException.get(); if (e instanceof RuntimeException) { throw (RuntimeException) e; } else { throw new JadxRuntimeException("Project load error", e); } } if (status == TaskStatus.CANCEL_BY_MEMORY) { showHeapUsageBar(); UiUtils.errorMessage(this, NLS.str("message.memoryLow")); return; } if (status != TaskStatus.COMPLETE) { LOG.warn("Loading task incomplete, status: {}", status); return; } checkLoadedStatus(); onOpen(); onFinish.run(); }); } private void saveAll() { saveOpenTabs(); BreakpointManager.saveAndExit(); } private void closeAll() { notifyLoadListeners(false); cancelBackgroundJobs(); clearTree(); resetCache(); LogCollector.getInstance().reset(); wrapper.close(); tabbedPane.closeAllTabs(); UiUtils.resetClipboardOwner(); System.gc(); update(); } private void checkLoadedStatus() { if (!wrapper.getClasses().isEmpty()) { return; } int errors = issuesPanel.getErrorsCount(); if (errors > 0) { int result = JOptionPane.showConfirmDialog(this, NLS.str("message.load_errors", errors), NLS.str("message.errorTitle"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE); if (result == JOptionPane.OK_OPTION) { showLogViewer(LogOptions.allWithLevel(Level.ERROR)); } } else { UiUtils.showMessageBox(this, NLS.str("message.no_classes")); } } private void onOpen() { initTree(); updateLiveReload(project.isEnableLiveReload()); BreakpointManager.init(project.getFilePaths().get(0).toAbsolutePath().getParent()); initEvents(); List<EditorViewState> openTabs = project.getOpenTabs(this); backgroundExecutor.execute(NLS.str("progress.load"), () -> preLoadOpenTabs(openTabs), status -> { restoreOpenTabs(openTabs); runInitialBackgroundJobs(); notifyLoadListeners(true); update(); }); } public void passesReloaded() { initEvents(); // TODO: events reset on reload passes on script run tabbedPane.reloadInactiveTabs(); reloadTree(); } private void initEvents() { events().addListener(JadxEvents.RELOAD_PROJECT, ev -> UiUtils.uiRun(this::reopen)); RenameService.init(this); } public void updateLiveReload(boolean state) { if (liveReloadWorker.isStarted() == state) { return; } project.setEnableLiveReload(state); liveReloadMenuItem.setEnabled(false); backgroundExecutor.execute( (state ? "Starting" : "Stopping") + " live reload", () -> liveReloadWorker.updateState(state), s -> { liveReloadMenuItem.setState(state); liveReloadMenuItem.setEnabled(true); }); } private void addTreeCustomNodes() { treeRoot.replaceCustomNode(ApkSignature.getApkSignature(wrapper)); treeRoot.replaceCustomNode(new SummaryNode(this)); } private boolean ensureProjectIsSaved() { if (!project.isSaved() && !project.isInitial()) { // Check if we saved settings that indicate what to do if (settings.getSaveOption() == JadxSettings.SAVEOPTION.NEVER) { return true; } if (settings.getSaveOption() == JadxSettings.SAVEOPTION.ALWAYS) { saveProject(); return true; } JCheckBox remember = new JCheckBox(NLS.str("confirm.remember")); JLabel message = new JLabel(NLS.str("confirm.not_saved_message")); JPanel inner = new JPanel(new BorderLayout()); inner.add(remember, BorderLayout.SOUTH); inner.add(message, BorderLayout.NORTH); int res = JOptionPane.showConfirmDialog( this, inner, NLS.str("confirm.not_saved_title"), JOptionPane.YES_NO_CANCEL_OPTION); if (res == JOptionPane.CANCEL_OPTION) { return false; } if (res == JOptionPane.YES_OPTION) { if (remember.isSelected()) { settings.setSaveOption(JadxSettings.SAVEOPTION.ALWAYS); settings.sync(); } saveProject(); } else if (res == JOptionPane.NO_OPTION) { if (remember.isSelected()) { settings.setSaveOption(JadxSettings.SAVEOPTION.NEVER); settings.sync(); } } } return true; } public void updateProject(@NotNull JadxProject jadxProject) { this.project = jadxProject; UiUtils.uiRun(this::update); } public void update() { UiUtils.uiThreadGuard(); newProjectAction.setEnabled(!project.isInitial()); saveProjectAction.setEnabled(loaded && !project.isSaved()); deobfToggleBtn.setSelected(settings.isDeobfuscationOn()); renameMappings.onUpdate(loaded); Path projectPath = project.getProjectPath(); String pathString; if (projectPath == null) { pathString = ""; } else { pathString = " [" + projectPath.toAbsolutePath().getParent() + ']'; } setTitle((project.isSaved() ? "" : '*') + project.getName() + pathString + " - " + DEFAULT_TITLE); } protected void resetCache() { cacheObject.reset(); } synchronized void runInitialBackgroundJobs() { if (settings.isAutoStartJobs()) { new Timer().schedule(new TimerTask() { @Override public void run() { requestFullDecompilation(); } }, 1000); } } public void requestFullDecompilation() { if (cacheObject.isFullDecompilationFinished()) { return; } backgroundExecutor.execute(new DecompileTask(this)); } public void resetCodeCache() { backgroundExecutor.execute( NLS.str("preferences.cache.task.delete"), () -> { try { getWrapper().getCurrentDecompiler().ifPresent(jadx -> { try { jadx.getArgs().getCodeCache().close(); } catch (Exception e) { LOG.error("Failed to close code cache", e); } }); Path cacheDir = project.getCacheDir(); project.resetCacheDir(); FileUtils.deleteDirIfExists(cacheDir); } catch (Exception e) { LOG.error("Error during code cache reset", e); } }, status -> events().send(ReloadProject.EVENT)); } public void cancelBackgroundJobs() { backgroundExecutor.cancelAll(); } private void saveAll(boolean export) { FileDialogWrapper fileDialog = new FileDialogWrapper(this, FileOpenMode.EXPORT); List<Path> saveDirs = fileDialog.show(); if (saveDirs.isEmpty()) { return; } JadxArgs decompilerArgs = wrapper.getArgs(); decompilerArgs.setExportAsGradleProject(export); if (export) { decompilerArgs.setSkipSources(false); decompilerArgs.setSkipResources(false); } else { decompilerArgs.setSkipSources(settings.isSkipSources()); decompilerArgs.setSkipResources(settings.isSkipResources()); } settings.setLastSaveFilePath(fileDialog.getCurrentDir()); backgroundExecutor.execute(new ExportTask(this, wrapper, saveDirs.get(0).toFile())); } public void initTree() { treeRoot = new JRoot(wrapper); treeRoot.setFlatPackages(isFlattenPackage); treeModel.setRoot(treeRoot); addTreeCustomNodes(); treeRoot.update(); reloadTree(); } private void clearTree() { tabbedPane.reset(); treeRoot = null; treeModel.setRoot(null); treeModel.reload(); } public void reloadTree() { treeReloading = true; treeUpdateListener.forEach(listener -> listener.accept(treeRoot)); treeModel.reload(); List<String[]> treeExpansions = project.getTreeExpansions(); if (!treeExpansions.isEmpty()) { expand(treeRoot, treeExpansions); } else { tree.expandRow(1); } treeReloading = false; } public void rebuildPackagesTree() { cacheObject.setPackageHelper(null); treeRoot.update(); } private void expand(TreeNode node, List<String[]> treeExpansions) { TreeNode[] pathNodes = treeModel.getPathToRoot(node); if (pathNodes == null) { return; } TreePath path = new TreePath(pathNodes); for (String[] expansion : treeExpansions) { if (Arrays.equals(expansion, getPathExpansion(path))) { tree.expandPath(path); break; } } for (int i = node.getChildCount() - 1; i >= 0; i--) { expand(node.getChildAt(i), treeExpansions); } } private void toggleFlattenPackage() { setFlattenPackage(!isFlattenPackage); } private void setFlattenPackage(boolean value) { isFlattenPackage = value; settings.setFlattenPackage(isFlattenPackage); flatPkgButton.setSelected(isFlattenPackage); flatPkgMenuItem.setState(isFlattenPackage); Object root = treeModel.getRoot(); if (root instanceof JRoot) { JRoot treeRoot = (JRoot) root; treeRoot.setFlatPackages(isFlattenPackage); reloadTree(); } } private void toggleDeobfuscation() { boolean deobfOn = !settings.isDeobfuscationOn(); settings.setDeobfuscationOn(deobfOn); settings.sync(); deobfToggleBtn.setSelected(deobfOn); deobfMenuItem.setState(deobfOn); reopen(); } private boolean nodeClickAction(@Nullable Object obj) { if (obj == null) { return false; } try { if (obj instanceof JResource) { JResource res = (JResource) obj; ResourceFile resFile = res.getResFile(); if (resFile != null && JResource.isSupportedForView(resFile.getType())) { return tabbedPane.showNode(res); } } else if (obj instanceof JNode) { JNode node = (JNode) obj; if (node.getRootClass() != null) { tabbedPane.codeJump(node); return true; } return tabbedPane.showNode(node); } } catch (Exception e) { LOG.error("Content loading error", e); } return false; } private void treeRightClickAction(MouseEvent e) { JNode node = getJNodeUnderMouse(e); if (node == null) { return; } JPopupMenu menu = node.onTreePopupMenu(this); if (menu != null) { menu.show(e.getComponent(), e.getX(), e.getY()); } } @Nullable private JNode getJNodeUnderMouse(MouseEvent mouseEvent) { TreePath path = tree.getClosestPathForLocation(mouseEvent.getX(), mouseEvent.getY()); if (path == null) { return null; } // allow 'closest' path only at the right of the item row Rectangle pathBounds = tree.getPathBounds(path); if (pathBounds != null) { int y = mouseEvent.getY(); if (y < pathBounds.y || y > (pathBounds.y + pathBounds.height)) { return null; } if (mouseEvent.getX() < pathBounds.x) { // exclude expand/collapse events return null; } } Object obj = path.getLastPathComponent(); if (obj instanceof JNode) { tree.setSelectionPath(path); return (JNode) obj; } return null; } public void syncWithEditor() { ContentPanel selectedContentPanel = tabbedPane.getSelectedContentPanel(); if (selectedContentPanel == null) { return; } JNode node = selectedContentPanel.getNode(); if (node.getParent() == null && treeRoot != null) { // node not register in tree node = treeRoot.searchNode(node); if (node == null) { LOG.error("Class not found in tree"); return; } } TreeNode[] pathNodes = treeModel.getPathToRoot(node); if (pathNodes == null) { return; } TreePath path = new TreePath(pathNodes); tree.setSelectionPath(path); tree.makeVisible(path); tree.scrollPathToVisible(path); tree.requestFocus(); } public void textSearch() { ContentPanel panel = tabbedPane.getSelectedContentPanel(); if (panel instanceof AbstractCodeContentPanel) { AbstractCodeArea codeArea = ((AbstractCodeContentPanel) panel).getCodeArea(); String preferText = codeArea.getSelectedText(); if (StringUtils.isEmpty(preferText)) { preferText = codeArea.getWordUnderCaret(); } if (!StringUtils.isEmpty(preferText)) { SearchDialog.searchText(MainWindow.this, preferText); return; } } SearchDialog.search(MainWindow.this, SearchDialog.SearchPreset.TEXT); } public void gotoMainActivity() { AndroidManifestParser parser = new AndroidManifestParser( AndroidManifestParser.getAndroidManifest(getWrapper().getResources()), EnumSet.of(AppAttribute.MAIN_ACTIVITY)); if (!parser.isManifestFound()) { JOptionPane.showMessageDialog(MainWindow.this, NLS.str("error_dialog.not_found", "AndroidManifest.xml"), NLS.str("error_dialog.title"), JOptionPane.ERROR_MESSAGE); return; } try { ApplicationParams results = parser.parse(); if (results.getMainActivityName() == null) { throw new JadxRuntimeException("Failed to get main activity name from manifest"); } JavaClass mainActivityClass = results.getMainActivity(getWrapper().getDecompiler()); if (mainActivityClass == null) { throw new JadxRuntimeException("Failed to find main activity class: " + results.getMainActivityName()); } tabbedPane.codeJump(getCacheObject().getNodeCache().makeFrom(mainActivityClass)); } catch (Exception e) { LOG.error("Main activity not found", e); JOptionPane.showMessageDialog(MainWindow.this, NLS.str("error_dialog.not_found", "Main Activity"), NLS.str("error_dialog.title"), JOptionPane.ERROR_MESSAGE); } } private void initMenuAndToolbar() { JadxGuiAction openAction = new JadxGuiAction(ActionModel.OPEN, this::openFileDialog); JadxGuiAction openProject = new JadxGuiAction(ActionModel.OPEN_PROJECT, this::openProjectDialog); JadxGuiAction addFilesAction = new JadxGuiAction(ActionModel.ADD_FILES, () -> addFiles()); newProjectAction = new JadxGuiAction(ActionModel.NEW_PROJECT, this::newProject); saveProjectAction = new JadxGuiAction(ActionModel.SAVE_PROJECT, this::saveProject); JadxGuiAction saveProjectAsAction = new JadxGuiAction(ActionModel.SAVE_PROJECT_AS, this::saveProjectAs); JadxGuiAction reloadAction = new JadxGuiAction(ActionModel.RELOAD, () -> UiUtils.uiRun(this::reopen)); JadxGuiAction liveReloadAction = new JadxGuiAction(ActionModel.LIVE_RELOAD, () -> updateLiveReload(!project.isEnableLiveReload())); liveReloadMenuItem = new JCheckBoxMenuItem(liveReloadAction); liveReloadMenuItem.setState(project.isEnableLiveReload()); JadxGuiAction saveAllAction = new JadxGuiAction(ActionModel.SAVE_ALL, () -> saveAll(false)); JadxGuiAction exportAction = new JadxGuiAction(ActionModel.EXPORT, () -> saveAll(true)); JMenu recentProjects = new JadxMenu(NLS.str("menu.recent_projects"), shortcutsController); recentProjects.addMenuListener(new RecentProjectsMenuListener(this, recentProjects)); JadxGuiAction prefsAction = new JadxGuiAction(ActionModel.PREFS, this::openSettings); JadxGuiAction exitAction = new JadxGuiAction(ActionModel.EXIT, this::closeWindow); isFlattenPackage = settings.isFlattenPackage(); flatPkgMenuItem = new JCheckBoxMenuItem(NLS.str("menu.flatten"), ICON_FLAT_PKG); flatPkgMenuItem.setState(isFlattenPackage); JCheckBoxMenuItem heapUsageBarMenuItem = new JCheckBoxMenuItem(NLS.str("menu.heapUsageBar")); heapUsageBarMenuItem.setState(settings.isShowHeapUsageBar()); heapUsageBarMenuItem.addActionListener(event -> { settings.setShowHeapUsageBar(!settings.isShowHeapUsageBar()); heapUsageBar.setVisible(settings.isShowHeapUsageBar()); }); JCheckBoxMenuItem alwaysSelectOpened = new JCheckBoxMenuItem(NLS.str("menu.alwaysSelectOpened")); alwaysSelectOpened.setState(settings.isAlwaysSelectOpened()); alwaysSelectOpened.addActionListener(event -> { settings.setAlwaysSelectOpened(!settings.isAlwaysSelectOpened()); if (settings.isAlwaysSelectOpened()) { this.syncWithEditor(); } }); JCheckBoxMenuItem dockLog = new JCheckBoxMenuItem(NLS.str("menu.dock_log")); dockLog.setState(settings.isDockLogViewer()); dockLog.addActionListener(event -> settings.setDockLogViewer(!settings.isDockLogViewer())); JadxGuiAction syncAction = new JadxGuiAction(ActionModel.SYNC, this::syncWithEditor); JadxGuiAction textSearchAction = new JadxGuiAction(ActionModel.TEXT_SEARCH, this::textSearch); JadxGuiAction clsSearchAction = new JadxGuiAction(ActionModel.CLASS_SEARCH, () -> SearchDialog.search(MainWindow.this, SearchDialog.SearchPreset.CLASS)); JadxGuiAction commentSearchAction = new JadxGuiAction(ActionModel.COMMENT_SEARCH, () -> SearchDialog.search(MainWindow.this, SearchDialog.SearchPreset.COMMENT)); JadxGuiAction gotoMainActivityAction = new JadxGuiAction(ActionModel.GOTO_MAIN_ACTIVITY, this::gotoMainActivity); JadxGuiAction decompileAllAction = new JadxGuiAction(ActionModel.DECOMPILE_ALL, this::requestFullDecompilation); JadxGuiAction resetCacheAction = new JadxGuiAction(ActionModel.RESET_CACHE, this::resetCodeCache); JadxGuiAction deobfAction = new JadxGuiAction(ActionModel.DEOBF, this::toggleDeobfuscation); deobfToggleBtn = new JToggleButton(deobfAction); deobfToggleBtn.setSelected(settings.isDeobfuscationOn()); deobfToggleBtn.setText(""); deobfMenuItem = new JCheckBoxMenuItem(deobfAction); deobfMenuItem.setState(settings.isDeobfuscationOn()); JadxGuiAction showLogAction = new JadxGuiAction(ActionModel.SHOW_LOG, () -> showLogViewer(LogOptions.current())); JadxGuiAction aboutAction = new JadxGuiAction(ActionModel.ABOUT, () -> new AboutDialog().setVisible(true)); JadxGuiAction backAction = new JadxGuiAction(ActionModel.BACK, tabbedPane::navBack); JadxGuiAction backVariantAction = new JadxGuiAction(ActionModel.BACK_V, tabbedPane::navBack); JadxGuiAction forwardAction = new JadxGuiAction(ActionModel.FORWARD, tabbedPane::navForward); JadxGuiAction forwardVariantAction = new JadxGuiAction(ActionModel.FORWARD_V, tabbedPane::navForward); JadxGuiAction quarkAction = new JadxGuiAction(ActionModel.QUARK, () -> new QuarkDialog(MainWindow.this).setVisible(true)); JadxGuiAction openDeviceAction = new JadxGuiAction(ActionModel.OPEN_DEVICE, () -> new ADBDialog(MainWindow.this).setVisible(true)); JMenu file = new JadxMenu(NLS.str("menu.file"), shortcutsController); file.setMnemonic(KeyEvent.VK_F); file.add(openAction); file.add(openProject); file.add(addFilesAction); file.addSeparator(); file.add(newProjectAction); file.add(saveProjectAction); file.add(saveProjectAsAction); file.addSeparator(); file.add(reloadAction); file.add(liveReloadMenuItem); renameMappings.addMenuActions(file); file.addSeparator(); file.add(saveAllAction); file.add(exportAction); file.addSeparator(); file.add(recentProjects); file.addSeparator(); file.add(prefsAction); file.addSeparator(); file.add(exitAction); JMenu view = new JadxMenu(NLS.str("menu.view"), shortcutsController); view.setMnemonic(KeyEvent.VK_V); view.add(flatPkgMenuItem); view.add(syncAction); view.add(heapUsageBarMenuItem); view.add(alwaysSelectOpened); view.add(dockLog); JMenu nav = new JadxMenu(NLS.str("menu.navigation"), shortcutsController); nav.setMnemonic(KeyEvent.VK_N); nav.add(textSearchAction); nav.add(clsSearchAction); nav.add(commentSearchAction); nav.add(gotoMainActivityAction); nav.addSeparator(); nav.add(backAction); nav.add(forwardAction); pluginsMenu = new JadxMenu(NLS.str("menu.plugins"), shortcutsController); pluginsMenu.setMnemonic(KeyEvent.VK_P); resetPluginsMenu(); JMenu tools = new JadxMenu(NLS.str("menu.tools"), shortcutsController); tools.setMnemonic(KeyEvent.VK_T); tools.add(decompileAllAction); tools.add(resetCacheAction); tools.add(deobfMenuItem); tools.add(quarkAction); tools.add(openDeviceAction); JMenu help = new JadxMenu(NLS.str("menu.help"), shortcutsController); help.setMnemonic(KeyEvent.VK_H); help.add(showLogAction); if (Jadx.isDevVersion()) { help.add(new AbstractAction("Show sample error report") { @Override public void actionPerformed(ActionEvent e) { ExceptionDialog.throwTestException(); } }); } help.add(aboutAction); menuBar = new JadxMenuBar(); menuBar.add(file); menuBar.add(view); menuBar.add(nav); menuBar.add(tools); menuBar.add(pluginsMenu); menuBar.add(help); setJMenuBar(menuBar); flatPkgButton = new JToggleButton(ICON_FLAT_PKG); flatPkgButton.setSelected(isFlattenPackage); ActionListener flatPkgAction = e -> toggleFlattenPackage(); flatPkgMenuItem.addActionListener(flatPkgAction); flatPkgButton.addActionListener(flatPkgAction); flatPkgButton.setToolTipText(NLS.str("menu.flatten")); updateLink = new Link("", JadxUpdate.JADX_RELEASES_URL); updateLink.setVisible(false); JToolBar toolbar = new JToolBar(); toolbar.setFloatable(false); toolbar.add(openAction); toolbar.add(addFilesAction); toolbar.addSeparator(); toolbar.add(reloadAction); toolbar.addSeparator(); toolbar.add(saveAllAction); toolbar.add(exportAction); toolbar.addSeparator(); toolbar.add(syncAction); toolbar.add(flatPkgButton); toolbar.addSeparator(); toolbar.add(textSearchAction); toolbar.add(clsSearchAction); toolbar.add(commentSearchAction); toolbar.add(gotoMainActivityAction); toolbar.addSeparator(); toolbar.add(backAction); toolbar.add(forwardAction); toolbar.addSeparator(); toolbar.add(deobfToggleBtn); toolbar.add(quarkAction); toolbar.add(openDeviceAction); toolbar.addSeparator(); toolbar.add(showLogAction); toolbar.addSeparator(); toolbar.add(prefsAction); toolbar.addSeparator(); toolbar.add(Box.createHorizontalGlue()); toolbar.add(updateLink); mainPanel.add(toolbar, BorderLayout.NORTH); nav.add(new HiddenMenuItem(backVariantAction)); nav.add(new HiddenMenuItem(forwardVariantAction)); shortcutsController.bind(backVariantAction); shortcutsController.bind(forwardVariantAction); addLoadListener(loaded -> { textSearchAction.setEnabled(loaded); clsSearchAction.setEnabled(loaded); commentSearchAction.setEnabled(loaded); gotoMainActivityAction.setEnabled(loaded); backAction.setEnabled(loaded); backVariantAction.setEnabled(loaded); forwardAction.setEnabled(loaded); forwardVariantAction.setEnabled(loaded); syncAction.setEnabled(loaded); saveAllAction.setEnabled(loaded); exportAction.setEnabled(loaded); saveProjectAsAction.setEnabled(loaded); reloadAction.setEnabled(loaded); decompileAllAction.setEnabled(loaded); deobfAction.setEnabled(loaded); quarkAction.setEnabled(loaded); resetCacheAction.setEnabled(loaded); return false; }); } private void initUI() { setMinimumSize(new Dimension(200, 150)); mainPanel = new JPanel(new BorderLayout()); treeSplitPane = new JSplitPane(); treeSplitPane.setResizeWeight(SPLIT_PANE_RESIZE_WEIGHT); mainPanel.add(treeSplitPane); DefaultMutableTreeNode treeRootNode = new DefaultMutableTreeNode(NLS.str("msg.open_file")); treeModel = new DefaultTreeModel(treeRootNode); tree = new JTree(treeModel); ToolTipManager.sharedInstance().registerComponent(tree); tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); tree.setFocusable(false); tree.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { tree.setFocusable(false); } }); tree.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e)) { if (!nodeClickAction(getJNodeUnderMouse(e))) { // click ignored -> switch to focusable mode tree.setFocusable(true); tree.requestFocus(); } } else if (SwingUtilities.isRightMouseButton(e)) { treeRightClickAction(e); } } }); tree.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { nodeClickAction(tree.getLastSelectedPathComponent()); } } }); tree.setCellRenderer(new DefaultTreeCellRenderer() { @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean isLeaf, int row, boolean focused) { Component c = super.getTreeCellRendererComponent(tree, value, selected, expanded, isLeaf, row, focused); if (value instanceof JNode) { JNode jNode = (JNode) value; NodeLabel.disableHtml(this, jNode.disableHtml()); setText(jNode.makeStringHtml()); setIcon(jNode.getIcon()); setToolTipText(jNode.getTooltip()); } else { setToolTipText(null); } if (value instanceof JPackage) { setEnabled(((JPackage) value).isEnabled()); } return c; } }); tree.addTreeWillExpandListener(new TreeWillExpandListener() { @Override public void treeWillExpand(TreeExpansionEvent event) { TreePath path = event.getPath(); Object node = path.getLastPathComponent(); if (node instanceof JLoadableNode) { ((JLoadableNode) node).loadNode(); } if (!treeReloading) { project.addTreeExpansion(getPathExpansion(event.getPath())); update(); } } @Override public void treeWillCollapse(TreeExpansionEvent event) { if (!treeReloading) { project.removeTreeExpansion(getPathExpansion(event.getPath())); update(); } } }); progressPane = new ProgressPanel(this, true); issuesPanel = new IssuesPanel(this); JPanel leftPane = new JPanel(new BorderLayout()); JScrollPane treeScrollPane = new JScrollPane(tree); treeScrollPane.setMinimumSize(new Dimension(100, 150)); JPanel bottomPane = new JPanel(new BorderLayout()); bottomPane.add(issuesPanel, BorderLayout.PAGE_START); bottomPane.add(progressPane, BorderLayout.PAGE_END); leftPane.add(treeScrollPane, BorderLayout.CENTER); leftPane.add(bottomPane, BorderLayout.PAGE_END); treeSplitPane.setLeftComponent(leftPane); tabbedPane = new TabbedPane(this); tabbedPane.setMinimumSize(new Dimension(150, 150)); new TabDndController(tabbedPane, settings); rightSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT); rightSplitPane.setTopComponent(tabbedPane); rightSplitPane.setResizeWeight(SPLIT_PANE_RESIZE_WEIGHT); treeSplitPane.setRightComponent(rightSplitPane); new DropTarget(this, DnDConstants.ACTION_COPY, new MainDropTarget(this)); heapUsageBar = new HeapUsageBar(); mainPanel.add(heapUsageBar, BorderLayout.SOUTH); bottomSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT); bottomSplitPane.setTopComponent(treeSplitPane); bottomSplitPane.setResizeWeight(SPLIT_PANE_RESIZE_WEIGHT); mainPanel.add(bottomSplitPane, BorderLayout.CENTER); setContentPane(mainPanel); setTitle(DEFAULT_TITLE); } private static String[] getPathExpansion(TreePath path) { List<String> pathList = new ArrayList<>(); while (path != null) { Object node = path.getLastPathComponent(); String name; if (node instanceof JClass) { name = ((JClass) node).getCls().getClassNode().getClassInfo().getFullName(); } else { name = node.toString(); } pathList.add(name); path = path.getParentPath(); } return pathList.toArray(new String[0]); } public static void getExpandedPaths(JTree tree, TreePath path, List<TreePath> list) { if (tree.isExpanded(path)) { list.add(path); TreeNode node = (TreeNode) path.getLastPathComponent(); for (int i = node.getChildCount() - 1; i >= 0; i--) { TreeNode n = node.getChildAt(i); TreePath child = path.pathByAddingChild(n); getExpandedPaths(tree, child, list); } } } public void setLocationAndPosition() { if (settings.loadWindowPos(this)) { return; } GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); DisplayMode mode = gd.getDisplayMode(); AffineTransform trans = gd.getDefaultConfiguration().getDefaultTransform(); int w = (int) (mode.getWidth() / trans.getScaleX()); int h = (int) (mode.getHeight() / trans.getScaleY()); setBounds((int) (w * BORDER_RATIO), (int) (h * BORDER_RATIO), (int) (w * WINDOW_RATIO), (int) (h * WINDOW_RATIO)); setLocationRelativeTo(null); } private void setEditorTheme(String editorThemePath) { try { URL themeUrl = getClass().getResource(editorThemePath); if (themeUrl != null) { try (InputStream is = themeUrl.openStream()) { editorTheme = Theme.load(is); return; } } Path themePath = Paths.get(editorThemePath); if (Files.isRegularFile(themePath)) { try (InputStream is = Files.newInputStream(themePath)) { editorTheme = Theme.load(is); return; } } } catch (Exception e) { LOG.error("Failed to load editor theme: {}", editorThemePath, e); } LOG.warn("Falling back to default editor theme: {}", editorThemePath); editorThemePath = EditorTheme.getDefaultTheme().getPath(); try (InputStream is = getClass().getResourceAsStream(editorThemePath)) { editorTheme = Theme.load(is); return; } catch (Exception e) { LOG.error("Failed to load default editor theme: {}", editorThemePath, e); editorTheme = new Theme(new RSyntaxTextArea()); } } public Theme getEditorTheme() { return editorTheme; } private void openSettings() { settingsOpen = true; JDialog settingsWindow = new JadxSettingsWindow(MainWindow.this, settings); settingsWindow.setVisible(true); settingsWindow.addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent e) { settingsOpen = false; } }); } public boolean isSettingsOpen() { return settingsOpen; } public void loadSettings() { // queue update to not interrupt current UI tasks UiUtils.uiRun(this::updateUiSettings); } private void updateUiSettings() { LafManager.updateLaf(settings); Font font = settings.getFont(); Font largerFont = font.deriveFont(font.getSize() + 2.f); setFont(largerFont); setEditorTheme(settings.getEditorThemePath()); tree.setFont(largerFont); tree.setRowHeight(-1); tabbedPane.loadSettings(); if (logPanel != null) { logPanel.loadSettings(); } shortcutsController.loadSettings(); } private void closeWindow() { saveAll(); if (!ensureProjectIsSaved()) { return; } settings.setTreeWidth(treeSplitPane.getDividerLocation()); settings.saveWindowPos(this); settings.setMainWindowExtendedState(getExtendedState()); if (debuggerPanel != null) { saveSplittersInfo(); } heapUsageBar.reset(); closeAll(); FileUtils.deleteTempRootDir(); dispose(); System.exit(0); } private void saveOpenTabs() { project.saveOpenTabs(tabbedPane.getEditorViewStates()); } private void restoreOpenTabs(List<EditorViewState> openTabs) { UiUtils.uiThreadGuard(); if (openTabs.isEmpty()) { return; } for (EditorViewState viewState : openTabs) { tabbedPane.restoreEditorViewState(viewState); } } private void preLoadOpenTabs(List<EditorViewState> openTabs) { UiUtils.notUiThreadGuard(); for (EditorViewState tabState : openTabs) { JNode node = tabState.getNode(); try { node.getCodeInfo(); } catch (Exception e) { LOG.warn("Failed to preload code for node: {}", node, e); } } } private void saveSplittersInfo() { settings.setMainWindowVerticalSplitterLoc(bottomSplitPane.getDividerLocation()); if (debuggerPanel != null) { settings.setDebuggerStackFrameSplitterLoc(debuggerPanel.getLeftSplitterLocation()); settings.setDebuggerVarTreeSplitterLoc(debuggerPanel.getRightSplitterLocation()); } } public void addLoadListener(ILoadListener loadListener) { this.loadListeners.add(loadListener); // set initial value loadListener.update(loaded); } public void notifyLoadListeners(boolean loaded) { this.loaded = loaded; loadListeners.removeIf(listener -> listener.update(loaded)); } public void addTreeUpdateListener(Consumer<JRoot> listener) { treeUpdateListener.add(listener); } public JadxWrapper getWrapper() { return wrapper; } public JadxProject getProject() { return project; } public TabbedPane getTabbedPane() { return tabbedPane; } public JadxSettings getSettings() { return settings; } public CacheObject getCacheObject() { return cacheObject; } public BackgroundExecutor getBackgroundExecutor() { return backgroundExecutor; } public JRoot getTreeRoot() { return treeRoot; } public JDebuggerPanel getDebuggerPanel() { initDebuggerPanel(); return debuggerPanel; } public ShortcutsController getShortcutsController() { return shortcutsController; } public void showDebuggerPanel() { initDebuggerPanel(); } public void destroyDebuggerPanel() { saveSplittersInfo(); if (debuggerPanel != null) { debuggerPanel.setVisible(false); debuggerPanel = null; } } public void showHeapUsageBar() { settings.setShowHeapUsageBar(true); heapUsageBar.setVisible(true); } private void initDebuggerPanel() { if (debuggerPanel == null) { debuggerPanel = new JDebuggerPanel(this); debuggerPanel.loadSettings(); bottomSplitPane.setBottomComponent(debuggerPanel); int loc = settings.getMainWindowVerticalSplitterLoc(); if (loc == 0) { loc = 300; } bottomSplitPane.setDividerLocation(loc); } } public void showLogViewer(LogOptions logOptions) { UiUtils.uiRun(() -> { if (settings.isDockLogViewer()) { showDockedLog(logOptions); } else { LogViewerDialog.open(this, logOptions); } }); } private void showDockedLog(LogOptions logOptions) { if (logPanel != null) { logPanel.applyLogOptions(logOptions); return; } Runnable undock = () -> { hideDockedLog(); settings.setDockLogViewer(false); LogViewerDialog.open(this, logOptions); }; logPanel = new LogPanel(this, logOptions, undock, this::hideDockedLog); rightSplitPane.setBottomComponent(logPanel); } private void hideDockedLog() { if (logPanel == null) { return; } logPanel.dispose(); logPanel = null; rightSplitPane.setBottomComponent(null); } public JMenu getPluginsMenu() { return pluginsMenu; } public void resetPluginsMenu() { pluginsMenu.removeAll(); pluginsMenu.add(new ActionHandler(() -> new PluginSettings(this, settings).addPlugin()) .withNameAndDesc(NLS.str("preferences.plugins.install"))); } public void addToPluginsMenu(Action item) { if (pluginsMenu.getMenuComponentCount() == 1) { pluginsMenu.addSeparator(); } pluginsMenu.add(item); } public RenameMappingsGui getRenameMappings() { return renameMappings; } public CacheManager getCacheManager() { return cacheManager; } /** * Events instance if decompiler not yet available */ private final IJadxEvents fallbackEvents = new JadxEventsImpl(); public IJadxEvents events() { return wrapper.getCurrentDecompiler() .map(JadxDecompiler::events) .orElse(fallbackEvents); } }
skylot/jadx
jadx-gui/src/main/java/jadx/gui/ui/MainWindow.java
44,880
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium.os; import static java.util.concurrent.TimeUnit.MILLISECONDS; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UncheckedIOException; import java.nio.charset.Charset; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import org.openqa.selenium.internal.Require; import org.openqa.selenium.io.CircularOutputStream; import org.openqa.selenium.io.MultiOutputStream; public class ExternalProcess { private static final Logger LOG = Logger.getLogger(ExternalProcess.class.getName()); public static class Builder { private ProcessBuilder builder; private OutputStream copyOutputTo; private int bufferSize = 32768; Builder() { this.builder = new ProcessBuilder(); } /** * Set the executable command to start the process, this consists of the executable and the * arguments. * * @param executable the executable to build the command * @param arguments the arguments to build the command * @return this instance to continue building */ public Builder command(String executable, List<String> arguments) { List<String> command = new ArrayList<>(arguments.size() + 1); command.add(executable); command.addAll(arguments); builder.command(command); return this; } /** * Set the executable command to start the process, this consists of the executable and the * arguments. * * @param command the executable, followed by the arguments * @return this instance to continue building */ public Builder command(List<String> command) { builder.command(command); return this; } /** * Set the executable command to start the process, this consists of the executable and the * arguments. * * @param command the executable, followed by the arguments * @return this instance to continue building */ public Builder command(String... command) { builder.command(command); return this; } /** * Get the executable command to start the process, this consists of the binary and the * arguments. * * @return an editable list, changes to it will update the command executed. */ public List<String> command() { return Collections.unmodifiableList(builder.command()); } /** * Set one environment variable of the process to start, will replace the old value if exists. * * @return this instance to continue building */ public Builder environment(String name, String value) { Require.argument("name", name).nonNull(); Require.argument("value", value).nonNull(); builder.environment().put(name, value); return this; } /** * Get the environment variables of the process to start. * * @return an editable map, changes to it will update the environment variables of the command * executed. */ public Map<String, String> environment() { return builder.environment(); } /** * Get the working directory of the process to start, maybe null. * * @return the working directory */ public File directory() { return builder.directory(); } /** * Set the working directory of the process to start. * * @param directory the path to the directory * @return this instance to continue building */ public Builder directory(String directory) { return directory(new File(directory)); } /** * Set the working directory of the process to start. * * @param directory the path to the directory * @return this instance to continue building */ public Builder directory(File directory) { builder.directory(directory); return this; } /** * Where to copy the combined stdout and stderr output to, {@code OsProcess#getOutput} is still * working when called. * * @param stream where to copy the combined output to * @return this instance to continue building */ public Builder copyOutputTo(OutputStream stream) { copyOutputTo = stream; return this; } /** * The number of bytes to buffer for {@code OsProcess#getOutput} calls. * * @param toKeep the number of bytes, default is 4096 * @return this instance to continue building */ public Builder bufferSize(int toKeep) { bufferSize = toKeep; return this; } public ExternalProcess start() throws UncheckedIOException { // redirect the stderr to stdout builder.redirectErrorStream(true); Process process; try { process = builder.start(); } catch (IOException ex) { throw new UncheckedIOException(ex); } try { CircularOutputStream circular = new CircularOutputStream(bufferSize); Thread worker = new Thread( () -> { // copyOutputTo might be system.out or system.err, do not to close OutputStream output = new MultiOutputStream(circular, copyOutputTo); // closing the InputStream does somehow disturb the process, do not to close InputStream input = process.getInputStream(); // use the CircularOutputStream as mandatory, we know it will never raise a // IOException try { // we must read the output to ensure the process will not lock up input.transferTo(output); } catch (IOException ex) { LOG.log( Level.WARNING, "failed to copy the output of process " + process.pid(), ex); } LOG.log(Level.FINE, "completed to copy the output of process " + process.pid()); }, "External Process Output Forwarder - " + (builder.command().isEmpty() ? "N/A" : builder.command().get(0))); worker.setDaemon(true); worker.start(); return new ExternalProcess(process, circular, worker); } catch (Throwable t) { // ensure we do not leak a process in case of failures try { process.destroyForcibly(); } catch (Throwable t2) { t.addSuppressed(t2); } throw t; } } } public static Builder builder() { return new Builder(); } private final Process process; private final CircularOutputStream outputStream; private final Thread worker; public ExternalProcess(Process process, CircularOutputStream outputStream, Thread worker) { this.process = process; this.outputStream = outputStream; this.worker = worker; } /** * The last N bytes of the combined stdout and stderr as String, the value of N is set while * building the OsProcess. * * @return stdout and stderr as String in Charset.defaultCharset() encoding */ public String getOutput() { return getOutput(Charset.defaultCharset()); } /** * The last N bytes of the combined stdout and stderr as String, the value of N is set while * building the OsProcess. * * @param encoding the encoding to decode the stream * @return stdout and stderr as String in the given encoding */ public String getOutput(Charset encoding) { return outputStream.toString(encoding); } public boolean isAlive() { return process.isAlive(); } public boolean waitFor(Duration duration) throws InterruptedException { boolean exited = process.waitFor(duration.toMillis(), TimeUnit.MILLISECONDS); if (exited) { try { // the worker might not stop even when process.destroyForcibly is called worker.join(8000); } catch (InterruptedException ex) { Thread.interrupted(); } finally { // if already stopped interrupt is ignored, otherwise raises I/O exceptions in the worker worker.interrupt(); try { // now we might be able to join worker.join(2000); } catch (InterruptedException ex) { Thread.interrupted(); } } } return exited; } public int exitValue() { return process.exitValue(); } /** * Initiate a normal shutdown of the process or kills it when the process is alive after 4 * seconds. */ public void shutdown() { shutdown(Duration.ofSeconds(4)); } /** * Initiate a normal shutdown of the process or kills it when the process is alive after the given * timeout. * * @param timeout the duration for a process to terminate before destroying it forcibly. */ public void shutdown(Duration timeout) { try { if (process.supportsNormalTermination()) { process.destroy(); try { if (process.waitFor(timeout.toMillis(), MILLISECONDS)) { // the outer finally block will take care of the worker return; } } catch (InterruptedException ex) { Thread.interrupted(); } } process.destroyForcibly(); try { process.waitFor(timeout.toMillis(), MILLISECONDS); } catch (InterruptedException ex) { Thread.interrupted(); } } finally { try { // the worker might not stop even when process.destroyForcibly is called worker.join(8000); } catch (InterruptedException ex) { Thread.interrupted(); } finally { // if already stopped interrupt is ignored, otherwise raises I/O exceptions in the worker worker.interrupt(); try { // now we might be able to join worker.join(2000); } catch (InterruptedException ex) { Thread.interrupted(); } } } } }
SeleniumHQ/selenium
java/src/org/openqa/selenium/os/ExternalProcess.java
44,881
/** * Copyright (c) 2013-2024 Nikita Koksharov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.redisson.api; import java.util.Collection; import java.util.List; import org.redisson.api.condition.Condition; import org.redisson.api.condition.Conditions; /** * The pre-registration of each entity class is not necessary. * * Entity's getters and setters operations gets redirected to Redis * automatically. * * @author Rui Gu (https://github.com/jackygurui) * @author Nikita Koksharov * */ public interface RLiveObjectService { /** * Finds the entity from Redis with the id. * * The entityClass should have a field annotated with RId, and the * entityClass itself should have REntity annotated. The type of the RId can * be anything <b>except</b> the followings: * <ol> * <li>An array i.e. byte[], int[], Integer[], etc.</li> * <li>or a RObject i.e. RedissonMap</li> * <li>or a Class with REntity annotation.</li> * </ol> * * * @param entityClass - entity class * @param id identifier * @param <T> Entity type * @return a proxied object if it exists in redis, or null if not. */ <T> T get(Class<T> entityClass, Object id); /** * Finds the entities matches specified <code>condition</code>. * <p><strong> * NOTE: open-source version is slow.<br> * Use <a href="https://redisson.pro">Redisson PRO</a> instead. * </strong><p> * Usage example: * <pre> * Collection objects = liveObjectService.find(MyObject.class, Conditions.or(Conditions.in("field", "value1", "value2"), * Conditions.and(Conditions.eq("field2", "value2"), Conditions.eq("field3", "value5")))); * </pre> * * @see Conditions * * @param <T> Entity type * @param entityClass - entity class * @param condition - condition object * @return collection of live objects or empty collection. */ <T> Collection<T> find(Class<T> entityClass, Condition condition); /** * Counts the entities matches specified <code>condition</code>. * <p><strong> * NOTE: open-source version is slow.<br> * Use <a href="https://redisson.pro">Redisson PRO</a> instead. * </strong><p> * Usage example: * <pre> * long objectsAmount = liveObjectService.count(MyObject.class, Conditions.or(Conditions.in("field", "value1", "value2"), * Conditions.and(Conditions.eq("field2", "value2"), Conditions.eq("field3", "value5")))); * </pre> * * @see Conditions * * @param entityClass - entity class * @param condition - condition object * @return amount of live objects. */ long count(Class<?> entityClass, Condition condition); /** * Returns iterator for all entry ids by specified <code>entityClass</code>. * Ids traversed with SCAN operation. Each SCAN operation loads * up to <code>count</code> keys per request. * * @param entityClass - entity class * @param <K> Key type * @return collection of ids or empty collection. */ <K> Iterable<K> findIds(Class<?> entityClass); /** * Returns iterator for all entry ids by specified <code>entityClass</code>. * Ids traversed with SCAN operation. Each SCAN operation loads * up to <code>count</code> keys per request. * * @param entityClass - entity class * @param count - keys loaded per request to Redis * @param <K> Key type * @return collection of ids or empty collection. */ <K> Iterable<K> findIds(Class<?> entityClass, int count); /** * Returns proxied object for the detached object. Discard all the * field values already in the detached instance. * * The class representing this object should have a field annotated with * RId, and the object should hold a non null value in that field. * * If this object is not in redis then a new <b>blank</b> proxied instance * with the same RId field value will be created. * * @param <T> Entity type * @param detachedObject - not proxied object * @return proxied object * @throws IllegalArgumentException if the object is is a RLiveObject instance. */ <T> T attach(T detachedObject); /** * Returns proxied object for the detached object. Transfers all the * <b>NON NULL</b> field values to the redis server. It does not delete any * existing data in redis in case of the field value is null. * * The class representing this object should have a field annotated with * RId, and the object should hold a non null value in that field. * * If this object is not in redis then a new hash key will be created to * store it. Otherwise overrides current object state in Redis with the given object state. * * @param <T> Entity type * @param detachedObject - not proxied object * @return proxied object * @throws IllegalArgumentException if the object is is a RLiveObject instance. */ <T> T merge(T detachedObject); /** * Returns proxied object for the detached object. Transfers all the * <b>NON NULL</b> field values to the redis server. It does not delete any * existing data in redis in case of the field value is null. * * The class representing this object should have a field annotated with * RId, and the object should hold a non null value in that field. * * If this object is not in redis then a new hash key will be created to * store it. Otherwise overrides current object state in Redis with the given object state. * * @param <T> Entity type * @param detachedObjects - not proxied objects * @return proxied object * @throws IllegalArgumentException if the object is is a RLiveObject instance. */ <T> List<T> merge(T... detachedObjects); /** * Returns proxied attached object for the detached object. Transfers all the * <b>NON NULL</b> field values to the redis server. Only when the it does * not already exist. * * @param <T> Entity type * @param detachedObject - not proxied object * @return proxied object */ <T> T persist(T detachedObject); /** * Returns proxied attached objects for the detached objects. Stores all the * <b>NON NULL</b> field values. * <p> * Executed in a batch mode. * * @param <T> Entity type * @param detachedObjects - not proxied objects * @return list of proxied objects */ <T> List<T> persist(T... detachedObjects); /** * Returns unproxied detached object for the attached object. * * @param <T> Entity type * @param attachedObject - proxied object * @return proxied object */ <T> T detach(T attachedObject); /** * Deletes attached object including all nested objects. * * @param <T> Entity type * @param attachedObject - proxied object */ <T> void delete(T attachedObject); /** * Deletes object by class and ids including all nested objects. * * @param <T> Entity type * @param entityClass - object class * @param ids - object ids * * @return amount of deleted objects */ <T> long delete(Class<T> entityClass, Object... ids); /** * To cast the instance to RLiveObject instance. * * @param <T> type of instance * @param instance - live object * @return RLiveObject compatible object */ <T> RLiveObject asLiveObject(T instance); /** * To cast the instance to RMap instance. * * @param <T> type of instance * @param <K> type of key * @param <V> type of value * @param instance - live object * @return RMap compatible object */ <T, K, V> RMap<K, V> asRMap(T instance); /** * Returns true if the instance is a instance of RLiveObject. * * @param <T> type of instance * @param instance - live object * @return <code>true</code> object is RLiveObject */ <T> boolean isLiveObject(T instance); /** * Returns true if the RLiveObject already exists in redis. It will return false if * the passed object is not a RLiveObject. * * @param <T> type of instance * @param instance - live object * @return <code>true</code> object exists */ <T> boolean isExists(T instance); /** * Pre register the class with the service, registering all the classes on * startup can speed up the instance creation. This is <b>NOT</b> mandatory * since the class will also be registered lazily when it is first used. * * All classed registered with the service is stored in a class cache. * * The cache is independent between different RedissonClient instances. When * a class is registered in one RLiveObjectService instance it is also * accessible in another RLiveObjectService instance so long as they are * created by the same RedissonClient instance. * * @param cls - class */ void registerClass(Class<?> cls); /** * Unregister the class with the service. This is useful after you decide * the class is no longer required. * * A class will be automatically unregistered if the service encountered any * errors during proxying or creating the object, since those errors are not * recoverable. * * All classed registered with the service is stored in a class cache. * * The cache is independent between different RedissonClient instances. When * a class is registered in one RLiveObjectService instance it is also * accessible in another RLiveObjectService instance so long as they are * created by the same RedissonClient instance. * * @param cls It can be either the proxied class or the unproxied conterpart. */ void unregisterClass(Class<?> cls); /** * Check if the class is registered in the cache. * * All classed registered with the service is stored in a class cache. * * The cache is independent between different RedissonClient instances. When * a class is registered in one RLiveObjectService instance it is also * accessible in another RLiveObjectService instance so long as they are * created by the same RedissonClient instance. * * @param cls - type of instance * @return <code>true</code> if class already registered */ boolean isClassRegistered(Class<?> cls); }
redisson/redisson
redisson/src/main/java/org/redisson/api/RLiveObjectService.java
44,882
package com.blankj.base.mvp; import android.util.Log; import java.util.HashMap; import java.util.Map; import androidx.annotation.CallSuper; import androidx.lifecycle.ViewModel; import androidx.lifecycle.ViewModelProvider; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/08/02 * desc : * </pre> */ public abstract class BasePresenter<V extends BaseView> { private static final String TAG = BaseView.TAG; private V mView; private Map<Class<? extends BaseModel>, BaseModel> mModelMap = new HashMap<>(); private boolean isAlive = true; public abstract void onBindView(); void bindView(V view) { this.mView = view; onBindView(); } public V getView() { return mView; } public <M extends BaseModel> M getModel(Class<M> modelClass) { BaseModel baseModel = mModelMap.get(modelClass); if (baseModel != null) { //noinspection unchecked return (M) baseModel; } try { M model = modelClass.newInstance(); mModelMap.put(modelClass, model); model.onCreate(); return model; } catch (IllegalAccessException e) { Log.e("BasePresenter", "getModel", e); } catch (InstantiationException e) { Log.e("BasePresenter", "getModel", e); } return null; } @CallSuper public void onDestroy() { Log.i(TAG, "destroy presenter: " + getClass().getSimpleName()); isAlive = false; for (BaseModel model : mModelMap.values()) { if (model != null) { model.onDestroy(); } } mModelMap.clear(); } public boolean isAlive() { return isAlive; } }
Blankj/AndroidUtilCode
lib/base/src/main/java/com/blankj/base/mvp/BasePresenter.java
44,883
package mindustry.entities.comp; import arc.func.*; import arc.graphics.g2d.*; import arc.math.*; import arc.math.geom.*; import arc.struct.*; import arc.util.*; import mindustry.annotations.Annotations.*; import mindustry.content.*; import mindustry.core.*; import mindustry.entities.*; import mindustry.entities.bullet.*; import mindustry.game.*; import mindustry.game.Teams.*; import mindustry.gen.*; import mindustry.graphics.*; import mindustry.world.*; import mindustry.world.blocks.environment.*; import static mindustry.Vars.*; @EntityDef(value = {Bulletc.class}, pooled = true, serialize = false) @Component(base = true) abstract class BulletComp implements Timedc, Damagec, Hitboxc, Teamc, Posc, Drawc, Shielderc, Ownerc, Velc, Bulletc, Timerc{ @Import Team team; @Import Entityc owner; @Import float x, y, damage, lastX, lastY, time, lifetime; @Import Vec2 vel; IntSeq collided = new IntSeq(6); BulletType type; Object data; float fdata; @ReadOnly private float rotation; //setting this variable to true prevents lifetime from decreasing for a frame. transient boolean keepAlive; transient @Nullable Tile aimTile; transient float aimX, aimY; transient float originX, originY; transient @Nullable Mover mover; transient boolean absorbed, hit; transient @Nullable Trail trail; transient int frags; @Override public void getCollisions(Cons<QuadTree> consumer){ Seq<TeamData> data = state.teams.present; for(int i = 0; i < data.size; i++){ if(data.items[i].team != team){ consumer.get(data.items[i].tree()); } } } //bullets always considered local @Override @Replace public boolean isLocal(){ return true; } @Override public void add(){ type.init(self()); } @Override public void remove(){ if(Groups.isClearing) return; //'despawned' only counts when the bullet is killed externally or reaches the end of life if(!hit){ type.despawned(self()); } type.removed(self()); collided.clear(); } @Override public float damageMultiplier(){ return type.damageMultiplier(self()); } @Override public void absorb(){ absorbed = true; remove(); } public boolean hasCollided(int id){ return collided.size != 0 && collided.contains(id); } @Replace public float clipSize(){ return type.drawSize; } @Replace @Override public boolean collides(Hitboxc other){ return type.collides && (other instanceof Teamc t && t.team() != team) && !(other instanceof Flyingc f && !f.checkTarget(type.collidesAir, type.collidesGround)) && !(type.pierce && hasCollided(other.id())); //prevent multiple collisions } @MethodPriority(100) @Override public void collision(Hitboxc other, float x, float y){ type.hit(self(), x, y); //must be last. if(!type.pierce){ hit = true; remove(); }else{ collided.add(other.id()); } type.hitEntity(self(), other, other instanceof Healthc h ? h.health() : 0f); } @Override public void update(){ if(mover != null){ mover.move(self()); } type.update(self()); if(type.collidesTiles && type.collides && type.collidesGround){ tileRaycast(World.toTile(lastX), World.toTile(lastY), tileX(), tileY()); } if(type.removeAfterPierce && type.pierceCap != -1 && collided.size >= type.pierceCap){ hit = true; remove(); } if(keepAlive){ time -= Time.delta; keepAlive = false; } } public void moveRelative(float x, float y){ float rot = rotation(); this.x += Angles.trnsx(rot, x * Time.delta, y * Time.delta); this.y += Angles.trnsy(rot, x * Time.delta, y * Time.delta); } public void turn(float x, float y){ float ang = vel.angle(); vel.add(Angles.trnsx(ang, x * Time.delta, y * Time.delta), Angles.trnsy(ang, x * Time.delta, y * Time.delta)).limit(type.speed); } public boolean checkUnderBuild(Building build, float x, float y){ return (!build.block.underBullets || //direct hit on correct tile (aimTile != null && aimTile.build == build) || //same team has no 'under build' mechanics (build.team == team) || //a piercing bullet overshot the aim tile, it's fine to hit things now (type.pierce && aimTile != null && Mathf.dst(x, y, originX, originY) > aimTile.dst(originX, originY) + 2f) || //there was nothing to aim at (aimX == -1f && aimY == -1f)); } //copy-paste of World#raycastEach, inlined for lambda capture performance. @Override public void tileRaycast(int x1, int y1, int x2, int y2){ int x = x1, dx = Math.abs(x2 - x), sx = x < x2 ? 1 : -1; int y = y1, dy = Math.abs(y2 - y), sy = y < y2 ? 1 : -1; int e2, err = dx - dy; int ww = world.width(), wh = world.height(); while(x >= 0 && y >= 0 && x < ww && y < wh){ Building build = world.build(x, y); if(type.collideFloor || type.collideTerrain){ Tile tile = world.tile(x, y); if( type.collideFloor && (tile == null || tile.floor().hasSurface() || tile.block() != Blocks.air) || type.collideTerrain && tile != null && tile.block() instanceof StaticWall ){ remove(); hit = true; return; } } if(build != null && isAdded() && checkUnderBuild(build, x * tilesize, y * tilesize) && build.collide(self()) && type.testCollision(self(), build) && !build.dead() && (type.collidesTeam || build.team != team) && !(type.pierceBuilding && hasCollided(build.id))){ boolean remove = false; float health = build.health; if(build.team != team){ remove = build.collision(self()); } if(remove || type.collidesTeam){ if(Mathf.dst2(lastX, lastY, x * tilesize, y * tilesize) < Mathf.dst2(lastX, lastY, this.x, this.y)){ this.x = x * tilesize; this.y = y * tilesize; } if(!type.pierceBuilding){ hit = true; remove(); }else{ collided.add(build.id); } } type.hitTile(self(), build, x * tilesize, y * tilesize, health, true); //stop raycasting when building is hit if(type.pierceBuilding) return; } if(x == x2 && y == y2) break; e2 = 2 * err; if(e2 > -dy){ err -= dy; x += sx; } if(e2 < dx){ err += dx; y += sy; } } } @Override public void draw(){ Draw.z(type.layer); type.draw(self()); type.drawLight(self()); Draw.reset(); } public void initVel(float angle, float amount){ vel.trns(angle, amount); rotation = angle; } /** Sets the bullet's rotation in degrees. */ @Override public void rotation(float angle){ vel.setAngle(rotation = angle); } /** @return the bullet's rotation. */ @Override public float rotation(){ return vel.isZero(0.001f) ? rotation : vel.angle(); } }
Anuken/Mindustry
core/src/mindustry/entities/comp/BulletComp.java
44,884
/* * Copyright (C) 2014 Brett Wooldridge * * 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.zaxxer.hikari.pool; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.Comparator; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.zaxxer.hikari.util.ClockSource; import com.zaxxer.hikari.util.ConcurrentBag.IConcurrentBagEntry; import com.zaxxer.hikari.util.FastList; /** * Entry used in the ConcurrentBag to track Connection instances. * * @author Brett Wooldridge */ final class PoolEntry implements IConcurrentBagEntry { private static final Logger LOGGER = LoggerFactory.getLogger(PoolEntry.class); static final Comparator<PoolEntry> LAST_ACCESS_COMPARABLE; Connection connection; long lastAccessed; long lastBorrowed; private volatile boolean evict; private volatile ScheduledFuture<?> endOfLife; private final FastList<Statement> openStatements; private final HikariPool hikariPool; private final AtomicInteger state; private final boolean isReadOnly; private final boolean isAutoCommit; static { LAST_ACCESS_COMPARABLE = new Comparator<PoolEntry>() { @Override public int compare(final PoolEntry entryOne, final PoolEntry entryTwo) { return Long.compare(entryOne.lastAccessed, entryTwo.lastAccessed); } }; } PoolEntry(final Connection connection, final PoolBase pool, final boolean isReadOnly, final boolean isAutoCommit) { this.connection = connection; this.hikariPool = (HikariPool) pool; this.isReadOnly = isReadOnly; this.isAutoCommit = isAutoCommit; this.state = new AtomicInteger(); this.lastAccessed = ClockSource.INSTANCE.currentTime(); this.openStatements = new FastList<>(Statement.class, 16); } /** * Release this entry back to the pool. * * @param lastAccessed last access time-stamp */ void recycle(final long lastAccessed) { this.lastAccessed = lastAccessed; hikariPool.releaseConnection(this); } /** * @param endOfLife the end future */ void setFutureEol(final ScheduledFuture<?> endOfLife) { this.endOfLife = endOfLife; } Connection createProxyConnection(final ProxyLeakTask leakTask, final long now) { return ProxyFactory.getProxyConnection(this, connection, openStatements, leakTask, now, isReadOnly, isAutoCommit); } void resetConnectionState(final ProxyConnection proxyConnection, final int dirtyBits) throws SQLException { hikariPool.resetConnectionState(connection, proxyConnection, dirtyBits); } String getPoolName() { return hikariPool.toString(); } boolean isMarkedEvicted() { return evict; } void markEvicted() { this.evict = true; } void evict(final String closureReason) { hikariPool.closeConnection(this, closureReason); } /** Returns millis since lastBorrowed */ long getMillisSinceBorrowed() { return ClockSource.INSTANCE.elapsedMillis(lastBorrowed); } /** {@inheritDoc} */ @Override public String toString() { final long now = ClockSource.INSTANCE.currentTime(); return connection + ", accessed " + ClockSource.INSTANCE.elapsedDisplayString(lastAccessed, now) + " ago, " + stateToString(); } // *********************************************************************** // IConcurrentBagEntry methods // *********************************************************************** /** {@inheritDoc} */ @Override public int getState() { return state.get(); } /** {@inheritDoc} */ @Override public boolean compareAndSet(int expect, int update) { return state.compareAndSet(expect, update); } /** {@inheritDoc} */ @Override public void lazySet(int update) { state.lazySet(update); } Connection close() { ScheduledFuture<?> eol = endOfLife; if (eol != null && !eol.isDone() && !eol.cancel(false)) { LOGGER.warn("{} - maxLifeTime expiration task cancellation unexpectedly returned false for connection {}", getPoolName(), connection); } Connection con = connection; connection = null; endOfLife = null; return con; } private String stateToString() { switch (state.get()) { case STATE_IN_USE: return "IN_USE"; case STATE_NOT_IN_USE: return "NOT_IN_USE"; case STATE_REMOVED: return "REMOVED"; case STATE_RESERVED: return "RESERVED"; default: return "Invalid"; } } }
brettwooldridge/HikariCP
src/main/java/com/zaxxer/hikari/pool/PoolEntry.java
44,885
/* ### * IP: GHIDRA * * 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 ghidra.util; import java.awt.Color; import java.util.HashMap; import java.util.Map; /** * Class for web color support. This class defines many of the colors used by html. This class * includes methods for converting a color to a string (name or hex value) and for converting * those strings back to a color. * <p> * Usage Note: Java's HTML rendering engine supports colors in hex form ('#aabb11'). Also, the * engine supports many web color names ('silver'). However, not all web color names defined in * this file are supported. Thus, when specifying HTML colors, do not rely on these web color * names. */ public abstract class WebColors { private static final Map<String, Color> nameToColorMap = new HashMap<>(); private static final Map<Integer, String> colorToNameMap = new HashMap<>(); //@formatter:off public static final Color BLACK = registerColor("Black", Color.black); public static final Color NAVY = registerColor("Navy", Color.decode("0x000080")); public static final Color DARK_BLUE = registerColor("DarkBlue", Color.decode("0x00008B")); public static final Color MEDIUM_BLUE = registerColor("MediumBlue", Color.decode("0x0000CD")); public static final Color BLUE = registerColor("Blue", Color.decode("0x0000FF")); public static final Color DARK_GREEN = registerColor("DarkGreen", Color.decode("0x006400")); public static final Color GREEN = registerColor("Green", Color.decode("0x008000")); public static final Color TEAL = registerColor("Teal", Color.decode("0x008080")); public static final Color DARK_CYAN = registerColor("DarkCyan", Color.decode("0x008B8B")); public static final Color DEEP_SKY_BLUE = registerColor("DeepSkyBlue", Color.decode("0x00BFFF")); public static final Color DARK_TURQUOSE = registerColor("DarkTurquoise", Color.decode("0x00CED1")); public static final Color LIME = registerColor("Lime", Color.decode("0x00FF00")); public static final Color SPRING_GREEN = registerColor("SpringGreen", Color.decode("0x00FF7F")); public static final Color AQUA = registerColor("Aqua", Color.decode("0x00FFFF")); public static final Color CYAN = registerColor("Cyan", Color.decode("0x00FFFF")); public static final Color MIDNIGHT_BLUE = registerColor("MidnightBlue", Color.decode("0x191970")); public static final Color DOGER_BLUE = registerColor("DodgerBlue", Color.decode("0x1E90FF")); public static final Color LIGHT_SEA_GREEN = registerColor("LightSeaGreen", Color.decode("0x20B2AA")); public static final Color FOREST_GREEN = registerColor("ForestGreen", Color.decode("0x228B22")); public static final Color SEA_GREEN = registerColor("SeaGreen", Color.decode("0x2E8B57")); public static final Color DARK_SLATE_GRAY = registerColor("DarkSlateGray", Color.decode("0x2F4F4F")); public static final Color LIME_GREEN = registerColor("LimeGreen", Color.decode("0x32CD32")); public static final Color TURQUOISE = registerColor("Turquoise", Color.decode("0x40E0D0")); public static final Color ROYAL_BLUE = registerColor("RoyalBlue", Color.decode("0x4169E1")); public static final Color STEEL_BLUE = registerColor("SteelBlue", Color.decode("0x4682B4")); public static final Color DARK_SLATE_BLUE = registerColor("DarkSlateBlue", Color.decode("0x483D8B")); public static final Color INDIGO = registerColor("Indigo", Color.decode("0x4B0082")); public static final Color CADET_BLUE = registerColor("CadetBlue", Color.decode("0x5F9EA0")); public static final Color REBECCA_PURPLE = registerColor("RebeccaPurple", Color.decode("0x663399")); public static final Color DIM_GRAY = registerColor("DimGray", Color.decode("0x696969")); public static final Color SLATE_BLUE = registerColor("SlateBlue", Color.decode("0x6A5ACD")); public static final Color OLIVE_DRAB = registerColor("OliveDrab", Color.decode("0x6B8E23")); public static final Color SLATE_GRAY = registerColor("SlateGray", Color.decode("0x708090")); public static final Color LAWN_GREEN = registerColor("LawnGreen", Color.decode("0x7CFC00")); public static final Color CHARTREUSE = registerColor("Chartreuse", Color.decode("0x7FFF00")); public static final Color AQUAMARINE = registerColor("Aquamarine", Color.decode("0x7FFFD4")); public static final Color MAROON = registerColor("Maroon", Color.decode("0x800000")); public static final Color PURPLE = registerColor("Purple", Color.decode("0x800080")); public static final Color OLIVE = registerColor("Olive", Color.decode("0x808000")); public static final Color GRAY = registerColor("Gray", Color.decode("0x808080")); public static final Color SYY_BLUE = registerColor("SkyBlue", Color.decode("0x87CEEB")); public static final Color LIGHT_SKY_BLUE = registerColor("LightSkyBlue", Color.decode("0x87CEFA")); public static final Color BLUE_VIOLET = registerColor("BlueViolet", Color.decode("0x8A2BE2")); public static final Color DARK_RED = registerColor("DarkRed", Color.decode("0x8B0000")); public static final Color DARK_MAGENTA = registerColor("DarkMagenta", Color.decode("0x8B008B")); public static final Color SADDLE_BROWN = registerColor("SaddleBrown", Color.decode("0x8B4513")); public static final Color DARK_SEA_GREEN = registerColor("DarkSeaGreen", Color.decode("0x8FBC8F")); public static final Color LIGHT_GREEN = registerColor("LightGreen", Color.decode("0x90EE90")); public static final Color MEDIUM_PURPLE = registerColor("MediumPurple", Color.decode("0x9370DB")); public static final Color DARK_VIOLET = registerColor("DarkViolet", Color.decode("0x9400D3")); public static final Color PALE_GREEN = registerColor("PaleGreen", Color.decode("0x98FB98")); public static final Color DARK_ORCHID = registerColor("DarkOrchid", Color.decode("0x9932CC")); public static final Color YELLOW_GREEN = registerColor("YellowGreen", Color.decode("0x9ACD32")); public static final Color SIENNA = registerColor("Sienna", Color.decode("0xA0522D")); public static final Color BROWN = registerColor("Brown", Color.decode("0xA52A2A")); public static final Color DARK_GRAY = registerColor("DarkGray", Color.decode("0xA9A9A9")); public static final Color LIGHT_BLUE = registerColor("LightBlue", Color.decode("0xADD8E6")); public static final Color GREEN_YELLOW = registerColor("GreenYellow", Color.decode("0xADFF2F")); public static final Color PALE_TURQUOISE = registerColor("PaleTurquoise", Color.decode("0xAFEEEE")); public static final Color POWDER_BLUE = registerColor("PowderBlue", Color.decode("0xB0E0E6")); public static final Color FIRE_BRICK = registerColor("FireBrick", Color.decode("0xB22222")); public static final Color DARK_GOLDENROD = registerColor("DarkGoldenRod", Color.decode("0xB8860B")); public static final Color MEDIUM_ORCHID = registerColor("MediumOrchid", Color.decode("0xBA55D3")); public static final Color ROSY_BROWN = registerColor("RosyBrown", Color.decode("0xBC8F8F")); public static final Color DARK_KHAKI = registerColor("DarkKhaki", Color.decode("0xBDB76B")); public static final Color SILVER = registerColor("Silver", Color.decode("0xC0C0C0")); public static final Color INDIAN_RED = registerColor("IndianRed", Color.decode("0xCD5C5C")); public static final Color PERU = registerColor("Peru", Color.decode("0xCD853F")); public static final Color CHOCOLATE = registerColor("Chocolate", Color.decode("0xD2691E")); public static final Color TAN = registerColor("Tan", Color.decode("0xD2B48C")); public static final Color LIGHT_GRAY = registerColor("LightGray", Color.decode("0xD3D3D3")); public static final Color THISTLE = registerColor("Thistle", Color.decode("0xD8BFD8")); public static final Color ORCHID = registerColor("Orchid", Color.decode("0xDA70D6")); public static final Color GOLDEN_ROD = registerColor("GoldenRod", Color.decode("0xDAA520")); public static final Color PALE_VIOLET_RED = registerColor("PaleVioletRed", Color.decode("0xDB7093")); public static final Color CRIMSON = registerColor("Crimson", Color.decode("0xDC143C")); public static final Color GAINSBORO = registerColor("Gainsboro", Color.decode("0xDCDCDC")); public static final Color PLUM = registerColor("Plum", Color.decode("0xDDA0DD")); public static final Color BURLYWOOD = registerColor("BurlyWood", Color.decode("0xDEB887")); public static final Color LIGHT_CYAN = registerColor("LightCyan", Color.decode("0xE0FFFF")); public static final Color LAVENDER = registerColor("Lavender", Color.decode("0xE6E6FA")); public static final Color DARK_SALMON = registerColor("DarkSalmon", Color.decode("0xE9967A")); public static final Color VIOLET = registerColor("Violet", Color.decode("0xEE82EE")); public static final Color PALE_GOLDENROD = registerColor("PaleGoldenRod", Color.decode("0xEEE8AA")); public static final Color LIGHT_CORAL = registerColor("LightCoral", Color.decode("0xF08080")); public static final Color KHAKE = registerColor("Khaki", Color.decode("0xF0E68C")); public static final Color ALICE_BLUE = registerColor("AliceBlue", Color.decode("0xF0F8FF")); public static final Color HONEY_DEW = registerColor("HoneyDew", Color.decode("0xF0FFF0")); public static final Color AZURE = registerColor("Azure", Color.decode("0xF0FFFF")); public static final Color SANDY_BROWN = registerColor("SandyBrown", Color.decode("0xF4A460")); public static final Color WHEAT = registerColor("Wheat", Color.decode("0xF5DEB3")); public static final Color BEIGE = registerColor("Beige", Color.decode("0xF5F5DC")); public static final Color WHITE_SMOKE = registerColor("WhiteSmoke", Color.decode("0xF5F5F5")); public static final Color MINT_CREAM = registerColor("MintCream", Color.decode("0xF5FFFA")); public static final Color GHOST_WHITE = registerColor("GhostWhite", Color.decode("0xF8F8FF")); public static final Color SALMON = registerColor("Salmon", Color.decode("0xFA8072")); public static final Color ANTIQUE_WHITE = registerColor("AntiqueWhite", Color.decode("0xFAEBD7")); public static final Color LINEN = registerColor("Linen", Color.decode("0xFAF0E6")); public static final Color OLDLACE = registerColor("OldLace", Color.decode("0xFDF5E6")); public static final Color RED = registerColor("Red", Color.decode("0xFF0000")); public static final Color FUCHSIA = registerColor("Fuchsia", Color.decode("0xFF00FF")); public static final Color MAGENTA = registerColor("Magenta", Color.decode("0xFF00FF")); public static final Color DEEP_PINK = registerColor("DeepPink", Color.decode("0xFF1493")); public static final Color ORANGE_RED = registerColor("OrangeRed", Color.decode("0xFF4500")); public static final Color TOMATO = registerColor("Tomato", Color.decode("0xFF6347")); public static final Color HOT_PINK = registerColor("HotPink", Color.decode("0xFF69B4")); public static final Color CORAL = registerColor("Coral", Color.decode("0xFF7F50")); public static final Color DARK_ORANGE = registerColor("DarkOrange", Color.decode("0xFF8C00")); public static final Color LIGHT_SALMON = registerColor("LightSalmon", Color.decode("0xFFA07A")); public static final Color ORANGE = registerColor("Orange", Color.decode("0xFFA500")); public static final Color LIGHT_PINK = registerColor("LightPink", Color.decode("0xFFB6C1")); public static final Color PINK = registerColor("Pink", Color.decode("0xFFC0CB")); public static final Color GOLD = registerColor("Gold", Color.decode("0xFFD700")); public static final Color PEACH_PUFF = registerColor("PeachPuff", Color.decode("0xFFDAB9")); public static final Color NAVAJO_WHITE = registerColor("NavajoWhite", Color.decode("0xFFDEAD")); public static final Color MOCCASIN = registerColor("Moccasin", Color.decode("0xFFE4B5")); public static final Color BISQUE = registerColor("Bisque", Color.decode("0xFFE4C4")); public static final Color MISTY_ROSE = registerColor("MistyRose", Color.decode("0xFFE4E1")); public static final Color BLANCHED_ALMOND = registerColor("BlanchedAlmond", Color.decode("0xFFEBCD")); public static final Color PAPAYA_WHIP = registerColor("PapayaWhip", Color.decode("0xFFEFD5")); public static final Color LAVENDER_BLUSH = registerColor("LavenderBlush", Color.decode("0xFFF0F5")); public static final Color SEASHELL = registerColor("SeaShell", Color.decode("0xFFF5EE")); public static final Color CORNSILK = registerColor("Cornsilk", Color.decode("0xFFF8DC")); public static final Color LEMON_CHIFFON = registerColor("LemonChiffon", Color.decode("0xFFFACD")); public static final Color FLORAL_WHITE = registerColor("FloralWhite", Color.decode("0xFFFAF0")); public static final Color SNOW = registerColor("Snow", Color.decode("0xFFFAFA")); public static final Color YELLOW = registerColor("Yellow", Color.decode("0xFFFF00")); public static final Color LIGHT_YELLOW = registerColor("LightYellow", Color.decode("0xFFFFE0")); public static final Color IVORY = registerColor("Ivory", Color.decode("0xFFFFF0")); public static final Color WHITE = registerColor("White", Color.decode("0xFFFFFF")); public static final Color MEDIUM_SPRING_GREEN = registerColor("MediumSpringGreen", Color.decode("0x00FA9A")); public static final Color LIGHT_GOLDENROD = registerColor("LightGoldenRodYellow", Color.decode("0xFAFAD2")); public static final Color MEDIUM_VIOLET_RED = registerColor("MediumVioletRed", Color.decode("0xC71585")); public static final Color LIGHT_STEEL_BLUE = registerColor("LightSteelBlue", Color.decode("0xB0C4DE")); public static final Color LIGHT_SLATE_GRAY = registerColor("LightSlateGray", Color.decode("0x778899")); public static final Color MEDIUM_SLATE_BLUE = registerColor("MediumSlateBlue", Color.decode("0x7B68EE")); public static final Color MEDIUM_SEA_GREEN = registerColor("MediumSeaGreen", Color.decode("0x3CB371")); public static final Color MEDUM_AQUA_MARINE = registerColor("MediumAquaMarine", Color.decode("0x66CDAA")); public static final Color MEDIUM_TURQOISE = registerColor("MediumTurquoise", Color.decode("0x48D1CC")); public static final Color DARK_OLIVE_GREEN = registerColor("DarkOliveGreen", Color.decode("0x556B2F")); public static final Color CORNFLOWER_BLUE = registerColor("CornflowerBlue", Color.decode("0x6495ED")); //@formatter:on // cannot instantiate nor extend private WebColors() { } /** * Tries to find a color for the given String value. The String value can either be * a hex string (see {@link Color#decode(String)}) or a web color name as defined * above * * @param value the string value to interpret as a color * @param defaultColor a default color to return if the string can't be converted to a color * @return a color for the given string value or the default color if the string can't be translated */ public static Color getColorOrDefault(String value, Color defaultColor) { Color color = getColor(value); return color != null ? color : defaultColor; } /** * Converts a color to a string value. If there is a defined color for the given color value, * the color name will be returned. Otherwise, it will return a hex string for the color as * follows. If the color has an non-opaque alpha value, it will be of the form #rrggbb. If * it has an alpha value,then the format will be #rrggbbaa. * * @param color the color to convert to a string. * @return the string representation for the given color. */ public static String toString(Color color) { return toString(color, true); } /** * Converts a color to a string value. If the color is a WebColor and the useNameIfPossible * is true, the name of the color will be returned. OOtherwise, it will return a hex string for the color as * follows. If the color has an non-opaque alpha value, it will be of the form #rrggbb. If * it has an alpha value ,then the format will be #rrggbbaa. * * @param color the color to convert to a string. * @param useNameIfPossible if true, the name of the color will be returned if the color is * a WebColor * @return the string representation for the given color. */ public static String toString(Color color, boolean useNameIfPossible) { if (useNameIfPossible) { String name = colorToNameMap.get(color.getRGB()); if (name != null) { return name; } } return toHexString(color); } public static String toColorName(Color color) { return colorToNameMap.get(color.getRGB()); } /** * Returns the hex value string for the given color * @param color the color * @return the string */ public static String toHexString(Color color) { int rgb = color.getRGB() & 0xffffff; //mask off any alpha value int alpha = color.getAlpha(); if (alpha != 0xff) { return String.format("#%06x%02x", rgb, alpha); } return String.format("#%06x", rgb); } /** * Returns the rgb value string for the given color * @param color the color * @return the string */ public static String toRgbString(Color color) { int r = color.getRed(); int g = color.getGreen(); int b = color.getBlue(); int a = color.getAlpha(); String rgb = r + "," + g + "," + b; if (a != 0xff) { return "rgba(" + rgb + "," + a + ")"; } return "rgb(" + rgb + ")"; } /** * Returns the WebColor name for the given color. Returns null if the color is not a WebColor * @param color the color to lookup a WebColor name. * @return the WebColor name for the given color. Returns null if the color is not a WebColor */ public static String toWebColorName(Color color) { return colorToNameMap.get(color.getRGB()); } private static Color registerColor(String name, Color color) { nameToColorMap.put(name.toLowerCase(), color); colorToNameMap.put(color.getRGB(), name); return color; } /** * Attempts to convert the given string into a color in a most flexible manner. It first checks * if the given string matches the name of a known web color as defined above. If so it * returns that color. Otherwise it tries to parse the string in any one of the following * formats: * <pre> * #rrggbb * #rrggbbaa * 0xrrggbb * 0xrrggbbaa * rgb(red, green, blue) * rgba(red, green, alpha) * </pre> * In the hex digit formats, the hex digits "rr", "gg", "bb", "aa" represent the values for red, * green, blue, and alpha, respectively. In the "rgb" and "rgba" formats the red, green, and * blue values are all integers between 0-255, while the alpha value is a float value from 0.0 to * 1.0. * <BR><BR> * @param colorString the color name * @return a color for the given string or null */ public static Color getColor(String colorString) { String value = colorString.trim().toLowerCase(); Color color = nameToColorMap.get(value.toLowerCase()); if (color != null) { return color; } return parseColor(value); } private static Color parseColor(String colorString) { if (colorString.startsWith("#") || colorString.startsWith("0x")) { return parseHexColor(colorString); } if (colorString.startsWith("rgba(")) { return parseRgbaColor(colorString); } return parseRgbColor(colorString); } /** * Parses the given string into a color. The string must be in one of the following formats: * <pre> * #rrggbb * #rrggbbaa * 0xrrggbb * 0xrrggbbaa * </pre> * * Each of the hex digits "rr", "gg", "bb", and "aa" specify the red, green, blue, and alpha * values respectively. * <br><br> * * @param hexString the string to parse into a color. * @return the parsed Color or null if the input string was invalid. */ private static Color parseHexColor(String hexString) { String value = hexString.trim(); if (value.startsWith("#")) { value = value.substring(1); } else if (value.startsWith("0x")) { value = value.substring(2); } else { return null; } if (value.length() != 8 && value.length() != 6) { return null; } boolean hasAlpha = value.length() == 8; if (hasAlpha) { // alpha value is the last 2 digits, Color wants alpha to be in upper bits so re-arrange value = value.substring(6) + value.substring(0, 6); } try { long colorValue = Long.parseLong(value, 16); return new Color((int) colorValue, hasAlpha); } catch (NumberFormatException e) { return null; } } /** * Parses the given string into a color. The string must be in one of the following formats: * <pre> * rgb(red, green, blue) * rgb(red, green, blue, alpha) * </pre> * Each of the values "red", "green", "blue", and "alpha" must be integer values between 0-255 * <br><br> * @param rgbString the string to parse into a color. * @return the parsed Color or null if the input string was invalid. */ private static Color parseRgbColor(String rgbString) { String value = rgbString.trim().replaceAll(" ", ""); if (value.startsWith("rgb(") && value.endsWith(")")) { value = value.substring(4, value.length() - 1); } // strip off to comma separated values String[] split = value.split(","); if (split.length != 3) { return null; } try { int red = Integer.parseInt(split[0]); int green = Integer.parseInt(split[1]); int blue = Integer.parseInt(split[2]); return new Color(red, green, blue); } catch (IllegalArgumentException e) { return null; } } private static Color parseRgbaColor(String rgbaString) { String value = rgbaString.replaceAll(" ", ""); if (value.startsWith("rgba(") && value.endsWith(")")) { value = value.substring(5, value.length() - 1); } // strip off to comma separated values value = value.replaceAll(" ", ""); String[] split = value.split(","); if (split.length != 4) { return null; } try { int red = Integer.parseInt(split[0]); int green = Integer.parseInt(split[1]); int blue = Integer.parseInt(split[2]); int alpha = parseAlpha(split[3]); return new Color(red, green, blue, alpha); } catch (IllegalArgumentException e) { return null; } } private static int parseAlpha(String string) { // alpha strings can either be a float between 0.0 and 1.0 or an integer from 0 to 255. // if it is a float, treat that value as a percentage of the 255 max value // if it is an int, don't allow the value to be bigger than 255. if (string.contains(".")) { float value = Float.parseFloat(string); return (int) (value * 0xff + 0.5) & 0xff; // convert to value in range (0-255) } return Integer.parseInt(string) & 0xff; // truncate any bits that would make it bigger than 255 } }
NationalSecurityAgency/ghidra
Ghidra/Framework/Gui/src/main/java/ghidra/util/WebColors.java
44,886
import java.util.Scanner; /** * Game of Pizza * <p> * Based on the Basic game of Hurkle here * https://github.com/coding-horror/basic-computer-games/blob/main/69%20Pizza/pizza.bas * <p> * Note: The idea was to create a version of the 1970's Basic game in Java, without introducing * new features - no additional text, error checking, etc has been added. */ public class Pizza { private final int MAX_DELIVERIES = 5; private enum GAME_STATE { STARTING, ENTER_NAME, DRAW_MAP, MORE_DIRECTIONS, START_DELIVER, DELIVER_PIZZA, TOO_DIFFICULT, END_GAME, GAME_OVER } // houses that can order pizza private final char[] houses = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P'}; // size of grid private final int[] gridPos = new int[]{1, 2, 3, 4}; private GAME_STATE gameState; private String playerName; // How many pizzas have been successfully delivered private int pizzaDeliveryCount; // current house that ordered a pizza private int currentHouseDelivery; // Used for keyboard input private final Scanner kbScanner; public Pizza() { gameState = GAME_STATE.STARTING; // Initialise kb scanner kbScanner = new Scanner(System.in); } /** * Main game loop */ public void play() { do { switch (gameState) { // Show an introduction the first time the game is played. case STARTING: init(); intro(); gameState = GAME_STATE.ENTER_NAME; break; // Enter the players name case ENTER_NAME: playerName = displayTextAndGetInput("WHAT IS YOUR FIRST NAME? "); System.out.println("HI " + playerName + ". IN GAME YOU ARE TO TAKE ORDERS"); System.out.println("FOR PIZZAS. THEN YOU ARE TO TELL A DELIVERY BOY"); System.out.println("WHERE TO DELIVER THE ORDERED PIZZAS."); System.out.println(); gameState = GAME_STATE.DRAW_MAP; break; // Draw the map case DRAW_MAP: drawMap(); gameState = GAME_STATE.MORE_DIRECTIONS; break; // need more directions (how to play) ? case MORE_DIRECTIONS: extendedIntro(); String moreInfo = displayTextAndGetInput("DO YOU NEED MORE DIRECTIONS? "); if (!yesOrNoEntered(moreInfo)) { System.out.println("'YES' OR 'NO' PLEASE, NOW THEN,"); } else { // More instructions selected if (yesEntered(moreInfo)) { displayMoreDirections(); // Player understand now? if (yesEntered(displayTextAndGetInput("UNDERSTAND? "))) { System.out.println("GOOD. YOU ARE NOW READY TO START TAKING ORDERS."); System.out.println(); System.out.println("GOOD LUCK!!"); System.out.println(); gameState = GAME_STATE.START_DELIVER; } else { // Not understood, essentially game over gameState = GAME_STATE.TOO_DIFFICULT; } } else { // no more directions were needed, start delivering pizza gameState = GAME_STATE.START_DELIVER; } } break; // Too difficult to understand, game over! case TOO_DIFFICULT: System.out.println("JOB IS DEFINITELY TOO DIFFICULT FOR YOU. THANKS ANYWAY"); gameState = GAME_STATE.GAME_OVER; break; // Delivering pizza case START_DELIVER: // select a random house and "order" a pizza for them. currentHouseDelivery = (int) (Math.random() * (houses.length) + 1) - 1; // Deduct 1 for 0-based array System.out.println("HELLO " + playerName + "'S PIZZA. THIS IS " + houses[currentHouseDelivery] + "."); System.out.println(" PLEASE SEND A PIZZA."); gameState = GAME_STATE.DELIVER_PIZZA; break; // Try and deliver the pizza case DELIVER_PIZZA: String question = " DRIVER TO " + playerName + ": WHERE DOES " + houses[currentHouseDelivery] + " LIVE ? "; String answer = displayTextAndGetInput(question); // Convert x,y entered by player to grid position of a house int x = getDelimitedValue(answer, 0); int y = getDelimitedValue(answer, 1); int calculatedPos = (x + (y - 1) * 4) - 1; // Did the player select the right house to deliver? if (calculatedPos == currentHouseDelivery) { System.out.println("HELLO " + playerName + ". THIS IS " + houses[currentHouseDelivery] + ", THANKS FOR THE PIZZA."); pizzaDeliveryCount++; // Delivered enough pizza? if (pizzaDeliveryCount > MAX_DELIVERIES) { gameState = GAME_STATE.END_GAME; } else { gameState = GAME_STATE.START_DELIVER; } } else { System.out.println("THIS IS " + houses[calculatedPos] + ". I DID NOT ORDER A PIZZA."); System.out.println("I LIVE AT " + x + "," + y); // Don't change gameState so state is executed again } break; // Sign off message for cases where the Chief is not upset case END_GAME: if (yesEntered(displayTextAndGetInput("DO YOU WANT TO DELIVER MORE PIZZAS? "))) { init(); gameState = GAME_STATE.START_DELIVER; } else { System.out.println(); System.out.println("O.K. " + playerName + ", SEE YOU LATER!"); System.out.println(); gameState = GAME_STATE.GAME_OVER; } break; // GAME_OVER State does not specifically have a case } } while (gameState != GAME_STATE.GAME_OVER); } private void drawMap() { System.out.println("MAP OF THE CITY OF HYATTSVILLE"); System.out.println(); System.out.println(" -----1-----2-----3-----4-----"); int k = 3; for (int i = 1; i < 5; i++) { System.out.println("-"); System.out.println("-"); System.out.println("-"); System.out.println("-"); System.out.print(gridPos[k]); int pos = 16 - 4 * i; System.out.print(" " + houses[pos]); System.out.print(" " + houses[pos + 1]); System.out.print(" " + houses[pos + 2]); System.out.print(" " + houses[pos + 3]); System.out.println(" " + gridPos[k]); k = k - 1; } System.out.println("-"); System.out.println("-"); System.out.println("-"); System.out.println("-"); System.out.println(" -----1-----2-----3-----4-----"); } /** * Basic information about the game */ private void intro() { System.out.println("PIZZA"); System.out.println("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); System.out.println(); System.out.println(); System.out.println("PIZZA DELIVERY GAME"); System.out.println(); } private void extendedIntro() { System.out.println("THE OUTPUT IS A MAP OF THE HOMES WHERE"); System.out.println("YOU ARE TO SEND PIZZAS."); System.out.println(); System.out.println("YOUR JOB IS TO GIVE A TRUCK DRIVER"); System.out.println("THE LOCATION OR COORDINATES OF THE"); System.out.println("HOME ORDERING THE PIZZA."); System.out.println(); } private void displayMoreDirections() { System.out.println(); System.out.println("SOMEBODY WILL ASK FOR A PIZZA TO BE"); System.out.println("DELIVERED. THEN A DELIVERY BOY WILL"); System.out.println("ASK YOU FOR THE LOCATION."); System.out.println(" EXAMPLE:"); System.out.println("THIS IS J. PLEASE SEND A PIZZA."); System.out.println("DRIVER TO " + playerName + ". WHERE DOES J LIVE?"); System.out.println("YOUR ANSWER WOULD BE 2,3"); System.out.println(); } private void init() { pizzaDeliveryCount = 1; } /** * Accepts a string delimited by comma's and returns the nth delimited * value (starting at count 0). * * @param text - text with values separated by comma's * @param pos - which position to return a value for * @return the int representation of the value */ private int getDelimitedValue(String text, int pos) { String[] tokens = text.split(","); return Integer.parseInt(tokens[pos]); } /** * Returns true if a given string is equal to at least one of the values specified in the call * to the stringIsAnyValue method * * @param text string to search * @return true if string is equal to one of the varargs */ private boolean yesEntered(String text) { return stringIsAnyValue(text, "Y", "YES"); } /** * returns true if Y, YES, N, or NO was the compared value in text * case-insensitive * * @param text search string * @return true if one of the varargs was found in text */ private boolean yesOrNoEntered(String text) { return stringIsAnyValue(text, "Y", "YES", "N", "NO"); } /** * Returns true if a given string contains at least one of the varargs (2nd parameter). * Note: Case insensitive comparison. * * @param text string to search * @param values varargs of type string containing values to compare * @return true if one of the varargs arguments was found in text */ private boolean stringIsAnyValue(String text, String... values) { // Cycle through the variable number of values and test each for (String val : values) { if (text.equalsIgnoreCase(val)) { return true; } } // no matches return false; } /* * Print a message on the screen, then accept input from Keyboard. * * @param text message to be displayed on screen. * @return what was typed by the player. */ private String displayTextAndGetInput(String text) { System.out.print(text); return kbScanner.next(); } }
coding-horror/basic-computer-games
69_Pizza/java/src/Pizza.java
44,887
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.net; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.Socket; import java.net.SocketException; import java.nio.charset.Charset; import javax.net.ServerSocketFactory; import javax.net.SocketFactory; /** * The SocketClient provides the basic operations that are required of * client objects accessing sockets. It is meant to be * subclassed to avoid having to rewrite the same code over and over again * to open a socket, close a socket, set timeouts, etc. Of special note * is the {@link #setSocketFactory setSocketFactory } * method, which allows you to control the type of Socket the SocketClient * creates for initiating network connections. This is especially useful * for adding SSL or proxy support as well as better support for applets. For * example, you could create a * {@link javax.net.SocketFactory} that * requests browser security capabilities before creating a socket. * All classes derived from SocketClient should use the * {@link #_socketFactory_ _socketFactory_ } member variable to * create Socket and ServerSocket instances rather than instantiating * them by directly invoking a constructor. By honoring this contract * you guarantee that a user will always be able to provide his own * Socket implementations by substituting his own SocketFactory. * @see SocketFactory */ public abstract class SocketClient { /** * The end of line character sequence used by most IETF protocols. That * is a carriage return followed by a newline: "\r\n" */ public static final String NETASCII_EOL = "\r\n"; /** The default SocketFactory shared by all SocketClient instances. */ private static final SocketFactory __DEFAULT_SOCKET_FACTORY = SocketFactory.getDefault(); /** The default {@link ServerSocketFactory} */ private static final ServerSocketFactory __DEFAULT_SERVER_SOCKET_FACTORY = ServerSocketFactory.getDefault(); /** * A ProtocolCommandSupport object used to manage the registering of * ProtocolCommandListeners and the firing of ProtocolCommandEvents. */ private ProtocolCommandSupport __commandSupport; /** The timeout to use after opening a socket. */ protected int _timeout_; /** The socket used for the connection. */ protected Socket _socket_; /** The hostname used for the connection (null = no hostname supplied). */ protected String _hostname_; /** The default port the client should connect to. */ protected int _defaultPort_; /** The socket's InputStream. */ protected InputStream _input_; /** The socket's OutputStream. */ protected OutputStream _output_; /** The socket's SocketFactory. */ protected SocketFactory _socketFactory_; /** The socket's ServerSocket Factory. */ protected ServerSocketFactory _serverSocketFactory_; /** The socket's connect timeout (0 = infinite timeout) */ private static final int DEFAULT_CONNECT_TIMEOUT = 0; protected int connectTimeout = DEFAULT_CONNECT_TIMEOUT; /** Hint for SO_RCVBUF size */ private int receiveBufferSize = -1; /** Hint for SO_SNDBUF size */ private int sendBufferSize = -1; /** The proxy to use when connecting. */ private Proxy connProxy; /** * Charset to use for byte IO. */ private Charset charset = Charset.defaultCharset(); /** * Default constructor for SocketClient. Initializes * _socket_ to null, _timeout_ to 0, _defaultPort to 0, * _isConnected_ to false, charset to {@code Charset.defaultCharset()} * and _socketFactory_ to a shared instance of * {@link org.apache.commons.net.DefaultSocketFactory}. */ public SocketClient() { _socket_ = null; _hostname_ = null; _input_ = null; _output_ = null; _timeout_ = 0; _defaultPort_ = 0; _socketFactory_ = __DEFAULT_SOCKET_FACTORY; _serverSocketFactory_ = __DEFAULT_SERVER_SOCKET_FACTORY; } /** * Because there are so many connect() methods, the _connectAction_() * method is provided as a means of performing some action immediately * after establishing a connection, rather than reimplementing all * of the connect() methods. The last action performed by every * connect() method after opening a socket is to call this method. * <p> * This method sets the timeout on the just opened socket to the default * timeout set by {@link #setDefaultTimeout setDefaultTimeout() }, * sets _input_ and _output_ to the socket's InputStream and OutputStream * respectively, and sets _isConnected_ to true. * <p> * Subclasses overriding this method should start by calling * <code> super._connectAction_() </code> first to ensure the * initialization of the aforementioned protected variables. * @throws IOException (SocketException) if a problem occurs with the socket */ protected void _connectAction_() throws IOException { _socket_.setSoTimeout(_timeout_); _input_ = _socket_.getInputStream(); _output_ = _socket_.getOutputStream(); } /** * Opens a Socket connected to a remote host at the specified port and * originating from the current host at a system assigned port. * Before returning, {@link #_connectAction_ _connectAction_() } * is called to perform connection initialization actions. * <p> * @param host The remote host. * @param port The port to connect to on the remote host. * @exception SocketException If the socket timeout could not be set. * @exception IOException If the socket could not be opened. In most * cases you will only want to catch IOException since SocketException is * derived from it. */ public void connect(InetAddress host, int port) throws SocketException, IOException { _hostname_ = null; _socket_ = _socketFactory_.createSocket(); if (receiveBufferSize != -1) { _socket_.setReceiveBufferSize(receiveBufferSize); } if (sendBufferSize != -1) { _socket_.setSendBufferSize(sendBufferSize); } _socket_.connect(new InetSocketAddress(host, port), connectTimeout); _connectAction_(); } /** * Opens a Socket connected to a remote host at the specified port and * originating from the current host at a system assigned port. * Before returning, {@link #_connectAction_ _connectAction_() } * is called to perform connection initialization actions. * <p> * @param hostname The name of the remote host. * @param port The port to connect to on the remote host. * @exception SocketException If the socket timeout could not be set. * @exception IOException If the socket could not be opened. In most * cases you will only want to catch IOException since SocketException is * derived from it. * @exception java.net.UnknownHostException If the hostname cannot be resolved. */ public void connect(String hostname, int port) throws SocketException, IOException { connect(InetAddress.getByName(hostname), port); _hostname_ = hostname; } /** * Opens a Socket connected to a remote host at the specified port and * originating from the specified local address and port. * Before returning, {@link #_connectAction_ _connectAction_() } * is called to perform connection initialization actions. * <p> * @param host The remote host. * @param port The port to connect to on the remote host. * @param localAddr The local address to use. * @param localPort The local port to use. * @exception SocketException If the socket timeout could not be set. * @exception IOException If the socket could not be opened. In most * cases you will only want to catch IOException since SocketException is * derived from it. */ public void connect(InetAddress host, int port, InetAddress localAddr, int localPort) throws SocketException, IOException { _hostname_ = null; _socket_ = _socketFactory_.createSocket(); if (receiveBufferSize != -1) { _socket_.setReceiveBufferSize(receiveBufferSize); } if (sendBufferSize != -1) { _socket_.setSendBufferSize(sendBufferSize); } _socket_.bind(new InetSocketAddress(localAddr, localPort)); _socket_.connect(new InetSocketAddress(host, port), connectTimeout); _connectAction_(); } /** * Opens a Socket connected to a remote host at the specified port and * originating from the specified local address and port. * Before returning, {@link #_connectAction_ _connectAction_() } * is called to perform connection initialization actions. * <p> * @param hostname The name of the remote host. * @param port The port to connect to on the remote host. * @param localAddr The local address to use. * @param localPort The local port to use. * @exception SocketException If the socket timeout could not be set. * @exception IOException If the socket could not be opened. In most * cases you will only want to catch IOException since SocketException is * derived from it. * @exception java.net.UnknownHostException If the hostname cannot be resolved. */ public void connect(String hostname, int port, InetAddress localAddr, int localPort) throws SocketException, IOException { connect(InetAddress.getByName(hostname), port, localAddr, localPort); _hostname_ = hostname; } /** * Opens a Socket connected to a remote host at the current default port * and originating from the current host at a system assigned port. * Before returning, {@link #_connectAction_ _connectAction_() } * is called to perform connection initialization actions. * <p> * @param host The remote host. * @exception SocketException If the socket timeout could not be set. * @exception IOException If the socket could not be opened. In most * cases you will only want to catch IOException since SocketException is * derived from it. */ public void connect(InetAddress host) throws SocketException, IOException { _hostname_ = null; connect(host, _defaultPort_); } /** * Opens a Socket connected to a remote host at the current default * port and originating from the current host at a system assigned port. * Before returning, {@link #_connectAction_ _connectAction_() } * is called to perform connection initialization actions. * <p> * @param hostname The name of the remote host. * @exception SocketException If the socket timeout could not be set. * @exception IOException If the socket could not be opened. In most * cases you will only want to catch IOException since SocketException is * derived from it. * @exception java.net.UnknownHostException If the hostname cannot be resolved. */ public void connect(String hostname) throws SocketException, IOException { connect(hostname, _defaultPort_); _hostname_ = hostname; } /** * Disconnects the socket connection. * You should call this method after you've finished using the class * instance and also before you call * {@link #connect connect() } * again. _isConnected_ is set to false, _socket_ is set to null, * _input_ is set to null, and _output_ is set to null. * <p> * @exception IOException If there is an error closing the socket. */ public void disconnect() throws IOException { closeQuietly(_socket_); closeQuietly(_input_); closeQuietly(_output_); _socket_ = null; _hostname_ = null; _input_ = null; _output_ = null; } private void closeQuietly(Socket socket) { if (socket != null){ try { socket.close(); } catch (IOException e) { // Ignored } } } private void closeQuietly(Closeable close){ if (close != null){ try { close.close(); } catch (IOException e) { // Ignored } } } /** * Returns true if the client is currently connected to a server. * <p> * Delegates to {@link Socket#isConnected()} * @return True if the client is currently connected to a server, * false otherwise. */ public boolean isConnected() { if (_socket_ == null) { return false; } return _socket_.isConnected(); } /** * Make various checks on the socket to test if it is available for use. * Note that the only sure test is to use it, but these checks may help * in some cases. * @see <a href="https://issues.apache.org/jira/browse/NET-350">NET-350</a> * @return {@code true} if the socket appears to be available for use * @since 3.0 */ public boolean isAvailable(){ if (isConnected()) { try { if (_socket_.getInetAddress() == null) { return false; } if (_socket_.getPort() == 0) { return false; } if (_socket_.getRemoteSocketAddress() == null) { return false; } if (_socket_.isClosed()) { return false; } /* these aren't exact checks (a Socket can be half-open), but since we usually require two-way data transfer, we check these here too: */ if (_socket_.isInputShutdown()) { return false; } if (_socket_.isOutputShutdown()) { return false; } /* ignore the result, catch exceptions: */ _socket_.getInputStream(); _socket_.getOutputStream(); } catch (IOException ioex) { return false; } return true; } else { return false; } } /** * Sets the default port the SocketClient should connect to when a port * is not specified. The {@link #_defaultPort_ _defaultPort_ } * variable stores this value. If never set, the default port is equal * to zero. * <p> * @param port The default port to set. */ public void setDefaultPort(int port) { _defaultPort_ = port; } /** * Returns the current value of the default port (stored in * {@link #_defaultPort_ _defaultPort_ }). * <p> * @return The current value of the default port. */ public int getDefaultPort() { return _defaultPort_; } /** * Set the default timeout in milliseconds to use when opening a socket. * This value is only used previous to a call to * {@link #connect connect()} * and should not be confused with {@link #setSoTimeout setSoTimeout()} * which operates on an the currently opened socket. _timeout_ contains * the new timeout value. * <p> * @param timeout The timeout in milliseconds to use for the socket * connection. */ public void setDefaultTimeout(int timeout) { _timeout_ = timeout; } /** * Returns the default timeout in milliseconds that is used when * opening a socket. * <p> * @return The default timeout in milliseconds that is used when * opening a socket. */ public int getDefaultTimeout() { return _timeout_; } /** * Set the timeout in milliseconds of a currently open connection. * Only call this method after a connection has been opened * by {@link #connect connect()}. * <p> * To set the initial timeout, use {@link #setDefaultTimeout(int)} instead. * * @param timeout The timeout in milliseconds to use for the currently * open socket connection. * @exception SocketException If the operation fails. * @throws NullPointerException if the socket is not currently open */ public void setSoTimeout(int timeout) throws SocketException { _socket_.setSoTimeout(timeout); } /** * Set the underlying socket send buffer size. * <p> * @param size The size of the buffer in bytes. * @throws SocketException never thrown, but subclasses might want to do so * @since 2.0 */ public void setSendBufferSize(int size) throws SocketException { sendBufferSize = size; } /** * Get the current sendBuffer size * @return the size, or -1 if not initialised * @since 3.0 */ protected int getSendBufferSize(){ return sendBufferSize; } /** * Sets the underlying socket receive buffer size. * <p> * @param size The size of the buffer in bytes. * @throws SocketException never (but subclasses may wish to do so) * @since 2.0 */ public void setReceiveBufferSize(int size) throws SocketException { receiveBufferSize = size; } /** * Get the current receivedBuffer size * @return the size, or -1 if not initialised * @since 3.0 */ protected int getReceiveBufferSize(){ return receiveBufferSize; } /** * Returns the timeout in milliseconds of the currently opened socket. * <p> * @return The timeout in milliseconds of the currently opened socket. * @exception SocketException If the operation fails. * @throws NullPointerException if the socket is not currently open */ public int getSoTimeout() throws SocketException { return _socket_.getSoTimeout(); } /** * Enables or disables the Nagle's algorithm (TCP_NODELAY) on the * currently opened socket. * <p> * @param on True if Nagle's algorithm is to be enabled, false if not. * @exception SocketException If the operation fails. * @throws NullPointerException if the socket is not currently open */ public void setTcpNoDelay(boolean on) throws SocketException { _socket_.setTcpNoDelay(on); } /** * Returns true if Nagle's algorithm is enabled on the currently opened * socket. * <p> * @return True if Nagle's algorithm is enabled on the currently opened * socket, false otherwise. * @exception SocketException If the operation fails. * @throws NullPointerException if the socket is not currently open */ public boolean getTcpNoDelay() throws SocketException { return _socket_.getTcpNoDelay(); } /** * Sets the SO_KEEPALIVE flag on the currently opened socket. * * From the Javadocs, the default keepalive time is 2 hours (although this is * implementation dependent). It looks as though the Windows WSA sockets implementation * allows a specific keepalive value to be set, although this seems not to be the case on * other systems. * @param keepAlive If true, keepAlive is turned on * @throws SocketException if there is a problem with the socket * @throws NullPointerException if the socket is not currently open * @since 2.2 */ public void setKeepAlive(boolean keepAlive) throws SocketException { _socket_.setKeepAlive(keepAlive); } /** * Returns the current value of the SO_KEEPALIVE flag on the currently opened socket. * Delegates to {@link Socket#getKeepAlive()} * @return True if SO_KEEPALIVE is enabled. * @throws SocketException if there is a problem with the socket * @throws NullPointerException if the socket is not currently open * @since 2.2 */ public boolean getKeepAlive() throws SocketException { return _socket_.getKeepAlive(); } /** * Sets the SO_LINGER timeout on the currently opened socket. * <p> * @param on True if linger is to be enabled, false if not. * @param val The linger timeout (in hundredths of a second?) * @exception SocketException If the operation fails. * @throws NullPointerException if the socket is not currently open */ public void setSoLinger(boolean on, int val) throws SocketException { _socket_.setSoLinger(on, val); } /** * Returns the current SO_LINGER timeout of the currently opened socket. * <p> * @return The current SO_LINGER timeout. If SO_LINGER is disabled returns * -1. * @exception SocketException If the operation fails. * @throws NullPointerException if the socket is not currently open */ public int getSoLinger() throws SocketException { return _socket_.getSoLinger(); } /** * Returns the port number of the open socket on the local host used * for the connection. * Delegates to {@link Socket#getLocalPort()} * <p> * @return The port number of the open socket on the local host used * for the connection. * @throws NullPointerException if the socket is not currently open */ public int getLocalPort() { return _socket_.getLocalPort(); } /** * Returns the local address to which the client's socket is bound. * Delegates to {@link Socket#getLocalAddress()} * <p> * @return The local address to which the client's socket is bound. * @throws NullPointerException if the socket is not currently open */ public InetAddress getLocalAddress() { return _socket_.getLocalAddress(); } /** * Returns the port number of the remote host to which the client is * connected. * Delegates to {@link Socket#getPort()} * <p> * @return The port number of the remote host to which the client is * connected. * @throws NullPointerException if the socket is not currently open */ public int getRemotePort() { return _socket_.getPort(); } /** * @return The remote address to which the client is connected. * Delegates to {@link Socket#getInetAddress()} * @throws NullPointerException if the socket is not currently open */ public InetAddress getRemoteAddress() { return _socket_.getInetAddress(); } /** * Verifies that the remote end of the given socket is connected to the * the same host that the SocketClient is currently connected to. This * is useful for doing a quick security check when a client needs to * accept a connection from a server, such as an FTP data connection or * a BSD R command standard error stream. * <p> * @param socket the item to check against * @return True if the remote hosts are the same, false if not. */ public boolean verifyRemote(Socket socket) { InetAddress host1, host2; host1 = socket.getInetAddress(); host2 = getRemoteAddress(); return host1.equals(host2); } /** * Sets the SocketFactory used by the SocketClient to open socket * connections. If the factory value is null, then a default * factory is used (only do this to reset the factory after having * previously altered it). * Any proxy setting is discarded. * <p> * @param factory The new SocketFactory the SocketClient should use. */ public void setSocketFactory(SocketFactory factory) { if (factory == null) { _socketFactory_ = __DEFAULT_SOCKET_FACTORY; } else { _socketFactory_ = factory; } // re-setting the socket factory makes the proxy setting useless, // so set the field to null so that getProxy() doesn't return a // Proxy that we're actually not using. connProxy = null; } /** * Sets the ServerSocketFactory used by the SocketClient to open ServerSocket * connections. If the factory value is null, then a default * factory is used (only do this to reset the factory after having * previously altered it). * <p> * @param factory The new ServerSocketFactory the SocketClient should use. * @since 2.0 */ public void setServerSocketFactory(ServerSocketFactory factory) { if (factory == null) { _serverSocketFactory_ = __DEFAULT_SERVER_SOCKET_FACTORY; } else { _serverSocketFactory_ = factory; } } /** * Sets the connection timeout in milliseconds, which will be passed to the {@link Socket} object's * connect() method. * @param connectTimeout The connection timeout to use (in ms) * @since 2.0 */ public void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; } /** * Get the underlying socket connection timeout. * @return timeout (in ms) * @since 2.0 */ public int getConnectTimeout() { return connectTimeout; } /** * Get the underlying {@link ServerSocketFactory} * @return The server socket factory * @since 2.2 */ public ServerSocketFactory getServerSocketFactory() { return _serverSocketFactory_; } /** * Adds a ProtocolCommandListener. * * @param listener The ProtocolCommandListener to add. * @since 3.0 */ public void addProtocolCommandListener(ProtocolCommandListener listener) { getCommandSupport().addProtocolCommandListener(listener); } /** * Removes a ProtocolCommandListener. * * @param listener The ProtocolCommandListener to remove. * @since 3.0 */ public void removeProtocolCommandListener(ProtocolCommandListener listener) { getCommandSupport().removeProtocolCommandListener(listener); } /** * If there are any listeners, send them the reply details. * * @param replyCode the code extracted from the reply * @param reply the full reply text * @since 3.0 */ protected void fireReplyReceived(int replyCode, String reply) { if (getCommandSupport().getListenerCount() > 0) { getCommandSupport().fireReplyReceived(replyCode, reply); } } /** * If there are any listeners, send them the command details. * * @param command the command name * @param message the complete message, including command name * @since 3.0 */ protected void fireCommandSent(String command, String message) { if (getCommandSupport().getListenerCount() > 0) { getCommandSupport().fireCommandSent(command, message); } } /** * Create the CommandSupport instance if required */ protected void createCommandSupport(){ __commandSupport = new ProtocolCommandSupport(this); } /** * Subclasses can override this if they need to provide their own * instance field for backwards compatibility. * * @return the CommandSupport instance, may be {@code null} * @since 3.0 */ protected ProtocolCommandSupport getCommandSupport() { return __commandSupport; } /** * Sets the proxy for use with all the connections. * The proxy is used for connections established after the * call to this method. * * @param proxy the new proxy for connections. * @since 3.2 */ public void setProxy(Proxy proxy) { setSocketFactory(new DefaultSocketFactory(proxy)); connProxy = proxy; } /** * Gets the proxy for use with all the connections. * @return the current proxy for connections. */ public Proxy getProxy() { return connProxy; } /** * Gets the charset name. * * @return the charset. * @since 3.3 * @deprecated Since the code now requires Java 1.6 as a mininmum */ @Deprecated public String getCharsetName() { return charset.name(); } /** * Gets the charset. * * @return the charset. * @since 3.3 */ public Charset getCharset() { return charset; } /** * Sets the charset. * * @param charset the charset. * @since 3.3 */ public void setCharset(Charset charset) { this.charset = charset; } /* * N.B. Fields cannot be pulled up into a super-class without breaking binary compatibility, * so the abstract method is needed to pass the instance to the methods which were moved here. */ }
alibaba/arthas
client/src/main/java/org/apache/commons/net/SocketClient.java
44,888
/* * Copyright (c) 2011-2019 Contributors to the Eclipse Foundation * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 * which is available at https://www.apache.org/licenses/LICENSE-2.0. * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 */ package io.vertx.core.net; import io.vertx.codegen.annotations.DataObject; import io.vertx.codegen.annotations.GenIgnore; import io.vertx.codegen.json.annotations.JsonGen; import io.vertx.core.buffer.Buffer; import io.vertx.core.json.JsonObject; import io.netty.handler.logging.ByteBufFormat; import java.util.*; import java.util.concurrent.TimeUnit; /** * Base class. TCP and SSL related options * * @author <a href="http://tfox.org">Tim Fox</a> */ @DataObject @JsonGen(publicConverter = false) public abstract class TCPSSLOptions extends NetworkOptions { /** * The default value of TCP-no-delay = true (Nagle disabled) */ public static final boolean DEFAULT_TCP_NO_DELAY = true; /** * The default value of TCP keep alive = false */ public static final boolean DEFAULT_TCP_KEEP_ALIVE = false; /** * The default value of SO_linger = -1 */ public static final int DEFAULT_SO_LINGER = -1; /** * SSL enable by default = false */ public static final boolean DEFAULT_SSL = false; /** * Default idle timeout = 0 */ public static final int DEFAULT_IDLE_TIMEOUT = 0; /** * Default idle time unit = SECONDS */ public static final TimeUnit DEFAULT_IDLE_TIMEOUT_TIME_UNIT = TimeUnit.SECONDS; /** * Default read idle timeout = 0 */ public static final int DEFAULT_READ_IDLE_TIMEOUT = 0; /** * Default write idle timeout = 0 */ public static final int DEFAULT_WRITE_IDLE_TIMEOUT = 0; /** * The default SSL engine options = null (autoguess) */ public static final SSLEngineOptions DEFAULT_SSL_ENGINE = null; /** * The default TCP_FASTOPEN value = false */ public static final boolean DEFAULT_TCP_FAST_OPEN = false; /** * The default TCP_CORK value = false */ public static final boolean DEFAULT_TCP_CORK = false; /** * The default TCP_QUICKACK value = false */ public static final boolean DEFAULT_TCP_QUICKACK = false; /** * The default TCP_USER_TIMEOUT value in milliseconds = 0 * <p/> * When the default value of 0 is used, TCP will use the system default. */ public static final int DEFAULT_TCP_USER_TIMEOUT = 0; private boolean tcpNoDelay; private boolean tcpKeepAlive; private int soLinger; private int idleTimeout; private int readIdleTimeout; private int writeIdleTimeout; private TimeUnit idleTimeoutUnit; private boolean ssl; private SSLEngineOptions sslEngineOptions; private SSLOptions sslOptions; private boolean tcpFastOpen; private boolean tcpCork; private boolean tcpQuickAck; private int tcpUserTimeout; private Set<String> enabledCipherSuites; private List<String> crlPaths; private List<Buffer> crlValues; /** * Default constructor */ public TCPSSLOptions() { super(); init(); } /** * Copy constructor * * @param other the options to copy */ public TCPSSLOptions(TCPSSLOptions other) { super(other); this.tcpNoDelay = other.isTcpNoDelay(); this.tcpKeepAlive = other.isTcpKeepAlive(); this.soLinger = other.getSoLinger(); this.idleTimeout = other.getIdleTimeout(); this.idleTimeoutUnit = other.getIdleTimeoutUnit() != null ? other.getIdleTimeoutUnit() : DEFAULT_IDLE_TIMEOUT_TIME_UNIT; this.readIdleTimeout = other.getReadIdleTimeout(); this.writeIdleTimeout = other.getWriteIdleTimeout(); this.ssl = other.isSsl(); this.sslEngineOptions = other.sslEngineOptions != null ? other.sslEngineOptions.copy() : null; this.tcpFastOpen = other.isTcpFastOpen(); this.tcpCork = other.isTcpCork(); this.tcpQuickAck = other.isTcpQuickAck(); this.tcpUserTimeout = other.getTcpUserTimeout(); SSLOptions sslOptions = other.sslOptions; if (sslOptions != null) { this.sslOptions = sslOptions.copy(); if (this.sslOptions != null) { enabledCipherSuites = this.sslOptions.enabledCipherSuites; crlPaths = this.sslOptions.crlPaths; crlValues = this.sslOptions.crlValues; } } } /** * Create options from JSON * * @param json the JSON */ public TCPSSLOptions(JsonObject json) { super(json); init(); TCPSSLOptionsConverter.fromJson(json ,this); // Legacy if (json.containsKey("pemKeyCertOptions")) { setKeyCertOptions(new PemKeyCertOptions(json.getJsonObject("pemKeyCertOptions"))); } else if (json.containsKey("keyStoreOptions")) { setKeyCertOptions(new JksOptions(json.getJsonObject("keyStoreOptions"))); } else if (json.containsKey("pfxKeyCertOptions")) { setKeyCertOptions(new PfxOptions(json.getJsonObject("pfxKeyCertOptions"))); } if (json.containsKey("pemTrustOptions")) { setTrustOptions(new PemTrustOptions(json.getJsonObject("pemTrustOptions"))); } else if (json.containsKey("pfxTrustOptions")) { setTrustOptions(new PfxOptions(json.getJsonObject("pfxTrustOptions"))); } else if (json.containsKey("trustStoreOptions")) { setTrustOptions(new JksOptions(json.getJsonObject("trustStoreOptions"))); } if (json.containsKey("jdkSslEngineOptions")) { setSslEngineOptions(new JdkSSLEngineOptions(json.getJsonObject("jdkSslEngineOptions"))); } else if (json.containsKey("openSslEngineOptions")) { setSslEngineOptions(new OpenSSLEngineOptions(json.getJsonObject("openSslEngineOptions"))); } } /** * Convert to JSON * * @return the JSON */ public JsonObject toJson() { JsonObject json = super.toJson(); TCPSSLOptionsConverter.toJson(this, json); if (sslOptions != null) { KeyCertOptions keyCertOptions = sslOptions.getKeyCertOptions(); if (keyCertOptions != null) { if (keyCertOptions instanceof PemKeyCertOptions) { json.put("pemKeyCertOptions", ((PemKeyCertOptions) keyCertOptions).toJson()); } else if (keyCertOptions instanceof JksOptions) { json.put("keyStoreOptions", ((JksOptions) keyCertOptions).toJson()); } else if (keyCertOptions instanceof PfxOptions) { json.put("pfxKeyCertOptions", ((PfxOptions) keyCertOptions).toJson()); } } TrustOptions trustOptions = sslOptions.getTrustOptions(); if (trustOptions instanceof PemTrustOptions) { json.put("pemTrustOptions", ((PemTrustOptions) trustOptions).toJson()); } else if (trustOptions instanceof PfxOptions) { json.put("pfxTrustOptions", ((PfxOptions) trustOptions).toJson()); } else if (trustOptions instanceof JksOptions) { json.put("trustStoreOptions", ((JksOptions) trustOptions).toJson()); } } SSLEngineOptions engineOptions = sslEngineOptions; if (engineOptions != null) { if (engineOptions instanceof JdkSSLEngineOptions) { json.put("jdkSslEngineOptions", ((JdkSSLEngineOptions) engineOptions).toJson()); } else if (engineOptions instanceof OpenSSLEngineOptions) { json.put("openSslEngineOptions", ((OpenSSLEngineOptions) engineOptions).toJson()); } } return json; } private void init() { tcpNoDelay = DEFAULT_TCP_NO_DELAY; tcpKeepAlive = DEFAULT_TCP_KEEP_ALIVE; soLinger = DEFAULT_SO_LINGER; idleTimeout = DEFAULT_IDLE_TIMEOUT; readIdleTimeout = DEFAULT_READ_IDLE_TIMEOUT; writeIdleTimeout = DEFAULT_WRITE_IDLE_TIMEOUT; idleTimeoutUnit = DEFAULT_IDLE_TIMEOUT_TIME_UNIT; ssl = DEFAULT_SSL; sslEngineOptions = DEFAULT_SSL_ENGINE; tcpFastOpen = DEFAULT_TCP_FAST_OPEN; tcpCork = DEFAULT_TCP_CORK; tcpQuickAck = DEFAULT_TCP_QUICKACK; tcpUserTimeout = DEFAULT_TCP_USER_TIMEOUT; sslOptions = null; } protected SSLOptions getOrCreateSSLOptions() { if (sslOptions == null) { sslOptions = this instanceof ClientOptionsBase ? new ClientSSLOptions() : new ServerSSLOptions(); // Necessary hacks because we return lazy created collections so we need to care about that if (enabledCipherSuites != null) { sslOptions.enabledCipherSuites = enabledCipherSuites; } else { enabledCipherSuites = sslOptions.enabledCipherSuites; } if (crlPaths != null) { sslOptions.crlPaths = crlPaths; } else { crlPaths = sslOptions.crlPaths; } if (crlValues != null) { sslOptions.crlValues = crlValues; } else { crlValues = sslOptions.crlValues; } } return sslOptions; } @GenIgnore public SSLOptions getSslOptions() { return sslOptions; } /** * @return TCP no delay enabled ? */ public boolean isTcpNoDelay() { return tcpNoDelay; } /** * Set whether TCP no delay is enabled * * @param tcpNoDelay true if TCP no delay is enabled (Nagle disabled) * @return a reference to this, so the API can be used fluently */ public TCPSSLOptions setTcpNoDelay(boolean tcpNoDelay) { this.tcpNoDelay = tcpNoDelay; return this; } /** * @return is TCP keep alive enabled? */ public boolean isTcpKeepAlive() { return tcpKeepAlive; } /** * Set whether TCP keep alive is enabled * * @param tcpKeepAlive true if TCP keep alive is enabled * @return a reference to this, so the API can be used fluently */ public TCPSSLOptions setTcpKeepAlive(boolean tcpKeepAlive) { this.tcpKeepAlive = tcpKeepAlive; return this; } /** * * @return is SO_linger enabled */ public int getSoLinger() { return soLinger; } /** * Set whether SO_linger keep alive is enabled * * @param soLinger true if SO_linger is enabled * @return a reference to this, so the API can be used fluently */ public TCPSSLOptions setSoLinger(int soLinger) { if (soLinger < 0 && soLinger != DEFAULT_SO_LINGER) { throw new IllegalArgumentException("soLinger must be >= 0"); } this.soLinger = soLinger; return this; } /** * Set the idle timeout, default time unit is seconds. Zero means don't timeout. * This determines if a connection will timeout and be closed if no data is received nor sent within the timeout. * * If you want change default time unit, use {@link #setIdleTimeoutUnit(TimeUnit)} * * @param idleTimeout the timeout * @return a reference to this, so the API can be used fluently */ public TCPSSLOptions setIdleTimeout(int idleTimeout) { if (idleTimeout < 0) { throw new IllegalArgumentException("idleTimeout must be >= 0"); } this.idleTimeout = idleTimeout; return this; } /** * @return the idle timeout, in time unit specified by {@link #getIdleTimeoutUnit()}. */ public int getIdleTimeout() { return idleTimeout; } /** * Set the read idle timeout, default time unit is seconds. Zero means don't timeout. * This determines if a connection will timeout and be closed if no data is received within the timeout. * * If you want change default time unit, use {@link #setIdleTimeoutUnit(TimeUnit)} * * @param idleTimeout the read timeout * @return a reference to this, so the API can be used fluently */ public TCPSSLOptions setReadIdleTimeout(int idleTimeout) { if (idleTimeout < 0) { throw new IllegalArgumentException("readIdleTimeout must be >= 0"); } this.readIdleTimeout = idleTimeout; return this; } /** * @return the read idle timeout, in time unit specified by {@link #getIdleTimeoutUnit()}. */ public int getReadIdleTimeout() { return readIdleTimeout; } /** * Set the write idle timeout, default time unit is seconds. Zero means don't timeout. * This determines if a connection will timeout and be closed if no data is sent within the timeout. * * If you want change default time unit, use {@link #setIdleTimeoutUnit(TimeUnit)} * * @param idleTimeout the write timeout * @return a reference to this, so the API can be used fluently */ public TCPSSLOptions setWriteIdleTimeout(int idleTimeout) { if (idleTimeout < 0) { throw new IllegalArgumentException("writeIdleTimeout must be >= 0"); } this.writeIdleTimeout = idleTimeout; return this; } /** * @return the write idle timeout, in time unit specified by {@link #getIdleTimeoutUnit()}. */ public int getWriteIdleTimeout() { return writeIdleTimeout; } /** * Set the idle timeout unit. If not specified, default is seconds. * * @param idleTimeoutUnit specify time unit. * @return a reference to this, so the API can be used fluently */ public TCPSSLOptions setIdleTimeoutUnit(TimeUnit idleTimeoutUnit) { this.idleTimeoutUnit = idleTimeoutUnit; return this; } /** * @return the idle timeout unit. */ public TimeUnit getIdleTimeoutUnit() { return idleTimeoutUnit; } /** * * @return is SSL/TLS enabled? */ public boolean isSsl() { return ssl; } /** * Set whether SSL/TLS is enabled * * @param ssl true if enabled * @return a reference to this, so the API can be used fluently */ public TCPSSLOptions setSsl(boolean ssl) { this.ssl = ssl; return this; } /** * @return the key/cert options */ @GenIgnore public KeyCertOptions getKeyCertOptions() { SSLOptions o = sslOptions; return o != null ? o.getKeyCertOptions() : null; } /** * Set the key/cert options. * * @param options the key store options * @return a reference to this, so the API can be used fluently */ @GenIgnore public TCPSSLOptions setKeyCertOptions(KeyCertOptions options) { getOrCreateSSLOptions().setKeyCertOptions(options); return this; } /** * @return the trust options */ public TrustOptions getTrustOptions() { SSLOptions o = sslOptions; return o != null ? o.getTrustOptions() : null; } /** * Set the trust options. * @param options the trust options * @return a reference to this, so the API can be used fluently */ public TCPSSLOptions setTrustOptions(TrustOptions options) { getOrCreateSSLOptions().setTrustOptions(options); return this; } /** * Add an enabled cipher suite, appended to the ordered suites. * * @param suite the suite * @return a reference to this, so the API can be used fluently * @see #getEnabledCipherSuites() */ public TCPSSLOptions addEnabledCipherSuite(String suite) { getOrCreateSSLOptions().addEnabledCipherSuite(suite); return this; } /** * Removes an enabled cipher suite from the ordered suites. * * @param suite the suite * @return a reference to this, so the API can be used fluently */ public TCPSSLOptions removeEnabledCipherSuite(String suite) { getOrCreateSSLOptions().removeEnabledCipherSuite(suite); return this; } /** * Return an ordered set of the cipher suites. * * <p> The set is initially empty and suite should be added to this set in the desired order. * * <p> When suites are added and therefore the list is not empty, it takes precedence over the * default suite defined by the {@link SSLEngineOptions} in use. * * @return the enabled cipher suites */ public Set<String> getEnabledCipherSuites() { if (enabledCipherSuites == null) { enabledCipherSuites = new LinkedHashSet<>(); } return enabledCipherSuites; } /** * * @return the CRL (Certificate revocation list) paths */ public List<String> getCrlPaths() { if (crlPaths == null) { crlPaths = new ArrayList<>(); } return crlPaths; } /** * Add a CRL path * @param crlPath the path * @return a reference to this, so the API can be used fluently * @throws NullPointerException */ public TCPSSLOptions addCrlPath(String crlPath) throws NullPointerException { getOrCreateSSLOptions().addCrlPath(crlPath); return this; } /** * Get the CRL values * * @return the list of values */ public List<Buffer> getCrlValues() { if (crlValues == null) { crlValues = new ArrayList<>(); } return crlValues; } /** * Add a CRL value * * @param crlValue the value * @return a reference to this, so the API can be used fluently * @throws NullPointerException */ public TCPSSLOptions addCrlValue(Buffer crlValue) throws NullPointerException { getOrCreateSSLOptions().addCrlValue(crlValue); return this; } /** * @return whether to use or not Application-Layer Protocol Negotiation */ public boolean isUseAlpn() { SSLOptions o = sslOptions; return o != null && o.isUseAlpn(); } /** * Set the ALPN usage. * * @param useAlpn true when Application-Layer Protocol Negotiation should be used */ public TCPSSLOptions setUseAlpn(boolean useAlpn) { getOrCreateSSLOptions().setUseAlpn(useAlpn); return this; } /** * @return the SSL engine implementation to use */ public SSLEngineOptions getSslEngineOptions() { return sslEngineOptions; } /** * Set to use SSL engine implementation to use. * * @param sslEngineOptions the ssl engine to use * @return a reference to this, so the API can be used fluently */ public TCPSSLOptions setSslEngineOptions(SSLEngineOptions sslEngineOptions) { this.sslEngineOptions = sslEngineOptions; return this; } /** * Sets the list of enabled SSL/TLS protocols. * * @param enabledSecureTransportProtocols the SSL/TLS protocols to enable * @return a reference to this, so the API can be used fluently */ public TCPSSLOptions setEnabledSecureTransportProtocols(Set<String> enabledSecureTransportProtocols) { getOrCreateSSLOptions().setEnabledSecureTransportProtocols(enabledSecureTransportProtocols); return this; } /** * Add an enabled SSL/TLS protocols, appended to the ordered protocols. * * @param protocol the SSL/TLS protocol to enable * @return a reference to this, so the API can be used fluently */ public TCPSSLOptions addEnabledSecureTransportProtocol(String protocol) { getOrCreateSSLOptions().addEnabledSecureTransportProtocol(protocol); return this; } /** * Removes an enabled SSL/TLS protocol from the ordered protocols. * * @param protocol the SSL/TLS protocol to disable * @return a reference to this, so the API can be used fluently */ public TCPSSLOptions removeEnabledSecureTransportProtocol(String protocol) { getOrCreateSSLOptions().removeEnabledSecureTransportProtocol(protocol); return this; } /** * @return wether {@code TCP_FASTOPEN} option is enabled */ public boolean isTcpFastOpen() { return tcpFastOpen; } /** * Enable the {@code TCP_FASTOPEN} option - only with linux native transport. * * @param tcpFastOpen the fast open value */ public TCPSSLOptions setTcpFastOpen(boolean tcpFastOpen) { this.tcpFastOpen = tcpFastOpen; return this; } /** * @return wether {@code TCP_CORK} option is enabled */ public boolean isTcpCork() { return tcpCork; } /** * Enable the {@code TCP_CORK} option - only with linux native transport. * * @param tcpCork the cork value */ public TCPSSLOptions setTcpCork(boolean tcpCork) { this.tcpCork = tcpCork; return this; } /** * @return wether {@code TCP_QUICKACK} option is enabled */ public boolean isTcpQuickAck() { return tcpQuickAck; } /** * Enable the {@code TCP_QUICKACK} option - only with linux native transport. * * @param tcpQuickAck the quick ack value */ public TCPSSLOptions setTcpQuickAck(boolean tcpQuickAck) { this.tcpQuickAck = tcpQuickAck; return this; } /** * * @return the {@code TCP_USER_TIMEOUT} value */ public int getTcpUserTimeout() { return tcpUserTimeout; } /** * Sets the {@code TCP_USER_TIMEOUT} option - only with linux native transport. * * @param tcpUserTimeout the tcp user timeout value */ public TCPSSLOptions setTcpUserTimeout(int tcpUserTimeout) { this.tcpUserTimeout = tcpUserTimeout; return this; } /** * Returns the enabled SSL/TLS protocols * @return the enabled protocols */ public Set<String> getEnabledSecureTransportProtocols() { SSLOptions o = sslOptions; return o != null ? o.getEnabledSecureTransportProtocols() : new LinkedHashSet<>(SSLOptions.DEFAULT_ENABLED_SECURE_TRANSPORT_PROTOCOLS); } /** * @return the SSL handshake timeout, in time unit specified by {@link #getSslHandshakeTimeoutUnit()}. */ public long getSslHandshakeTimeout() { SSLOptions o = sslOptions; return o != null ? o.getSslHandshakeTimeout() : SSLOptions.DEFAULT_SSL_HANDSHAKE_TIMEOUT; } /** * Set the SSL handshake timeout, default time unit is seconds. * * @param sslHandshakeTimeout the SSL handshake timeout to set, in milliseconds * @return a reference to this, so the API can be used fluently */ public TCPSSLOptions setSslHandshakeTimeout(long sslHandshakeTimeout) { getOrCreateSSLOptions().setSslHandshakeTimeout(sslHandshakeTimeout); return this; } /** * Set the SSL handshake timeout unit. If not specified, default is seconds. * * @param sslHandshakeTimeoutUnit specify time unit. * @return a reference to this, so the API can be used fluently */ public TCPSSLOptions setSslHandshakeTimeoutUnit(TimeUnit sslHandshakeTimeoutUnit) { getOrCreateSSLOptions().setSslHandshakeTimeoutUnit(sslHandshakeTimeoutUnit); return this; } /** * @return the SSL handshake timeout unit. */ public TimeUnit getSslHandshakeTimeoutUnit() { SSLOptions o = sslOptions; return o != null ? o.getSslHandshakeTimeoutUnit() : SSLOptions.DEFAULT_SSL_HANDSHAKE_TIMEOUT_TIME_UNIT; } @Override public TCPSSLOptions setLogActivity(boolean logEnabled) { return (TCPSSLOptions) super.setLogActivity(logEnabled); } @Override public TCPSSLOptions setActivityLogDataFormat(ByteBufFormat activityLogDataFormat) { return (TCPSSLOptions) super.setActivityLogDataFormat(activityLogDataFormat); } @Override public TCPSSLOptions setSendBufferSize(int sendBufferSize) { return (TCPSSLOptions) super.setSendBufferSize(sendBufferSize); } @Override public TCPSSLOptions setReceiveBufferSize(int receiveBufferSize) { return (TCPSSLOptions) super.setReceiveBufferSize(receiveBufferSize); } @Override public TCPSSLOptions setReuseAddress(boolean reuseAddress) { return (TCPSSLOptions) super.setReuseAddress(reuseAddress); } @Override public TCPSSLOptions setTrafficClass(int trafficClass) { return (TCPSSLOptions) super.setTrafficClass(trafficClass); } @Override public TCPSSLOptions setReusePort(boolean reusePort) { return (TCPSSLOptions) super.setReusePort(reusePort); } }
eclipse-vertx/vert.x
src/main/java/io/vertx/core/net/TCPSSLOptions.java
44,889
package cn.hutool.http; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.convert.Convert; import cn.hutool.core.io.IORuntimeException; import cn.hutool.core.io.resource.BytesResource; import cn.hutool.core.io.resource.FileResource; import cn.hutool.core.io.resource.MultiFileResource; import cn.hutool.core.io.resource.Resource; import cn.hutool.core.lang.Assert; import cn.hutool.core.map.MapUtil; import cn.hutool.core.map.TableMap; import cn.hutool.core.net.SSLUtil; import cn.hutool.core.net.url.UrlBuilder; import cn.hutool.core.net.url.UrlQuery; import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.http.body.FormUrlEncodedBody; import cn.hutool.http.body.MultipartBody; import cn.hutool.http.body.RequestBody; import cn.hutool.http.body.ResourceBody; import cn.hutool.http.cookie.GlobalCookieManager; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSocketFactory; import java.io.File; import java.io.IOException; import java.net.*; import java.nio.charset.Charset; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; /** * http请求类<br> * Http请求类用于构建Http请求并同步获取结果,此类通过CookieManager持有域名对应的Cookie值,再次请求时会自动附带Cookie信息 * * @author Looly */ public class HttpRequest extends HttpBase<HttpRequest> { // ---------------------------------------------------------------- static Http Method start /** * POST请求 * * @param url URL * @return HttpRequest */ public static HttpRequest post(String url) { return of(url).method(Method.POST); } /** * GET请求 * * @param url URL * @return HttpRequest */ public static HttpRequest get(String url) { return of(url).method(Method.GET); } /** * HEAD请求 * * @param url URL * @return HttpRequest */ public static HttpRequest head(String url) { return of(url).method(Method.HEAD); } /** * OPTIONS请求 * * @param url URL * @return HttpRequest */ public static HttpRequest options(String url) { return of(url).method(Method.OPTIONS); } /** * PUT请求 * * @param url URL * @return HttpRequest */ public static HttpRequest put(String url) { return of(url).method(Method.PUT); } /** * PATCH请求 * * @param url URL * @return HttpRequest * @since 3.0.9 */ public static HttpRequest patch(String url) { return of(url).method(Method.PATCH); } /** * DELETE请求 * * @param url URL * @return HttpRequest */ public static HttpRequest delete(String url) { return of(url).method(Method.DELETE); } /** * TRACE请求 * * @param url URL * @return HttpRequest */ public static HttpRequest trace(String url) { return of(url).method(Method.TRACE); } /** * 构建一个HTTP请求<br> * 对于传入的URL,可以自定义是否解码已经编码的内容,设置见{@link HttpGlobalConfig#setDecodeUrl(boolean)}<br> * 在构建Http请求时,用户传入的URL可能有编码后和未编码的内容混合在一起,如果{@link HttpGlobalConfig#isDecodeUrl()}为{@code true},则会统一解码编码后的参数,<br> * 按照RFC3986规范,在发送请求时,全部编码之。如果为{@code false},则不会解码已经编码的内容,在请求时只编码需要编码的部分。 * * @param url URL链接,默认自动编码URL中的参数等信息 * @return HttpRequest * @since 5.7.18 */ public static HttpRequest of(String url) { return of(url, HttpGlobalConfig.isDecodeUrl() ? DEFAULT_CHARSET : null); } /** * 构建一个HTTP请求<br> * 对于传入的URL,可以自定义是否解码已经编码的内容。<br> * 在构建Http请求时,用户传入的URL可能有编码后和未编码的内容混合在一起,如果charset参数不为{@code null},则会统一解码编码后的参数,<br> * 按照RFC3986规范,在发送请求时,全部编码之。如果为{@code false},则不会解码已经编码的内容,在请求时只编码需要编码的部分。 * * @param url URL链接 * @param charset 编码,如果为{@code null}不自动解码编码URL * @return HttpRequest * @since 5.7.18 */ public static HttpRequest of(String url, Charset charset) { return of(UrlBuilder.ofHttp(url, charset)); } /** * 构建一个HTTP请求<br> * * @param url {@link UrlBuilder} * @return HttpRequest * @since 5.8.0 */ public static HttpRequest of(UrlBuilder url) { return new HttpRequest(url); } /** * 设置全局默认的连接和读取超时时长 * * @param customTimeout 超时时长 * @see HttpGlobalConfig#setTimeout(int) * @since 4.6.2 */ public static void setGlobalTimeout(int customTimeout) { HttpGlobalConfig.setTimeout(customTimeout); } /** * 获取Cookie管理器,用于自定义Cookie管理 * * @return {@link CookieManager} * @see GlobalCookieManager#getCookieManager() * @since 4.1.0 */ public static CookieManager getCookieManager() { return GlobalCookieManager.getCookieManager(); } /** * 自定义{@link CookieManager} * * @param customCookieManager 自定义的{@link CookieManager} * @see GlobalCookieManager#setCookieManager(CookieManager) * @since 4.5.14 */ public static void setCookieManager(CookieManager customCookieManager) { GlobalCookieManager.setCookieManager(customCookieManager); } /** * 关闭Cookie * * @see GlobalCookieManager#setCookieManager(CookieManager) * @since 4.1.9 */ public static void closeCookie() { GlobalCookieManager.setCookieManager(null); } // ---------------------------------------------------------------- static Http Method end private HttpConfig config = HttpConfig.create(); private UrlBuilder url; private URLStreamHandler urlHandler; private Method method = Method.GET; /** * 连接对象 */ private HttpConnection httpConnection; /** * 存储表单数据 */ private Map<String, Object> form; /** * Cookie */ private String cookie; /** * 是否为Multipart表单 */ private boolean isMultiPart; /** * 是否是REST请求模式 */ private boolean isRest; /** * 重定向次数计数器,内部使用 */ private int redirectCount; /** * 构造,URL编码默认使用UTF-8 * * @param url URL * @deprecated 请使用 {@link #of(String)} */ @Deprecated public HttpRequest(String url) { this(UrlBuilder.ofHttp(url)); } /** * 构造 * * @param url {@link UrlBuilder} */ public HttpRequest(UrlBuilder url) { this.url = Assert.notNull(url, "URL must be not null!"); // 给定默认URL编码 final Charset charset = url.getCharset(); if (null != charset) { this.charset(charset); } // 给定一个默认头信息 this.header(GlobalHeaders.INSTANCE.headers); } /** * 获取请求URL * * @return URL字符串 * @since 4.1.8 */ public String getUrl() { return url.toString(); } /** * 设置URL * * @param url url字符串 * @return this * @since 4.1.8 */ public HttpRequest setUrl(String url) { return setUrl(UrlBuilder.ofHttp(url, this.charset)); } /** * 设置URL * * @param urlBuilder url字符串 * @return this * @since 5.3.1 */ public HttpRequest setUrl(UrlBuilder urlBuilder) { this.url = urlBuilder; return this; } /** * 设置{@link URLStreamHandler} * <p> * 部分环境下需要单独设置此项,例如当 WebLogic Server 实例充当 SSL 客户端角色(它会尝试通过 SSL 连接到其他服务器或应用程序)时,<br> * 它会验证 SSL 服务器在数字证书中返回的主机名是否与用于连接 SSL 服务器的 URL 主机名相匹配。如果主机名不匹配,则删除此连接。<br> * 因此weblogic不支持https的sni协议的主机名验证,此时需要将此值设置为sun.net.www.protocol.https.Handler对象。 * <p> * 相关issue见:<a href="https://gitee.com/dromara/hutool/issues/IMD1X">https://gitee.com/dromara/hutool/issues/IMD1X</a> * * @param urlHandler {@link URLStreamHandler} * @return this * @since 4.1.9 */ public HttpRequest setUrlHandler(URLStreamHandler urlHandler) { this.urlHandler = urlHandler; return this; } /** * 获取Http请求方法 * * @return {@link Method} * @since 4.1.8 */ public Method getMethod() { return this.method; } /** * 设置请求方法 * * @param method HTTP方法 * @return HttpRequest * @see #method(Method) * @since 4.1.8 */ public HttpRequest setMethod(Method method) { return method(method); } /** * 获取{@link HttpConnection}<br> * 在{@link #execute()} 执行前此对象为null * * @return {@link HttpConnection} * @since 4.2.2 */ public HttpConnection getConnection() { return this.httpConnection; } /** * 设置请求方法 * * @param method HTTP方法 * @return HttpRequest */ public HttpRequest method(Method method) { this.method = method; return this; } // ---------------------------------------------------------------- Http Request Header start /** * 设置contentType * * @param contentType contentType * @return HttpRequest */ public HttpRequest contentType(String contentType) { header(Header.CONTENT_TYPE, contentType); return this; } /** * 设置是否为长连接 * * @param isKeepAlive 是否长连接 * @return HttpRequest */ public HttpRequest keepAlive(boolean isKeepAlive) { header(Header.CONNECTION, isKeepAlive ? "Keep-Alive" : "Close"); return this; } /** * @return 获取是否为长连接 */ public boolean isKeepAlive() { String connection = header(Header.CONNECTION); if (connection == null) { return false == HTTP_1_0.equalsIgnoreCase(httpVersion); } return false == "close".equalsIgnoreCase(connection); } /** * 获取内容长度 * * @return String */ public String contentLength() { return header(Header.CONTENT_LENGTH); } /** * 设置内容长度 * * @param value 长度 * @return HttpRequest */ public HttpRequest contentLength(int value) { header(Header.CONTENT_LENGTH, String.valueOf(value)); return this; } /** * 设置Cookie<br> * 自定义Cookie后会覆盖Hutool的默认Cookie行为 * * @param cookies Cookie值数组,如果为{@code null}则设置无效,使用默认Cookie行为 * @return this * @since 5.4.1 */ public HttpRequest cookie(Collection<HttpCookie> cookies) { return cookie(CollUtil.isEmpty(cookies) ? null : cookies.toArray(new HttpCookie[0])); } /** * 设置Cookie<br> * 自定义Cookie后会覆盖Hutool的默认Cookie行为 * * @param cookies Cookie值数组,如果为{@code null}则设置无效,使用默认Cookie行为 * @return this * @since 3.1.1 */ public HttpRequest cookie(HttpCookie... cookies) { if (ArrayUtil.isEmpty(cookies)) { return disableCookie(); } // 名称/值对之间用分号和空格 ('; ') // https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Cookie return cookie(ArrayUtil.join(cookies, "; ")); } /** * 设置Cookie<br> * 自定义Cookie后会覆盖Hutool的默认Cookie行为 * * @param cookie Cookie值,如果为{@code null}则设置无效,使用默认Cookie行为 * @return this * @since 3.0.7 */ public HttpRequest cookie(String cookie) { this.cookie = cookie; return this; } /** * 禁用默认Cookie行为,此方法调用后会将Cookie置为空。<br> * 如果想重新启用Cookie,请调用:{@link #cookie(String)}方法自定义Cookie。<br> * 如果想启动默认的Cookie行为(自动回填服务器传回的Cookie),则调用{@link #enableDefaultCookie()} * * @return this * @since 3.0.7 */ public HttpRequest disableCookie() { return cookie(StrUtil.EMPTY); } /** * 打开默认的Cookie行为(自动回填服务器传回的Cookie) * * @return this */ public HttpRequest enableDefaultCookie() { return cookie((String) null); } // ---------------------------------------------------------------- Http Request Header end // ---------------------------------------------------------------- Form start /** * 设置表单数据<br> * * @param name 名 * @param value 值 * @return this */ public HttpRequest form(String name, Object value) { if (StrUtil.isBlank(name) || ObjectUtil.isNull(value)) { return this; // 忽略非法的form表单项内容; } // 停用body this.body = null; if (value instanceof File) { // 文件上传 return this.form(name, (File) value); } if (value instanceof Resource) { return form(name, (Resource) value); } // 普通值 String strValue; if (value instanceof Iterable) { // 列表对象 strValue = CollUtil.join((Iterable<?>) value, ","); } else if (ArrayUtil.isArray(value)) { if (File.class == ArrayUtil.getComponentType(value)) { // 多文件 return this.form(name, (File[]) value); } // 数组对象 strValue = ArrayUtil.join((Object[]) value, ","); } else { // 其他对象一律转换为字符串 strValue = Convert.toStr(value, null); } return putToForm(name, strValue); } /** * 设置表单数据 * * @param name 名 * @param value 值 * @param parameters 参数对,奇数为名,偶数为值 * @return this */ public HttpRequest form(String name, Object value, Object... parameters) { form(name, value); for (int i = 0; i < parameters.length; i += 2) { form(parameters[i].toString(), parameters[i + 1]); } return this; } /** * 设置map类型表单数据 * * @param formMap 表单内容 * @return this */ public HttpRequest form(Map<String, Object> formMap) { if (MapUtil.isNotEmpty(formMap)) { formMap.forEach(this::form); } return this; } /** * 设置map&lt;String, String&gt;类型表单数据 * * @param formMapStr 表单内容 * @return this * @since 5.6.7 */ public HttpRequest formStr(Map<String, String> formMapStr) { if (MapUtil.isNotEmpty(formMapStr)) { formMapStr.forEach(this::form); } return this; } /** * 文件表单项<br> * 一旦有文件加入,表单变为multipart/form-data * * @param name 名 * @param files 需要上传的文件,为空跳过 * @return this */ public HttpRequest form(String name, File... files) { if (ArrayUtil.isEmpty(files)) { return this; } if (1 == files.length) { final File file = files[0]; return form(name, file, file.getName()); } return form(name, new MultiFileResource(files)); } /** * 文件表单项<br> * 一旦有文件加入,表单变为multipart/form-data * * @param name 名 * @param file 需要上传的文件 * @return this */ public HttpRequest form(String name, File file) { return form(name, file, file.getName()); } /** * 文件表单项<br> * 一旦有文件加入,表单变为multipart/form-data * * @param name 名 * @param file 需要上传的文件 * @param fileName 文件名,为空使用文件默认的文件名 * @return this */ public HttpRequest form(String name, File file, String fileName) { if (null != file) { form(name, new FileResource(file, fileName)); } return this; } /** * 文件byte[]表单项<br> * 一旦有文件加入,表单变为multipart/form-data * * @param name 名 * @param fileBytes 需要上传的文件 * @param fileName 文件名 * @return this * @since 4.1.0 */ public HttpRequest form(String name, byte[] fileBytes, String fileName) { if (null != fileBytes) { form(name, new BytesResource(fileBytes, fileName)); } return this; } /** * 文件表单项<br> * 一旦有文件加入,表单变为multipart/form-data * * @param name 名 * @param resource 数据源,文件可以使用{@link FileResource}包装使用 * @return this * @since 4.0.9 */ public HttpRequest form(String name, Resource resource) { if (null != resource) { if (false == isKeepAlive()) { keepAlive(true); } this.isMultiPart = true; return putToForm(name, resource); } return this; } /** * 获取表单数据 * * @return 表单Map */ public Map<String, Object> form() { return this.form; } /** * 获取文件表单数据 * * @return 文件表单Map * @since 3.3.0 */ public Map<String, Resource> fileForm() { final Map<String, Resource> result = MapUtil.newHashMap(); this.form.forEach((key, value) -> { if (value instanceof Resource) { result.put(key, (Resource) value); } }); return result; } // ---------------------------------------------------------------- Form end // ---------------------------------------------------------------- Body start /** * 设置内容主体<br> * 请求体body参数支持两种类型: * * <pre> * 1. 标准参数,例如 a=1&amp;b=2 这种格式 * 2. Rest模式,此时body需要传入一个JSON或者XML字符串,Hutool会自动绑定其对应的Content-Type * </pre> * * @param body 请求体 * @return this */ public HttpRequest body(String body) { return this.body(body, null); } /** * 设置内容主体<br> * 请求体body参数支持两种类型: * * <pre> * 1. 标准参数,例如 a=1&amp;b=2 这种格式 * 2. Rest模式,此时body需要传入一个JSON或者XML字符串,Hutool会自动绑定其对应的Content-Type * </pre> * * @param body 请求体 * @param contentType 请求体类型,{@code null}表示自动判断类型 * @return this */ public HttpRequest body(String body, String contentType) { byte[] bytes = StrUtil.bytes(body, this.charset); body(bytes); this.form = null; // 当使用body时,停止form的使用 if (null != contentType) { // Content-Type自定义设置 this.contentType(contentType); } else { // 在用户未自定义的情况下自动根据内容判断 contentType = HttpUtil.getContentTypeByRequestBody(body); if (null != contentType && ContentType.isDefault(this.header(Header.CONTENT_TYPE))) { if (null != this.charset) { // 附加编码信息 contentType = ContentType.build(contentType, this.charset); } this.contentType(contentType); } } // 判断是否为rest请求 if (StrUtil.containsAnyIgnoreCase(contentType, "json", "xml")) { this.isRest = true; contentLength(bytes.length); } return this; } /** * 设置主体字节码<br> * 需在此方法调用前使用charset方法设置编码,否则使用默认编码UTF-8 * * @param bodyBytes 主体 * @return this */ public HttpRequest body(byte[] bodyBytes) { if (ArrayUtil.isNotEmpty(bodyBytes)) { return body(new BytesResource(bodyBytes)); } return this; } /** * 设置主体字节码<br> * 需在此方法调用前使用charset方法设置编码,否则使用默认编码UTF-8 * * @param resource 主体 * @return this */ public HttpRequest body(Resource resource) { if (null != resource) { this.body = resource; } return this; } // ---------------------------------------------------------------- Body end /** * 将新的配置加入<br> * 注意加入的配置可能被修改 * * @param config 配置 * @return this */ public HttpRequest setConfig(HttpConfig config) { this.config = config; return this; } /** * 设置超时,单位:毫秒<br> * 超时包括: * * <pre> * 1. 连接超时 * 2. 读取响应超时 * </pre> * * @param milliseconds 超时毫秒数 * @return this * @see #setConnectionTimeout(int) * @see #setReadTimeout(int) */ public HttpRequest timeout(int milliseconds) { config.timeout(milliseconds); return this; } /** * 设置连接超时,单位:毫秒 * * @param milliseconds 超时毫秒数 * @return this * @since 4.5.6 */ public HttpRequest setConnectionTimeout(int milliseconds) { config.setConnectionTimeout(milliseconds); return this; } /** * 设置连接超时,单位:毫秒 * * @param milliseconds 超时毫秒数 * @return this * @since 4.5.6 */ public HttpRequest setReadTimeout(int milliseconds) { config.setReadTimeout(milliseconds); return this; } /** * 禁用缓存 * * @return this */ public HttpRequest disableCache() { config.disableCache(); return this; } /** * 设置是否打开重定向,如果打开默认重定向次数为2<br> * 此方法效果与{@link #setMaxRedirectCount(int)} 一致 * * <p> * 需要注意的是,当设置为{@code true}时,如果全局重定向次数非0,直接复用,否则设置默认2次。<br> * 当设置为{@code false}时,无论全局是否设置次数,都设置为0。<br> * 不调用此方法的情况下,使用全局默认的次数。 * </p> * * @param isFollowRedirects 是否打开重定向 * @return this */ public HttpRequest setFollowRedirects(boolean isFollowRedirects) { if (isFollowRedirects) { if (config.maxRedirectCount <= 0) { // 默认两次跳转 return setMaxRedirectCount(2); } } else { // 手动强制关闭重定向,此时不受全局重定向设置影响 if (config.maxRedirectCount < 0) { return setMaxRedirectCount(0); } } return this; } /** * 自动重定向时是否处理cookie * @param followRedirectsCookie 自动重定向时是否处理cookie * @return this */ public HttpRequest setFollowRedirectsCookie(boolean followRedirectsCookie) { config.setFollowRedirectsCookie(followRedirectsCookie); return this; } /** * 设置最大重定向次数<br> * 如果次数小于1则表示不重定向,大于等于1表示打开重定向 * * @param maxRedirectCount 最大重定向次数 * @return this * @since 3.3.0 */ public HttpRequest setMaxRedirectCount(int maxRedirectCount) { config.setMaxRedirectCount(maxRedirectCount); return this; } /** * 设置域名验证器<br> * 只针对HTTPS请求,如果不设置,不做验证,所有域名被信任 * * @param hostnameVerifier HostnameVerifier * @return this */ public HttpRequest setHostnameVerifier(HostnameVerifier hostnameVerifier) { config.setHostnameVerifier(hostnameVerifier); return this; } /** * 设置Http代理 * * @param host 代理 主机 * @param port 代理 端口 * @return this * @since 5.4.5 */ public HttpRequest setHttpProxy(String host, int port) { config.setHttpProxy(host, port); return this; } /** * 设置代理 * * @param proxy 代理 {@link Proxy} * @return this */ public HttpRequest setProxy(Proxy proxy) { config.setProxy(proxy); return this; } /** * 设置SSLSocketFactory<br> * 只针对HTTPS请求,如果不设置,使用默认的SSLSocketFactory<br> * 默认SSLSocketFactory为:SSLSocketFactoryBuilder.create().build(); * * @param ssf SSLScketFactory * @return this */ public HttpRequest setSSLSocketFactory(SSLSocketFactory ssf) { config.setSSLSocketFactory(ssf); return this; } /** * 设置HTTPS安全连接协议,只针对HTTPS请求,可以使用的协议包括:<br> * 此方法调用后{@link #setSSLSocketFactory(SSLSocketFactory)} 将被覆盖。 * * <pre> * 1. TLSv1.2 * 2. TLSv1.1 * 3. SSLv3 * ... * </pre> * * @param protocol 协议 * @return this * @see SSLUtil#createSSLContext(String) * @see #setSSLSocketFactory(SSLSocketFactory) */ public HttpRequest setSSLProtocol(String protocol) { config.setSSLProtocol(protocol); return this; } /** * 设置是否rest模式<br> * rest模式下get请求不会把参数附加到URL之后 * * @param isRest 是否rest模式 * @return this * @since 4.5.0 */ public HttpRequest setRest(boolean isRest) { this.isRest = isRest; return this; } /** * 采用流方式上传数据,无需本地缓存数据。<br> * HttpUrlConnection默认是将所有数据读到本地缓存,然后再发送给服务器,这样上传大文件时就会导致内存溢出。 * * @param blockSize 块大小(bytes数),0或小于0表示不设置Chuncked模式 * @return this * @since 4.6.5 */ public HttpRequest setChunkedStreamingMode(int blockSize) { config.setBlockSize(blockSize); return this; } /** * 设置拦截器,用于在请求前重新编辑请求 * * @param interceptor 拦截器实现 * @return this * @see #addRequestInterceptor(HttpInterceptor) * @since 5.7.16 */ public HttpRequest addInterceptor(HttpInterceptor<HttpRequest> interceptor) { return addRequestInterceptor(interceptor); } /** * 设置拦截器,用于在请求前重新编辑请求 * * @param interceptor 拦截器实现 * @return this * @since 5.8.0 */ public HttpRequest addRequestInterceptor(HttpInterceptor<HttpRequest> interceptor) { config.addRequestInterceptor(interceptor); return this; } /** * 设置拦截器,用于在请求前重新编辑请求 * * @param interceptor 拦截器实现 * @return this * @since 5.8.0 */ public HttpRequest addResponseInterceptor(HttpInterceptor<HttpResponse> interceptor) { config.addResponseInterceptor(interceptor); return this; } /** * 执行Reuqest请求 * * @return this */ public HttpResponse execute() { return this.execute(false); } /** * 异步请求<br> * 异步请求后获取的{@link HttpResponse} 为异步模式,执行完此方法后发送请求到服务器,但是并不立即读取响应内容。<br> * 此时保持Http连接不关闭,直调用获取内容方法为止。 * * <p> * 一般执行完execute之后会把响应内容全部读出来放在一个 byte数组里,如果你响应的内容太多内存就爆了,此法是发送完请求不直接读响应内容,等有需要的时候读。 * * @return 异步对象,使用get方法获取HttpResponse对象 */ public HttpResponse executeAsync() { return this.execute(true); } /** * 执行Reuqest请求 * * @param isAsync 是否异步 * @return this */ public HttpResponse execute(boolean isAsync) { return doExecute(isAsync, config.requestInterceptors, config.responseInterceptors); } /** * 执行Request请求后,对响应内容后续处理<br> * 处理结束后关闭连接 * * @param consumer 响应内容处理函数 * @since 5.7.8 */ public void then(Consumer<HttpResponse> consumer) { try (final HttpResponse response = execute(true)) { consumer.accept(response); } } /** * 执行Request请求后,对响应内容后续处理<br> * 处理结束后关闭连接 * * @param <T> 处理结果类型 * @param function 响应内容处理函数 * @return 处理结果 * @since 5.8.5 */ public <T> T thenFunction(Function<HttpResponse, T> function) { try (final HttpResponse response = execute(true)) { return function.apply(response); } } /** * 简单验证,生成的头信息类似于: * <pre> * Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l * </pre> * * @param username 用户名 * @param password 密码 * @return this */ public HttpRequest basicAuth(String username, String password) { return auth(HttpUtil.buildBasicAuth(username, password, charset)); } /** * 简单代理验证,生成的头信息类似于: * <pre> * Proxy-Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l * </pre> * * @param username 用户名 * @param password 密码 * @return this * @since 5.4.6 */ public HttpRequest basicProxyAuth(String username, String password) { return proxyAuth(HttpUtil.buildBasicAuth(username, password, charset)); } /** * 令牌验证,生成的头类似于:"Authorization: Bearer XXXXX",一般用于JWT * * @param token 令牌内容 * @return HttpRequest * @since 5.5.3 */ public HttpRequest bearerAuth(String token) { return auth("Bearer " + token); } /** * 验证,简单插入Authorization头 * * @param content 验证内容 * @return HttpRequest * @since 5.2.4 */ public HttpRequest auth(String content) { header(Header.AUTHORIZATION, content, true); return this; } /** * 验证,简单插入Authorization头 * * @param content 验证内容 * @return HttpRequest * @since 5.4.6 */ public HttpRequest proxyAuth(String content) { header(Header.PROXY_AUTHORIZATION, content, true); return this; } @Override public String toString() { final StringBuilder sb = StrUtil.builder(); sb.append("Request Url: ").append(this.url.setCharset(this.charset)).append(StrUtil.CRLF); // header sb.append("Request Headers: ").append(StrUtil.CRLF); for (Map.Entry<String, List<String>> entry : this.headers.entrySet()) { sb.append(" ").append( entry.getKey()).append(": ").append(CollUtil.join(entry.getValue(), ",")) .append(StrUtil.CRLF); } // body sb.append("Request Body: ").append(StrUtil.CRLF); sb.append(" ").append(createBody()).append(StrUtil.CRLF); return sb.toString(); } // ---------------------------------------------------------------- Private method start /** * 执行Reuqest请求 * * @param isAsync 是否异步 * @param requestInterceptors 请求拦截器列表 * @param responseInterceptors 响应拦截器列表 * @return this */ private HttpResponse doExecute(boolean isAsync, HttpInterceptor.Chain<HttpRequest> requestInterceptors, HttpInterceptor.Chain<HttpResponse> responseInterceptors) { if (null != requestInterceptors) { for (HttpInterceptor<HttpRequest> interceptor : requestInterceptors) { interceptor.process(this); } } // 初始化URL urlWithParamIfGet(); // 初始化 connection initConnection(); // 发送请求 send(); // 手动实现重定向 HttpResponse httpResponse = sendRedirectIfPossible(isAsync); // 获取响应 if (null == httpResponse) { httpResponse = new HttpResponse(this.httpConnection, this.config, this.charset, isAsync, isIgnoreResponseBody()); } // 拦截响应 if (null != responseInterceptors) { for (HttpInterceptor<HttpResponse> interceptor : responseInterceptors) { interceptor.process(httpResponse); } } return httpResponse; } /** * 初始化网络连接 */ private void initConnection() { if (null != this.httpConnection) { // 执行下次请求时自动关闭上次请求(常用于转发) this.httpConnection.disconnectQuietly(); } this.httpConnection = HttpConnection // issue#I50NHQ // 在生成正式URL前,设置自定义编码 .create(this.url.setCharset(this.charset).toURL(this.urlHandler), config.proxy)// .setConnectTimeout(config.connectionTimeout)// .setReadTimeout(config.readTimeout)// .setMethod(this.method)// .setHttpsInfo(config.hostnameVerifier, config.ssf)// // 关闭JDK自动转发,采用手动转发方式 .setInstanceFollowRedirects(false) // 流方式上传数据 .setChunkedStreamingMode(config.blockSize) // 覆盖默认Header .header(this.headers, true); if (null != this.cookie) { // 当用户自定义Cookie时,全局Cookie自动失效 this.httpConnection.setCookie(this.cookie); } else { // 读取全局Cookie信息并附带到请求中 GlobalCookieManager.add(this.httpConnection); } // 是否禁用缓存 if (config.isDisableCache) { this.httpConnection.disableCache(); } } /** * 对于GET请求将参数加到URL中<br> * 此处不对URL中的特殊字符做单独编码<br> * 对于非rest的GET请求,且处于重定向时,参数丢弃 */ private void urlWithParamIfGet() { if (Method.GET.equals(method) && false == this.isRest && this.redirectCount <= 0) { UrlQuery query = this.url.getQuery(); if (null == query) { query = new UrlQuery(); this.url.setQuery(query); } // 优先使用body形式的参数,不存在使用form if (null != this.body) { query.parse(StrUtil.str(this.body.readBytes(), this.charset), this.charset); } else { query.addAll(this.form); } } } /** * 调用转发,如果需要转发返回转发结果,否则返回{@code null} * * @param isAsync 是否异步 * @return {@link HttpResponse},无转发返回 {@code null} */ private HttpResponse sendRedirectIfPossible(boolean isAsync) { // 手动实现重定向 if (config.maxRedirectCount > 0) { final int responseCode; try { responseCode = httpConnection.responseCode(); } catch (IOException e) { // 错误时静默关闭连接 this.httpConnection.disconnectQuietly(); throw new HttpException(e); } // 支持自动重定向时处理cookie // https://github.com/dromara/hutool/issues/2960 if (config.followRedirectsCookie) { GlobalCookieManager.store(httpConnection); } if (responseCode != HttpURLConnection.HTTP_OK) { if (HttpStatus.isRedirected(responseCode)) { final UrlBuilder redirectUrl; String location = httpConnection.header(Header.LOCATION); if (false == HttpUtil.isHttp(location) && false == HttpUtil.isHttps(location)) { // issue#I5TPSY, location可能为相对路径 if (false == location.startsWith("/")) { location = StrUtil.addSuffixIfNot(this.url.getPathStr(), "/") + location; } // issue#3265, 相对路径中可能存在参数,单独处理参数 final String query; final List<String> split = StrUtil.split(location, '?', 2); if (split.size() == 2) { // 存在参数 location = split.get(0); query = split.get(1); } else { query = null; } redirectUrl = UrlBuilder.of(this.url.getScheme(), this.url.getHost(), this.url.getPort() , location, query, null, this.charset); } else { redirectUrl = UrlBuilder.ofHttpWithoutEncode(location); } setUrl(redirectUrl); if (redirectCount < config.maxRedirectCount) { redirectCount++; // 重定向不再走过滤器 return doExecute(isAsync, config.interceptorOnRedirect ? config.requestInterceptors : null, config.interceptorOnRedirect ? config.responseInterceptors : null); } } } } return null; } /** * 发送数据流 * * @throws IORuntimeException IO异常 */ private void send() throws IORuntimeException { try { if (Method.POST.equals(this.method) // || Method.PUT.equals(this.method) // || Method.DELETE.equals(this.method) // || this.isRest) { if (isMultipart()) { sendMultipart(); // 文件上传表单 } else { sendFormUrlEncoded();// 普通表单 } } else { this.httpConnection.connect(); } } catch (IOException e) { // 异常时关闭连接 this.httpConnection.disconnectQuietly(); throw new IORuntimeException(e); } } /** * 发送普通表单<br> * 发送数据后自动关闭输出流 * * @throws IOException IO异常 */ private void sendFormUrlEncoded() throws IOException { if (StrUtil.isBlank(this.header(Header.CONTENT_TYPE))) { // 如果未自定义Content-Type,使用默认的application/x-www-form-urlencoded this.httpConnection.header(Header.CONTENT_TYPE, ContentType.FORM_URLENCODED.toString(this.charset), true); } // Write的时候会优先使用body中的内容,write时自动关闭OutputStream createBody().writeClose(this.httpConnection.getOutputStream()); } /** * 创建body * * @return body */ private RequestBody createBody(){ // Write的时候会优先使用body中的内容,write时自动关闭OutputStream if (null != this.body) { return ResourceBody.create(this.body); } else { return FormUrlEncodedBody.create(this.form, this.charset); } } /** * 发送多组件请求(例如包含文件的表单)<br> * 发送数据后自动关闭输出流 * * @throws IOException IO异常 */ private void sendMultipart() throws IOException { final RequestBody body; // issue#3158,当用户自定义为multipart同时传入body,则不做单独处理 if(null == form && null != this.body) { body = ResourceBody.create(this.body); }else{ final MultipartBody multipartBody = MultipartBody.create(this.form, this.charset); //设置表单类型为Multipart(文件上传) this.httpConnection.header(Header.CONTENT_TYPE, multipartBody.getContentType(), true); body = multipartBody; } body.writeClose(this.httpConnection.getOutputStream()); } /** * 是否忽略读取响应body部分<br> * HEAD、CONNECT、TRACE方法将不读取响应体 * * @return 是否需要忽略响应body部分 * @since 3.1.2 */ private boolean isIgnoreResponseBody() { return Method.HEAD == this.method // || Method.CONNECT == this.method // || Method.TRACE == this.method; } /** * 判断是否为multipart/form-data表单,条件如下: * * <pre> * 1. 存在资源对象(fileForm非空) * 2. 用户自定义头为multipart/form-data开头 * </pre> * * @return 是否为multipart/form-data表单 * @since 5.3.5 */ private boolean isMultipart() { if (this.isMultiPart) { return true; } final String contentType = header(Header.CONTENT_TYPE); return StrUtil.isNotEmpty(contentType) && contentType.startsWith(ContentType.MULTIPART.getValue()); } /** * 将参数加入到form中,如果form为空,新建之。 * * @param name 表单属性名 * @param value 属性值 * @return this */ private HttpRequest putToForm(String name, Object value) { if (null == name || null == value) { return this; } if (null == this.form) { this.form = new TableMap<>(16); } this.form.put(name, value); return this; } // ---------------------------------------------------------------- Private method end }
dromara/hutool
hutool-http/src/main/java/cn/hutool/http/HttpRequest.java
44,890
/* * Copyright (C) 2016 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.google.android.exoplayer2; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.LOCAL_VARIABLE; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE_USE; import android.annotation.SuppressLint; import android.content.Context; import android.media.AudioAttributes; import android.media.AudioFormat; import android.media.AudioManager; import android.media.MediaCodec; import android.media.MediaCrypto; import android.media.MediaFormat; import android.net.Uri; import android.view.Surface; import androidx.annotation.IntDef; import androidx.annotation.RequiresApi; import com.google.android.exoplayer2.util.MimeTypes; import com.google.android.exoplayer2.util.Util; import com.google.errorprone.annotations.InlineMe; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.UUID; /** Defines constants used by the library. */ @SuppressWarnings("InlinedApi") public final class C { private C() {} /** * Special constant representing a time corresponding to the end of a source. Suitable for use in * any time base. */ public static final long TIME_END_OF_SOURCE = Long.MIN_VALUE; /** * Special constant representing an unset or unknown time or duration. Suitable for use in any * time base. */ public static final long TIME_UNSET = Long.MIN_VALUE + 1; /** Represents an unset or unknown index. */ public static final int INDEX_UNSET = -1; /** Represents an unset or unknown position. */ public static final int POSITION_UNSET = -1; /** Represents an unset or unknown rate. */ public static final float RATE_UNSET = -Float.MAX_VALUE; /** Represents an unset or unknown integer rate. */ public static final int RATE_UNSET_INT = Integer.MIN_VALUE + 1; /** Represents an unset or unknown length. */ public static final int LENGTH_UNSET = -1; /** Represents an unset or unknown percentage. */ public static final int PERCENTAGE_UNSET = -1; /** The number of milliseconds in one second. */ public static final long MILLIS_PER_SECOND = 1000L; /** The number of microseconds in one second. */ public static final long MICROS_PER_SECOND = 1000000L; /** The number of nanoseconds in one second. */ public static final long NANOS_PER_SECOND = 1000000000L; /** The number of bits per byte. */ public static final int BITS_PER_BYTE = 8; /** The number of bytes per float. */ public static final int BYTES_PER_FLOAT = 4; /** * @deprecated Use {@link java.nio.charset.StandardCharsets} or {@link * com.google.common.base.Charsets} instead. */ @Deprecated public static final String ASCII_NAME = "US-ASCII"; /** * @deprecated Use {@link java.nio.charset.StandardCharsets} or {@link * com.google.common.base.Charsets} instead. */ @Deprecated public static final String UTF8_NAME = "UTF-8"; /** * @deprecated Use {@link java.nio.charset.StandardCharsets} or {@link * com.google.common.base.Charsets} instead. */ @Deprecated public static final String ISO88591_NAME = "ISO-8859-1"; /** * @deprecated Use {@link java.nio.charset.StandardCharsets} or {@link * com.google.common.base.Charsets} instead. */ @Deprecated public static final String UTF16_NAME = "UTF-16"; /** * @deprecated Use {@link java.nio.charset.StandardCharsets} or {@link * com.google.common.base.Charsets} instead. */ @Deprecated public static final String UTF16LE_NAME = "UTF-16LE"; /** The name of the serif font family. */ public static final String SERIF_NAME = "serif"; /** The name of the sans-serif font family. */ public static final String SANS_SERIF_NAME = "sans-serif"; /** The {@link Uri#getScheme() URI scheme} used for content with server side ad insertion. */ public static final String SSAI_SCHEME = "ssai"; /** * Types of crypto implementation. May be one of {@link #CRYPTO_TYPE_NONE}, {@link * #CRYPTO_TYPE_UNSUPPORTED} or {@link #CRYPTO_TYPE_FRAMEWORK}. May also be an app-defined value * (see {@link #CRYPTO_TYPE_CUSTOM_BASE}). */ @Documented @Retention(RetentionPolicy.SOURCE) @Target(TYPE_USE) @IntDef( open = true, value = { CRYPTO_TYPE_UNSUPPORTED, CRYPTO_TYPE_NONE, CRYPTO_TYPE_FRAMEWORK, }) public @interface CryptoType {} /** No crypto. */ public static final int CRYPTO_TYPE_NONE = 0; /** An unsupported crypto type. */ public static final int CRYPTO_TYPE_UNSUPPORTED = 1; /** Framework crypto in which a {@link MediaCodec} is configured with a {@link MediaCrypto}. */ public static final int CRYPTO_TYPE_FRAMEWORK = 2; /** * Applications or extensions may define custom {@code CRYPTO_TYPE_*} constants greater than or * equal to this value. */ public static final int CRYPTO_TYPE_CUSTOM_BASE = 10000; /** * Crypto modes for a codec. One of {@link #CRYPTO_MODE_UNENCRYPTED}, {@link #CRYPTO_MODE_AES_CTR} * or {@link #CRYPTO_MODE_AES_CBC}. */ @Documented @Retention(RetentionPolicy.SOURCE) @Target(TYPE_USE) @IntDef({CRYPTO_MODE_UNENCRYPTED, CRYPTO_MODE_AES_CTR, CRYPTO_MODE_AES_CBC}) public @interface CryptoMode {} /** * @see MediaCodec#CRYPTO_MODE_UNENCRYPTED */ public static final int CRYPTO_MODE_UNENCRYPTED = MediaCodec.CRYPTO_MODE_UNENCRYPTED; /** * @see MediaCodec#CRYPTO_MODE_AES_CTR */ public static final int CRYPTO_MODE_AES_CTR = MediaCodec.CRYPTO_MODE_AES_CTR; /** * @see MediaCodec#CRYPTO_MODE_AES_CBC */ public static final int CRYPTO_MODE_AES_CBC = MediaCodec.CRYPTO_MODE_AES_CBC; /** * Represents an unset {@link android.media.AudioTrack} session identifier. Equal to {@link * AudioManager#AUDIO_SESSION_ID_GENERATE}. */ public static final int AUDIO_SESSION_ID_UNSET = AudioManager.AUDIO_SESSION_ID_GENERATE; /** * Represents an audio encoding, or an invalid or unset value. One of {@link Format#NO_VALUE}, * {@link #ENCODING_INVALID}, {@link #ENCODING_PCM_8BIT}, {@link #ENCODING_PCM_16BIT}, {@link * #ENCODING_PCM_16BIT_BIG_ENDIAN}, {@link #ENCODING_PCM_24BIT}, {@link #ENCODING_PCM_32BIT}, * {@link #ENCODING_PCM_FLOAT}, {@link #ENCODING_MP3}, {@link #ENCODING_AC3}, {@link * #ENCODING_E_AC3}, {@link #ENCODING_E_AC3_JOC}, {@link #ENCODING_AC4}, {@link #ENCODING_DTS}, * {@link #ENCODING_DTS_HD}, {@link #ENCODING_DOLBY_TRUEHD} or {@link #ENCODING_OPUS}. */ @Documented @Retention(RetentionPolicy.SOURCE) @Target(TYPE_USE) @IntDef({ Format.NO_VALUE, ENCODING_INVALID, ENCODING_PCM_8BIT, ENCODING_PCM_16BIT, ENCODING_PCM_16BIT_BIG_ENDIAN, ENCODING_PCM_24BIT, ENCODING_PCM_32BIT, ENCODING_PCM_FLOAT, ENCODING_MP3, ENCODING_AAC_LC, ENCODING_AAC_HE_V1, ENCODING_AAC_HE_V2, ENCODING_AAC_XHE, ENCODING_AAC_ELD, ENCODING_AAC_ER_BSAC, ENCODING_AC3, ENCODING_E_AC3, ENCODING_E_AC3_JOC, ENCODING_AC4, ENCODING_DTS, ENCODING_DTS_HD, ENCODING_DOLBY_TRUEHD, ENCODING_OPUS, }) public @interface Encoding {} /** * Represents a PCM audio encoding, or an invalid or unset value. One of {@link Format#NO_VALUE}, * {@link #ENCODING_INVALID}, {@link #ENCODING_PCM_8BIT}, {@link #ENCODING_PCM_16BIT}, {@link * #ENCODING_PCM_16BIT_BIG_ENDIAN}, {@link #ENCODING_PCM_24BIT}, {@link #ENCODING_PCM_32BIT}, * {@link #ENCODING_PCM_FLOAT}. */ @Documented @Retention(RetentionPolicy.SOURCE) @Target(TYPE_USE) @IntDef({ Format.NO_VALUE, ENCODING_INVALID, ENCODING_PCM_8BIT, ENCODING_PCM_16BIT, ENCODING_PCM_16BIT_BIG_ENDIAN, ENCODING_PCM_24BIT, ENCODING_PCM_32BIT, ENCODING_PCM_FLOAT }) public @interface PcmEncoding {} /** * @see AudioFormat#ENCODING_INVALID */ public static final int ENCODING_INVALID = AudioFormat.ENCODING_INVALID; /** * @see AudioFormat#ENCODING_PCM_8BIT */ public static final int ENCODING_PCM_8BIT = AudioFormat.ENCODING_PCM_8BIT; /** * @see AudioFormat#ENCODING_PCM_16BIT */ public static final int ENCODING_PCM_16BIT = AudioFormat.ENCODING_PCM_16BIT; /** Like {@link #ENCODING_PCM_16BIT}, but with the bytes in big endian order. */ public static final int ENCODING_PCM_16BIT_BIG_ENDIAN = 0x10000000; /** PCM encoding with 24 bits per sample. */ public static final int ENCODING_PCM_24BIT = 0x20000000; /** PCM encoding with 32 bits per sample. */ public static final int ENCODING_PCM_32BIT = 0x30000000; /** * @see AudioFormat#ENCODING_PCM_FLOAT */ public static final int ENCODING_PCM_FLOAT = AudioFormat.ENCODING_PCM_FLOAT; /** * @see AudioFormat#ENCODING_MP3 */ public static final int ENCODING_MP3 = AudioFormat.ENCODING_MP3; /** * @see AudioFormat#ENCODING_AAC_LC */ public static final int ENCODING_AAC_LC = AudioFormat.ENCODING_AAC_LC; /** * @see AudioFormat#ENCODING_AAC_HE_V1 */ public static final int ENCODING_AAC_HE_V1 = AudioFormat.ENCODING_AAC_HE_V1; /** * @see AudioFormat#ENCODING_AAC_HE_V2 */ public static final int ENCODING_AAC_HE_V2 = AudioFormat.ENCODING_AAC_HE_V2; /** * @see AudioFormat#ENCODING_AAC_XHE */ public static final int ENCODING_AAC_XHE = AudioFormat.ENCODING_AAC_XHE; /** * @see AudioFormat#ENCODING_AAC_ELD */ public static final int ENCODING_AAC_ELD = AudioFormat.ENCODING_AAC_ELD; /** AAC Error Resilient Bit-Sliced Arithmetic Coding. */ public static final int ENCODING_AAC_ER_BSAC = 0x40000000; /** * @see AudioFormat#ENCODING_AC3 */ public static final int ENCODING_AC3 = AudioFormat.ENCODING_AC3; /** * @see AudioFormat#ENCODING_E_AC3 */ public static final int ENCODING_E_AC3 = AudioFormat.ENCODING_E_AC3; /** * @see AudioFormat#ENCODING_E_AC3_JOC */ public static final int ENCODING_E_AC3_JOC = AudioFormat.ENCODING_E_AC3_JOC; /** * @see AudioFormat#ENCODING_AC4 */ public static final int ENCODING_AC4 = AudioFormat.ENCODING_AC4; /** * @see AudioFormat#ENCODING_DTS */ public static final int ENCODING_DTS = AudioFormat.ENCODING_DTS; /** * @see AudioFormat#ENCODING_DTS_HD */ public static final int ENCODING_DTS_HD = AudioFormat.ENCODING_DTS_HD; /** * @see AudioFormat#ENCODING_DOLBY_TRUEHD */ public static final int ENCODING_DOLBY_TRUEHD = AudioFormat.ENCODING_DOLBY_TRUEHD; /** * @see AudioFormat#ENCODING_OPUS */ public static final int ENCODING_OPUS = AudioFormat.ENCODING_OPUS; /** Represents the behavior affecting whether spatialization will be used. */ @Documented @Retention(RetentionPolicy.SOURCE) @Target(TYPE_USE) @IntDef({SPATIALIZATION_BEHAVIOR_AUTO, SPATIALIZATION_BEHAVIOR_NEVER}) public @interface SpatializationBehavior {} /** * @see AudioAttributes#SPATIALIZATION_BEHAVIOR_AUTO */ public static final int SPATIALIZATION_BEHAVIOR_AUTO = AudioAttributes.SPATIALIZATION_BEHAVIOR_AUTO; /** * @see AudioAttributes#SPATIALIZATION_BEHAVIOR_NEVER */ public static final int SPATIALIZATION_BEHAVIOR_NEVER = AudioAttributes.SPATIALIZATION_BEHAVIOR_NEVER; /** * Stream types for an {@link android.media.AudioTrack}. One of {@link #STREAM_TYPE_ALARM}, {@link * #STREAM_TYPE_DTMF}, {@link #STREAM_TYPE_MUSIC}, {@link #STREAM_TYPE_NOTIFICATION}, {@link * #STREAM_TYPE_RING}, {@link #STREAM_TYPE_SYSTEM}, {@link #STREAM_TYPE_VOICE_CALL} or {@link * #STREAM_TYPE_DEFAULT}. */ // @Target list includes both 'default' targets and TYPE_USE, to ensure backwards compatibility // with Kotlin usages from before TYPE_USE was added. @SuppressLint("UniqueConstants") // Intentional duplication to set STREAM_TYPE_DEFAULT. @Documented @Retention(RetentionPolicy.SOURCE) @Target({FIELD, METHOD, PARAMETER, LOCAL_VARIABLE, TYPE_USE}) @IntDef({ STREAM_TYPE_ALARM, STREAM_TYPE_DTMF, STREAM_TYPE_MUSIC, STREAM_TYPE_NOTIFICATION, STREAM_TYPE_RING, STREAM_TYPE_SYSTEM, STREAM_TYPE_VOICE_CALL, STREAM_TYPE_DEFAULT }) public @interface StreamType {} /** * @see AudioManager#STREAM_ALARM */ public static final int STREAM_TYPE_ALARM = AudioManager.STREAM_ALARM; /** * @see AudioManager#STREAM_DTMF */ public static final int STREAM_TYPE_DTMF = AudioManager.STREAM_DTMF; /** * @see AudioManager#STREAM_MUSIC */ public static final int STREAM_TYPE_MUSIC = AudioManager.STREAM_MUSIC; /** * @see AudioManager#STREAM_NOTIFICATION */ public static final int STREAM_TYPE_NOTIFICATION = AudioManager.STREAM_NOTIFICATION; /** * @see AudioManager#STREAM_RING */ public static final int STREAM_TYPE_RING = AudioManager.STREAM_RING; /** * @see AudioManager#STREAM_SYSTEM */ public static final int STREAM_TYPE_SYSTEM = AudioManager.STREAM_SYSTEM; /** * @see AudioManager#STREAM_VOICE_CALL */ public static final int STREAM_TYPE_VOICE_CALL = AudioManager.STREAM_VOICE_CALL; /** The default stream type used by audio renderers. Equal to {@link #STREAM_TYPE_MUSIC}. */ public static final int STREAM_TYPE_DEFAULT = STREAM_TYPE_MUSIC; /** * Content types for audio attributes. One of: * * <ul> * <li>{@link #AUDIO_CONTENT_TYPE_MOVIE} * <li>{@link #AUDIO_CONTENT_TYPE_MUSIC} * <li>{@link #AUDIO_CONTENT_TYPE_SONIFICATION} * <li>{@link #AUDIO_CONTENT_TYPE_SPEECH} * <li>{@link #AUDIO_CONTENT_TYPE_UNKNOWN} * </ul> */ // @Target list includes both 'default' targets and TYPE_USE, to ensure backwards compatibility // with Kotlin usages from before TYPE_USE was added. @Documented @Retention(RetentionPolicy.SOURCE) @Target({FIELD, METHOD, PARAMETER, LOCAL_VARIABLE, TYPE_USE}) @IntDef({ AUDIO_CONTENT_TYPE_MOVIE, AUDIO_CONTENT_TYPE_MUSIC, AUDIO_CONTENT_TYPE_SONIFICATION, AUDIO_CONTENT_TYPE_SPEECH, AUDIO_CONTENT_TYPE_UNKNOWN }) public @interface AudioContentType {} /** See {@link AudioAttributes#CONTENT_TYPE_MOVIE}. */ public static final int AUDIO_CONTENT_TYPE_MOVIE = AudioAttributes.CONTENT_TYPE_MOVIE; /** * @deprecated Use {@link #AUDIO_CONTENT_TYPE_MOVIE} instead. */ @Deprecated public static final int CONTENT_TYPE_MOVIE = AUDIO_CONTENT_TYPE_MOVIE; /** See {@link AudioAttributes#CONTENT_TYPE_MUSIC}. */ public static final int AUDIO_CONTENT_TYPE_MUSIC = AudioAttributes.CONTENT_TYPE_MUSIC; /** * @deprecated Use {@link #AUDIO_CONTENT_TYPE_MUSIC} instead. */ @Deprecated public static final int CONTENT_TYPE_MUSIC = AUDIO_CONTENT_TYPE_MUSIC; /** See {@link AudioAttributes#CONTENT_TYPE_SONIFICATION}. */ public static final int AUDIO_CONTENT_TYPE_SONIFICATION = AudioAttributes.CONTENT_TYPE_SONIFICATION; /** * @deprecated Use {@link #AUDIO_CONTENT_TYPE_SONIFICATION} instead. */ @Deprecated public static final int CONTENT_TYPE_SONIFICATION = AUDIO_CONTENT_TYPE_SONIFICATION; /** See {@link AudioAttributes#CONTENT_TYPE_SPEECH}. */ public static final int AUDIO_CONTENT_TYPE_SPEECH = AudioAttributes.CONTENT_TYPE_SPEECH; /** * @deprecated Use {@link #AUDIO_CONTENT_TYPE_SPEECH} instead. */ @Deprecated public static final int CONTENT_TYPE_SPEECH = AUDIO_CONTENT_TYPE_SPEECH; /** See {@link AudioAttributes#CONTENT_TYPE_UNKNOWN}. */ public static final int AUDIO_CONTENT_TYPE_UNKNOWN = AudioAttributes.CONTENT_TYPE_UNKNOWN; /** * @deprecated Use {@link #AUDIO_CONTENT_TYPE_UNKNOWN} instead. */ @Deprecated public static final int CONTENT_TYPE_UNKNOWN = AUDIO_CONTENT_TYPE_UNKNOWN; /** * Flags for audio attributes. Possible flag value is {@link #FLAG_AUDIBILITY_ENFORCED}. * * <p>Note that {@code FLAG_HW_AV_SYNC} is not available because the player takes care of setting * the flag when tunneling is enabled via a track selector. */ // @Target list includes both 'default' targets and TYPE_USE, to ensure backwards compatibility // with Kotlin usages from before TYPE_USE was added. @Documented @Retention(RetentionPolicy.SOURCE) @Target({FIELD, METHOD, PARAMETER, LOCAL_VARIABLE, TYPE_USE}) @IntDef( flag = true, value = {FLAG_AUDIBILITY_ENFORCED}) public @interface AudioFlags {} /** * @see android.media.AudioAttributes#FLAG_AUDIBILITY_ENFORCED */ public static final int FLAG_AUDIBILITY_ENFORCED = android.media.AudioAttributes.FLAG_AUDIBILITY_ENFORCED; /** * Usage types for audio attributes. One of {@link #USAGE_ALARM}, {@link * #USAGE_ASSISTANCE_ACCESSIBILITY}, {@link #USAGE_ASSISTANCE_NAVIGATION_GUIDANCE}, {@link * #USAGE_ASSISTANCE_SONIFICATION}, {@link #USAGE_ASSISTANT}, {@link #USAGE_GAME}, {@link * #USAGE_MEDIA}, {@link #USAGE_NOTIFICATION}, {@link #USAGE_NOTIFICATION_COMMUNICATION_DELAYED}, * {@link #USAGE_NOTIFICATION_COMMUNICATION_INSTANT}, {@link * #USAGE_NOTIFICATION_COMMUNICATION_REQUEST}, {@link #USAGE_NOTIFICATION_EVENT}, {@link * #USAGE_NOTIFICATION_RINGTONE}, {@link #USAGE_UNKNOWN}, {@link #USAGE_VOICE_COMMUNICATION} or * {@link #USAGE_VOICE_COMMUNICATION_SIGNALLING}. */ // @Target list includes both 'default' targets and TYPE_USE, to ensure backwards compatibility // with Kotlin usages from before TYPE_USE was added. @Documented @Retention(RetentionPolicy.SOURCE) @Target({FIELD, METHOD, PARAMETER, LOCAL_VARIABLE, TYPE_USE}) @IntDef({ USAGE_ALARM, USAGE_ASSISTANCE_ACCESSIBILITY, USAGE_ASSISTANCE_NAVIGATION_GUIDANCE, USAGE_ASSISTANCE_SONIFICATION, USAGE_ASSISTANT, USAGE_GAME, USAGE_MEDIA, USAGE_NOTIFICATION, USAGE_NOTIFICATION_COMMUNICATION_DELAYED, USAGE_NOTIFICATION_COMMUNICATION_INSTANT, USAGE_NOTIFICATION_COMMUNICATION_REQUEST, USAGE_NOTIFICATION_EVENT, USAGE_NOTIFICATION_RINGTONE, USAGE_UNKNOWN, USAGE_VOICE_COMMUNICATION, USAGE_VOICE_COMMUNICATION_SIGNALLING }) public @interface AudioUsage {} /** * @see android.media.AudioAttributes#USAGE_ALARM */ public static final int USAGE_ALARM = android.media.AudioAttributes.USAGE_ALARM; /** * @see android.media.AudioAttributes#USAGE_ASSISTANCE_ACCESSIBILITY */ public static final int USAGE_ASSISTANCE_ACCESSIBILITY = android.media.AudioAttributes.USAGE_ASSISTANCE_ACCESSIBILITY; /** * @see android.media.AudioAttributes#USAGE_ASSISTANCE_NAVIGATION_GUIDANCE */ public static final int USAGE_ASSISTANCE_NAVIGATION_GUIDANCE = android.media.AudioAttributes.USAGE_ASSISTANCE_NAVIGATION_GUIDANCE; /** * @see android.media.AudioAttributes#USAGE_ASSISTANCE_SONIFICATION */ public static final int USAGE_ASSISTANCE_SONIFICATION = android.media.AudioAttributes.USAGE_ASSISTANCE_SONIFICATION; /** * @see android.media.AudioAttributes#USAGE_ASSISTANT */ public static final int USAGE_ASSISTANT = android.media.AudioAttributes.USAGE_ASSISTANT; /** * @see android.media.AudioAttributes#USAGE_GAME */ public static final int USAGE_GAME = android.media.AudioAttributes.USAGE_GAME; /** * @see android.media.AudioAttributes#USAGE_MEDIA */ public static final int USAGE_MEDIA = android.media.AudioAttributes.USAGE_MEDIA; /** * @see android.media.AudioAttributes#USAGE_NOTIFICATION */ public static final int USAGE_NOTIFICATION = android.media.AudioAttributes.USAGE_NOTIFICATION; /** * @see android.media.AudioAttributes#USAGE_NOTIFICATION_COMMUNICATION_DELAYED */ public static final int USAGE_NOTIFICATION_COMMUNICATION_DELAYED = android.media.AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_DELAYED; /** * @see android.media.AudioAttributes#USAGE_NOTIFICATION_COMMUNICATION_INSTANT */ public static final int USAGE_NOTIFICATION_COMMUNICATION_INSTANT = android.media.AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_INSTANT; /** * @see android.media.AudioAttributes#USAGE_NOTIFICATION_COMMUNICATION_REQUEST */ public static final int USAGE_NOTIFICATION_COMMUNICATION_REQUEST = android.media.AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_REQUEST; /** * @see android.media.AudioAttributes#USAGE_NOTIFICATION_EVENT */ public static final int USAGE_NOTIFICATION_EVENT = android.media.AudioAttributes.USAGE_NOTIFICATION_EVENT; /** * @see android.media.AudioAttributes#USAGE_NOTIFICATION_RINGTONE */ public static final int USAGE_NOTIFICATION_RINGTONE = android.media.AudioAttributes.USAGE_NOTIFICATION_RINGTONE; /** * @see android.media.AudioAttributes#USAGE_UNKNOWN */ public static final int USAGE_UNKNOWN = android.media.AudioAttributes.USAGE_UNKNOWN; /** * @see android.media.AudioAttributes#USAGE_VOICE_COMMUNICATION */ public static final int USAGE_VOICE_COMMUNICATION = android.media.AudioAttributes.USAGE_VOICE_COMMUNICATION; /** * @see android.media.AudioAttributes#USAGE_VOICE_COMMUNICATION_SIGNALLING */ public static final int USAGE_VOICE_COMMUNICATION_SIGNALLING = android.media.AudioAttributes.USAGE_VOICE_COMMUNICATION_SIGNALLING; /** * Capture policies for audio attributes. One of {@link #ALLOW_CAPTURE_BY_ALL}, {@link * #ALLOW_CAPTURE_BY_NONE} or {@link #ALLOW_CAPTURE_BY_SYSTEM}. */ // @Target list includes both 'default' targets and TYPE_USE, to ensure backwards compatibility // with Kotlin usages from before TYPE_USE was added. @Documented @Retention(RetentionPolicy.SOURCE) @Target({FIELD, METHOD, PARAMETER, LOCAL_VARIABLE, TYPE_USE}) @IntDef({ALLOW_CAPTURE_BY_ALL, ALLOW_CAPTURE_BY_NONE, ALLOW_CAPTURE_BY_SYSTEM}) public @interface AudioAllowedCapturePolicy {} /** See {@link android.media.AudioAttributes#ALLOW_CAPTURE_BY_ALL}. */ public static final int ALLOW_CAPTURE_BY_ALL = AudioAttributes.ALLOW_CAPTURE_BY_ALL; /** See {@link android.media.AudioAttributes#ALLOW_CAPTURE_BY_NONE}. */ public static final int ALLOW_CAPTURE_BY_NONE = AudioAttributes.ALLOW_CAPTURE_BY_NONE; /** See {@link android.media.AudioAttributes#ALLOW_CAPTURE_BY_SYSTEM}. */ public static final int ALLOW_CAPTURE_BY_SYSTEM = AudioAttributes.ALLOW_CAPTURE_BY_SYSTEM; /** * Flags which can apply to a buffer containing a media sample. Possible flag values are {@link * #BUFFER_FLAG_KEY_FRAME}, {@link #BUFFER_FLAG_END_OF_STREAM}, {@link #BUFFER_FLAG_FIRST_SAMPLE}, * {@link #BUFFER_FLAG_LAST_SAMPLE}, {@link #BUFFER_FLAG_ENCRYPTED} and {@link * #BUFFER_FLAG_DECODE_ONLY}. */ @Documented @Retention(RetentionPolicy.SOURCE) @Target(TYPE_USE) @IntDef( flag = true, value = { BUFFER_FLAG_KEY_FRAME, BUFFER_FLAG_END_OF_STREAM, BUFFER_FLAG_FIRST_SAMPLE, BUFFER_FLAG_HAS_SUPPLEMENTAL_DATA, BUFFER_FLAG_LAST_SAMPLE, BUFFER_FLAG_ENCRYPTED, BUFFER_FLAG_DECODE_ONLY }) public @interface BufferFlags {} /** Indicates that a buffer holds a synchronization sample. */ public static final int BUFFER_FLAG_KEY_FRAME = MediaCodec.BUFFER_FLAG_KEY_FRAME; /** Flag for empty buffers that signal that the end of the stream was reached. */ public static final int BUFFER_FLAG_END_OF_STREAM = MediaCodec.BUFFER_FLAG_END_OF_STREAM; /** Indicates that a buffer is known to contain the first media sample of the stream. */ public static final int BUFFER_FLAG_FIRST_SAMPLE = 1 << 27; // 0x08000000 /** Indicates that a buffer has supplemental data. */ public static final int BUFFER_FLAG_HAS_SUPPLEMENTAL_DATA = 1 << 28; // 0x10000000 /** Indicates that a buffer is known to contain the last media sample of the stream. */ public static final int BUFFER_FLAG_LAST_SAMPLE = 1 << 29; // 0x20000000 /** Indicates that a buffer is (at least partially) encrypted. */ public static final int BUFFER_FLAG_ENCRYPTED = 1 << 30; // 0x40000000 /** Indicates that a buffer should be decoded but not rendered. */ public static final int BUFFER_FLAG_DECODE_ONLY = 1 << 31; // 0x80000000 /** * Video decoder output modes. Possible modes are {@link #VIDEO_OUTPUT_MODE_NONE}, {@link * #VIDEO_OUTPUT_MODE_YUV} and {@link #VIDEO_OUTPUT_MODE_SURFACE_YUV}. */ @Documented @Retention(RetentionPolicy.SOURCE) @Target(TYPE_USE) @IntDef(value = {VIDEO_OUTPUT_MODE_NONE, VIDEO_OUTPUT_MODE_YUV, VIDEO_OUTPUT_MODE_SURFACE_YUV}) public @interface VideoOutputMode {} /** Video decoder output mode is not set. */ public static final int VIDEO_OUTPUT_MODE_NONE = -1; /** Video decoder output mode that outputs raw 4:2:0 YUV planes. */ public static final int VIDEO_OUTPUT_MODE_YUV = 0; /** Video decoder output mode that renders 4:2:0 YUV planes directly to a surface. */ public static final int VIDEO_OUTPUT_MODE_SURFACE_YUV = 1; /** * Video scaling modes for {@link MediaCodec}-based renderers. One of {@link * #VIDEO_SCALING_MODE_SCALE_TO_FIT}, {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING} or * {@link #VIDEO_SCALING_MODE_DEFAULT}. */ // @Target list includes both 'default' targets and TYPE_USE, to ensure backwards compatibility // with Kotlin usages from before TYPE_USE was added. @SuppressLint("UniqueConstants") // Intentional duplication to set VIDEO_SCALING_MODE_DEFAULT. @Documented @Retention(RetentionPolicy.SOURCE) @Target({FIELD, METHOD, PARAMETER, LOCAL_VARIABLE, TYPE_USE}) @IntDef({ VIDEO_SCALING_MODE_SCALE_TO_FIT, VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING, VIDEO_SCALING_MODE_DEFAULT }) public @interface VideoScalingMode {} /** See {@link MediaCodec#VIDEO_SCALING_MODE_SCALE_TO_FIT}. */ public static final int VIDEO_SCALING_MODE_SCALE_TO_FIT = MediaCodec.VIDEO_SCALING_MODE_SCALE_TO_FIT; /** See {@link MediaCodec#VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING}. */ public static final int VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING = MediaCodec.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING; /** A default video scaling mode for {@link MediaCodec}-based renderers. */ public static final int VIDEO_SCALING_MODE_DEFAULT = VIDEO_SCALING_MODE_SCALE_TO_FIT; /** Strategies for calling {@link Surface#setFrameRate}. */ // @Target list includes both 'default' targets and TYPE_USE, to ensure backwards compatibility // with Kotlin usages from before TYPE_USE was added. @Documented @Retention(RetentionPolicy.SOURCE) @Target({FIELD, METHOD, PARAMETER, LOCAL_VARIABLE, TYPE_USE}) @IntDef({VIDEO_CHANGE_FRAME_RATE_STRATEGY_OFF, VIDEO_CHANGE_FRAME_RATE_STRATEGY_ONLY_IF_SEAMLESS}) public @interface VideoChangeFrameRateStrategy {} /** * Strategy to never call {@link Surface#setFrameRate}. Use this strategy if you prefer to call * {@link Surface#setFrameRate} directly from application code. */ public static final int VIDEO_CHANGE_FRAME_RATE_STRATEGY_OFF = Integer.MIN_VALUE; /** * Strategy to call {@link Surface#setFrameRate} with {@link * Surface#CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS} when the output frame rate is known. */ public static final int VIDEO_CHANGE_FRAME_RATE_STRATEGY_ONLY_IF_SEAMLESS = Surface.CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS; /** * Track selection flags. Possible flag values are {@link #SELECTION_FLAG_DEFAULT}, {@link * #SELECTION_FLAG_FORCED} and {@link #SELECTION_FLAG_AUTOSELECT}. */ // @Target list includes both 'default' targets and TYPE_USE, to ensure backwards compatibility // with Kotlin usages from before TYPE_USE was added. @Documented @Retention(RetentionPolicy.SOURCE) @Target({FIELD, METHOD, PARAMETER, LOCAL_VARIABLE, TYPE_USE}) @IntDef( flag = true, value = {SELECTION_FLAG_DEFAULT, SELECTION_FLAG_FORCED, SELECTION_FLAG_AUTOSELECT}) public @interface SelectionFlags {} // LINT.IfChange(selection_flags) /** Indicates that the track should be selected if user preferences do not state otherwise. */ public static final int SELECTION_FLAG_DEFAULT = 1; /** * Indicates that the track should be selected if its language matches the language of the * selected audio track and user preferences do not state otherwise. Only applies to text tracks. * * <p>Tracks with this flag generally provide translation for elements that don't match the * declared language of the selected audio track (e.g. speech in an alien language). See <a * href="https://partnerhelp.netflixstudios.com/hc/en-us/articles/217558918">Netflix's summary</a> * for more info. */ public static final int SELECTION_FLAG_FORCED = 1 << 1; // 2 /** * Indicates that the player may choose to play the track in absence of an explicit user * preference. */ public static final int SELECTION_FLAG_AUTOSELECT = 1 << 2; // 4 /** Represents an undetermined language as an ISO 639-2 language code. */ public static final String LANGUAGE_UNDETERMINED = "und"; /** * Represents a streaming or other media type. One of: * * <ul> * <li>{@link #CONTENT_TYPE_DASH} * <li>{@link #CONTENT_TYPE_SS} * <li>{@link #CONTENT_TYPE_HLS} * <li>{@link #CONTENT_TYPE_RTSP} * <li>{@link #CONTENT_TYPE_OTHER} * </ul> */ // @Target list includes both 'default' targets and TYPE_USE, to ensure backwards compatibility // with Kotlin usages from before TYPE_USE was added. @Documented @Retention(RetentionPolicy.SOURCE) @Target({FIELD, METHOD, PARAMETER, LOCAL_VARIABLE, TYPE_USE}) @IntDef({ CONTENT_TYPE_DASH, CONTENT_TYPE_SS, CONTENT_TYPE_HLS, CONTENT_TYPE_RTSP, CONTENT_TYPE_OTHER }) public @interface ContentType {} /** Value representing a DASH manifest. */ public static final int CONTENT_TYPE_DASH = 0; /** * @deprecated Use {@link #CONTENT_TYPE_DASH} instead. */ @Deprecated public static final int TYPE_DASH = CONTENT_TYPE_DASH; /** Value representing a Smooth Streaming manifest. */ public static final int CONTENT_TYPE_SS = 1; /** * @deprecated Use {@link #CONTENT_TYPE_SS} instead. */ @Deprecated public static final int TYPE_SS = CONTENT_TYPE_SS; /** Value representing an HLS manifest. */ public static final int CONTENT_TYPE_HLS = 2; /** * @deprecated Use {@link #CONTENT_TYPE_HLS} instead. */ @Deprecated public static final int TYPE_HLS = CONTENT_TYPE_HLS; /** Value representing an RTSP stream. */ public static final int CONTENT_TYPE_RTSP = 3; /** * @deprecated Use {@link #CONTENT_TYPE_RTSP} instead. */ @Deprecated public static final int TYPE_RTSP = CONTENT_TYPE_RTSP; /** Value representing files other than DASH, HLS or Smooth Streaming manifests, or RTSP URIs. */ public static final int CONTENT_TYPE_OTHER = 4; /** * @deprecated Use {@link #CONTENT_TYPE_OTHER} instead. */ @Deprecated public static final int TYPE_OTHER = CONTENT_TYPE_OTHER; /** A return value for methods where the end of an input was encountered. */ public static final int RESULT_END_OF_INPUT = -1; /** * A return value for methods where the length of parsed data exceeds the maximum length allowed. */ public static final int RESULT_MAX_LENGTH_EXCEEDED = -2; /** A return value for methods where nothing was read. */ public static final int RESULT_NOTHING_READ = -3; /** A return value for methods where a buffer was read. */ public static final int RESULT_BUFFER_READ = -4; /** A return value for methods where a format was read. */ public static final int RESULT_FORMAT_READ = -5; /** * Represents a type of data. May be one of {@link #DATA_TYPE_UNKNOWN}, {@link #DATA_TYPE_MEDIA}, * {@link #DATA_TYPE_MEDIA_INITIALIZATION}, {@link #DATA_TYPE_DRM}, {@link #DATA_TYPE_MANIFEST}, * {@link #DATA_TYPE_TIME_SYNCHRONIZATION}, {@link #DATA_TYPE_AD}, or {@link * #DATA_TYPE_MEDIA_PROGRESSIVE_LIVE}. May also be an app-defined value (see {@link * #DATA_TYPE_CUSTOM_BASE}). */ @Documented @Retention(RetentionPolicy.SOURCE) @Target(TYPE_USE) @IntDef( open = true, value = { DATA_TYPE_UNKNOWN, DATA_TYPE_MEDIA, DATA_TYPE_MEDIA_INITIALIZATION, DATA_TYPE_DRM, DATA_TYPE_MANIFEST, DATA_TYPE_TIME_SYNCHRONIZATION, DATA_TYPE_AD, DATA_TYPE_MEDIA_PROGRESSIVE_LIVE }) public @interface DataType {} /** A data type constant for data of unknown or unspecified type. */ public static final int DATA_TYPE_UNKNOWN = 0; /** A data type constant for media, typically containing media samples. */ public static final int DATA_TYPE_MEDIA = 1; /** A data type constant for media, typically containing only initialization data. */ public static final int DATA_TYPE_MEDIA_INITIALIZATION = 2; /** A data type constant for drm or encryption data. */ public static final int DATA_TYPE_DRM = 3; /** A data type constant for a manifest file. */ public static final int DATA_TYPE_MANIFEST = 4; /** A data type constant for time synchronization data. */ public static final int DATA_TYPE_TIME_SYNCHRONIZATION = 5; /** A data type constant for ads loader data. */ public static final int DATA_TYPE_AD = 6; /** * A data type constant for live progressive media streams, typically containing media samples. */ public static final int DATA_TYPE_MEDIA_PROGRESSIVE_LIVE = 7; /** * Applications or extensions may define custom {@code DATA_TYPE_*} constants greater than or * equal to this value. */ public static final int DATA_TYPE_CUSTOM_BASE = 10000; /** * Represents a type of media track. May be one of {@link #TRACK_TYPE_UNKNOWN}, {@link * #TRACK_TYPE_DEFAULT}, {@link #TRACK_TYPE_AUDIO}, {@link #TRACK_TYPE_VIDEO}, {@link * #TRACK_TYPE_TEXT}, {@link #TRACK_TYPE_IMAGE}, {@link #TRACK_TYPE_METADATA}, {@link * #TRACK_TYPE_CAMERA_MOTION} or {@link #TRACK_TYPE_NONE}. May also be an app-defined value (see * {@link #TRACK_TYPE_CUSTOM_BASE}). */ @Documented @Retention(RetentionPolicy.SOURCE) @Target(TYPE_USE) @IntDef( open = true, value = { TRACK_TYPE_UNKNOWN, TRACK_TYPE_DEFAULT, TRACK_TYPE_AUDIO, TRACK_TYPE_VIDEO, TRACK_TYPE_TEXT, TRACK_TYPE_IMAGE, TRACK_TYPE_METADATA, TRACK_TYPE_CAMERA_MOTION, TRACK_TYPE_NONE, }) public @interface TrackType {} /** A type constant for a fake or empty track. */ public static final int TRACK_TYPE_NONE = -2; /** A type constant for tracks of unknown type. */ public static final int TRACK_TYPE_UNKNOWN = -1; /** A type constant for tracks of some default type, where the type itself is unknown. */ public static final int TRACK_TYPE_DEFAULT = 0; /** A type constant for audio tracks. */ public static final int TRACK_TYPE_AUDIO = 1; /** A type constant for video tracks. */ public static final int TRACK_TYPE_VIDEO = 2; /** A type constant for text tracks. */ public static final int TRACK_TYPE_TEXT = 3; /** A type constant for image tracks. */ public static final int TRACK_TYPE_IMAGE = 4; /** A type constant for metadata tracks. */ public static final int TRACK_TYPE_METADATA = 5; /** A type constant for camera motion tracks. */ public static final int TRACK_TYPE_CAMERA_MOTION = 6; /** * Applications or extensions may define custom {@code TRACK_TYPE_*} constants greater than or * equal to this value. */ public static final int TRACK_TYPE_CUSTOM_BASE = 10000; /** * Represents a reason for selection. May be one of {@link #SELECTION_REASON_UNKNOWN}, {@link * #SELECTION_REASON_INITIAL}, {@link #SELECTION_REASON_MANUAL}, {@link * #SELECTION_REASON_ADAPTIVE} or {@link #SELECTION_REASON_TRICK_PLAY}. May also be an app-defined * value (see {@link #SELECTION_REASON_CUSTOM_BASE}). */ @Documented @Retention(RetentionPolicy.SOURCE) @Target(TYPE_USE) @IntDef( open = true, value = { SELECTION_REASON_UNKNOWN, SELECTION_REASON_INITIAL, SELECTION_REASON_MANUAL, SELECTION_REASON_ADAPTIVE, SELECTION_REASON_TRICK_PLAY }) public @interface SelectionReason {} /** A selection reason constant for selections whose reasons are unknown or unspecified. */ public static final int SELECTION_REASON_UNKNOWN = 0; /** A selection reason constant for an initial track selection. */ public static final int SELECTION_REASON_INITIAL = 1; /** A selection reason constant for an manual (i.e. user initiated) track selection. */ public static final int SELECTION_REASON_MANUAL = 2; /** A selection reason constant for an adaptive track selection. */ public static final int SELECTION_REASON_ADAPTIVE = 3; /** A selection reason constant for a trick play track selection. */ public static final int SELECTION_REASON_TRICK_PLAY = 4; /** * Applications or extensions may define custom {@code SELECTION_REASON_*} constants greater than * or equal to this value. */ public static final int SELECTION_REASON_CUSTOM_BASE = 10000; /** A default size in bytes for an individual allocation that forms part of a larger buffer. */ public static final int DEFAULT_BUFFER_SEGMENT_SIZE = 64 * 1024; /** A default seek back increment, in milliseconds. */ public static final long DEFAULT_SEEK_BACK_INCREMENT_MS = 5_000; /** A default seek forward increment, in milliseconds. */ public static final long DEFAULT_SEEK_FORWARD_INCREMENT_MS = 15_000; /** * A default maximum position for which a seek to previous will seek to the previous window, in * milliseconds. */ public static final long DEFAULT_MAX_SEEK_TO_PREVIOUS_POSITION_MS = 3_000; /** "cenc" scheme type name as defined in ISO/IEC 23001-7:2016. */ @SuppressWarnings("ConstantField") public static final String CENC_TYPE_cenc = "cenc"; /** "cbc1" scheme type name as defined in ISO/IEC 23001-7:2016. */ @SuppressWarnings("ConstantField") public static final String CENC_TYPE_cbc1 = "cbc1"; /** "cens" scheme type name as defined in ISO/IEC 23001-7:2016. */ @SuppressWarnings("ConstantField") public static final String CENC_TYPE_cens = "cens"; /** "cbcs" scheme type name as defined in ISO/IEC 23001-7:2016. */ @SuppressWarnings("ConstantField") public static final String CENC_TYPE_cbcs = "cbcs"; /** * The Nil UUID as defined by <a * href="https://tools.ietf.org/html/rfc4122#section-4.1.7">RFC4122</a>. */ public static final UUID UUID_NIL = new UUID(0L, 0L); /** * UUID for the W3C <a * href="https://w3c.github.io/encrypted-media/format-registry/initdata/cenc.html">Common PSSH * box</a>. */ public static final UUID COMMON_PSSH_UUID = new UUID(0x1077EFECC0B24D02L, 0xACE33C1E52E2FB4BL); /** * UUID for the ClearKey DRM scheme. * * <p>ClearKey is supported on Android devices running Android 5.0 (API Level 21) and up. */ public static final UUID CLEARKEY_UUID = new UUID(0xE2719D58A985B3C9L, 0x781AB030AF78D30EL); /** * UUID for the Widevine DRM scheme. * * <p>Widevine is supported on Android devices running Android 4.3 (API Level 18) and up. */ public static final UUID WIDEVINE_UUID = new UUID(0xEDEF8BA979D64ACEL, 0xA3C827DCD51D21EDL); /** * UUID for the PlayReady DRM scheme. * * <p>PlayReady is supported on all AndroidTV devices. Note that most other Android devices do not * provide PlayReady support. */ public static final UUID PLAYREADY_UUID = new UUID(0x9A04F07998404286L, 0xAB92E65BE0885F95L); /** * The stereo mode for 360/3D/VR videos. One of {@link Format#NO_VALUE}, {@link * #STEREO_MODE_MONO}, {@link #STEREO_MODE_TOP_BOTTOM}, {@link #STEREO_MODE_LEFT_RIGHT} or {@link * #STEREO_MODE_STEREO_MESH}. */ @Documented @Retention(RetentionPolicy.SOURCE) @Target(TYPE_USE) @IntDef({ Format.NO_VALUE, STEREO_MODE_MONO, STEREO_MODE_TOP_BOTTOM, STEREO_MODE_LEFT_RIGHT, STEREO_MODE_STEREO_MESH }) public @interface StereoMode {} /** Indicates Monoscopic stereo layout, used with 360/3D/VR videos. */ public static final int STEREO_MODE_MONO = 0; /** Indicates Top-Bottom stereo layout, used with 360/3D/VR videos. */ public static final int STEREO_MODE_TOP_BOTTOM = 1; /** Indicates Left-Right stereo layout, used with 360/3D/VR videos. */ public static final int STEREO_MODE_LEFT_RIGHT = 2; /** * Indicates a stereo layout where the left and right eyes have separate meshes, used with * 360/3D/VR videos. */ public static final int STEREO_MODE_STEREO_MESH = 3; // LINT.IfChange(color_space) /** * Video colorspaces. One of {@link Format#NO_VALUE}, {@link #COLOR_SPACE_BT601}, {@link * #COLOR_SPACE_BT709} or {@link #COLOR_SPACE_BT2020}. */ @Documented @Retention(RetentionPolicy.SOURCE) @Target(TYPE_USE) @IntDef({Format.NO_VALUE, COLOR_SPACE_BT601, COLOR_SPACE_BT709, COLOR_SPACE_BT2020}) public @interface ColorSpace {} /** * @see MediaFormat#COLOR_STANDARD_BT601_PAL */ public static final int COLOR_SPACE_BT601 = MediaFormat.COLOR_STANDARD_BT601_PAL; /** * @see MediaFormat#COLOR_STANDARD_BT709 */ public static final int COLOR_SPACE_BT709 = MediaFormat.COLOR_STANDARD_BT709; /** * @see MediaFormat#COLOR_STANDARD_BT2020 */ public static final int COLOR_SPACE_BT2020 = MediaFormat.COLOR_STANDARD_BT2020; // LINT.IfChange(color_transfer) /** * Video color transfer characteristics. One of {@link Format#NO_VALUE}, {@link * #COLOR_TRANSFER_SDR}, {@link #COLOR_TRANSFER_ST2084} or {@link #COLOR_TRANSFER_HLG}. */ @Documented @Retention(RetentionPolicy.SOURCE) @Target(TYPE_USE) @IntDef({Format.NO_VALUE, COLOR_TRANSFER_SDR, COLOR_TRANSFER_ST2084, COLOR_TRANSFER_HLG}) public @interface ColorTransfer {} /** * @see MediaFormat#COLOR_TRANSFER_SDR_VIDEO */ public static final int COLOR_TRANSFER_SDR = MediaFormat.COLOR_TRANSFER_SDR_VIDEO; /** * @see MediaFormat#COLOR_TRANSFER_ST2084 */ public static final int COLOR_TRANSFER_ST2084 = MediaFormat.COLOR_TRANSFER_ST2084; /** * @see MediaFormat#COLOR_TRANSFER_HLG */ public static final int COLOR_TRANSFER_HLG = MediaFormat.COLOR_TRANSFER_HLG; // LINT.IfChange(color_range) /** * Video color range. One of {@link Format#NO_VALUE}, {@link #COLOR_RANGE_LIMITED} or {@link * #COLOR_RANGE_FULL}. */ @Documented @Retention(RetentionPolicy.SOURCE) @Target(TYPE_USE) @IntDef({Format.NO_VALUE, COLOR_RANGE_LIMITED, COLOR_RANGE_FULL}) public @interface ColorRange {} /** * @see MediaFormat#COLOR_RANGE_LIMITED */ public static final int COLOR_RANGE_LIMITED = MediaFormat.COLOR_RANGE_LIMITED; /** * @see MediaFormat#COLOR_RANGE_FULL */ public static final int COLOR_RANGE_FULL = MediaFormat.COLOR_RANGE_FULL; /** Video projection types. */ @Documented @Retention(RetentionPolicy.SOURCE) @Target(TYPE_USE) @IntDef({ Format.NO_VALUE, PROJECTION_RECTANGULAR, PROJECTION_EQUIRECTANGULAR, PROJECTION_CUBEMAP, PROJECTION_MESH }) public @interface Projection {} /** Conventional rectangular projection. */ public static final int PROJECTION_RECTANGULAR = 0; /** Equirectangular spherical projection. */ public static final int PROJECTION_EQUIRECTANGULAR = 1; /** Cube map projection. */ public static final int PROJECTION_CUBEMAP = 2; /** 3-D mesh projection. */ public static final int PROJECTION_MESH = 3; /** * Priority for media playback. * * <p>Larger values indicate higher priorities. */ public static final int PRIORITY_PLAYBACK = 0; /** * Priority for media downloading. * * <p>Larger values indicate higher priorities. */ public static final int PRIORITY_DOWNLOAD = PRIORITY_PLAYBACK - 1000; /** * Network connection type. One of {@link #NETWORK_TYPE_UNKNOWN}, {@link #NETWORK_TYPE_OFFLINE}, * {@link #NETWORK_TYPE_WIFI}, {@link #NETWORK_TYPE_2G}, {@link #NETWORK_TYPE_3G}, {@link * #NETWORK_TYPE_4G}, {@link #NETWORK_TYPE_5G_SA}, {@link #NETWORK_TYPE_5G_NSA}, {@link * #NETWORK_TYPE_CELLULAR_UNKNOWN}, {@link #NETWORK_TYPE_ETHERNET} or {@link #NETWORK_TYPE_OTHER}. */ // @Target list includes both 'default' targets and TYPE_USE, to ensure backwards compatibility // with Kotlin usages from before TYPE_USE was added. @Documented @Retention(RetentionPolicy.SOURCE) @Target({FIELD, METHOD, PARAMETER, LOCAL_VARIABLE, TYPE_USE}) @IntDef({ NETWORK_TYPE_UNKNOWN, NETWORK_TYPE_OFFLINE, NETWORK_TYPE_WIFI, NETWORK_TYPE_2G, NETWORK_TYPE_3G, NETWORK_TYPE_4G, NETWORK_TYPE_5G_SA, NETWORK_TYPE_5G_NSA, NETWORK_TYPE_CELLULAR_UNKNOWN, NETWORK_TYPE_ETHERNET, NETWORK_TYPE_OTHER }) public @interface NetworkType {} /** Unknown network type. */ public static final int NETWORK_TYPE_UNKNOWN = 0; /** No network connection. */ public static final int NETWORK_TYPE_OFFLINE = 1; /** Network type for a Wifi connection. */ public static final int NETWORK_TYPE_WIFI = 2; /** Network type for a 2G cellular connection. */ public static final int NETWORK_TYPE_2G = 3; /** Network type for a 3G cellular connection. */ public static final int NETWORK_TYPE_3G = 4; /** Network type for a 4G cellular connection. */ public static final int NETWORK_TYPE_4G = 5; /** Network type for a 5G stand-alone (SA) cellular connection. */ public static final int NETWORK_TYPE_5G_SA = 9; /** Network type for a 5G non-stand-alone (NSA) cellular connection. */ public static final int NETWORK_TYPE_5G_NSA = 10; /** * Network type for cellular connections which cannot be mapped to one of {@link * #NETWORK_TYPE_2G}, {@link #NETWORK_TYPE_3G}, or {@link #NETWORK_TYPE_4G}. */ public static final int NETWORK_TYPE_CELLULAR_UNKNOWN = 6; /** Network type for an Ethernet connection. */ public static final int NETWORK_TYPE_ETHERNET = 7; /** Network type for other connections which are not Wifi or cellular (e.g. VPN, Bluetooth). */ public static final int NETWORK_TYPE_OTHER = 8; /** * Mode specifying whether the player should hold a WakeLock and a WifiLock. One of {@link * #WAKE_MODE_NONE}, {@link #WAKE_MODE_LOCAL} or {@link #WAKE_MODE_NETWORK}. */ // @Target list includes both 'default' targets and TYPE_USE, to ensure backwards compatibility // with Kotlin usages from before TYPE_USE was added. @Documented @Retention(RetentionPolicy.SOURCE) @Target({FIELD, METHOD, PARAMETER, LOCAL_VARIABLE, TYPE_USE}) @IntDef({WAKE_MODE_NONE, WAKE_MODE_LOCAL, WAKE_MODE_NETWORK}) public @interface WakeMode {} /** * A wake mode that will not cause the player to hold any locks. * * <p>This is suitable for applications that do not play media with the screen off. */ public static final int WAKE_MODE_NONE = 0; /** * A wake mode that will cause the player to hold a {@link android.os.PowerManager.WakeLock} * during playback. * * <p>This is suitable for applications that play media with the screen off and do not load media * over wifi. */ public static final int WAKE_MODE_LOCAL = 1; /** * A wake mode that will cause the player to hold a {@link android.os.PowerManager.WakeLock} and a * {@link android.net.wifi.WifiManager.WifiLock} during playback. * * <p>This is suitable for applications that play media with the screen off and may load media * over wifi. */ public static final int WAKE_MODE_NETWORK = 2; /** * Track role flags. Possible flag values are {@link #ROLE_FLAG_MAIN}, {@link * #ROLE_FLAG_ALTERNATE}, {@link #ROLE_FLAG_SUPPLEMENTARY}, {@link #ROLE_FLAG_COMMENTARY}, {@link * #ROLE_FLAG_DUB}, {@link #ROLE_FLAG_EMERGENCY}, {@link #ROLE_FLAG_CAPTION}, {@link * #ROLE_FLAG_SUBTITLE}, {@link #ROLE_FLAG_SIGN}, {@link #ROLE_FLAG_DESCRIBES_VIDEO}, {@link * #ROLE_FLAG_DESCRIBES_MUSIC_AND_SOUND}, {@link #ROLE_FLAG_ENHANCED_DIALOG_INTELLIGIBILITY}, * {@link #ROLE_FLAG_TRANSCRIBES_DIALOG}, {@link #ROLE_FLAG_EASY_TO_READ} and {@link * #ROLE_FLAG_TRICK_PLAY}. */ // @Target list includes both 'default' targets and TYPE_USE, to ensure backwards compatibility // with Kotlin usages from before TYPE_USE was added. @Documented @Retention(RetentionPolicy.SOURCE) @Target({FIELD, METHOD, PARAMETER, LOCAL_VARIABLE, TYPE_USE}) @IntDef( flag = true, value = { ROLE_FLAG_MAIN, ROLE_FLAG_ALTERNATE, ROLE_FLAG_SUPPLEMENTARY, ROLE_FLAG_COMMENTARY, ROLE_FLAG_DUB, ROLE_FLAG_EMERGENCY, ROLE_FLAG_CAPTION, ROLE_FLAG_SUBTITLE, ROLE_FLAG_SIGN, ROLE_FLAG_DESCRIBES_VIDEO, ROLE_FLAG_DESCRIBES_MUSIC_AND_SOUND, ROLE_FLAG_ENHANCED_DIALOG_INTELLIGIBILITY, ROLE_FLAG_TRANSCRIBES_DIALOG, ROLE_FLAG_EASY_TO_READ, ROLE_FLAG_TRICK_PLAY }) public @interface RoleFlags {} // LINT.IfChange(role_flags) /** Indicates a main track. */ public static final int ROLE_FLAG_MAIN = 1; /** * Indicates an alternate track. For example a video track recorded from an different view point * than the main track(s). */ public static final int ROLE_FLAG_ALTERNATE = 1 << 1; /** * Indicates a supplementary track, meaning the track has lower importance than the main track(s). * For example a video track that provides a visual accompaniment to a main audio track. */ public static final int ROLE_FLAG_SUPPLEMENTARY = 1 << 2; /** Indicates the track contains commentary, for example from the director. */ public static final int ROLE_FLAG_COMMENTARY = 1 << 3; /** * Indicates the track is in a different language from the original, for example dubbed audio or * translated captions. */ public static final int ROLE_FLAG_DUB = 1 << 4; /** Indicates the track contains information about a current emergency. */ public static final int ROLE_FLAG_EMERGENCY = 1 << 5; /** * Indicates the track contains captions. This flag may be set on video tracks to indicate the * presence of burned in captions. */ public static final int ROLE_FLAG_CAPTION = 1 << 6; /** * Indicates the track contains subtitles. This flag may be set on video tracks to indicate the * presence of burned in subtitles. */ public static final int ROLE_FLAG_SUBTITLE = 1 << 7; /** Indicates the track contains a visual sign-language interpretation of an audio track. */ public static final int ROLE_FLAG_SIGN = 1 << 8; /** Indicates the track contains an audio or textual description of a video track. */ public static final int ROLE_FLAG_DESCRIBES_VIDEO = 1 << 9; /** Indicates the track contains a textual description of music and sound. */ public static final int ROLE_FLAG_DESCRIBES_MUSIC_AND_SOUND = 1 << 10; /** Indicates the track is designed for improved intelligibility of dialogue. */ public static final int ROLE_FLAG_ENHANCED_DIALOG_INTELLIGIBILITY = 1 << 11; /** Indicates the track contains a transcription of spoken dialog. */ public static final int ROLE_FLAG_TRANSCRIBES_DIALOG = 1 << 12; /** Indicates the track contains a text that has been edited for ease of reading. */ public static final int ROLE_FLAG_EASY_TO_READ = 1 << 13; /** Indicates the track is intended for trick play. */ public static final int ROLE_FLAG_TRICK_PLAY = 1 << 14; /** * Level of renderer support for a format. One of {@link #FORMAT_HANDLED}, {@link * #FORMAT_EXCEEDS_CAPABILITIES}, {@link #FORMAT_UNSUPPORTED_DRM}, {@link * #FORMAT_UNSUPPORTED_SUBTYPE} or {@link #FORMAT_UNSUPPORTED_TYPE}. */ // @Target list includes both 'default' targets and TYPE_USE, to ensure backwards compatibility // with Kotlin usages from before TYPE_USE was added. @Documented @Retention(RetentionPolicy.SOURCE) @Target({FIELD, METHOD, PARAMETER, LOCAL_VARIABLE, TYPE_USE}) @IntDef({ FORMAT_HANDLED, FORMAT_EXCEEDS_CAPABILITIES, FORMAT_UNSUPPORTED_DRM, FORMAT_UNSUPPORTED_SUBTYPE, FORMAT_UNSUPPORTED_TYPE }) public @interface FormatSupport {} // TODO(b/172315872) Renderer was a link. Link to equivalent concept or remove @code. /** The {@code Renderer} is capable of rendering the format. */ public static final int FORMAT_HANDLED = 0b100; /** * The {@code Renderer} is capable of rendering formats with the same MIME type, but the * properties of the format exceed the renderer's capabilities. There is a chance the renderer * will be able to play the format in practice because some renderers report their capabilities * conservatively, but the expected outcome is that playback will fail. * * <p>Example: The {@code Renderer} is capable of rendering H264 and the format's MIME type is * {@code MimeTypes#VIDEO_H264}, but the format's resolution exceeds the maximum limit supported * by the underlying H264 decoder. */ public static final int FORMAT_EXCEEDS_CAPABILITIES = 0b011; /** * The {@code Renderer} is capable of rendering formats with the same MIME type, but is not * capable of rendering the format because the format's drm protection is not supported. * * <p>Example: The {@code Renderer} is capable of rendering H264 and the format's MIME type is * {@link MimeTypes#VIDEO_H264}, but the format indicates PlayReady drm protection whereas the * renderer only supports Widevine. */ public static final int FORMAT_UNSUPPORTED_DRM = 0b010; /** * The {@code Renderer} is a general purpose renderer for formats of the same top-level type, but * is not capable of rendering the format or any other format with the same MIME type because the * sub-type is not supported. * * <p>Example: The {@code Renderer} is a general purpose audio renderer and the format's MIME type * matches audio/[subtype], but there does not exist a suitable decoder for [subtype]. */ public static final int FORMAT_UNSUPPORTED_SUBTYPE = 0b001; /** * The {@code Renderer} is not capable of rendering the format, either because it does not support * the format's top-level type, or because it's a specialized renderer for a different MIME type. * * <p>Example: The {@code Renderer} is a general purpose video renderer, but the format has an * audio MIME type. */ public static final int FORMAT_UNSUPPORTED_TYPE = 0b000; /** * @deprecated Use {@link Util#usToMs(long)}. */ @InlineMe( replacement = "Util.usToMs(timeUs)", imports = {"com.google.android.exoplayer2.util.Util"}) @Deprecated public static long usToMs(long timeUs) { return Util.usToMs(timeUs); } /** * @deprecated Use {@link Util#msToUs(long)}. */ @InlineMe( replacement = "Util.msToUs(timeMs)", imports = {"com.google.android.exoplayer2.util.Util"}) @Deprecated public static long msToUs(long timeMs) { return Util.msToUs(timeMs); } /** * @deprecated Use {@link Util#generateAudioSessionIdV21(Context)}. */ @InlineMe( replacement = "Util.generateAudioSessionIdV21(context)", imports = {"com.google.android.exoplayer2.util.Util"}) @Deprecated @RequiresApi(21) public static int generateAudioSessionIdV21(Context context) { return Util.generateAudioSessionIdV21(context); } /** * @deprecated Use {@link Util#getFormatSupportString(int)}. */ @InlineMe( replacement = "Util.getFormatSupportString(formatSupport)", imports = {"com.google.android.exoplayer2.util.Util"}) @Deprecated public static String getFormatSupportString(@FormatSupport int formatSupport) { return Util.getFormatSupportString(formatSupport); } /** * @deprecated Use {@link Util#getErrorCodeForMediaDrmErrorCode(int)}. */ @InlineMe( replacement = "Util.getErrorCodeForMediaDrmErrorCode(mediaDrmErrorCode)", imports = {"com.google.android.exoplayer2.util.Util"}) @Deprecated public static @PlaybackException.ErrorCode int getErrorCodeForMediaDrmErrorCode( int mediaDrmErrorCode) { return Util.getErrorCodeForMediaDrmErrorCode(mediaDrmErrorCode); } }
NekoX-Dev/NekoX
TMessagesProj/src/main/java/com/google/android/exoplayer2/C.java
44,891
/* * Copyright 2015 The gRPC Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.grpc; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.Preconditions; import java.io.File; import java.io.InputStream; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; /** * A builder for {@link Server} instances. * * @param <T> The concrete type of this builder. * @since 1.0.0 */ public abstract class ServerBuilder<T extends ServerBuilder<T>> { /** * Static factory for creating a new ServerBuilder. * * @param port the port to listen on * @since 1.0.0 */ public static ServerBuilder<?> forPort(int port) { return ServerProvider.provider().builderForPort(port); } /** * Execute application code directly in the transport thread. * * <p>Depending on the underlying transport, using a direct executor may lead to substantial * performance improvements. However, it also requires the application to not block under * any circumstances. * * <p>Calling this method is semantically equivalent to calling {@link #executor(Executor)} and * passing in a direct executor. However, this is the preferred way as it may allow the transport * to perform special optimizations. * * @return this * @since 1.0.0 */ public abstract T directExecutor(); /** * Provides a custom executor. * * <p>It's an optional parameter. If the user has not provided an executor when the server is * built, the builder will use a static cached thread pool. * * <p>The server won't take ownership of the given executor. It's caller's responsibility to * shut down the executor when it's desired. * * @return this * @since 1.0.0 */ public abstract T executor(@Nullable Executor executor); /** * Allows for defining a way to provide a custom executor to handle the server call. * This executor is the result of calling * {@link ServerCallExecutorSupplier#getExecutor(ServerCall, Metadata)} per RPC. * * <p>It's an optional parameter. If it is provided, the {@link #executor(Executor)} would still * run necessary tasks before the {@link ServerCallExecutorSupplier} is ready to be called, then * it switches over. But if calling {@link ServerCallExecutorSupplier} returns null, the server * call is still handled by the default {@link #executor(Executor)} as a fallback. * * @param executorSupplier the server call executor provider * @return this * @since 1.39.0 * * */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/8274") public T callExecutor(ServerCallExecutorSupplier executorSupplier) { return thisT(); } /** * Adds a service implementation to the handler registry. * * @param service ServerServiceDefinition object * @return this * @since 1.0.0 */ public abstract T addService(ServerServiceDefinition service); /** * Adds a service implementation to the handler registry. * * @param bindableService BindableService object * @return this * @since 1.0.0 */ public abstract T addService(BindableService bindableService); /** * Adds a list of service implementations to the handler registry together. * * @param services the list of ServerServiceDefinition objects * @return this * @since 1.37.0 */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/7925") public final T addServices(List<ServerServiceDefinition> services) { checkNotNull(services, "services"); for (ServerServiceDefinition service : services) { addService(service); } return thisT(); } /** * Adds a {@link ServerInterceptor} that is run for all services on the server. Interceptors * added through this method always run before per-service interceptors added through {@link * ServerInterceptors}. Interceptors run in the reverse order in which they are added, just as * with consecutive calls to {@code ServerInterceptors.intercept()}. * * @param interceptor the all-service interceptor * @return this * @since 1.5.0 */ public T intercept(ServerInterceptor interceptor) { throw new UnsupportedOperationException(); } /** * Adds a {@link ServerTransportFilter}. The order of filters being added is the order they will * be executed. * * @return this * @since 1.2.0 */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/2132") public T addTransportFilter(ServerTransportFilter filter) { throw new UnsupportedOperationException(); } /** * Adds a {@link ServerStreamTracer.Factory} to measure server-side traffic. The order of * factories being added is the order they will be executed. * * @return this * @since 1.3.0 */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/2861") public T addStreamTracerFactory(ServerStreamTracer.Factory factory) { throw new UnsupportedOperationException(); } /** * Sets a fallback handler registry that will be looked up in if a method is not found in the * primary registry. The primary registry (configured via {@code addService()}) is faster but * immutable. The fallback registry is more flexible and allows implementations to mutate over * time and load services on-demand. * * @return this * @since 1.0.0 */ public abstract T fallbackHandlerRegistry(@Nullable HandlerRegistry fallbackRegistry); /** * Makes the server use TLS. * * @param certChain file containing the full certificate chain * @param privateKey file containing the private key * * @return this * @throws UnsupportedOperationException if the server does not support TLS. * @since 1.0.0 */ public abstract T useTransportSecurity(File certChain, File privateKey); /** * Makes the server use TLS. * * @param certChain InputStream containing the full certificate chain * @param privateKey InputStream containing the private key * * @return this * @throws UnsupportedOperationException if the server does not support TLS, or does not support * reading these files from an InputStream. * @since 1.12.0 */ public T useTransportSecurity(InputStream certChain, InputStream privateKey) { throw new UnsupportedOperationException(); } /** * Set the decompression registry for use in the channel. This is an advanced API call and * shouldn't be used unless you are using custom message encoding. The default supported * decompressors are in {@code DecompressorRegistry.getDefaultInstance}. * * @return this * @since 1.0.0 */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1704") public abstract T decompressorRegistry(@Nullable DecompressorRegistry registry); /** * Set the compression registry for use in the channel. This is an advanced API call and * shouldn't be used unless you are using custom message encoding. The default supported * compressors are in {@code CompressorRegistry.getDefaultInstance}. * * @return this * @since 1.0.0 */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1704") public abstract T compressorRegistry(@Nullable CompressorRegistry registry); /** * Sets the permitted time for new connections to complete negotiation handshakes before being * killed. The default value is 2 minutes. * * @return this * @throws IllegalArgumentException if timeout is negative * @throws UnsupportedOperationException if unsupported * @since 1.8.0 */ public T handshakeTimeout(long timeout, TimeUnit unit) { throw new UnsupportedOperationException(); } /** * Sets the time without read activity before sending a keepalive ping. An unreasonably small * value might be increased, and {@code Long.MAX_VALUE} nano seconds or an unreasonably large * value will disable keepalive. The typical default is two hours when supported. * * @throws IllegalArgumentException if time is not positive * @throws UnsupportedOperationException if unsupported * @see <a href="https://github.com/grpc/proposal/blob/master/A9-server-side-conn-mgt.md">gRFC A9 * Server-side Connection Management</a> * @since 1.47.0 */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/9009") public T keepAliveTime(long keepAliveTime, TimeUnit timeUnit) { throw new UnsupportedOperationException(); } /** * Sets a time waiting for read activity after sending a keepalive ping. If the time expires * without any read activity on the connection, the connection is considered dead. An unreasonably * small value might be increased. Defaults to 20 seconds when supported. * * <p>This value should be at least multiple times the RTT to allow for lost packets. * * @throws IllegalArgumentException if timeout is not positive * @throws UnsupportedOperationException if unsupported * @see <a href="https://github.com/grpc/proposal/blob/master/A9-server-side-conn-mgt.md">gRFC A9 * Server-side Connection Management</a> * @since 1.47.0 */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/9009") public T keepAliveTimeout(long keepAliveTimeout, TimeUnit timeUnit) { throw new UnsupportedOperationException(); } /** * Sets the maximum connection idle time, connections being idle for longer than which will be * gracefully terminated. Idleness duration is defined since the most recent time the number of * outstanding RPCs became zero or the connection establishment. An unreasonably small value might * be increased. {@code Long.MAX_VALUE} nano seconds or an unreasonably large value will disable * max connection idle. * * @throws IllegalArgumentException if idle is not positive * @throws UnsupportedOperationException if unsupported * @see <a href="https://github.com/grpc/proposal/blob/master/A9-server-side-conn-mgt.md">gRFC A9 * Server-side Connection Management</a> * @since 1.47.0 */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/9009") public T maxConnectionIdle(long maxConnectionIdle, TimeUnit timeUnit) { throw new UnsupportedOperationException(); } /** * Sets the maximum connection age, connections lasting longer than which will be gracefully * terminated. An unreasonably small value might be increased. A random jitter of +/-10% will be * added to it. {@code Long.MAX_VALUE} nano seconds or an unreasonably large value will disable * max connection age. * * @throws IllegalArgumentException if age is not positive * @throws UnsupportedOperationException if unsupported * @see <a href="https://github.com/grpc/proposal/blob/master/A9-server-side-conn-mgt.md">gRFC A9 * Server-side Connection Management</a> * @since 1.47.0 */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/9009") public T maxConnectionAge(long maxConnectionAge, TimeUnit timeUnit) { throw new UnsupportedOperationException(); } /** * Sets the grace time for the graceful connection termination. Once the max connection age * is reached, RPCs have the grace time to complete. RPCs that do not complete in time will be * cancelled, allowing the connection to terminate. {@code Long.MAX_VALUE} nano seconds or an * unreasonably large value are considered infinite. * * @throws IllegalArgumentException if grace is negative * @throws UnsupportedOperationException if unsupported * @see #maxConnectionAge(long, TimeUnit) * @see <a href="https://github.com/grpc/proposal/blob/master/A9-server-side-conn-mgt.md">gRFC A9 * Server-side Connection Management</a> * @since 1.47.0 */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/9009") public T maxConnectionAgeGrace(long maxConnectionAgeGrace, TimeUnit timeUnit) { throw new UnsupportedOperationException(); } /** * Specify the most aggressive keep-alive time clients are permitted to configure. The server will * try to detect clients exceeding this rate and when detected will forcefully close the * connection. The typical default is 5 minutes when supported. * * <p>Even though a default is defined that allows some keep-alives, clients must not use * keep-alive without approval from the service owner. Otherwise, they may experience failures in * the future if the service becomes more restrictive. When unthrottled, keep-alives can cause a * significant amount of traffic and CPU usage, so clients and servers should be conservative in * what they use and accept. * * @throws IllegalArgumentException if time is negative * @throws UnsupportedOperationException if unsupported * @see #permitKeepAliveWithoutCalls(boolean) * @see <a href="https://github.com/grpc/proposal/blob/master/A8-client-side-keepalive.md">gRFC A8 * Client-side Keepalive</a> * @since 1.47.0 */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/9009") public T permitKeepAliveTime(long keepAliveTime, TimeUnit timeUnit) { throw new UnsupportedOperationException(); } /** * Sets whether to allow clients to send keep-alive HTTP/2 PINGs even if there are no outstanding * RPCs on the connection. Defaults to {@code false} when supported. * * @throws UnsupportedOperationException if unsupported * @see #permitKeepAliveTime(long, TimeUnit) * @see <a href="https://github.com/grpc/proposal/blob/master/A8-client-side-keepalive.md">gRFC A8 * Client-side Keepalive</a> * @since 1.47.0 */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/9009") public T permitKeepAliveWithoutCalls(boolean permit) { throw new UnsupportedOperationException(); } /** * Sets the maximum message size allowed to be received on the server. If not called, * defaults to 4 MiB. The default provides protection to servers who haven't considered the * possibility of receiving large messages while trying to be large enough to not be hit in normal * usage. * * <p>This method is advisory, and implementations may decide to not enforce this. Currently, * the only known transport to not enforce this is {@code InProcessServer}. * * @param bytes the maximum number of bytes a single message can be. * @return this * @throws IllegalArgumentException if bytes is negative. * @throws UnsupportedOperationException if unsupported. * @since 1.13.0 */ public T maxInboundMessageSize(int bytes) { // intentional noop rather than throw, this method is only advisory. Preconditions.checkArgument(bytes >= 0, "bytes must be >= 0"); return thisT(); } /** * Sets the maximum size of metadata allowed to be received. {@code Integer.MAX_VALUE} disables * the enforcement. The default is implementation-dependent, but is not generally less than 8 KiB * and may be unlimited. * * <p>This is cumulative size of the metadata. The precise calculation is * implementation-dependent, but implementations are encouraged to follow the calculation used for * <a href="http://httpwg.org/specs/rfc7540.html#rfc.section.6.5.2"> * HTTP/2's SETTINGS_MAX_HEADER_LIST_SIZE</a>. It sums the bytes from each entry's key and value, * plus 32 bytes of overhead per entry. * * @param bytes the maximum size of received metadata * @return this * @throws IllegalArgumentException if bytes is non-positive * @since 1.17.0 */ public T maxInboundMetadataSize(int bytes) { Preconditions.checkArgument(bytes > 0, "maxInboundMetadataSize must be > 0"); // intentional noop rather than throw, this method is only advisory. return thisT(); } /** * Sets the BinaryLog object that this server should log to. The server does not take * ownership of the object, and users are responsible for calling {@link BinaryLog#close()}. * * @param binaryLog the object to provide logging. * @return this * @since 1.13.0 */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/4017") public T setBinaryLog(BinaryLog binaryLog) { throw new UnsupportedOperationException(); } /** * Builds a server using the given parameters. * * <p>The returned service will not been started or be bound a port. You will need to start it * with {@link Server#start()}. * * @return a new Server * @since 1.0.0 */ public abstract Server build(); /** * Returns the correctly typed version of the builder. */ private T thisT() { @SuppressWarnings("unchecked") T thisT = (T) this; return thisT; } }
grpc/grpc-java
api/src/main/java/io/grpc/ServerBuilder.java
44,892
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; /** * Constants. * * @author Remy Maucherat */ public final class Constants { public static final Charset DEFAULT_URI_CHARSET = StandardCharsets.UTF_8; public static final Charset DEFAULT_BODY_CHARSET = StandardCharsets.ISO_8859_1; public static final int MAX_NOTES = 32; // Request states public static final int STAGE_NEW = 0; public static final int STAGE_PARSE = 1; public static final int STAGE_PREPARE = 2; public static final int STAGE_SERVICE = 3; public static final int STAGE_ENDINPUT = 4; public static final int STAGE_ENDOUTPUT = 5; public static final int STAGE_KEEPALIVE = 6; public static final int STAGE_ENDED = 7; // Default protocol settings public static final int DEFAULT_CONNECTION_LINGER = -1; public static final boolean DEFAULT_TCP_NO_DELAY = true; /** * The request attribute that is set to the value of {@code Boolean.TRUE} if connector processing this request * supports use of sendfile. */ public static final String SENDFILE_SUPPORTED_ATTR = "org.apache.tomcat.sendfile.support"; /** * The request attribute that can be used by a servlet to pass to the connector the name of the file that is to be * served by sendfile. The value should be {@code String} that is {@code File.getCanonicalPath()} of the file to be * served. */ public static final String SENDFILE_FILENAME_ATTR = "org.apache.tomcat.sendfile.filename"; /** * The request attribute that can be used by a servlet to pass to the connector the start offset of the part of a * file that is to be served by sendfile. The value should be {@code java.lang.Long}. To serve complete file the * value should be {@code Long.valueOf(0)}. */ public static final String SENDFILE_FILE_START_ATTR = "org.apache.tomcat.sendfile.start"; /** * The request attribute that can be used by a servlet to pass to the connector the end offset (not including) of * the part of a file that is to be served by sendfile. The value should be {@code java.lang.Long}. To serve * complete file the value should be equal to the length of the file. */ public static final String SENDFILE_FILE_END_ATTR = "org.apache.tomcat.sendfile.end"; /** * The request attribute set by the RemoteIpFilter, RemoteIpValve (and may be set by other similar components) that * identifies for the connector the remote IP address claimed to be associated with this request when a request is * received via one or more proxies. It is typically provided via the X-Forwarded-For HTTP header. */ public static final String REMOTE_ADDR_ATTRIBUTE = "org.apache.tomcat.remoteAddr"; /** * The request attribute set by the RemoteIpFilter, RemoteIpValve (and may be set by other similar components) that * identifies for the connector the connection peer IP address. */ public static final String PEER_ADDR_ATTRIBUTE = "org.apache.tomcat.peerAddr"; }
apache/tomcat
java/org/apache/coyote/Constants.java
44,893
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.lockableobject.domain; import com.iluwatar.lockableobject.Lockable; import java.util.HashSet; import java.util.Set; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import lombok.extern.slf4j.Slf4j; /** * An abstract class of a creature that wanders across the wasteland. It can attack, get hit and * acquire a Lockable object. */ @Getter @Setter @Slf4j public abstract class Creature { private String name; private CreatureType type; private int health; private int damage; Set<Lockable> instruments; protected Creature(@NonNull String name) { this.name = name; this.instruments = new HashSet<>(); } /** * Reaches for the Lockable and tried to hold it. * * @param lockable as the Lockable to lock. * @return true of Lockable was locked by this creature. */ public boolean acquire(@NonNull Lockable lockable) { if (lockable.lock(this)) { instruments.add(lockable); return true; } return false; } /** Terminates the Creature and unlocks all the Lockable that it possesses. */ public synchronized void kill() { LOGGER.info("{} {} has been slayed!", type, name); for (Lockable lockable : instruments) { lockable.unlock(this); } this.instruments.clear(); } /** * Attacks a foe. * * @param creature as the foe to be attacked. */ public synchronized void attack(@NonNull Creature creature) { creature.hit(getDamage()); } /** * When a creature gets hit it removed the amount of damage from the creature's life. * * @param damage as the damage that was taken. */ public synchronized void hit(int damage) { if (damage < 0) { throw new IllegalArgumentException("Damage cannot be a negative number"); } if (isAlive()) { setHealth(getHealth() - damage); if (!isAlive()) { kill(); } } } /** * Checks if the creature is still alive. * * @return true of creature is alive. */ public synchronized boolean isAlive() { return getHealth() > 0; } }
iluwatar/java-design-patterns
lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Creature.java
44,894
package edu.stanford.nlp.util; import edu.stanford.nlp.util.logging.PrettyLoggable; import java.io.Serializable; /** * Base type for all annotatable core objects. Should usually be instantiated as * {@link ArrayCoreMap}. Many common key definitions live in * {@link edu.stanford.nlp.ling.CoreAnnotations}, but others may be defined elsewhere. See * {@link edu.stanford.nlp.ling.CoreAnnotations} for details. * * Note that implementations of this interface must take care to implement * equality correctly: by default, two CoreMaps are .equal if they contain the * same keys and all corresponding values are .equal. Subclasses that wish to * change this behavior (such as {@link HashableCoreMap}) must make sure that * all other CoreMap implementations have a special case in their .equals to use * that equality definition when appropriate. Similarly, care must be taken when * defining hashcodes. The default hashcode is 37 * sum of all keys' hashcodes * plus the sum of all values' hashcodes. However, use of this class as HashMap * keys is discouraged because the hashcode can change over time. Consider using * a {@link HashableCoreMap}. * * @author dramage * @author rafferty */ public interface CoreMap extends TypesafeMap, PrettyLoggable, Serializable { /** Attempt to provide a briefer and more human readable String for the contents of * a CoreMap. * The method may not be capable of printing circular dependencies in CoreMaps. * * @param what An array (varargs) of Strings that say what annotation keys * to print. These need to be provided in a shortened form where you * are just giving the part of the class name without package and up to * "Annotation". That is, * edu.stanford.nlp.ling.CoreAnnotations.PartOfSpeechAnnotation ➔ PartOfSpeech . * As a special case, an empty array means to print everything, not nothing. * @return A more human readable String giving possibly partial contents of a * CoreMap. */ String toShorterString(String... what); }
stanfordnlp/CoreNLP
src/edu/stanford/nlp/util/CoreMap.java
44,895
package com.macro.mall.model; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; public class OmsOrder implements Serializable { @ApiModelProperty(value = "订单id") private Long id; private Long memberId; private Long couponId; @ApiModelProperty(value = "订单编号") private String orderSn; @ApiModelProperty(value = "提交时间") private Date createTime; @ApiModelProperty(value = "用户帐号") private String memberUsername; @ApiModelProperty(value = "订单总金额") private BigDecimal totalAmount; @ApiModelProperty(value = "应付金额(实际支付金额)") private BigDecimal payAmount; @ApiModelProperty(value = "运费金额") private BigDecimal freightAmount; @ApiModelProperty(value = "促销优化金额(促销价、满减、阶梯价)") private BigDecimal promotionAmount; @ApiModelProperty(value = "积分抵扣金额") private BigDecimal integrationAmount; @ApiModelProperty(value = "优惠券抵扣金额") private BigDecimal couponAmount; @ApiModelProperty(value = "管理员后台调整订单使用的折扣金额") private BigDecimal discountAmount; @ApiModelProperty(value = "支付方式:0->未支付;1->支付宝;2->微信") private Integer payType; @ApiModelProperty(value = "订单来源:0->PC订单;1->app订单") private Integer sourceType; @ApiModelProperty(value = "订单状态:0->待付款;1->待发货;2->已发货;3->已完成;4->已关闭;5->无效订单") private Integer status; @ApiModelProperty(value = "订单类型:0->正常订单;1->秒杀订单") private Integer orderType; @ApiModelProperty(value = "物流公司(配送方式)") private String deliveryCompany; @ApiModelProperty(value = "物流单号") private String deliverySn; @ApiModelProperty(value = "自动确认时间(天)") private Integer autoConfirmDay; @ApiModelProperty(value = "可以获得的积分") private Integer integration; @ApiModelProperty(value = "可以活动的成长值") private Integer growth; @ApiModelProperty(value = "活动信息") private String promotionInfo; @ApiModelProperty(value = "发票类型:0->不开发票;1->电子发票;2->纸质发票") private Integer billType; @ApiModelProperty(value = "发票抬头") private String billHeader; @ApiModelProperty(value = "发票内容") private String billContent; @ApiModelProperty(value = "收票人电话") private String billReceiverPhone; @ApiModelProperty(value = "收票人邮箱") private String billReceiverEmail; @ApiModelProperty(value = "收货人姓名") private String receiverName; @ApiModelProperty(value = "收货人电话") private String receiverPhone; @ApiModelProperty(value = "收货人邮编") private String receiverPostCode; @ApiModelProperty(value = "省份/直辖市") private String receiverProvince; @ApiModelProperty(value = "城市") private String receiverCity; @ApiModelProperty(value = "区") private String receiverRegion; @ApiModelProperty(value = "详细地址") private String receiverDetailAddress; @ApiModelProperty(value = "订单备注") private String note; @ApiModelProperty(value = "确认收货状态:0->未确认;1->已确认") private Integer confirmStatus; @ApiModelProperty(value = "删除状态:0->未删除;1->已删除") private Integer deleteStatus; @ApiModelProperty(value = "下单时使用的积分") private Integer useIntegration; @ApiModelProperty(value = "支付时间") private Date paymentTime; @ApiModelProperty(value = "发货时间") private Date deliveryTime; @ApiModelProperty(value = "确认收货时间") private Date receiveTime; @ApiModelProperty(value = "评价时间") private Date commentTime; @ApiModelProperty(value = "修改时间") private Date modifyTime; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public Long getCouponId() { return couponId; } public void setCouponId(Long couponId) { this.couponId = couponId; } public String getOrderSn() { return orderSn; } public void setOrderSn(String orderSn) { this.orderSn = orderSn; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getMemberUsername() { return memberUsername; } public void setMemberUsername(String memberUsername) { this.memberUsername = memberUsername; } public BigDecimal getTotalAmount() { return totalAmount; } public void setTotalAmount(BigDecimal totalAmount) { this.totalAmount = totalAmount; } public BigDecimal getPayAmount() { return payAmount; } public void setPayAmount(BigDecimal payAmount) { this.payAmount = payAmount; } public BigDecimal getFreightAmount() { return freightAmount; } public void setFreightAmount(BigDecimal freightAmount) { this.freightAmount = freightAmount; } public BigDecimal getPromotionAmount() { return promotionAmount; } public void setPromotionAmount(BigDecimal promotionAmount) { this.promotionAmount = promotionAmount; } public BigDecimal getIntegrationAmount() { return integrationAmount; } public void setIntegrationAmount(BigDecimal integrationAmount) { this.integrationAmount = integrationAmount; } public BigDecimal getCouponAmount() { return couponAmount; } public void setCouponAmount(BigDecimal couponAmount) { this.couponAmount = couponAmount; } public BigDecimal getDiscountAmount() { return discountAmount; } public void setDiscountAmount(BigDecimal discountAmount) { this.discountAmount = discountAmount; } public Integer getPayType() { return payType; } public void setPayType(Integer payType) { this.payType = payType; } public Integer getSourceType() { return sourceType; } public void setSourceType(Integer sourceType) { this.sourceType = sourceType; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Integer getOrderType() { return orderType; } public void setOrderType(Integer orderType) { this.orderType = orderType; } public String getDeliveryCompany() { return deliveryCompany; } public void setDeliveryCompany(String deliveryCompany) { this.deliveryCompany = deliveryCompany; } public String getDeliverySn() { return deliverySn; } public void setDeliverySn(String deliverySn) { this.deliverySn = deliverySn; } public Integer getAutoConfirmDay() { return autoConfirmDay; } public void setAutoConfirmDay(Integer autoConfirmDay) { this.autoConfirmDay = autoConfirmDay; } public Integer getIntegration() { return integration; } public void setIntegration(Integer integration) { this.integration = integration; } public Integer getGrowth() { return growth; } public void setGrowth(Integer growth) { this.growth = growth; } public String getPromotionInfo() { return promotionInfo; } public void setPromotionInfo(String promotionInfo) { this.promotionInfo = promotionInfo; } public Integer getBillType() { return billType; } public void setBillType(Integer billType) { this.billType = billType; } public String getBillHeader() { return billHeader; } public void setBillHeader(String billHeader) { this.billHeader = billHeader; } public String getBillContent() { return billContent; } public void setBillContent(String billContent) { this.billContent = billContent; } public String getBillReceiverPhone() { return billReceiverPhone; } public void setBillReceiverPhone(String billReceiverPhone) { this.billReceiverPhone = billReceiverPhone; } public String getBillReceiverEmail() { return billReceiverEmail; } public void setBillReceiverEmail(String billReceiverEmail) { this.billReceiverEmail = billReceiverEmail; } public String getReceiverName() { return receiverName; } public void setReceiverName(String receiverName) { this.receiverName = receiverName; } public String getReceiverPhone() { return receiverPhone; } public void setReceiverPhone(String receiverPhone) { this.receiverPhone = receiverPhone; } public String getReceiverPostCode() { return receiverPostCode; } public void setReceiverPostCode(String receiverPostCode) { this.receiverPostCode = receiverPostCode; } public String getReceiverProvince() { return receiverProvince; } public void setReceiverProvince(String receiverProvince) { this.receiverProvince = receiverProvince; } public String getReceiverCity() { return receiverCity; } public void setReceiverCity(String receiverCity) { this.receiverCity = receiverCity; } public String getReceiverRegion() { return receiverRegion; } public void setReceiverRegion(String receiverRegion) { this.receiverRegion = receiverRegion; } public String getReceiverDetailAddress() { return receiverDetailAddress; } public void setReceiverDetailAddress(String receiverDetailAddress) { this.receiverDetailAddress = receiverDetailAddress; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public Integer getConfirmStatus() { return confirmStatus; } public void setConfirmStatus(Integer confirmStatus) { this.confirmStatus = confirmStatus; } public Integer getDeleteStatus() { return deleteStatus; } public void setDeleteStatus(Integer deleteStatus) { this.deleteStatus = deleteStatus; } public Integer getUseIntegration() { return useIntegration; } public void setUseIntegration(Integer useIntegration) { this.useIntegration = useIntegration; } public Date getPaymentTime() { return paymentTime; } public void setPaymentTime(Date paymentTime) { this.paymentTime = paymentTime; } public Date getDeliveryTime() { return deliveryTime; } public void setDeliveryTime(Date deliveryTime) { this.deliveryTime = deliveryTime; } public Date getReceiveTime() { return receiveTime; } public void setReceiveTime(Date receiveTime) { this.receiveTime = receiveTime; } public Date getCommentTime() { return commentTime; } public void setCommentTime(Date commentTime) { this.commentTime = commentTime; } public Date getModifyTime() { return modifyTime; } public void setModifyTime(Date modifyTime) { this.modifyTime = modifyTime; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", memberId=").append(memberId); sb.append(", couponId=").append(couponId); sb.append(", orderSn=").append(orderSn); sb.append(", createTime=").append(createTime); sb.append(", memberUsername=").append(memberUsername); sb.append(", totalAmount=").append(totalAmount); sb.append(", payAmount=").append(payAmount); sb.append(", freightAmount=").append(freightAmount); sb.append(", promotionAmount=").append(promotionAmount); sb.append(", integrationAmount=").append(integrationAmount); sb.append(", couponAmount=").append(couponAmount); sb.append(", discountAmount=").append(discountAmount); sb.append(", payType=").append(payType); sb.append(", sourceType=").append(sourceType); sb.append(", status=").append(status); sb.append(", orderType=").append(orderType); sb.append(", deliveryCompany=").append(deliveryCompany); sb.append(", deliverySn=").append(deliverySn); sb.append(", autoConfirmDay=").append(autoConfirmDay); sb.append(", integration=").append(integration); sb.append(", growth=").append(growth); sb.append(", promotionInfo=").append(promotionInfo); sb.append(", billType=").append(billType); sb.append(", billHeader=").append(billHeader); sb.append(", billContent=").append(billContent); sb.append(", billReceiverPhone=").append(billReceiverPhone); sb.append(", billReceiverEmail=").append(billReceiverEmail); sb.append(", receiverName=").append(receiverName); sb.append(", receiverPhone=").append(receiverPhone); sb.append(", receiverPostCode=").append(receiverPostCode); sb.append(", receiverProvince=").append(receiverProvince); sb.append(", receiverCity=").append(receiverCity); sb.append(", receiverRegion=").append(receiverRegion); sb.append(", receiverDetailAddress=").append(receiverDetailAddress); sb.append(", note=").append(note); sb.append(", confirmStatus=").append(confirmStatus); sb.append(", deleteStatus=").append(deleteStatus); sb.append(", useIntegration=").append(useIntegration); sb.append(", paymentTime=").append(paymentTime); sb.append(", deliveryTime=").append(deliveryTime); sb.append(", receiveTime=").append(receiveTime); sb.append(", commentTime=").append(commentTime); sb.append(", modifyTime=").append(modifyTime); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
macrozheng/mall
mall-mbg/src/main/java/com/macro/mall/model/OmsOrder.java
44,896
/* * Copyright (c) 2016-present, RxJava Contributors. * * 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 io.reactivex.rxjava3.processors; import java.util.Objects; import java.util.concurrent.atomic.*; import org.reactivestreams.*; import io.reactivex.rxjava3.annotations.*; import io.reactivex.rxjava3.internal.functions.*; import io.reactivex.rxjava3.internal.subscriptions.*; import io.reactivex.rxjava3.internal.util.*; import io.reactivex.rxjava3.operators.QueueSubscription; import io.reactivex.rxjava3.operators.SpscLinkedArrayQueue; import io.reactivex.rxjava3.plugins.RxJavaPlugins; /** * A {@link FlowableProcessor} variant that queues up events until a single {@link Subscriber} subscribes to it, replays * those events to it until the {@code Subscriber} catches up and then switches to relaying events live to * this single {@code Subscriber} until this {@code UnicastProcessor} terminates or the {@code Subscriber} cancels * its subscription. * <p> * <img width="640" height="370" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/UnicastProcessor.png" alt=""> * <p> * This processor does not have a public constructor by design; a new empty instance of this * {@code UnicastProcessor} can be created via the following {@code create} methods that * allow specifying the retention policy for items: * <ul> * <li>{@link #create()} - creates an empty, unbounded {@code UnicastProcessor} that * caches all items and the terminal event it receives.</li> * <li>{@link #create(int)} - creates an empty, unbounded {@code UnicastProcessor} * with a hint about how many <b>total</b> items one expects to retain.</li> * <li>{@link #create(boolean)} - creates an empty, unbounded {@code UnicastProcessor} that * optionally delays an error it receives and replays it after the regular items have been emitted.</li> * <li>{@link #create(int, Runnable)} - creates an empty, unbounded {@code UnicastProcessor} * with a hint about how many <b>total</b> items one expects to retain and a callback that will be * called exactly once when the {@code UnicastProcessor} gets terminated or the single {@code Subscriber} cancels.</li> * <li>{@link #create(int, Runnable, boolean)} - creates an empty, unbounded {@code UnicastProcessor} * with a hint about how many <b>total</b> items one expects to retain and a callback that will be * called exactly once when the {@code UnicastProcessor} gets terminated or the single {@code Subscriber} cancels * and optionally delays an error it receives and replays it after the regular items have been emitted.</li> * </ul> * <p> * If more than one {@code Subscriber} attempts to subscribe to this Processor, they * will receive an {@link IllegalStateException} if this {@link UnicastProcessor} hasn't terminated yet, * or the Subscribers receive the terminal event (error or completion) if this * Processor has terminated. * <p> * The {@code UnicastProcessor} buffers notifications and replays them to the single {@code Subscriber} as requested, * for which it holds upstream items an unbounded internal buffer until they can be emitted. * <p> * Since a {@code UnicastProcessor} is a Reactive Streams {@code Processor}, * {@code null}s are not allowed (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.13">Rule 2.13</a>) as * parameters to {@link #onNext(Object)} and {@link #onError(Throwable)}. Such calls will result in a * {@link NullPointerException} being thrown and the processor's state is not changed. * <p> * Since a {@code UnicastProcessor} is a {@link io.reactivex.rxjava3.core.Flowable} as well as a {@link FlowableProcessor}, it * honors the downstream backpressure but consumes an upstream source in an unbounded manner (requesting {@link Long#MAX_VALUE}). * <p> * When this {@code UnicastProcessor} is terminated via {@link #onError(Throwable)} the current or late single {@code Subscriber} * may receive the {@code Throwable} before any available items could be emitted. To make sure an {@code onError} event is delivered * to the {@code Subscriber} after the normal items, create a {@code UnicastProcessor} with the {@link #create(boolean)} or * {@link #create(int, Runnable, boolean)} factory methods. * <p> * Even though {@code UnicastProcessor} implements the {@code Subscriber} interface, calling * {@code onSubscribe} is not required (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.12">Rule 2.12</a>) * if the processor is used as a standalone source. However, calling {@code onSubscribe} * after the {@code UnicastProcessor} reached its terminal state will result in the * given {@code Subscription} being canceled immediately. * <p> * Calling {@link #onNext(Object)}, {@link #onError(Throwable)} and {@link #onComplete()} * is required to be serialized (called from the same thread or called non-overlappingly from different threads * through external means of serialization). The {@link #toSerialized()} method available to all {@link FlowableProcessor}s * provides such serialization and also protects against reentrance (i.e., when a downstream {@code Subscriber} * consuming this processor also wants to call {@link #onNext(Object)} on this processor recursively). * <p> * This {@code UnicastProcessor} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()}, * {@link #getThrowable()} and {@link #hasSubscribers()}. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>{@code UnicastProcessor} honors the downstream backpressure but consumes an upstream source * (if any) in an unbounded manner (requesting {@link Long#MAX_VALUE}).</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code UnicastProcessor} does not operate by default on a particular {@link io.reactivex.rxjava3.core.Scheduler} and * the single {@code Subscriber} gets notified on the thread the respective {@code onXXX} methods were invoked.</dd> * <dt><b>Error handling:</b></dt> * <dd>When the {@link #onError(Throwable)} is called, the {@code UnicastProcessor} enters into a terminal state * and emits the same {@code Throwable} instance to the current single {@code Subscriber}. During this emission, * if the single {@code Subscriber}s cancels its respective {@code Subscription}s, the * {@code Throwable} is delivered to the global error handler via * {@link io.reactivex.rxjava3.plugins.RxJavaPlugins#onError(Throwable)}. * If there were no {@code Subscriber}s subscribed to this {@code UnicastProcessor} when the {@code onError()} * was called, the global error handler is not invoked. * </dd> * </dl> * <p> * Example usage: * <pre><code> * UnicastProcessor&lt;Integer&gt; processor = UnicastProcessor.create(); * * TestSubscriber&lt;Integer&gt; ts1 = processor.test(); * * // fresh UnicastProcessors are empty * ts1.assertEmpty(); * * TestSubscriber&lt;Integer&gt; ts2 = processor.test(); * * // A UnicastProcessor only allows one Subscriber during its lifetime * ts2.assertFailure(IllegalStateException.class); * * processor.onNext(1); * ts1.assertValue(1); * * processor.onNext(2); * ts1.assertValues(1, 2); * * processor.onComplete(); * ts1.assertResult(1, 2); * * // ---------------------------------------------------- * * UnicastProcessor&lt;Integer&gt; processor2 = UnicastProcessor.create(); * * // a UnicastProcessor caches events until its single Subscriber subscribes * processor2.onNext(1); * processor2.onNext(2); * processor2.onComplete(); * * TestSubscriber&lt;Integer&gt; ts3 = processor2.test(); * * // the cached events are emitted in order * ts3.assertResult(1, 2); * </code></pre> * * @param <T> the value type received and emitted by this Processor subclass * @since 2.0 */ public final class UnicastProcessor<@NonNull T> extends FlowableProcessor<T> { final SpscLinkedArrayQueue<T> queue; final AtomicReference<Runnable> onTerminate; final boolean delayError; volatile boolean done; Throwable error; final AtomicReference<Subscriber<? super T>> downstream; volatile boolean cancelled; final AtomicBoolean once; final BasicIntQueueSubscription<T> wip; final AtomicLong requested; boolean enableOperatorFusion; /** * Creates an UnicastSubject with an internal buffer capacity hint 16. * @param <T> the value type * @return an UnicastSubject instance */ @CheckReturnValue @NonNull public static <T> UnicastProcessor<T> create() { return new UnicastProcessor<>(bufferSize(), null, true); } /** * Creates an UnicastProcessor with the given internal buffer capacity hint. * @param <T> the value type * @param capacityHint the hint to size the internal unbounded buffer * @return an UnicastProcessor instance * @throws IllegalArgumentException if {@code capacityHint} is non-positive */ @CheckReturnValue @NonNull public static <T> UnicastProcessor<T> create(int capacityHint) { ObjectHelper.verifyPositive(capacityHint, "capacityHint"); return new UnicastProcessor<>(capacityHint, null, true); } /** * Creates an UnicastProcessor with default internal buffer capacity hint and delay error flag. * <p>History: 2.0.8 - experimental * @param <T> the value type * @param delayError deliver pending onNext events before onError * @return an UnicastProcessor instance * @since 2.2 */ @CheckReturnValue @NonNull public static <T> UnicastProcessor<T> create(boolean delayError) { return new UnicastProcessor<>(bufferSize(), null, delayError); } /** * Creates an UnicastProcessor with the given internal buffer capacity hint and a callback for * the case when the single Subscriber cancels its subscription or the * processor is terminated. * * <p>The callback, if not null, is called exactly once and * non-overlapped with any active replay. * * @param <T> the value type * @param capacityHint the hint to size the internal unbounded buffer * @param onTerminate the non null callback * @return an UnicastProcessor instance * @throws NullPointerException if {@code onTerminate} is {@code null} * @throws IllegalArgumentException if {@code capacityHint} is non-positive */ @CheckReturnValue @NonNull public static <T> UnicastProcessor<T> create(int capacityHint, @NonNull Runnable onTerminate) { return create(capacityHint, onTerminate, true); } /** * Creates an UnicastProcessor with the given internal buffer capacity hint, delay error flag and a callback for * the case when the single Subscriber cancels its subscription or * the processor is terminated. * * <p>The callback, if not null, is called exactly once and * non-overlapped with any active replay. * <p>History: 2.0.8 - experimental * @param <T> the value type * @param capacityHint the hint to size the internal unbounded buffer * @param onTerminate the non null callback * @param delayError deliver pending onNext events before onError * @return an UnicastProcessor instance * @throws NullPointerException if {@code onTerminate} is {@code null} * @throws IllegalArgumentException if {@code capacityHint} is non-positive * @since 2.2 */ @CheckReturnValue @NonNull public static <T> UnicastProcessor<T> create(int capacityHint, @NonNull Runnable onTerminate, boolean delayError) { Objects.requireNonNull(onTerminate, "onTerminate"); ObjectHelper.verifyPositive(capacityHint, "capacityHint"); return new UnicastProcessor<>(capacityHint, onTerminate, delayError); } /** * Creates an UnicastProcessor with the given capacity hint and callback * for when the Processor is terminated normally or its single Subscriber cancels. * <p>History: 2.0.8 - experimental * @param capacityHint the capacity hint for the internal, unbounded queue * @param onTerminate the callback to run when the Processor is terminated or cancelled, null not allowed * @param delayError deliver pending onNext events before onError * @since 2.2 */ UnicastProcessor(int capacityHint, Runnable onTerminate, boolean delayError) { this.queue = new SpscLinkedArrayQueue<>(capacityHint); this.onTerminate = new AtomicReference<>(onTerminate); this.delayError = delayError; this.downstream = new AtomicReference<>(); this.once = new AtomicBoolean(); this.wip = new UnicastQueueSubscription(); this.requested = new AtomicLong(); } void doTerminate() { Runnable r = onTerminate.getAndSet(null); if (r != null) { r.run(); } } void drainRegular(Subscriber<? super T> a) { int missed = 1; final SpscLinkedArrayQueue<T> q = queue; final boolean failFast = !delayError; for (;;) { long r = requested.get(); long e = 0L; while (r != e) { boolean d = done; T t = q.poll(); boolean empty = t == null; if (checkTerminated(failFast, d, empty, a, q)) { return; } if (empty) { break; } a.onNext(t); e++; } if (r == e && checkTerminated(failFast, done, q.isEmpty(), a, q)) { return; } if (e != 0 && r != Long.MAX_VALUE) { requested.addAndGet(-e); } missed = wip.addAndGet(-missed); if (missed == 0) { break; } } } void drainFused(Subscriber<? super T> a) { int missed = 1; final SpscLinkedArrayQueue<T> q = queue; final boolean failFast = !delayError; for (;;) { if (cancelled) { downstream.lazySet(null); return; } boolean d = done; if (failFast && d && error != null) { q.clear(); downstream.lazySet(null); a.onError(error); return; } a.onNext(null); if (d) { downstream.lazySet(null); Throwable ex = error; if (ex != null) { a.onError(ex); } else { a.onComplete(); } return; } missed = wip.addAndGet(-missed); if (missed == 0) { break; } } } void drain() { if (wip.getAndIncrement() != 0) { return; } int missed = 1; Subscriber<? super T> a = downstream.get(); for (;;) { if (a != null) { if (enableOperatorFusion) { drainFused(a); } else { drainRegular(a); } return; } missed = wip.addAndGet(-missed); if (missed == 0) { break; } a = downstream.get(); } } boolean checkTerminated(boolean failFast, boolean d, boolean empty, Subscriber<? super T> a, SpscLinkedArrayQueue<T> q) { if (cancelled) { q.clear(); downstream.lazySet(null); return true; } if (d) { if (failFast && error != null) { q.clear(); downstream.lazySet(null); a.onError(error); return true; } if (empty) { Throwable e = error; downstream.lazySet(null); if (e != null) { a.onError(e); } else { a.onComplete(); } return true; } } return false; } @Override public void onSubscribe(Subscription s) { if (done || cancelled) { s.cancel(); } else { s.request(Long.MAX_VALUE); } } @Override public void onNext(T t) { ExceptionHelper.nullCheck(t, "onNext called with a null value."); if (done || cancelled) { return; } queue.offer(t); drain(); } @Override public void onError(Throwable t) { ExceptionHelper.nullCheck(t, "onError called with a null Throwable."); if (done || cancelled) { RxJavaPlugins.onError(t); return; } error = t; done = true; doTerminate(); drain(); } @Override public void onComplete() { if (done || cancelled) { return; } done = true; doTerminate(); drain(); } @Override protected void subscribeActual(Subscriber<? super T> s) { if (!once.get() && once.compareAndSet(false, true)) { s.onSubscribe(wip); downstream.set(s); if (cancelled) { downstream.lazySet(null); } else { drain(); } } else { EmptySubscription.error(new IllegalStateException("This processor allows only a single Subscriber"), s); } } final class UnicastQueueSubscription extends BasicIntQueueSubscription<T> { private static final long serialVersionUID = -4896760517184205454L; @Nullable @Override public T poll() { return queue.poll(); } @Override public boolean isEmpty() { return queue.isEmpty(); } @Override public void clear() { queue.clear(); } @Override public int requestFusion(int requestedMode) { if ((requestedMode & QueueSubscription.ASYNC) != 0) { enableOperatorFusion = true; return QueueSubscription.ASYNC; } return QueueSubscription.NONE; } @Override public void request(long n) { if (SubscriptionHelper.validate(n)) { BackpressureHelper.add(requested, n); drain(); } } @Override public void cancel() { if (cancelled) { return; } cancelled = true; doTerminate(); downstream.lazySet(null); if (wip.getAndIncrement() == 0) { downstream.lazySet(null); if (!enableOperatorFusion) { queue.clear(); } } } } @Override @CheckReturnValue public boolean hasSubscribers() { return downstream.get() != null; } @Override @Nullable @CheckReturnValue public Throwable getThrowable() { if (done) { return error; } return null; } @Override @CheckReturnValue public boolean hasComplete() { return done && error == null; } @Override @CheckReturnValue public boolean hasThrowable() { return done && error != null; } }
ReactiveX/RxJava
src/main/java/io/reactivex/rxjava3/processors/UnicastProcessor.java
44,897
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd package com.google.protobuf; import static com.google.protobuf.Internal.checkNotNull; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.RandomAccess; /** * {@code RepeatedFieldBuilder} implements a structure that a protocol message uses to hold a * repeated field of other protocol messages. It supports the classical use case of adding immutable * {@link Message}'s to the repeated field and is highly optimized around this (no extra memory * allocations and sharing of immutable arrays). <br> * It also supports the additional use case of adding a {@link Message.Builder} to the repeated * field and deferring conversion of that {@code Builder} to an immutable {@code Message}. In this * way, it's possible to maintain a tree of {@code Builder}'s that acts as a fully read/write data * structure. <br> * Logically, one can think of a tree of builders as converting the entire tree to messages when * build is called on the root or when any method is called that desires a Message instead of a * Builder. In terms of the implementation, the {@code SingleFieldBuilder} and {@code * RepeatedFieldBuilder} classes cache messages that were created so that messages only need to be * created when some change occurred in its builder or a builder for one of its descendants. * * @param <MType> the type of message for the field * @param <BType> the type of builder for the field * @param <IType> the common interface for the message and the builder * @author [email protected] (Jon Perlow) */ public class RepeatedFieldBuilder< MType extends GeneratedMessage, BType extends GeneratedMessage.Builder, IType extends MessageOrBuilder> implements GeneratedMessage.BuilderParent { // Parent to send changes to. private GeneratedMessage.BuilderParent parent; // List of messages. Never null. It may be immutable, in which case // isMessagesListMutable will be false. See note below. private List<MType> messages; // Whether messages is an mutable array that can be modified. private boolean isMessagesListMutable; // List of builders. May be null, in which case, no nested builders were // created. If not null, entries represent the builder for that index. private List<SingleFieldBuilder<MType, BType, IType>> builders; // Here are the invariants for messages and builders: // 1. messages is never null and its count corresponds to the number of items // in the repeated field. // 2. If builders is non-null, messages and builders MUST always // contain the same number of items. // 3. Entries in either array can be null, but for any index, there MUST be // either a Message in messages or a builder in builders. // 4. If the builder at an index is non-null, the builder is // authoritative. This is the case where a Builder was set on the index. // Any message in the messages array MUST be ignored. // t. If the builder at an index is null, the message in the messages // list is authoritative. This is the case where a Message (not a Builder) // was set directly for an index. // Indicates that we've built a message and so we are now obligated // to dispatch dirty invalidations. See GeneratedMessage.BuilderListener. private boolean isClean; // A view of this builder that exposes a List interface of messages. This is // initialized on demand. This is fully backed by this object and all changes // are reflected in it. Access to any item converts it to a message if it // was a builder. private MessageExternalList<MType, BType, IType> externalMessageList; // A view of this builder that exposes a List interface of builders. This is // initialized on demand. This is fully backed by this object and all changes // are reflected in it. Access to any item converts it to a builder if it // was a message. private BuilderExternalList<MType, BType, IType> externalBuilderList; // A view of this builder that exposes a List interface of the interface // implemented by messages and builders. This is initialized on demand. This // is fully backed by this object and all changes are reflected in it. // Access to any item returns either a builder or message depending on // what is most efficient. private MessageOrBuilderExternalList<MType, BType, IType> externalMessageOrBuilderList; /** * Constructs a new builder with an empty list of messages. * * @param messages the current list of messages * @param isMessagesListMutable Whether the messages list is mutable * @param parent a listener to notify of changes * @param isClean whether the builder is initially marked clean */ public RepeatedFieldBuilder( List<MType> messages, boolean isMessagesListMutable, GeneratedMessage.BuilderParent parent, boolean isClean) { this.messages = messages; this.isMessagesListMutable = isMessagesListMutable; this.parent = parent; this.isClean = isClean; } public void dispose() { // Null out parent so we stop sending it invalidations. parent = null; } /** * Ensures that the list of messages is mutable so it can be updated. If it's immutable, a copy is * made. */ private void ensureMutableMessageList() { if (!isMessagesListMutable) { messages = new ArrayList<MType>(messages); isMessagesListMutable = true; } } /** * Ensures that the list of builders is not null. If it's null, the list is created and * initialized to be the same size as the messages list with null entries. */ private void ensureBuilders() { if (this.builders == null) { this.builders = new ArrayList<SingleFieldBuilder<MType, BType, IType>>(messages.size()); for (int i = 0; i < messages.size(); i++) { builders.add(null); } } } /** * Gets the count of items in the list. * * @return the count of items in the list. */ public int getCount() { return messages.size(); } /** * Gets whether the list is empty. * * @return whether the list is empty */ public boolean isEmpty() { return messages.isEmpty(); } /** * Get the message at the specified index. If the message is currently stored as a {@code * Builder}, it is converted to a {@code Message} by calling {@link Message.Builder#buildPartial} * on it. * * @param index the index of the message to get * @return the message for the specified index */ public MType getMessage(int index) { return getMessage(index, false); } /** * Get the message at the specified index. If the message is currently stored as a {@code * Builder}, it is converted to a {@code Message} by calling {@link Message.Builder#buildPartial} * on it. * * @param index the index of the message to get * @param forBuild this is being called for build so we want to make sure we * SingleFieldBuilder.build to send dirty invalidations * @return the message for the specified index */ private MType getMessage(int index, boolean forBuild) { if (this.builders == null) { // We don't have any builders -- return the current Message. // This is the case where no builder was created, so we MUST have a // Message. return messages.get(index); } SingleFieldBuilder<MType, BType, IType> builder = builders.get(index); if (builder == null) { // We don't have a builder -- return the current message. // This is the case where no builder was created for the entry at index, // so we MUST have a message. return messages.get(index); } else { return forBuild ? builder.build() : builder.getMessage(); } } /** * Gets a builder for the specified index. If no builder has been created for that index, a * builder is created on demand by calling {@link Message#toBuilder}. * * @param index the index of the message to get * @return The builder for that index */ public BType getBuilder(int index) { ensureBuilders(); SingleFieldBuilder<MType, BType, IType> builder = builders.get(index); if (builder == null) { MType message = messages.get(index); builder = new SingleFieldBuilder<MType, BType, IType>(message, this, isClean); builders.set(index, builder); } return builder.getBuilder(); } /** * Gets the base class interface for the specified index. This may either be a builder or a * message. It will return whatever is more efficient. * * @param index the index of the message to get * @return the message or builder for the index as the base class interface */ @SuppressWarnings("unchecked") public IType getMessageOrBuilder(int index) { if (this.builders == null) { // We don't have any builders -- return the current Message. // This is the case where no builder was created, so we MUST have a // Message. return (IType) messages.get(index); } SingleFieldBuilder<MType, BType, IType> builder = builders.get(index); if (builder == null) { // We don't have a builder -- return the current message. // This is the case where no builder was created for the entry at index, // so we MUST have a message. return (IType) messages.get(index); } else { return builder.getMessageOrBuilder(); } } /** * Sets a message at the specified index replacing the existing item at that index. * * @param index the index to set. * @param message the message to set * @return the builder */ @CanIgnoreReturnValue public RepeatedFieldBuilder<MType, BType, IType> setMessage(int index, MType message) { checkNotNull(message); ensureMutableMessageList(); messages.set(index, message); if (builders != null) { SingleFieldBuilder<MType, BType, IType> entry = builders.set(index, null); if (entry != null) { entry.dispose(); } } onChanged(); incrementModCounts(); return this; } /** * Appends the specified element to the end of this list. * * @param message the message to add * @return the builder */ @CanIgnoreReturnValue public RepeatedFieldBuilder<MType, BType, IType> addMessage(MType message) { checkNotNull(message); ensureMutableMessageList(); messages.add(message); if (builders != null) { builders.add(null); } onChanged(); incrementModCounts(); return this; } /** * Inserts the specified message at the specified position in this list. Shifts the element * currently at that position (if any) and any subsequent elements to the right (adds one to their * indices). * * @param index the index at which to insert the message * @param message the message to add * @return the builder */ @CanIgnoreReturnValue public RepeatedFieldBuilder<MType, BType, IType> addMessage(int index, MType message) { checkNotNull(message); ensureMutableMessageList(); messages.add(index, message); if (builders != null) { builders.add(index, null); } onChanged(); incrementModCounts(); return this; } /** * Appends all of the messages in the specified collection to the end of this list, in the order * that they are returned by the specified collection's iterator. * * @param values the messages to add * @return the builder */ @CanIgnoreReturnValue public RepeatedFieldBuilder<MType, BType, IType> addAllMessages( Iterable<? extends MType> values) { for (final MType value : values) { checkNotNull(value); } // If we can inspect the size, we can more efficiently add messages. int size = -1; if (values instanceof Collection) { final Collection<?> collection = (Collection<?>) values; if (collection.isEmpty()) { return this; } size = collection.size(); } ensureMutableMessageList(); if (size >= 0 && messages instanceof ArrayList) { ((ArrayList<MType>) messages).ensureCapacity(messages.size() + size); } for (MType value : values) { addMessage(value); } onChanged(); incrementModCounts(); return this; } /** * Appends a new builder to the end of this list and returns the builder. * * @param message the message to add which is the basis of the builder * @return the new builder */ public BType addBuilder(MType message) { ensureMutableMessageList(); ensureBuilders(); SingleFieldBuilder<MType, BType, IType> builder = new SingleFieldBuilder<MType, BType, IType>(message, this, isClean); messages.add(null); builders.add(builder); onChanged(); incrementModCounts(); return builder.getBuilder(); } /** * Inserts a new builder at the specified position in this list. Shifts the element currently at * that position (if any) and any subsequent elements to the right (adds one to their indices). * * @param index the index at which to insert the builder * @param message the message to add which is the basis of the builder * @return the builder */ public BType addBuilder(int index, MType message) { ensureMutableMessageList(); ensureBuilders(); SingleFieldBuilder<MType, BType, IType> builder = new SingleFieldBuilder<MType, BType, IType>(message, this, isClean); messages.add(index, null); builders.add(index, builder); onChanged(); incrementModCounts(); return builder.getBuilder(); } /** * Removes the element at the specified position in this list. Shifts any subsequent elements to * the left (subtracts one from their indices). * * @param index the index at which to remove the message */ public void remove(int index) { ensureMutableMessageList(); messages.remove(index); if (builders != null) { SingleFieldBuilder<MType, BType, IType> entry = builders.remove(index); if (entry != null) { entry.dispose(); } } onChanged(); incrementModCounts(); } /** Removes all of the elements from this list. The list will be empty after this call returns. */ public void clear() { messages = Collections.emptyList(); isMessagesListMutable = false; if (builders != null) { for (SingleFieldBuilder<MType, BType, IType> entry : builders) { if (entry != null) { entry.dispose(); } } builders = null; } onChanged(); incrementModCounts(); } /** * Builds the list of messages from the builder and returns them. * * @return an immutable list of messages */ public List<MType> build() { // Now that build has been called, we are required to dispatch // invalidations. isClean = true; if (!isMessagesListMutable && builders == null) { // We still have an immutable list and we never created a builder. return messages; } boolean allMessagesInSync = true; if (!isMessagesListMutable) { // We still have an immutable list. Let's see if any of them are out // of sync with their builders. for (int i = 0; i < messages.size(); i++) { Message message = messages.get(i); SingleFieldBuilder<MType, BType, IType> builder = builders.get(i); if (builder != null) { if (builder.build() != message) { allMessagesInSync = false; break; } } } if (allMessagesInSync) { // Immutable list is still in sync. return messages; } } // Need to make sure messages is up to date ensureMutableMessageList(); for (int i = 0; i < messages.size(); i++) { messages.set(i, getMessage(i, true)); } // We're going to return our list as immutable so we mark that we can // no longer update it. messages = Collections.unmodifiableList(messages); isMessagesListMutable = false; return messages; } /** * Gets a view of the builder as a list of messages. The returned list is live and will reflect * any changes to the underlying builder. * * @return the messages in the list */ public List<MType> getMessageList() { if (externalMessageList == null) { externalMessageList = new MessageExternalList<MType, BType, IType>(this); } return externalMessageList; } /** * Gets a view of the builder as a list of builders. This returned list is live and will reflect * any changes to the underlying builder. * * @return the builders in the list */ public List<BType> getBuilderList() { if (externalBuilderList == null) { externalBuilderList = new BuilderExternalList<MType, BType, IType>(this); } return externalBuilderList; } /** * Gets a view of the builder as a list of MessageOrBuilders. This returned list is live and will * reflect any changes to the underlying builder. * * @return the builders in the list */ public List<IType> getMessageOrBuilderList() { if (externalMessageOrBuilderList == null) { externalMessageOrBuilderList = new MessageOrBuilderExternalList<MType, BType, IType>(this); } return externalMessageOrBuilderList; } /** * Called when a the builder or one of its nested children has changed and any parent should be * notified of its invalidation. */ private void onChanged() { if (isClean && parent != null) { parent.markDirty(); // Don't keep dispatching invalidations until build is called again. isClean = false; } } @Override public void markDirty() { onChanged(); } /** * Increments the mod counts so that an ConcurrentModificationException can be thrown if calling * code tries to modify the builder while its iterating the list. */ private void incrementModCounts() { if (externalMessageList != null) { externalMessageList.incrementModCount(); } if (externalBuilderList != null) { externalBuilderList.incrementModCount(); } if (externalMessageOrBuilderList != null) { externalMessageOrBuilderList.incrementModCount(); } } /** * Provides a live view of the builder as a list of messages. * * @param <MType> the type of message for the field * @param <BType> the type of builder for the field * @param <IType> the common interface for the message and the builder */ private static class MessageExternalList< MType extends GeneratedMessage, BType extends GeneratedMessage.Builder, IType extends MessageOrBuilder> extends AbstractList<MType> implements List<MType>, RandomAccess { RepeatedFieldBuilder<MType, BType, IType> builder; MessageExternalList(RepeatedFieldBuilder<MType, BType, IType> builder) { this.builder = builder; } @Override public int size() { return this.builder.getCount(); } @Override public MType get(int index) { return builder.getMessage(index); } void incrementModCount() { modCount++; } } /** * Provides a live view of the builder as a list of builders. * * @param <MType> the type of message for the field * @param <BType> the type of builder for the field * @param <IType> the common interface for the message and the builder */ private static class BuilderExternalList< MType extends GeneratedMessage, BType extends GeneratedMessage.Builder, IType extends MessageOrBuilder> extends AbstractList<BType> implements List<BType>, RandomAccess { RepeatedFieldBuilder<MType, BType, IType> builder; BuilderExternalList(RepeatedFieldBuilder<MType, BType, IType> builder) { this.builder = builder; } @Override public int size() { return this.builder.getCount(); } @Override public BType get(int index) { return builder.getBuilder(index); } void incrementModCount() { modCount++; } } /** * Provides a live view of the builder as a list of builders. * * @param <MType> the type of message for the field * @param <BType> the type of builder for the field * @param <IType> the common interface for the message and the builder */ private static class MessageOrBuilderExternalList< MType extends GeneratedMessage, BType extends GeneratedMessage.Builder, IType extends MessageOrBuilder> extends AbstractList<IType> implements List<IType>, RandomAccess { RepeatedFieldBuilder<MType, BType, IType> builder; MessageOrBuilderExternalList(RepeatedFieldBuilder<MType, BType, IType> builder) { this.builder = builder; } @Override public int size() { return this.builder.getCount(); } @Override public IType get(int index) { return builder.getMessageOrBuilder(index); } void incrementModCount() { modCount++; } } }
protocolbuffers/protobuf
java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilder.java
44,898
package com.baeldung.entity; public class DeliveryAddress { private String forename; private String surname; private String street; private String postalcode; private String county; public String getForename() { return forename; } public DeliveryAddress setForename(String forename) { this.forename = forename; return this; } public String getSurname() { return surname; } public DeliveryAddress setSurname(String surname) { this.surname = surname; return this; } public String getStreet() { return street; } public DeliveryAddress setStreet(String street) { this.street = street; return this; } public String getPostalcode() { return postalcode; } public DeliveryAddress setPostalcode(String postalcode) { this.postalcode = postalcode; return this; } public String getCounty() { return county; } public DeliveryAddress setCounty(String county) { this.county = county; return this; } }
eugenp/tutorials
mapstruct/src/main/java/com/baeldung/entity/DeliveryAddress.java
44,899
package com.macro.mall.service; import com.macro.mall.dto.*; import com.macro.mall.model.OmsOrder; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * 订单管理Service * Created by macro on 2018/10/11. */ public interface OmsOrderService { /** * 分页查询订单 */ List<OmsOrder> list(OmsOrderQueryParam queryParam, Integer pageSize, Integer pageNum); /** * 批量发货 */ @Transactional int delivery(List<OmsOrderDeliveryParam> deliveryParamList); /** * 批量关闭订单 */ @Transactional int close(List<Long> ids, String note); /** * 批量删除订单 */ int delete(List<Long> ids); /** * 获取指定订单详情 */ OmsOrderDetail detail(Long id); /** * 修改订单收货人信息 */ @Transactional int updateReceiverInfo(OmsReceiverInfoParam receiverInfoParam); /** * 修改订单费用信息 */ @Transactional int updateMoneyInfo(OmsMoneyInfoParam moneyInfoParam); /** * 修改订单备注 */ @Transactional int updateNote(Long id, String note, Integer status); }
macrozheng/mall
mall-admin/src/main/java/com/macro/mall/service/OmsOrderService.java
44,900
/* * Copyright 2012-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot; import java.lang.StackWalker.StackFrame; import java.lang.management.ManagementFactory; import java.lang.reflect.Method; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Properties; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Stream; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.crac.management.CRaCMXBean; import org.springframework.aot.AotDetector; import org.springframework.beans.BeansException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.groovy.GroovyBeanDefinitionReader; import org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.BeanNameGenerator; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.boot.Banner.Mode; import org.springframework.boot.context.properties.bind.Bindable; import org.springframework.boot.context.properties.bind.BindableRuntimeHintsRegistrar; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.boot.context.properties.source.ConfigurationPropertySources; import org.springframework.boot.convert.ApplicationConversionService; import org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext; import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ApplicationListener; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotatedBeanDefinitionReader; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.AnnotationConfigUtils; import org.springframework.context.annotation.ClassPathBeanDefinitionScanner; import org.springframework.context.annotation.ConfigurationClassPostProcessor; import org.springframework.context.aot.AotApplicationContextInitializer; import org.springframework.context.event.ApplicationContextEvent; import org.springframework.context.event.ContextClosedEvent; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.GenericTypeResolver; import org.springframework.core.NativeDetector; import org.springframework.core.OrderComparator; import org.springframework.core.OrderComparator.OrderSourceProvider; import org.springframework.core.Ordered; import org.springframework.core.annotation.AnnotationAwareOrderComparator; import org.springframework.core.annotation.Order; import org.springframework.core.env.CommandLinePropertySource; import org.springframework.core.env.CompositePropertySource; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertySource; import org.springframework.core.env.SimpleCommandLinePropertySource; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.SpringFactoriesLoader; import org.springframework.core.io.support.SpringFactoriesLoader.ArgumentResolver; import org.springframework.core.metrics.ApplicationStartup; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.CollectionUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; import org.springframework.util.function.ThrowingConsumer; import org.springframework.util.function.ThrowingSupplier; /** * Class that can be used to bootstrap and launch a Spring application from a Java main * method. By default class will perform the following steps to bootstrap your * application: * * <ul> * <li>Create an appropriate {@link ApplicationContext} instance (depending on your * classpath)</li> * <li>Register a {@link CommandLinePropertySource} to expose command line arguments as * Spring properties</li> * <li>Refresh the application context, loading all singleton beans</li> * <li>Trigger any {@link CommandLineRunner} beans</li> * </ul> * * In most circumstances the static {@link #run(Class, String[])} method can be called * directly from your {@literal main} method to bootstrap your application: * * <pre class="code"> * &#064;Configuration * &#064;EnableAutoConfiguration * public class MyApplication { * * // ... Bean definitions * * public static void main(String[] args) { * SpringApplication.run(MyApplication.class, args); * } * } * </pre> * * <p> * For more advanced configuration a {@link SpringApplication} instance can be created and * customized before being run: * * <pre class="code"> * public static void main(String[] args) { * SpringApplication application = new SpringApplication(MyApplication.class); * // ... customize application settings here * application.run(args) * } * </pre> * * {@link SpringApplication}s can read beans from a variety of different sources. It is * generally recommended that a single {@code @Configuration} class is used to bootstrap * your application, however, you may also set {@link #getSources() sources} from: * <ul> * <li>The fully qualified class name to be loaded by * {@link AnnotatedBeanDefinitionReader}</li> * <li>The location of an XML resource to be loaded by {@link XmlBeanDefinitionReader}, or * a groovy script to be loaded by {@link GroovyBeanDefinitionReader}</li> * <li>The name of a package to be scanned by {@link ClassPathBeanDefinitionScanner}</li> * </ul> * * Configuration properties are also bound to the {@link SpringApplication}. This makes it * possible to set {@link SpringApplication} properties dynamically, like additional * sources ("spring.main.sources" - a CSV list) the flag to indicate a web environment * ("spring.main.web-application-type=none") or the flag to switch off the banner * ("spring.main.banner-mode=off"). * * @author Phillip Webb * @author Dave Syer * @author Andy Wilkinson * @author Christian Dupuis * @author Stephane Nicoll * @author Jeremy Rickard * @author Craig Burke * @author Michael Simons * @author Madhura Bhave * @author Brian Clozel * @author Ethan Rubinson * @author Chris Bono * @author Moritz Halbritter * @author Tadaya Tsuyukubo * @author Lasse Wulff * @author Yanming Zhou * @since 1.0.0 * @see #run(Class, String[]) * @see #run(Class[], String[]) * @see #SpringApplication(Class...) */ public class SpringApplication { /** * Default banner location. */ public static final String BANNER_LOCATION_PROPERTY_VALUE = SpringApplicationBannerPrinter.DEFAULT_BANNER_LOCATION; /** * Banner location property key. */ public static final String BANNER_LOCATION_PROPERTY = SpringApplicationBannerPrinter.BANNER_LOCATION_PROPERTY; private static final String SYSTEM_PROPERTY_JAVA_AWT_HEADLESS = "java.awt.headless"; private static final Log logger = LogFactory.getLog(SpringApplication.class); static final SpringApplicationShutdownHook shutdownHook = new SpringApplicationShutdownHook(); private static final ThreadLocal<SpringApplicationHook> applicationHook = new ThreadLocal<>(); private final Set<Class<?>> primarySources; private Set<String> sources = new LinkedHashSet<>(); private Class<?> mainApplicationClass; private Banner.Mode bannerMode = Banner.Mode.CONSOLE; private boolean logStartupInfo = true; private boolean addCommandLineProperties = true; private boolean addConversionService = true; private Banner banner; private ResourceLoader resourceLoader; private BeanNameGenerator beanNameGenerator; private ConfigurableEnvironment environment; private WebApplicationType webApplicationType; private boolean headless = true; private boolean registerShutdownHook = true; private List<ApplicationContextInitializer<?>> initializers; private List<ApplicationListener<?>> listeners; private Map<String, Object> defaultProperties; private final List<BootstrapRegistryInitializer> bootstrapRegistryInitializers; private Set<String> additionalProfiles = Collections.emptySet(); private boolean allowBeanDefinitionOverriding; private boolean allowCircularReferences; private boolean isCustomEnvironment = false; private boolean lazyInitialization = false; private String environmentPrefix; private ApplicationContextFactory applicationContextFactory = ApplicationContextFactory.DEFAULT; private ApplicationStartup applicationStartup = ApplicationStartup.DEFAULT; private boolean keepAlive; /** * Create a new {@link SpringApplication} instance. The application context will load * beans from the specified primary sources (see {@link SpringApplication class-level} * documentation for details). The instance can be customized before calling * {@link #run(String...)}. * @param primarySources the primary bean sources * @see #run(Class, String[]) * @see #SpringApplication(ResourceLoader, Class...) * @see #setSources(Set) */ public SpringApplication(Class<?>... primarySources) { this(null, primarySources); } /** * Create a new {@link SpringApplication} instance. The application context will load * beans from the specified primary sources (see {@link SpringApplication class-level} * documentation for details). The instance can be customized before calling * {@link #run(String...)}. * @param resourceLoader the resource loader to use * @param primarySources the primary bean sources * @see #run(Class, String[]) * @see #setSources(Set) */ @SuppressWarnings({ "unchecked", "rawtypes" }) public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) { this.resourceLoader = resourceLoader; Assert.notNull(primarySources, "PrimarySources must not be null"); this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources)); this.webApplicationType = WebApplicationType.deduceFromClasspath(); this.bootstrapRegistryInitializers = new ArrayList<>( getSpringFactoriesInstances(BootstrapRegistryInitializer.class)); setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class)); setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class)); this.mainApplicationClass = deduceMainApplicationClass(); } private Class<?> deduceMainApplicationClass() { return StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE) .walk(this::findMainClass) .orElse(null); } private Optional<Class<?>> findMainClass(Stream<StackFrame> stack) { return stack.filter((frame) -> Objects.equals(frame.getMethodName(), "main")) .findFirst() .map(StackWalker.StackFrame::getDeclaringClass); } /** * Run the Spring application, creating and refreshing a new * {@link ApplicationContext}. * @param args the application arguments (usually passed from a Java main method) * @return a running {@link ApplicationContext} */ public ConfigurableApplicationContext run(String... args) { Startup startup = Startup.create(); if (this.registerShutdownHook) { SpringApplication.shutdownHook.enableShutdownHookAddition(); } DefaultBootstrapContext bootstrapContext = createBootstrapContext(); ConfigurableApplicationContext context = null; configureHeadlessProperty(); SpringApplicationRunListeners listeners = getRunListeners(args); listeners.starting(bootstrapContext, this.mainApplicationClass); try { ApplicationArguments applicationArguments = new DefaultApplicationArguments(args); ConfigurableEnvironment environment = prepareEnvironment(listeners, bootstrapContext, applicationArguments); Banner printedBanner = printBanner(environment); context = createApplicationContext(); context.setApplicationStartup(this.applicationStartup); prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner); refreshContext(context); afterRefresh(context, applicationArguments); startup.started(); if (this.logStartupInfo) { new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), startup); } listeners.started(context, startup.timeTakenToStarted()); callRunners(context, applicationArguments); } catch (Throwable ex) { throw handleRunFailure(context, ex, listeners); } try { if (context.isRunning()) { listeners.ready(context, startup.ready()); } } catch (Throwable ex) { throw handleRunFailure(context, ex, null); } return context; } private DefaultBootstrapContext createBootstrapContext() { DefaultBootstrapContext bootstrapContext = new DefaultBootstrapContext(); this.bootstrapRegistryInitializers.forEach((initializer) -> initializer.initialize(bootstrapContext)); return bootstrapContext; } private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners, DefaultBootstrapContext bootstrapContext, ApplicationArguments applicationArguments) { // Create and configure the environment ConfigurableEnvironment environment = getOrCreateEnvironment(); configureEnvironment(environment, applicationArguments.getSourceArgs()); ConfigurationPropertySources.attach(environment); listeners.environmentPrepared(bootstrapContext, environment); DefaultPropertiesPropertySource.moveToEnd(environment); Assert.state(!environment.containsProperty("spring.main.environment-prefix"), "Environment prefix cannot be set via properties."); bindToSpringApplication(environment); if (!this.isCustomEnvironment) { EnvironmentConverter environmentConverter = new EnvironmentConverter(getClassLoader()); environment = environmentConverter.convertEnvironmentIfNecessary(environment, deduceEnvironmentClass()); } ConfigurationPropertySources.attach(environment); return environment; } private Class<? extends ConfigurableEnvironment> deduceEnvironmentClass() { Class<? extends ConfigurableEnvironment> environmentType = this.applicationContextFactory .getEnvironmentType(this.webApplicationType); if (environmentType == null && this.applicationContextFactory != ApplicationContextFactory.DEFAULT) { environmentType = ApplicationContextFactory.DEFAULT.getEnvironmentType(this.webApplicationType); } if (environmentType == null) { return ApplicationEnvironment.class; } return environmentType; } private void prepareContext(DefaultBootstrapContext bootstrapContext, ConfigurableApplicationContext context, ConfigurableEnvironment environment, SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) { context.setEnvironment(environment); postProcessApplicationContext(context); addAotGeneratedInitializerIfNecessary(this.initializers); applyInitializers(context); listeners.contextPrepared(context); bootstrapContext.close(context); if (this.logStartupInfo) { logStartupInfo(context.getParent() == null); logStartupProfileInfo(context); } // Add boot specific singleton beans ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); beanFactory.registerSingleton("springApplicationArguments", applicationArguments); if (printedBanner != null) { beanFactory.registerSingleton("springBootBanner", printedBanner); } if (beanFactory instanceof AbstractAutowireCapableBeanFactory autowireCapableBeanFactory) { autowireCapableBeanFactory.setAllowCircularReferences(this.allowCircularReferences); if (beanFactory instanceof DefaultListableBeanFactory listableBeanFactory) { listableBeanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding); } } if (this.lazyInitialization) { context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor()); } if (this.keepAlive) { context.addApplicationListener(new KeepAlive()); } context.addBeanFactoryPostProcessor(new PropertySourceOrderingBeanFactoryPostProcessor(context)); if (!AotDetector.useGeneratedArtifacts()) { // Load the sources Set<Object> sources = getAllSources(); Assert.notEmpty(sources, "Sources must not be empty"); load(context, sources.toArray(new Object[0])); } listeners.contextLoaded(context); } private void addAotGeneratedInitializerIfNecessary(List<ApplicationContextInitializer<?>> initializers) { if (AotDetector.useGeneratedArtifacts()) { List<ApplicationContextInitializer<?>> aotInitializers = new ArrayList<>( initializers.stream().filter(AotApplicationContextInitializer.class::isInstance).toList()); if (aotInitializers.isEmpty()) { String initializerClassName = this.mainApplicationClass.getName() + "__ApplicationContextInitializer"; if (!ClassUtils.isPresent(initializerClassName, getClassLoader())) { throw new AotInitializerNotFoundException(this.mainApplicationClass, initializerClassName); } aotInitializers.add(AotApplicationContextInitializer.forInitializerClasses(initializerClassName)); } initializers.removeAll(aotInitializers); initializers.addAll(0, aotInitializers); } } private void refreshContext(ConfigurableApplicationContext context) { if (this.registerShutdownHook) { shutdownHook.registerApplicationContext(context); } refresh(context); } private void configureHeadlessProperty() { System.setProperty(SYSTEM_PROPERTY_JAVA_AWT_HEADLESS, System.getProperty(SYSTEM_PROPERTY_JAVA_AWT_HEADLESS, Boolean.toString(this.headless))); } private SpringApplicationRunListeners getRunListeners(String[] args) { ArgumentResolver argumentResolver = ArgumentResolver.of(SpringApplication.class, this); argumentResolver = argumentResolver.and(String[].class, args); List<SpringApplicationRunListener> listeners = getSpringFactoriesInstances(SpringApplicationRunListener.class, argumentResolver); SpringApplicationHook hook = applicationHook.get(); SpringApplicationRunListener hookListener = (hook != null) ? hook.getRunListener(this) : null; if (hookListener != null) { listeners = new ArrayList<>(listeners); listeners.add(hookListener); } return new SpringApplicationRunListeners(logger, listeners, this.applicationStartup); } private <T> List<T> getSpringFactoriesInstances(Class<T> type) { return getSpringFactoriesInstances(type, null); } private <T> List<T> getSpringFactoriesInstances(Class<T> type, ArgumentResolver argumentResolver) { return SpringFactoriesLoader.forDefaultResourceLocation(getClassLoader()).load(type, argumentResolver); } private ConfigurableEnvironment getOrCreateEnvironment() { if (this.environment != null) { return this.environment; } ConfigurableEnvironment environment = this.applicationContextFactory.createEnvironment(this.webApplicationType); if (environment == null && this.applicationContextFactory != ApplicationContextFactory.DEFAULT) { environment = ApplicationContextFactory.DEFAULT.createEnvironment(this.webApplicationType); } return (environment != null) ? environment : new ApplicationEnvironment(); } /** * Template method delegating to * {@link #configurePropertySources(ConfigurableEnvironment, String[])} and * {@link #configureProfiles(ConfigurableEnvironment, String[])} in that order. * Override this method for complete control over Environment customization, or one of * the above for fine-grained control over property sources or profiles, respectively. * @param environment this application's environment * @param args arguments passed to the {@code run} method * @see #configureProfiles(ConfigurableEnvironment, String[]) * @see #configurePropertySources(ConfigurableEnvironment, String[]) */ protected void configureEnvironment(ConfigurableEnvironment environment, String[] args) { if (this.addConversionService) { environment.setConversionService(new ApplicationConversionService()); } configurePropertySources(environment, args); configureProfiles(environment, args); } /** * Add, remove or re-order any {@link PropertySource}s in this application's * environment. * @param environment this application's environment * @param args arguments passed to the {@code run} method * @see #configureEnvironment(ConfigurableEnvironment, String[]) */ protected void configurePropertySources(ConfigurableEnvironment environment, String[] args) { MutablePropertySources sources = environment.getPropertySources(); if (!CollectionUtils.isEmpty(this.defaultProperties)) { DefaultPropertiesPropertySource.addOrMerge(this.defaultProperties, sources); } if (this.addCommandLineProperties && args.length > 0) { String name = CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME; if (sources.contains(name)) { PropertySource<?> source = sources.get(name); CompositePropertySource composite = new CompositePropertySource(name); composite .addPropertySource(new SimpleCommandLinePropertySource("springApplicationCommandLineArgs", args)); composite.addPropertySource(source); sources.replace(name, composite); } else { sources.addFirst(new SimpleCommandLinePropertySource(args)); } } } /** * Configure which profiles are active (or active by default) for this application * environment. Additional profiles may be activated during configuration file * processing through the {@code spring.profiles.active} property. * @param environment this application's environment * @param args arguments passed to the {@code run} method * @see #configureEnvironment(ConfigurableEnvironment, String[]) */ protected void configureProfiles(ConfigurableEnvironment environment, String[] args) { } /** * Bind the environment to the {@link SpringApplication}. * @param environment the environment to bind */ protected void bindToSpringApplication(ConfigurableEnvironment environment) { try { Binder.get(environment).bind("spring.main", Bindable.ofInstance(this)); } catch (Exception ex) { throw new IllegalStateException("Cannot bind to SpringApplication", ex); } } private Banner printBanner(ConfigurableEnvironment environment) { if (this.bannerMode == Banner.Mode.OFF) { return null; } ResourceLoader resourceLoader = (this.resourceLoader != null) ? this.resourceLoader : new DefaultResourceLoader(null); SpringApplicationBannerPrinter bannerPrinter = new SpringApplicationBannerPrinter(resourceLoader, this.banner); if (this.bannerMode == Mode.LOG) { return bannerPrinter.print(environment, this.mainApplicationClass, logger); } return bannerPrinter.print(environment, this.mainApplicationClass, System.out); } /** * Strategy method used to create the {@link ApplicationContext}. By default this * method will respect any explicitly set application context class or factory before * falling back to a suitable default. * @return the application context (not yet refreshed) * @see #setApplicationContextFactory(ApplicationContextFactory) */ protected ConfigurableApplicationContext createApplicationContext() { return this.applicationContextFactory.create(this.webApplicationType); } /** * Apply any relevant post-processing to the {@link ApplicationContext}. Subclasses * can apply additional processing as required. * @param context the application context */ protected void postProcessApplicationContext(ConfigurableApplicationContext context) { if (this.beanNameGenerator != null) { context.getBeanFactory() .registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, this.beanNameGenerator); } if (this.resourceLoader != null) { if (context instanceof GenericApplicationContext genericApplicationContext) { genericApplicationContext.setResourceLoader(this.resourceLoader); } if (context instanceof DefaultResourceLoader defaultResourceLoader) { defaultResourceLoader.setClassLoader(this.resourceLoader.getClassLoader()); } } if (this.addConversionService) { context.getBeanFactory().setConversionService(context.getEnvironment().getConversionService()); } } /** * Apply any {@link ApplicationContextInitializer}s to the context before it is * refreshed. * @param context the configured ApplicationContext (not refreshed yet) * @see ConfigurableApplicationContext#refresh() */ @SuppressWarnings({ "rawtypes", "unchecked" }) protected void applyInitializers(ConfigurableApplicationContext context) { for (ApplicationContextInitializer initializer : getInitializers()) { Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(initializer.getClass(), ApplicationContextInitializer.class); Assert.isInstanceOf(requiredType, context, "Unable to call initializer."); initializer.initialize(context); } } /** * Called to log startup information, subclasses may override to add additional * logging. * @param isRoot true if this application is the root of a context hierarchy */ protected void logStartupInfo(boolean isRoot) { if (isRoot) { new StartupInfoLogger(this.mainApplicationClass).logStarting(getApplicationLog()); } } /** * Called to log active profile information. * @param context the application context */ protected void logStartupProfileInfo(ConfigurableApplicationContext context) { Log log = getApplicationLog(); if (log.isInfoEnabled()) { List<String> activeProfiles = quoteProfiles(context.getEnvironment().getActiveProfiles()); if (ObjectUtils.isEmpty(activeProfiles)) { List<String> defaultProfiles = quoteProfiles(context.getEnvironment().getDefaultProfiles()); String message = String.format("%s default %s: ", defaultProfiles.size(), (defaultProfiles.size() <= 1) ? "profile" : "profiles"); log.info("No active profile set, falling back to " + message + StringUtils.collectionToDelimitedString(defaultProfiles, ", ")); } else { String message = (activeProfiles.size() == 1) ? "1 profile is active: " : activeProfiles.size() + " profiles are active: "; log.info("The following " + message + StringUtils.collectionToDelimitedString(activeProfiles, ", ")); } } } private List<String> quoteProfiles(String[] profiles) { return Arrays.stream(profiles).map((profile) -> "\"" + profile + "\"").toList(); } /** * Returns the {@link Log} for the application. By default will be deduced. * @return the application log */ protected Log getApplicationLog() { if (this.mainApplicationClass == null) { return logger; } return LogFactory.getLog(this.mainApplicationClass); } /** * Load beans into the application context. * @param context the context to load beans into * @param sources the sources to load */ protected void load(ApplicationContext context, Object[] sources) { if (logger.isDebugEnabled()) { logger.debug("Loading source " + StringUtils.arrayToCommaDelimitedString(sources)); } BeanDefinitionLoader loader = createBeanDefinitionLoader(getBeanDefinitionRegistry(context), sources); if (this.beanNameGenerator != null) { loader.setBeanNameGenerator(this.beanNameGenerator); } if (this.resourceLoader != null) { loader.setResourceLoader(this.resourceLoader); } if (this.environment != null) { loader.setEnvironment(this.environment); } loader.load(); } /** * The ResourceLoader that will be used in the ApplicationContext. * @return the resourceLoader the resource loader that will be used in the * ApplicationContext (or null if the default) */ public ResourceLoader getResourceLoader() { return this.resourceLoader; } /** * Either the ClassLoader that will be used in the ApplicationContext (if * {@link #setResourceLoader(ResourceLoader) resourceLoader} is set), or the context * class loader (if not null), or the loader of the Spring {@link ClassUtils} class. * @return a ClassLoader (never null) */ public ClassLoader getClassLoader() { if (this.resourceLoader != null) { return this.resourceLoader.getClassLoader(); } return ClassUtils.getDefaultClassLoader(); } /** * Get the bean definition registry. * @param context the application context * @return the BeanDefinitionRegistry if it can be determined */ private BeanDefinitionRegistry getBeanDefinitionRegistry(ApplicationContext context) { if (context instanceof BeanDefinitionRegistry registry) { return registry; } if (context instanceof AbstractApplicationContext abstractApplicationContext) { return (BeanDefinitionRegistry) abstractApplicationContext.getBeanFactory(); } throw new IllegalStateException("Could not locate BeanDefinitionRegistry"); } /** * Factory method used to create the {@link BeanDefinitionLoader}. * @param registry the bean definition registry * @param sources the sources to load * @return the {@link BeanDefinitionLoader} that will be used to load beans */ protected BeanDefinitionLoader createBeanDefinitionLoader(BeanDefinitionRegistry registry, Object[] sources) { return new BeanDefinitionLoader(registry, sources); } /** * Refresh the underlying {@link ApplicationContext}. * @param applicationContext the application context to refresh */ protected void refresh(ConfigurableApplicationContext applicationContext) { applicationContext.refresh(); } /** * Called after the context has been refreshed. * @param context the application context * @param args the application arguments */ protected void afterRefresh(ConfigurableApplicationContext context, ApplicationArguments args) { } private void callRunners(ConfigurableApplicationContext context, ApplicationArguments args) { ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); String[] beanNames = beanFactory.getBeanNamesForType(Runner.class); Map<Runner, String> instancesToBeanNames = new IdentityHashMap<>(); for (String beanName : beanNames) { instancesToBeanNames.put(beanFactory.getBean(beanName, Runner.class), beanName); } Comparator<Object> comparator = getOrderComparator(beanFactory) .withSourceProvider(new FactoryAwareOrderSourceProvider(beanFactory, instancesToBeanNames)); instancesToBeanNames.keySet().stream().sorted(comparator).forEach((runner) -> callRunner(runner, args)); } private OrderComparator getOrderComparator(ConfigurableListableBeanFactory beanFactory) { Comparator<?> dependencyComparator = (beanFactory instanceof DefaultListableBeanFactory defaultListableBeanFactory) ? defaultListableBeanFactory.getDependencyComparator() : null; return (dependencyComparator instanceof OrderComparator orderComparator) ? orderComparator : AnnotationAwareOrderComparator.INSTANCE; } private void callRunner(Runner runner, ApplicationArguments args) { if (runner instanceof ApplicationRunner) { callRunner(ApplicationRunner.class, runner, (applicationRunner) -> applicationRunner.run(args)); } if (runner instanceof CommandLineRunner) { callRunner(CommandLineRunner.class, runner, (commandLineRunner) -> commandLineRunner.run(args.getSourceArgs())); } } @SuppressWarnings("unchecked") private <R extends Runner> void callRunner(Class<R> type, Runner runner, ThrowingConsumer<R> call) { call.throwing( (message, ex) -> new IllegalStateException("Failed to execute " + ClassUtils.getShortName(type), ex)) .accept((R) runner); } private RuntimeException handleRunFailure(ConfigurableApplicationContext context, Throwable exception, SpringApplicationRunListeners listeners) { if (exception instanceof AbandonedRunException abandonedRunException) { return abandonedRunException; } try { try { handleExitCode(context, exception); if (listeners != null) { listeners.failed(context, exception); } } finally { reportFailure(getExceptionReporters(context), exception); if (context != null) { context.close(); shutdownHook.deregisterFailedApplicationContext(context); } } } catch (Exception ex) { logger.warn("Unable to close ApplicationContext", ex); } return (exception instanceof RuntimeException runtimeException) ? runtimeException : new IllegalStateException(exception); } private Collection<SpringBootExceptionReporter> getExceptionReporters(ConfigurableApplicationContext context) { try { ArgumentResolver argumentResolver = ArgumentResolver.of(ConfigurableApplicationContext.class, context); return getSpringFactoriesInstances(SpringBootExceptionReporter.class, argumentResolver); } catch (Throwable ex) { return Collections.emptyList(); } } private void reportFailure(Collection<SpringBootExceptionReporter> exceptionReporters, Throwable failure) { try { for (SpringBootExceptionReporter reporter : exceptionReporters) { if (reporter.reportException(failure)) { registerLoggedException(failure); return; } } } catch (Throwable ex) { // Continue with normal handling of the original failure } if (logger.isErrorEnabled()) { if (NativeDetector.inNativeImage()) { // Depending on how early the failure was, logging may not work in a // native image so we output the stack trace directly to System.out // instead. System.out.println("Application run failed"); failure.printStackTrace(System.out); } else { logger.error("Application run failed", failure); } registerLoggedException(failure); } } /** * Register that the given exception has been logged. By default, if the running in * the main thread, this method will suppress additional printing of the stacktrace. * @param exception the exception that was logged */ protected void registerLoggedException(Throwable exception) { SpringBootExceptionHandler handler = getSpringBootExceptionHandler(); if (handler != null) { handler.registerLoggedException(exception); } } private void handleExitCode(ConfigurableApplicationContext context, Throwable exception) { int exitCode = getExitCodeFromException(context, exception); if (exitCode != 0) { if (context != null) { context.publishEvent(new ExitCodeEvent(context, exitCode)); } SpringBootExceptionHandler handler = getSpringBootExceptionHandler(); if (handler != null) { handler.registerExitCode(exitCode); } } } private int getExitCodeFromException(ConfigurableApplicationContext context, Throwable exception) { int exitCode = getExitCodeFromMappedException(context, exception); if (exitCode == 0) { exitCode = getExitCodeFromExitCodeGeneratorException(exception); } return exitCode; } private int getExitCodeFromMappedException(ConfigurableApplicationContext context, Throwable exception) { if (context == null || !context.isActive()) { return 0; } ExitCodeGenerators generators = new ExitCodeGenerators(); Collection<ExitCodeExceptionMapper> beans = context.getBeansOfType(ExitCodeExceptionMapper.class).values(); generators.addAll(exception, beans); return generators.getExitCode(); } private int getExitCodeFromExitCodeGeneratorException(Throwable exception) { if (exception == null) { return 0; } if (exception instanceof ExitCodeGenerator generator) { return generator.getExitCode(); } return getExitCodeFromExitCodeGeneratorException(exception.getCause()); } SpringBootExceptionHandler getSpringBootExceptionHandler() { if (isMainThread(Thread.currentThread())) { return SpringBootExceptionHandler.forCurrentThread(); } return null; } private boolean isMainThread(Thread currentThread) { return ("main".equals(currentThread.getName()) || "restartedMain".equals(currentThread.getName())) && "main".equals(currentThread.getThreadGroup().getName()); } /** * Returns the main application class that has been deduced or explicitly configured. * @return the main application class or {@code null} */ public Class<?> getMainApplicationClass() { return this.mainApplicationClass; } /** * Set a specific main application class that will be used as a log source and to * obtain version information. By default the main application class will be deduced. * Can be set to {@code null} if there is no explicit application class. * @param mainApplicationClass the mainApplicationClass to set or {@code null} */ public void setMainApplicationClass(Class<?> mainApplicationClass) { this.mainApplicationClass = mainApplicationClass; } /** * Returns the type of web application that is being run. * @return the type of web application * @since 2.0.0 */ public WebApplicationType getWebApplicationType() { return this.webApplicationType; } /** * Sets the type of web application to be run. If not explicitly set the type of web * application will be deduced based on the classpath. * @param webApplicationType the web application type * @since 2.0.0 */ public void setWebApplicationType(WebApplicationType webApplicationType) { Assert.notNull(webApplicationType, "WebApplicationType must not be null"); this.webApplicationType = webApplicationType; } /** * Sets if bean definition overriding, by registering a definition with the same name * as an existing definition, should be allowed. Defaults to {@code false}. * @param allowBeanDefinitionOverriding if overriding is allowed * @since 2.1.0 * @see DefaultListableBeanFactory#setAllowBeanDefinitionOverriding(boolean) */ public void setAllowBeanDefinitionOverriding(boolean allowBeanDefinitionOverriding) { this.allowBeanDefinitionOverriding = allowBeanDefinitionOverriding; } /** * Sets whether to allow circular references between beans and automatically try to * resolve them. Defaults to {@code false}. * @param allowCircularReferences if circular references are allowed * @since 2.6.0 * @see AbstractAutowireCapableBeanFactory#setAllowCircularReferences(boolean) */ public void setAllowCircularReferences(boolean allowCircularReferences) { this.allowCircularReferences = allowCircularReferences; } /** * Sets if beans should be initialized lazily. Defaults to {@code false}. * @param lazyInitialization if initialization should be lazy * @since 2.2 * @see BeanDefinition#setLazyInit(boolean) */ public void setLazyInitialization(boolean lazyInitialization) { this.lazyInitialization = lazyInitialization; } /** * Sets if the application is headless and should not instantiate AWT. Defaults to * {@code true} to prevent java icons appearing. * @param headless if the application is headless */ public void setHeadless(boolean headless) { this.headless = headless; } /** * Sets if the created {@link ApplicationContext} should have a shutdown hook * registered. Defaults to {@code true} to ensure that JVM shutdowns are handled * gracefully. * @param registerShutdownHook if the shutdown hook should be registered * @see #getShutdownHandlers() */ public void setRegisterShutdownHook(boolean registerShutdownHook) { this.registerShutdownHook = registerShutdownHook; } /** * Sets the {@link Banner} instance which will be used to print the banner when no * static banner file is provided. * @param banner the Banner instance to use */ public void setBanner(Banner banner) { this.banner = banner; } /** * Sets the mode used to display the banner when the application runs. Defaults to * {@code Banner.Mode.CONSOLE}. * @param bannerMode the mode used to display the banner */ public void setBannerMode(Banner.Mode bannerMode) { this.bannerMode = bannerMode; } /** * Sets if the application information should be logged when the application starts. * Defaults to {@code true}. * @param logStartupInfo if startup info should be logged. */ public void setLogStartupInfo(boolean logStartupInfo) { this.logStartupInfo = logStartupInfo; } /** * Sets if a {@link CommandLinePropertySource} should be added to the application * context in order to expose arguments. Defaults to {@code true}. * @param addCommandLineProperties if command line arguments should be exposed */ public void setAddCommandLineProperties(boolean addCommandLineProperties) { this.addCommandLineProperties = addCommandLineProperties; } /** * Sets if the {@link ApplicationConversionService} should be added to the application * context's {@link Environment}. * @param addConversionService if the application conversion service should be added * @since 2.1.0 */ public void setAddConversionService(boolean addConversionService) { this.addConversionService = addConversionService; } /** * Adds {@link BootstrapRegistryInitializer} instances that can be used to initialize * the {@link BootstrapRegistry}. * @param bootstrapRegistryInitializer the bootstrap registry initializer to add * @since 2.4.5 */ public void addBootstrapRegistryInitializer(BootstrapRegistryInitializer bootstrapRegistryInitializer) { Assert.notNull(bootstrapRegistryInitializer, "BootstrapRegistryInitializer must not be null"); this.bootstrapRegistryInitializers.addAll(Arrays.asList(bootstrapRegistryInitializer)); } /** * Set default environment properties which will be used in addition to those in the * existing {@link Environment}. * @param defaultProperties the additional properties to set */ public void setDefaultProperties(Map<String, Object> defaultProperties) { this.defaultProperties = defaultProperties; } /** * Convenient alternative to {@link #setDefaultProperties(Map)}. * @param defaultProperties some {@link Properties} */ public void setDefaultProperties(Properties defaultProperties) { this.defaultProperties = new HashMap<>(); for (Object key : Collections.list(defaultProperties.propertyNames())) { this.defaultProperties.put((String) key, defaultProperties.get(key)); } } /** * Set additional profile values to use (on top of those set in system or command line * properties). * @param profiles the additional profiles to set */ public void setAdditionalProfiles(String... profiles) { this.additionalProfiles = Collections.unmodifiableSet(new LinkedHashSet<>(Arrays.asList(profiles))); } /** * Return an immutable set of any additional profiles in use. * @return the additional profiles */ public Set<String> getAdditionalProfiles() { return this.additionalProfiles; } /** * Sets the bean name generator that should be used when generating bean names. * @param beanNameGenerator the bean name generator */ public void setBeanNameGenerator(BeanNameGenerator beanNameGenerator) { this.beanNameGenerator = beanNameGenerator; } /** * Sets the underlying environment that should be used with the created application * context. * @param environment the environment */ public void setEnvironment(ConfigurableEnvironment environment) { this.isCustomEnvironment = true; this.environment = environment; } /** * Add additional items to the primary sources that will be added to an * ApplicationContext when {@link #run(String...)} is called. * <p> * The sources here are added to those that were set in the constructor. Most users * should consider using {@link #getSources()}/{@link #setSources(Set)} rather than * calling this method. * @param additionalPrimarySources the additional primary sources to add * @see #SpringApplication(Class...) * @see #getSources() * @see #setSources(Set) * @see #getAllSources() */ public void addPrimarySources(Collection<Class<?>> additionalPrimarySources) { this.primarySources.addAll(additionalPrimarySources); } /** * Returns a mutable set of the sources that will be added to an ApplicationContext * when {@link #run(String...)} is called. * <p> * Sources set here will be used in addition to any primary sources set in the * constructor. * @return the application sources. * @see #SpringApplication(Class...) * @see #getAllSources() */ public Set<String> getSources() { return this.sources; } /** * Set additional sources that will be used to create an ApplicationContext. A source * can be: a class name, package name, or an XML resource location. * <p> * Sources set here will be used in addition to any primary sources set in the * constructor. * @param sources the application sources to set * @see #SpringApplication(Class...) * @see #getAllSources() */ public void setSources(Set<String> sources) { Assert.notNull(sources, "Sources must not be null"); this.sources = new LinkedHashSet<>(sources); } /** * Return an immutable set of all the sources that will be added to an * ApplicationContext when {@link #run(String...)} is called. This method combines any * primary sources specified in the constructor with any additional ones that have * been {@link #setSources(Set) explicitly set}. * @return an immutable set of all sources */ public Set<Object> getAllSources() { Set<Object> allSources = new LinkedHashSet<>(); if (!CollectionUtils.isEmpty(this.primarySources)) { allSources.addAll(this.primarySources); } if (!CollectionUtils.isEmpty(this.sources)) { allSources.addAll(this.sources); } return Collections.unmodifiableSet(allSources); } /** * Sets the {@link ResourceLoader} that should be used when loading resources. * @param resourceLoader the resource loader */ public void setResourceLoader(ResourceLoader resourceLoader) { Assert.notNull(resourceLoader, "ResourceLoader must not be null"); this.resourceLoader = resourceLoader; } /** * Return a prefix that should be applied when obtaining configuration properties from * the system environment. * @return the environment property prefix * @since 2.5.0 */ public String getEnvironmentPrefix() { return this.environmentPrefix; } /** * Set the prefix that should be applied when obtaining configuration properties from * the system environment. * @param environmentPrefix the environment property prefix to set * @since 2.5.0 */ public void setEnvironmentPrefix(String environmentPrefix) { this.environmentPrefix = environmentPrefix; } /** * Sets the factory that will be called to create the application context. If not set, * defaults to a factory that will create * {@link AnnotationConfigServletWebServerApplicationContext} for servlet web * applications, {@link AnnotationConfigReactiveWebServerApplicationContext} for * reactive web applications, and {@link AnnotationConfigApplicationContext} for * non-web applications. * @param applicationContextFactory the factory for the context * @since 2.4.0 */ public void setApplicationContextFactory(ApplicationContextFactory applicationContextFactory) { this.applicationContextFactory = (applicationContextFactory != null) ? applicationContextFactory : ApplicationContextFactory.DEFAULT; } /** * Sets the {@link ApplicationContextInitializer} that will be applied to the Spring * {@link ApplicationContext}. * @param initializers the initializers to set */ public void setInitializers(Collection<? extends ApplicationContextInitializer<?>> initializers) { this.initializers = new ArrayList<>(initializers); } /** * Add {@link ApplicationContextInitializer}s to be applied to the Spring * {@link ApplicationContext}. * @param initializers the initializers to add */ public void addInitializers(ApplicationContextInitializer<?>... initializers) { this.initializers.addAll(Arrays.asList(initializers)); } /** * Returns read-only ordered Set of the {@link ApplicationContextInitializer}s that * will be applied to the Spring {@link ApplicationContext}. * @return the initializers */ public Set<ApplicationContextInitializer<?>> getInitializers() { return asUnmodifiableOrderedSet(this.initializers); } /** * Sets the {@link ApplicationListener}s that will be applied to the SpringApplication * and registered with the {@link ApplicationContext}. * @param listeners the listeners to set */ public void setListeners(Collection<? extends ApplicationListener<?>> listeners) { this.listeners = new ArrayList<>(listeners); } /** * Add {@link ApplicationListener}s to be applied to the SpringApplication and * registered with the {@link ApplicationContext}. * @param listeners the listeners to add */ public void addListeners(ApplicationListener<?>... listeners) { this.listeners.addAll(Arrays.asList(listeners)); } /** * Returns read-only ordered Set of the {@link ApplicationListener}s that will be * applied to the SpringApplication and registered with the {@link ApplicationContext} * . * @return the listeners */ public Set<ApplicationListener<?>> getListeners() { return asUnmodifiableOrderedSet(this.listeners); } /** * Set the {@link ApplicationStartup} to use for collecting startup metrics. * @param applicationStartup the application startup to use * @since 2.4.0 */ public void setApplicationStartup(ApplicationStartup applicationStartup) { this.applicationStartup = (applicationStartup != null) ? applicationStartup : ApplicationStartup.DEFAULT; } /** * Returns the {@link ApplicationStartup} used for collecting startup metrics. * @return the application startup * @since 2.4.0 */ public ApplicationStartup getApplicationStartup() { return this.applicationStartup; } /** * Whether to keep the application alive even if there are no more non-daemon threads. * @return whether to keep the application alive even if there are no more non-daemon * threads * @since 3.2.0 */ public boolean isKeepAlive() { return this.keepAlive; } /** * Set whether to keep the application alive even if there are no more non-daemon * threads. * @param keepAlive whether to keep the application alive even if there are no more * non-daemon threads * @since 3.2.0 */ public void setKeepAlive(boolean keepAlive) { this.keepAlive = keepAlive; } /** * Return a {@link SpringApplicationShutdownHandlers} instance that can be used to add * or remove handlers that perform actions before the JVM is shutdown. * @return a {@link SpringApplicationShutdownHandlers} instance * @since 2.5.1 */ public static SpringApplicationShutdownHandlers getShutdownHandlers() { return shutdownHook.getHandlers(); } /** * Static helper that can be used to run a {@link SpringApplication} from the * specified source using default settings. * @param primarySource the primary source to load * @param args the application arguments (usually passed from a Java main method) * @return the running {@link ApplicationContext} */ public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) { return run(new Class<?>[] { primarySource }, args); } /** * Static helper that can be used to run a {@link SpringApplication} from the * specified sources using default settings and user supplied arguments. * @param primarySources the primary sources to load * @param args the application arguments (usually passed from a Java main method) * @return the running {@link ApplicationContext} */ public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) { return new SpringApplication(primarySources).run(args); } /** * A basic main that can be used to launch an application. This method is useful when * application sources are defined through a {@literal --spring.main.sources} command * line argument. * <p> * Most developers will want to define their own main method and call the * {@link #run(Class, String...) run} method instead. * @param args command line arguments * @throws Exception if the application cannot be started * @see SpringApplication#run(Class[], String[]) * @see SpringApplication#run(Class, String...) */ public static void main(String[] args) throws Exception { SpringApplication.run(new Class<?>[0], args); } /** * Static helper that can be used to exit a {@link SpringApplication} and obtain a * code indicating success (0) or otherwise. Does not throw exceptions but should * print stack traces of any encountered. Applies the specified * {@link ExitCodeGenerator ExitCodeGenerators} in addition to any Spring beans that * implement {@link ExitCodeGenerator}. When multiple generators are available, the * first non-zero exit code is used. Generators are ordered based on their * {@link Ordered} implementation and {@link Order @Order} annotation. * @param context the context to close if possible * @param exitCodeGenerators exit code generators * @return the outcome (0 if successful) */ public static int exit(ApplicationContext context, ExitCodeGenerator... exitCodeGenerators) { Assert.notNull(context, "Context must not be null"); int exitCode = 0; try { try { ExitCodeGenerators generators = new ExitCodeGenerators(); Collection<ExitCodeGenerator> beans = context.getBeansOfType(ExitCodeGenerator.class).values(); generators.addAll(exitCodeGenerators); generators.addAll(beans); exitCode = generators.getExitCode(); if (exitCode != 0) { context.publishEvent(new ExitCodeEvent(context, exitCode)); } } finally { close(context); } } catch (Exception ex) { ex.printStackTrace(); exitCode = (exitCode != 0) ? exitCode : 1; } return exitCode; } /** * Create an application from an existing {@code main} method that can run with * additional {@code @Configuration} or bean classes. This method can be helpful when * writing a test harness that needs to start an application with additional * configuration. * @param main the main method entry point that runs the {@link SpringApplication} * @return a {@link SpringApplication.Augmented} instance that can be used to add * configuration and run the application * @since 3.1.0 * @see #withHook(SpringApplicationHook, Runnable) */ public static SpringApplication.Augmented from(ThrowingConsumer<String[]> main) { Assert.notNull(main, "Main must not be null"); return new Augmented(main, Collections.emptySet()); } /** * Perform the given action with the given {@link SpringApplicationHook} attached if * the action triggers an {@link SpringApplication#run(String...) application run}. * @param hook the hook to apply * @param action the action to run * @since 3.0.0 * @see #withHook(SpringApplicationHook, ThrowingSupplier) */ public static void withHook(SpringApplicationHook hook, Runnable action) { withHook(hook, () -> { action.run(); return null; }); } /** * Perform the given action with the given {@link SpringApplicationHook} attached if * the action triggers an {@link SpringApplication#run(String...) application run}. * @param <T> the result type * @param hook the hook to apply * @param action the action to run * @return the result of the action * @since 3.0.0 * @see #withHook(SpringApplicationHook, Runnable) */ public static <T> T withHook(SpringApplicationHook hook, ThrowingSupplier<T> action) { applicationHook.set(hook); try { return action.get(); } finally { applicationHook.remove(); } } private static void close(ApplicationContext context) { if (context instanceof ConfigurableApplicationContext closable) { closable.close(); } } private static <E> Set<E> asUnmodifiableOrderedSet(Collection<E> elements) { List<E> list = new ArrayList<>(elements); list.sort(AnnotationAwareOrderComparator.INSTANCE); return new LinkedHashSet<>(list); } /** * Used to configure and run an augmented {@link SpringApplication} where additional * configuration should be applied. * * @since 3.1.0 */ public static class Augmented { private final ThrowingConsumer<String[]> main; private final Set<Class<?>> sources; Augmented(ThrowingConsumer<String[]> main, Set<Class<?>> sources) { this.main = main; this.sources = Set.copyOf(sources); } /** * Return a new {@link SpringApplication.Augmented} instance with additional * sources that should be applied when the application runs. * @param sources the sources that should be applied * @return a new {@link SpringApplication.Augmented} instance */ public Augmented with(Class<?>... sources) { LinkedHashSet<Class<?>> merged = new LinkedHashSet<>(this.sources); merged.addAll(Arrays.asList(sources)); return new Augmented(this.main, merged); } /** * Run the application using the given args. * @param args the main method args * @return the running {@link ApplicationContext} */ public SpringApplication.Running run(String... args) { RunListener runListener = new RunListener(); SpringApplicationHook hook = new SingleUseSpringApplicationHook((springApplication) -> { springApplication.addPrimarySources(this.sources); return runListener; }); withHook(hook, () -> this.main.accept(args)); return runListener; } /** * {@link SpringApplicationRunListener} to capture {@link Running} application * details. */ private static final class RunListener implements SpringApplicationRunListener, Running { private final List<ConfigurableApplicationContext> contexts = Collections .synchronizedList(new ArrayList<>()); @Override public void contextLoaded(ConfigurableApplicationContext context) { this.contexts.add(context); } @Override public ConfigurableApplicationContext getApplicationContext() { List<ConfigurableApplicationContext> rootContexts = this.contexts.stream() .filter((context) -> context.getParent() == null) .toList(); Assert.state(!rootContexts.isEmpty(), "No root application context located"); Assert.state(rootContexts.size() == 1, "No unique root application context located"); return rootContexts.get(0); } } } /** * Provides access to details of a {@link SpringApplication} run using * {@link Augmented#run(String...)}. * * @since 3.1.0 */ public interface Running { /** * Return the root {@link ConfigurableApplicationContext} of the running * application. * @return the root application context */ ConfigurableApplicationContext getApplicationContext(); } /** * {@link BeanFactoryPostProcessor} to re-order our property sources below any * {@code @PropertySource} items added by the {@link ConfigurationClassPostProcessor}. */ private static class PropertySourceOrderingBeanFactoryPostProcessor implements BeanFactoryPostProcessor, Ordered { private final ConfigurableApplicationContext context; PropertySourceOrderingBeanFactoryPostProcessor(ConfigurableApplicationContext context) { this.context = context; } @Override public int getOrder() { return Ordered.HIGHEST_PRECEDENCE; } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { DefaultPropertiesPropertySource.moveToEnd(this.context.getEnvironment()); } } static class SpringApplicationRuntimeHints extends BindableRuntimeHintsRegistrar { SpringApplicationRuntimeHints() { super(SpringApplication.class); } } /** * Exception that can be thrown to silently exit a running {@link SpringApplication} * without handling run failures. * * @since 3.0.0 */ public static class AbandonedRunException extends RuntimeException { private final ConfigurableApplicationContext applicationContext; /** * Create a new {@link AbandonedRunException} instance. */ public AbandonedRunException() { this(null); } /** * Create a new {@link AbandonedRunException} instance with the given application * context. * @param applicationContext the application context that was available when the * run was abandoned */ public AbandonedRunException(ConfigurableApplicationContext applicationContext) { this.applicationContext = applicationContext; } /** * Return the application context that was available when the run was abandoned or * {@code null} if no context was available. * @return the application context */ public ConfigurableApplicationContext getApplicationContext() { return this.applicationContext; } } /** * {@link SpringApplicationHook} decorator that ensures the hook is only used once. */ private static final class SingleUseSpringApplicationHook implements SpringApplicationHook { private final AtomicBoolean used = new AtomicBoolean(); private final SpringApplicationHook delegate; private SingleUseSpringApplicationHook(SpringApplicationHook delegate) { this.delegate = delegate; } @Override public SpringApplicationRunListener getRunListener(SpringApplication springApplication) { return this.used.compareAndSet(false, true) ? this.delegate.getRunListener(springApplication) : null; } } /** * Starts a non-daemon thread to keep the JVM alive on {@link ContextRefreshedEvent}. * Stops the thread on {@link ContextClosedEvent}. */ private static final class KeepAlive implements ApplicationListener<ApplicationContextEvent> { private final AtomicReference<Thread> thread = new AtomicReference<>(); @Override public void onApplicationEvent(ApplicationContextEvent event) { if (event instanceof ContextRefreshedEvent) { startKeepAliveThread(); } else if (event instanceof ContextClosedEvent) { stopKeepAliveThread(); } } private void startKeepAliveThread() { Thread thread = new Thread(() -> { while (true) { try { Thread.sleep(Long.MAX_VALUE); } catch (InterruptedException ex) { break; } } }); if (this.thread.compareAndSet(null, thread)) { thread.setDaemon(false); thread.setName("keep-alive"); thread.start(); } } private void stopKeepAliveThread() { Thread thread = this.thread.getAndSet(null); if (thread == null) { return; } thread.interrupt(); } } /** * Strategy used to handle startup concerns. */ abstract static class Startup { private Duration timeTakenToStarted; protected abstract long startTime(); protected abstract Long processUptime(); protected abstract String action(); final Duration started() { long now = System.currentTimeMillis(); this.timeTakenToStarted = Duration.ofMillis(now - startTime()); return this.timeTakenToStarted; } Duration timeTakenToStarted() { return this.timeTakenToStarted; } private Duration ready() { long now = System.currentTimeMillis(); return Duration.ofMillis(now - startTime()); } static Startup create() { ClassLoader classLoader = Startup.class.getClassLoader(); return (ClassUtils.isPresent("jdk.crac.management.CRaCMXBean", classLoader) && ClassUtils.isPresent("org.crac.management.CRaCMXBean", classLoader)) ? new CoordinatedRestoreAtCheckpointStartup() : new StandardStartup(); } } /** * Standard {@link Startup} implementation. */ private static final class StandardStartup extends Startup { private final Long startTime = System.currentTimeMillis(); @Override protected long startTime() { return this.startTime; } @Override protected Long processUptime() { try { return ManagementFactory.getRuntimeMXBean().getUptime(); } catch (Throwable ex) { return null; } } @Override protected String action() { return "Started"; } } /** * Coordinated-Restore-At-Checkpoint {@link Startup} implementation. */ private static final class CoordinatedRestoreAtCheckpointStartup extends Startup { private final StandardStartup fallback = new StandardStartup(); @Override protected Long processUptime() { long uptime = CRaCMXBean.getCRaCMXBean().getUptimeSinceRestore(); return (uptime >= 0) ? uptime : this.fallback.processUptime(); } @Override protected String action() { return (restoreTime() >= 0) ? "Restored" : this.fallback.action(); } private long restoreTime() { return CRaCMXBean.getCRaCMXBean().getRestoreTime(); } @Override protected long startTime() { long restoreTime = restoreTime(); return (restoreTime >= 0) ? restoreTime : this.fallback.startTime(); } } /** * {@link OrderSourceProvider} used to obtain factory method and target type order * sources. Based on internal {@link DefaultListableBeanFactory} code. */ private class FactoryAwareOrderSourceProvider implements OrderSourceProvider { private final ConfigurableBeanFactory beanFactory; private final Map<?, String> instancesToBeanNames; FactoryAwareOrderSourceProvider(ConfigurableBeanFactory beanFactory, Map<?, String> instancesToBeanNames) { this.beanFactory = beanFactory; this.instancesToBeanNames = instancesToBeanNames; } @Override public Object getOrderSource(Object obj) { String beanName = this.instancesToBeanNames.get(obj); return (beanName != null) ? getOrderSource(beanName, obj.getClass()) : null; } private Object getOrderSource(String beanName, Class<?> instanceType) { try { RootBeanDefinition beanDefinition = (RootBeanDefinition) this.beanFactory .getMergedBeanDefinition(beanName); Method factoryMethod = beanDefinition.getResolvedFactoryMethod(); Class<?> targetType = beanDefinition.getTargetType(); targetType = (targetType != instanceType) ? targetType : null; return Stream.of(factoryMethod, targetType).filter(Objects::nonNull).toArray(); } catch (NoSuchBeanDefinitionException ex) { return null; } } } }
spring-projects/spring-boot
spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java
44,901
/* * Copyright The async-profiler authors * SPDX-License-Identifier: Apache-2.0 */ import one.convert.*; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class Main { public static void main(String[] argv) throws Exception { Arguments args = new Arguments(argv); if (args.help || args.files.isEmpty()) { usage(); return; } if (args.files.size() == 1) { args.files.add("."); } int fileCount = args.files.size() - 1; String lastFile = args.files.get(fileCount); boolean isDirectory = new File(lastFile).isDirectory(); if (args.output == null) { int ext; if (!isDirectory && (ext = lastFile.lastIndexOf('.')) > 0) { args.output = lastFile.substring(ext + 1); } else { args.output = "html"; } } for (int i = 0; i < fileCount; i++) { String input = args.files.get(i); String output = isDirectory ? new File(lastFile, replaceExt(input, args.output)).getPath() : lastFile; System.out.print("Converting " + getFileName(input) + " -> " + getFileName(output) + " "); System.out.flush(); long startTime = System.nanoTime(); convert(input, output, args); long endTime = System.nanoTime(); System.out.print("# " + (endTime - startTime) / 1000000 / 1000.0 + " s\n"); } } public static void convert(String input, String output, Arguments args) throws IOException { if (isJfr(input)) { if ("html".equals(args.output)) { JfrToFlame.convert(input, output, args); } else if ("pprof".equals(args.output) || "pb".equals(args.output) || args.output.endsWith("gz")) { JfrToPprof.convert(input, output, args); } else { throw new IllegalArgumentException("Unrecognized output format: " + args.output); } } else { FlameGraph.convert(input, output, args); } } private static String getFileName(String fileName) { return fileName.substring(fileName.lastIndexOf(File.separatorChar) + 1); } private static String replaceExt(String fileName, String ext) { int slash = fileName.lastIndexOf(File.separatorChar); int dot = fileName.lastIndexOf('.'); return dot > slash ? fileName.substring(slash + 1, dot + 1) + ext : fileName.substring(slash + 1) + '.' + ext; } private static boolean isJfr(String fileName) throws IOException { if (fileName.endsWith(".jfr")) { return true; } else if (fileName.endsWith(".collapsed") || fileName.endsWith(".txt") || fileName.endsWith(".csv")) { return false; } byte[] buf = new byte[4]; try (FileInputStream fis = new FileInputStream(fileName)) { return fis.read(buf) == 4 && buf[0] == 'F' && buf[1] == 'L' && buf[2] == 'R' && buf[3] == 0; } } private static void usage() { System.out.print("Usage: jfrconv [options] <input> [<input>...] <output>\n" + "\n" + "Conversion options:\n" + " -o --output FORMAT Output format: html, collapsed, pprof, pb.gz\n" + "\n" + "JFR options:\n" + " --cpu CPU profile\n" + " --wall Wall clock profile\n" + " --alloc Allocation profile\n" + " --live Live object profile\n" + " --lock Lock contention profile\n" + " -t --threads Split stack traces by threads\n" + " -s --state LIST Filter thread states: runnable, sleeping\n" + " --classify Classify samples into predefined categories\n" + " --total Accumulate total value (time, bytes, etc.)\n" + " --lines Show line numbers\n" + " --bci Show bytecode indices\n" + " --simple Simple class names instead of FQN\n" + " --norm Normalize names of hidden classes / lambdas\n" + " --dot Dotted class names\n" + " --from TIME Start time in ms (absolute or relative)\n" + " --to TIME End time in ms (absolute or relative)\n" + "\n" + "Flame Graph options:\n" + " --title STRING Flame Graph title\n" + " --minwidth X Skip frames smaller than X%\n" + " --skip N Skip N bottom frames\n" + " -r --reverse Reverse stack traces (icicle graph)\n" + " -I --include REGEX Include only stacks with the specified frames\n" + " -X --exclude REGEX Exclude stacks with the specified frames\n" + " --highlight REGEX Highlight frames matching the given pattern\n"); } }
async-profiler/async-profiler
src/converter/Main.java
44,902
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.transport; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.elasticsearch.action.ActionListener; import org.elasticsearch.common.AsyncBiFunction; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.metrics.CounterMetric; import org.elasticsearch.common.util.concurrent.AbstractRunnable; import org.elasticsearch.common.util.concurrent.ConcurrentCollections; import org.elasticsearch.core.TimeValue; import org.elasticsearch.threadpool.ThreadPool; import java.io.Closeable; import java.io.IOException; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicBoolean; /** * Implements the scheduling and sending of keep alive pings. Client channels send keep alive pings to the * server and server channels respond. Pings are only sent at the scheduled time if the channel did not send * and receive a message since the last ping. */ final class TransportKeepAlive implements Closeable { static final int PING_DATA_SIZE = -1; private static final BytesReference PING_MESSAGE; static { try (BytesStreamOutput out = new BytesStreamOutput()) { out.writeByte((byte) 'E'); out.writeByte((byte) 'S'); out.writeInt(PING_DATA_SIZE); PING_MESSAGE = out.copyBytes(); } catch (IOException e) { throw new AssertionError(e.getMessage(), e); // won't happen } } private static final Logger logger = LogManager.getLogger(TransportKeepAlive.class); private final CounterMetric successfulPings = new CounterMetric(); private final CounterMetric failedPings = new CounterMetric(); private final ConcurrentMap<TimeValue, ScheduledPing> pingIntervals = ConcurrentCollections.newConcurrentMap(); private final ThreadPool threadPool; private final AsyncBiFunction<TcpChannel, BytesReference, Void> pingSender; private volatile boolean isClosed; TransportKeepAlive(ThreadPool threadPool, AsyncBiFunction<TcpChannel, BytesReference, Void> pingSender) { this.threadPool = threadPool; this.pingSender = pingSender; } void registerNodeConnection(List<TcpChannel> nodeChannels, ConnectionProfile connectionProfile) { TimeValue pingInterval = connectionProfile.getPingInterval(); if (pingInterval.millis() < 0) { return; } final ScheduledPing scheduledPing = pingIntervals.computeIfAbsent(pingInterval, ScheduledPing::new); scheduledPing.ensureStarted(); for (TcpChannel channel : nodeChannels) { scheduledPing.addChannel(channel); channel.addCloseListener(ActionListener.running(() -> scheduledPing.removeChannel(channel))); } } /** * Called when a keep alive ping is received. If the channel that received the keep alive ping is a * server channel, a ping is sent back. If the channel that received the keep alive is a client channel, * this method does nothing as the client initiated the ping in the first place. * * @param channel that received the keep alive ping */ void receiveKeepAlive(TcpChannel channel) { // The client-side initiates pings and the server-side responds. So if this is a client channel, this // method is a no-op. if (channel.isServerChannel()) { sendPing(channel); } } long successfulPingCount() { return successfulPings.count(); } long failedPingCount() { return failedPings.count(); } private void sendPing(TcpChannel channel) { pingSender.apply(channel, PING_MESSAGE, new ActionListener<Void>() { @Override public void onResponse(Void v) { successfulPings.inc(); } @Override public void onFailure(Exception e) { if (channel.isOpen()) { logger.debug(() -> "[" + channel + "] failed to send transport ping", e); failedPings.inc(); } else { logger.trace(() -> "[" + channel + "] failed to send transport ping (channel closed)", e); } } }); } @Override public void close() { isClosed = true; } private class ScheduledPing extends AbstractRunnable { private final TimeValue pingInterval; private final Set<TcpChannel> channels = ConcurrentCollections.newConcurrentSet(); private final AtomicBoolean isStarted = new AtomicBoolean(false); private volatile long lastPingRelativeMillis; private ScheduledPing(TimeValue pingInterval) { this.pingInterval = pingInterval; this.lastPingRelativeMillis = threadPool.relativeTimeInMillis(); } void ensureStarted() { if (isStarted.get() == false && isStarted.compareAndSet(false, true)) { threadPool.schedule(this, pingInterval, threadPool.generic()); } } void addChannel(TcpChannel channel) { channels.add(channel); } void removeChannel(TcpChannel channel) { channels.remove(channel); } @Override protected void doRun() throws Exception { if (isClosed) { return; } for (TcpChannel channel : channels) { // In the future it is possible that we may want to kill a channel if we have not read from // the channel since the last ping. However, this will need to be backwards compatible with // pre-6.6 nodes that DO NOT respond to pings if (needsKeepAlivePing(channel)) { sendPing(channel); } } this.lastPingRelativeMillis = threadPool.relativeTimeInMillis(); } @Override public void onAfter() { if (isClosed) { return; } threadPool.scheduleUnlessShuttingDown(pingInterval, threadPool.generic(), this); } @Override public void onFailure(Exception e) { logger.warn("failed to send ping transport message", e); } private boolean needsKeepAlivePing(TcpChannel channel) { TcpChannel.ChannelStats stats = channel.getChannelStats(); long accessedDelta = stats.lastAccessedTime() - lastPingRelativeMillis; return accessedDelta <= 0; } } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/transport/TransportKeepAlive.java
44,903
/* * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.build.docs; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.gradle.api.DefaultTask; import org.gradle.api.Task; import org.gradle.api.file.FileCollection; import org.gradle.api.file.RegularFileProperty; import org.gradle.api.provider.ListProperty; import org.gradle.api.provider.Property; import org.gradle.api.tasks.Classpath; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.OutputFile; import org.gradle.api.tasks.TaskAction; import org.gradle.internal.jvm.Jvm; /** * {@link Task} to run an application for the purpose of capturing its output for * inclusion in the reference documentation. * * @author Andy Wilkinson */ public class ApplicationRunner extends DefaultTask { private final RegularFileProperty output = getProject().getObjects().fileProperty(); private final ListProperty<String> args = getProject().getObjects().listProperty(String.class); private final Property<String> mainClass = getProject().getObjects().property(String.class); private final Property<String> expectedLogging = getProject().getObjects().property(String.class); private final Property<String> applicationJar = getProject().getObjects() .property(String.class) .convention("/opt/apps/myapp.jar"); private final Map<String, String> normalizations = new HashMap<>(); private FileCollection classpath; @OutputFile public RegularFileProperty getOutput() { return this.output; } @Classpath public FileCollection getClasspath() { return this.classpath; } public void setClasspath(FileCollection classpath) { this.classpath = classpath; } @Input public ListProperty<String> getArgs() { return this.args; } @Input public Property<String> getMainClass() { return this.mainClass; } @Input public Property<String> getExpectedLogging() { return this.expectedLogging; } @Input Map<String, String> getNormalizations() { return this.normalizations; } @Input public Property<String> getApplicationJar() { return this.applicationJar; } public void normalizeTomcatPort() { this.normalizations.put("(Tomcat started on port )[\\d]+( \\(http\\))", "$18080$2"); this.normalizations.put("(Tomcat initialized with port )[\\d]+( \\(http\\))", "$18080$2"); } public void normalizeLiveReloadPort() { this.normalizations.put("(LiveReload server is running on port )[\\d]+", "$135729"); } @TaskAction void runApplication() throws IOException { List<String> command = new ArrayList<>(); File executable = Jvm.current().getExecutable("java"); command.add(executable.getAbsolutePath()); command.add("-cp"); command.add(this.classpath.getFiles() .stream() .map(File::getAbsolutePath) .collect(Collectors.joining(File.pathSeparator))); command.add(this.mainClass.get()); command.addAll(this.args.get()); File outputFile = this.output.getAsFile().get(); Process process = new ProcessBuilder().redirectOutput(outputFile) .redirectError(outputFile) .command(command) .start(); awaitLogging(process); process.destroy(); normalizeLogging(); } private void awaitLogging(Process process) { long end = System.currentTimeMillis() + 60000; String expectedLogging = this.expectedLogging.get(); while (System.currentTimeMillis() < end) { for (String line : outputLines()) { if (line.contains(expectedLogging)) { return; } } if (!process.isAlive()) { throw new IllegalStateException("Process exited before '" + expectedLogging + "' was logged"); } } throw new IllegalStateException("'" + expectedLogging + "' was not logged within 60 seconds"); } private List<String> outputLines() { Path outputPath = this.output.get().getAsFile().toPath(); try { return Files.readAllLines(outputPath); } catch (IOException ex) { throw new RuntimeException("Failed to read lines of output from '" + outputPath + "'", ex); } } private void normalizeLogging() { List<String> outputLines = outputLines(); List<String> normalizedLines = normalize(outputLines); Path outputPath = this.output.get().getAsFile().toPath(); try { Files.write(outputPath, normalizedLines); } catch (IOException ex) { throw new RuntimeException("Failed to write normalized lines of output to '" + outputPath + "'", ex); } } private List<String> normalize(List<String> lines) { List<String> normalizedLines = lines; Map<String, String> normalizations = new HashMap<>(this.normalizations); normalizations.put("(Starting .* using Java .* with PID [\\d]+ \\().*( started by ).*( in ).*(\\))", "$1" + this.applicationJar.get() + "$2myuser$3/opt/apps/$4"); for (Entry<String, String> normalization : normalizations.entrySet()) { Pattern pattern = Pattern.compile(normalization.getKey()); normalizedLines = normalize(normalizedLines, pattern, normalization.getValue()); } return normalizedLines; } private List<String> normalize(List<String> lines, Pattern pattern, String replacement) { boolean matched = false; List<String> normalizedLines = new ArrayList<>(); for (String line : lines) { Matcher matcher = pattern.matcher(line); StringBuilder transformed = new StringBuilder(); while (matcher.find()) { matched = true; matcher.appendReplacement(transformed, replacement); } matcher.appendTail(transformed); normalizedLines.add(transformed.toString()); } if (!matched) { reportUnmatchedNormalization(lines, pattern); } return normalizedLines; } private void reportUnmatchedNormalization(List<String> lines, Pattern pattern) { StringBuilder message = new StringBuilder( "'" + pattern + "' did not match any of the following lines of output:"); message.append(String.format("%n")); for (String line : lines) { message.append(String.format("%s%n", line)); } throw new IllegalStateException(message.toString()); } }
spring-projects/spring-boot
buildSrc/src/main/java/org/springframework/boot/build/docs/ApplicationRunner.java
44,904
package com.macro.mall.service.impl; import com.github.pagehelper.PageHelper; import com.macro.mall.dao.OmsOrderDao; import com.macro.mall.dao.OmsOrderOperateHistoryDao; import com.macro.mall.dto.*; import com.macro.mall.mapper.OmsOrderMapper; import com.macro.mall.mapper.OmsOrderOperateHistoryMapper; import com.macro.mall.model.OmsOrder; import com.macro.mall.model.OmsOrderExample; import com.macro.mall.model.OmsOrderOperateHistory; import com.macro.mall.service.OmsOrderService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; import java.util.List; import java.util.stream.Collectors; /** * 订单管理Service实现类 * Created by macro on 2018/10/11. */ @Service public class OmsOrderServiceImpl implements OmsOrderService { @Autowired private OmsOrderMapper orderMapper; @Autowired private OmsOrderDao orderDao; @Autowired private OmsOrderOperateHistoryDao orderOperateHistoryDao; @Autowired private OmsOrderOperateHistoryMapper orderOperateHistoryMapper; @Override public List<OmsOrder> list(OmsOrderQueryParam queryParam, Integer pageSize, Integer pageNum) { PageHelper.startPage(pageNum, pageSize); return orderDao.getList(queryParam); } @Override public int delivery(List<OmsOrderDeliveryParam> deliveryParamList) { //批量发货 int count = orderDao.delivery(deliveryParamList); //添加操作记录 List<OmsOrderOperateHistory> operateHistoryList = deliveryParamList.stream() .map(omsOrderDeliveryParam -> { OmsOrderOperateHistory history = new OmsOrderOperateHistory(); history.setOrderId(omsOrderDeliveryParam.getOrderId()); history.setCreateTime(new Date()); history.setOperateMan("后台管理员"); history.setOrderStatus(2); history.setNote("完成发货"); return history; }).collect(Collectors.toList()); orderOperateHistoryDao.insertList(operateHistoryList); return count; } @Override public int close(List<Long> ids, String note) { OmsOrder record = new OmsOrder(); record.setStatus(4); OmsOrderExample example = new OmsOrderExample(); example.createCriteria().andDeleteStatusEqualTo(0).andIdIn(ids); int count = orderMapper.updateByExampleSelective(record, example); List<OmsOrderOperateHistory> historyList = ids.stream().map(orderId -> { OmsOrderOperateHistory history = new OmsOrderOperateHistory(); history.setOrderId(orderId); history.setCreateTime(new Date()); history.setOperateMan("后台管理员"); history.setOrderStatus(4); history.setNote("订单关闭:"+note); return history; }).collect(Collectors.toList()); orderOperateHistoryDao.insertList(historyList); return count; } @Override public int delete(List<Long> ids) { OmsOrder record = new OmsOrder(); record.setDeleteStatus(1); OmsOrderExample example = new OmsOrderExample(); example.createCriteria().andDeleteStatusEqualTo(0).andIdIn(ids); return orderMapper.updateByExampleSelective(record, example); } @Override public OmsOrderDetail detail(Long id) { return orderDao.getDetail(id); } @Override public int updateReceiverInfo(OmsReceiverInfoParam receiverInfoParam) { OmsOrder order = new OmsOrder(); order.setId(receiverInfoParam.getOrderId()); order.setReceiverName(receiverInfoParam.getReceiverName()); order.setReceiverPhone(receiverInfoParam.getReceiverPhone()); order.setReceiverPostCode(receiverInfoParam.getReceiverPostCode()); order.setReceiverDetailAddress(receiverInfoParam.getReceiverDetailAddress()); order.setReceiverProvince(receiverInfoParam.getReceiverProvince()); order.setReceiverCity(receiverInfoParam.getReceiverCity()); order.setReceiverRegion(receiverInfoParam.getReceiverRegion()); order.setModifyTime(new Date()); int count = orderMapper.updateByPrimaryKeySelective(order); //插入操作记录 OmsOrderOperateHistory history = new OmsOrderOperateHistory(); history.setOrderId(receiverInfoParam.getOrderId()); history.setCreateTime(new Date()); history.setOperateMan("后台管理员"); history.setOrderStatus(receiverInfoParam.getStatus()); history.setNote("修改收货人信息"); orderOperateHistoryMapper.insert(history); return count; } @Override public int updateMoneyInfo(OmsMoneyInfoParam moneyInfoParam) { OmsOrder order = new OmsOrder(); order.setId(moneyInfoParam.getOrderId()); order.setFreightAmount(moneyInfoParam.getFreightAmount()); order.setDiscountAmount(moneyInfoParam.getDiscountAmount()); order.setModifyTime(new Date()); int count = orderMapper.updateByPrimaryKeySelective(order); //插入操作记录 OmsOrderOperateHistory history = new OmsOrderOperateHistory(); history.setOrderId(moneyInfoParam.getOrderId()); history.setCreateTime(new Date()); history.setOperateMan("后台管理员"); history.setOrderStatus(moneyInfoParam.getStatus()); history.setNote("修改费用信息"); orderOperateHistoryMapper.insert(history); return count; } @Override public int updateNote(Long id, String note, Integer status) { OmsOrder order = new OmsOrder(); order.setId(id); order.setNote(note); order.setModifyTime(new Date()); int count = orderMapper.updateByPrimaryKeySelective(order); OmsOrderOperateHistory history = new OmsOrderOperateHistory(); history.setOrderId(id); history.setCreateTime(new Date()); history.setOperateMan("后台管理员"); history.setOrderStatus(status); history.setNote("修改备注信息:"+note); orderOperateHistoryMapper.insert(history); return count; } }
macrozheng/mall
mall-admin/src/main/java/com/macro/mall/service/impl/OmsOrderServiceImpl.java
44,905
/* * Copyright (c) 2016-present, RxJava Contributors. * * 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 io.reactivex.rxjava3.subjects; import java.lang.reflect.Array; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.*; import io.reactivex.rxjava3.annotations.*; import io.reactivex.rxjava3.core.Observer; import io.reactivex.rxjava3.core.Scheduler; import io.reactivex.rxjava3.disposables.Disposable; import io.reactivex.rxjava3.internal.functions.ObjectHelper; import io.reactivex.rxjava3.internal.util.*; import io.reactivex.rxjava3.plugins.RxJavaPlugins; /** * Replays events (in a configurable bounded or unbounded manner) to current and late {@link Observer}s. * <p> * This subject does not have a public constructor by design; a new empty instance of this * {@code ReplaySubject} can be created via the following {@code create} methods that * allow specifying the retention policy for items: * <ul> * <li>{@link #create()} - creates an empty, unbounded {@code ReplaySubject} that * caches all items and the terminal event it receives. * <p> * <img width="640" height="299" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/ReplaySubject.u.png" alt=""> * <p> * <img width="640" height="398" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/ReplaySubject.ue.png" alt=""> * </li> * <li>{@link #create(int)} - creates an empty, unbounded {@code ReplaySubject} * with a hint about how many <b>total</b> items one expects to retain. * </li> * <li>{@link #createWithSize(int)} - creates an empty, size-bound {@code ReplaySubject} * that retains at most the given number of the latest item it receives. * <p> * <img width="640" height="420" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/ReplaySubject.n.png" alt=""> * </li> * <li>{@link #createWithTime(long, TimeUnit, Scheduler)} - creates an empty, time-bound * {@code ReplaySubject} that retains items no older than the specified time amount. * <p> * <img width="640" height="415" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/ReplaySubject.t.png" alt=""> * </li> * <li>{@link #createWithTimeAndSize(long, TimeUnit, Scheduler, int)} - creates an empty, * time- and size-bound {@code ReplaySubject} that retains at most the given number * items that are also not older than the specified time amount. * <p> * <img width="640" height="404" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/ReplaySubject.nt.png" alt=""> * </li> * </ul> * <p> * Since a {@code Subject} is conceptionally derived from the {@code Processor} type in the Reactive Streams specification, * {@code null}s are not allowed (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.13">Rule 2.13</a>) as * parameters to {@link #onNext(Object)} and {@link #onError(Throwable)}. Such calls will result in a * {@link NullPointerException} being thrown and the subject's state is not changed. * <p> * Since a {@code ReplaySubject} is an {@link io.reactivex.rxjava3.core.Observable}, it does not support backpressure. * <p> * When this {@code ReplaySubject} is terminated via {@link #onError(Throwable)} or {@link #onComplete()}, * late {@link io.reactivex.rxjava3.core.Observer}s will receive the retained/cached items first (if any) followed by the respective * terminal event. If the {@code ReplaySubject} has a time-bound, the age of the retained/cached items are still considered * when replaying and thus it may result in no items being emitted before the terminal event. * <p> * Once an {@code Observer} has subscribed, it will receive items continuously from that point on. Bounds only affect how * many past items a new {@code Observer} will receive before it catches up with the live event feed. * <p> * Even though {@code ReplaySubject} implements the {@code Observer} interface, calling * {@code onSubscribe} is not required (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.12">Rule 2.12</a>) * if the subject is used as a standalone source. However, calling {@code onSubscribe} * after the {@code ReplaySubject} reached its terminal state will result in the * given {@code Disposable} being disposed immediately. * <p> * Calling {@link #onNext(Object)}, {@link #onError(Throwable)} and {@link #onComplete()} * is required to be serialized (called from the same thread or called non-overlappingly from different threads * through external means of serialization). The {@link #toSerialized()} method available to all {@code Subject}s * provides such serialization and also protects against reentrance (i.e., when a downstream {@code Observer} * consuming this subject also wants to call {@link #onNext(Object)} on this subject recursively). * <p> * This {@code ReplaySubject} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()}, * {@link #getThrowable()} and {@link #hasObservers()} as well as means to read the retained/cached items * in a non-blocking and thread-safe manner via {@link #hasValue()}, {@link #getValue()}, * {@link #getValues()} or {@link #getValues(Object[])}. * <p> * Note that due to concurrency requirements, a size- and time-bounded {@code ReplaySubject} may hold strong references to more * source emissions than specified while it isn't terminated yet. Use the {@link #cleanupBuffer()} to allow * such inaccessible items to be cleaned up by GC once no consumer references it anymore. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code ReplaySubject} does not operate by default on a particular {@link io.reactivex.rxjava3.core.Scheduler} and * the {@code Observer}s get notified on the thread the respective {@code onXXX} methods were invoked. * Time-bound {@code ReplaySubject}s use the given {@code Scheduler} in their {@code create} methods * as time source to timestamp of items received for the age checks.</dd> * <dt><b>Error handling:</b></dt> * <dd>When the {@link #onError(Throwable)} is called, the {@code ReplaySubject} enters into a terminal state * and emits the same {@code Throwable} instance to the last set of {@code Observer}s. During this emission, * if one or more {@code Observer}s dispose their respective {@code Disposable}s, the * {@code Throwable} is delivered to the global error handler via * {@link io.reactivex.rxjava3.plugins.RxJavaPlugins#onError(Throwable)} (multiple times if multiple {@code Observer}s * cancel at once). * If there were no {@code Observer}s subscribed to this {@code ReplaySubject} when the {@code onError()} * was called, the global error handler is not invoked. * </dd> * </dl> * <p> * Example usage: * <pre> {@code ReplaySubject<Object> subject = ReplaySubject.create(); subject.onNext("one"); subject.onNext("two"); subject.onNext("three"); subject.onComplete(); // both of the following will get the onNext/onComplete calls from above subject.subscribe(observer1); subject.subscribe(observer2); } </pre> * * @param <T> the value type */ public final class ReplaySubject<T> extends Subject<T> { final ReplayBuffer<T> buffer; final AtomicReference<ReplayDisposable<T>[]> observers; @SuppressWarnings("rawtypes") static final ReplayDisposable[] EMPTY = new ReplayDisposable[0]; @SuppressWarnings("rawtypes") static final ReplayDisposable[] TERMINATED = new ReplayDisposable[0]; boolean done; /** * Creates an unbounded replay subject. * <p> * The internal buffer is backed by an {@link ArrayList} and starts with an initial capacity of 16. Once the * number of items reaches this capacity, it will grow as necessary (usually by 50%). However, as the * number of items grows, this causes frequent array reallocation and copying, and may hurt performance * and latency. This can be avoided with the {@link #create(int)} overload which takes an initial capacity * parameter and can be tuned to reduce the array reallocation frequency as needed. * * @param <T> * the type of items observed and emitted by the Subject * @return the created subject */ @CheckReturnValue @NonNull public static <T> ReplaySubject<T> create() { return new ReplaySubject<>(new UnboundedReplayBuffer<>(16)); } /** * Creates an unbounded replay subject with the specified initial buffer capacity. * <p> * Use this method to avoid excessive array reallocation while the internal buffer grows to accommodate new * items. For example, if you know that the buffer will hold 32k items, you can ask the * {@code ReplaySubject} to preallocate its internal array with a capacity to hold that many items. Once * the items start to arrive, the internal array won't need to grow, creating less garbage and no overhead * due to frequent array-copying. * * @param <T> * the type of items observed and emitted by the Subject * @param capacityHint * the initial buffer capacity * @return the created subject * @throws IllegalArgumentException if {@code capacityHint} is non-positive */ @CheckReturnValue @NonNull public static <T> ReplaySubject<T> create(int capacityHint) { ObjectHelper.verifyPositive(capacityHint, "capacityHint"); return new ReplaySubject<>(new UnboundedReplayBuffer<>(capacityHint)); } /** * Creates a size-bounded replay subject. * <p> * In this setting, the {@code ReplaySubject} holds at most {@code size} items in its internal buffer and * discards the oldest item. * <p> * When observers subscribe to a terminated {@code ReplaySubject}, they are guaranteed to see at most * {@code size} {@code onNext} events followed by a termination event. * <p> * If an observer subscribes while the {@code ReplaySubject} is active, it will observe all items in the * buffer at that point in time and each item observed afterwards, even if the buffer evicts items due to * the size constraint in the mean time. In other words, once an Observer subscribes, it will receive items * without gaps in the sequence. * * @param <T> * the type of items observed and emitted by the Subject * @param maxSize * the maximum number of buffered items * @return the created subject * @throws IllegalArgumentException if {@code maxSize} is non-positive */ @CheckReturnValue @NonNull public static <T> ReplaySubject<T> createWithSize(int maxSize) { ObjectHelper.verifyPositive(maxSize, "maxSize"); return new ReplaySubject<>(new SizeBoundReplayBuffer<>(maxSize)); } /** * Creates an unbounded replay subject with the bounded-implementation for testing purposes. * <p> * This variant behaves like the regular unbounded {@code ReplaySubject} created via {@link #create()} but * uses the structures of the bounded-implementation. This is by no means intended for the replacement of * the original, array-backed and unbounded {@code ReplaySubject} due to the additional overhead of the * linked-list based internal buffer. The sole purpose is to allow testing and reasoning about the behavior * of the bounded implementations without the interference of the eviction policies. * * @param <T> * the type of items observed and emitted by the Subject * @return the created subject */ /* test */ static <T> ReplaySubject<T> createUnbounded() { return new ReplaySubject<>(new SizeBoundReplayBuffer<>(Integer.MAX_VALUE)); } /** * Creates a time-bounded replay subject. * <p> * In this setting, the {@code ReplaySubject} internally tags each observed item with a timestamp value * supplied by the {@link Scheduler} and keeps only those whose age is less than the supplied time value * converted to milliseconds. For example, an item arrives at T=0 and the max age is set to 5; at T&gt;=5 * this first item is then evicted by any subsequent item or termination event, leaving the buffer empty. * <p> * Once the subject is terminated, observers subscribing to it will receive items that remained in the * buffer after the terminal event, regardless of their age. * <p> * If an observer subscribes while the {@code ReplaySubject} is active, it will observe only those items * from within the buffer that have an age less than the specified time, and each item observed thereafter, * even if the buffer evicts items due to the time constraint in the mean time. In other words, once an * observer subscribes, it observes items without gaps in the sequence except for any outdated items at the * beginning of the sequence. * <p> * Note that terminal notifications ({@code onError} and {@code onComplete}) trigger eviction as well. For * example, with a max age of 5, the first item is observed at T=0, then an {@code onComplete} notification * arrives at T=10. If an observer subscribes at T=11, it will find an empty {@code ReplaySubject} with just * an {@code onComplete} notification. * * @param <T> * the type of items observed and emitted by the Subject * @param maxAge * the maximum age of the contained items * @param unit * the time unit of {@code time} * @param scheduler * the {@link Scheduler} that provides the current time * @return the created subject * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null} * @throws IllegalArgumentException if {@code maxAge} is non-positive */ @CheckReturnValue @NonNull public static <T> ReplaySubject<T> createWithTime(long maxAge, @NonNull TimeUnit unit, @NonNull Scheduler scheduler) { ObjectHelper.verifyPositive(maxAge, "maxAge"); Objects.requireNonNull(unit, "unit is null"); Objects.requireNonNull(scheduler, "scheduler is null"); return new ReplaySubject<>(new SizeAndTimeBoundReplayBuffer<>(Integer.MAX_VALUE, maxAge, unit, scheduler)); } /** * Creates a time- and size-bounded replay subject. * <p> * In this setting, the {@code ReplaySubject} internally tags each received item with a timestamp value * supplied by the {@link Scheduler} and holds at most {@code size} items in its internal buffer. It evicts * items from the start of the buffer if their age becomes less-than or equal to the supplied age in * milliseconds or the buffer reaches its {@code size} limit. * <p> * When observers subscribe to a terminated {@code ReplaySubject}, they observe the items that remained in * the buffer after the terminal notification, regardless of their age, but at most {@code size} items. * <p> * If an observer subscribes while the {@code ReplaySubject} is active, it will observe only those items * from within the buffer that have age less than the specified time and each subsequent item, even if the * buffer evicts items due to the time constraint in the mean time. In other words, once an observer * subscribes, it observes items without gaps in the sequence except for the outdated items at the beginning * of the sequence. * <p> * Note that terminal notifications ({@code onError} and {@code onComplete}) trigger eviction as well. For * example, with a max age of 5, the first item is observed at T=0, then an {@code onComplete} notification * arrives at T=10. If an observer subscribes at T=11, it will find an empty {@code ReplaySubject} with just * an {@code onComplete} notification. * * @param <T> * the type of items observed and emitted by the Subject * @param maxAge * the maximum age of the contained items * @param unit * the time unit of {@code time} * @param maxSize * the maximum number of buffered items * @param scheduler * the {@link Scheduler} that provides the current time * @return the created subject * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null} * @throws IllegalArgumentException if {@code maxAge} or {@code maxSize} is non-positive */ @CheckReturnValue @NonNull public static <T> ReplaySubject<T> createWithTimeAndSize(long maxAge, @NonNull TimeUnit unit, @NonNull Scheduler scheduler, int maxSize) { ObjectHelper.verifyPositive(maxSize, "maxSize"); ObjectHelper.verifyPositive(maxAge, "maxAge"); Objects.requireNonNull(unit, "unit is null"); Objects.requireNonNull(scheduler, "scheduler is null"); return new ReplaySubject<>(new SizeAndTimeBoundReplayBuffer<>(maxSize, maxAge, unit, scheduler)); } /** * Constructs a ReplayProcessor with the given custom ReplayBuffer instance. * @param buffer the ReplayBuffer instance, not null (not verified) */ @SuppressWarnings("unchecked") ReplaySubject(ReplayBuffer<T> buffer) { this.buffer = buffer; this.observers = new AtomicReference<>(EMPTY); } @Override protected void subscribeActual(Observer<? super T> observer) { ReplayDisposable<T> rs = new ReplayDisposable<>(observer, this); observer.onSubscribe(rs); if (add(rs)) { if (rs.cancelled) { remove(rs); return; } } buffer.replay(rs); } @Override public void onSubscribe(Disposable d) { if (done) { d.dispose(); } } @Override public void onNext(T t) { ExceptionHelper.nullCheck(t, "onNext called with a null value."); if (done) { return; } ReplayBuffer<T> b = buffer; b.add(t); for (ReplayDisposable<T> rs : observers.get()) { b.replay(rs); } } @Override public void onError(Throwable t) { ExceptionHelper.nullCheck(t, "onError called with a null Throwable."); if (done) { RxJavaPlugins.onError(t); return; } done = true; Object o = NotificationLite.error(t); ReplayBuffer<T> b = buffer; b.addFinal(o); for (ReplayDisposable<T> rs : terminate(o)) { b.replay(rs); } } @Override public void onComplete() { if (done) { return; } done = true; Object o = NotificationLite.complete(); ReplayBuffer<T> b = buffer; b.addFinal(o); for (ReplayDisposable<T> rs : terminate(o)) { b.replay(rs); } } @Override @CheckReturnValue public boolean hasObservers() { return observers.get().length != 0; } @CheckReturnValue /* test */ int observerCount() { return observers.get().length; } @Override @Nullable @CheckReturnValue public Throwable getThrowable() { Object o = buffer.get(); if (NotificationLite.isError(o)) { return NotificationLite.getError(o); } return null; } /** * Returns a single value the Subject currently has or null if no such value exists. * <p>The method is thread-safe. * @return a single value the Subject currently has or null if no such value exists */ @Nullable @CheckReturnValue public T getValue() { return buffer.getValue(); } /** * Makes sure the item cached by the head node in a bounded * ReplaySubject is released (as it is never part of a replay). * <p> * By default, live bounded buffers will remember one item before * the currently receivable one to ensure subscribers can always * receive a continuous sequence of items. A terminated ReplaySubject * automatically releases this inaccessible item. * <p> * The method must be called sequentially, similar to the standard * {@code onXXX} methods. * <p>History: 2.1.11 - experimental * @since 2.2 */ public void cleanupBuffer() { buffer.trimHead(); } /** An empty array to avoid allocation in getValues(). */ private static final Object[] EMPTY_ARRAY = new Object[0]; /** * Returns an Object array containing snapshot all values of the Subject. * <p>The method is thread-safe. * @return the array containing the snapshot of all values of the Subject */ @CheckReturnValue public Object[] getValues() { @SuppressWarnings("unchecked") T[] a = (T[])EMPTY_ARRAY; T[] b = getValues(a); if (b == EMPTY_ARRAY) { return new Object[0]; } return b; } /** * Returns a typed array containing a snapshot of all values of the Subject. * <p>The method follows the conventions of Collection.toArray by setting the array element * after the last value to null (if the capacity permits). * <p>The method is thread-safe. * @param array the target array to copy values into if it fits * @return the given array if the values fit into it or a new array containing all values */ @CheckReturnValue public T[] getValues(T[] array) { return buffer.getValues(array); } @Override @CheckReturnValue public boolean hasComplete() { Object o = buffer.get(); return NotificationLite.isComplete(o); } @Override @CheckReturnValue public boolean hasThrowable() { Object o = buffer.get(); return NotificationLite.isError(o); } /** * Returns true if the subject has any value. * <p>The method is thread-safe. * @return true if the subject has any value */ @CheckReturnValue public boolean hasValue() { return buffer.size() != 0; // NOPMD } @CheckReturnValue /* test*/ int size() { return buffer.size(); } boolean add(ReplayDisposable<T> rs) { for (;;) { ReplayDisposable<T>[] a = observers.get(); if (a == TERMINATED) { return false; } int len = a.length; @SuppressWarnings("unchecked") ReplayDisposable<T>[] b = new ReplayDisposable[len + 1]; System.arraycopy(a, 0, b, 0, len); b[len] = rs; if (observers.compareAndSet(a, b)) { return true; } } } @SuppressWarnings("unchecked") void remove(ReplayDisposable<T> rs) { for (;;) { ReplayDisposable<T>[] a = observers.get(); if (a == TERMINATED || a == EMPTY) { return; } int len = a.length; int j = -1; for (int i = 0; i < len; i++) { if (a[i] == rs) { j = i; break; } } if (j < 0) { return; } ReplayDisposable<T>[] b; if (len == 1) { b = EMPTY; } else { b = new ReplayDisposable[len - 1]; System.arraycopy(a, 0, b, 0, j); System.arraycopy(a, j + 1, b, j, len - j - 1); } if (observers.compareAndSet(a, b)) { return; } } } @SuppressWarnings("unchecked") ReplayDisposable<T>[] terminate(Object terminalValue) { buffer.compareAndSet(null, terminalValue); return observers.getAndSet(TERMINATED); } /** * Abstraction over a buffer that receives events and replays them to * individual Observers. * * @param <T> the value type */ interface ReplayBuffer<T> { void add(T value); void addFinal(Object notificationLite); void replay(ReplayDisposable<T> rs); int size(); @Nullable T getValue(); T[] getValues(T[] array); /** * Returns the terminal NotificationLite object or null if not yet terminated. * @return the terminal NotificationLite object or null if not yet terminated */ Object get(); /** * Atomically compares and sets the next terminal NotificationLite object if the * current equals to the expected NotificationLite object. * @param expected the expected NotificationLite object * @param next the next NotificationLite object * @return true if successful */ boolean compareAndSet(Object expected, Object next); /** * Make sure an old inaccessible head value is released * in a bounded buffer. */ void trimHead(); } static final class ReplayDisposable<T> extends AtomicInteger implements Disposable { private static final long serialVersionUID = 466549804534799122L; final Observer<? super T> downstream; final ReplaySubject<T> state; Object index; volatile boolean cancelled; ReplayDisposable(Observer<? super T> actual, ReplaySubject<T> state) { this.downstream = actual; this.state = state; } @Override public void dispose() { if (!cancelled) { cancelled = true; state.remove(this); } } @Override public boolean isDisposed() { return cancelled; } } static final class UnboundedReplayBuffer<T> extends AtomicReference<Object> implements ReplayBuffer<T> { private static final long serialVersionUID = -733876083048047795L; final List<Object> buffer; volatile boolean done; volatile int size; UnboundedReplayBuffer(int capacityHint) { this.buffer = new ArrayList<>(capacityHint); } @Override public void add(T value) { buffer.add(value); size++; } @Override public void addFinal(Object notificationLite) { buffer.add(notificationLite); trimHead(); size++; done = true; } @Override public void trimHead() { // no-op in this type of buffer } @Override @Nullable @SuppressWarnings("unchecked") public T getValue() { int s = size; if (s != 0) { List<Object> b = buffer; Object o = b.get(s - 1); if (NotificationLite.isComplete(o) || NotificationLite.isError(o)) { if (s == 1) { return null; } return (T)b.get(s - 2); } return (T)o; } return null; } @Override @SuppressWarnings("unchecked") public T[] getValues(T[] array) { int s = size; if (s == 0) { if (array.length != 0) { array[0] = null; } return array; } List<Object> b = buffer; Object o = b.get(s - 1); if (NotificationLite.isComplete(o) || NotificationLite.isError(o)) { s--; if (s == 0) { if (array.length != 0) { array[0] = null; } return array; } } if (array.length < s) { array = (T[])Array.newInstance(array.getClass().getComponentType(), s); } for (int i = 0; i < s; i++) { array[i] = (T)b.get(i); } if (array.length > s) { array[s] = null; } return array; } @Override @SuppressWarnings("unchecked") public void replay(ReplayDisposable<T> rs) { if (rs.getAndIncrement() != 0) { return; } int missed = 1; final List<Object> b = buffer; final Observer<? super T> a = rs.downstream; Integer indexObject = (Integer)rs.index; int index; if (indexObject != null) { index = indexObject; } else { index = 0; rs.index = 0; } for (;;) { if (rs.cancelled) { rs.index = null; return; } int s = size; while (s != index) { if (rs.cancelled) { rs.index = null; return; } Object o = b.get(index); if (done) { if (index + 1 == s) { s = size; if (index + 1 == s) { if (NotificationLite.isComplete(o)) { a.onComplete(); } else { a.onError(NotificationLite.getError(o)); } rs.index = null; rs.cancelled = true; return; } } } a.onNext((T)o); index++; } if (index != size) { continue; } rs.index = index; missed = rs.addAndGet(-missed); if (missed == 0) { break; } } } @Override public int size() { int s = size; if (s != 0) { Object o = buffer.get(s - 1); if (NotificationLite.isComplete(o) || NotificationLite.isError(o)) { return s - 1; } return s; } return 0; } } static final class Node<T> extends AtomicReference<Node<T>> { private static final long serialVersionUID = 6404226426336033100L; final T value; Node(T value) { this.value = value; } } static final class TimedNode<T> extends AtomicReference<TimedNode<T>> { private static final long serialVersionUID = 6404226426336033100L; final T value; final long time; TimedNode(T value, long time) { this.value = value; this.time = time; } } static final class SizeBoundReplayBuffer<T> extends AtomicReference<Object> implements ReplayBuffer<T> { private static final long serialVersionUID = 1107649250281456395L; final int maxSize; int size; volatile Node<Object> head; Node<Object> tail; volatile boolean done; SizeBoundReplayBuffer(int maxSize) { this.maxSize = maxSize; Node<Object> h = new Node<>(null); this.tail = h; this.head = h; } void trim() { if (size > maxSize) { size--; Node<Object> h = head; head = h.get(); } } @Override public void add(T value) { Node<Object> n = new Node<>(value); Node<Object> t = tail; tail = n; size++; t.set(n); // releases both the tail and size trim(); } @Override public void addFinal(Object notificationLite) { Node<Object> n = new Node<>(notificationLite); Node<Object> t = tail; tail = n; size++; t.lazySet(n); // releases both the tail and size trimHead(); done = true; } /** * Replace a non-empty head node with an empty one to * allow the GC of the inaccessible old value. */ @Override public void trimHead() { Node<Object> h = head; if (h.value != null) { Node<Object> n = new Node<>(null); n.lazySet(h.get()); head = n; } } @Override @Nullable @SuppressWarnings("unchecked") public T getValue() { Node<Object> prev = null; Node<Object> h = head; for (;;) { Node<Object> next = h.get(); if (next == null) { break; } prev = h; h = next; } Object v = h.value; if (v == null) { return null; } if (NotificationLite.isComplete(v) || NotificationLite.isError(v)) { return (T)prev.value; } return (T)v; } @Override @SuppressWarnings("unchecked") public T[] getValues(T[] array) { Node<Object> h = head; int s = size(); if (s == 0) { if (array.length != 0) { array[0] = null; } } else { if (array.length < s) { array = (T[])Array.newInstance(array.getClass().getComponentType(), s); } int i = 0; while (i != s) { Node<Object> next = h.get(); array[i] = (T)next.value; i++; h = next; } if (array.length > s) { array[s] = null; } } return array; } @Override @SuppressWarnings("unchecked") public void replay(ReplayDisposable<T> rs) { if (rs.getAndIncrement() != 0) { return; } int missed = 1; final Observer<? super T> a = rs.downstream; Node<Object> index = (Node<Object>)rs.index; if (index == null) { index = head; } for (;;) { for (;;) { if (rs.cancelled) { rs.index = null; return; } Node<Object> n = index.get(); if (n == null) { break; } Object o = n.value; if (done) { if (n.get() == null) { if (NotificationLite.isComplete(o)) { a.onComplete(); } else { a.onError(NotificationLite.getError(o)); } rs.index = null; rs.cancelled = true; return; } } a.onNext((T)o); index = n; } if (index.get() != null) { continue; } rs.index = index; missed = rs.addAndGet(-missed); if (missed == 0) { break; } } } @Override public int size() { int s = 0; Node<Object> h = head; while (s != Integer.MAX_VALUE) { Node<Object> next = h.get(); if (next == null) { Object o = h.value; if (NotificationLite.isComplete(o) || NotificationLite.isError(o)) { s--; } break; } s++; h = next; } return s; } } static final class SizeAndTimeBoundReplayBuffer<T> extends AtomicReference<Object> implements ReplayBuffer<T> { private static final long serialVersionUID = -8056260896137901749L; final int maxSize; final long maxAge; final TimeUnit unit; final Scheduler scheduler; int size; volatile TimedNode<Object> head; TimedNode<Object> tail; volatile boolean done; SizeAndTimeBoundReplayBuffer(int maxSize, long maxAge, TimeUnit unit, Scheduler scheduler) { this.maxSize = maxSize; this.maxAge = maxAge; this.unit = unit; this.scheduler = scheduler; TimedNode<Object> h = new TimedNode<>(null, 0L); this.tail = h; this.head = h; } void trim() { if (size > maxSize) { size--; TimedNode<Object> h = head; head = h.get(); } long limit = scheduler.now(unit) - maxAge; TimedNode<Object> h = head; for (;;) { if (size <= 1) { head = h; break; } TimedNode<Object> next = h.get(); if (next.time > limit) { head = h; break; } h = next; size--; } } void trimFinal() { long limit = scheduler.now(unit) - maxAge; TimedNode<Object> h = head; for (;;) { TimedNode<Object> next = h.get(); if (next.get() == null) { if (h.value != null) { TimedNode<Object> lasth = new TimedNode<>(null, 0L); lasth.lazySet(h.get()); head = lasth; } else { head = h; } break; } if (next.time > limit) { if (h.value != null) { TimedNode<Object> lasth = new TimedNode<>(null, 0L); lasth.lazySet(h.get()); head = lasth; } else { head = h; } break; } h = next; } } @Override public void add(T value) { TimedNode<Object> n = new TimedNode<>(value, scheduler.now(unit)); TimedNode<Object> t = tail; tail = n; size++; t.set(n); // releases both the tail and size trim(); } @Override public void addFinal(Object notificationLite) { TimedNode<Object> n = new TimedNode<>(notificationLite, Long.MAX_VALUE); TimedNode<Object> t = tail; tail = n; size++; t.lazySet(n); // releases both the tail and size trimFinal(); done = true; } /** * Replace a non-empty head node with an empty one to * allow the GC of the inaccessible old value. */ @Override public void trimHead() { TimedNode<Object> h = head; if (h.value != null) { TimedNode<Object> n = new TimedNode<>(null, 0); n.lazySet(h.get()); head = n; } } @Override @Nullable @SuppressWarnings("unchecked") public T getValue() { TimedNode<Object> prev = null; TimedNode<Object> h = head; for (;;) { TimedNode<Object> next = h.get(); if (next == null) { break; } prev = h; h = next; } long limit = scheduler.now(unit) - maxAge; if (h.time < limit) { return null; } Object v = h.value; if (v == null) { return null; } if (NotificationLite.isComplete(v) || NotificationLite.isError(v)) { return (T)prev.value; } return (T)v; } TimedNode<Object> getHead() { TimedNode<Object> index = head; // skip old entries long limit = scheduler.now(unit) - maxAge; TimedNode<Object> next = index.get(); while (next != null) { long ts = next.time; if (ts > limit) { break; } index = next; next = index.get(); } return index; } @Override @SuppressWarnings("unchecked") public T[] getValues(T[] array) { TimedNode<Object> h = getHead(); int s = size(h); if (s == 0) { if (array.length != 0) { array[0] = null; } } else { if (array.length < s) { array = (T[])Array.newInstance(array.getClass().getComponentType(), s); } int i = 0; while (i != s) { TimedNode<Object> next = h.get(); array[i] = (T)next.value; i++; h = next; } if (array.length > s) { array[s] = null; } } return array; } @Override @SuppressWarnings("unchecked") public void replay(ReplayDisposable<T> rs) { if (rs.getAndIncrement() != 0) { return; } int missed = 1; final Observer<? super T> a = rs.downstream; TimedNode<Object> index = (TimedNode<Object>)rs.index; if (index == null) { index = getHead(); } for (;;) { for (;;) { if (rs.cancelled) { rs.index = null; return; } TimedNode<Object> n = index.get(); if (n == null) { break; } Object o = n.value; if (done) { if (n.get() == null) { if (NotificationLite.isComplete(o)) { a.onComplete(); } else { a.onError(NotificationLite.getError(o)); } rs.index = null; rs.cancelled = true; return; } } a.onNext((T)o); index = n; } rs.index = index; missed = rs.addAndGet(-missed); if (missed == 0) { break; } } } @Override public int size() { return size(getHead()); } int size(TimedNode<Object> h) { int s = 0; while (s != Integer.MAX_VALUE) { TimedNode<Object> next = h.get(); if (next == null) { Object o = h.value; if (NotificationLite.isComplete(o) || NotificationLite.isError(o)) { s--; } break; } s++; h = next; } return s; } } }
ReactiveX/RxJava
src/main/java/io/reactivex/rxjava3/subjects/ReplaySubject.java
44,906
package com.macro.mall.dto; import io.swagger.annotations.ApiModelProperty; import lombok.Getter; import lombok.Setter; /** * 订单发货参数 * Created by macro on 2018/10/12. */ @Getter @Setter public class OmsOrderDeliveryParam { @ApiModelProperty("订单id") private Long orderId; @ApiModelProperty("物流公司") private String deliveryCompany; @ApiModelProperty("物流单号") private String deliverySn; }
macrozheng/mall
mall-admin/src/main/java/com/macro/mall/dto/OmsOrderDeliveryParam.java
44,907
/* * Copyright (c) 2016-present, RxJava Contributors. * * 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 io.reactivex.rxjava3.processors; import java.lang.reflect.Array; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.*; import org.reactivestreams.*; import io.reactivex.rxjava3.annotations.*; import io.reactivex.rxjava3.core.Scheduler; import io.reactivex.rxjava3.internal.functions.ObjectHelper; import io.reactivex.rxjava3.internal.subscriptions.SubscriptionHelper; import io.reactivex.rxjava3.internal.util.*; import io.reactivex.rxjava3.plugins.RxJavaPlugins; /** * Replays events to Subscribers. * <p> * The {@code ReplayProcessor} supports the following item retention strategies: * <ul> * <li>{@link #create()} and {@link #create(int)}: retains and replays all events to current and * future {@code Subscriber}s. * <p> * <img width="640" height="269" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/ReplayProcessor.u.png" alt=""> * <p> * <img width="640" height="345" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/ReplayProcessor.ue.png" alt=""> * </li> * <li>{@link #createWithSize(int)}: retains at most the given number of items and replays only these * latest items to new {@code Subscriber}s. * <p> * <img width="640" height="332" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/ReplayProcessor.n.png" alt=""> * </li> * <li>{@link #createWithTime(long, TimeUnit, Scheduler)}: retains items no older than the specified time * and replays them to new {@code Subscriber}s (which could mean all items age out). * <p> * <img width="640" height="415" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/ReplayProcessor.t.png" alt=""> * </li> * <li>{@link #createWithTimeAndSize(long, TimeUnit, Scheduler, int)}: retains no more than the given number of items * which are also no older than the specified time and replays them to new {@code Subscriber}s (which could mean all items age out). * <p> * <img width="640" height="404" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/ReplayProcessor.nt.png" alt=""> * </li> * </ul> * <p> * The {@code ReplayProcessor} can be created in bounded and unbounded mode. It can be bounded by * size (maximum number of elements retained at most) and/or time (maximum age of elements replayed). * <p> * Since a {@code ReplayProcessor} is a Reactive Streams {@code Processor}, * {@code null}s are not allowed (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.13">Rule 2.13</a>) as * parameters to {@link #onNext(Object)} and {@link #onError(Throwable)}. Such calls will result in a * {@link NullPointerException} being thrown and the processor's state is not changed. * <p> * This {@code ReplayProcessor} respects the individual backpressure behavior of its {@code Subscriber}s but * does not coordinate their request amounts towards the upstream (because there might not be any) and * consumes the upstream in an unbounded manner (requesting {@link Long#MAX_VALUE}). * Note that {@code Subscriber}s receive a continuous sequence of values after they subscribed even * if an individual item gets delayed due to backpressure. * Due to concurrency requirements, a size-bounded {@code ReplayProcessor} may hold strong references to more source * emissions than specified. * <p> * When this {@code ReplayProcessor} is terminated via {@link #onError(Throwable)} or {@link #onComplete()}, * late {@link Subscriber}s will receive the retained/cached items first (if any) followed by the respective * terminal event. If the {@code ReplayProcessor} has a time-bound, the age of the retained/cached items are still considered * when replaying and thus it may result in no items being emitted before the terminal event. * <p> * Once an {@code Subscriber} has subscribed, it will receive items continuously from that point on. Bounds only affect how * many past items a new {@code Subscriber} will receive before it catches up with the live event feed. * <p> * Even though {@code ReplayProcessor} implements the {@code Subscriber} interface, calling * {@code onSubscribe} is not required (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.12">Rule 2.12</a>) * if the processor is used as a standalone source. However, calling {@code onSubscribe} * after the {@code ReplayProcessor} reached its terminal state will result in the * given {@code Subscription} being canceled immediately. * <p> * Calling {@link #onNext(Object)}, {@link #onError(Throwable)} and {@link #onComplete()} * is required to be serialized (called from the same thread or called non-overlappingly from different threads * through external means of serialization). The {@link #toSerialized()} method available to all {@code FlowableProcessor}s * provides such serialization and also protects against reentrance (i.e., when a downstream {@code Subscriber} * consuming this processor also wants to call {@link #onNext(Object)} on this processor recursively). * <p> * This {@code ReplayProcessor} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()}, * {@link #getThrowable()} and {@link #hasSubscribers()} as well as means to read the retained/cached items * in a non-blocking and thread-safe manner via {@link #hasValue()}, {@link #getValue()}, * {@link #getValues()} or {@link #getValues(Object[])}. * <p> * Note that due to concurrency requirements, a size- and time-bounded {@code ReplayProcessor} may hold strong references to more * source emissions than specified while it isn't terminated yet. Use the {@link #cleanupBuffer()} to allow * such inaccessible items to be cleaned up by GC once no consumer references them anymore. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>This {@code ReplayProcessor} respects the individual backpressure behavior of its {@code Subscriber}s but * does not coordinate their request amounts towards the upstream (because there might not be any) and * consumes the upstream in an unbounded manner (requesting {@link Long#MAX_VALUE}). * Note that {@code Subscriber}s receive a continuous sequence of values after they subscribed even * if an individual item gets delayed due to backpressure.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code ReplayProcessor} does not operate by default on a particular {@link io.reactivex.rxjava3.core.Scheduler} and * the {@code Subscriber}s get notified on the thread the respective {@code onXXX} methods were invoked. * Time-bound {@code ReplayProcessor}s use the given {@code Scheduler} in their {@code create} methods * as time source to timestamp of items received for the age checks.</dd> * <dt><b>Error handling:</b></dt> * <dd>When the {@link #onError(Throwable)} is called, the {@code ReplayProcessor} enters into a terminal state * and emits the same {@code Throwable} instance to the last set of {@code Subscriber}s. During this emission, * if one or more {@code Subscriber}s cancel their respective {@code Subscription}s, the * {@code Throwable} is delivered to the global error handler via * {@link io.reactivex.rxjava3.plugins.RxJavaPlugins#onError(Throwable)} (multiple times if multiple {@code Subscriber}s * cancel at once). * If there were no {@code Subscriber}s subscribed to this {@code ReplayProcessor} when the {@code onError()} * was called, the global error handler is not invoked. * </dd> * </dl> * <p> * Example usage: * <pre> {@code ReplayProcessor<Object> processor = new ReplayProcessor<T>(); processor.onNext("one"); processor.onNext("two"); processor.onNext("three"); processor.onComplete(); // both of the following will get the onNext/onComplete calls from above processor.subscribe(subscriber1); processor.subscribe(subscriber2); } </pre> * * @param <T> the value type */ public final class ReplayProcessor<@NonNull T> extends FlowableProcessor<T> { /** An empty array to avoid allocation in getValues(). */ private static final Object[] EMPTY_ARRAY = new Object[0]; final ReplayBuffer<T> buffer; boolean done; final AtomicReference<ReplaySubscription<T>[]> subscribers; @SuppressWarnings("rawtypes") static final ReplaySubscription[] EMPTY = new ReplaySubscription[0]; @SuppressWarnings("rawtypes") static final ReplaySubscription[] TERMINATED = new ReplaySubscription[0]; /** * Creates an unbounded ReplayProcessor. * <p> * The internal buffer is backed by an {@link ArrayList} and starts with an initial capacity of 16. Once the * number of items reaches this capacity, it will grow as necessary (usually by 50%). However, as the * number of items grows, this causes frequent array reallocation and copying, and may hurt performance * and latency. This can be avoided with the {@link #create(int)} overload which takes an initial capacity * parameter and can be tuned to reduce the array reallocation frequency as needed. * * @param <T> * the type of items observed and emitted by the ReplayProcessor * @return the created ReplayProcessor */ @CheckReturnValue @NonNull public static <T> ReplayProcessor<T> create() { return new ReplayProcessor<>(new UnboundedReplayBuffer<>(16)); } /** * Creates an unbounded ReplayProcessor with the specified initial buffer capacity. * <p> * Use this method to avoid excessive array reallocation while the internal buffer grows to accommodate new * items. For example, if you know that the buffer will hold 32k items, you can ask the * {@code ReplayProcessor} to preallocate its internal array with a capacity to hold that many items. Once * the items start to arrive, the internal array won't need to grow, creating less garbage and no overhead * due to frequent array-copying. * * @param <T> * the type of items observed and emitted by this type of processor * @param capacityHint * the initial buffer capacity * @return the created processor * @throws IllegalArgumentException if {@code capacityHint} is non-positive */ @CheckReturnValue @NonNull public static <T> ReplayProcessor<T> create(int capacityHint) { ObjectHelper.verifyPositive(capacityHint, "capacityHint"); return new ReplayProcessor<>(new UnboundedReplayBuffer<>(capacityHint)); } /** * Creates a size-bounded ReplayProcessor. * <p> * In this setting, the {@code ReplayProcessor} holds at most {@code size} items in its internal buffer and * discards the oldest item. * <p> * When {@code Subscriber}s subscribe to a terminated {@code ReplayProcessor}, they are guaranteed to see at most * {@code size} {@code onNext} events followed by a termination event. * <p> * If a {@code Subscriber} subscribes while the {@code ReplayProcessor} is active, it will observe all items in the * buffer at that point in time and each item observed afterwards, even if the buffer evicts items due to * the size constraint in the mean time. In other words, once a {@code Subscriber} subscribes, it will receive items * without gaps in the sequence. * * @param <T> * the type of items observed and emitted by this type of processor * @param maxSize * the maximum number of buffered items * @return the created processor * @throws IllegalArgumentException if {@code maxSize} is non-positive */ @CheckReturnValue @NonNull public static <T> ReplayProcessor<T> createWithSize(int maxSize) { ObjectHelper.verifyPositive(maxSize, "maxSize"); return new ReplayProcessor<>(new SizeBoundReplayBuffer<>(maxSize)); } /** * Creates an unbounded ReplayProcessor with the bounded-implementation for testing purposes. * <p> * This variant behaves like the regular unbounded {@code ReplayProcessor} created via {@link #create()} but * uses the structures of the bounded-implementation. This is by no means intended for the replacement of * the original, array-backed and unbounded {@code ReplayProcessor} due to the additional overhead of the * linked-list based internal buffer. The sole purpose is to allow testing and reasoning about the behavior * of the bounded implementations without the interference of the eviction policies. * * @param <T> * the type of items observed and emitted by this type of processor * @return the created processor */ @CheckReturnValue /* test */ static <T> ReplayProcessor<T> createUnbounded() { return new ReplayProcessor<>(new SizeBoundReplayBuffer<>(Integer.MAX_VALUE)); } /** * Creates a time-bounded ReplayProcessor. * <p> * In this setting, the {@code ReplayProcessor} internally tags each observed item with a timestamp value * supplied by the {@link Scheduler} and keeps only those whose age is less than the supplied time value * converted to milliseconds. For example, an item arrives at T=0 and the max age is set to 5; at T&gt;=5 * this first item is then evicted by any subsequent item or termination event, leaving the buffer empty. * <p> * Once the processor is terminated, {@code Subscriber}s subscribing to it will receive items that remained in the * buffer after the terminal event, regardless of their age. * <p> * If a {@code Subscriber} subscribes while the {@code ReplayProcessor} is active, it will observe only those items * from within the buffer that have an age less than the specified time, and each item observed thereafter, * even if the buffer evicts items due to the time constraint in the mean time. In other words, once a * {@code Subscriber} subscribes, it observes items without gaps in the sequence except for any outdated items at the * beginning of the sequence. * <p> * Note that terminal notifications ({@code onError} and {@code onComplete}) trigger eviction as well. For * example, with a max age of 5, the first item is observed at T=0, then an {@code onComplete} notification * arrives at T=10. If a {@code Subscriber} subscribes at T=11, it will find an empty {@code ReplayProcessor} with just * an {@code onComplete} notification. * * @param <T> * the type of items observed and emitted by this type of processor * @param maxAge * the maximum age of the contained items * @param unit * the time unit of {@code time} * @param scheduler * the {@link Scheduler} that provides the current time * @return the created processor * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null} * @throws IllegalArgumentException if {@code maxAge} is non-positive */ @CheckReturnValue @NonNull public static <T> ReplayProcessor<T> createWithTime(long maxAge, @NonNull TimeUnit unit, @NonNull Scheduler scheduler) { ObjectHelper.verifyPositive(maxAge, "maxAge"); Objects.requireNonNull(unit, "unit is null"); Objects.requireNonNull(scheduler, "scheduler is null"); return new ReplayProcessor<>(new SizeAndTimeBoundReplayBuffer<>(Integer.MAX_VALUE, maxAge, unit, scheduler)); } /** * Creates a time- and size-bounded ReplayProcessor. * <p> * In this setting, the {@code ReplayProcessor} internally tags each received item with a timestamp value * supplied by the {@link Scheduler} and holds at most {@code size} items in its internal buffer. It evicts * items from the start of the buffer if their age becomes less-than or equal to the supplied age in * milliseconds or the buffer reaches its {@code size} limit. * <p> * When {@code Subscriber}s subscribe to a terminated {@code ReplayProcessor}, they observe the items that remained in * the buffer after the terminal notification, regardless of their age, but at most {@code size} items. * <p> * If a {@code Subscriber} subscribes while the {@code ReplayProcessor} is active, it will observe only those items * from within the buffer that have age less than the specified time and each subsequent item, even if the * buffer evicts items due to the time constraint in the mean time. In other words, once a {@code Subscriber} * subscribes, it observes items without gaps in the sequence except for the outdated items at the beginning * of the sequence. * <p> * Note that terminal notifications ({@code onError} and {@code onComplete}) trigger eviction as well. For * example, with a max age of 5, the first item is observed at T=0, then an {@code onComplete} notification * arrives at T=10. If a {@code Subscriber} subscribes at T=11, it will find an empty {@code ReplayProcessor} with just * an {@code onComplete} notification. * * @param <T> * the type of items observed and emitted by this type of processor * @param maxAge * the maximum age of the contained items * @param unit * the time unit of {@code time} * @param maxSize * the maximum number of buffered items * @param scheduler * the {@link Scheduler} that provides the current time * @return the created processor * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null} * @throws IllegalArgumentException if {@code maxAge} or {@code maxSize} is non-positive */ @CheckReturnValue @NonNull public static <T> ReplayProcessor<T> createWithTimeAndSize(long maxAge, @NonNull TimeUnit unit, @NonNull Scheduler scheduler, int maxSize) { ObjectHelper.verifyPositive(maxSize, "maxSize"); ObjectHelper.verifyPositive(maxAge, "maxAge"); Objects.requireNonNull(unit, "unit is null"); Objects.requireNonNull(scheduler, "scheduler is null"); return new ReplayProcessor<>(new SizeAndTimeBoundReplayBuffer<>(maxSize, maxAge, unit, scheduler)); } /** * Constructs a ReplayProcessor with the given custom ReplayBuffer instance. * @param buffer the ReplayBuffer instance, not null (not verified) */ @SuppressWarnings("unchecked") ReplayProcessor(ReplayBuffer<T> buffer) { this.buffer = buffer; this.subscribers = new AtomicReference<>(EMPTY); } @Override protected void subscribeActual(Subscriber<? super T> s) { ReplaySubscription<T> rs = new ReplaySubscription<>(s, this); s.onSubscribe(rs); if (add(rs)) { if (rs.cancelled) { remove(rs); return; } } buffer.replay(rs); } @Override public void onSubscribe(Subscription s) { if (done) { s.cancel(); return; } s.request(Long.MAX_VALUE); } @Override public void onNext(T t) { ExceptionHelper.nullCheck(t, "onNext called with a null value."); if (done) { return; } ReplayBuffer<T> b = buffer; b.next(t); for (ReplaySubscription<T> rs : subscribers.get()) { b.replay(rs); } } @SuppressWarnings("unchecked") @Override public void onError(Throwable t) { ExceptionHelper.nullCheck(t, "onError called with a null Throwable."); if (done) { RxJavaPlugins.onError(t); return; } done = true; ReplayBuffer<T> b = buffer; b.error(t); for (ReplaySubscription<T> rs : subscribers.getAndSet(TERMINATED)) { b.replay(rs); } } @SuppressWarnings("unchecked") @Override public void onComplete() { if (done) { return; } done = true; ReplayBuffer<T> b = buffer; b.complete(); for (ReplaySubscription<T> rs : subscribers.getAndSet(TERMINATED)) { b.replay(rs); } } @Override @CheckReturnValue public boolean hasSubscribers() { return subscribers.get().length != 0; } @CheckReturnValue /* test */ int subscriberCount() { return subscribers.get().length; } @Override @Nullable @CheckReturnValue public Throwable getThrowable() { ReplayBuffer<T> b = buffer; if (b.isDone()) { return b.getError(); } return null; } /** * Makes sure the item cached by the head node in a bounded * ReplayProcessor is released (as it is never part of a replay). * <p> * By default, live bounded buffers will remember one item before * the currently receivable one to ensure subscribers can always * receive a continuous sequence of items. A terminated ReplayProcessor * automatically releases this inaccessible item. * <p> * The method must be called sequentially, similar to the standard * {@code onXXX} methods. * <p>History: 2.1.11 - experimental * @since 2.2 */ public void cleanupBuffer() { buffer.trimHead(); } /** * Returns the latest value this processor has or null if no such value exists. * <p>The method is thread-safe. * @return the latest value this processor currently has or null if no such value exists */ @CheckReturnValue public T getValue() { return buffer.getValue(); } /** * Returns an Object array containing snapshot all values of this processor. * <p>The method is thread-safe. * @return the array containing the snapshot of all values of this processor */ @CheckReturnValue public Object[] getValues() { @SuppressWarnings("unchecked") T[] a = (T[])EMPTY_ARRAY; T[] b = getValues(a); if (b == EMPTY_ARRAY) { return new Object[0]; } return b; } /** * Returns a typed array containing a snapshot of all values of this processor. * <p>The method follows the conventions of Collection.toArray by setting the array element * after the last value to null (if the capacity permits). * <p>The method is thread-safe. * @param array the target array to copy values into if it fits * @return the given array if the values fit into it or a new array containing all values */ @CheckReturnValue public T[] getValues(T[] array) { return buffer.getValues(array); } @Override @CheckReturnValue public boolean hasComplete() { ReplayBuffer<T> b = buffer; return b.isDone() && b.getError() == null; } @Override @CheckReturnValue public boolean hasThrowable() { ReplayBuffer<T> b = buffer; return b.isDone() && b.getError() != null; } /** * Returns true if this processor has any value. * <p>The method is thread-safe. * @return true if the processor has any value */ @CheckReturnValue public boolean hasValue() { return buffer.size() != 0; // NOPMD } @CheckReturnValue /* test*/ int size() { return buffer.size(); } boolean add(ReplaySubscription<T> rs) { for (;;) { ReplaySubscription<T>[] a = subscribers.get(); if (a == TERMINATED) { return false; } int len = a.length; @SuppressWarnings("unchecked") ReplaySubscription<T>[] b = new ReplaySubscription[len + 1]; System.arraycopy(a, 0, b, 0, len); b[len] = rs; if (subscribers.compareAndSet(a, b)) { return true; } } } @SuppressWarnings("unchecked") void remove(ReplaySubscription<T> rs) { for (;;) { ReplaySubscription<T>[] a = subscribers.get(); if (a == TERMINATED || a == EMPTY) { return; } int len = a.length; int j = -1; for (int i = 0; i < len; i++) { if (a[i] == rs) { j = i; break; } } if (j < 0) { return; } ReplaySubscription<T>[] b; if (len == 1) { b = EMPTY; } else { b = new ReplaySubscription[len - 1]; System.arraycopy(a, 0, b, 0, j); System.arraycopy(a, j + 1, b, j, len - j - 1); } if (subscribers.compareAndSet(a, b)) { return; } } } /** * Abstraction over a buffer that receives events and replays them to * individual Subscribers. * * @param <T> the value type */ interface ReplayBuffer<@NonNull T> { void next(T value); void error(Throwable ex); void complete(); void replay(ReplaySubscription<T> rs); int size(); @Nullable T getValue(); T[] getValues(T[] array); boolean isDone(); Throwable getError(); /** * Make sure an old inaccessible head value is released * in a bounded buffer. */ void trimHead(); } static final class ReplaySubscription<@NonNull T> extends AtomicInteger implements Subscription { private static final long serialVersionUID = 466549804534799122L; final Subscriber<? super T> downstream; final ReplayProcessor<T> state; Object index; final AtomicLong requested; volatile boolean cancelled; long emitted; ReplaySubscription(Subscriber<? super T> actual, ReplayProcessor<T> state) { this.downstream = actual; this.state = state; this.requested = new AtomicLong(); } @Override public void request(long n) { if (SubscriptionHelper.validate(n)) { BackpressureHelper.add(requested, n); state.buffer.replay(this); } } @Override public void cancel() { if (!cancelled) { cancelled = true; state.remove(this); } } } static final class UnboundedReplayBuffer<T> implements ReplayBuffer<T> { final List<T> buffer; Throwable error; volatile boolean done; volatile int size; UnboundedReplayBuffer(int capacityHint) { this.buffer = new ArrayList<>(capacityHint); } @Override public void next(T value) { buffer.add(value); size++; } @Override public void error(Throwable ex) { error = ex; done = true; } @Override public void complete() { done = true; } @Override public void trimHead() { // not applicable for an unbounded buffer } @Override @Nullable public T getValue() { int s = size; if (s == 0) { return null; } return buffer.get(s - 1); } @Override @SuppressWarnings("unchecked") public T[] getValues(T[] array) { int s = size; if (s == 0) { if (array.length != 0) { array[0] = null; } return array; } List<T> b = buffer; if (array.length < s) { array = (T[])Array.newInstance(array.getClass().getComponentType(), s); } for (int i = 0; i < s; i++) { array[i] = b.get(i); } if (array.length > s) { array[s] = null; } return array; } @Override public void replay(ReplaySubscription<T> rs) { if (rs.getAndIncrement() != 0) { return; } int missed = 1; final List<T> b = buffer; final Subscriber<? super T> a = rs.downstream; Integer indexObject = (Integer)rs.index; int index; if (indexObject != null) { index = indexObject; } else { index = 0; rs.index = 0; } long e = rs.emitted; for (;;) { long r = rs.requested.get(); while (e != r) { if (rs.cancelled) { rs.index = null; return; } boolean d = done; int s = size; if (d && index == s) { rs.index = null; rs.cancelled = true; Throwable ex = error; if (ex == null) { a.onComplete(); } else { a.onError(ex); } return; } if (index == s) { break; } a.onNext(b.get(index)); index++; e++; } if (e == r) { if (rs.cancelled) { rs.index = null; return; } boolean d = done; int s = size; if (d && index == s) { rs.index = null; rs.cancelled = true; Throwable ex = error; if (ex == null) { a.onComplete(); } else { a.onError(ex); } return; } } rs.index = index; rs.emitted = e; missed = rs.addAndGet(-missed); if (missed == 0) { break; } } } @Override public int size() { return size; } @Override public boolean isDone() { return done; } @Override public Throwable getError() { return error; } } static final class Node<T> extends AtomicReference<Node<T>> { private static final long serialVersionUID = 6404226426336033100L; final T value; Node(T value) { this.value = value; } } static final class TimedNode<T> extends AtomicReference<TimedNode<T>> { private static final long serialVersionUID = 6404226426336033100L; final T value; final long time; TimedNode(T value, long time) { this.value = value; this.time = time; } } static final class SizeBoundReplayBuffer<@NonNull T> implements ReplayBuffer<T> { final int maxSize; int size; volatile Node<T> head; Node<T> tail; Throwable error; volatile boolean done; SizeBoundReplayBuffer(int maxSize) { this.maxSize = maxSize; Node<T> h = new Node<>(null); this.tail = h; this.head = h; } void trim() { if (size > maxSize) { size--; Node<T> h = head; head = h.get(); } } @Override public void next(T value) { Node<T> n = new Node<>(value); Node<T> t = tail; tail = n; size++; t.set(n); // releases both the tail and size trim(); } @Override public void error(Throwable ex) { error = ex; trimHead(); done = true; } @Override public void complete() { trimHead(); done = true; } @Override public void trimHead() { if (head.value != null) { Node<T> n = new Node<>(null); n.lazySet(head.get()); head = n; } } @Override public boolean isDone() { return done; } @Override public Throwable getError() { return error; } @Override public T getValue() { Node<T> h = head; for (;;) { Node<T> n = h.get(); if (n == null) { return h.value; } h = n; } } @Override @SuppressWarnings("unchecked") public T[] getValues(T[] array) { int s = 0; Node<T> h = head; Node<T> h0 = h; for (;;) { Node<T> next = h0.get(); if (next == null) { break; } s++; h0 = next; } if (array.length < s) { array = (T[])Array.newInstance(array.getClass().getComponentType(), s); } for (int j = 0; j < s; j++) { h = h.get(); array[j] = h.value; } if (array.length > s) { array[s] = null; } return array; } @Override @SuppressWarnings("unchecked") public void replay(ReplaySubscription<T> rs) { if (rs.getAndIncrement() != 0) { return; } int missed = 1; final Subscriber<? super T> a = rs.downstream; Node<T> index = (Node<T>)rs.index; if (index == null) { index = head; } long e = rs.emitted; for (;;) { long r = rs.requested.get(); while (e != r) { if (rs.cancelled) { rs.index = null; return; } boolean d = done; Node<T> next = index.get(); boolean empty = next == null; if (d && empty) { rs.index = null; rs.cancelled = true; Throwable ex = error; if (ex == null) { a.onComplete(); } else { a.onError(ex); } return; } if (empty) { break; } a.onNext(next.value); e++; index = next; } if (e == r) { if (rs.cancelled) { rs.index = null; return; } boolean d = done; if (d && index.get() == null) { rs.index = null; rs.cancelled = true; Throwable ex = error; if (ex == null) { a.onComplete(); } else { a.onError(ex); } return; } } rs.index = index; rs.emitted = e; missed = rs.addAndGet(-missed); if (missed == 0) { break; } } } @Override public int size() { int s = 0; Node<T> h = head; while (s != Integer.MAX_VALUE) { Node<T> next = h.get(); if (next == null) { break; } s++; h = next; } return s; } } static final class SizeAndTimeBoundReplayBuffer<T> implements ReplayBuffer<T> { final int maxSize; final long maxAge; final TimeUnit unit; final Scheduler scheduler; int size; volatile TimedNode<T> head; TimedNode<T> tail; Throwable error; volatile boolean done; SizeAndTimeBoundReplayBuffer(int maxSize, long maxAge, TimeUnit unit, Scheduler scheduler) { this.maxSize = maxSize; this.maxAge = maxAge; this.unit = unit; this.scheduler = scheduler; TimedNode<T> h = new TimedNode<>(null, 0L); this.tail = h; this.head = h; } void trim() { if (size > maxSize) { size--; TimedNode<T> h = head; head = h.get(); } long limit = scheduler.now(unit) - maxAge; TimedNode<T> h = head; for (;;) { if (size <= 1) { head = h; break; } TimedNode<T> next = h.get(); if (next.time > limit) { head = h; break; } h = next; size--; } } void trimFinal() { long limit = scheduler.now(unit) - maxAge; TimedNode<T> h = head; for (;;) { TimedNode<T> next = h.get(); if (next == null) { if (h.value != null) { head = new TimedNode<>(null, 0L); } else { head = h; } break; } if (next.time > limit) { if (h.value != null) { TimedNode<T> n = new TimedNode<>(null, 0L); n.lazySet(h.get()); head = n; } else { head = h; } break; } h = next; } } @Override public void trimHead() { if (head.value != null) { TimedNode<T> n = new TimedNode<>(null, 0L); n.lazySet(head.get()); head = n; } } @Override public void next(T value) { TimedNode<T> n = new TimedNode<>(value, scheduler.now(unit)); TimedNode<T> t = tail; tail = n; size++; t.set(n); // releases both the tail and size trim(); } @Override public void error(Throwable ex) { trimFinal(); error = ex; done = true; } @Override public void complete() { trimFinal(); done = true; } @Override @Nullable public T getValue() { TimedNode<T> h = head; for (;;) { TimedNode<T> next = h.get(); if (next == null) { break; } h = next; } long limit = scheduler.now(unit) - maxAge; if (h.time < limit) { return null; } return h.value; } @Override @SuppressWarnings("unchecked") public T[] getValues(T[] array) { TimedNode<T> h = getHead(); int s = size(h); if (s == 0) { if (array.length != 0) { array[0] = null; } } else { if (array.length < s) { array = (T[])Array.newInstance(array.getClass().getComponentType(), s); } int i = 0; while (i != s) { TimedNode<T> next = h.get(); array[i] = next.value; i++; h = next; } if (array.length > s) { array[s] = null; } } return array; } TimedNode<T> getHead() { TimedNode<T> index = head; // skip old entries long limit = scheduler.now(unit) - maxAge; TimedNode<T> next = index.get(); while (next != null) { long ts = next.time; if (ts > limit) { break; } index = next; next = index.get(); } return index; } @Override @SuppressWarnings("unchecked") public void replay(ReplaySubscription<T> rs) { if (rs.getAndIncrement() != 0) { return; } int missed = 1; final Subscriber<? super T> a = rs.downstream; TimedNode<T> index = (TimedNode<T>)rs.index; if (index == null) { index = getHead(); } long e = rs.emitted; for (;;) { long r = rs.requested.get(); while (e != r) { if (rs.cancelled) { rs.index = null; return; } boolean d = done; TimedNode<T> next = index.get(); boolean empty = next == null; if (d && empty) { rs.index = null; rs.cancelled = true; Throwable ex = error; if (ex == null) { a.onComplete(); } else { a.onError(ex); } return; } if (empty) { break; } a.onNext(next.value); e++; index = next; } if (e == r) { if (rs.cancelled) { rs.index = null; return; } boolean d = done; if (d && index.get() == null) { rs.index = null; rs.cancelled = true; Throwable ex = error; if (ex == null) { a.onComplete(); } else { a.onError(ex); } return; } } rs.index = index; rs.emitted = e; missed = rs.addAndGet(-missed); if (missed == 0) { break; } } } @Override public int size() { return size(getHead()); } int size(TimedNode<T> h) { int s = 0; while (s != Integer.MAX_VALUE) { TimedNode<T> next = h.get(); if (next == null) { break; } s++; h = next; } return s; } @Override public Throwable getError() { return error; } @Override public boolean isDone() { return done; } } }
ReactiveX/RxJava
src/main/java/io/reactivex/rxjava3/processors/ReplayProcessor.java
44,908
class Solution { public int maxAliveYear(int[] birth, int[] death) { int base = 1900; int[] d = new int[102]; for (int i = 0; i < birth.length; ++i) { int a = birth[i] - base; int b = death[i] - base; ++d[a]; --d[b + 1]; } int s = 0, mx = 0; int ans = 0; for (int i = 0; i < d.length; ++i) { s += d[i]; if (mx < s) { mx = s; ans = base + i; } } return ans; } }
doocs/leetcode
lcci/16.10.Living People/Solution.java
44,909
/* * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ package org.webrtc.audio; import android.annotation.TargetApi; import android.content.Context; import android.media.AudioDeviceInfo; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioRecord; import android.media.AudioRecordingConfiguration; import android.media.AudioTimestamp; import android.media.MediaRecorder.AudioSource; import android.os.Build; import android.os.Process; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import com.google.android.exoplayer2.util.Log; import java.lang.System; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import org.webrtc.CalledByNative; import org.webrtc.Logging; import org.webrtc.ThreadUtils; import org.webrtc.audio.JavaAudioDeviceModule.AudioRecordErrorCallback; import org.webrtc.audio.JavaAudioDeviceModule.AudioRecordStartErrorCode; import org.webrtc.audio.JavaAudioDeviceModule.AudioRecordStateCallback; import org.webrtc.audio.JavaAudioDeviceModule.SamplesReadyCallback; class WebRtcAudioRecord { private static final String TAG = "WebRtcAudioRecordExternal"; // Requested size of each recorded buffer provided to the client. private static final int CALLBACK_BUFFER_SIZE_MS = 10; // Average number of callbacks per second. private static final int BUFFERS_PER_SECOND = 1000 / CALLBACK_BUFFER_SIZE_MS; // We ask for a native buffer size of BUFFER_SIZE_FACTOR * (minimum required // buffer size). The extra space is allocated to guard against glitches under // high load. private static final int BUFFER_SIZE_FACTOR = 2; // The AudioRecordJavaThread is allowed to wait for successful call to join() // but the wait times out afther this amount of time. private static final long AUDIO_RECORD_THREAD_JOIN_TIMEOUT_MS = 2000; public static final int DEFAULT_AUDIO_SOURCE = AudioSource.VOICE_COMMUNICATION; // Default audio data format is PCM 16 bit per sample. // Guaranteed to be supported by all devices. public static final int DEFAULT_AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT; // Indicates AudioRecord has started recording audio. private static final int AUDIO_RECORD_START = 0; // Indicates AudioRecord has stopped recording audio. private static final int AUDIO_RECORD_STOP = 1; // Time to wait before checking recording status after start has been called. Tests have // shown that the result can sometimes be invalid (our own status might be missing) if we check // directly after start. private static final int CHECK_REC_STATUS_DELAY_MS = 100; private final Context context; private final AudioManager audioManager; private final int audioSource; private final int audioFormat; private long nativeAudioRecord; private final WebRtcAudioEffects effects = new WebRtcAudioEffects(); private @Nullable ByteBuffer byteBuffer; private @Nullable AudioRecord audioRecord; private @Nullable AudioRecordThread audioThread; private @Nullable AudioDeviceInfo preferredDevice; private final ScheduledExecutorService executor; private @Nullable ScheduledFuture<String> future; private volatile boolean microphoneMute; private final AtomicReference<Boolean> audioSourceMatchesRecordingSessionRef = new AtomicReference<>(); private byte[] emptyBytes; private final @Nullable AudioRecordErrorCallback errorCallback; private final @Nullable AudioRecordStateCallback stateCallback; private final @Nullable SamplesReadyCallback audioSamplesReadyCallback; private final boolean isAcousticEchoCancelerSupported; private final boolean isNoiseSuppressorSupported; /** * Audio thread which keeps calling ByteBuffer.read() waiting for audio * to be recorded. Feeds recorded data to the native counterpart as a * periodic sequence of callbacks using DataIsRecorded(). * This thread uses a Process.THREAD_PRIORITY_URGENT_AUDIO priority. */ private class AudioRecordThread extends Thread { private volatile boolean keepAlive = true; public AudioRecordThread(String name) { super(name); } @Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_URGENT_AUDIO); Logging.d(TAG, "AudioRecordThread" + WebRtcAudioUtils.getThreadInfo()); assertTrue(audioRecord.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING); // Audio recording has started and the client is informed about it. doAudioRecordStateCallback(AUDIO_RECORD_START); long lastTime = System.nanoTime(); while (keepAlive) { int bytesRead = audioRecord.read(byteBuffer, byteBuffer.capacity()); if (bytesRead == byteBuffer.capacity()) { if (microphoneMute) { byteBuffer.clear(); byteBuffer.put(emptyBytes); } // It's possible we've been shut down during the read, and stopRecording() tried and // failed to join this thread. To be a bit safer, try to avoid calling any native methods // in case they've been unregistered after stopRecording() returned. if (keepAlive) { nativeDataIsRecorded(nativeAudioRecord, bytesRead); } if (audioSamplesReadyCallback != null) { // Copy the entire byte buffer array. The start of the byteBuffer is not necessarily // at index 0. byte[] data = Arrays.copyOfRange(byteBuffer.array(), byteBuffer.arrayOffset(), byteBuffer.capacity() + byteBuffer.arrayOffset()); audioSamplesReadyCallback.onWebRtcAudioRecordSamplesReady( new JavaAudioDeviceModule.AudioSamples(audioRecord.getAudioFormat(), audioRecord.getChannelCount(), audioRecord.getSampleRate(), data)); } } else { String errorMessage = "AudioRecord.read failed: " + bytesRead; Logging.e(TAG, errorMessage); if (bytesRead == AudioRecord.ERROR_INVALID_OPERATION) { keepAlive = false; reportWebRtcAudioRecordError(errorMessage); } } } try { if (audioRecord != null) { audioRecord.stop(); doAudioRecordStateCallback(AUDIO_RECORD_STOP); } } catch (IllegalStateException e) { Logging.e(TAG, "AudioRecord.stop failed: " + e.getMessage()); } } // Stops the inner thread loop and also calls AudioRecord.stop(). // Does not block the calling thread. public void stopThread() { Logging.d(TAG, "stopThread"); keepAlive = false; } } @CalledByNative WebRtcAudioRecord(Context context, AudioManager audioManager) { this(context, newDefaultScheduler() /* scheduler */, audioManager, DEFAULT_AUDIO_SOURCE, DEFAULT_AUDIO_FORMAT, null /* errorCallback */, null /* stateCallback */, null /* audioSamplesReadyCallback */, WebRtcAudioEffects.isAcousticEchoCancelerSupported(), WebRtcAudioEffects.isNoiseSuppressorSupported()); } public WebRtcAudioRecord(Context context, ScheduledExecutorService scheduler, AudioManager audioManager, int audioSource, int audioFormat, @Nullable AudioRecordErrorCallback errorCallback, @Nullable AudioRecordStateCallback stateCallback, @Nullable SamplesReadyCallback audioSamplesReadyCallback, boolean isAcousticEchoCancelerSupported, boolean isNoiseSuppressorSupported) { if (isAcousticEchoCancelerSupported && !WebRtcAudioEffects.isAcousticEchoCancelerSupported()) { throw new IllegalArgumentException("HW AEC not supported"); } if (isNoiseSuppressorSupported && !WebRtcAudioEffects.isNoiseSuppressorSupported()) { throw new IllegalArgumentException("HW NS not supported"); } this.context = context; this.executor = scheduler; this.audioManager = audioManager; this.audioSource = audioSource; this.audioFormat = audioFormat; this.errorCallback = errorCallback; this.stateCallback = stateCallback; this.audioSamplesReadyCallback = audioSamplesReadyCallback; this.isAcousticEchoCancelerSupported = isAcousticEchoCancelerSupported; this.isNoiseSuppressorSupported = isNoiseSuppressorSupported; Logging.d(TAG, "ctor" + WebRtcAudioUtils.getThreadInfo()); } @CalledByNative public void setNativeAudioRecord(long nativeAudioRecord) { this.nativeAudioRecord = nativeAudioRecord; } @CalledByNative boolean isAcousticEchoCancelerSupported() { return isAcousticEchoCancelerSupported; } @CalledByNative boolean isNoiseSuppressorSupported() { return isNoiseSuppressorSupported; } // Returns true if a valid call to verifyAudioConfig() has been done. Should always be // checked before using the returned value of isAudioSourceMatchingRecordingSession(). @CalledByNative boolean isAudioConfigVerified() { return audioSourceMatchesRecordingSessionRef.get() != null; } // Returns true if verifyAudioConfig() succeeds. This value is set after a specific delay when // startRecording() has been called. Hence, should preferably be called in combination with // stopRecording() to ensure that it has been set properly. |isAudioConfigVerified| is // enabled in WebRtcAudioRecord to ensure that the returned value is valid. @CalledByNative boolean isAudioSourceMatchingRecordingSession() { Boolean audioSourceMatchesRecordingSession = audioSourceMatchesRecordingSessionRef.get(); if (audioSourceMatchesRecordingSession == null) { Logging.w(TAG, "Audio configuration has not yet been verified"); return false; } return audioSourceMatchesRecordingSession; } @CalledByNative private boolean enableBuiltInAEC(boolean enable) { Logging.d(TAG, "enableBuiltInAEC(" + enable + ")"); return effects.setAEC(enable); } @CalledByNative private boolean enableBuiltInNS(boolean enable) { Logging.d(TAG, "enableBuiltInNS(" + enable + ")"); return effects.setNS(enable); } @CalledByNative private int initRecording(int sampleRate, int channels) { Logging.d(TAG, "initRecording(sampleRate=" + sampleRate + ", channels=" + channels + ")"); if (audioRecord != null) { reportWebRtcAudioRecordInitError("InitRecording called twice without StopRecording."); return -1; } final int bytesPerFrame = channels * getBytesPerSample(audioFormat); final int framesPerBuffer = sampleRate / BUFFERS_PER_SECOND; byteBuffer = ByteBuffer.allocateDirect(bytesPerFrame * framesPerBuffer); if (!(byteBuffer.hasArray())) { reportWebRtcAudioRecordInitError("ByteBuffer does not have backing array."); return -1; } Logging.d(TAG, "byteBuffer.capacity: " + byteBuffer.capacity()); emptyBytes = new byte[byteBuffer.capacity()]; // Rather than passing the ByteBuffer with every callback (requiring // the potentially expensive GetDirectBufferAddress) we simply have the // the native class cache the address to the memory once. nativeCacheDirectBufferAddress(nativeAudioRecord, byteBuffer); // Get the minimum buffer size required for the successful creation of // an AudioRecord object, in byte units. // Note that this size doesn't guarantee a smooth recording under load. final int channelConfig = channelCountToConfiguration(channels); int minBufferSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat); if (minBufferSize == AudioRecord.ERROR || minBufferSize == AudioRecord.ERROR_BAD_VALUE) { reportWebRtcAudioRecordInitError("AudioRecord.getMinBufferSize failed: " + minBufferSize); return -1; } Logging.d(TAG, "AudioRecord.getMinBufferSize: " + minBufferSize); // Use a larger buffer size than the minimum required when creating the // AudioRecord instance to ensure smooth recording under load. It has been // verified that it does not increase the actual recording latency. int bufferSizeInBytes = Math.max(BUFFER_SIZE_FACTOR * minBufferSize, byteBuffer.capacity()); Logging.d(TAG, "bufferSizeInBytes: " + bufferSizeInBytes); try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // Use the AudioRecord.Builder class on Android M (23) and above. // Throws IllegalArgumentException. audioRecord = createAudioRecordOnMOrHigher( audioSource, sampleRate, channelConfig, audioFormat, bufferSizeInBytes); audioSourceMatchesRecordingSessionRef.set(null); if (preferredDevice != null) { setPreferredDevice(preferredDevice); } } else { // Use the old AudioRecord constructor for API levels below 23. // Throws UnsupportedOperationException. audioRecord = createAudioRecordOnLowerThanM( audioSource, sampleRate, channelConfig, audioFormat, bufferSizeInBytes); audioSourceMatchesRecordingSessionRef.set(null); } } catch (IllegalArgumentException | UnsupportedOperationException e) { // Report of exception message is sufficient. Example: "Cannot create AudioRecord". reportWebRtcAudioRecordInitError(e.getMessage()); releaseAudioResources(); return -1; } if (audioRecord == null || audioRecord.getState() != AudioRecord.STATE_INITIALIZED) { reportWebRtcAudioRecordInitError("Creation or initialization of audio recorder failed."); releaseAudioResources(); return -1; } effects.enable(audioRecord.getAudioSessionId()); logMainParameters(); logMainParametersExtended(); // Check number of active recording sessions. Should be zero but we have seen conflict cases // and adding a log for it can help us figure out details about conflicting sessions. final int numActiveRecordingSessions = logRecordingConfigurations(audioRecord, false /* verifyAudioConfig */); if (numActiveRecordingSessions != 0) { // Log the conflict as a warning since initialization did in fact succeed. Most likely, the // upcoming call to startRecording() will fail under these conditions. Logging.w( TAG, "Potential microphone conflict. Active sessions: " + numActiveRecordingSessions); } return framesPerBuffer; } /** * Prefer a specific {@link AudioDeviceInfo} device for recording. Calling after recording starts * is valid but may cause a temporary interruption if the audio routing changes. */ @RequiresApi(Build.VERSION_CODES.M) @TargetApi(Build.VERSION_CODES.M) void setPreferredDevice(@Nullable AudioDeviceInfo preferredDevice) { Logging.d( TAG, "setPreferredDevice " + (preferredDevice != null ? preferredDevice.getId() : null)); this.preferredDevice = preferredDevice; if (audioRecord != null) { if (!audioRecord.setPreferredDevice(preferredDevice)) { Logging.e(TAG, "setPreferredDevice failed"); } } } @CalledByNative private boolean startRecording() { Logging.d(TAG, "startRecording"); assertTrue(audioRecord != null); assertTrue(audioThread == null); try { audioRecord.startRecording(); } catch (IllegalStateException e) { reportWebRtcAudioRecordStartError(AudioRecordStartErrorCode.AUDIO_RECORD_START_EXCEPTION, "AudioRecord.startRecording failed: " + e.getMessage()); return false; } if (audioRecord.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING) { reportWebRtcAudioRecordStartError(AudioRecordStartErrorCode.AUDIO_RECORD_START_STATE_MISMATCH, "AudioRecord.startRecording failed - incorrect state: " + audioRecord.getRecordingState()); return false; } audioThread = new AudioRecordThread("AudioRecordJavaThread"); audioThread.start(); scheduleLogRecordingConfigurationsTask(audioRecord); return true; } @CalledByNative private boolean stopRecording() { Logging.d(TAG, "stopRecording"); assertTrue(audioThread != null); if (future != null) { if (!future.isDone()) { // Might be needed if the client calls startRecording(), stopRecording() back-to-back. future.cancel(true /* mayInterruptIfRunning */); } future = null; } audioThread.stopThread(); if (!ThreadUtils.joinUninterruptibly(audioThread, AUDIO_RECORD_THREAD_JOIN_TIMEOUT_MS)) { Logging.e(TAG, "Join of AudioRecordJavaThread timed out"); WebRtcAudioUtils.logAudioState(TAG, context, audioManager); } audioThread = null; effects.release(); releaseAudioResources(); return true; } @TargetApi(Build.VERSION_CODES.M) private static AudioRecord createAudioRecordOnMOrHigher( int audioSource, int sampleRate, int channelConfig, int audioFormat, int bufferSizeInBytes) { Logging.d(TAG, "createAudioRecordOnMOrHigher"); return new AudioRecord.Builder() .setAudioSource(audioSource) .setAudioFormat(new AudioFormat.Builder() .setEncoding(audioFormat) .setSampleRate(sampleRate) .setChannelMask(channelConfig) .build()) .setBufferSizeInBytes(bufferSizeInBytes) .build(); } private static AudioRecord createAudioRecordOnLowerThanM( int audioSource, int sampleRate, int channelConfig, int audioFormat, int bufferSizeInBytes) { Logging.d(TAG, "createAudioRecordOnLowerThanM"); return new AudioRecord(audioSource, sampleRate, channelConfig, audioFormat, bufferSizeInBytes); } private void logMainParameters() { Logging.d(TAG, "AudioRecord: " + "session ID: " + audioRecord.getAudioSessionId() + ", " + "channels: " + audioRecord.getChannelCount() + ", " + "sample rate: " + audioRecord.getSampleRate()); } @TargetApi(Build.VERSION_CODES.M) private void logMainParametersExtended() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { Logging.d(TAG, "AudioRecord: " // The frame count of the native AudioRecord buffer. + "buffer size in frames: " + audioRecord.getBufferSizeInFrames()); } } @TargetApi(Build.VERSION_CODES.N) // Checks the number of active recording sessions and logs the states of all active sessions. // Returns number of active sessions. Note that this could occur on arbituary thread. private int logRecordingConfigurations(AudioRecord audioRecord, boolean verifyAudioConfig) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { Logging.w(TAG, "AudioManager#getActiveRecordingConfigurations() requires N or higher"); return 0; } if (audioRecord == null) { return 0; } // Get a list of the currently active audio recording configurations of the device (can be more // than one). An empty list indicates there is no recording active when queried. List<AudioRecordingConfiguration> configs = audioManager.getActiveRecordingConfigurations(); final int numActiveRecordingSessions = configs.size(); Logging.d(TAG, "Number of active recording sessions: " + numActiveRecordingSessions); if (numActiveRecordingSessions > 0) { logActiveRecordingConfigs(audioRecord.getAudioSessionId(), configs); if (verifyAudioConfig) { // Run an extra check to verify that the existing audio source doing the recording (tied // to the AudioRecord instance) is matching what the audio recording configuration lists // as its client parameters. If these do not match, recording might work but under invalid // conditions. audioSourceMatchesRecordingSessionRef.set( verifyAudioConfig(audioRecord.getAudioSource(), audioRecord.getAudioSessionId(), audioRecord.getFormat(), audioRecord.getRoutedDevice(), configs)); } } return numActiveRecordingSessions; } // Helper method which throws an exception when an assertion has failed. private static void assertTrue(boolean condition) { if (!condition) { throw new AssertionError("Expected condition to be true"); } } private int channelCountToConfiguration(int channels) { return (channels == 1 ? AudioFormat.CHANNEL_IN_MONO : AudioFormat.CHANNEL_IN_STEREO); } private native void nativeCacheDirectBufferAddress( long nativeAudioRecordJni, ByteBuffer byteBuffer); private native void nativeDataIsRecorded(long nativeAudioRecordJni, int bytes); // Sets all recorded samples to zero if |mute| is true, i.e., ensures that // the microphone is muted. public void setMicrophoneMute(boolean mute) { Logging.w(TAG, "setMicrophoneMute(" + mute + ")"); microphoneMute = mute; } // Releases the native AudioRecord resources. private void releaseAudioResources() { Logging.d(TAG, "releaseAudioResources"); if (audioRecord != null) { audioRecord.release(); audioRecord = null; } audioSourceMatchesRecordingSessionRef.set(null); } private void reportWebRtcAudioRecordInitError(String errorMessage) { Logging.e(TAG, "Init recording error: " + errorMessage); WebRtcAudioUtils.logAudioState(TAG, context, audioManager); logRecordingConfigurations(audioRecord, false /* verifyAudioConfig */); if (errorCallback != null) { errorCallback.onWebRtcAudioRecordInitError(errorMessage); } } private void reportWebRtcAudioRecordStartError( AudioRecordStartErrorCode errorCode, String errorMessage) { Logging.e(TAG, "Start recording error: " + errorCode + ". " + errorMessage); WebRtcAudioUtils.logAudioState(TAG, context, audioManager); logRecordingConfigurations(audioRecord, false /* verifyAudioConfig */); if (errorCallback != null) { errorCallback.onWebRtcAudioRecordStartError(errorCode, errorMessage); } } private void reportWebRtcAudioRecordError(String errorMessage) { Logging.e(TAG, "Run-time recording error: " + errorMessage); WebRtcAudioUtils.logAudioState(TAG, context, audioManager); if (errorCallback != null) { errorCallback.onWebRtcAudioRecordError(errorMessage); } } private void doAudioRecordStateCallback(int audioState) { Logging.d(TAG, "doAudioRecordStateCallback: " + audioStateToString(audioState)); if (stateCallback != null) { if (audioState == WebRtcAudioRecord.AUDIO_RECORD_START) { stateCallback.onWebRtcAudioRecordStart(); } else if (audioState == WebRtcAudioRecord.AUDIO_RECORD_STOP) { stateCallback.onWebRtcAudioRecordStop(); } else { Logging.e(TAG, "Invalid audio state"); } } } // Reference from Android code, AudioFormat.getBytesPerSample. BitPerSample / 8 // Default audio data format is PCM 16 bits per sample. // Guaranteed to be supported by all devices private static int getBytesPerSample(int audioFormat) { switch (audioFormat) { case AudioFormat.ENCODING_PCM_8BIT: return 1; case AudioFormat.ENCODING_PCM_16BIT: case AudioFormat.ENCODING_IEC61937: case AudioFormat.ENCODING_DEFAULT: return 2; case AudioFormat.ENCODING_PCM_FLOAT: return 4; case AudioFormat.ENCODING_INVALID: default: throw new IllegalArgumentException("Bad audio format " + audioFormat); } } // Use an ExecutorService to schedule a task after a given delay where the task consists of // checking (by logging) the current status of active recording sessions. private void scheduleLogRecordingConfigurationsTask(AudioRecord audioRecord) { Logging.d(TAG, "scheduleLogRecordingConfigurationsTask"); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { return; } Callable<String> callable = () -> { if (this.audioRecord == audioRecord) { logRecordingConfigurations(audioRecord, true /* verifyAudioConfig */); } else { Logging.d(TAG, "audio record has changed"); } return "Scheduled task is done"; }; if (future != null && !future.isDone()) { future.cancel(true /* mayInterruptIfRunning */); } // Schedule call to logRecordingConfigurations() from executor thread after fixed delay. future = executor.schedule(callable, CHECK_REC_STATUS_DELAY_MS, TimeUnit.MILLISECONDS); }; @TargetApi(Build.VERSION_CODES.N) private static boolean logActiveRecordingConfigs( int session, List<AudioRecordingConfiguration> configs) { assertTrue(!configs.isEmpty()); final Iterator<AudioRecordingConfiguration> it = configs.iterator(); Logging.d(TAG, "AudioRecordingConfigurations: "); while (it.hasNext()) { final AudioRecordingConfiguration config = it.next(); StringBuilder conf = new StringBuilder(); // The audio source selected by the client. final int audioSource = config.getClientAudioSource(); conf.append(" client audio source=") .append(WebRtcAudioUtils.audioSourceToString(audioSource)) .append(", client session id=") .append(config.getClientAudioSessionId()) // Compare with our own id (based on AudioRecord#getAudioSessionId()). .append(" (") .append(session) .append(")") .append("\n"); // Audio format at which audio is recorded on this Android device. Note that it may differ // from the client application recording format (see getClientFormat()). AudioFormat format = config.getFormat(); conf.append(" Device AudioFormat: ") .append("channel count=") .append(format.getChannelCount()) .append(", channel index mask=") .append(format.getChannelIndexMask()) // Only AudioFormat#CHANNEL_IN_MONO is guaranteed to work on all devices. .append(", channel mask=") .append(WebRtcAudioUtils.channelMaskToString(format.getChannelMask())) .append(", encoding=") .append(WebRtcAudioUtils.audioEncodingToString(format.getEncoding())) .append(", sample rate=") .append(format.getSampleRate()) .append("\n"); // Audio format at which the client application is recording audio. format = config.getClientFormat(); conf.append(" Client AudioFormat: ") .append("channel count=") .append(format.getChannelCount()) .append(", channel index mask=") .append(format.getChannelIndexMask()) // Only AudioFormat#CHANNEL_IN_MONO is guaranteed to work on all devices. .append(", channel mask=") .append(WebRtcAudioUtils.channelMaskToString(format.getChannelMask())) .append(", encoding=") .append(WebRtcAudioUtils.audioEncodingToString(format.getEncoding())) .append(", sample rate=") .append(format.getSampleRate()) .append("\n"); // Audio input device used for this recording session. final AudioDeviceInfo device = config.getAudioDevice(); if (device != null) { assertTrue(device.isSource()); conf.append(" AudioDevice: ") .append("type=") .append(WebRtcAudioUtils.deviceTypeToString(device.getType())) .append(", id=") .append(device.getId()); } Logging.d(TAG, conf.toString()); } return true; } // Verify that the client audio configuration (device and format) matches the requested // configuration (same as AudioRecord's). @TargetApi(Build.VERSION_CODES.N) private static boolean verifyAudioConfig(int source, int session, AudioFormat format, AudioDeviceInfo device, List<AudioRecordingConfiguration> configs) { assertTrue(!configs.isEmpty()); final Iterator<AudioRecordingConfiguration> it = configs.iterator(); while (it.hasNext()) { final AudioRecordingConfiguration config = it.next(); final AudioDeviceInfo configDevice = config.getAudioDevice(); if (configDevice == null) { continue; } if ((config.getClientAudioSource() == source) && (config.getClientAudioSessionId() == session) // Check the client format (should match the format of the AudioRecord instance). && (config.getClientFormat().getEncoding() == format.getEncoding()) && (config.getClientFormat().getSampleRate() == format.getSampleRate()) && (config.getClientFormat().getChannelMask() == format.getChannelMask()) && (config.getClientFormat().getChannelIndexMask() == format.getChannelIndexMask()) // Ensure that the device format is properly configured. && (config.getFormat().getEncoding() != AudioFormat.ENCODING_INVALID) && (config.getFormat().getSampleRate() > 0) // For the channel mask, either the position or index-based value must be valid. && ((config.getFormat().getChannelMask() != AudioFormat.CHANNEL_INVALID) || (config.getFormat().getChannelIndexMask() != AudioFormat.CHANNEL_INVALID)) && checkDeviceMatch(configDevice, device)) { Logging.d(TAG, "verifyAudioConfig: PASS"); return true; } } Logging.e(TAG, "verifyAudioConfig: FAILED"); return false; } @TargetApi(Build.VERSION_CODES.N) // Returns true if device A parameters matches those of device B. // TODO(henrika): can be improved by adding AudioDeviceInfo#getAddress() but it requires API 29. private static boolean checkDeviceMatch(AudioDeviceInfo devA, AudioDeviceInfo devB) { return ((devA.getId() == devB.getId() && (devA.getType() == devB.getType()))); } private static String audioStateToString(int state) { switch (state) { case WebRtcAudioRecord.AUDIO_RECORD_START: return "START"; case WebRtcAudioRecord.AUDIO_RECORD_STOP: return "STOP"; default: return "INVALID"; } } private static final AtomicInteger nextSchedulerId = new AtomicInteger(0); static ScheduledExecutorService newDefaultScheduler() { AtomicInteger nextThreadId = new AtomicInteger(0); return Executors.newScheduledThreadPool(0, new ThreadFactory() { /** * Constructs a new {@code Thread} */ @Override public Thread newThread(Runnable r) { Thread thread = Executors.defaultThreadFactory().newThread(r); thread.setName(String.format("WebRtcAudioRecordScheduler-%s-%s", nextSchedulerId.getAndIncrement(), nextThreadId.getAndIncrement())); return thread; } }); } }
NekoX-Dev/NekoX
TMessagesProj/src/main/java/org/webrtc/audio/WebRtcAudioRecord.java
44,910
404: Not Found
apache/dubbo
dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe/LivenessProbe.java
44,912
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.uimanager; import android.view.View; import androidx.annotation.Nullable; import com.facebook.react.bridge.Dynamic; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; /** * This is an interface that should be implemented by view managers supporting the base view * properties such as backgroundColor, opacity, etc. */ public interface BaseViewManagerInterface<T extends View> { void setAccessibilityActions(T view, @Nullable ReadableArray accessibilityActions); void setAccessibilityHint(T view, @Nullable String accessibilityHint); void setAccessibilityLabel(T view, @Nullable String accessibilityLabel); void setAccessibilityLiveRegion(T view, @Nullable String liveRegion); void setAccessibilityRole(T view, @Nullable String accessibilityRole); void setAccessibilityCollection(T view, @Nullable ReadableMap accessibilityCollection); void setAccessibilityCollectionItem(T view, @Nullable ReadableMap accessibilityCollectionItem); void setViewState(T view, @Nullable ReadableMap accessibilityState); void setBackgroundColor(T view, int backgroundColor); void setBorderRadius(T view, float borderRadius); void setBorderBottomLeftRadius(T view, float borderRadius); void setBorderBottomRightRadius(T view, float borderRadius); void setBorderTopLeftRadius(T view, float borderRadius); void setBorderTopRightRadius(T view, float borderRadius); void setElevation(T view, float elevation); void setFilter(T view, ReadableArray filter); void setShadowColor(T view, int shadowColor); void setImportantForAccessibility(T view, @Nullable String importantForAccessibility); void setRole(T view, @Nullable String role); void setNativeId(T view, @Nullable String nativeId); void setAccessibilityLabelledBy(T view, @Nullable Dynamic nativeId); void setOpacity(T view, float opacity); void setRenderToHardwareTexture(T view, boolean useHWTexture); void setRotation(T view, float rotation); void setScaleX(T view, float scaleX); void setScaleY(T view, float scaleY); void setTestId(T view, String testId); void setTransform(T view, @Nullable ReadableArray matrix); void setTransformOrigin(T view, @Nullable ReadableArray transformOrigin); void setTranslateX(T view, float translateX); void setTranslateY(T view, float translateY); void setZIndex(T view, float zIndex); }
facebook/react-native
packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/BaseViewManagerInterface.java
44,913
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina; import java.beans.PropertyChangeListener; import java.io.IOException; /** * A <b>Manager</b> manages the pool of Sessions that are associated with a * particular Context. Different Manager implementations may support * value-added features such as the persistent storage of session data, * as well as migrating sessions for distributable web applications. * <p> * In order for a <code>Manager</code> implementation to successfully operate * with a <code>Context</code> implementation that implements reloading, it * must obey the following constraints: * <ul> * <li>Must implement <code>Lifecycle</code> so that the Context can indicate * that a restart is required. * <li>Must allow a call to <code>stop()</code> to be followed by a call to * <code>start()</code> on the same <code>Manager</code> instance. * </ul> * * @author Craig R. McClanahan */ public interface Manager { // ------------------------------------------------------------- Properties /** * Get the Context with which this Manager is associated. * * @return The associated Context */ Context getContext(); /** * Set the Context with which this Manager is associated. The Context must * be set to a non-null value before the Manager is first used. Multiple * calls to this method before first use are permitted. Once the Manager has * been used, this method may not be used to change the Context (including * setting a {@code null} value) that the Manager is associated with. * * @param context The newly associated Context */ void setContext(Context context); /** * @return the session id generator */ SessionIdGenerator getSessionIdGenerator(); /** * Sets the session id generator * * @param sessionIdGenerator The session id generator */ void setSessionIdGenerator(SessionIdGenerator sessionIdGenerator); /** * Returns the total number of sessions created by this manager, which is * approximated as the number of active sessions plus the number of * expired sessions. * * @return Total number of sessions created by this manager. */ long getSessionCounter(); /** * Gets the maximum number of sessions that have been active at the same * time. * * @return Maximum number of sessions that have been active at the same * time */ int getMaxActive(); /** * (Re)sets the maximum number of sessions that have been active at the * same time. * * @param maxActive Maximum number of sessions that have been active at * the same time. */ void setMaxActive(int maxActive); /** * Gets the number of currently active sessions. * * @return Number of currently active sessions */ int getActiveSessions(); /** * Gets the number of sessions that have expired. * * @return Number of sessions that have expired */ long getExpiredSessions(); /** * Sets the number of sessions that have expired. * * @param expiredSessions Number of sessions that have expired */ void setExpiredSessions(long expiredSessions); /** * Gets the number of sessions that were not created because the maximum * number of active sessions was reached. * * @return Number of rejected sessions */ int getRejectedSessions(); /** * Gets the longest time (in seconds) that an expired session had been * alive. * * @return Longest time (in seconds) that an expired session had been * alive. */ int getSessionMaxAliveTime(); /** * Sets the longest time (in seconds) that an expired session had been * alive. * * @param sessionMaxAliveTime Longest time (in seconds) that an expired * session had been alive. */ void setSessionMaxAliveTime(int sessionMaxAliveTime); /** * Gets the average time (in seconds) that expired sessions had been * alive. This may be based on sample data. * * @return Average time (in seconds) that expired sessions had been * alive. */ int getSessionAverageAliveTime(); /** * Gets the current rate of session creation (in session per minute). This * may be based on sample data. * * @return The current rate (in sessions per minute) of session creation */ int getSessionCreateRate(); /** * Gets the current rate of session expiration (in session per minute). This * may be based on sample data * * @return The current rate (in sessions per minute) of session expiration */ int getSessionExpireRate(); // --------------------------------------------------------- Public Methods /** * Add this Session to the set of active Sessions for this Manager. * * @param session Session to be added */ void add(Session session); /** * Add a property change listener to this component. * * @param listener The listener to add */ void addPropertyChangeListener(PropertyChangeListener listener); /** * Change the session ID of the current session to a new randomly generated * session ID. * * @param session The session to change the session ID for * * @return The new session ID */ default String rotateSessionId(Session session) { String newSessionId = getSessionIdGenerator().generateSessionId(); changeSessionId(session, newSessionId); return newSessionId; } /** * Change the session ID of the current session to a specified session ID. * * @param session The session to change the session ID for * @param newId new session ID */ void changeSessionId(Session session, String newId); /** * Get a session from the recycled ones or create a new empty one. * The PersistentManager manager does not need to create session data * because it reads it from the Store. * * @return An empty Session object */ Session createEmptySession(); /** * Construct and return a new session object, based on the default * settings specified by this Manager's properties. The session * id specified will be used as the session id. * If a new session cannot be created for any reason, return * <code>null</code>. * * @param sessionId The session id which should be used to create the * new session; if <code>null</code>, the session * id will be assigned by this method, and available via the getId() * method of the returned session. * @exception IllegalStateException if a new session cannot be * instantiated for any reason * * @return An empty Session object with the given ID or a newly created * session ID if none was specified */ Session createSession(String sessionId); /** * Return the active Session, associated with this Manager, with the * specified session id (if any); otherwise return <code>null</code>. * * @param id The session id for the session to be returned * * @exception IllegalStateException if a new session cannot be * instantiated for any reason * @exception IOException if an input/output error occurs while * processing this request * * @return the request session or {@code null} if a session with the * requested ID could not be found */ Session findSession(String id) throws IOException; /** * Return the set of active Sessions associated with this Manager. * If this Manager has no active Sessions, a zero-length array is returned. * * @return All the currently active sessions managed by this manager */ Session[] findSessions(); /** * Load any currently active sessions that were previously unloaded * to the appropriate persistence mechanism, if any. If persistence is not * supported, this method returns without doing anything. * * @exception ClassNotFoundException if a serialized class cannot be * found during the reload * @exception IOException if an input/output error occurs */ void load() throws ClassNotFoundException, IOException; /** * Remove this Session from the active Sessions for this Manager. * * @param session Session to be removed */ void remove(Session session); /** * Remove this Session from the active Sessions for this Manager. * * @param session Session to be removed * @param update Should the expiration statistics be updated */ void remove(Session session, boolean update); /** * Remove a property change listener from this component. * * @param listener The listener to remove */ void removePropertyChangeListener(PropertyChangeListener listener); /** * Save any currently active sessions in the appropriate persistence * mechanism, if any. If persistence is not supported, this method * returns without doing anything. * * @exception IOException if an input/output error occurs */ void unload() throws IOException; /** * This method will be invoked by the context/container on a periodic * basis and allows the manager to implement * a method that executes periodic tasks, such as expiring sessions etc. */ void backgroundProcess(); /** * Would the Manager distribute the given session attribute? Manager * implementations may provide additional configuration options to control * which attributes are distributable. * * @param name The attribute name * @param value The attribute value * * @return {@code true} if the Manager would distribute the given attribute * otherwise {@code false} */ boolean willAttributeDistribute(String name, Object value); /** * When an attribute that is already present in the session is added again * under the same name and the attribute implements {@link * jakarta.servlet.http.HttpSessionBindingListener}, should * {@link jakarta.servlet.http.HttpSessionBindingListener#valueUnbound(jakarta.servlet.http.HttpSessionBindingEvent)} * be called followed by * {@link jakarta.servlet.http.HttpSessionBindingListener#valueBound(jakarta.servlet.http.HttpSessionBindingEvent)}? * <p> * The default value is {@code false}. * * @return {@code true} if the listener will be notified, {@code false} if * it will not */ default boolean getNotifyBindingListenerOnUnchangedValue() { return false; } /** * Configure if * {@link jakarta.servlet.http.HttpSessionBindingListener#valueUnbound(jakarta.servlet.http.HttpSessionBindingEvent)} * be called followed by * {@link jakarta.servlet.http.HttpSessionBindingListener#valueBound(jakarta.servlet.http.HttpSessionBindingEvent)} * when an attribute that is already present in the session is added again * under the same name and the attribute implements {@link * jakarta.servlet.http.HttpSessionBindingListener}. * * @param notifyBindingListenerOnUnchangedValue {@code true} the listener * will be called, {@code * false} it will not */ void setNotifyBindingListenerOnUnchangedValue( boolean notifyBindingListenerOnUnchangedValue); /** * When an attribute that is already present in the session is added again * under the same name and a {@link * jakarta.servlet.http.HttpSessionAttributeListener} is configured for the * session should * {@link jakarta.servlet.http.HttpSessionAttributeListener#attributeReplaced(jakarta.servlet.http.HttpSessionBindingEvent)} * be called? * <p> * The default value is {@code true}. * * @return {@code true} if the listener will be notified, {@code false} if * it will not */ default boolean getNotifyAttributeListenerOnUnchangedValue() { return true; } /** * Configure if * {@link jakarta.servlet.http.HttpSessionAttributeListener#attributeReplaced(jakarta.servlet.http.HttpSessionBindingEvent)} * when an attribute that is already present in the session is added again * under the same name and a {@link * jakarta.servlet.http.HttpSessionAttributeListener} is configured for the * session. * * @param notifyAttributeListenerOnUnchangedValue {@code true} the listener * will be called, {@code * false} it will not */ void setNotifyAttributeListenerOnUnchangedValue( boolean notifyAttributeListenerOnUnchangedValue); /** * If this is <code>true</code>, Tomcat will track the number of active * requests for each session. When determining if a session is valid, any * session with at least one active request will always be considered valid. * If <code>org.apache.catalina.STRICT_SERVLET_COMPLIANCE</code> is set to * <code>true</code>, the default of this setting will be <code>true</code>, * else the default value will be <code>false</code>. * @return the flag value */ default boolean getSessionActivityCheck() { return Globals.STRICT_SERVLET_COMPLIANCE; } /** * Configure if Tomcat will track the number of active requests for each * session. When determining if a session is valid, any session with at * least one active request will always be considered valid. * @param sessionActivityCheck the new flag value */ void setSessionActivityCheck(boolean sessionActivityCheck); /** * If this is <code>true</code>, the last accessed time for sessions will * be calculated from the beginning of the previous request. If * <code>false</code>, the last accessed time for sessions will be calculated * from the end of the previous request. This also affects how the idle time * is calculated. * If <code>org.apache.catalina.STRICT_SERVLET_COMPLIANCE</code> is set to * <code>true</code>, the default of this setting will be <code>true</code>, * else the default value will be <code>false</code>. * @return the flag value */ default boolean getSessionLastAccessAtStart() { return Globals.STRICT_SERVLET_COMPLIANCE; } /** * Configure if the last accessed time for sessions will * be calculated from the beginning of the previous request. If * <code>false</code>, the last accessed time for sessions will be calculated * from the end of the previous request. This also affects how the idle time * is calculated. * @param sessionLastAccessAtStart the new flag value */ void setSessionLastAccessAtStart(boolean sessionLastAccessAtStart); }
apache/tomcat
java/org/apache/catalina/Manager.java
44,914
/* * Copyright (c) 2016-present, RxJava Contributors. * * 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 io.reactivex.rxjava3.subjects; import java.util.Objects; import java.util.concurrent.atomic.*; import io.reactivex.rxjava3.annotations.*; import io.reactivex.rxjava3.core.Observer; import io.reactivex.rxjava3.disposables.Disposable; import io.reactivex.rxjava3.internal.disposables.EmptyDisposable; import io.reactivex.rxjava3.internal.functions.*; import io.reactivex.rxjava3.internal.observers.BasicIntQueueDisposable; import io.reactivex.rxjava3.internal.util.ExceptionHelper; import io.reactivex.rxjava3.operators.SimpleQueue; import io.reactivex.rxjava3.operators.SpscLinkedArrayQueue; import io.reactivex.rxjava3.plugins.RxJavaPlugins; /** * A Subject that queues up events until a single {@link Observer} subscribes to it, replays * those events to it until the {@code Observer} catches up and then switches to relaying events live to * this single {@code Observer} until this {@code UnicastSubject} terminates or the {@code Observer} disposes. * <p> * <img width="640" height="370" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/UnicastSubject.png" alt=""> * <p> * Note that {@code UnicastSubject} holds an unbounded internal buffer. * <p> * This subject does not have a public constructor by design; a new empty instance of this * {@code UnicastSubject} can be created via the following {@code create} methods that * allow specifying the retention policy for items: * <ul> * <li>{@link #create()} - creates an empty, unbounded {@code UnicastSubject} that * caches all items and the terminal event it receives.</li> * <li>{@link #create(int)} - creates an empty, unbounded {@code UnicastSubject} * with a hint about how many <b>total</b> items one expects to retain.</li> * <li>{@link #create(boolean)} - creates an empty, unbounded {@code UnicastSubject} that * optionally delays an error it receives and replays it after the regular items have been emitted.</li> * <li>{@link #create(int, Runnable)} - creates an empty, unbounded {@code UnicastSubject} * with a hint about how many <b>total</b> items one expects to retain and a callback that will be * called exactly once when the {@code UnicastSubject} gets terminated or the single {@code Observer} disposes.</li> * <li>{@link #create(int, Runnable, boolean)} - creates an empty, unbounded {@code UnicastSubject} * with a hint about how many <b>total</b> items one expects to retain and a callback that will be * called exactly once when the {@code UnicastSubject} gets terminated or the single {@code Observer} disposes * and optionally delays an error it receives and replays it after the regular items have been emitted.</li> * </ul> * <p> * If more than one {@code Observer} attempts to subscribe to this {@code UnicastSubject}, they * will receive an {@code IllegalStateException} indicating the single-use-only nature of this {@code UnicastSubject}, * even if the {@code UnicastSubject} already terminated with an error. * <p> * Since a {@code Subject} is conceptionally derived from the {@code Processor} type in the Reactive Streams specification, * {@code null}s are not allowed (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.13">Rule 2.13</a>) as * parameters to {@link #onNext(Object)} and {@link #onError(Throwable)}. Such calls will result in a * {@link NullPointerException} being thrown and the subject's state is not changed. * <p> * Since a {@code UnicastSubject} is an {@link io.reactivex.rxjava3.core.Observable}, it does not support backpressure. * <p> * When this {@code UnicastSubject} is terminated via {@link #onError(Throwable)} the current or late single {@code Observer} * may receive the {@code Throwable} before any available items could be emitted. To make sure an onError event is delivered * to the {@code Observer} after the normal items, create a {@code UnicastSubject} with the {@link #create(boolean)} or * {@link #create(int, Runnable, boolean)} factory methods. * <p> * Even though {@code UnicastSubject} implements the {@code Observer} interface, calling * {@code onSubscribe} is not required (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.12">Rule 2.12</a>) * if the subject is used as a standalone source. However, calling {@code onSubscribe} * after the {@code UnicastSubject} reached its terminal state will result in the * given {@code Disposable} being disposed immediately. * <p> * Calling {@link #onNext(Object)}, {@link #onError(Throwable)} and {@link #onComplete()} * is required to be serialized (called from the same thread or called non-overlappingly from different threads * through external means of serialization). The {@link #toSerialized()} method available to all {@code Subject}s * provides such serialization and also protects against reentrance (i.e., when a downstream {@code Observer} * consuming this subject also wants to call {@link #onNext(Object)} on this subject recursively). * <p> * This {@code UnicastSubject} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()}, * {@link #getThrowable()} and {@link #hasObservers()}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code UnicastSubject} does not operate by default on a particular {@link io.reactivex.rxjava3.core.Scheduler} and * the single {@code Observer} gets notified on the thread the respective {@code onXXX} methods were invoked.</dd> * <dt><b>Error handling:</b></dt> * <dd>When the {@link #onError(Throwable)} is called, the {@code UnicastSubject} enters into a terminal state * and emits the same {@code Throwable} instance to the current single {@code Observer}. During this emission, * if the single {@code Observer}s disposes its respective {@code Disposable}, the * {@code Throwable} is delivered to the global error handler via * {@link io.reactivex.rxjava3.plugins.RxJavaPlugins#onError(Throwable)}. * If there were no {@code Observer}s subscribed to this {@code UnicastSubject} when the {@code onError()} * was called, the global error handler is not invoked. * </dd> * </dl> * <p> * Example usage: * <pre><code> * UnicastSubject&lt;Integer&gt; subject = UnicastSubject.create(); * * TestObserver&lt;Integer&gt; to1 = subject.test(); * * // fresh UnicastSubjects are empty * to1.assertEmpty(); * * TestObserver&lt;Integer&gt; to2 = subject.test(); * * // A UnicastSubject only allows one Observer during its lifetime * to2.assertFailure(IllegalStateException.class); * * subject.onNext(1); * to1.assertValue(1); * * subject.onNext(2); * to1.assertValues(1, 2); * * subject.onComplete(); * to1.assertResult(1, 2); * * // ---------------------------------------------------- * * UnicastSubject&lt;Integer&gt; subject2 = UnicastSubject.create(); * * // a UnicastSubject caches events until its single Observer subscribes * subject2.onNext(1); * subject2.onNext(2); * subject2.onComplete(); * * TestObserver&lt;Integer&gt; to3 = subject2.test(); * * // the cached events are emitted in order * to3.assertResult(1, 2); * </code></pre> * @param <T> the value type received and emitted by this Subject subclass * @since 2.0 */ public final class UnicastSubject<T> extends Subject<T> { /** The queue that buffers the source events. */ final SpscLinkedArrayQueue<T> queue; /** The single Observer. */ final AtomicReference<Observer<? super T>> downstream; /** The optional callback when the Subject gets cancelled or terminates. */ final AtomicReference<Runnable> onTerminate; /** deliver onNext events before error event. */ final boolean delayError; /** Indicates the single observer has cancelled. */ volatile boolean disposed; /** Indicates the source has terminated. */ volatile boolean done; /** * The terminal error if not null. * Must be set before writing to done and read after done == true. */ Throwable error; /** Set to 1 atomically for the first and only Subscriber. */ final AtomicBoolean once; /** The wip counter and QueueDisposable surface. */ final BasicIntQueueDisposable<T> wip; boolean enableOperatorFusion; /** * Creates an UnicastSubject with an internal buffer capacity hint 16. * @param <T> the value type * @return an UnicastSubject instance */ @CheckReturnValue @NonNull public static <T> UnicastSubject<T> create() { return new UnicastSubject<>(bufferSize(), null, true); } /** * Creates an UnicastSubject with the given internal buffer capacity hint. * @param <T> the value type * @param capacityHint the hint to size the internal unbounded buffer * @return an UnicastSubject instance * @throws IllegalArgumentException if {@code capacityHint} is non-positive */ @CheckReturnValue @NonNull public static <T> UnicastSubject<T> create(int capacityHint) { ObjectHelper.verifyPositive(capacityHint, "capacityHint"); return new UnicastSubject<>(capacityHint, null, true); } /** * Creates an UnicastSubject with the given internal buffer capacity hint and a callback for * the case when the single Subscriber cancels its subscription * or the subject is terminated. * * <p>The callback, if not null, is called exactly once and * non-overlapped with any active replay. * * @param <T> the value type * @param capacityHint the hint to size the internal unbounded buffer * @param onTerminate the callback to run when the Subject is terminated or cancelled, null not allowed * @return an UnicastSubject instance * @throws NullPointerException if {@code onTerminate} is {@code null} * @throws IllegalArgumentException if {@code capacityHint} is non-positive */ @CheckReturnValue @NonNull public static <T> UnicastSubject<T> create(int capacityHint, @NonNull Runnable onTerminate) { ObjectHelper.verifyPositive(capacityHint, "capacityHint"); Objects.requireNonNull(onTerminate, "onTerminate"); return new UnicastSubject<>(capacityHint, onTerminate, true); } /** * Creates an UnicastSubject with the given internal buffer capacity hint, delay error flag and * a callback for the case when the single Observer disposes its {@link Disposable} * or the subject is terminated. * * <p>The callback, if not null, is called exactly once and * non-overlapped with any active replay. * <p>History: 2.0.8 - experimental * @param <T> the value type * @param capacityHint the hint to size the internal unbounded buffer * @param onTerminate the callback to run when the Subject is terminated or cancelled, null not allowed * @param delayError deliver pending onNext events before onError * @return an UnicastSubject instance * @throws NullPointerException if {@code onTerminate} is {@code null} * @throws IllegalArgumentException if {@code capacityHint} is non-positive * @since 2.2 */ @CheckReturnValue @NonNull public static <T> UnicastSubject<T> create(int capacityHint, @NonNull Runnable onTerminate, boolean delayError) { ObjectHelper.verifyPositive(capacityHint, "capacityHint"); Objects.requireNonNull(onTerminate, "onTerminate"); return new UnicastSubject<>(capacityHint, onTerminate, delayError); } /** * Creates an UnicastSubject with an internal buffer capacity hint 16 and given delay error flag. * * <p>The callback, if not null, is called exactly once and * non-overlapped with any active replay. * <p>History: 2.0.8 - experimental * @param <T> the value type * @param delayError deliver pending onNext events before onError * @return an UnicastSubject instance * @since 2.2 */ @CheckReturnValue @NonNull public static <T> UnicastSubject<T> create(boolean delayError) { return new UnicastSubject<>(bufferSize(), null, delayError); } /** * Creates an UnicastSubject with the given capacity hint, delay error flag and callback * for when the Subject is terminated normally or its single Subscriber cancels. * <p>History: 2.0.8 - experimental * @param capacityHint the capacity hint for the internal, unbounded queue * @param onTerminate the callback to run when the Subject is terminated or cancelled, null not allowed * @param delayError deliver pending onNext events before onError * @since 2.2 */ UnicastSubject(int capacityHint, Runnable onTerminate, boolean delayError) { this.queue = new SpscLinkedArrayQueue<>(capacityHint); this.onTerminate = new AtomicReference<>(onTerminate); this.delayError = delayError; this.downstream = new AtomicReference<>(); this.once = new AtomicBoolean(); this.wip = new UnicastQueueDisposable(); } @Override protected void subscribeActual(Observer<? super T> observer) { if (!once.get() && once.compareAndSet(false, true)) { observer.onSubscribe(wip); downstream.lazySet(observer); // full barrier in drain if (disposed) { downstream.lazySet(null); return; } drain(); } else { EmptyDisposable.error(new IllegalStateException("Only a single observer allowed."), observer); } } void doTerminate() { Runnable r = onTerminate.get(); if (r != null && onTerminate.compareAndSet(r, null)) { r.run(); } } @Override public void onSubscribe(Disposable d) { if (done || disposed) { d.dispose(); } } @Override public void onNext(T t) { ExceptionHelper.nullCheck(t, "onNext called with a null value."); if (done || disposed) { return; } queue.offer(t); drain(); } @Override public void onError(Throwable t) { ExceptionHelper.nullCheck(t, "onError called with a null Throwable."); if (done || disposed) { RxJavaPlugins.onError(t); return; } error = t; done = true; doTerminate(); drain(); } @Override public void onComplete() { if (done || disposed) { return; } done = true; doTerminate(); drain(); } void drainNormal(Observer<? super T> a) { int missed = 1; SimpleQueue<T> q = queue; boolean failFast = !this.delayError; boolean canBeError = true; for (;;) { for (;;) { if (disposed) { downstream.lazySet(null); q.clear(); return; } boolean d = this.done; T v = queue.poll(); boolean empty = v == null; if (d) { if (failFast && canBeError) { if (failedFast(q, a)) { return; } else { canBeError = false; } } if (empty) { errorOrComplete(a); return; } } if (empty) { break; } a.onNext(v); } missed = wip.addAndGet(-missed); if (missed == 0) { break; } } } void drainFused(Observer<? super T> a) { int missed = 1; final SpscLinkedArrayQueue<T> q = queue; final boolean failFast = !delayError; for (;;) { if (disposed) { downstream.lazySet(null); return; } boolean d = done; if (failFast && d) { if (failedFast(q, a)) { return; } } a.onNext(null); if (d) { errorOrComplete(a); return; } missed = wip.addAndGet(-missed); if (missed == 0) { break; } } } void errorOrComplete(Observer<? super T> a) { downstream.lazySet(null); Throwable ex = error; if (ex != null) { a.onError(ex); } else { a.onComplete(); } } boolean failedFast(final SimpleQueue<T> q, Observer<? super T> a) { Throwable ex = error; if (ex != null) { downstream.lazySet(null); q.clear(); a.onError(ex); return true; } else { return false; } } void drain() { if (wip.getAndIncrement() != 0) { return; } Observer<? super T> a = downstream.get(); int missed = 1; for (;;) { if (a != null) { if (enableOperatorFusion) { drainFused(a); } else { drainNormal(a); } return; } missed = wip.addAndGet(-missed); if (missed == 0) { break; } a = downstream.get(); } } @Override @CheckReturnValue public boolean hasObservers() { return downstream.get() != null; } @Override @Nullable @CheckReturnValue public Throwable getThrowable() { if (done) { return error; } return null; } @Override @CheckReturnValue public boolean hasThrowable() { return done && error != null; } @Override @CheckReturnValue public boolean hasComplete() { return done && error == null; } final class UnicastQueueDisposable extends BasicIntQueueDisposable<T> { private static final long serialVersionUID = 7926949470189395511L; @Override public int requestFusion(int mode) { if ((mode & ASYNC) != 0) { enableOperatorFusion = true; return ASYNC; } return NONE; } @Nullable @Override public T poll() { return queue.poll(); } @Override public boolean isEmpty() { return queue.isEmpty(); } @Override public void clear() { queue.clear(); } @Override public void dispose() { if (!disposed) { disposed = true; doTerminate(); downstream.lazySet(null); if (wip.getAndIncrement() == 0) { downstream.lazySet(null); if (!enableOperatorFusion) { queue.clear(); } } } } @Override public boolean isDisposed() { return disposed; } } }
ReactiveX/RxJava
src/main/java/io/reactivex/rxjava3/subjects/UnicastSubject.java
44,915
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.testFramework; import com.intellij.ide.IdeEventQueue; import com.intellij.ide.ProhibitAWTEvents; import com.intellij.openapi.application.AccessToken; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.impl.LaterInvocator; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ex.ProjectEx; import com.intellij.openapi.project.impl.ProjectImpl; import com.intellij.openapi.util.Disposer; import com.intellij.platform.diagnostic.telemetry.TelemetryManager; import com.intellij.testFramework.common.DumpKt; import com.intellij.testFramework.common.TestApplicationKt; import com.intellij.testFramework.common.ThreadLeakTracker; import com.intellij.testFramework.common.ThreadUtil; import com.intellij.util.PairProcessor; import com.intellij.util.ReflectionUtil; import com.intellij.util.io.PersistentEnumeratorCache; import com.intellij.util.ref.DebugReflectionUtil; import com.intellij.util.ui.UIUtil; import kotlin.Suppress; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.swing.*; import java.util.*; import java.util.function.Predicate; import java.util.function.Supplier; public final class LeakHunter { @TestOnly public static @NotNull String getCreationPlace(@NotNull Project project) { String creationTrace = project instanceof ProjectEx ? ((ProjectEx)project).getCreationTrace() : null; return project + " " + (creationTrace == null ? " " : creationTrace); } @TestOnly public static void checkProjectLeak() throws AssertionError { checkLeak(allRoots(), ProjectImpl.class, project -> !project.isDefault() && !project.isLight()); } @TestOnly public static void checkNonDefaultProjectLeak() { checkLeak(allRoots(), ProjectImpl.class, project -> !project.isDefault()); } @TestOnly public static void checkLeak(@NotNull Object root, @NotNull Class<?> suspectClass) throws AssertionError { checkLeak(root, suspectClass, null); } /** * Checks if there is a memory leak if an object of type {@code suspectClass} is strongly accessible via references from the {@code root} object. */ @TestOnly public static <T> void checkLeak(@NotNull Supplier<? extends Map<Object, String>> rootsSupplier, @NotNull Class<T> suspectClass, @Nullable Predicate<? super T> isReallyLeak) throws AssertionError { processLeaks(rootsSupplier, suspectClass, isReallyLeak, (leaked, backLink)->{ String message = getLeakedObjectDetails(leaked, backLink, true); System.out.println(message); System.out.println(";-----"); ThreadUtil.printThreadDump(); throw new AssertionError(message); }); } /** * Checks if there is a memory leak if an object of type {@code suspectClass} is strongly accessible via references from the {@code root} object. */ @TestOnly public static <T> void processLeaks(@NotNull Supplier<? extends Map<Object, String>> rootsSupplier, @NotNull Class<T> suspectClass, @Nullable Predicate<? super T> isReallyLeak, @NotNull PairProcessor<? super T, Object> processor) throws AssertionError { if (SwingUtilities.isEventDispatchThread()) { UIUtil.dispatchAllInvocationEvents(); } else { UIUtil.pump(); } PersistentEnumeratorCache.clearCacheForTests(); flushTelemetry(); //noinspection CallToSystemGC System.gc(); Runnable runnable = () -> { try (AccessToken ignored = ProhibitAWTEvents.start("checking for leaks")) { DebugReflectionUtil.walkObjects(10000, rootsSupplier.get(), suspectClass, __ -> true, (leaked, backLink) -> { if (isReallyLeak == null || isReallyLeak.test(leaked)) { return processor.process(leaked, backLink); } return true; }); } }; Application application = ApplicationManager.getApplication(); if (application == null) { runnable.run(); } else { application.runReadAction(runnable); } } /** * Checks if there is a memory leak if an object of type {@code suspectClass} is strongly accessible via references from the {@code root} object. */ @TestOnly public static <T> void checkLeak(@NotNull Object root, @NotNull Class<T> suspectClass, @Nullable Predicate<? super T> isReallyLeak) throws AssertionError { checkLeak(() -> Collections.singletonMap(root, "Root object"), suspectClass, isReallyLeak); } @TestOnly public static @NotNull Supplier<Map<Object, String>> allRoots() { return () -> { ClassLoader classLoader = LeakHunter.class.getClassLoader(); // inspect static fields of all loaded classes Collection<?> allLoadedClasses = ReflectionUtil.getField(classLoader.getClass(), classLoader, Vector.class, "classes"); // Remove expired invocations, so they are not used as object roots. LaterInvocator.purgeExpiredItems(); Map<Object, String> result = new IdentityHashMap<>(); Application application = ApplicationManager.getApplication(); if (application != null) { result.put(application, "ApplicationManager.getApplication()"); } result.put(Disposer.getTree(), "Disposer.getTree()"); result.put(IdeEventQueue.getInstance(), "IdeEventQueue.getInstance()"); result.put(LaterInvocator.getLaterInvocatorEdtQueue(), "LaterInvocator.getLaterInvocatorEdtQueue()"); result.put(ThreadLeakTracker.getThreads().values(), "all live threads"); if (allLoadedClasses != null) { result.put(allLoadedClasses, "all loaded classes statics"); } return result; }; } @TestOnly @NotNull public static String getLeakedObjectDetails(@NotNull Object leaked, @Nullable Object backLink, boolean detailedErrorDescription) { int hashCode = System.identityHashCode(leaked); String result = "Found a leaked instance of "+leaked.getClass() +"\nInstance: "+leaked +"\nHashcode: "+hashCode; if (detailedErrorDescription) { result += "\n"+getLeakedObjectErrorDescription(null); } if (backLink != null) { result += "\nExisting strong reference path to the instance:\n" +backLink.toString().indent(2); } String creationPlace = leaked instanceof Project ? getCreationPlace((Project)leaked) : null; if (creationPlace != null) { result += "\nThe instance was created at: "+creationPlace; } return result; } @TestOnly public static @NotNull String getLeakedObjectErrorDescription(@Nullable String knownHeapDumpPath) { String result = """ Error description: This error means that the object is expected to be collected by the garbage collector by this time, but it was not. Please make sure you dispose your resources properly. See https://plugins.jetbrains.com/docs/intellij/disposers.html"""; if (TeamCityLogger.isUnderTC) { result+="\n You can find a memory snapshot `" +TestApplicationKt.LEAKED_PROJECTS +".hproof.zip` in the \"Artifacts\" tab of the build run."; result+="\n If you suspect a particular test, you can reproduce the problem locally " + "calling TestApplicationManager.testProjectLeak() after the test."; } else if (knownHeapDumpPath != null) { result += "\n Please see ``" + knownHeapDumpPath + "` for a memory dump"; } else { result += "\n Try looking for '"+DumpKt.HEAP_DUMP_IS_PUBLISHED +"' line in the system output log below. It contains a path to a collected memory snapshot"; } return result; } // OTel traces may store references to cancellation exceptions. // In the case of kotlin coroutines, a cancellation exception references `Job`, which may reference `CoroutineContext`, // which may reference `ComponentManager`s (such as `Project` of `Application`). // The traces are processed in batches, so we cannot predict when they get cleared, // although we know that they be cleared after a certain finite period of time. // Here we forcibly flush the batch and avoid a leak of component managers. private static void flushTelemetry() { //noinspection TestOnlyProblems TelemetryManager.getInstance().forceFlushMetricsBlocking(); } }
JetBrains/intellij-community
platform/testFramework/common/src/LeakHunter.java
44,916
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.search.internal; import org.elasticsearch.core.AbstractRefCounted; import org.elasticsearch.core.RefCounted; import org.elasticsearch.core.Releasable; import org.elasticsearch.core.Releasables; import org.elasticsearch.index.IndexService; import org.elasticsearch.index.engine.Engine; import org.elasticsearch.index.shard.IndexShard; import org.elasticsearch.search.RescoreDocIds; import org.elasticsearch.search.dfs.AggregatedDfs; import org.elasticsearch.transport.TransportRequest; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; /** * Holds a reference to a point in time {@link Engine.Searcher} that will be used to construct {@link SearchContext}. * This class also implements {@link RefCounted} since in some situations like * in {@link org.elasticsearch.search.SearchService} a SearchContext can be closed concurrently due to independent events * ie. when an index gets removed. To prevent accessing closed IndexReader / IndexSearcher instances the SearchContext * can be guarded by a reference count and fail if it's been closed by an external event. */ public class ReaderContext implements Releasable { private final ShardSearchContextId id; private final IndexService indexService; private final IndexShard indexShard; protected final Engine.SearcherSupplier searcherSupplier; private final AtomicBoolean closed = new AtomicBoolean(false); private final boolean singleSession; private final AtomicLong keepAlive; private final AtomicLong lastAccessTime; // For reference why we use RefCounted here see https://github.com/elastic/elasticsearch/pull/20095. private final AbstractRefCounted refCounted; private final List<Releasable> onCloses = new CopyOnWriteArrayList<>(); private final long startTimeInNano = System.nanoTime(); private Map<String, Object> context; @SuppressWarnings("this-escape") public ReaderContext( ShardSearchContextId id, IndexService indexService, IndexShard indexShard, Engine.SearcherSupplier searcherSupplier, long keepAliveInMillis, boolean singleSession ) { this.id = id; this.indexService = indexService; this.indexShard = indexShard; this.searcherSupplier = searcherSupplier; this.singleSession = singleSession; this.keepAlive = new AtomicLong(keepAliveInMillis); this.lastAccessTime = new AtomicLong(nowInMillis()); this.refCounted = AbstractRefCounted.of(this::doClose); } public void validate(TransportRequest request) { indexShard.getSearchOperationListener().validateReaderContext(this, request); } private long nowInMillis() { return indexShard.getThreadPool().relativeTimeInMillis(); } @Override public final void close() { if (closed.compareAndSet(false, true)) { refCounted.decRef(); } } void doClose() { Releasables.close(Releasables.wrap(onCloses), searcherSupplier); } public void addOnClose(Releasable releasable) { onCloses.add(releasable); } public ShardSearchContextId id() { return id; } public IndexService indexService() { return indexService; } public IndexShard indexShard() { return indexShard; } public Engine.Searcher acquireSearcher(String source) { return searcherSupplier.acquireSearcher(source); } private void tryUpdateKeepAlive(long keepAlive) { this.keepAlive.accumulateAndGet(keepAlive, Math::max); } /** * Returns a releasable to indicate that the caller has stopped using this reader. * The time to live of the reader after usage can be extended using the provided * <code>keepAliveInMillis</code>. */ public Releasable markAsUsed(long keepAliveInMillis) { refCounted.incRef(); tryUpdateKeepAlive(keepAliveInMillis); return Releasables.releaseOnce(() -> { this.lastAccessTime.updateAndGet(curr -> Math.max(curr, nowInMillis())); refCounted.decRef(); }); } public boolean isExpired() { if (refCounted.refCount() > 1) { return false; // being used by markAsUsed } final long elapsed = nowInMillis() - lastAccessTime.get(); return elapsed > keepAlive.get(); } // BWC public ShardSearchRequest getShardSearchRequest(ShardSearchRequest other) { return Objects.requireNonNull(other, "ShardSearchRequest must be sent back in a fetch request"); } public ScrollContext scrollContext() { return null; } public AggregatedDfs getAggregatedDfs(AggregatedDfs other) { return other; } public void setAggregatedDfs(AggregatedDfs aggregatedDfs) { } public RescoreDocIds getRescoreDocIds(RescoreDocIds other) { return Objects.requireNonNull(other, "RescoreDocIds must be sent back in a fetch request"); } public void setRescoreDocIds(RescoreDocIds rescoreDocIds) { } /** * Returns {@code true} for readers that are intended to use in a single query. For readers that are intended * to use in multiple queries (i.e., scroll or readers), we should not release them after the fetch phase * or the query phase with empty results. */ public boolean singleSession() { return singleSession; } /** * Returns the object or <code>null</code> if the given key does not have a * value in the context */ @SuppressWarnings("unchecked") // (T)object public <T> T getFromContext(String key) { return context != null ? (T) context.get(key) : null; } /** * Puts the object into the context */ public void putInContext(String key, Object value) { if (context == null) { context = new HashMap<>(); } context.put(key, value); } public long getStartTimeInNano() { return startTimeInNano; } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/search/internal/ReaderContext.java
44,917
// This file is part of OpenTSDB. // Copyright (C) 2013 The OpenTSDB Authors. // // This program is free software: you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 2.1 of the License, or (at your // option) any later version. This program is distributed in the hope that it // will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser // General Public License for more details. You should have received a copy // of the GNU Lesser General Public License along with this program. If not, // see <http://www.gnu.org/licenses/>. package net.opentsdb.tsd; import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.MemoryPoolMXBean; import java.lang.management.OperatingSystemMXBean; import java.lang.management.RuntimeMXBean; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import net.opentsdb.core.IncomingDataPoint; import net.opentsdb.core.TSDB; import net.opentsdb.stats.QueryStats; import net.opentsdb.stats.StatsCollector; import net.opentsdb.utils.JSON; import org.hbase.async.RegionClientStats; import org.jboss.netty.channel.Channel; import org.jboss.netty.handler.codec.http.HttpMethod; import org.jboss.netty.handler.codec.http.HttpResponseStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.stumbleupon.async.Deferred; /** * Handles fetching statistics from all over the code, collating them in a * string buffer or list, and emitting them to the caller. Stats are collected * lazily, i.e. only when this method is called. * This class supports the 1.x style HTTP call as well as the 2.x style API * calls. * @since 2.0 */ public final class StatsRpc implements TelnetRpc, HttpRpc { private static final Logger LOG = LoggerFactory.getLogger(StatsRpc.class); /** * Telnet RPC responder that returns the stats in ASCII style * @param tsdb The TSDB to use for fetching stats * @param chan The netty channel to respond on * @param cmd call parameters */ public Deferred<Object> execute(final TSDB tsdb, final Channel chan, final String[] cmd) { final boolean canonical = tsdb.getConfig().getBoolean("tsd.stats.canonical"); final StringBuilder buf = new StringBuilder(1024); final ASCIICollector collector = new ASCIICollector("tsd", buf, null); doCollectStats(tsdb, collector, canonical); chan.write(buf.toString()); return Deferred.fromResult(null); } /** * HTTP resposne handler * @param tsdb The TSDB to which we belong * @param query The query to parse and respond to */ public void execute(final TSDB tsdb, final HttpQuery query) { // only accept GET/POST if (query.method() != HttpMethod.GET && query.method() != HttpMethod.POST) { throw new BadRequestException(HttpResponseStatus.METHOD_NOT_ALLOWED, "Method not allowed", "The HTTP method [" + query.method().getName() + "] is not permitted for this endpoint"); } try { final String[] uri = query.explodeAPIPath(); final String endpoint = uri.length > 1 ? uri[1].toLowerCase() : ""; // Handle /threads and /regions. if ("threads".equals(endpoint)) { printThreadStats(query); return; } else if ("jvm".equals(endpoint)) { printJVMStats(tsdb, query); return; } else if ("query".equals(endpoint)) { printQueryStats(query); return; } else if ("region_clients".equals(endpoint)) { printRegionClientStats(tsdb, query); return; } } catch (IllegalArgumentException e) { // this is thrown if the url doesn't start with /api. To maintain backwards // compatibility with the /stats endpoint we can catch and continue here. } final boolean canonical = tsdb.getConfig().getBoolean("tsd.stats.canonical"); // if we don't have an API request we need to respond with the 1.x version if (query.apiVersion() < 1) { final boolean json = query.hasQueryStringParam("json"); final StringBuilder buf = json ? null : new StringBuilder(2048); final ArrayList<String> stats = json ? new ArrayList<String>(64) : null; final ASCIICollector collector = new ASCIICollector("tsd", buf, stats); doCollectStats(tsdb, collector, canonical); if (json) { query.sendReply(JSON.serializeToBytes(stats)); } else { query.sendReply(buf); } return; } // we have an API version, so go newschool final List<IncomingDataPoint> dps = new ArrayList<IncomingDataPoint>(64); final SerializerCollector collector = new SerializerCollector("tsd", dps, canonical); ConnectionManager.collectStats(collector); RpcHandler.collectStats(collector); RpcManager.collectStats(collector); tsdb.collectStats(collector); query.sendReply(query.serializer().formatStatsV1(dps)); } /** * Helper to record the statistics for the current TSD * @param tsdb The TSDB to use for fetching stats * @param collector The collector class to call for emitting stats */ private void doCollectStats(final TSDB tsdb, final StatsCollector collector, final boolean canonical) { collector.addHostTag(canonical); ConnectionManager.collectStats(collector); RpcHandler.collectStats(collector); RpcManager.collectStats(collector); collectThreadStats(collector); tsdb.collectStats(collector); } /** * Display stats for each region client * @param tsdb The TSDB to use for fetching stats * @param query The query to respond to */ private void printRegionClientStats(final TSDB tsdb, final HttpQuery query) { final List<RegionClientStats> region_stats = tsdb.getClient().regionStats(); final List<Map<String, Object>> stats = new ArrayList<Map<String, Object>>(region_stats.size()); for (final RegionClientStats rcs : region_stats) { final Map<String, Object> stat_map = new HashMap<String, Object>(8); stat_map.put("rpcsSent", rcs.rpcsSent()); stat_map.put("rpcsInFlight", rcs.inflightRPCs()); stat_map.put("pendingRPCs", rcs.pendingRPCs()); stat_map.put("pendingBatchedRPCs", rcs.pendingBatchedRPCs()); stat_map.put("dead", rcs.isDead()); stat_map.put("rpcid", rcs.rpcID()); stat_map.put("endpoint", rcs.remoteEndpoint()); stat_map.put("rpcsTimedout", rcs.rpcsTimedout()); stat_map.put("rpcResponsesTimedout", rcs.rpcResponsesTimedout()); stat_map.put("rpcResponsesUnknown", rcs.rpcResponsesUnknown()); stat_map.put("inflightBreached", rcs.inflightBreached()); stat_map.put("pendingBreached", rcs.pendingBreached()); stat_map.put("writesBlocked", rcs.writesBlocked()); stats.add(stat_map); } query.sendReply(query.serializer().formatRegionStatsV1(stats)); } /** * Grabs a snapshot of all JVM thread states and formats it in a manner to * be displayed via API. * @param query The query to respond to */ private void printThreadStats(final HttpQuery query) { final Set<Thread> threads = Thread.getAllStackTraces().keySet(); final List<Map<String, Object>> output = new ArrayList<Map<String, Object>>(threads.size()); for (final Thread thread : threads) { final Map<String, Object> status = new HashMap<String, Object>(); status.put("threadID", thread.getId()); status.put("name", thread.getName()); status.put("state", thread.getState().toString()); status.put("interrupted", thread.isInterrupted()); status.put("priority", thread.getPriority()); final List<String> stack = new ArrayList<String>(thread.getStackTrace().length); for (final StackTraceElement element: thread.getStackTrace()) { stack.add(element.toString()); } status.put("stack", stack); output.add(status); } query.sendReply(query.serializer().formatThreadStatsV1(output)); } /** * Yield (chiefly memory-related) stats about this OpenTSDB instance's JVM. * @param tsdb The TSDB from which to fetch stats. * @param query The query to which to respond. */ private void printJVMStats(final TSDB tsdb, final HttpQuery query) { final Map<String, Map<String, Object>> map = new HashMap<String, Map<String, Object>>(); final RuntimeMXBean runtime_bean = ManagementFactory.getRuntimeMXBean(); final Map<String, Object> runtime = new HashMap<String, Object>(); map.put("runtime", runtime); runtime.put("startTime", runtime_bean.getStartTime()); runtime.put("uptime", runtime_bean.getUptime()); runtime.put("vmName", runtime_bean.getVmName()); runtime.put("vmVendor", runtime_bean.getVmVendor()); runtime.put("vmVersion", runtime_bean.getVmVersion()); final MemoryMXBean mem_bean = ManagementFactory.getMemoryMXBean(); final Map<String, Object> memory = new HashMap<String, Object>(); map.put("memory", memory); memory.put("heapMemoryUsage", mem_bean.getHeapMemoryUsage()); memory.put("nonHeapMemoryUsage", mem_bean.getNonHeapMemoryUsage()); memory.put("objectsPendingFinalization", mem_bean.getObjectPendingFinalizationCount()); final List<GarbageCollectorMXBean> gc_beans = ManagementFactory.getGarbageCollectorMXBeans(); final Map<String, Object> gc = new HashMap<String, Object>(); map.put("gc", gc); for (final GarbageCollectorMXBean gc_bean : gc_beans) { final Map<String, Object> stats = new HashMap<String, Object>(); final String name = formatStatName(gc_bean.getName()); if (name == null) { LOG.warn("Null name for bean: " + gc_bean); continue; } gc.put(name, stats); stats.put("collectionCount", gc_bean.getCollectionCount()); stats.put("collectionTime", gc_bean.getCollectionTime()); } final List<MemoryPoolMXBean> pool_beans = ManagementFactory.getMemoryPoolMXBeans(); final Map<String, Object> pools = new HashMap<String, Object>(); map.put("pools", pools); for (final MemoryPoolMXBean pool_bean : pool_beans) { final Map<String, Object> stats = new HashMap<String, Object>(); final String name = formatStatName(pool_bean.getName()); if (name == null) { LOG.warn("Null name for bean: " + pool_bean); continue; } pools.put(name, stats); stats.put("collectionUsage", pool_bean.getCollectionUsage()); stats.put("usage", pool_bean.getUsage()); stats.put("peakUsage", pool_bean.getPeakUsage()); stats.put("type", pool_bean.getType()); } final OperatingSystemMXBean os_bean = ManagementFactory.getOperatingSystemMXBean(); final Map<String, Object> os = new HashMap<String, Object>(); map.put("os", os); os.put("systemLoadAverage", os_bean.getSystemLoadAverage()); query.sendReply(query.serializer().formatJVMStatsV1(map)); } /** * Runs through the live threads and counts captures a coune of their * states for dumping in the stats page. * @param collector The collector to write to */ private void collectThreadStats(final StatsCollector collector) { final Set<Thread> threads = Thread.getAllStackTraces().keySet(); final Map<String, Integer> states = new HashMap<String, Integer>(6); states.put("new", 0); states.put("runnable", 0); states.put("blocked", 0); states.put("waiting", 0); states.put("timed_waiting", 0); states.put("terminated", 0); for (final Thread thread : threads) { int state_count = states.get(thread.getState().toString().toLowerCase()); state_count++; states.put(thread.getState().toString().toLowerCase(), state_count); } for (final Map.Entry<String, Integer> entry : states.entrySet()) { collector.record("jvm.thread.states", entry.getValue(), "state=" + entry.getKey()); } collector.record("jvm.thread.count", threads.size()); } /** * Little helper to convert the first character to lowercase and remove any * spaces * @param stat The name to cleanup * @return a clean name or null if the original string was null or empty */ private static String formatStatName(final String stat) { if (stat == null || stat.isEmpty()) { return stat; } String name = stat.replace(" ", ""); return name.substring(0, 1).toLowerCase() + name.substring(1); } /** * Print the detailed query stats to the caller using the proper serializer * @param query The query to answer to * @throws BadRequestException if the API version hasn't been implemented * yet */ private void printQueryStats(final HttpQuery query) { switch (query.apiVersion()) { case 0: case 1: query.sendReply(query.serializer().formatQueryStatsV1( QueryStats.getRunningAndCompleteStats())); break; default: throw new BadRequestException(HttpResponseStatus.NOT_IMPLEMENTED, "Requested API version not implemented", "Version " + query.apiVersion() + " is not implemented"); } } /** * Implements the StatsCollector with ASCII style output. Builds a string * buffer response to send to the caller */ final class ASCIICollector extends StatsCollector { final StringBuilder buf; final ArrayList<String> stats; /** * Default constructor * @param prefix The prefix to prepend to all statistics * @param buf The buffer to store responses in * @param stats An array of strings to write for the old style JSON output * May be null. If that's the case, we'll try to write to the {@code buf} */ public ASCIICollector(final String prefix, final StringBuilder buf, final ArrayList<String> stats) { super(prefix); this.buf = buf; this.stats = stats; } /** * Called by the {@link #record} method after a source writes a statistic. */ @Override public final void emit(final String line) { if (stats != null) { stats.add(line.substring(0, line.length() - 1)); // strip the '\n' } else { buf.append(line); } } } /** * Implements the StatsCollector with a list of IncomingDataPoint objects that * can be passed on to a serializer for output. */ final class SerializerCollector extends StatsCollector { final boolean canonical; final List<IncomingDataPoint> dps; /** * Default constructor * @param prefix The prefix to prepend to all statistics * @param dps The array to store objects in */ public SerializerCollector(final String prefix, final List<IncomingDataPoint> dps, final boolean canonical) { super(prefix); this.dps = dps; this.canonical = canonical; } /** * Override that records the stat to an IncomingDataPoint object and puts it * in the list * @param name Metric name * @param value The value to store * @param xtratag An optional extra tag in the format "tagk=tagv". Can only * have one extra tag */ @Override public void record(final String name, final long value, final String xtratag) { final IncomingDataPoint dp = new IncomingDataPoint(); dp.setMetric(prefix + "." + name); dp.setTimestamp(System.currentTimeMillis() / 1000L); dp.setValue(Long.toString(value)); String tagk = ""; if (xtratag != null) { if (xtratag.indexOf('=') != xtratag.lastIndexOf('=')) { throw new IllegalArgumentException("invalid xtratag: " + xtratag + " (multiple '=' signs), name=" + name + ", value=" + value); } else if (xtratag.indexOf('=') < 0) { throw new IllegalArgumentException("invalid xtratag: " + xtratag + " (missing '=' signs), name=" + name + ", value=" + value); } final String[] pair = xtratag.split("="); tagk = pair[0]; addExtraTag(tagk, pair[1]); } addHostTag(canonical); final HashMap<String, String> tags = new HashMap<String, String>(extratags); dp.setTags(tags); dps.add(dp); if (!tagk.isEmpty()) { clearExtraTag(tagk); } } } }
OpenTSDB/opentsdb
src/tsd/StatsRpc.java
44,918
/* * Copyright 2014 The gRPC Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.grpc; import static com.google.common.base.Charsets.US_ASCII; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.io.BaseEncoding; import com.google.common.io.ByteStreams; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import javax.annotation.concurrent.NotThreadSafe; /** * Provides access to read and write metadata values to be exchanged during a call. * * <p>Keys are allowed to be associated with more than one value. * * <p>This class is not thread safe, implementations should ensure that header reads and writes do * not occur in multiple threads concurrently. */ @NotThreadSafe public final class Metadata { private static final Logger logger = Logger.getLogger(Metadata.class.getName()); /** * All binary headers should have this suffix in their names. Vice versa. * * <p>Its value is {@code "-bin"}. An ASCII header's name must not end with this. */ public static final String BINARY_HEADER_SUFFIX = "-bin"; /** * Simple metadata marshaller that encodes bytes as is. * * <p>This should be used when raw bytes are favored over un-serialized version of object. Can be * helpful in situations where more processing to bytes is needed on application side, avoids * double encoding/decoding. * * <p>Both {@link BinaryMarshaller#toBytes} and {@link BinaryMarshaller#parseBytes} methods do not * return a copy of the byte array. Do _not_ modify the byte arrays of either the arguments or * return values. */ public static final BinaryMarshaller<byte[]> BINARY_BYTE_MARSHALLER = new BinaryMarshaller<byte[]>() { @Override public byte[] toBytes(byte[] value) { return value; } @Override public byte[] parseBytes(byte[] serialized) { return serialized; } }; /** * Simple metadata marshaller that encodes strings as is. * * <p>This should be used with ASCII strings that only contain the characters listed in the class * comment of {@link AsciiMarshaller}. Otherwise the output may be considered invalid and * discarded by the transport, or the call may fail. */ public static final AsciiMarshaller<String> ASCII_STRING_MARSHALLER = new AsciiMarshaller<String>() { @Override public String toAsciiString(String value) { return value; } @Override public String parseAsciiString(String serialized) { return serialized; } }; static final BaseEncoding BASE64_ENCODING_OMIT_PADDING = BaseEncoding.base64().omitPadding(); /** * Constructor called by the transport layer when it receives binary metadata. Metadata will * mutate the passed in array. */ Metadata(byte[]... binaryValues) { this(binaryValues.length / 2, binaryValues); } /** * Constructor called by the transport layer when it receives binary metadata. Metadata will * mutate the passed in array. * * @param usedNames the number of names */ Metadata(int usedNames, byte[]... binaryValues) { this(usedNames, (Object[]) binaryValues); } /** * Constructor called by the transport layer when it receives partially-parsed metadata. * Metadata will mutate the passed in array. * * @param usedNames the number of names * @param namesAndValues an array of interleaved names and values, with each name * (at even indices) represented by a byte array, and values (at odd indices) as * described by {@link InternalMetadata#newMetadataWithParsedValues}. */ Metadata(int usedNames, Object[] namesAndValues) { assert (namesAndValues.length & 1) == 0 : "Odd number of key-value pairs " + namesAndValues.length; size = usedNames; this.namesAndValues = namesAndValues; } private Object[] namesAndValues; // The unscaled number of headers present. private int size; private byte[] name(int i) { return (byte[]) namesAndValues[i * 2]; } private void name(int i, byte[] name) { namesAndValues[i * 2] = name; } private Object value(int i) { return namesAndValues[i * 2 + 1]; } private void value(int i, byte[] value) { namesAndValues[i * 2 + 1] = value; } private void value(int i, Object value) { if (namesAndValues instanceof byte[][]) { // Reallocate an array of Object. expand(cap()); } namesAndValues[i * 2 + 1] = value; } private byte[] valueAsBytes(int i) { Object value = value(i); if (value instanceof byte[]) { return (byte[]) value; } else { return ((LazyValue<?>) value).toBytes(); } } private Object valueAsBytesOrStream(int i) { Object value = value(i); if (value instanceof byte[]) { return value; } else { return ((LazyValue<?>) value).toStream(); } } private <T> T valueAsT(int i, Key<T> key) { Object value = value(i); if (value instanceof byte[]) { return key.parseBytes((byte[]) value); } else { return ((LazyValue<?>) value).toObject(key); } } private int cap() { return namesAndValues != null ? namesAndValues.length : 0; } // The scaled version of size. private int len() { return size * 2; } /** checks when {@link #namesAndValues} is null or has no elements. */ private boolean isEmpty() { return size == 0; } /** Constructor called by the application layer when it wants to send metadata. */ public Metadata() {} /** Returns the total number of key-value headers in this metadata, including duplicates. */ int headerCount() { return size; } /** * Returns true if a value is defined for the given key. * * <p>This is done by linear search, so if it is followed by {@link #get} or {@link #getAll}, * prefer calling them directly and checking the return value against {@code null}. */ public boolean containsKey(Key<?> key) { for (int i = 0; i < size; i++) { if (bytesEqual(key.asciiName(), name(i))) { return true; } } return false; } /** * Returns the last metadata entry added with the name 'name' parsed as T. * * @return the parsed metadata entry or null if there are none. */ @Nullable public <T> T get(Key<T> key) { for (int i = size - 1; i >= 0; i--) { if (bytesEqual(key.asciiName(), name(i))) { return valueAsT(i, key); } } return null; } private final class IterableAt<T> implements Iterable<T> { private final Key<T> key; private int startIdx; private IterableAt(Key<T> key, int startIdx) { this.key = key; this.startIdx = startIdx; } @Override public Iterator<T> iterator() { return new Iterator<T>() { private boolean hasNext = true; private int idx = startIdx; @Override public boolean hasNext() { if (hasNext) { return true; } for (; idx < size; idx++) { if (bytesEqual(key.asciiName(), name(idx))) { hasNext = true; return hasNext; } } return false; } @Override public T next() { if (hasNext()) { hasNext = false; return valueAsT(idx++, key); } throw new NoSuchElementException(); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } } /** * Returns all the metadata entries named 'name', in the order they were received, parsed as T, or * null if there are none. The iterator is not guaranteed to be "live." It may or may not be * accurate if Metadata is mutated. */ @Nullable public <T> Iterable<T> getAll(final Key<T> key) { for (int i = 0; i < size; i++) { if (bytesEqual(key.asciiName(), name(i))) { return new IterableAt<>(key, i); } } return null; } /** * Returns set of all keys in store. * * @return unmodifiable Set of keys */ @SuppressWarnings("deprecation") // The String ctor is deprecated, but fast. public Set<String> keys() { if (isEmpty()) { return Collections.emptySet(); } Set<String> ks = new HashSet<>(size); for (int i = 0; i < size; i++) { ks.add(new String(name(i), 0 /* hibyte */)); } // immutable in case we decide to change the implementation later. return Collections.unmodifiableSet(ks); } /** * Adds the {@code key, value} pair. If {@code key} already has values, {@code value} is added to * the end. Duplicate values for the same key are permitted. * * @throws NullPointerException if key or value is null */ public <T> void put(Key<T> key, T value) { Preconditions.checkNotNull(key, "key"); Preconditions.checkNotNull(value, "value"); maybeExpand(); name(size, key.asciiName()); if (key.serializesToStreams()) { value(size, LazyValue.create(key, value)); } else { value(size, key.toBytes(value)); } size++; } private void maybeExpand() { if (len() == 0 || len() == cap()) { expand(Math.max(len() * 2, 8)); } } // Expands to exactly the desired capacity. private void expand(int newCapacity) { Object[] newNamesAndValues = new Object[newCapacity]; if (!isEmpty()) { System.arraycopy(namesAndValues, 0, newNamesAndValues, 0, len()); } namesAndValues = newNamesAndValues; } /** * Removes the first occurrence of {@code value} for {@code key}. * * @param key key for value * @param value value * @return {@code true} if {@code value} removed; {@code false} if {@code value} was not present * @throws NullPointerException if {@code key} or {@code value} is null */ public <T> boolean remove(Key<T> key, T value) { Preconditions.checkNotNull(key, "key"); Preconditions.checkNotNull(value, "value"); for (int i = 0; i < size; i++) { if (!bytesEqual(key.asciiName(), name(i))) { continue; } T stored = valueAsT(i, key); if (!value.equals(stored)) { continue; } int writeIdx = i * 2; int readIdx = (i + 1) * 2; int readLen = len() - readIdx; System.arraycopy(namesAndValues, readIdx, namesAndValues, writeIdx, readLen); size -= 1; name(size, null); value(size, (byte[]) null); return true; } return false; } /** Remove all values for the given key. If there were no values, {@code null} is returned. */ public <T> Iterable<T> removeAll(Key<T> key) { if (isEmpty()) { return null; } int writeIdx = 0; int readIdx = 0; List<T> ret = null; for (; readIdx < size; readIdx++) { if (bytesEqual(key.asciiName(), name(readIdx))) { ret = ret != null ? ret : new ArrayList<T>(); ret.add(valueAsT(readIdx, key)); continue; } name(writeIdx, name(readIdx)); value(writeIdx, value(readIdx)); writeIdx++; } int newSize = writeIdx; // Multiply by two since namesAndValues is interleaved. Arrays.fill(namesAndValues, writeIdx * 2, len(), null); size = newSize; return ret; } /** * Remove all values for the given key without returning them. This is a minor performance * optimization if you do not need the previous values. */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/4691") public <T> void discardAll(Key<T> key) { if (isEmpty()) { return; } int writeIdx = 0; int readIdx = 0; for (; readIdx < size; readIdx++) { if (bytesEqual(key.asciiName(), name(readIdx))) { continue; } name(writeIdx, name(readIdx)); value(writeIdx, value(readIdx)); writeIdx++; } int newSize = writeIdx; // Multiply by two since namesAndValues is interleaved. Arrays.fill(namesAndValues, writeIdx * 2, len(), null); size = newSize; } /** * Serialize all the metadata entries. * * <p>It produces serialized names and values interleaved. result[i*2] are names, while * result[i*2+1] are values. * * <p>Names are ASCII string bytes that contains only the characters listed in the class comment * of {@link Key}. If the name ends with {@code "-bin"}, the value can be raw binary. Otherwise, * the value must contain only characters listed in the class comments of {@link AsciiMarshaller} * * <p>The returned individual byte arrays <em>must not</em> be modified. However, the top level * array may be modified. * * <p>This method is intended for transport use only. */ @Nullable byte[][] serialize() { byte[][] serialized = new byte[len()][]; if (namesAndValues instanceof byte[][]) { System.arraycopy(namesAndValues, 0, serialized, 0, len()); } else { for (int i = 0; i < size; i++) { serialized[i * 2] = name(i); serialized[i * 2 + 1] = valueAsBytes(i); } } return serialized; } /** * Serializes all metadata entries, leaving some values as {@link InputStream}s. * * <p>Produces serialized names and values interleaved. result[i*2] are names, while * result[i*2+1] are values. * * <p>Names are byte arrays as described according to the {@link #serialize} * method. Values are either byte arrays or {@link InputStream}s. * * <p>This method is intended for transport use only. */ @Nullable Object[] serializePartial() { Object[] serialized = new Object[len()]; for (int i = 0; i < size; i++) { serialized[i * 2] = name(i); serialized[i * 2 + 1] = valueAsBytesOrStream(i); } return serialized; } /** * Perform a simple merge of two sets of metadata. * * <p>This is a purely additive operation, because a single key can be associated with multiple * values. */ public void merge(Metadata other) { if (other.isEmpty()) { return; } int remaining = cap() - len(); if (isEmpty() || remaining < other.len()) { expand(len() + other.len()); } System.arraycopy(other.namesAndValues, 0, namesAndValues, len(), other.len()); size += other.size; } /** * Merge values from the given set of keys into this set of metadata. If a key is present in keys, * then all of the associated values will be copied over. * * @param other The source of the new key values. * @param keys The subset of matching key we want to copy, if they exist in the source. */ public void merge(Metadata other, Set<Key<?>> keys) { Preconditions.checkNotNull(other, "other"); // Use ByteBuffer for equals and hashCode. Map<ByteBuffer, Key<?>> asciiKeys = new HashMap<>(keys.size()); for (Key<?> key : keys) { asciiKeys.put(ByteBuffer.wrap(key.asciiName()), key); } for (int i = 0; i < other.size; i++) { ByteBuffer wrappedNamed = ByteBuffer.wrap(other.name(i)); if (asciiKeys.containsKey(wrappedNamed)) { maybeExpand(); name(size, other.name(i)); value(size, other.value(i)); size++; } } } @Override public String toString() { StringBuilder sb = new StringBuilder("Metadata("); for (int i = 0; i < size; i++) { if (i != 0) { sb.append(','); } String headerName = new String(name(i), US_ASCII); sb.append(headerName).append('='); if (headerName.endsWith(BINARY_HEADER_SUFFIX)) { sb.append(BASE64_ENCODING_OMIT_PADDING.encode(valueAsBytes(i))); } else { String headerValue = new String(valueAsBytes(i), US_ASCII); sb.append(headerValue); } } return sb.append(')').toString(); } private boolean bytesEqual(byte[] left, byte[] right) { return Arrays.equals(left, right); } /** Marshaller for metadata values that are serialized into raw binary. */ public interface BinaryMarshaller<T> { /** * Serialize a metadata value to bytes. * * @param value to serialize * @return serialized version of value */ byte[] toBytes(T value); /** * Parse a serialized metadata value from bytes. * * @param serialized value of metadata to parse * @return a parsed instance of type T */ T parseBytes(byte[] serialized); } /** * Marshaller for metadata values that are serialized into ASCII strings. The strings contain only * following characters: * * <ul> * <li>Space: {@code 0x20}, but must not be at the beginning or at the end of the value. Leading * or trailing whitespace may not be preserved. * <li>ASCII visible characters ({@code 0x21-0x7E}). * </ul> * * <p>Note this has to be the subset of valid characters in {@code field-content} from RFC 7230 * Section 3.2. */ public interface AsciiMarshaller<T> { /** * Serialize a metadata value to a ASCII string that contains only the characters listed in the * class comment of {@link AsciiMarshaller}. Otherwise the output may be considered invalid and * discarded by the transport, or the call may fail. * * @param value to serialize * @return serialized version of value, or null if value cannot be transmitted. */ String toAsciiString(T value); /** * Parse a serialized metadata value from an ASCII string. * * @param serialized value of metadata to parse * @return a parsed instance of type T */ T parseAsciiString(String serialized); } /** Marshaller for metadata values that are serialized to an InputStream. */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/6575") public interface BinaryStreamMarshaller<T> { /** * Serializes a metadata value to an {@link InputStream}. * * @param value to serialize * @return serialized version of value */ InputStream toStream(T value); /** * Parses a serialized metadata value from an {@link InputStream}. * * @param stream of metadata to parse * @return a parsed instance of type T */ T parseStream(InputStream stream); } /** * Key for metadata entries. Allows for parsing and serialization of metadata. * * <h3>Valid characters in key names</h3> * * <p>Only the following ASCII characters are allowed in the names of keys: * * <ul> * <li>digits: {@code 0-9} * <li>uppercase letters: {@code A-Z} (normalized to lower) * <li>lowercase letters: {@code a-z} * <li>special characters: {@code -_.} * </ul> * * <p>This is a strict subset of the HTTP field-name rules. Applications may not send or receive * metadata with invalid key names. However, the gRPC library may preserve any metadata received * even if it does not conform to the above limitations. Additionally, if metadata contains non * conforming field names, they will still be sent. In this way, unknown metadata fields are * parsed, serialized and preserved, but never interpreted. They are similar to protobuf unknown * fields. * * <p>Note this has to be the subset of valid HTTP/2 token characters as defined in RFC7230 * Section 3.2.6 and RFC5234 Section B.1 * * <p>Note that a key is immutable but it may not be deeply immutable, because the key depends on * its marshaller, and the marshaller can be mutable though not recommended. * * @see <a href="https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md">Wire Spec</a> * @see <a href="https://tools.ietf.org/html/rfc7230#section-3.2.6">RFC7230</a> * @see <a href="https://tools.ietf.org/html/rfc5234#appendix-B.1">RFC5234</a> */ @Immutable public abstract static class Key<T> { /** Valid characters for field names as defined in RFC7230 and RFC5234. */ private static final BitSet VALID_T_CHARS = generateValidTChars(); /** * Creates a key for a binary header. * * @param name Must contain only the valid key characters as defined in the class comment. Must * end with {@link #BINARY_HEADER_SUFFIX}. */ public static <T> Key<T> of(String name, BinaryMarshaller<T> marshaller) { return new BinaryKey<>(name, marshaller); } /** * Creates a key for a binary header, serializing to input streams. * * @param name Must contain only the valid key characters as defined in the class comment. Must * end with {@link #BINARY_HEADER_SUFFIX}. */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/6575") public static <T> Key<T> of(String name, BinaryStreamMarshaller<T> marshaller) { return new LazyStreamBinaryKey<>(name, marshaller); } /** * Creates a key for an ASCII header. * * @param name Must contain only the valid key characters as defined in the class comment. Must * <b>not</b> end with {@link #BINARY_HEADER_SUFFIX} */ public static <T> Key<T> of(String name, AsciiMarshaller<T> marshaller) { return of(name, false, marshaller); } static <T> Key<T> of(String name, boolean pseudo, AsciiMarshaller<T> marshaller) { return new AsciiKey<>(name, pseudo, marshaller); } static <T> Key<T> of(String name, boolean pseudo, TrustedAsciiMarshaller<T> marshaller) { return new TrustedAsciiKey<>(name, pseudo, marshaller); } private final String originalName; private final String name; private final byte[] nameBytes; private final Object marshaller; private static BitSet generateValidTChars() { BitSet valid = new BitSet(0x7f); valid.set('-'); valid.set('_'); valid.set('.'); for (char c = '0'; c <= '9'; c++) { valid.set(c); } // Only validates after normalization, so we exclude uppercase. for (char c = 'a'; c <= 'z'; c++) { valid.set(c); } return valid; } private static String validateName(String n, boolean pseudo) { checkNotNull(n, "name"); checkArgument(!n.isEmpty(), "token must have at least 1 tchar"); if (n.equals("connection")) { logger.log( Level.WARNING, "Metadata key is 'Connection', which should not be used. That is used by HTTP/1 for " + "connection-specific headers which are not to be forwarded. There is probably an " + "HTTP/1 conversion bug. Simply removing the Connection header is not enough; you " + "should remove all headers it references as well. See RFC 7230 section 6.1", new RuntimeException("exception to show backtrace")); } for (int i = 0; i < n.length(); i++) { char tChar = n.charAt(i); if (pseudo && tChar == ':' && i == 0) { continue; } checkArgument( VALID_T_CHARS.get(tChar), "Invalid character '%s' in key name '%s'", tChar, n); } return n; } private Key(String name, boolean pseudo, Object marshaller) { this.originalName = checkNotNull(name, "name"); this.name = validateName(this.originalName.toLowerCase(Locale.ROOT), pseudo); this.nameBytes = this.name.getBytes(US_ASCII); this.marshaller = marshaller; } /** * Returns the original name used to create this key. */ public final String originalName() { return originalName; } /** * Returns the normalized name for this key. */ public final String name() { return name; } /** * Get the name as bytes using ASCII-encoding. * * <p>The returned byte arrays <em>must not</em> be modified. * * <p>This method is intended for transport use only. */ // TODO (louiscryan): Migrate to ByteString @VisibleForTesting byte[] asciiName() { return nameBytes; } /** * Returns true if the two objects are both Keys, and their names match (case insensitive). */ @SuppressWarnings("EqualsGetClass") @Override public final boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Key<?> key = (Key<?>) o; return name.equals(key.name); } @Override public final int hashCode() { return name.hashCode(); } @Override public String toString() { return "Key{name='" + name + "'}"; } /** * Serialize a metadata value to bytes. * * @param value to serialize * @return serialized version of value */ abstract byte[] toBytes(T value); /** * Parse a serialized metadata value from bytes. * * @param serialized value of metadata to parse * @return a parsed instance of type T */ abstract T parseBytes(byte[] serialized); /** * Returns whether this key will be serialized to bytes lazily. */ boolean serializesToStreams() { return false; } /** * Gets this keys (implementation-specific) marshaller, or null if the * marshaller is not of the given type. * * @param marshallerClass The type we expect the marshaller to be. * @return the marshaller object for this key, or null. */ @Nullable final <M> M getMarshaller(Class<M> marshallerClass) { if (marshallerClass.isInstance(marshaller)) { return marshallerClass.cast(marshaller); } return null; } } private static class BinaryKey<T> extends Key<T> { private final BinaryMarshaller<T> marshaller; /** Keys have a name and a binary marshaller used for serialization. */ private BinaryKey(String name, BinaryMarshaller<T> marshaller) { super(name, false /* not pseudo */, marshaller); checkArgument( name.endsWith(BINARY_HEADER_SUFFIX), "Binary header is named %s. It must end with %s", name, BINARY_HEADER_SUFFIX); checkArgument(name.length() > BINARY_HEADER_SUFFIX.length(), "empty key name"); this.marshaller = checkNotNull(marshaller, "marshaller is null"); } @Override byte[] toBytes(T value) { return Preconditions.checkNotNull(marshaller.toBytes(value), "null marshaller.toBytes()"); } @Override T parseBytes(byte[] serialized) { return marshaller.parseBytes(serialized); } } /** A binary key for values which should be serialized lazily to {@link InputStream}s. */ private static class LazyStreamBinaryKey<T> extends Key<T> { private final BinaryStreamMarshaller<T> marshaller; /** Keys have a name and a stream marshaller used for serialization. */ private LazyStreamBinaryKey(String name, BinaryStreamMarshaller<T> marshaller) { super(name, false /* not pseudo */, marshaller); checkArgument( name.endsWith(BINARY_HEADER_SUFFIX), "Binary header is named %s. It must end with %s", name, BINARY_HEADER_SUFFIX); checkArgument(name.length() > BINARY_HEADER_SUFFIX.length(), "empty key name"); this.marshaller = checkNotNull(marshaller, "marshaller is null"); } @Override byte[] toBytes(T value) { return streamToBytes(checkNotNull(marshaller.toStream(value), "null marshaller.toStream()")); } @Override T parseBytes(byte[] serialized) { return marshaller.parseStream(new ByteArrayInputStream(serialized)); } @Override boolean serializesToStreams() { return true; } } /** Internal holder for values which are serialized/de-serialized lazily. */ static final class LazyValue<T> { private final BinaryStreamMarshaller<T> marshaller; private final T value; private volatile byte[] serialized; static <T> LazyValue<T> create(Key<T> key, T value) { return new LazyValue<>(checkNotNull(getBinaryStreamMarshaller(key)), value); } /** A value set by the application. */ LazyValue(BinaryStreamMarshaller<T> marshaller, T value) { this.marshaller = marshaller; this.value = value; } InputStream toStream() { return checkNotNull(marshaller.toStream(value), "null marshaller.toStream()"); } byte[] toBytes() { if (serialized == null) { synchronized (this) { if (serialized == null) { serialized = streamToBytes(toStream()); } } } return serialized; } <T2> T2 toObject(Key<T2> key) { if (key.serializesToStreams()) { BinaryStreamMarshaller<T2> marshaller = getBinaryStreamMarshaller(key); if (marshaller != null) { return marshaller.parseStream(toStream()); } } return key.parseBytes(toBytes()); } @Nullable @SuppressWarnings("unchecked") private static <T> BinaryStreamMarshaller<T> getBinaryStreamMarshaller(Key<T> key) { return (BinaryStreamMarshaller<T>) key.getMarshaller(BinaryStreamMarshaller.class); } } private static class AsciiKey<T> extends Key<T> { private final AsciiMarshaller<T> marshaller; /** Keys have a name and an ASCII marshaller used for serialization. */ private AsciiKey(String name, boolean pseudo, AsciiMarshaller<T> marshaller) { super(name, pseudo, marshaller); Preconditions.checkArgument( !name.endsWith(BINARY_HEADER_SUFFIX), "ASCII header is named %s. Only binary headers may end with %s", name, BINARY_HEADER_SUFFIX); this.marshaller = Preconditions.checkNotNull(marshaller, "marshaller"); } @Override byte[] toBytes(T value) { String encoded = Preconditions.checkNotNull( marshaller.toAsciiString(value), "null marshaller.toAsciiString()"); return encoded.getBytes(US_ASCII); } @Override T parseBytes(byte[] serialized) { return marshaller.parseAsciiString(new String(serialized, US_ASCII)); } } private static final class TrustedAsciiKey<T> extends Key<T> { private final TrustedAsciiMarshaller<T> marshaller; /** Keys have a name and an ASCII marshaller used for serialization. */ private TrustedAsciiKey(String name, boolean pseudo, TrustedAsciiMarshaller<T> marshaller) { super(name, pseudo, marshaller); Preconditions.checkArgument( !name.endsWith(BINARY_HEADER_SUFFIX), "ASCII header is named %s. Only binary headers may end with %s", name, BINARY_HEADER_SUFFIX); this.marshaller = Preconditions.checkNotNull(marshaller, "marshaller"); } @Override byte[] toBytes(T value) { return Preconditions.checkNotNull( marshaller.toAsciiString(value), "null marshaller.toAsciiString()"); } @Override T parseBytes(byte[] serialized) { return marshaller.parseAsciiString(serialized); } } /** * A specialized plain ASCII marshaller. Both input and output are assumed to be valid header * ASCII. */ @Immutable interface TrustedAsciiMarshaller<T> { /** * Serialize a metadata value to a ASCII string that contains only the characters listed in the * class comment of {@link io.grpc.Metadata.AsciiMarshaller}. Otherwise the output may be * considered invalid and discarded by the transport, or the call may fail. * * @param value to serialize * @return serialized version of value, or null if value cannot be transmitted. */ byte[] toAsciiString(T value); /** * Parse a serialized metadata value from an ASCII string. * * @param serialized value of metadata to parse * @return a parsed instance of type T */ T parseAsciiString(byte[] serialized); } private static byte[] streamToBytes(InputStream stream) { try { return ByteStreams.toByteArray(stream); } catch (IOException ioe) { throw new RuntimeException("failure reading serialized stream", ioe); } } }
grpc/grpc-java
api/src/main/java/io/grpc/Metadata.java
44,919
package org.chromium.net; import android.content.Context; import android.net.http.HttpResponseCache; import android.util.Log; import androidx.annotation.VisibleForTesting; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandlerFactory; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.Executor; import javax.net.ssl.HttpsURLConnection; /** * An engine to process {@link UrlRequest}s, which uses the best HTTP stack available on the current * platform. An instance of this class can be created using {@link Builder}. */ public abstract class CronetEngine { private static final String TAG = CronetEngine.class.getSimpleName(); /** * A builder for {@link CronetEngine}s, which allows runtime configuration of {@code * CronetEngine}. Configuration options are set on the builder and then {@link #build} is called * to create the {@code CronetEngine}. */ // NOTE(kapishnikov): In order to avoid breaking the existing API clients, all future methods // added to this class and other API classes must have default implementation. public static class Builder { /** * A class which provides a method for loading the cronet native library. Apps needing to * implement custom library loading logic can inherit from this class and pass an instance to * {@link CronetEngine.Builder#setLibraryLoader}. For example, this might be required to work * around {@code UnsatisfiedLinkError}s caused by flaky installation on certain older devices. */ public abstract static class LibraryLoader { /** * Loads the native library. * * @param libName name of the library to load */ public abstract void loadLibrary(String libName); } /** Reference to the actual builder implementation. {@hide exclude from JavaDoc}. */ protected final ICronetEngineBuilder mBuilderDelegate; /** * Constructs a {@link Builder} object that facilitates creating a {@link CronetEngine}. The * default configuration enables HTTP/2 and QUIC, but disables the HTTP cache. * * @param context Android {@link Context}, which is used by {@link Builder} to retrieve the * application context. A reference to only the application context will be kept, so as to * avoid extending the lifetime of {@code context} unnecessarily. */ public Builder(Context context) { this(createBuilderDelegate(context)); } /** * Constructs {@link Builder} with a given delegate that provides the actual implementation of * the {@code Builder} methods. This constructor is used only by the internal implementation. * * @param builderDelegate delegate that provides the actual implementation. * <p>{@hide} */ public Builder(ICronetEngineBuilder builderDelegate) { mBuilderDelegate = builderDelegate; } /** * Constructs a User-Agent string including application name and version, system build version, * model and id, and Cronet version. * * @return User-Agent string. */ public String getDefaultUserAgent() { return mBuilderDelegate.getDefaultUserAgent(); } /** * Overrides the User-Agent header for all requests. An explicitly set User-Agent header (set * using {@link UrlRequest.Builder#addHeader}) will override a value set using this function. * * @param userAgent the User-Agent string to use for all requests. * @return the builder to facilitate chaining. */ public Builder setUserAgent(String userAgent) { mBuilderDelegate.setUserAgent(userAgent); return this; } /** * Sets directory for HTTP Cache and Cookie Storage. The directory must exist. * * <p><b>NOTE:</b> Do not use the same storage directory with more than one {@code CronetEngine} * at a time. Access to the storage directory does not support concurrent access by multiple * {@code CronetEngine}s. * * @param value path to existing directory. * @return the builder to facilitate chaining. */ public Builder setStoragePath(String value) { mBuilderDelegate.setStoragePath(value); return this; } /** * Sets a {@link LibraryLoader} to be used to load the native library. If not set, the library * will be loaded using {@link System#loadLibrary}. * * @param loader {@code LibraryLoader} to be used to load the native library. * @return the builder to facilitate chaining. */ public Builder setLibraryLoader(LibraryLoader loader) { mBuilderDelegate.setLibraryLoader(loader); return this; } /** * Sets whether <a href="https://www.chromium.org/quic">QUIC</a> protocol is enabled. Defaults * to enabled. If QUIC is enabled, then QUIC User Agent Id containing application name and * Cronet version is sent to the server. * * @param value {@code true} to enable QUIC, {@code false} to disable. * @return the builder to facilitate chaining. */ public Builder enableQuic(boolean value) { mBuilderDelegate.enableQuic(value); return this; } /** * Sets whether <a href="https://tools.ietf.org/html/rfc7540">HTTP/2</a> protocol is enabled. * Defaults to enabled. * * @param value {@code true} to enable HTTP/2, {@code false} to disable. * @return the builder to facilitate chaining. */ public Builder enableHttp2(boolean value) { mBuilderDelegate.enableHttp2(value); return this; } /** * @deprecated SDCH is deprecated in Cronet M63. This method is a no-op. {@hide exclude from * JavaDoc}. */ @Deprecated public Builder enableSdch(boolean value) { return this; } /** * Sets whether <a href="https://tools.ietf.org/html/rfc7932">Brotli</a> compression is enabled. * If enabled, Brotli will be advertised in Accept-Encoding request headers. Defaults to * disabled. * * @param value {@code true} to enable Brotli, {@code false} to disable. * @return the builder to facilitate chaining. */ public Builder enableBrotli(boolean value) { mBuilderDelegate.enableBrotli(value); return this; } /** * Setting to disable HTTP cache. Some data may still be temporarily stored in memory. Passed to * {@link #enableHttpCache}. */ public static final int HTTP_CACHE_DISABLED = 0; /** * Setting to enable in-memory HTTP cache, including HTTP data. Passed to {@link * #enableHttpCache}. */ public static final int HTTP_CACHE_IN_MEMORY = 1; /** * Setting to enable on-disk cache, excluding HTTP data. {@link #setStoragePath} must be called * prior to passing this constant to {@link #enableHttpCache}. */ public static final int HTTP_CACHE_DISK_NO_HTTP = 2; /** * Setting to enable on-disk cache, including HTTP data. {@link #setStoragePath} must be called * prior to passing this constant to {@link #enableHttpCache}. */ public static final int HTTP_CACHE_DISK = 3; /** * Enables or disables caching of HTTP data and other information like QUIC server information. * * @param cacheMode control location and type of cached data. Must be one of {@link * #HTTP_CACHE_DISABLED HTTP_CACHE_*}. * @param maxSize maximum size in bytes used to cache data (advisory and maybe exceeded at * times). * @return the builder to facilitate chaining. */ public Builder enableHttpCache(int cacheMode, long maxSize) { mBuilderDelegate.enableHttpCache(cacheMode, maxSize); return this; } /** * Adds hint that {@code host} supports QUIC. Note that {@link #enableHttpCache enableHttpCache} * ({@link #HTTP_CACHE_DISK}) is needed to take advantage of 0-RTT connection establishment * between sessions. * * @param host hostname of the server that supports QUIC. * @param port host of the server that supports QUIC. * @param alternatePort alternate port to use for QUIC. * @return the builder to facilitate chaining. */ public Builder addQuicHint(String host, int port, int alternatePort) { mBuilderDelegate.addQuicHint(host, port, alternatePort); return this; } /** * Pins a set of public keys for a given host. By pinning a set of public keys, {@code * pinsSha256}, communication with {@code hostName} is required to authenticate with a * certificate with a public key from the set of pinned ones. An app can pin the public key of * the root certificate, any of the intermediate certificates or the end-entry certificate. * Authentication will fail and secure communication will not be established if none of the * public keys is present in the host's certificate chain, even if the host attempts to * authenticate with a certificate allowed by the device's trusted store of certificates. * * <p>Calling this method multiple times with the same host name overrides the previously set * pins for the host. * * <p>More information about the public key pinning can be found in <a * href="https://tools.ietf.org/html/rfc7469">RFC 7469</a>. * * @param hostName name of the host to which the public keys should be pinned. A host that * consists only of digits and the dot character is treated as invalid. * @param pinsSha256 a set of pins. Each pin is the SHA-256 cryptographic hash of the * DER-encoded ASN.1 representation of the Subject Public Key Info (SPKI) of the host's * X.509 certificate. Use {@link java.security.cert.Certificate#getPublicKey() * Certificate.getPublicKey()} and {@link java.security.Key#getEncoded() Key.getEncoded()} * to obtain DER-encoded ASN.1 representation of the SPKI. Although, the method does not * mandate the presence of the backup pin that can be used if the control of the primary * private key has been lost, it is highly recommended to supply one. * @param includeSubdomains indicates whether the pinning policy should be applied to subdomains * of {@code hostName}. * @param expirationDate specifies the expiration date for the pins. * @return the builder to facilitate chaining. * @throws NullPointerException if any of the input parameters are {@code null}. * @throws IllegalArgumentException if the given host name is invalid or {@code pinsSha256} * contains a byte array that does not represent a valid SHA-256 hash. */ public Builder addPublicKeyPins(String hostName, Set<byte[]> pinsSha256, boolean includeSubdomains, Date expirationDate) { mBuilderDelegate.addPublicKeyPins(hostName, pinsSha256, includeSubdomains, expirationDate); return this; } /** * Enables or disables public key pinning bypass for local trust anchors. Disabling the bypass * for local trust anchors is highly discouraged since it may prohibit the app from * communicating with the pinned hosts. E.g., a user may want to send all traffic through an SSL * enabled proxy by changing the device proxy settings and adding the proxy certificate to the * list of local trust anchor. Disabling the bypass will most likely prevent the app from * sending any traffic to the pinned hosts. For more information see 'How does key pinning * interact with local proxies and filters?' at * https://www.chromium.org/Home/chromium-security/security-faq * * @param value {@code true} to enable the bypass, {@code false} to disable. * @return the builder to facilitate chaining. */ public Builder enablePublicKeyPinningBypassForLocalTrustAnchors(boolean value) { mBuilderDelegate.enablePublicKeyPinningBypassForLocalTrustAnchors(value); return this; } /** * Build a {@link CronetEngine} using this builder's configuration. * * @return constructed {@link CronetEngine}. */ public CronetEngine build() { return mBuilderDelegate.build(); } /** * Creates an implementation of {@link ICronetEngineBuilder} that can be used to delegate the * builder calls to. The method uses {@link CronvoyProvider} to obtain the list of available * providers. * * @param context Android Context to use. * @return the created {@code ICronetEngineBuilder}. */ private static ICronetEngineBuilder createBuilderDelegate(Context context) { List<CronvoyProvider> providers = new ArrayList<>(CronvoyProvider.getAllProviders(context)); CronvoyProvider provider = getEnabledCronvoyProviders(context, providers).get(0); if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, String.format("Using '%s' provider for creating CronetEngine.Builder.", provider)); } return provider.createBuilder().mBuilderDelegate; } /** * Returns the list of available and enabled {@link CronvoyProvider}. The returned list is * sorted based on the provider versions and types. * * @param context Android Context to use. * @param providers the list of enabled and disabled providers to filter out and sort. * @return the sorted list of enabled providers. The list contains at least one provider. * @throws RuntimeException is the list of providers is empty or all of the providers are * disabled. */ @VisibleForTesting static List<CronvoyProvider> getEnabledCronvoyProviders(Context context, List<CronvoyProvider> providers) { // Check that there is at least one available provider. if (providers.size() == 0) { throw new RuntimeException("Unable to find any Cronet provider." + " Have you included all necessary jars?"); } // Exclude disabled providers from the list. for (Iterator<CronvoyProvider> i = providers.iterator(); i.hasNext();) { CronvoyProvider provider = i.next(); if (!provider.isEnabled()) { i.remove(); } } // Check that there is at least one enabled provider. if (providers.size() == 0) { throw new RuntimeException("All available Cronet providers are disabled." + " A provider should be enabled before it can be used."); } // Sort providers based on version and type. Collections.sort(providers, new Comparator<CronvoyProvider>() { @Override public int compare(CronvoyProvider p1, CronvoyProvider p2) { // The fallback provider should always be at the end of the list. if (CronvoyProvider.PROVIDER_NAME_FALLBACK.equals(p1.getName())) { return 1; } if (CronvoyProvider.PROVIDER_NAME_FALLBACK.equals(p2.getName())) { return -1; } // A provider with higher version should go first. return -compareVersions(p1.getVersion(), p2.getVersion()); } }); return providers; } /** * Compares two strings that contain versions. The string should only contain dot-separated * segments that contain an arbitrary number of digits digits [0-9]. * * @param s1 the first string. * @param s2 the second string. * @return -1 if s1<s2, +1 if s1>s2 and 0 if s1=s2. If two versions are equal, the version with * the higher number of segments is considered to be higher. * @throws IllegalArgumentException if any of the strings contains an illegal version number. */ @VisibleForTesting static int compareVersions(String s1, String s2) { if (s1 == null || s2 == null) { throw new IllegalArgumentException("The input values cannot be null"); } String[] s1segments = s1.split("\\."); String[] s2segments = s2.split("\\."); for (int i = 0; i < s1segments.length && i < s2segments.length; i++) { try { int s1segment = Integer.parseInt(s1segments[i]); int s2segment = Integer.parseInt(s2segments[i]); if (s1segment != s2segment) { return Integer.signum(s1segment - s2segment); } } catch (NumberFormatException e) { throw new IllegalArgumentException("Unable to convert version segments into" + " integers: " + s1segments[i] + " & " + s2segments[i], e); } } return Integer.signum(s1segments.length - s2segments.length); } } /** @return a human-readable version string of the engine. */ public abstract String getVersionString(); /** * Shuts down the {@link CronetEngine} if there are no active requests, otherwise throws an * exception. * * <p>Cannot be called on network thread - the thread Cronet calls into Executor on (which is * different from the thread the Executor invokes callbacks on). May block until all the {@code * CronetEngine}'s resources have been cleaned up. */ public abstract void shutdown(); /** * Starts NetLog logging to a file. The NetLog will contain events emitted by all live * CronetEngines. The NetLog is useful for debugging. The file can be viewed using a Chrome * browser navigated to chrome://net-internals/#import * * @param fileName the complete file path. It must not be empty. If the file exists, it is * truncated before starting. If actively logging, this method is ignored. * @param logAll {@code true} to include basic events, user cookies, credentials and all * transferred bytes in the log. This option presents a privacy risk, since it exposes the * user's credentials, and should only be used with the user's consent and in situations where * the log won't be public. {@code false} to just include basic events. */ public abstract void startNetLogToFile(String fileName, boolean logAll); /** * Stops NetLog logging and flushes file to disk. If a logging session is not in progress, this * call is ignored. */ public abstract void stopNetLog(); /** * Returns differences in metrics collected by Cronet since the last call to this method. * * <p>Cronet collects these metrics globally. This means deltas returned by {@code * getGlobalMetricsDeltas()} will include measurements of requests processed by other {@link * CronetEngine} instances. Since this function returns differences in metrics collected since the * last call, and these metrics are collected globally, a call to any {@code CronetEngine} * instance's {@code getGlobalMetricsDeltas()} method will affect the deltas returned by any other * {@code CronetEngine} instance's {@code getGlobalMetricsDeltas()}. * * <p>Cronet starts collecting these metrics after the first call to {@code * getGlobalMetricsDeltras()}, so the first call returns no useful data as no metrics have yet * been collected. * * @return differences in metrics collected by Cronet, since the last call to {@code * getGlobalMetricsDeltas()}, serialized as a <a * href=https://developers.google.com/protocol-buffers>protobuf </a>. */ public abstract byte[] getGlobalMetricsDeltas(); /** * Establishes a new connection to the resource specified by the {@link URL} {@code url}. * * <p><b>Note:</b> Cronet's {@link java.net.HttpURLConnection} implementation is subject to * certain limitations, see {@link #createURLStreamHandlerFactory} for details. * * @param url URL of resource to connect to. * @return an {@link java.net.HttpURLConnection} instance implemented by this CronetEngine. * @throws IOException if an error occurs while opening the connection. */ public abstract URLConnection openConnection(URL url) throws IOException; /** * Creates a {@link URLStreamHandlerFactory} to handle HTTP and HTTPS traffic. An instance of this * class can be installed via {@link URL#setURLStreamHandlerFactory} thus using this CronetEngine * by default for all requests created via {@link URL#openConnection}. * * <p>Cronet does not use certain HTTP features provided via the system: * * <ul> * <li>the HTTP cache installed via {@link HttpResponseCache#install(java.io.File, long) * HttpResponseCache.install()} * <li>the HTTP authentication method installed via {@link java.net.Authenticator#setDefault} * <li>the HTTP cookie storage installed via {@link java.net.CookieHandler#setDefault} * </ul> * * <p>While Cronet supports and encourages requests using the HTTPS protocol, Cronet does not * provide support for the {@link HttpsURLConnection} API. This lack of support also includes not * using certain HTTPS features provided via the system: * * <ul> * <li>the HTTPS hostname verifier installed via {@link * HttpsURLConnection#setDefaultHostnameVerifier(javax.net.ssl.HostnameVerifier) * HttpsURLConnection.setDefaultHostnameVerifier()} * <li>the HTTPS socket factory installed via {@link * HttpsURLConnection#setDefaultSSLSocketFactory(javax.net.ssl.SSLSocketFactory) * HttpsURLConnection.setDefaultSSLSocketFactory()} * </ul> * * @return an {@link URLStreamHandlerFactory} instance implemented by this CronetEngine. */ public abstract URLStreamHandlerFactory createURLStreamHandlerFactory(); /** * Creates a builder for {@link UrlRequest}. All callbacks for generated {@link UrlRequest} * objects will be invoked on {@code executor}'s threads. {@code executor} must not run tasks on * the thread calling {@link Executor#execute} to prevent blocking networking operations and * causing exceptions during shutdown. * * @param url URL for the generated requests. * @param callback callback object that gets invoked on different events. * @param executor {@link Executor} on which all callbacks will be invoked. */ public abstract UrlRequest.Builder newUrlRequestBuilder(String url, UrlRequest.Callback callback, Executor executor); }
envoyproxy/envoy
mobile/library/java/org/chromium/net/CronetEngine.java
44,920
package com.baeldung.sshj; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import net.schmizz.keepalive.KeepAliveProvider; import net.schmizz.sshj.DefaultConfig; import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.connection.channel.direct.LocalPortForwarder; import net.schmizz.sshj.connection.channel.direct.Parameters; import net.schmizz.sshj.connection.channel.direct.Session; import net.schmizz.sshj.connection.channel.direct.Session.Command; import net.schmizz.sshj.connection.channel.forwarded.RemotePortForwarder; import net.schmizz.sshj.connection.channel.forwarded.RemotePortForwarder.Forward; import net.schmizz.sshj.connection.channel.forwarded.SocketForwardingConnectListener; import net.schmizz.sshj.sftp.SFTPClient; import net.schmizz.sshj.transport.verification.PromiscuousVerifier; import net.schmizz.sshj.userauth.keyprovider.KeyProvider; import net.schmizz.sshj.xfer.FileSystemFile; public class SSHJAppDemo { public static SSHClient loginSftp(String host, int port, String username, String password) throws Exception { SSHClient client = new SSHClient(); client.addHostKeyVerifier(new PromiscuousVerifier()); client.connect(host, port); client.authPassword(username, password); return client; } public static SSHClient loginPubKey(String host, String username, String privateFilePath, int port) throws IOException { final SSHClient client = new SSHClient(); File privateKeyFile = new File(privateFilePath + "/private_key"); try { KeyProvider privateKey = client.loadKeys(privateKeyFile.getPath()); client.addHostKeyVerifier(new PromiscuousVerifier()); client.connect(host, port); client.authPublickey(username, privateKey); System.out.println(client.getRemoteHostname()); } catch (Exception e) { e.printStackTrace(); } return client; } public static String executeCommand(SSHClient sshClient) throws IOException { String response = ""; try (Session session = sshClient.startSession()) { final Command cmd = session.exec("ls -lsa"); try (BufferedReader reader = new BufferedReader(new InputStreamReader(cmd.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } cmd.join(5, TimeUnit.SECONDS); response = "success"; System.out.println("\n** exit status: " + cmd.getExitStatus()); } return response; } public static void scpUpload(SSHClient ssh, String filePath) throws IOException { ssh.useCompression(); ssh.newSCPFileTransfer() .upload(new FileSystemFile(filePath), "/upload/"); } public static void scpDownLoad(SSHClient ssh, String downloadPath, String fileName) throws IOException { ssh.useCompression(); ssh.newSCPFileTransfer() .download("/upload/" + fileName, downloadPath); } public static void SFTPUpload(SSHClient ssh, String filePath) throws IOException { final SFTPClient sftp = ssh.newSFTPClient(); sftp.put(new FileSystemFile(filePath), "/upload/"); } public static void SFTPDownLoad(SSHClient ssh, String downloadPath, String fileName) throws IOException { final SFTPClient sftp = ssh.newSFTPClient(); try { sftp.get("/upload/" + fileName, downloadPath); } finally { sftp.close(); } } public static LocalPortForwarder localPortForwarding(SSHClient ssh) throws IOException, InterruptedException { LocalPortForwarder locForwarder; final Parameters params = new Parameters(ssh.getRemoteHostname(), 8081, "google.com", 80); final ServerSocket ss = new ServerSocket(); ss.setReuseAddress(true); ss.bind(new InetSocketAddress(params.getLocalHost(), params.getLocalPort())); locForwarder = ssh.newLocalPortForwarder(params, ss); new Thread(() -> { try { locForwarder.listen(); } catch (Exception e) { e.printStackTrace(); } }).start(); return locForwarder; } public static RemotePortForwarder remotePortForwarding(SSHClient ssh) throws IOException, InterruptedException { RemotePortForwarder rpf; ssh.getConnection() .getKeepAlive() .setKeepAliveInterval(5); rpf = ssh.getRemotePortForwarder(); new Thread(() -> { try { rpf.bind(new Forward(8083), new SocketForwardingConnectListener(new InetSocketAddress("google.com", 80))); ssh.getTransport() .join(); } catch (Exception e) { e.printStackTrace(); } }).start(); return rpf; } public static String KeepAlive(String hostName, String userName, String password) throws IOException, InterruptedException { String response = ""; DefaultConfig defaultConfig = new DefaultConfig(); defaultConfig.setKeepAliveProvider(KeepAliveProvider.KEEP_ALIVE); final SSHClient ssh = new SSHClient(defaultConfig); try { ssh.addHostKeyVerifier(new PromiscuousVerifier()); ssh.connect(hostName, 22); ssh.getConnection() .getKeepAlive() .setKeepAliveInterval(5); ssh.authPassword(userName, password); Session session = ssh.startSession(); session.allocateDefaultPTY(); new CountDownLatch(1).await(); try { session.allocateDefaultPTY(); } finally { session.close(); } } finally { ssh.disconnect(); } response = "success"; return response; } }
eugenp/tutorials
libraries-security/src/main/java/com/baeldung/sshj/SSHJAppDemo.java
44,921
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.cluster.coordination; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.elasticsearch.Version; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.ActionListenerResponseHandler; import org.elasticsearch.action.admin.cluster.coordination.MasterHistoryAction; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.core.Nullable; import org.elasticsearch.core.Releasable; import org.elasticsearch.core.Releasables; import org.elasticsearch.core.TimeValue; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportRequestOptions; import org.elasticsearch.transport.TransportResponseHandler; import org.elasticsearch.transport.TransportService; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.function.LongSupplier; /** * This service provides access to this node's view of the master history, as well as access to other nodes' view of master stability. */ public class MasterHistoryService { private final TransportService transportService; private final MasterHistory localMasterHistory; private final LongSupplier currentTimeMillisSupplier; private final TimeValue acceptableRemoteHistoryAge; /* * This is a view of the master history one a remote node, or the exception that fetching it resulted in. This is populated * asynchronously. It is non-private for testing. Note that this field is not nulled out after its time to live expires. That check * is only done in getRemoteMasterHistory(). All non-testing access to this field needs to go through getRemoteMasterHistory(). */ volatile RemoteHistoryOrException remoteHistoryOrException = new RemoteHistoryOrException(null, null, Long.MIN_VALUE); private static final Logger logger = LogManager.getLogger(MasterHistoryService.class); private static final TimeValue DEFAULT_REMOTE_HISTORY_TIME_TO_LIVE = new TimeValue(5, TimeUnit.MINUTES); /** * This is the amount of time that can pass after a RemoteHistoryOrException is returned from the remote master until it is * considered stale and not usable. */ public static final Setting<TimeValue> REMOTE_HISTORY_TIME_TO_LIVE_SETTING = Setting.positiveTimeSetting( "master_history.remote_history_time_to_live", DEFAULT_REMOTE_HISTORY_TIME_TO_LIVE, Setting.Property.NodeScope ); public MasterHistoryService(TransportService transportService, ThreadPool threadPool, ClusterService clusterService) { this.transportService = transportService; this.localMasterHistory = new MasterHistory(threadPool, clusterService); this.currentTimeMillisSupplier = threadPool::relativeTimeInMillis; this.acceptableRemoteHistoryAge = REMOTE_HISTORY_TIME_TO_LIVE_SETTING.get(clusterService.getSettings()); } /** * This returns the MasterHistory as seen from this node. The returned MasterHistory will be automatically updated whenever the * ClusterState on this node is updated with new information about the master. * @return The MasterHistory from this node's point of view. This MasterHistory object will be updated whenever the ClusterState changes */ public MasterHistory getLocalMasterHistory() { return localMasterHistory; } /** * This method returns a static view of the MasterHistory on a remote node. This MasterHistory is static in that it will not be * updated even if the ClusterState is updated on this node or the remote node. The history is retrieved asynchronously, and only if * refreshRemoteMasterHistory has been called for this node. If anything has gone wrong fetching it, the exception returned by the * remote machine will be thrown here. If the remote history has not been fetched or if something went wrong and there was no exception, * the returned value will be null. If the remote history is old enough to be considered stale (that is, older than * MAX_USABLE_REMOTE_HISTORY_AGE_SETTING), then the returned value will be null. * @return The MasterHistory from a remote node's point of view. This MasterHistory object will not be updated with future changes * @throws Exception the exception (if any) returned by the remote machine when fetching the history */ @Nullable public List<DiscoveryNode> getRemoteMasterHistory() throws Exception { // Grabbing a reference to the object in case it is replaced in another thread during this method: RemoteHistoryOrException remoteHistoryOrExceptionCopy = remoteHistoryOrException; /* * If the remote history we have is too old, we just return null with the assumption that it is stale and the new one has not * come in yet. */ long acceptableRemoteHistoryTime = currentTimeMillisSupplier.getAsLong() - acceptableRemoteHistoryAge.getMillis(); if (remoteHistoryOrExceptionCopy.creationTimeMillis < acceptableRemoteHistoryTime) { return null; } if (remoteHistoryOrExceptionCopy.exception != null) { throw remoteHistoryOrExceptionCopy.exception; } return remoteHistoryOrExceptionCopy.remoteHistory; } /** * This method attempts to fetch the master history from the requested node. If we are able to successfully fetch it, it will be * available in a later call to getRemoteMasterHistory. The client is not notified if or when the remote history is successfully * retrieved. This method only fetches the remote master history once, and it is never updated unless this method is called again. If * two calls are made to this method, the response of one will overwrite the response of the other (with no guarantee of the ordering * of responses). * This is a remote call, so clients should avoid calling it any more often than necessary. * @param node The node whose view of the master history we want to fetch */ public void refreshRemoteMasterHistory(DiscoveryNode node) { Version minSupportedVersion = Version.V_8_4_0; if (node.getVersion().before(minSupportedVersion)) { // This was introduced in 8.3.0 (and the action name changed in 8.4.0) logger.trace( "Cannot get master history for {} because it is at version {} and {} is required", node, node.getVersion(), minSupportedVersion ); return; } long startTime = System.nanoTime(); transportService.connectToNode( // Note: This connection must be explicitly closed below node, new ActionListener<>() { @Override public void onResponse(Releasable releasable) { logger.trace("Connected to {}, making master history request", node); // If we don't get a response in 10 seconds that is a failure worth capturing on its own: final TimeValue remoteMasterHistoryTimeout = TimeValue.timeValueSeconds(10); transportService.sendRequest( node, MasterHistoryAction.NAME, new MasterHistoryAction.Request(), TransportRequestOptions.timeout(remoteMasterHistoryTimeout), new ActionListenerResponseHandler<>(ActionListener.runBefore(new ActionListener<>() { @Override public void onResponse(MasterHistoryAction.Response response) { long endTime = System.nanoTime(); logger.trace("Received history from {} in {}", node, TimeValue.timeValueNanos(endTime - startTime)); remoteHistoryOrException = new RemoteHistoryOrException( response.getMasterHistory(), currentTimeMillisSupplier.getAsLong() ); } @Override public void onFailure(Exception e) { logger.warn("Exception in master history request to master node", e); remoteHistoryOrException = new RemoteHistoryOrException(e, currentTimeMillisSupplier.getAsLong()); } }, () -> Releasables.close(releasable)), MasterHistoryAction.Response::new, TransportResponseHandler.TRANSPORT_WORKER ) ); } @Override public void onFailure(Exception e) { logger.warn("Exception connecting to master node", e); remoteHistoryOrException = new RemoteHistoryOrException(e, currentTimeMillisSupplier.getAsLong()); } } ); } // non-private for testing record RemoteHistoryOrException(List<DiscoveryNode> remoteHistory, Exception exception, long creationTimeMillis) { public RemoteHistoryOrException { if (remoteHistory != null && exception != null) { throw new IllegalArgumentException("Remote history and exception cannot both be non-null"); } } RemoteHistoryOrException(List<DiscoveryNode> remoteHistory, long creationTimeMillis) { this(remoteHistory, null, creationTimeMillis); } RemoteHistoryOrException(Exception exception, long creationTimeMillis) { this(null, exception, creationTimeMillis); } } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/cluster/coordination/MasterHistoryService.java
44,922
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.index.engine; import org.apache.lucene.codecs.FieldsProducer; import org.apache.lucene.index.CodecReader; import org.apache.lucene.index.FilterCodecReader; import org.apache.lucene.index.FilterLeafReader; import org.apache.lucene.index.FilteredTermsEnum; import org.apache.lucene.index.ImpactsEnum; import org.apache.lucene.index.MergePolicy; import org.apache.lucene.index.OneMergeWrappingMergePolicy; import org.apache.lucene.index.PostingsEnum; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.search.DocIdSetIterator; import org.apache.lucene.util.Bits; import org.apache.lucene.util.BytesRef; import java.io.IOException; import java.util.Iterator; /** * This merge policy drops id field postings for all delete documents this can be * useful to guarantee consistent update performance even if a large number of deleted / updated documents * are retained. Merging postings away is efficient since lucene visits postings term by term and * with the original live-docs being available we are adding a negotiable overhead such that we can * prune soft-deletes by default. Yet, using this merge policy will cause loosing all search capabilities on top of * soft deleted documents independent of the retention policy. Note, in order for this merge policy to be effective it needs to be added * before the {@link org.apache.lucene.index.SoftDeletesRetentionMergePolicy} because otherwise only documents that are deleted / removed * anyways will be pruned. */ final class PrunePostingsMergePolicy extends OneMergeWrappingMergePolicy { PrunePostingsMergePolicy(MergePolicy in, String idField) { super(in, toWrap -> new OneMerge(toWrap.segments) { @Override public CodecReader wrapForMerge(CodecReader reader) throws IOException { CodecReader wrapped = toWrap.wrapForMerge(reader); return wrapReader(wrapped, idField); } }); } private static CodecReader wrapReader(CodecReader reader, String idField) { Bits liveDocs = reader.getLiveDocs(); if (liveDocs == null) { return reader; // no deleted docs - we are good! } final boolean fullyDeletedSegment = reader.numDocs() == 0; return new FilterCodecReader(reader) { @Override public FieldsProducer getPostingsReader() { FieldsProducer postingsReader = super.getPostingsReader(); if (postingsReader == null) { return null; } return new FieldsProducer() { @Override public void close() throws IOException { postingsReader.close(); } @Override public void checkIntegrity() throws IOException { postingsReader.checkIntegrity(); } @Override public Iterator<String> iterator() { return postingsReader.iterator(); } @Override public Terms terms(String field) throws IOException { Terms in = postingsReader.terms(field); if (idField.equals(field) && in != null) { return new FilterLeafReader.FilterTerms(in) { @Override public TermsEnum iterator() throws IOException { TermsEnum iterator = super.iterator(); return new FilteredTermsEnum(iterator, false) { private PostingsEnum internal; @Override protected AcceptStatus accept(BytesRef term) throws IOException { if (fullyDeletedSegment) { return AcceptStatus.END; // short-cut this if we don't match anything } internal = postings(internal, PostingsEnum.NONE); if (internal.nextDoc() != DocIdSetIterator.NO_MORE_DOCS) { return AcceptStatus.YES; } return AcceptStatus.NO; } @Override public PostingsEnum postings(PostingsEnum reuse, int flags) throws IOException { if (reuse instanceof OnlyLiveDocsPostingsEnum reuseInstance) { reuseInstance.reset(super.postings(reuseInstance.in, flags)); return reuseInstance; } return new OnlyLiveDocsPostingsEnum(super.postings(null, flags), liveDocs); } @Override public ImpactsEnum impacts(int flags) throws IOException { throw new UnsupportedOperationException(); } }; } }; } else { return in; } } @Override public int size() { return postingsReader.size(); } }; } @Override public CacheHelper getCoreCacheHelper() { return null; } @Override public CacheHelper getReaderCacheHelper() { return null; } }; } private static final class OnlyLiveDocsPostingsEnum extends PostingsEnum { private final Bits liveDocs; private PostingsEnum in; OnlyLiveDocsPostingsEnum(PostingsEnum in, Bits liveDocs) { this.liveDocs = liveDocs; reset(in); } void reset(PostingsEnum in) { this.in = in; } @Override public int docID() { return in.docID(); } @Override public int nextDoc() throws IOException { int docId; do { docId = in.nextDoc(); } while (docId != DocIdSetIterator.NO_MORE_DOCS && liveDocs.get(docId) == false); return docId; } @Override public int advance(int target) { throw new UnsupportedOperationException(); } @Override public long cost() { return in.cost(); } @Override public int freq() throws IOException { return in.freq(); } @Override public int nextPosition() throws IOException { return in.nextPosition(); } @Override public int startOffset() throws IOException { return in.startOffset(); } @Override public int endOffset() throws IOException { return in.endOffset(); } @Override public BytesRef getPayload() throws IOException { return in.getPayload(); } } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/index/engine/PrunePostingsMergePolicy.java
44,923
package com.macro.mall.model; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; public class OmsOrderExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public OmsOrderExample() { oredCriteria = new ArrayList<>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Long value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Long value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Long value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Long value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Long value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Long value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Long> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Long> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Long value1, Long value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Long value1, Long value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andMemberIdIsNull() { addCriterion("member_id is null"); return (Criteria) this; } public Criteria andMemberIdIsNotNull() { addCriterion("member_id is not null"); return (Criteria) this; } public Criteria andMemberIdEqualTo(Long value) { addCriterion("member_id =", value, "memberId"); return (Criteria) this; } public Criteria andMemberIdNotEqualTo(Long value) { addCriterion("member_id <>", value, "memberId"); return (Criteria) this; } public Criteria andMemberIdGreaterThan(Long value) { addCriterion("member_id >", value, "memberId"); return (Criteria) this; } public Criteria andMemberIdGreaterThanOrEqualTo(Long value) { addCriterion("member_id >=", value, "memberId"); return (Criteria) this; } public Criteria andMemberIdLessThan(Long value) { addCriterion("member_id <", value, "memberId"); return (Criteria) this; } public Criteria andMemberIdLessThanOrEqualTo(Long value) { addCriterion("member_id <=", value, "memberId"); return (Criteria) this; } public Criteria andMemberIdIn(List<Long> values) { addCriterion("member_id in", values, "memberId"); return (Criteria) this; } public Criteria andMemberIdNotIn(List<Long> values) { addCriterion("member_id not in", values, "memberId"); return (Criteria) this; } public Criteria andMemberIdBetween(Long value1, Long value2) { addCriterion("member_id between", value1, value2, "memberId"); return (Criteria) this; } public Criteria andMemberIdNotBetween(Long value1, Long value2) { addCriterion("member_id not between", value1, value2, "memberId"); return (Criteria) this; } public Criteria andCouponIdIsNull() { addCriterion("coupon_id is null"); return (Criteria) this; } public Criteria andCouponIdIsNotNull() { addCriterion("coupon_id is not null"); return (Criteria) this; } public Criteria andCouponIdEqualTo(Long value) { addCriterion("coupon_id =", value, "couponId"); return (Criteria) this; } public Criteria andCouponIdNotEqualTo(Long value) { addCriterion("coupon_id <>", value, "couponId"); return (Criteria) this; } public Criteria andCouponIdGreaterThan(Long value) { addCriterion("coupon_id >", value, "couponId"); return (Criteria) this; } public Criteria andCouponIdGreaterThanOrEqualTo(Long value) { addCriterion("coupon_id >=", value, "couponId"); return (Criteria) this; } public Criteria andCouponIdLessThan(Long value) { addCriterion("coupon_id <", value, "couponId"); return (Criteria) this; } public Criteria andCouponIdLessThanOrEqualTo(Long value) { addCriterion("coupon_id <=", value, "couponId"); return (Criteria) this; } public Criteria andCouponIdIn(List<Long> values) { addCriterion("coupon_id in", values, "couponId"); return (Criteria) this; } public Criteria andCouponIdNotIn(List<Long> values) { addCriterion("coupon_id not in", values, "couponId"); return (Criteria) this; } public Criteria andCouponIdBetween(Long value1, Long value2) { addCriterion("coupon_id between", value1, value2, "couponId"); return (Criteria) this; } public Criteria andCouponIdNotBetween(Long value1, Long value2) { addCriterion("coupon_id not between", value1, value2, "couponId"); return (Criteria) this; } public Criteria andOrderSnIsNull() { addCriterion("order_sn is null"); return (Criteria) this; } public Criteria andOrderSnIsNotNull() { addCriterion("order_sn is not null"); return (Criteria) this; } public Criteria andOrderSnEqualTo(String value) { addCriterion("order_sn =", value, "orderSn"); return (Criteria) this; } public Criteria andOrderSnNotEqualTo(String value) { addCriterion("order_sn <>", value, "orderSn"); return (Criteria) this; } public Criteria andOrderSnGreaterThan(String value) { addCriterion("order_sn >", value, "orderSn"); return (Criteria) this; } public Criteria andOrderSnGreaterThanOrEqualTo(String value) { addCriterion("order_sn >=", value, "orderSn"); return (Criteria) this; } public Criteria andOrderSnLessThan(String value) { addCriterion("order_sn <", value, "orderSn"); return (Criteria) this; } public Criteria andOrderSnLessThanOrEqualTo(String value) { addCriterion("order_sn <=", value, "orderSn"); return (Criteria) this; } public Criteria andOrderSnLike(String value) { addCriterion("order_sn like", value, "orderSn"); return (Criteria) this; } public Criteria andOrderSnNotLike(String value) { addCriterion("order_sn not like", value, "orderSn"); return (Criteria) this; } public Criteria andOrderSnIn(List<String> values) { addCriterion("order_sn in", values, "orderSn"); return (Criteria) this; } public Criteria andOrderSnNotIn(List<String> values) { addCriterion("order_sn not in", values, "orderSn"); return (Criteria) this; } public Criteria andOrderSnBetween(String value1, String value2) { addCriterion("order_sn between", value1, value2, "orderSn"); return (Criteria) this; } public Criteria andOrderSnNotBetween(String value1, String value2) { addCriterion("order_sn not between", value1, value2, "orderSn"); return (Criteria) this; } public Criteria andCreateTimeIsNull() { addCriterion("create_time is null"); return (Criteria) this; } public Criteria andCreateTimeIsNotNull() { addCriterion("create_time is not null"); return (Criteria) this; } public Criteria andCreateTimeEqualTo(Date value) { addCriterion("create_time =", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotEqualTo(Date value) { addCriterion("create_time <>", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThan(Date value) { addCriterion("create_time >", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) { addCriterion("create_time >=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThan(Date value) { addCriterion("create_time <", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThanOrEqualTo(Date value) { addCriterion("create_time <=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeIn(List<Date> values) { addCriterion("create_time in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotIn(List<Date> values) { addCriterion("create_time not in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeBetween(Date value1, Date value2) { addCriterion("create_time between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotBetween(Date value1, Date value2) { addCriterion("create_time not between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andMemberUsernameIsNull() { addCriterion("member_username is null"); return (Criteria) this; } public Criteria andMemberUsernameIsNotNull() { addCriterion("member_username is not null"); return (Criteria) this; } public Criteria andMemberUsernameEqualTo(String value) { addCriterion("member_username =", value, "memberUsername"); return (Criteria) this; } public Criteria andMemberUsernameNotEqualTo(String value) { addCriterion("member_username <>", value, "memberUsername"); return (Criteria) this; } public Criteria andMemberUsernameGreaterThan(String value) { addCriterion("member_username >", value, "memberUsername"); return (Criteria) this; } public Criteria andMemberUsernameGreaterThanOrEqualTo(String value) { addCriterion("member_username >=", value, "memberUsername"); return (Criteria) this; } public Criteria andMemberUsernameLessThan(String value) { addCriterion("member_username <", value, "memberUsername"); return (Criteria) this; } public Criteria andMemberUsernameLessThanOrEqualTo(String value) { addCriterion("member_username <=", value, "memberUsername"); return (Criteria) this; } public Criteria andMemberUsernameLike(String value) { addCriterion("member_username like", value, "memberUsername"); return (Criteria) this; } public Criteria andMemberUsernameNotLike(String value) { addCriterion("member_username not like", value, "memberUsername"); return (Criteria) this; } public Criteria andMemberUsernameIn(List<String> values) { addCriterion("member_username in", values, "memberUsername"); return (Criteria) this; } public Criteria andMemberUsernameNotIn(List<String> values) { addCriterion("member_username not in", values, "memberUsername"); return (Criteria) this; } public Criteria andMemberUsernameBetween(String value1, String value2) { addCriterion("member_username between", value1, value2, "memberUsername"); return (Criteria) this; } public Criteria andMemberUsernameNotBetween(String value1, String value2) { addCriterion("member_username not between", value1, value2, "memberUsername"); return (Criteria) this; } public Criteria andTotalAmountIsNull() { addCriterion("total_amount is null"); return (Criteria) this; } public Criteria andTotalAmountIsNotNull() { addCriterion("total_amount is not null"); return (Criteria) this; } public Criteria andTotalAmountEqualTo(BigDecimal value) { addCriterion("total_amount =", value, "totalAmount"); return (Criteria) this; } public Criteria andTotalAmountNotEqualTo(BigDecimal value) { addCriterion("total_amount <>", value, "totalAmount"); return (Criteria) this; } public Criteria andTotalAmountGreaterThan(BigDecimal value) { addCriterion("total_amount >", value, "totalAmount"); return (Criteria) this; } public Criteria andTotalAmountGreaterThanOrEqualTo(BigDecimal value) { addCriterion("total_amount >=", value, "totalAmount"); return (Criteria) this; } public Criteria andTotalAmountLessThan(BigDecimal value) { addCriterion("total_amount <", value, "totalAmount"); return (Criteria) this; } public Criteria andTotalAmountLessThanOrEqualTo(BigDecimal value) { addCriterion("total_amount <=", value, "totalAmount"); return (Criteria) this; } public Criteria andTotalAmountIn(List<BigDecimal> values) { addCriterion("total_amount in", values, "totalAmount"); return (Criteria) this; } public Criteria andTotalAmountNotIn(List<BigDecimal> values) { addCriterion("total_amount not in", values, "totalAmount"); return (Criteria) this; } public Criteria andTotalAmountBetween(BigDecimal value1, BigDecimal value2) { addCriterion("total_amount between", value1, value2, "totalAmount"); return (Criteria) this; } public Criteria andTotalAmountNotBetween(BigDecimal value1, BigDecimal value2) { addCriterion("total_amount not between", value1, value2, "totalAmount"); return (Criteria) this; } public Criteria andPayAmountIsNull() { addCriterion("pay_amount is null"); return (Criteria) this; } public Criteria andPayAmountIsNotNull() { addCriterion("pay_amount is not null"); return (Criteria) this; } public Criteria andPayAmountEqualTo(BigDecimal value) { addCriterion("pay_amount =", value, "payAmount"); return (Criteria) this; } public Criteria andPayAmountNotEqualTo(BigDecimal value) { addCriterion("pay_amount <>", value, "payAmount"); return (Criteria) this; } public Criteria andPayAmountGreaterThan(BigDecimal value) { addCriterion("pay_amount >", value, "payAmount"); return (Criteria) this; } public Criteria andPayAmountGreaterThanOrEqualTo(BigDecimal value) { addCriterion("pay_amount >=", value, "payAmount"); return (Criteria) this; } public Criteria andPayAmountLessThan(BigDecimal value) { addCriterion("pay_amount <", value, "payAmount"); return (Criteria) this; } public Criteria andPayAmountLessThanOrEqualTo(BigDecimal value) { addCriterion("pay_amount <=", value, "payAmount"); return (Criteria) this; } public Criteria andPayAmountIn(List<BigDecimal> values) { addCriterion("pay_amount in", values, "payAmount"); return (Criteria) this; } public Criteria andPayAmountNotIn(List<BigDecimal> values) { addCriterion("pay_amount not in", values, "payAmount"); return (Criteria) this; } public Criteria andPayAmountBetween(BigDecimal value1, BigDecimal value2) { addCriterion("pay_amount between", value1, value2, "payAmount"); return (Criteria) this; } public Criteria andPayAmountNotBetween(BigDecimal value1, BigDecimal value2) { addCriterion("pay_amount not between", value1, value2, "payAmount"); return (Criteria) this; } public Criteria andFreightAmountIsNull() { addCriterion("freight_amount is null"); return (Criteria) this; } public Criteria andFreightAmountIsNotNull() { addCriterion("freight_amount is not null"); return (Criteria) this; } public Criteria andFreightAmountEqualTo(BigDecimal value) { addCriterion("freight_amount =", value, "freightAmount"); return (Criteria) this; } public Criteria andFreightAmountNotEqualTo(BigDecimal value) { addCriterion("freight_amount <>", value, "freightAmount"); return (Criteria) this; } public Criteria andFreightAmountGreaterThan(BigDecimal value) { addCriterion("freight_amount >", value, "freightAmount"); return (Criteria) this; } public Criteria andFreightAmountGreaterThanOrEqualTo(BigDecimal value) { addCriterion("freight_amount >=", value, "freightAmount"); return (Criteria) this; } public Criteria andFreightAmountLessThan(BigDecimal value) { addCriterion("freight_amount <", value, "freightAmount"); return (Criteria) this; } public Criteria andFreightAmountLessThanOrEqualTo(BigDecimal value) { addCriterion("freight_amount <=", value, "freightAmount"); return (Criteria) this; } public Criteria andFreightAmountIn(List<BigDecimal> values) { addCriterion("freight_amount in", values, "freightAmount"); return (Criteria) this; } public Criteria andFreightAmountNotIn(List<BigDecimal> values) { addCriterion("freight_amount not in", values, "freightAmount"); return (Criteria) this; } public Criteria andFreightAmountBetween(BigDecimal value1, BigDecimal value2) { addCriterion("freight_amount between", value1, value2, "freightAmount"); return (Criteria) this; } public Criteria andFreightAmountNotBetween(BigDecimal value1, BigDecimal value2) { addCriterion("freight_amount not between", value1, value2, "freightAmount"); return (Criteria) this; } public Criteria andPromotionAmountIsNull() { addCriterion("promotion_amount is null"); return (Criteria) this; } public Criteria andPromotionAmountIsNotNull() { addCriterion("promotion_amount is not null"); return (Criteria) this; } public Criteria andPromotionAmountEqualTo(BigDecimal value) { addCriterion("promotion_amount =", value, "promotionAmount"); return (Criteria) this; } public Criteria andPromotionAmountNotEqualTo(BigDecimal value) { addCriterion("promotion_amount <>", value, "promotionAmount"); return (Criteria) this; } public Criteria andPromotionAmountGreaterThan(BigDecimal value) { addCriterion("promotion_amount >", value, "promotionAmount"); return (Criteria) this; } public Criteria andPromotionAmountGreaterThanOrEqualTo(BigDecimal value) { addCriterion("promotion_amount >=", value, "promotionAmount"); return (Criteria) this; } public Criteria andPromotionAmountLessThan(BigDecimal value) { addCriterion("promotion_amount <", value, "promotionAmount"); return (Criteria) this; } public Criteria andPromotionAmountLessThanOrEqualTo(BigDecimal value) { addCriterion("promotion_amount <=", value, "promotionAmount"); return (Criteria) this; } public Criteria andPromotionAmountIn(List<BigDecimal> values) { addCriterion("promotion_amount in", values, "promotionAmount"); return (Criteria) this; } public Criteria andPromotionAmountNotIn(List<BigDecimal> values) { addCriterion("promotion_amount not in", values, "promotionAmount"); return (Criteria) this; } public Criteria andPromotionAmountBetween(BigDecimal value1, BigDecimal value2) { addCriterion("promotion_amount between", value1, value2, "promotionAmount"); return (Criteria) this; } public Criteria andPromotionAmountNotBetween(BigDecimal value1, BigDecimal value2) { addCriterion("promotion_amount not between", value1, value2, "promotionAmount"); return (Criteria) this; } public Criteria andIntegrationAmountIsNull() { addCriterion("integration_amount is null"); return (Criteria) this; } public Criteria andIntegrationAmountIsNotNull() { addCriterion("integration_amount is not null"); return (Criteria) this; } public Criteria andIntegrationAmountEqualTo(BigDecimal value) { addCriterion("integration_amount =", value, "integrationAmount"); return (Criteria) this; } public Criteria andIntegrationAmountNotEqualTo(BigDecimal value) { addCriterion("integration_amount <>", value, "integrationAmount"); return (Criteria) this; } public Criteria andIntegrationAmountGreaterThan(BigDecimal value) { addCriterion("integration_amount >", value, "integrationAmount"); return (Criteria) this; } public Criteria andIntegrationAmountGreaterThanOrEqualTo(BigDecimal value) { addCriterion("integration_amount >=", value, "integrationAmount"); return (Criteria) this; } public Criteria andIntegrationAmountLessThan(BigDecimal value) { addCriterion("integration_amount <", value, "integrationAmount"); return (Criteria) this; } public Criteria andIntegrationAmountLessThanOrEqualTo(BigDecimal value) { addCriterion("integration_amount <=", value, "integrationAmount"); return (Criteria) this; } public Criteria andIntegrationAmountIn(List<BigDecimal> values) { addCriterion("integration_amount in", values, "integrationAmount"); return (Criteria) this; } public Criteria andIntegrationAmountNotIn(List<BigDecimal> values) { addCriterion("integration_amount not in", values, "integrationAmount"); return (Criteria) this; } public Criteria andIntegrationAmountBetween(BigDecimal value1, BigDecimal value2) { addCriterion("integration_amount between", value1, value2, "integrationAmount"); return (Criteria) this; } public Criteria andIntegrationAmountNotBetween(BigDecimal value1, BigDecimal value2) { addCriterion("integration_amount not between", value1, value2, "integrationAmount"); return (Criteria) this; } public Criteria andCouponAmountIsNull() { addCriterion("coupon_amount is null"); return (Criteria) this; } public Criteria andCouponAmountIsNotNull() { addCriterion("coupon_amount is not null"); return (Criteria) this; } public Criteria andCouponAmountEqualTo(BigDecimal value) { addCriterion("coupon_amount =", value, "couponAmount"); return (Criteria) this; } public Criteria andCouponAmountNotEqualTo(BigDecimal value) { addCriterion("coupon_amount <>", value, "couponAmount"); return (Criteria) this; } public Criteria andCouponAmountGreaterThan(BigDecimal value) { addCriterion("coupon_amount >", value, "couponAmount"); return (Criteria) this; } public Criteria andCouponAmountGreaterThanOrEqualTo(BigDecimal value) { addCriterion("coupon_amount >=", value, "couponAmount"); return (Criteria) this; } public Criteria andCouponAmountLessThan(BigDecimal value) { addCriterion("coupon_amount <", value, "couponAmount"); return (Criteria) this; } public Criteria andCouponAmountLessThanOrEqualTo(BigDecimal value) { addCriterion("coupon_amount <=", value, "couponAmount"); return (Criteria) this; } public Criteria andCouponAmountIn(List<BigDecimal> values) { addCriterion("coupon_amount in", values, "couponAmount"); return (Criteria) this; } public Criteria andCouponAmountNotIn(List<BigDecimal> values) { addCriterion("coupon_amount not in", values, "couponAmount"); return (Criteria) this; } public Criteria andCouponAmountBetween(BigDecimal value1, BigDecimal value2) { addCriterion("coupon_amount between", value1, value2, "couponAmount"); return (Criteria) this; } public Criteria andCouponAmountNotBetween(BigDecimal value1, BigDecimal value2) { addCriterion("coupon_amount not between", value1, value2, "couponAmount"); return (Criteria) this; } public Criteria andDiscountAmountIsNull() { addCriterion("discount_amount is null"); return (Criteria) this; } public Criteria andDiscountAmountIsNotNull() { addCriterion("discount_amount is not null"); return (Criteria) this; } public Criteria andDiscountAmountEqualTo(BigDecimal value) { addCriterion("discount_amount =", value, "discountAmount"); return (Criteria) this; } public Criteria andDiscountAmountNotEqualTo(BigDecimal value) { addCriterion("discount_amount <>", value, "discountAmount"); return (Criteria) this; } public Criteria andDiscountAmountGreaterThan(BigDecimal value) { addCriterion("discount_amount >", value, "discountAmount"); return (Criteria) this; } public Criteria andDiscountAmountGreaterThanOrEqualTo(BigDecimal value) { addCriterion("discount_amount >=", value, "discountAmount"); return (Criteria) this; } public Criteria andDiscountAmountLessThan(BigDecimal value) { addCriterion("discount_amount <", value, "discountAmount"); return (Criteria) this; } public Criteria andDiscountAmountLessThanOrEqualTo(BigDecimal value) { addCriterion("discount_amount <=", value, "discountAmount"); return (Criteria) this; } public Criteria andDiscountAmountIn(List<BigDecimal> values) { addCriterion("discount_amount in", values, "discountAmount"); return (Criteria) this; } public Criteria andDiscountAmountNotIn(List<BigDecimal> values) { addCriterion("discount_amount not in", values, "discountAmount"); return (Criteria) this; } public Criteria andDiscountAmountBetween(BigDecimal value1, BigDecimal value2) { addCriterion("discount_amount between", value1, value2, "discountAmount"); return (Criteria) this; } public Criteria andDiscountAmountNotBetween(BigDecimal value1, BigDecimal value2) { addCriterion("discount_amount not between", value1, value2, "discountAmount"); return (Criteria) this; } public Criteria andPayTypeIsNull() { addCriterion("pay_type is null"); return (Criteria) this; } public Criteria andPayTypeIsNotNull() { addCriterion("pay_type is not null"); return (Criteria) this; } public Criteria andPayTypeEqualTo(Integer value) { addCriterion("pay_type =", value, "payType"); return (Criteria) this; } public Criteria andPayTypeNotEqualTo(Integer value) { addCriterion("pay_type <>", value, "payType"); return (Criteria) this; } public Criteria andPayTypeGreaterThan(Integer value) { addCriterion("pay_type >", value, "payType"); return (Criteria) this; } public Criteria andPayTypeGreaterThanOrEqualTo(Integer value) { addCriterion("pay_type >=", value, "payType"); return (Criteria) this; } public Criteria andPayTypeLessThan(Integer value) { addCriterion("pay_type <", value, "payType"); return (Criteria) this; } public Criteria andPayTypeLessThanOrEqualTo(Integer value) { addCriterion("pay_type <=", value, "payType"); return (Criteria) this; } public Criteria andPayTypeIn(List<Integer> values) { addCriterion("pay_type in", values, "payType"); return (Criteria) this; } public Criteria andPayTypeNotIn(List<Integer> values) { addCriterion("pay_type not in", values, "payType"); return (Criteria) this; } public Criteria andPayTypeBetween(Integer value1, Integer value2) { addCriterion("pay_type between", value1, value2, "payType"); return (Criteria) this; } public Criteria andPayTypeNotBetween(Integer value1, Integer value2) { addCriterion("pay_type not between", value1, value2, "payType"); return (Criteria) this; } public Criteria andSourceTypeIsNull() { addCriterion("source_type is null"); return (Criteria) this; } public Criteria andSourceTypeIsNotNull() { addCriterion("source_type is not null"); return (Criteria) this; } public Criteria andSourceTypeEqualTo(Integer value) { addCriterion("source_type =", value, "sourceType"); return (Criteria) this; } public Criteria andSourceTypeNotEqualTo(Integer value) { addCriterion("source_type <>", value, "sourceType"); return (Criteria) this; } public Criteria andSourceTypeGreaterThan(Integer value) { addCriterion("source_type >", value, "sourceType"); return (Criteria) this; } public Criteria andSourceTypeGreaterThanOrEqualTo(Integer value) { addCriterion("source_type >=", value, "sourceType"); return (Criteria) this; } public Criteria andSourceTypeLessThan(Integer value) { addCriterion("source_type <", value, "sourceType"); return (Criteria) this; } public Criteria andSourceTypeLessThanOrEqualTo(Integer value) { addCriterion("source_type <=", value, "sourceType"); return (Criteria) this; } public Criteria andSourceTypeIn(List<Integer> values) { addCriterion("source_type in", values, "sourceType"); return (Criteria) this; } public Criteria andSourceTypeNotIn(List<Integer> values) { addCriterion("source_type not in", values, "sourceType"); return (Criteria) this; } public Criteria andSourceTypeBetween(Integer value1, Integer value2) { addCriterion("source_type between", value1, value2, "sourceType"); return (Criteria) this; } public Criteria andSourceTypeNotBetween(Integer value1, Integer value2) { addCriterion("source_type not between", value1, value2, "sourceType"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("status is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("status is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(Integer value) { addCriterion("status =", value, "status"); return (Criteria) this; } public Criteria andStatusNotEqualTo(Integer value) { addCriterion("status <>", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThan(Integer value) { addCriterion("status >", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(Integer value) { addCriterion("status >=", value, "status"); return (Criteria) this; } public Criteria andStatusLessThan(Integer value) { addCriterion("status <", value, "status"); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(Integer value) { addCriterion("status <=", value, "status"); return (Criteria) this; } public Criteria andStatusIn(List<Integer> values) { addCriterion("status in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List<Integer> values) { addCriterion("status not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(Integer value1, Integer value2) { addCriterion("status between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(Integer value1, Integer value2) { addCriterion("status not between", value1, value2, "status"); return (Criteria) this; } public Criteria andOrderTypeIsNull() { addCriterion("order_type is null"); return (Criteria) this; } public Criteria andOrderTypeIsNotNull() { addCriterion("order_type is not null"); return (Criteria) this; } public Criteria andOrderTypeEqualTo(Integer value) { addCriterion("order_type =", value, "orderType"); return (Criteria) this; } public Criteria andOrderTypeNotEqualTo(Integer value) { addCriterion("order_type <>", value, "orderType"); return (Criteria) this; } public Criteria andOrderTypeGreaterThan(Integer value) { addCriterion("order_type >", value, "orderType"); return (Criteria) this; } public Criteria andOrderTypeGreaterThanOrEqualTo(Integer value) { addCriterion("order_type >=", value, "orderType"); return (Criteria) this; } public Criteria andOrderTypeLessThan(Integer value) { addCriterion("order_type <", value, "orderType"); return (Criteria) this; } public Criteria andOrderTypeLessThanOrEqualTo(Integer value) { addCriterion("order_type <=", value, "orderType"); return (Criteria) this; } public Criteria andOrderTypeIn(List<Integer> values) { addCriterion("order_type in", values, "orderType"); return (Criteria) this; } public Criteria andOrderTypeNotIn(List<Integer> values) { addCriterion("order_type not in", values, "orderType"); return (Criteria) this; } public Criteria andOrderTypeBetween(Integer value1, Integer value2) { addCriterion("order_type between", value1, value2, "orderType"); return (Criteria) this; } public Criteria andOrderTypeNotBetween(Integer value1, Integer value2) { addCriterion("order_type not between", value1, value2, "orderType"); return (Criteria) this; } public Criteria andDeliveryCompanyIsNull() { addCriterion("delivery_company is null"); return (Criteria) this; } public Criteria andDeliveryCompanyIsNotNull() { addCriterion("delivery_company is not null"); return (Criteria) this; } public Criteria andDeliveryCompanyEqualTo(String value) { addCriterion("delivery_company =", value, "deliveryCompany"); return (Criteria) this; } public Criteria andDeliveryCompanyNotEqualTo(String value) { addCriterion("delivery_company <>", value, "deliveryCompany"); return (Criteria) this; } public Criteria andDeliveryCompanyGreaterThan(String value) { addCriterion("delivery_company >", value, "deliveryCompany"); return (Criteria) this; } public Criteria andDeliveryCompanyGreaterThanOrEqualTo(String value) { addCriterion("delivery_company >=", value, "deliveryCompany"); return (Criteria) this; } public Criteria andDeliveryCompanyLessThan(String value) { addCriterion("delivery_company <", value, "deliveryCompany"); return (Criteria) this; } public Criteria andDeliveryCompanyLessThanOrEqualTo(String value) { addCriterion("delivery_company <=", value, "deliveryCompany"); return (Criteria) this; } public Criteria andDeliveryCompanyLike(String value) { addCriterion("delivery_company like", value, "deliveryCompany"); return (Criteria) this; } public Criteria andDeliveryCompanyNotLike(String value) { addCriterion("delivery_company not like", value, "deliveryCompany"); return (Criteria) this; } public Criteria andDeliveryCompanyIn(List<String> values) { addCriterion("delivery_company in", values, "deliveryCompany"); return (Criteria) this; } public Criteria andDeliveryCompanyNotIn(List<String> values) { addCriterion("delivery_company not in", values, "deliveryCompany"); return (Criteria) this; } public Criteria andDeliveryCompanyBetween(String value1, String value2) { addCriterion("delivery_company between", value1, value2, "deliveryCompany"); return (Criteria) this; } public Criteria andDeliveryCompanyNotBetween(String value1, String value2) { addCriterion("delivery_company not between", value1, value2, "deliveryCompany"); return (Criteria) this; } public Criteria andDeliverySnIsNull() { addCriterion("delivery_sn is null"); return (Criteria) this; } public Criteria andDeliverySnIsNotNull() { addCriterion("delivery_sn is not null"); return (Criteria) this; } public Criteria andDeliverySnEqualTo(String value) { addCriterion("delivery_sn =", value, "deliverySn"); return (Criteria) this; } public Criteria andDeliverySnNotEqualTo(String value) { addCriterion("delivery_sn <>", value, "deliverySn"); return (Criteria) this; } public Criteria andDeliverySnGreaterThan(String value) { addCriterion("delivery_sn >", value, "deliverySn"); return (Criteria) this; } public Criteria andDeliverySnGreaterThanOrEqualTo(String value) { addCriterion("delivery_sn >=", value, "deliverySn"); return (Criteria) this; } public Criteria andDeliverySnLessThan(String value) { addCriterion("delivery_sn <", value, "deliverySn"); return (Criteria) this; } public Criteria andDeliverySnLessThanOrEqualTo(String value) { addCriterion("delivery_sn <=", value, "deliverySn"); return (Criteria) this; } public Criteria andDeliverySnLike(String value) { addCriterion("delivery_sn like", value, "deliverySn"); return (Criteria) this; } public Criteria andDeliverySnNotLike(String value) { addCriterion("delivery_sn not like", value, "deliverySn"); return (Criteria) this; } public Criteria andDeliverySnIn(List<String> values) { addCriterion("delivery_sn in", values, "deliverySn"); return (Criteria) this; } public Criteria andDeliverySnNotIn(List<String> values) { addCriterion("delivery_sn not in", values, "deliverySn"); return (Criteria) this; } public Criteria andDeliverySnBetween(String value1, String value2) { addCriterion("delivery_sn between", value1, value2, "deliverySn"); return (Criteria) this; } public Criteria andDeliverySnNotBetween(String value1, String value2) { addCriterion("delivery_sn not between", value1, value2, "deliverySn"); return (Criteria) this; } public Criteria andAutoConfirmDayIsNull() { addCriterion("auto_confirm_day is null"); return (Criteria) this; } public Criteria andAutoConfirmDayIsNotNull() { addCriterion("auto_confirm_day is not null"); return (Criteria) this; } public Criteria andAutoConfirmDayEqualTo(Integer value) { addCriterion("auto_confirm_day =", value, "autoConfirmDay"); return (Criteria) this; } public Criteria andAutoConfirmDayNotEqualTo(Integer value) { addCriterion("auto_confirm_day <>", value, "autoConfirmDay"); return (Criteria) this; } public Criteria andAutoConfirmDayGreaterThan(Integer value) { addCriterion("auto_confirm_day >", value, "autoConfirmDay"); return (Criteria) this; } public Criteria andAutoConfirmDayGreaterThanOrEqualTo(Integer value) { addCriterion("auto_confirm_day >=", value, "autoConfirmDay"); return (Criteria) this; } public Criteria andAutoConfirmDayLessThan(Integer value) { addCriterion("auto_confirm_day <", value, "autoConfirmDay"); return (Criteria) this; } public Criteria andAutoConfirmDayLessThanOrEqualTo(Integer value) { addCriterion("auto_confirm_day <=", value, "autoConfirmDay"); return (Criteria) this; } public Criteria andAutoConfirmDayIn(List<Integer> values) { addCriterion("auto_confirm_day in", values, "autoConfirmDay"); return (Criteria) this; } public Criteria andAutoConfirmDayNotIn(List<Integer> values) { addCriterion("auto_confirm_day not in", values, "autoConfirmDay"); return (Criteria) this; } public Criteria andAutoConfirmDayBetween(Integer value1, Integer value2) { addCriterion("auto_confirm_day between", value1, value2, "autoConfirmDay"); return (Criteria) this; } public Criteria andAutoConfirmDayNotBetween(Integer value1, Integer value2) { addCriterion("auto_confirm_day not between", value1, value2, "autoConfirmDay"); return (Criteria) this; } public Criteria andIntegrationIsNull() { addCriterion("integration is null"); return (Criteria) this; } public Criteria andIntegrationIsNotNull() { addCriterion("integration is not null"); return (Criteria) this; } public Criteria andIntegrationEqualTo(Integer value) { addCriterion("integration =", value, "integration"); return (Criteria) this; } public Criteria andIntegrationNotEqualTo(Integer value) { addCriterion("integration <>", value, "integration"); return (Criteria) this; } public Criteria andIntegrationGreaterThan(Integer value) { addCriterion("integration >", value, "integration"); return (Criteria) this; } public Criteria andIntegrationGreaterThanOrEqualTo(Integer value) { addCriterion("integration >=", value, "integration"); return (Criteria) this; } public Criteria andIntegrationLessThan(Integer value) { addCriterion("integration <", value, "integration"); return (Criteria) this; } public Criteria andIntegrationLessThanOrEqualTo(Integer value) { addCriterion("integration <=", value, "integration"); return (Criteria) this; } public Criteria andIntegrationIn(List<Integer> values) { addCriterion("integration in", values, "integration"); return (Criteria) this; } public Criteria andIntegrationNotIn(List<Integer> values) { addCriterion("integration not in", values, "integration"); return (Criteria) this; } public Criteria andIntegrationBetween(Integer value1, Integer value2) { addCriterion("integration between", value1, value2, "integration"); return (Criteria) this; } public Criteria andIntegrationNotBetween(Integer value1, Integer value2) { addCriterion("integration not between", value1, value2, "integration"); return (Criteria) this; } public Criteria andGrowthIsNull() { addCriterion("growth is null"); return (Criteria) this; } public Criteria andGrowthIsNotNull() { addCriterion("growth is not null"); return (Criteria) this; } public Criteria andGrowthEqualTo(Integer value) { addCriterion("growth =", value, "growth"); return (Criteria) this; } public Criteria andGrowthNotEqualTo(Integer value) { addCriterion("growth <>", value, "growth"); return (Criteria) this; } public Criteria andGrowthGreaterThan(Integer value) { addCriterion("growth >", value, "growth"); return (Criteria) this; } public Criteria andGrowthGreaterThanOrEqualTo(Integer value) { addCriterion("growth >=", value, "growth"); return (Criteria) this; } public Criteria andGrowthLessThan(Integer value) { addCriterion("growth <", value, "growth"); return (Criteria) this; } public Criteria andGrowthLessThanOrEqualTo(Integer value) { addCriterion("growth <=", value, "growth"); return (Criteria) this; } public Criteria andGrowthIn(List<Integer> values) { addCriterion("growth in", values, "growth"); return (Criteria) this; } public Criteria andGrowthNotIn(List<Integer> values) { addCriterion("growth not in", values, "growth"); return (Criteria) this; } public Criteria andGrowthBetween(Integer value1, Integer value2) { addCriterion("growth between", value1, value2, "growth"); return (Criteria) this; } public Criteria andGrowthNotBetween(Integer value1, Integer value2) { addCriterion("growth not between", value1, value2, "growth"); return (Criteria) this; } public Criteria andPromotionInfoIsNull() { addCriterion("promotion_info is null"); return (Criteria) this; } public Criteria andPromotionInfoIsNotNull() { addCriterion("promotion_info is not null"); return (Criteria) this; } public Criteria andPromotionInfoEqualTo(String value) { addCriterion("promotion_info =", value, "promotionInfo"); return (Criteria) this; } public Criteria andPromotionInfoNotEqualTo(String value) { addCriterion("promotion_info <>", value, "promotionInfo"); return (Criteria) this; } public Criteria andPromotionInfoGreaterThan(String value) { addCriterion("promotion_info >", value, "promotionInfo"); return (Criteria) this; } public Criteria andPromotionInfoGreaterThanOrEqualTo(String value) { addCriterion("promotion_info >=", value, "promotionInfo"); return (Criteria) this; } public Criteria andPromotionInfoLessThan(String value) { addCriterion("promotion_info <", value, "promotionInfo"); return (Criteria) this; } public Criteria andPromotionInfoLessThanOrEqualTo(String value) { addCriterion("promotion_info <=", value, "promotionInfo"); return (Criteria) this; } public Criteria andPromotionInfoLike(String value) { addCriterion("promotion_info like", value, "promotionInfo"); return (Criteria) this; } public Criteria andPromotionInfoNotLike(String value) { addCriterion("promotion_info not like", value, "promotionInfo"); return (Criteria) this; } public Criteria andPromotionInfoIn(List<String> values) { addCriterion("promotion_info in", values, "promotionInfo"); return (Criteria) this; } public Criteria andPromotionInfoNotIn(List<String> values) { addCriterion("promotion_info not in", values, "promotionInfo"); return (Criteria) this; } public Criteria andPromotionInfoBetween(String value1, String value2) { addCriterion("promotion_info between", value1, value2, "promotionInfo"); return (Criteria) this; } public Criteria andPromotionInfoNotBetween(String value1, String value2) { addCriterion("promotion_info not between", value1, value2, "promotionInfo"); return (Criteria) this; } public Criteria andBillTypeIsNull() { addCriterion("bill_type is null"); return (Criteria) this; } public Criteria andBillTypeIsNotNull() { addCriterion("bill_type is not null"); return (Criteria) this; } public Criteria andBillTypeEqualTo(Integer value) { addCriterion("bill_type =", value, "billType"); return (Criteria) this; } public Criteria andBillTypeNotEqualTo(Integer value) { addCriterion("bill_type <>", value, "billType"); return (Criteria) this; } public Criteria andBillTypeGreaterThan(Integer value) { addCriterion("bill_type >", value, "billType"); return (Criteria) this; } public Criteria andBillTypeGreaterThanOrEqualTo(Integer value) { addCriterion("bill_type >=", value, "billType"); return (Criteria) this; } public Criteria andBillTypeLessThan(Integer value) { addCriterion("bill_type <", value, "billType"); return (Criteria) this; } public Criteria andBillTypeLessThanOrEqualTo(Integer value) { addCriterion("bill_type <=", value, "billType"); return (Criteria) this; } public Criteria andBillTypeIn(List<Integer> values) { addCriterion("bill_type in", values, "billType"); return (Criteria) this; } public Criteria andBillTypeNotIn(List<Integer> values) { addCriterion("bill_type not in", values, "billType"); return (Criteria) this; } public Criteria andBillTypeBetween(Integer value1, Integer value2) { addCriterion("bill_type between", value1, value2, "billType"); return (Criteria) this; } public Criteria andBillTypeNotBetween(Integer value1, Integer value2) { addCriterion("bill_type not between", value1, value2, "billType"); return (Criteria) this; } public Criteria andBillHeaderIsNull() { addCriterion("bill_header is null"); return (Criteria) this; } public Criteria andBillHeaderIsNotNull() { addCriterion("bill_header is not null"); return (Criteria) this; } public Criteria andBillHeaderEqualTo(String value) { addCriterion("bill_header =", value, "billHeader"); return (Criteria) this; } public Criteria andBillHeaderNotEqualTo(String value) { addCriterion("bill_header <>", value, "billHeader"); return (Criteria) this; } public Criteria andBillHeaderGreaterThan(String value) { addCriterion("bill_header >", value, "billHeader"); return (Criteria) this; } public Criteria andBillHeaderGreaterThanOrEqualTo(String value) { addCriterion("bill_header >=", value, "billHeader"); return (Criteria) this; } public Criteria andBillHeaderLessThan(String value) { addCriterion("bill_header <", value, "billHeader"); return (Criteria) this; } public Criteria andBillHeaderLessThanOrEqualTo(String value) { addCriterion("bill_header <=", value, "billHeader"); return (Criteria) this; } public Criteria andBillHeaderLike(String value) { addCriterion("bill_header like", value, "billHeader"); return (Criteria) this; } public Criteria andBillHeaderNotLike(String value) { addCriterion("bill_header not like", value, "billHeader"); return (Criteria) this; } public Criteria andBillHeaderIn(List<String> values) { addCriterion("bill_header in", values, "billHeader"); return (Criteria) this; } public Criteria andBillHeaderNotIn(List<String> values) { addCriterion("bill_header not in", values, "billHeader"); return (Criteria) this; } public Criteria andBillHeaderBetween(String value1, String value2) { addCriterion("bill_header between", value1, value2, "billHeader"); return (Criteria) this; } public Criteria andBillHeaderNotBetween(String value1, String value2) { addCriterion("bill_header not between", value1, value2, "billHeader"); return (Criteria) this; } public Criteria andBillContentIsNull() { addCriterion("bill_content is null"); return (Criteria) this; } public Criteria andBillContentIsNotNull() { addCriterion("bill_content is not null"); return (Criteria) this; } public Criteria andBillContentEqualTo(String value) { addCriterion("bill_content =", value, "billContent"); return (Criteria) this; } public Criteria andBillContentNotEqualTo(String value) { addCriterion("bill_content <>", value, "billContent"); return (Criteria) this; } public Criteria andBillContentGreaterThan(String value) { addCriterion("bill_content >", value, "billContent"); return (Criteria) this; } public Criteria andBillContentGreaterThanOrEqualTo(String value) { addCriterion("bill_content >=", value, "billContent"); return (Criteria) this; } public Criteria andBillContentLessThan(String value) { addCriterion("bill_content <", value, "billContent"); return (Criteria) this; } public Criteria andBillContentLessThanOrEqualTo(String value) { addCriterion("bill_content <=", value, "billContent"); return (Criteria) this; } public Criteria andBillContentLike(String value) { addCriterion("bill_content like", value, "billContent"); return (Criteria) this; } public Criteria andBillContentNotLike(String value) { addCriterion("bill_content not like", value, "billContent"); return (Criteria) this; } public Criteria andBillContentIn(List<String> values) { addCriterion("bill_content in", values, "billContent"); return (Criteria) this; } public Criteria andBillContentNotIn(List<String> values) { addCriterion("bill_content not in", values, "billContent"); return (Criteria) this; } public Criteria andBillContentBetween(String value1, String value2) { addCriterion("bill_content between", value1, value2, "billContent"); return (Criteria) this; } public Criteria andBillContentNotBetween(String value1, String value2) { addCriterion("bill_content not between", value1, value2, "billContent"); return (Criteria) this; } public Criteria andBillReceiverPhoneIsNull() { addCriterion("bill_receiver_phone is null"); return (Criteria) this; } public Criteria andBillReceiverPhoneIsNotNull() { addCriterion("bill_receiver_phone is not null"); return (Criteria) this; } public Criteria andBillReceiverPhoneEqualTo(String value) { addCriterion("bill_receiver_phone =", value, "billReceiverPhone"); return (Criteria) this; } public Criteria andBillReceiverPhoneNotEqualTo(String value) { addCriterion("bill_receiver_phone <>", value, "billReceiverPhone"); return (Criteria) this; } public Criteria andBillReceiverPhoneGreaterThan(String value) { addCriterion("bill_receiver_phone >", value, "billReceiverPhone"); return (Criteria) this; } public Criteria andBillReceiverPhoneGreaterThanOrEqualTo(String value) { addCriterion("bill_receiver_phone >=", value, "billReceiverPhone"); return (Criteria) this; } public Criteria andBillReceiverPhoneLessThan(String value) { addCriterion("bill_receiver_phone <", value, "billReceiverPhone"); return (Criteria) this; } public Criteria andBillReceiverPhoneLessThanOrEqualTo(String value) { addCriterion("bill_receiver_phone <=", value, "billReceiverPhone"); return (Criteria) this; } public Criteria andBillReceiverPhoneLike(String value) { addCriterion("bill_receiver_phone like", value, "billReceiverPhone"); return (Criteria) this; } public Criteria andBillReceiverPhoneNotLike(String value) { addCriterion("bill_receiver_phone not like", value, "billReceiverPhone"); return (Criteria) this; } public Criteria andBillReceiverPhoneIn(List<String> values) { addCriterion("bill_receiver_phone in", values, "billReceiverPhone"); return (Criteria) this; } public Criteria andBillReceiverPhoneNotIn(List<String> values) { addCriterion("bill_receiver_phone not in", values, "billReceiverPhone"); return (Criteria) this; } public Criteria andBillReceiverPhoneBetween(String value1, String value2) { addCriterion("bill_receiver_phone between", value1, value2, "billReceiverPhone"); return (Criteria) this; } public Criteria andBillReceiverPhoneNotBetween(String value1, String value2) { addCriterion("bill_receiver_phone not between", value1, value2, "billReceiverPhone"); return (Criteria) this; } public Criteria andBillReceiverEmailIsNull() { addCriterion("bill_receiver_email is null"); return (Criteria) this; } public Criteria andBillReceiverEmailIsNotNull() { addCriterion("bill_receiver_email is not null"); return (Criteria) this; } public Criteria andBillReceiverEmailEqualTo(String value) { addCriterion("bill_receiver_email =", value, "billReceiverEmail"); return (Criteria) this; } public Criteria andBillReceiverEmailNotEqualTo(String value) { addCriterion("bill_receiver_email <>", value, "billReceiverEmail"); return (Criteria) this; } public Criteria andBillReceiverEmailGreaterThan(String value) { addCriterion("bill_receiver_email >", value, "billReceiverEmail"); return (Criteria) this; } public Criteria andBillReceiverEmailGreaterThanOrEqualTo(String value) { addCriterion("bill_receiver_email >=", value, "billReceiverEmail"); return (Criteria) this; } public Criteria andBillReceiverEmailLessThan(String value) { addCriterion("bill_receiver_email <", value, "billReceiverEmail"); return (Criteria) this; } public Criteria andBillReceiverEmailLessThanOrEqualTo(String value) { addCriterion("bill_receiver_email <=", value, "billReceiverEmail"); return (Criteria) this; } public Criteria andBillReceiverEmailLike(String value) { addCriterion("bill_receiver_email like", value, "billReceiverEmail"); return (Criteria) this; } public Criteria andBillReceiverEmailNotLike(String value) { addCriterion("bill_receiver_email not like", value, "billReceiverEmail"); return (Criteria) this; } public Criteria andBillReceiverEmailIn(List<String> values) { addCriterion("bill_receiver_email in", values, "billReceiverEmail"); return (Criteria) this; } public Criteria andBillReceiverEmailNotIn(List<String> values) { addCriterion("bill_receiver_email not in", values, "billReceiverEmail"); return (Criteria) this; } public Criteria andBillReceiverEmailBetween(String value1, String value2) { addCriterion("bill_receiver_email between", value1, value2, "billReceiverEmail"); return (Criteria) this; } public Criteria andBillReceiverEmailNotBetween(String value1, String value2) { addCriterion("bill_receiver_email not between", value1, value2, "billReceiverEmail"); return (Criteria) this; } public Criteria andReceiverNameIsNull() { addCriterion("receiver_name is null"); return (Criteria) this; } public Criteria andReceiverNameIsNotNull() { addCriterion("receiver_name is not null"); return (Criteria) this; } public Criteria andReceiverNameEqualTo(String value) { addCriterion("receiver_name =", value, "receiverName"); return (Criteria) this; } public Criteria andReceiverNameNotEqualTo(String value) { addCriterion("receiver_name <>", value, "receiverName"); return (Criteria) this; } public Criteria andReceiverNameGreaterThan(String value) { addCriterion("receiver_name >", value, "receiverName"); return (Criteria) this; } public Criteria andReceiverNameGreaterThanOrEqualTo(String value) { addCriterion("receiver_name >=", value, "receiverName"); return (Criteria) this; } public Criteria andReceiverNameLessThan(String value) { addCriterion("receiver_name <", value, "receiverName"); return (Criteria) this; } public Criteria andReceiverNameLessThanOrEqualTo(String value) { addCriterion("receiver_name <=", value, "receiverName"); return (Criteria) this; } public Criteria andReceiverNameLike(String value) { addCriterion("receiver_name like", value, "receiverName"); return (Criteria) this; } public Criteria andReceiverNameNotLike(String value) { addCriterion("receiver_name not like", value, "receiverName"); return (Criteria) this; } public Criteria andReceiverNameIn(List<String> values) { addCriterion("receiver_name in", values, "receiverName"); return (Criteria) this; } public Criteria andReceiverNameNotIn(List<String> values) { addCriterion("receiver_name not in", values, "receiverName"); return (Criteria) this; } public Criteria andReceiverNameBetween(String value1, String value2) { addCriterion("receiver_name between", value1, value2, "receiverName"); return (Criteria) this; } public Criteria andReceiverNameNotBetween(String value1, String value2) { addCriterion("receiver_name not between", value1, value2, "receiverName"); return (Criteria) this; } public Criteria andReceiverPhoneIsNull() { addCriterion("receiver_phone is null"); return (Criteria) this; } public Criteria andReceiverPhoneIsNotNull() { addCriterion("receiver_phone is not null"); return (Criteria) this; } public Criteria andReceiverPhoneEqualTo(String value) { addCriterion("receiver_phone =", value, "receiverPhone"); return (Criteria) this; } public Criteria andReceiverPhoneNotEqualTo(String value) { addCriterion("receiver_phone <>", value, "receiverPhone"); return (Criteria) this; } public Criteria andReceiverPhoneGreaterThan(String value) { addCriterion("receiver_phone >", value, "receiverPhone"); return (Criteria) this; } public Criteria andReceiverPhoneGreaterThanOrEqualTo(String value) { addCriterion("receiver_phone >=", value, "receiverPhone"); return (Criteria) this; } public Criteria andReceiverPhoneLessThan(String value) { addCriterion("receiver_phone <", value, "receiverPhone"); return (Criteria) this; } public Criteria andReceiverPhoneLessThanOrEqualTo(String value) { addCriterion("receiver_phone <=", value, "receiverPhone"); return (Criteria) this; } public Criteria andReceiverPhoneLike(String value) { addCriterion("receiver_phone like", value, "receiverPhone"); return (Criteria) this; } public Criteria andReceiverPhoneNotLike(String value) { addCriterion("receiver_phone not like", value, "receiverPhone"); return (Criteria) this; } public Criteria andReceiverPhoneIn(List<String> values) { addCriterion("receiver_phone in", values, "receiverPhone"); return (Criteria) this; } public Criteria andReceiverPhoneNotIn(List<String> values) { addCriterion("receiver_phone not in", values, "receiverPhone"); return (Criteria) this; } public Criteria andReceiverPhoneBetween(String value1, String value2) { addCriterion("receiver_phone between", value1, value2, "receiverPhone"); return (Criteria) this; } public Criteria andReceiverPhoneNotBetween(String value1, String value2) { addCriterion("receiver_phone not between", value1, value2, "receiverPhone"); return (Criteria) this; } public Criteria andReceiverPostCodeIsNull() { addCriterion("receiver_post_code is null"); return (Criteria) this; } public Criteria andReceiverPostCodeIsNotNull() { addCriterion("receiver_post_code is not null"); return (Criteria) this; } public Criteria andReceiverPostCodeEqualTo(String value) { addCriterion("receiver_post_code =", value, "receiverPostCode"); return (Criteria) this; } public Criteria andReceiverPostCodeNotEqualTo(String value) { addCriterion("receiver_post_code <>", value, "receiverPostCode"); return (Criteria) this; } public Criteria andReceiverPostCodeGreaterThan(String value) { addCriterion("receiver_post_code >", value, "receiverPostCode"); return (Criteria) this; } public Criteria andReceiverPostCodeGreaterThanOrEqualTo(String value) { addCriterion("receiver_post_code >=", value, "receiverPostCode"); return (Criteria) this; } public Criteria andReceiverPostCodeLessThan(String value) { addCriterion("receiver_post_code <", value, "receiverPostCode"); return (Criteria) this; } public Criteria andReceiverPostCodeLessThanOrEqualTo(String value) { addCriterion("receiver_post_code <=", value, "receiverPostCode"); return (Criteria) this; } public Criteria andReceiverPostCodeLike(String value) { addCriterion("receiver_post_code like", value, "receiverPostCode"); return (Criteria) this; } public Criteria andReceiverPostCodeNotLike(String value) { addCriterion("receiver_post_code not like", value, "receiverPostCode"); return (Criteria) this; } public Criteria andReceiverPostCodeIn(List<String> values) { addCriterion("receiver_post_code in", values, "receiverPostCode"); return (Criteria) this; } public Criteria andReceiverPostCodeNotIn(List<String> values) { addCriterion("receiver_post_code not in", values, "receiverPostCode"); return (Criteria) this; } public Criteria andReceiverPostCodeBetween(String value1, String value2) { addCriterion("receiver_post_code between", value1, value2, "receiverPostCode"); return (Criteria) this; } public Criteria andReceiverPostCodeNotBetween(String value1, String value2) { addCriterion("receiver_post_code not between", value1, value2, "receiverPostCode"); return (Criteria) this; } public Criteria andReceiverProvinceIsNull() { addCriterion("receiver_province is null"); return (Criteria) this; } public Criteria andReceiverProvinceIsNotNull() { addCriterion("receiver_province is not null"); return (Criteria) this; } public Criteria andReceiverProvinceEqualTo(String value) { addCriterion("receiver_province =", value, "receiverProvince"); return (Criteria) this; } public Criteria andReceiverProvinceNotEqualTo(String value) { addCriterion("receiver_province <>", value, "receiverProvince"); return (Criteria) this; } public Criteria andReceiverProvinceGreaterThan(String value) { addCriterion("receiver_province >", value, "receiverProvince"); return (Criteria) this; } public Criteria andReceiverProvinceGreaterThanOrEqualTo(String value) { addCriterion("receiver_province >=", value, "receiverProvince"); return (Criteria) this; } public Criteria andReceiverProvinceLessThan(String value) { addCriterion("receiver_province <", value, "receiverProvince"); return (Criteria) this; } public Criteria andReceiverProvinceLessThanOrEqualTo(String value) { addCriterion("receiver_province <=", value, "receiverProvince"); return (Criteria) this; } public Criteria andReceiverProvinceLike(String value) { addCriterion("receiver_province like", value, "receiverProvince"); return (Criteria) this; } public Criteria andReceiverProvinceNotLike(String value) { addCriterion("receiver_province not like", value, "receiverProvince"); return (Criteria) this; } public Criteria andReceiverProvinceIn(List<String> values) { addCriterion("receiver_province in", values, "receiverProvince"); return (Criteria) this; } public Criteria andReceiverProvinceNotIn(List<String> values) { addCriterion("receiver_province not in", values, "receiverProvince"); return (Criteria) this; } public Criteria andReceiverProvinceBetween(String value1, String value2) { addCriterion("receiver_province between", value1, value2, "receiverProvince"); return (Criteria) this; } public Criteria andReceiverProvinceNotBetween(String value1, String value2) { addCriterion("receiver_province not between", value1, value2, "receiverProvince"); return (Criteria) this; } public Criteria andReceiverCityIsNull() { addCriterion("receiver_city is null"); return (Criteria) this; } public Criteria andReceiverCityIsNotNull() { addCriterion("receiver_city is not null"); return (Criteria) this; } public Criteria andReceiverCityEqualTo(String value) { addCriterion("receiver_city =", value, "receiverCity"); return (Criteria) this; } public Criteria andReceiverCityNotEqualTo(String value) { addCriterion("receiver_city <>", value, "receiverCity"); return (Criteria) this; } public Criteria andReceiverCityGreaterThan(String value) { addCriterion("receiver_city >", value, "receiverCity"); return (Criteria) this; } public Criteria andReceiverCityGreaterThanOrEqualTo(String value) { addCriterion("receiver_city >=", value, "receiverCity"); return (Criteria) this; } public Criteria andReceiverCityLessThan(String value) { addCriterion("receiver_city <", value, "receiverCity"); return (Criteria) this; } public Criteria andReceiverCityLessThanOrEqualTo(String value) { addCriterion("receiver_city <=", value, "receiverCity"); return (Criteria) this; } public Criteria andReceiverCityLike(String value) { addCriterion("receiver_city like", value, "receiverCity"); return (Criteria) this; } public Criteria andReceiverCityNotLike(String value) { addCriterion("receiver_city not like", value, "receiverCity"); return (Criteria) this; } public Criteria andReceiverCityIn(List<String> values) { addCriterion("receiver_city in", values, "receiverCity"); return (Criteria) this; } public Criteria andReceiverCityNotIn(List<String> values) { addCriterion("receiver_city not in", values, "receiverCity"); return (Criteria) this; } public Criteria andReceiverCityBetween(String value1, String value2) { addCriterion("receiver_city between", value1, value2, "receiverCity"); return (Criteria) this; } public Criteria andReceiverCityNotBetween(String value1, String value2) { addCriterion("receiver_city not between", value1, value2, "receiverCity"); return (Criteria) this; } public Criteria andReceiverRegionIsNull() { addCriterion("receiver_region is null"); return (Criteria) this; } public Criteria andReceiverRegionIsNotNull() { addCriterion("receiver_region is not null"); return (Criteria) this; } public Criteria andReceiverRegionEqualTo(String value) { addCriterion("receiver_region =", value, "receiverRegion"); return (Criteria) this; } public Criteria andReceiverRegionNotEqualTo(String value) { addCriterion("receiver_region <>", value, "receiverRegion"); return (Criteria) this; } public Criteria andReceiverRegionGreaterThan(String value) { addCriterion("receiver_region >", value, "receiverRegion"); return (Criteria) this; } public Criteria andReceiverRegionGreaterThanOrEqualTo(String value) { addCriterion("receiver_region >=", value, "receiverRegion"); return (Criteria) this; } public Criteria andReceiverRegionLessThan(String value) { addCriterion("receiver_region <", value, "receiverRegion"); return (Criteria) this; } public Criteria andReceiverRegionLessThanOrEqualTo(String value) { addCriterion("receiver_region <=", value, "receiverRegion"); return (Criteria) this; } public Criteria andReceiverRegionLike(String value) { addCriterion("receiver_region like", value, "receiverRegion"); return (Criteria) this; } public Criteria andReceiverRegionNotLike(String value) { addCriterion("receiver_region not like", value, "receiverRegion"); return (Criteria) this; } public Criteria andReceiverRegionIn(List<String> values) { addCriterion("receiver_region in", values, "receiverRegion"); return (Criteria) this; } public Criteria andReceiverRegionNotIn(List<String> values) { addCriterion("receiver_region not in", values, "receiverRegion"); return (Criteria) this; } public Criteria andReceiverRegionBetween(String value1, String value2) { addCriterion("receiver_region between", value1, value2, "receiverRegion"); return (Criteria) this; } public Criteria andReceiverRegionNotBetween(String value1, String value2) { addCriterion("receiver_region not between", value1, value2, "receiverRegion"); return (Criteria) this; } public Criteria andReceiverDetailAddressIsNull() { addCriterion("receiver_detail_address is null"); return (Criteria) this; } public Criteria andReceiverDetailAddressIsNotNull() { addCriterion("receiver_detail_address is not null"); return (Criteria) this; } public Criteria andReceiverDetailAddressEqualTo(String value) { addCriterion("receiver_detail_address =", value, "receiverDetailAddress"); return (Criteria) this; } public Criteria andReceiverDetailAddressNotEqualTo(String value) { addCriterion("receiver_detail_address <>", value, "receiverDetailAddress"); return (Criteria) this; } public Criteria andReceiverDetailAddressGreaterThan(String value) { addCriterion("receiver_detail_address >", value, "receiverDetailAddress"); return (Criteria) this; } public Criteria andReceiverDetailAddressGreaterThanOrEqualTo(String value) { addCriterion("receiver_detail_address >=", value, "receiverDetailAddress"); return (Criteria) this; } public Criteria andReceiverDetailAddressLessThan(String value) { addCriterion("receiver_detail_address <", value, "receiverDetailAddress"); return (Criteria) this; } public Criteria andReceiverDetailAddressLessThanOrEqualTo(String value) { addCriterion("receiver_detail_address <=", value, "receiverDetailAddress"); return (Criteria) this; } public Criteria andReceiverDetailAddressLike(String value) { addCriterion("receiver_detail_address like", value, "receiverDetailAddress"); return (Criteria) this; } public Criteria andReceiverDetailAddressNotLike(String value) { addCriterion("receiver_detail_address not like", value, "receiverDetailAddress"); return (Criteria) this; } public Criteria andReceiverDetailAddressIn(List<String> values) { addCriterion("receiver_detail_address in", values, "receiverDetailAddress"); return (Criteria) this; } public Criteria andReceiverDetailAddressNotIn(List<String> values) { addCriterion("receiver_detail_address not in", values, "receiverDetailAddress"); return (Criteria) this; } public Criteria andReceiverDetailAddressBetween(String value1, String value2) { addCriterion("receiver_detail_address between", value1, value2, "receiverDetailAddress"); return (Criteria) this; } public Criteria andReceiverDetailAddressNotBetween(String value1, String value2) { addCriterion("receiver_detail_address not between", value1, value2, "receiverDetailAddress"); return (Criteria) this; } public Criteria andNoteIsNull() { addCriterion("note is null"); return (Criteria) this; } public Criteria andNoteIsNotNull() { addCriterion("note is not null"); return (Criteria) this; } public Criteria andNoteEqualTo(String value) { addCriterion("note =", value, "note"); return (Criteria) this; } public Criteria andNoteNotEqualTo(String value) { addCriterion("note <>", value, "note"); return (Criteria) this; } public Criteria andNoteGreaterThan(String value) { addCriterion("note >", value, "note"); return (Criteria) this; } public Criteria andNoteGreaterThanOrEqualTo(String value) { addCriterion("note >=", value, "note"); return (Criteria) this; } public Criteria andNoteLessThan(String value) { addCriterion("note <", value, "note"); return (Criteria) this; } public Criteria andNoteLessThanOrEqualTo(String value) { addCriterion("note <=", value, "note"); return (Criteria) this; } public Criteria andNoteLike(String value) { addCriterion("note like", value, "note"); return (Criteria) this; } public Criteria andNoteNotLike(String value) { addCriterion("note not like", value, "note"); return (Criteria) this; } public Criteria andNoteIn(List<String> values) { addCriterion("note in", values, "note"); return (Criteria) this; } public Criteria andNoteNotIn(List<String> values) { addCriterion("note not in", values, "note"); return (Criteria) this; } public Criteria andNoteBetween(String value1, String value2) { addCriterion("note between", value1, value2, "note"); return (Criteria) this; } public Criteria andNoteNotBetween(String value1, String value2) { addCriterion("note not between", value1, value2, "note"); return (Criteria) this; } public Criteria andConfirmStatusIsNull() { addCriterion("confirm_status is null"); return (Criteria) this; } public Criteria andConfirmStatusIsNotNull() { addCriterion("confirm_status is not null"); return (Criteria) this; } public Criteria andConfirmStatusEqualTo(Integer value) { addCriterion("confirm_status =", value, "confirmStatus"); return (Criteria) this; } public Criteria andConfirmStatusNotEqualTo(Integer value) { addCriterion("confirm_status <>", value, "confirmStatus"); return (Criteria) this; } public Criteria andConfirmStatusGreaterThan(Integer value) { addCriterion("confirm_status >", value, "confirmStatus"); return (Criteria) this; } public Criteria andConfirmStatusGreaterThanOrEqualTo(Integer value) { addCriterion("confirm_status >=", value, "confirmStatus"); return (Criteria) this; } public Criteria andConfirmStatusLessThan(Integer value) { addCriterion("confirm_status <", value, "confirmStatus"); return (Criteria) this; } public Criteria andConfirmStatusLessThanOrEqualTo(Integer value) { addCriterion("confirm_status <=", value, "confirmStatus"); return (Criteria) this; } public Criteria andConfirmStatusIn(List<Integer> values) { addCriterion("confirm_status in", values, "confirmStatus"); return (Criteria) this; } public Criteria andConfirmStatusNotIn(List<Integer> values) { addCriterion("confirm_status not in", values, "confirmStatus"); return (Criteria) this; } public Criteria andConfirmStatusBetween(Integer value1, Integer value2) { addCriterion("confirm_status between", value1, value2, "confirmStatus"); return (Criteria) this; } public Criteria andConfirmStatusNotBetween(Integer value1, Integer value2) { addCriterion("confirm_status not between", value1, value2, "confirmStatus"); return (Criteria) this; } public Criteria andDeleteStatusIsNull() { addCriterion("delete_status is null"); return (Criteria) this; } public Criteria andDeleteStatusIsNotNull() { addCriterion("delete_status is not null"); return (Criteria) this; } public Criteria andDeleteStatusEqualTo(Integer value) { addCriterion("delete_status =", value, "deleteStatus"); return (Criteria) this; } public Criteria andDeleteStatusNotEqualTo(Integer value) { addCriterion("delete_status <>", value, "deleteStatus"); return (Criteria) this; } public Criteria andDeleteStatusGreaterThan(Integer value) { addCriterion("delete_status >", value, "deleteStatus"); return (Criteria) this; } public Criteria andDeleteStatusGreaterThanOrEqualTo(Integer value) { addCriterion("delete_status >=", value, "deleteStatus"); return (Criteria) this; } public Criteria andDeleteStatusLessThan(Integer value) { addCriterion("delete_status <", value, "deleteStatus"); return (Criteria) this; } public Criteria andDeleteStatusLessThanOrEqualTo(Integer value) { addCriterion("delete_status <=", value, "deleteStatus"); return (Criteria) this; } public Criteria andDeleteStatusIn(List<Integer> values) { addCriterion("delete_status in", values, "deleteStatus"); return (Criteria) this; } public Criteria andDeleteStatusNotIn(List<Integer> values) { addCriterion("delete_status not in", values, "deleteStatus"); return (Criteria) this; } public Criteria andDeleteStatusBetween(Integer value1, Integer value2) { addCriterion("delete_status between", value1, value2, "deleteStatus"); return (Criteria) this; } public Criteria andDeleteStatusNotBetween(Integer value1, Integer value2) { addCriterion("delete_status not between", value1, value2, "deleteStatus"); return (Criteria) this; } public Criteria andUseIntegrationIsNull() { addCriterion("use_integration is null"); return (Criteria) this; } public Criteria andUseIntegrationIsNotNull() { addCriterion("use_integration is not null"); return (Criteria) this; } public Criteria andUseIntegrationEqualTo(Integer value) { addCriterion("use_integration =", value, "useIntegration"); return (Criteria) this; } public Criteria andUseIntegrationNotEqualTo(Integer value) { addCriterion("use_integration <>", value, "useIntegration"); return (Criteria) this; } public Criteria andUseIntegrationGreaterThan(Integer value) { addCriterion("use_integration >", value, "useIntegration"); return (Criteria) this; } public Criteria andUseIntegrationGreaterThanOrEqualTo(Integer value) { addCriterion("use_integration >=", value, "useIntegration"); return (Criteria) this; } public Criteria andUseIntegrationLessThan(Integer value) { addCriterion("use_integration <", value, "useIntegration"); return (Criteria) this; } public Criteria andUseIntegrationLessThanOrEqualTo(Integer value) { addCriterion("use_integration <=", value, "useIntegration"); return (Criteria) this; } public Criteria andUseIntegrationIn(List<Integer> values) { addCriterion("use_integration in", values, "useIntegration"); return (Criteria) this; } public Criteria andUseIntegrationNotIn(List<Integer> values) { addCriterion("use_integration not in", values, "useIntegration"); return (Criteria) this; } public Criteria andUseIntegrationBetween(Integer value1, Integer value2) { addCriterion("use_integration between", value1, value2, "useIntegration"); return (Criteria) this; } public Criteria andUseIntegrationNotBetween(Integer value1, Integer value2) { addCriterion("use_integration not between", value1, value2, "useIntegration"); return (Criteria) this; } public Criteria andPaymentTimeIsNull() { addCriterion("payment_time is null"); return (Criteria) this; } public Criteria andPaymentTimeIsNotNull() { addCriterion("payment_time is not null"); return (Criteria) this; } public Criteria andPaymentTimeEqualTo(Date value) { addCriterion("payment_time =", value, "paymentTime"); return (Criteria) this; } public Criteria andPaymentTimeNotEqualTo(Date value) { addCriterion("payment_time <>", value, "paymentTime"); return (Criteria) this; } public Criteria andPaymentTimeGreaterThan(Date value) { addCriterion("payment_time >", value, "paymentTime"); return (Criteria) this; } public Criteria andPaymentTimeGreaterThanOrEqualTo(Date value) { addCriterion("payment_time >=", value, "paymentTime"); return (Criteria) this; } public Criteria andPaymentTimeLessThan(Date value) { addCriterion("payment_time <", value, "paymentTime"); return (Criteria) this; } public Criteria andPaymentTimeLessThanOrEqualTo(Date value) { addCriterion("payment_time <=", value, "paymentTime"); return (Criteria) this; } public Criteria andPaymentTimeIn(List<Date> values) { addCriterion("payment_time in", values, "paymentTime"); return (Criteria) this; } public Criteria andPaymentTimeNotIn(List<Date> values) { addCriterion("payment_time not in", values, "paymentTime"); return (Criteria) this; } public Criteria andPaymentTimeBetween(Date value1, Date value2) { addCriterion("payment_time between", value1, value2, "paymentTime"); return (Criteria) this; } public Criteria andPaymentTimeNotBetween(Date value1, Date value2) { addCriterion("payment_time not between", value1, value2, "paymentTime"); return (Criteria) this; } public Criteria andDeliveryTimeIsNull() { addCriterion("delivery_time is null"); return (Criteria) this; } public Criteria andDeliveryTimeIsNotNull() { addCriterion("delivery_time is not null"); return (Criteria) this; } public Criteria andDeliveryTimeEqualTo(Date value) { addCriterion("delivery_time =", value, "deliveryTime"); return (Criteria) this; } public Criteria andDeliveryTimeNotEqualTo(Date value) { addCriterion("delivery_time <>", value, "deliveryTime"); return (Criteria) this; } public Criteria andDeliveryTimeGreaterThan(Date value) { addCriterion("delivery_time >", value, "deliveryTime"); return (Criteria) this; } public Criteria andDeliveryTimeGreaterThanOrEqualTo(Date value) { addCriterion("delivery_time >=", value, "deliveryTime"); return (Criteria) this; } public Criteria andDeliveryTimeLessThan(Date value) { addCriterion("delivery_time <", value, "deliveryTime"); return (Criteria) this; } public Criteria andDeliveryTimeLessThanOrEqualTo(Date value) { addCriterion("delivery_time <=", value, "deliveryTime"); return (Criteria) this; } public Criteria andDeliveryTimeIn(List<Date> values) { addCriterion("delivery_time in", values, "deliveryTime"); return (Criteria) this; } public Criteria andDeliveryTimeNotIn(List<Date> values) { addCriterion("delivery_time not in", values, "deliveryTime"); return (Criteria) this; } public Criteria andDeliveryTimeBetween(Date value1, Date value2) { addCriterion("delivery_time between", value1, value2, "deliveryTime"); return (Criteria) this; } public Criteria andDeliveryTimeNotBetween(Date value1, Date value2) { addCriterion("delivery_time not between", value1, value2, "deliveryTime"); return (Criteria) this; } public Criteria andReceiveTimeIsNull() { addCriterion("receive_time is null"); return (Criteria) this; } public Criteria andReceiveTimeIsNotNull() { addCriterion("receive_time is not null"); return (Criteria) this; } public Criteria andReceiveTimeEqualTo(Date value) { addCriterion("receive_time =", value, "receiveTime"); return (Criteria) this; } public Criteria andReceiveTimeNotEqualTo(Date value) { addCriterion("receive_time <>", value, "receiveTime"); return (Criteria) this; } public Criteria andReceiveTimeGreaterThan(Date value) { addCriterion("receive_time >", value, "receiveTime"); return (Criteria) this; } public Criteria andReceiveTimeGreaterThanOrEqualTo(Date value) { addCriterion("receive_time >=", value, "receiveTime"); return (Criteria) this; } public Criteria andReceiveTimeLessThan(Date value) { addCriterion("receive_time <", value, "receiveTime"); return (Criteria) this; } public Criteria andReceiveTimeLessThanOrEqualTo(Date value) { addCriterion("receive_time <=", value, "receiveTime"); return (Criteria) this; } public Criteria andReceiveTimeIn(List<Date> values) { addCriterion("receive_time in", values, "receiveTime"); return (Criteria) this; } public Criteria andReceiveTimeNotIn(List<Date> values) { addCriterion("receive_time not in", values, "receiveTime"); return (Criteria) this; } public Criteria andReceiveTimeBetween(Date value1, Date value2) { addCriterion("receive_time between", value1, value2, "receiveTime"); return (Criteria) this; } public Criteria andReceiveTimeNotBetween(Date value1, Date value2) { addCriterion("receive_time not between", value1, value2, "receiveTime"); return (Criteria) this; } public Criteria andCommentTimeIsNull() { addCriterion("comment_time is null"); return (Criteria) this; } public Criteria andCommentTimeIsNotNull() { addCriterion("comment_time is not null"); return (Criteria) this; } public Criteria andCommentTimeEqualTo(Date value) { addCriterion("comment_time =", value, "commentTime"); return (Criteria) this; } public Criteria andCommentTimeNotEqualTo(Date value) { addCriterion("comment_time <>", value, "commentTime"); return (Criteria) this; } public Criteria andCommentTimeGreaterThan(Date value) { addCriterion("comment_time >", value, "commentTime"); return (Criteria) this; } public Criteria andCommentTimeGreaterThanOrEqualTo(Date value) { addCriterion("comment_time >=", value, "commentTime"); return (Criteria) this; } public Criteria andCommentTimeLessThan(Date value) { addCriterion("comment_time <", value, "commentTime"); return (Criteria) this; } public Criteria andCommentTimeLessThanOrEqualTo(Date value) { addCriterion("comment_time <=", value, "commentTime"); return (Criteria) this; } public Criteria andCommentTimeIn(List<Date> values) { addCriterion("comment_time in", values, "commentTime"); return (Criteria) this; } public Criteria andCommentTimeNotIn(List<Date> values) { addCriterion("comment_time not in", values, "commentTime"); return (Criteria) this; } public Criteria andCommentTimeBetween(Date value1, Date value2) { addCriterion("comment_time between", value1, value2, "commentTime"); return (Criteria) this; } public Criteria andCommentTimeNotBetween(Date value1, Date value2) { addCriterion("comment_time not between", value1, value2, "commentTime"); return (Criteria) this; } public Criteria andModifyTimeIsNull() { addCriterion("modify_time is null"); return (Criteria) this; } public Criteria andModifyTimeIsNotNull() { addCriterion("modify_time is not null"); return (Criteria) this; } public Criteria andModifyTimeEqualTo(Date value) { addCriterion("modify_time =", value, "modifyTime"); return (Criteria) this; } public Criteria andModifyTimeNotEqualTo(Date value) { addCriterion("modify_time <>", value, "modifyTime"); return (Criteria) this; } public Criteria andModifyTimeGreaterThan(Date value) { addCriterion("modify_time >", value, "modifyTime"); return (Criteria) this; } public Criteria andModifyTimeGreaterThanOrEqualTo(Date value) { addCriterion("modify_time >=", value, "modifyTime"); return (Criteria) this; } public Criteria andModifyTimeLessThan(Date value) { addCriterion("modify_time <", value, "modifyTime"); return (Criteria) this; } public Criteria andModifyTimeLessThanOrEqualTo(Date value) { addCriterion("modify_time <=", value, "modifyTime"); return (Criteria) this; } public Criteria andModifyTimeIn(List<Date> values) { addCriterion("modify_time in", values, "modifyTime"); return (Criteria) this; } public Criteria andModifyTimeNotIn(List<Date> values) { addCriterion("modify_time not in", values, "modifyTime"); return (Criteria) this; } public Criteria andModifyTimeBetween(Date value1, Date value2) { addCriterion("modify_time between", value1, value2, "modifyTime"); return (Criteria) this; } public Criteria andModifyTimeNotBetween(Date value1, Date value2) { addCriterion("modify_time not between", value1, value2, "modifyTime"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
macrozheng/mall
mall-mbg/src/main/java/com/macro/mall/model/OmsOrderExample.java
44,924
package com.crossoverjie.concurrent; import com.crossoverjie.concurrent.communication.Notify; import com.crossoverjie.concurrent.future.Callable; import com.crossoverjie.concurrent.future.Future; import com.crossoverjie.concurrent.future.FutureTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.AbstractSet; import java.util.Iterator; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantLock; /** * Function:线程池 * * @author crossoverJie * Date: 2019-05-14 10:51 * @since JDK 1.8 */ public class CustomThreadPool { private final static Logger LOGGER = LoggerFactory.getLogger(CustomThreadPool.class); private final ReentrantLock lock = new ReentrantLock(); /** * 最小线程数,也叫核心线程数 */ private volatile int miniSize; /** * 最大线程数 */ private volatile int maxSize; /** * 线程需要被回收的时间 */ private long keepAliveTime; private TimeUnit unit; /** * 存放线程的阻塞队列 */ private BlockingQueue<Runnable> workQueue; /** * 存放线程池 */ private volatile Set<Worker> workers; /** * 是否关闭线程池标志 */ private AtomicBoolean isShutDown = new AtomicBoolean(false); /** * 提交到线程池中的任务总数 */ private AtomicInteger totalTask = new AtomicInteger(); /** * 线程池任务全部执行完毕后的通知组件 */ private Object shutDownNotify = new Object(); private Notify notify; /** * @param miniSize 最小线程数 * @param maxSize 最大线程数 * @param keepAliveTime 线程保活时间 * @param unit * @param workQueue 阻塞队列 * @param notify 通知接口 */ public CustomThreadPool(int miniSize, int maxSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, Notify notify) { this.miniSize = miniSize; this.maxSize = maxSize; this.keepAliveTime = keepAliveTime; this.unit = unit; this.workQueue = workQueue; this.notify = notify; workers = new ConcurrentHashSet<>(); } /** * 有返回值 * * @param callable * @param <T> * @return */ public <T> Future<T> submit(Callable<T> callable) { FutureTask<T> future = new FutureTask(callable); execute(future); return future; } /** * 执行任务 * * @param runnable 需要执行的任务 */ public void execute(Runnable runnable) { if (runnable == null) { throw new NullPointerException("runnable nullPointerException"); } if (isShutDown.get()) { LOGGER.info("线程池已经关闭,不能再提交任务!"); return; } //提交的线程 计数 totalTask.incrementAndGet(); //小于最小线程数时新建线程 if (workers.size() < miniSize) { addWorker(runnable); return; } boolean offer = workQueue.offer(runnable); //写入队列失败 if (!offer) { //创建新的线程执行 if (workers.size() < maxSize) { addWorker(runnable); return; } else { LOGGER.error("超过最大线程数"); try { //会阻塞 workQueue.put(runnable); } catch (InterruptedException e) { } } } } /** * 添加任务,需要加锁 * * @param runnable 任务 */ private void addWorker(Runnable runnable) { Worker worker = new Worker(runnable, true); worker.startTask(); workers.add(worker); } /** * 工作线程 */ private final class Worker extends Thread { private Runnable task; private Thread thread; /** * true --> 创建新的线程执行 * false --> 从队列里获取线程执行 */ private boolean isNewTask; public Worker(Runnable task, boolean isNewTask) { this.task = task; this.isNewTask = isNewTask; thread = this; } public void startTask() { thread.start(); } public void close() { thread.interrupt(); } @Override public void run() { Runnable task = null; if (isNewTask) { task = this.task; } boolean compile = true ; try { while ((task != null || (task = getTask()) != null)) { try { //执行任务 task.run(); } catch (Exception e) { compile = false ; throw e ; } finally { //任务执行完毕 task = null; int number = totalTask.decrementAndGet(); //LOGGER.info("number={}",number); if (number == 0) { synchronized (shutDownNotify) { shutDownNotify.notify(); } } } } } finally { //释放线程 boolean remove = workers.remove(this); //LOGGER.info("remove={},size={}", remove, workers.size()); if (!compile){ addWorker(null); } tryClose(true); } } } /** * 从队列中获取任务 * * @return */ private Runnable getTask() { //关闭标识及任务是否全部完成 if (isShutDown.get() && totalTask.get() == 0) { return null; } //while (true) { // // if (workers.size() > miniSize) { // boolean value = number.compareAndSet(number.get(), number.get() - 1); // if (value) { // return null; // } else { // continue; // } // } lock.lock(); try { Runnable task = null; if (workers.size() > miniSize) { //大于核心线程数时需要用保活时间获取任务 task = workQueue.poll(keepAliveTime, unit); } else { task = workQueue.take(); } if (task != null) { return task; } } catch (InterruptedException e) { return null; } finally { lock.unlock(); } return null; //} } /** * 任务执行完毕后关闭线程池 */ public void shutdown() { isShutDown.set(true); tryClose(true); //中断所有线程 //synchronized (shutDownNotify){ // while (totalTask.get() > 0){ // try { // shutDownNotify.wait(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } //} } /** * 立即关闭线程池,会造成任务丢失 */ public void shutDownNow() { isShutDown.set(true); tryClose(false); } /** * 阻塞等到任务执行完毕 */ public void mainNotify() { synchronized (shutDownNotify) { while (totalTask.get() > 0) { try { shutDownNotify.wait(); if (notify != null) { notify.notifyListen(); } } catch (InterruptedException e) { return; } } } } /** * 关闭线程池 * * @param isTry true 尝试关闭 --> 会等待所有任务执行完毕 * false 立即关闭线程池--> 任务有丢失的可能 */ private void tryClose(boolean isTry) { if (!isTry) { closeAllTask(); } else { if (isShutDown.get() && totalTask.get() == 0) { closeAllTask(); } } } /** * 关闭所有任务 */ private void closeAllTask() { for (Worker worker : workers) { //LOGGER.info("开始关闭"); worker.close(); } } /** * 获取工作线程数量 * * @return */ public int getWorkerCount() { return workers.size(); } /** * 内部存放工作线程容器,并发安全。 * * @param <T> */ private final class ConcurrentHashSet<T> extends AbstractSet<T> { private ConcurrentHashMap<T, Object> map = new ConcurrentHashMap<>(); private final Object PRESENT = new Object(); private AtomicInteger count = new AtomicInteger(); @Override public Iterator<T> iterator() { return map.keySet().iterator(); } @Override public boolean add(T t) { count.incrementAndGet(); return map.put(t, PRESENT) == null; } @Override public boolean remove(Object o) { count.decrementAndGet(); return map.remove(o) == PRESENT; } @Override public int size() { return count.get(); } } }
crossoverJie/JCSprout
src/main/java/com/crossoverjie/concurrent/CustomThreadPool.java
44,925
package com.macro.mall.dao; import com.macro.mall.dto.OmsOrderDeliveryParam; import com.macro.mall.dto.OmsOrderDetail; import com.macro.mall.dto.OmsOrderQueryParam; import com.macro.mall.model.OmsOrder; import org.apache.ibatis.annotations.Param; import java.util.List; /** * 订单查询自定义Dao * Created by macro on 2018/10/12. */ public interface OmsOrderDao { /** * 条件查询订单 */ List<OmsOrder> getList(@Param("queryParam") OmsOrderQueryParam queryParam); /** * 批量发货 */ int delivery(@Param("list") List<OmsOrderDeliveryParam> deliveryParamList); /** * 获取订单详情 */ OmsOrderDetail getDetail(@Param("id") Long id); }
macrozheng/mall
mall-admin/src/main/java/com/macro/mall/dao/OmsOrderDao.java
44,926
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * 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.alibaba.druid.pool; import com.alibaba.druid.Constants; import com.alibaba.druid.DbType; import com.alibaba.druid.TransactionTimeoutException; import com.alibaba.druid.VERSION; import com.alibaba.druid.filter.AutoLoad; import com.alibaba.druid.filter.Filter; import com.alibaba.druid.filter.FilterChainImpl; import com.alibaba.druid.mock.MockDriver; import com.alibaba.druid.pool.DruidPooledPreparedStatement.PreparedStatementKey; import com.alibaba.druid.pool.vendor.*; import com.alibaba.druid.proxy.DruidDriver; import com.alibaba.druid.proxy.jdbc.DataSourceProxyConfig; import com.alibaba.druid.proxy.jdbc.TransactionInfo; import com.alibaba.druid.sql.ast.SQLStatement; import com.alibaba.druid.sql.ast.statement.SQLSelectQuery; import com.alibaba.druid.sql.ast.statement.SQLSelectQueryBlock; import com.alibaba.druid.sql.ast.statement.SQLSelectStatement; import com.alibaba.druid.sql.parser.SQLParserUtils; import com.alibaba.druid.sql.parser.SQLStatementParser; import com.alibaba.druid.stat.DruidDataSourceStatManager; import com.alibaba.druid.stat.JdbcDataSourceStat; import com.alibaba.druid.stat.JdbcSqlStat; import com.alibaba.druid.stat.JdbcSqlStatValue; import com.alibaba.druid.support.clickhouse.BalancedClickhouseDriver; import com.alibaba.druid.support.clickhouse.BalancedClickhouseDriverNative; import com.alibaba.druid.support.logging.Log; import com.alibaba.druid.support.logging.LogFactory; import com.alibaba.druid.util.*; import com.alibaba.druid.wall.WallFilter; import com.alibaba.druid.wall.WallProviderStatValue; import javax.management.JMException; import javax.management.MBeanRegistration; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.naming.NamingException; import javax.naming.Reference; import javax.naming.Referenceable; import javax.naming.StringRefAddr; import javax.sql.ConnectionEvent; import javax.sql.ConnectionEventListener; import javax.sql.ConnectionPoolDataSource; import javax.sql.PooledConnection; import java.io.Closeable; import java.net.Socket; import java.security.AccessController; import java.security.PrivilegedAction; import java.sql.Connection; import java.sql.SQLException; import java.sql.SQLRecoverableException; import java.sql.Statement; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.concurrent.atomic.AtomicLongFieldUpdater; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import static com.alibaba.druid.util.Utils.getBoolean; /** * @author ljw [[email protected]] * @author wenshao [[email protected]] */ public class DruidDataSource extends DruidAbstractDataSource implements DruidDataSourceMBean, ManagedDataSource, Referenceable, Closeable, Cloneable, ConnectionPoolDataSource, MBeanRegistration { private static final Log LOG = LogFactory.getLog(DruidDataSource.class); private static final long serialVersionUID = 1L; // stats private volatile long recycleErrorCount; private volatile long discardErrorCount; private volatile Throwable discardErrorLast; private long connectCount; private long closeCount; private volatile long connectErrorCount; private long recycleCount; private long removeAbandonedCount; private long notEmptyWaitCount; private long notEmptySignalCount; private long notEmptyWaitNanos; private int keepAliveCheckCount; private int activePeak; private long activePeakTime; private int poolingPeak; private long poolingPeakTime; private volatile int keepAliveCheckErrorCount; private volatile Throwable keepAliveCheckErrorLast; // store private volatile DruidConnectionHolder[] connections; private int poolingCount; private int activeCount; private volatile int createDirectCount; private volatile long discardCount; private int notEmptyWaitThreadCount; private int notEmptyWaitThreadPeak; // private DruidConnectionHolder[] evictConnections; private DruidConnectionHolder[] keepAliveConnections; // for clean connection old references. private volatile DruidConnectionHolder[] nullConnections; // threads private volatile ScheduledFuture<?> destroySchedulerFuture; private DestroyTask destroyTask; private final Map<CreateConnectionTask, Future<?>> createSchedulerFutures = new ConcurrentHashMap<>(16); private CreateConnectionThread createConnectionThread; private DestroyConnectionThread destroyConnectionThread; private LogStatsThread logStatsThread; private int createTaskCount; private volatile long createTaskIdSeed = 1L; private long[] createTasks; private volatile boolean enable = true; private boolean resetStatEnable = true; private volatile long resetCount; private String initStackTrace; private volatile boolean closing; private volatile boolean closed; private long closeTimeMillis = -1L; protected JdbcDataSourceStat dataSourceStat; private boolean useGlobalDataSourceStat; private boolean mbeanRegistered; private boolean logDifferentThread = true; private volatile boolean keepAlive; private boolean asyncInit; protected boolean killWhenSocketReadTimeout; protected boolean checkExecuteTime; private static List<Filter> autoFilters; private boolean loadSpifilterSkip; private volatile DataSourceDisableException disableException; protected static final AtomicLongFieldUpdater<DruidDataSource> recycleErrorCountUpdater = AtomicLongFieldUpdater.newUpdater(DruidDataSource.class, "recycleErrorCount"); protected static final AtomicLongFieldUpdater<DruidDataSource> connectErrorCountUpdater = AtomicLongFieldUpdater.newUpdater(DruidDataSource.class, "connectErrorCount"); protected static final AtomicLongFieldUpdater<DruidDataSource> resetCountUpdater = AtomicLongFieldUpdater.newUpdater(DruidDataSource.class, "resetCount"); protected static final AtomicLongFieldUpdater<DruidDataSource> createTaskIdSeedUpdater = AtomicLongFieldUpdater.newUpdater(DruidDataSource.class, "createTaskIdSeed"); protected static final AtomicLongFieldUpdater<DruidDataSource> discardErrorCountUpdater = AtomicLongFieldUpdater.newUpdater(DruidDataSource.class, "discardErrorCount"); protected static final AtomicIntegerFieldUpdater<DruidDataSource> keepAliveCheckErrorCountUpdater = AtomicIntegerFieldUpdater.newUpdater(DruidDataSource.class, "keepAliveCheckErrorCount"); protected static final AtomicIntegerFieldUpdater<DruidDataSource> createDirectCountUpdater = AtomicIntegerFieldUpdater.newUpdater(DruidDataSource.class, "createDirectCount"); public DruidDataSource() { this(false); } public DruidDataSource(boolean fairLock) { super(fairLock); configFromPropeties(System.getProperties()); } public boolean isAsyncInit() { return asyncInit; } public void setAsyncInit(boolean asyncInit) { this.asyncInit = asyncInit; } @Deprecated public void configFromPropety(Properties properties) { configFromPropeties(properties); } public void configFromPropeties(Properties properties) { { String property = properties.getProperty("druid.name"); if (property != null) { this.setName(property); } } { String property = properties.getProperty("druid.url"); if (property != null) { this.setUrl(property); } } { String property = properties.getProperty("druid.username"); if (property != null) { this.setUsername(property); } } { String property = properties.getProperty("druid.password"); if (property != null) { this.setPassword(property); } } { Boolean value = getBoolean(properties, "druid.testWhileIdle"); if (value != null) { this.testWhileIdle = value; } } { Boolean value = getBoolean(properties, "druid.testOnBorrow"); if (value != null) { this.testOnBorrow = value; } } { String property = properties.getProperty("druid.validationQuery"); if (property != null && property.length() > 0) { this.setValidationQuery(property); } } { Boolean value = getBoolean(properties, "druid.useGlobalDataSourceStat"); if (value != null) { this.setUseGlobalDataSourceStat(value); } } { Boolean value = getBoolean(properties, "druid.useGloalDataSourceStat"); // compatible for early versions if (value != null) { this.setUseGlobalDataSourceStat(value); } } { Boolean value = getBoolean(properties, "druid.asyncInit"); // compatible for early versions if (value != null) { this.setAsyncInit(value); } } { String property = properties.getProperty("druid.filters"); if (property != null && property.length() > 0) { try { this.setFilters(property); } catch (SQLException e) { LOG.error("setFilters error", e); } } } { String property = properties.getProperty(Constants.DRUID_TIME_BETWEEN_LOG_STATS_MILLIS); if (property != null && property.length() > 0) { try { long value = Long.parseLong(property); this.setTimeBetweenLogStatsMillis(value); } catch (NumberFormatException e) { LOG.error("illegal property '" + Constants.DRUID_TIME_BETWEEN_LOG_STATS_MILLIS + "'", e); } } } { String property = properties.getProperty(Constants.DRUID_STAT_SQL_MAX_SIZE); if (property != null && property.length() > 0) { try { int value = Integer.parseInt(property); if (dataSourceStat != null) { dataSourceStat.setMaxSqlSize(value); } } catch (NumberFormatException e) { LOG.error("illegal property '" + Constants.DRUID_STAT_SQL_MAX_SIZE + "'", e); } } } { Boolean value = getBoolean(properties, "druid.clearFiltersEnable"); if (value != null) { this.setClearFiltersEnable(value); } } { Boolean value = getBoolean(properties, "druid.resetStatEnable"); if (value != null) { this.setResetStatEnable(value); } } { String property = properties.getProperty("druid.notFullTimeoutRetryCount"); if (property != null && property.length() > 0) { try { int value = Integer.parseInt(property); this.setNotFullTimeoutRetryCount(value); } catch (NumberFormatException e) { LOG.error("illegal property 'druid.notFullTimeoutRetryCount'", e); } } } { String property = properties.getProperty("druid.timeBetweenEvictionRunsMillis"); if (property != null && property.length() > 0) { try { long value = Long.parseLong(property); this.setTimeBetweenEvictionRunsMillis(value); } catch (NumberFormatException e) { LOG.error("illegal property 'druid.timeBetweenEvictionRunsMillis'", e); } } } { String property = properties.getProperty("druid.maxWaitThreadCount"); if (property != null && property.length() > 0) { try { int value = Integer.parseInt(property); this.setMaxWaitThreadCount(value); } catch (NumberFormatException e) { LOG.error("illegal property 'druid.maxWaitThreadCount'", e); } } } { String property = properties.getProperty("druid.maxWait"); if (property != null && property.length() > 0) { try { int value = Integer.parseInt(property); this.setMaxWait(value); } catch (NumberFormatException e) { LOG.error("illegal property 'druid.maxWait'", e); } } } { Boolean value = getBoolean(properties, "druid.failFast"); if (value != null) { this.setFailFast(value); } } { String property = properties.getProperty("druid.phyTimeoutMillis"); if (property != null && property.length() > 0) { try { long value = Long.parseLong(property); this.setPhyTimeoutMillis(value); } catch (NumberFormatException e) { LOG.error("illegal property 'druid.phyTimeoutMillis'", e); } } } { String property = properties.getProperty("druid.phyMaxUseCount"); if (property != null && property.length() > 0) { try { long value = Long.parseLong(property); this.setPhyMaxUseCount(value); } catch (NumberFormatException e) { LOG.error("illegal property 'druid.phyMaxUseCount'", e); } } } { String property = properties.getProperty("druid.minEvictableIdleTimeMillis"); if (property != null && property.length() > 0) { try { long value = Long.parseLong(property); this.setMinEvictableIdleTimeMillis(value); } catch (NumberFormatException e) { LOG.error("illegal property 'druid.minEvictableIdleTimeMillis'", e); } } } { String property = properties.getProperty("druid.maxEvictableIdleTimeMillis"); if (property != null && property.length() > 0) { try { long value = Long.parseLong(property); this.setMaxEvictableIdleTimeMillis(value); } catch (NumberFormatException e) { LOG.error("illegal property 'druid.maxEvictableIdleTimeMillis'", e); } } } { Boolean value = getBoolean(properties, "druid.keepAlive"); if (value != null) { this.setKeepAlive(value); } } { String property = properties.getProperty("druid.keepAliveBetweenTimeMillis"); if (property != null && property.length() > 0) { try { long value = Long.parseLong(property); this.setKeepAliveBetweenTimeMillis(value); } catch (NumberFormatException e) { LOG.error("illegal property 'druid.keepAliveBetweenTimeMillis'", e); } } } { Boolean value = getBoolean(properties, "druid.poolPreparedStatements"); if (value != null) { this.setPoolPreparedStatements0(value); } } { Boolean value = getBoolean(properties, "druid.initVariants"); if (value != null) { this.setInitVariants(value); } } { Boolean value = getBoolean(properties, "druid.initGlobalVariants"); if (value != null) { this.setInitGlobalVariants(value); } } { Boolean value = getBoolean(properties, "druid.useUnfairLock"); if (value != null) { this.setUseUnfairLock(value); } } { String property = properties.getProperty("druid.driverClassName"); if (property != null) { this.setDriverClassName(property); } } { String property = properties.getProperty("druid.initialSize"); if (property != null && property.length() > 0) { try { int value = Integer.parseInt(property); this.setInitialSize(value); } catch (NumberFormatException e) { LOG.error("illegal property 'druid.initialSize'", e); } } } { String property = properties.getProperty("druid.minIdle"); if (property != null && property.length() > 0) { try { int value = Integer.parseInt(property); this.setMinIdle(value); } catch (NumberFormatException e) { LOG.error("illegal property 'druid.minIdle'", e); } } } { String property = properties.getProperty("druid.maxActive"); if (property != null && property.length() > 0) { try { int value = Integer.parseInt(property); this.setMaxActive(value); } catch (NumberFormatException e) { LOG.error("illegal property 'druid.maxActive'", e); } } } { Boolean value = getBoolean(properties, "druid.killWhenSocketReadTimeout"); if (value != null) { setKillWhenSocketReadTimeout(value); } } { String property = properties.getProperty("druid.connectProperties"); if (property != null) { this.setConnectionProperties(property); } } { String property = properties.getProperty("druid.maxPoolPreparedStatementPerConnectionSize"); if (property != null && property.length() > 0) { try { int value = Integer.parseInt(property); this.setMaxPoolPreparedStatementPerConnectionSize(value); } catch (NumberFormatException e) { LOG.error("illegal property 'druid.maxPoolPreparedStatementPerConnectionSize'", e); } } } { String property = properties.getProperty("druid.initConnectionSqls"); if (property != null && property.length() > 0) { try { StringTokenizer tokenizer = new StringTokenizer(property, ";"); setConnectionInitSqls(Collections.list(tokenizer)); } catch (NumberFormatException e) { LOG.error("illegal property 'druid.initConnectionSqls'", e); } } } { String property = System.getProperty("druid.load.spifilter.skip"); if (property != null && !"false".equals(property)) { loadSpifilterSkip = true; } } { String property = System.getProperty("druid.checkExecuteTime"); if (property != null && !"false".equals(property)) { checkExecuteTime = true; } } } public boolean isKillWhenSocketReadTimeout() { return killWhenSocketReadTimeout; } public void setKillWhenSocketReadTimeout(boolean killWhenSocketTimeOut) { this.killWhenSocketReadTimeout = killWhenSocketTimeOut; } public boolean isUseGlobalDataSourceStat() { return useGlobalDataSourceStat; } public void setUseGlobalDataSourceStat(boolean useGlobalDataSourceStat) { this.useGlobalDataSourceStat = useGlobalDataSourceStat; } public boolean isKeepAlive() { return keepAlive; } public void setKeepAlive(boolean keepAlive) { this.keepAlive = keepAlive; } public String getInitStackTrace() { return initStackTrace; } public boolean isResetStatEnable() { return resetStatEnable; } public void setResetStatEnable(boolean resetStatEnable) { this.resetStatEnable = resetStatEnable; if (dataSourceStat != null) { dataSourceStat.setResetStatEnable(resetStatEnable); } } public long getDiscardCount() { return discardCount; } public void restart() throws SQLException { this.restart(null); } public void restart(Properties properties) throws SQLException { lock.lock(); try { if (activeCount > 0) { throw new SQLException("can not restart, activeCount not zero. " + activeCount); } if (LOG.isInfoEnabled()) { LOG.info("{dataSource-" + this.getID() + "} restart"); } this.close(); this.resetStat(); this.inited = false; this.enable = true; this.closed = false; if (properties != null) { configFromPropeties(properties); } } finally { lock.unlock(); } } public void resetStat() { if (!isResetStatEnable()) { return; } lock.lock(); try { connectCount = 0; closeCount = 0; discardCount = 0; recycleCount = 0; createCount = 0L; directCreateCount = 0; destroyCount = 0L; removeAbandonedCount = 0; notEmptyWaitCount = 0; notEmptySignalCount = 0L; notEmptyWaitNanos = 0; activePeak = activeCount; activePeakTime = 0; poolingPeak = 0; createTimespan = 0; lastError = null; lastErrorTimeMillis = 0; lastCreateError = null; lastCreateErrorTimeMillis = 0; } finally { lock.unlock(); } connectErrorCountUpdater.set(this, 0); errorCountUpdater.set(this, 0); commitCountUpdater.set(this, 0); rollbackCountUpdater.set(this, 0); startTransactionCountUpdater.set(this, 0); cachedPreparedStatementHitCountUpdater.set(this, 0); closedPreparedStatementCountUpdater.set(this, 0); preparedStatementCountUpdater.set(this, 0); transactionHistogram.reset(); cachedPreparedStatementDeleteCountUpdater.set(this, 0); recycleErrorCountUpdater.set(this, 0); resetCountUpdater.incrementAndGet(this); } public long getResetCount() { return this.resetCount; } public boolean isEnable() { return enable; } public void setEnable(boolean enable) { lock.lock(); try { this.enable = enable; if (!enable) { notEmpty.signalAll(); notEmptySignalCount++; } } finally { lock.unlock(); } } public void setPoolPreparedStatements(boolean value) { setPoolPreparedStatements0(value); } private void setPoolPreparedStatements0(boolean value) { if (this.poolPreparedStatements == value) { return; } this.poolPreparedStatements = value; if (!inited) { return; } if (LOG.isInfoEnabled()) { LOG.info("set poolPreparedStatements " + this.poolPreparedStatements + " -> " + value); } if (!value) { lock.lock(); try { for (int i = 0; i < poolingCount; ++i) { DruidConnectionHolder connection = connections[i]; for (PreparedStatementHolder holder : connection.getStatementPool().getMap().values()) { closePreapredStatement(holder); } connection.getStatementPool().getMap().clear(); } } finally { lock.unlock(); } } } public void setMaxActive(int maxActive) { if (this.maxActive == maxActive) { return; } if (maxActive == 0) { throw new IllegalArgumentException("maxActive can't not set zero"); } if (!inited) { this.maxActive = maxActive; return; } if (maxActive < this.minIdle) { throw new IllegalArgumentException("maxActive less than minIdle, " + maxActive + " < " + this.minIdle); } if (LOG.isInfoEnabled()) { LOG.info("maxActive changed : " + this.maxActive + " -> " + maxActive); } lock.lock(); try { int allCount = this.poolingCount + this.activeCount; if (maxActive > allCount) { this.connections = Arrays.copyOf(this.connections, maxActive); evictConnections = new DruidConnectionHolder[maxActive]; keepAliveConnections = new DruidConnectionHolder[maxActive]; nullConnections = new DruidConnectionHolder[maxActive]; } else { this.connections = Arrays.copyOf(this.connections, allCount); evictConnections = new DruidConnectionHolder[allCount]; keepAliveConnections = new DruidConnectionHolder[allCount]; nullConnections = new DruidConnectionHolder[allCount]; } this.maxActive = maxActive; } finally { lock.unlock(); } } @SuppressWarnings("rawtypes") public void setConnectProperties(Properties properties) { if (properties == null) { properties = new Properties(); } boolean equals; if (properties.size() == this.connectProperties.size()) { equals = true; for (Map.Entry entry : properties.entrySet()) { if ( !Objects.equals( this.connectProperties.get(entry.getKey()), entry.getValue() ) ) { equals = false; break; } } } else { equals = false; } if (!equals) { if (inited && LOG.isInfoEnabled()) { LOG.info("connectProperties changed : " + this.connectProperties + " -> " + properties); } configFromPropeties(properties); for (Filter filter : this.filters) { filter.configFromProperties(properties); } if (exceptionSorter != null) { exceptionSorter.configFromProperties(properties); } if (validConnectionChecker != null) { validConnectionChecker.configFromProperties(properties); } if (statLogger != null) { statLogger.configFromProperties(properties); } } this.connectProperties = properties; } public void init() throws SQLException { if (inited) { return; } // bug fixed for dead lock, for issue #2980 DruidDriver.getInstance(); final ReentrantLock lock = this.lock; try { lock.lockInterruptibly(); } catch (InterruptedException e) { throw new SQLException("interrupt", e); } boolean init = false; try { if (inited) { return; } initStackTrace = Utils.toString(Thread.currentThread().getStackTrace()); this.id = DruidDriver.createDataSourceId(); if (this.id > 1) { long delta = (this.id - 1) * 100000; connectionIdSeedUpdater.addAndGet(this, delta); statementIdSeedUpdater.addAndGet(this, delta); resultSetIdSeedUpdater.addAndGet(this, delta); transactionIdSeedUpdater.addAndGet(this, delta); } if (this.jdbcUrl != null) { this.jdbcUrl = this.jdbcUrl.trim(); initFromWrapDriverUrl(); } initTimeoutsFromUrlOrProperties(); for (Filter filter : filters) { filter.init(this); } if (this.dbTypeName == null || this.dbTypeName.length() == 0) { this.dbTypeName = JdbcUtils.getDbType(jdbcUrl, null); } DbType dbType = DbType.of(this.dbTypeName); if (JdbcUtils.isMysqlDbType(dbType)) { boolean cacheServerConfigurationSet = false; if (this.connectProperties.containsKey("cacheServerConfiguration")) { cacheServerConfigurationSet = true; } else if (this.jdbcUrl.indexOf("cacheServerConfiguration") != -1) { cacheServerConfigurationSet = true; } if (cacheServerConfigurationSet) { this.connectProperties.put("cacheServerConfiguration", "true"); } } if (maxActive <= 0) { throw new IllegalArgumentException("illegal maxActive " + maxActive); } if (maxActive < minIdle) { throw new IllegalArgumentException("illegal maxActive " + maxActive); } if (getInitialSize() > maxActive) { throw new IllegalArgumentException("illegal initialSize " + this.initialSize + ", maxActive " + maxActive); } if (timeBetweenLogStatsMillis > 0 && useGlobalDataSourceStat) { throw new IllegalArgumentException("timeBetweenLogStatsMillis not support useGlobalDataSourceStat=true"); } if (maxEvictableIdleTimeMillis < minEvictableIdleTimeMillis) { throw new SQLException("maxEvictableIdleTimeMillis must be grater than minEvictableIdleTimeMillis"); } if (keepAlive && keepAliveBetweenTimeMillis <= timeBetweenEvictionRunsMillis) { throw new SQLException("keepAliveBetweenTimeMillis must be greater than timeBetweenEvictionRunsMillis"); } if (this.driverClass != null) { this.driverClass = driverClass.trim(); } initFromSPIServiceLoader(); resolveDriver(); initCheck(); this.netTimeoutExecutor = new SynchronousExecutor(); initExceptionSorter(); initValidConnectionChecker(); validationQueryCheck(); if (isUseGlobalDataSourceStat()) { dataSourceStat = JdbcDataSourceStat.getGlobal(); if (dataSourceStat == null) { dataSourceStat = new JdbcDataSourceStat("Global", "Global", this.dbTypeName); JdbcDataSourceStat.setGlobal(dataSourceStat); } if (dataSourceStat.getDbType() == null) { dataSourceStat.setDbType(this.dbTypeName); } } else { dataSourceStat = new JdbcDataSourceStat(this.name, this.jdbcUrl, this.dbTypeName, this.connectProperties); } dataSourceStat.setResetStatEnable(this.resetStatEnable); connections = new DruidConnectionHolder[maxActive]; evictConnections = new DruidConnectionHolder[maxActive]; keepAliveConnections = new DruidConnectionHolder[maxActive]; nullConnections = new DruidConnectionHolder[maxActive]; SQLException connectError = null; if (createScheduler != null && asyncInit) { for (int i = 0; i < initialSize; ++i) { submitCreateTask(true); } } else if (!asyncInit) { // init connections while (poolingCount < initialSize) { try { PhysicalConnectionInfo pyConnectInfo = createPhysicalConnection(); DruidConnectionHolder holder = new DruidConnectionHolder(this, pyConnectInfo); connections[poolingCount++] = holder; } catch (SQLException ex) { LOG.error("init datasource error, url: " + this.getUrl(), ex); if (initExceptionThrow) { connectError = ex; break; } else { Thread.sleep(3000); } } } if (poolingCount > 0) { poolingPeak = poolingCount; poolingPeakTime = System.currentTimeMillis(); } } createAndLogThread(); createAndStartCreatorThread(); createAndStartDestroyThread(); // await threads initedLatch to support dataSource restart. if (createConnectionThread != null) { createConnectionThread.getInitedLatch().await(); } if (destroyConnectionThread != null) { destroyConnectionThread.getInitedLatch().await(); } init = true; initedTime = new Date(); registerMbean(); if (connectError != null && poolingCount == 0) { throw connectError; } if (keepAlive) { if (createScheduler != null) { // async fill to minIdle for (int i = 0; i < minIdle - initialSize; ++i) { submitCreateTask(true); } } else { empty.signal(); } } } catch (SQLException e) { LOG.error("{dataSource-" + this.getID() + "} init error", e); throw e; } catch (InterruptedException e) { throw new SQLException(e.getMessage(), e); } catch (RuntimeException e) { LOG.error("{dataSource-" + this.getID() + "} init error", e); throw e; } catch (Error e) { LOG.error("{dataSource-" + this.getID() + "} init error", e); throw e; } finally { inited = true; lock.unlock(); if (init && LOG.isInfoEnabled()) { String msg = "{dataSource-" + this.getID(); if (this.name != null && !this.name.isEmpty()) { msg += ","; msg += this.name; } msg += "} inited"; LOG.info(msg); } } } private void initTimeoutsFromUrlOrProperties() { // createPhysicalConnection will set the corresponding parameters based on dbType. if (jdbcUrl != null && (jdbcUrl.indexOf("connectTimeout=") != -1 || jdbcUrl.indexOf("socketTimeout=") != -1)) { String[] items = jdbcUrl.split("(\\?|&)"); for (int i = 0; i < items.length; i++) { String item = items[i]; if (item.startsWith("connectTimeout=")) { String strVal = item.substring("connectTimeout=".length()); setConnectTimeout(strVal); } else if (item.startsWith("socketTimeout=")) { String strVal = item.substring("socketTimeout=".length()); setSocketTimeout(strVal); } } } Object propertyConnectTimeout = connectProperties.get("connectTimeout"); if (propertyConnectTimeout instanceof String) { setConnectTimeout((String) propertyConnectTimeout); } else if (propertyConnectTimeout instanceof Number) { setConnectTimeout(((Number) propertyConnectTimeout).intValue()); } Object propertySocketTimeout = connectProperties.get("socketTimeout"); if (propertySocketTimeout instanceof String) { setSocketTimeout((String) propertySocketTimeout); } else if (propertySocketTimeout instanceof Number) { setSocketTimeout(((Number) propertySocketTimeout).intValue()); } } /** * Issue 5192,Issue 5457 * @see <a href="https://dev.mysql.com/doc/connector-j/8.1/en/connector-j-reference-jdbc-url-format.html">MySQL Connection URL Syntax</a> * @see <a href="https://mariadb.com/kb/en/about-mariadb-connector-j/">About MariaDB Connector/J</a> * @param jdbcUrl * @return */ private static boolean isMysqlOrMariaDBUrl(String jdbcUrl) { return jdbcUrl.startsWith("jdbc:mysql://") || jdbcUrl.startsWith("jdbc:mysql:loadbalance://") || jdbcUrl.startsWith("jdbc:mysql:replication://") || jdbcUrl.startsWith("jdbc:mariadb://") || jdbcUrl.startsWith("jdbc:mariadb:loadbalance://") || jdbcUrl.startsWith("jdbc:mariadb:replication://"); } private void submitCreateTask(boolean initTask) { createTaskCount++; CreateConnectionTask task = new CreateConnectionTask(initTask); if (createTasks == null) { createTasks = new long[8]; } boolean putted = false; for (int i = 0; i < createTasks.length; ++i) { if (createTasks[i] == 0) { createTasks[i] = task.taskId; putted = true; break; } } if (!putted) { long[] array = new long[createTasks.length * 3 / 2]; System.arraycopy(createTasks, 0, array, 0, createTasks.length); array[createTasks.length] = task.taskId; createTasks = array; } this.createSchedulerFutures.put(task, createScheduler.submit(task)); } private boolean clearCreateTask(long taskId) { if (createTasks == null) { return false; } if (taskId == 0) { return false; } for (int i = 0; i < createTasks.length; i++) { if (createTasks[i] == taskId) { createTasks[i] = 0; createTaskCount--; if (createTaskCount < 0) { createTaskCount = 0; } if (createTaskCount == 0 && createTasks.length > 8) { createTasks = new long[8]; } return true; } } if (LOG.isWarnEnabled()) { LOG.warn("clear create task failed : " + taskId); } return false; } private void createAndLogThread() { if (this.timeBetweenLogStatsMillis <= 0) { return; } String threadName = "Druid-ConnectionPool-Log-" + System.identityHashCode(this); logStatsThread = new LogStatsThread(threadName); logStatsThread.start(); this.resetStatEnable = false; } protected void createAndStartDestroyThread() { destroyTask = new DestroyTask(); if (destroyScheduler != null) { long period = timeBetweenEvictionRunsMillis; if (period <= 0) { period = 1000; } destroySchedulerFuture = destroyScheduler.scheduleAtFixedRate(destroyTask, period, period, TimeUnit.MILLISECONDS); return; } String threadName = "Druid-ConnectionPool-Destroy-" + System.identityHashCode(this); destroyConnectionThread = new DestroyConnectionThread(threadName); destroyConnectionThread.start(); } protected void createAndStartCreatorThread() { if (createScheduler == null) { String threadName = "Druid-ConnectionPool-Create-" + System.identityHashCode(this); createConnectionThread = new CreateConnectionThread(threadName); createConnectionThread.start(); } } /** * load filters from SPI ServiceLoader * * @see ServiceLoader */ private void initFromSPIServiceLoader() { if (loadSpifilterSkip) { return; } if (autoFilters == null) { List<Filter> filters = new ArrayList<Filter>(); ServiceLoader<Filter> autoFilterLoader = ServiceLoader.load(Filter.class); for (Filter filter : autoFilterLoader) { AutoLoad autoLoad = filter.getClass().getAnnotation(AutoLoad.class); if (autoLoad != null && autoLoad.value()) { filters.add(filter); } } autoFilters = filters; } for (Filter filter : autoFilters) { if (LOG.isInfoEnabled()) { LOG.info("load filter from spi :" + filter.getClass().getName()); } addFilter(filter); } } private void initFromWrapDriverUrl() throws SQLException { if (!jdbcUrl.startsWith(DruidDriver.DEFAULT_PREFIX)) { return; } DataSourceProxyConfig config = DruidDriver.parseConfig(jdbcUrl, null); this.driverClass = config.getRawDriverClassName(); LOG.error("error url : '" + sanitizedUrl(jdbcUrl) + "', it should be : '" + config.getRawUrl() + "'"); this.jdbcUrl = config.getRawUrl(); if (this.name == null) { this.name = config.getName(); } for (Filter filter : config.getFilters()) { addFilter(filter); } } /** * 会去重复 * * @param filter */ private void addFilter(Filter filter) { boolean exists = false; for (Filter initedFilter : this.filters) { if (initedFilter.getClass() == filter.getClass()) { exists = true; break; } } if (!exists) { filter.init(this); this.filters.add(filter); } } private void validationQueryCheck() { if (!(testOnBorrow || testOnReturn || testWhileIdle)) { return; } if (this.validConnectionChecker != null) { return; } if (this.validationQuery != null && this.validationQuery.length() > 0) { return; } if ("odps".equals(dbTypeName)) { return; } String errorMessage = ""; if (testOnBorrow) { errorMessage += "testOnBorrow is true, "; } if (testOnReturn) { errorMessage += "testOnReturn is true, "; } if (testWhileIdle) { errorMessage += "testWhileIdle is true, "; } LOG.error(errorMessage + "validationQuery not set"); } protected void resolveDriver() throws SQLException { if (this.driver == null) { if (this.driverClass == null || this.driverClass.isEmpty()) { this.driverClass = JdbcUtils.getDriverClassName(this.jdbcUrl); } if (MockDriver.class.getName().equals(driverClass)) { driver = MockDriver.instance; } else if ("com.alibaba.druid.support.clickhouse.BalancedClickhouseDriver".equals(driverClass)) { Properties info = new Properties(); info.put("user", username); info.put("password", password); info.putAll(connectProperties); driver = new BalancedClickhouseDriver(jdbcUrl, info); } else if ("com.alibaba.druid.support.clickhouse.BalancedClickhouseDriverNative".equals(driverClass)) { Properties info = new Properties(); info.put("user", username); info.put("password", password); info.putAll(connectProperties); driver = new BalancedClickhouseDriverNative(jdbcUrl, info); } else { if (jdbcUrl == null && (driverClass == null || driverClass.length() == 0)) { throw new SQLException("url not set"); } driver = JdbcUtils.createDriver(driverClassLoader, driverClass); } } else { if (this.driverClass == null) { this.driverClass = driver.getClass().getName(); } } } protected void initCheck() throws SQLException { DbType dbType = DbType.of(this.dbTypeName); if (dbType == DbType.oracle) { isOracle = true; if (driver.getMajorVersion() < 10) { throw new SQLException("not support oracle driver " + driver.getMajorVersion() + "." + driver.getMinorVersion()); } if (driver.getMajorVersion() == 10 && isUseOracleImplicitCache()) { this.getConnectProperties().setProperty("oracle.jdbc.FreeMemoryOnEnterImplicitCache", "true"); } oracleValidationQueryCheck(); } else if (dbType == DbType.db2) { db2ValidationQueryCheck(); } else if (dbType == DbType.mysql || JdbcUtils.MYSQL_DRIVER.equals(this.driverClass) || JdbcUtils.MYSQL_DRIVER_6.equals(this.driverClass) || JdbcUtils.MYSQL_DRIVER_603.equals(this.driverClass) || JdbcUtils.GOLDENDB_DRIVER.equals(this.driverClass) || JdbcUtils.GBASE8S_DRIVER.equals(this.driverClass) ) { isMySql = true; } if (removeAbandoned) { LOG.warn("removeAbandoned is true, not use in production."); } } private void oracleValidationQueryCheck() { if (validationQuery == null) { return; } if (validationQuery.length() == 0) { return; } SQLStatementParser sqlStmtParser = SQLParserUtils.createSQLStatementParser(validationQuery, this.dbTypeName); List<SQLStatement> stmtList = sqlStmtParser.parseStatementList(); if (stmtList.size() != 1) { return; } SQLStatement stmt = stmtList.get(0); if (!(stmt instanceof SQLSelectStatement)) { return; } SQLSelectQuery query = ((SQLSelectStatement) stmt).getSelect().getQuery(); if (query instanceof SQLSelectQueryBlock) { if (((SQLSelectQueryBlock) query).getFrom() == null) { LOG.error("invalid oracle validationQuery. " + validationQuery + ", may should be : " + validationQuery + " FROM DUAL"); } } } private void db2ValidationQueryCheck() { if (validationQuery == null) { return; } if (validationQuery.length() == 0) { return; } SQLStatementParser sqlStmtParser = SQLParserUtils.createSQLStatementParser(validationQuery, this.dbTypeName); List<SQLStatement> stmtList = sqlStmtParser.parseStatementList(); if (stmtList.size() != 1) { return; } SQLStatement stmt = stmtList.get(0); if (!(stmt instanceof SQLSelectStatement)) { return; } SQLSelectQuery query = ((SQLSelectStatement) stmt).getSelect().getQuery(); if (query instanceof SQLSelectQueryBlock) { if (((SQLSelectQueryBlock) query).getFrom() == null) { LOG.error("invalid db2 validationQuery. " + validationQuery + ", may should be : " + validationQuery + " FROM SYSDUMMY"); } } } private void initValidConnectionChecker() { if (this.validConnectionChecker != null) { return; } String realDriverClassName = driver.getClass().getName(); if (JdbcUtils.isMySqlDriver(realDriverClassName)) { this.validConnectionChecker = new MySqlValidConnectionChecker(); } else if (realDriverClassName.equals(JdbcConstants.ORACLE_DRIVER) || realDriverClassName.equals(JdbcConstants.ORACLE_DRIVER2)) { this.validConnectionChecker = new OracleValidConnectionChecker(); } else if (realDriverClassName.equals(JdbcConstants.SQL_SERVER_DRIVER) || realDriverClassName.equals(JdbcConstants.SQL_SERVER_DRIVER_SQLJDBC4) || realDriverClassName.equals(JdbcConstants.SQL_SERVER_DRIVER_JTDS)) { this.validConnectionChecker = new MSSQLValidConnectionChecker(); } else if (realDriverClassName.equals(JdbcConstants.POSTGRESQL_DRIVER) || realDriverClassName.equals(JdbcConstants.ENTERPRISEDB_DRIVER) || realDriverClassName.equals(JdbcConstants.POLARDB_DRIVER)) { this.validConnectionChecker = new PGValidConnectionChecker(); } else if (realDriverClassName.equals(JdbcConstants.OCEANBASE_DRIVER) || (realDriverClassName.equals(JdbcConstants.OCEANBASE_DRIVER2))) { DbType dbType = DbType.of(this.dbTypeName); this.validConnectionChecker = new OceanBaseValidConnectionChecker(dbType); } } private void initExceptionSorter() { if (exceptionSorter instanceof NullExceptionSorter) { if (driver instanceof MockDriver) { return; } } else if (this.exceptionSorter != null) { return; } for (Class<?> driverClass = driver.getClass(); ; ) { String realDriverClassName = driverClass.getName(); if (realDriverClassName.equals(JdbcConstants.MYSQL_DRIVER) // || realDriverClassName.equals(JdbcConstants.MYSQL_DRIVER_6) || realDriverClassName.equals(JdbcConstants.MYSQL_DRIVER_603)) { this.exceptionSorter = new MySqlExceptionSorter(); this.isMySql = true; } else if (realDriverClassName.equals(JdbcConstants.ORACLE_DRIVER) || realDriverClassName.equals(JdbcConstants.ORACLE_DRIVER2)) { this.exceptionSorter = new OracleExceptionSorter(); } else if (realDriverClassName.equals(JdbcConstants.OCEANBASE_DRIVER)) { // 写一个真实的 TestCase if (JdbcUtils.OCEANBASE_ORACLE.name().equalsIgnoreCase(dbTypeName)) { this.exceptionSorter = new OceanBaseOracleExceptionSorter(); } else { this.exceptionSorter = new MySqlExceptionSorter(); } } else if (realDriverClassName.equals("com.informix.jdbc.IfxDriver")) { this.exceptionSorter = new InformixExceptionSorter(); } else if (realDriverClassName.equals("com.sybase.jdbc2.jdbc.SybDriver")) { this.exceptionSorter = new SybaseExceptionSorter(); } else if (realDriverClassName.equals(JdbcConstants.POSTGRESQL_DRIVER) || realDriverClassName.equals(JdbcConstants.ENTERPRISEDB_DRIVER) || realDriverClassName.equals(JdbcConstants.POLARDB_DRIVER)) { this.exceptionSorter = new PGExceptionSorter(); } else if (realDriverClassName.equals("com.alibaba.druid.mock.MockDriver")) { this.exceptionSorter = new MockExceptionSorter(); } else if (realDriverClassName.contains("DB2")) { this.exceptionSorter = new DB2ExceptionSorter(); } else { Class<?> superClass = driverClass.getSuperclass(); if (superClass != null && superClass != Object.class) { driverClass = superClass; continue; } } break; } } @Override public DruidPooledConnection getConnection() throws SQLException { return getConnection(maxWait); } public DruidPooledConnection getConnection(long maxWaitMillis) throws SQLException { if (jdbcUrl == null || jdbcUrl.isEmpty()) { LOG.warn("getConnection but jdbcUrl is not set,jdbcUrl=" + jdbcUrl + ",username=" + username); return null; } init(); final int filtersSize = filters.size(); if (filtersSize > 0) { FilterChainImpl filterChain = createChain(); try { return filterChain.dataSource_connect(this, maxWaitMillis); } finally { recycleFilterChain(filterChain); } } else { return getConnectionDirect(maxWaitMillis); } } @Override public PooledConnection getPooledConnection() throws SQLException { return getConnection(maxWait); } @Override public PooledConnection getPooledConnection(String user, String password) throws SQLException { throw new UnsupportedOperationException("Not supported by DruidDataSource"); } public DruidPooledConnection getConnectionDirect(long maxWaitMillis) throws SQLException { int notFullTimeoutRetryCnt = 0; for (; ; ) { // handle notFullTimeoutRetry DruidPooledConnection poolableConnection; try { poolableConnection = getConnectionInternal(maxWaitMillis); } catch (GetConnectionTimeoutException ex) { if (notFullTimeoutRetryCnt < this.notFullTimeoutRetryCount && !isFull()) { notFullTimeoutRetryCnt++; if (LOG.isWarnEnabled()) { LOG.warn("get connection timeout retry : " + notFullTimeoutRetryCnt); } continue; } throw ex; } if (testOnBorrow) { boolean validated = testConnectionInternal(poolableConnection.holder, poolableConnection.conn); if (!validated) { if (LOG.isDebugEnabled()) { LOG.debug("skip not validated connection."); } discardConnection(poolableConnection.holder); continue; } } else { if (poolableConnection.conn.isClosed()) { discardConnection(poolableConnection.holder); // 传入null,避免重复关闭 continue; } if (testWhileIdle) { final DruidConnectionHolder holder = poolableConnection.holder; long currentTimeMillis = System.currentTimeMillis(); long lastActiveTimeMillis = holder.lastActiveTimeMillis; long lastExecTimeMillis = holder.lastExecTimeMillis; long lastKeepTimeMillis = holder.lastKeepTimeMillis; if (checkExecuteTime && lastExecTimeMillis != lastActiveTimeMillis) { lastActiveTimeMillis = lastExecTimeMillis; } if (lastKeepTimeMillis > lastActiveTimeMillis) { lastActiveTimeMillis = lastKeepTimeMillis; } long idleMillis = currentTimeMillis - lastActiveTimeMillis; if (idleMillis >= timeBetweenEvictionRunsMillis || idleMillis < 0 // unexcepted branch ) { boolean validated = testConnectionInternal(poolableConnection.holder, poolableConnection.conn); if (!validated) { if (LOG.isDebugEnabled()) { LOG.debug("skip not validated connection."); } discardConnection(poolableConnection.holder); continue; } } } } if (removeAbandoned) { StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); poolableConnection.connectStackTrace = stackTrace; poolableConnection.setConnectedTimeNano(); poolableConnection.traceEnable = true; activeConnectionLock.lock(); try { activeConnections.put(poolableConnection, PRESENT); } finally { activeConnectionLock.unlock(); } } if (!this.defaultAutoCommit) { poolableConnection.setAutoCommit(false); } return poolableConnection; } } /** * 抛弃连接,不进行回收,而是抛弃 * * @param conn the connection to be discarded * @return a boolean indicating whether the empty signal was called * @deprecated */ @Override public boolean discardConnection(Connection conn) { boolean emptySignalCalled = false; if (conn == null) { return emptySignalCalled; } try { if (!conn.isClosed()) { conn.close(); } } catch (SQLRecoverableException ignored) { discardErrorCountUpdater.incrementAndGet(this); // ignored } catch (Throwable e) { discardErrorCountUpdater.incrementAndGet(this); if (LOG.isDebugEnabled()) { LOG.debug("discard to close connection error", e); } } lock.lock(); try { activeCount--; discardCount++; int fillCount = minIdle - (activeCount + poolingCount + createTaskCount); if (fillCount > 0) { emptySignalCalled = true; emptySignal(fillCount); } } finally { lock.unlock(); } return emptySignalCalled; } @Override public boolean discardConnection(DruidConnectionHolder holder) { boolean emptySignalCalled = false; if (holder == null) { return emptySignalCalled; } Connection conn = holder.getConnection(); if (conn != null) { JdbcUtils.close(conn); } Socket socket = holder.socket; if (socket != null) { JdbcUtils.close(socket); } lock.lock(); try { if (holder.discard) { return emptySignalCalled; } if (holder.active) { activeCount--; holder.active = false; } discardCount++; holder.discard = true; int fillCount = minIdle - (activeCount + poolingCount + createTaskCount); if (fillCount > 0) { emptySignalCalled = true; emptySignal(fillCount); } } finally { lock.unlock(); } return emptySignalCalled; } private DruidPooledConnection getConnectionInternal(long maxWait) throws SQLException { if (closed) { connectErrorCountUpdater.incrementAndGet(this); throw new DataSourceClosedException("dataSource already closed at " + new Date(closeTimeMillis)); } if (!enable) { connectErrorCountUpdater.incrementAndGet(this); if (disableException != null) { throw disableException; } throw new DataSourceDisableException(); } final int maxWaitThreadCount = this.maxWaitThreadCount; DruidConnectionHolder holder; long startTime = System.currentTimeMillis(); //进入循环等待之前,先记录开始尝试获取连接的时间 final long expiredTime = startTime + maxWait; for (boolean createDirect = false; ; ) { if (createDirect) { try { createStartNanosUpdater.set(this, System.nanoTime()); if (creatingCountUpdater.compareAndSet(this, 0, 1)) { PhysicalConnectionInfo pyConnInfo = DruidDataSource.this.createPhysicalConnection(); holder = new DruidConnectionHolder(this, pyConnInfo); holder.lastActiveTimeMillis = System.currentTimeMillis(); creatingCountUpdater.decrementAndGet(this); directCreateCountUpdater.incrementAndGet(this); if (LOG.isDebugEnabled()) { LOG.debug("conn-direct_create "); } final Lock lock = this.lock; lock.lock(); try { if (activeCount + poolingCount < maxActive) { activeCount++; holder.active = true; if (activeCount > activePeak) { activePeak = activeCount; activePeakTime = System.currentTimeMillis(); } break; } } finally { lock.unlock(); } JdbcUtils.close(pyConnInfo.getPhysicalConnection()); } } finally { createDirect = false; createDirectCountUpdater.decrementAndGet(this); } } final ReentrantLock lock = this.lock; try { lock.lockInterruptibly(); } catch (InterruptedException e) { connectErrorCountUpdater.incrementAndGet(this); throw new SQLException("interrupt", e); } try { if (maxWaitThreadCount > 0 && notEmptyWaitThreadCount > maxWaitThreadCount) { connectErrorCountUpdater.incrementAndGet(this); throw new SQLException("maxWaitThreadCount " + maxWaitThreadCount + ", current wait Thread count " + lock.getQueueLength()); } if (onFatalError && onFatalErrorMaxActive > 0 && activeCount >= onFatalErrorMaxActive) { connectErrorCountUpdater.incrementAndGet(this); StringBuilder errorMsg = new StringBuilder(); errorMsg.append("onFatalError, activeCount ") .append(activeCount) .append(", onFatalErrorMaxActive ") .append(onFatalErrorMaxActive); if (lastFatalErrorTimeMillis > 0) { errorMsg.append(", time '") .append(StringUtils.formatDateTime19( lastFatalErrorTimeMillis, TimeZone.getDefault())) .append("'"); } if (lastFatalErrorSql != null) { errorMsg.append(", sql \n") .append(lastFatalErrorSql); } throw new SQLException( errorMsg.toString(), lastFatalError); } connectCount++; if (createScheduler != null && poolingCount == 0 && activeCount < maxActive && createDirectCountUpdater.get(this) == 0 && creatingCountUpdater.get(this) == 0 && createScheduler instanceof ScheduledThreadPoolExecutor) { ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor) createScheduler; if (executor.getQueue().size() > 0) { if (maxWait > 0 && System.currentTimeMillis() - startTime >= maxWait) { holder = null; break; } createDirect = true; createDirectCountUpdater.incrementAndGet(this); continue; } } if (maxWait > 0) { if (System.currentTimeMillis() < expiredTime) { holder = pollLast(startTime, expiredTime); } else { holder = null; break; } } else { holder = takeLast(startTime); } if (holder != null) { if (holder.discard) { holder = null; if (maxWait > 0 && System.currentTimeMillis() >= expiredTime) { break; } continue; } activeCount++; holder.active = true; if (activeCount > activePeak) { activePeak = activeCount; activePeakTime = System.currentTimeMillis(); } } } catch (InterruptedException e) { connectErrorCountUpdater.incrementAndGet(this); throw new SQLException(e.getMessage(), e); } catch (SQLException e) { connectErrorCountUpdater.incrementAndGet(this); throw e; } finally { lock.unlock(); } break; } if (holder == null) { long waitMillis = System.currentTimeMillis() - startTime; final long activeCount; final long maxActive; final long creatingCount; final long createStartNanos; final long createErrorCount; final Throwable createError; try { lock.lock(); activeCount = this.activeCount; maxActive = this.maxActive; creatingCount = this.creatingCount; createStartNanos = this.createStartNanos; createErrorCount = this.createErrorCount; createError = this.createError; } finally { lock.unlock(); } StringBuilder buf = new StringBuilder(128); buf.append("wait millis ") .append(waitMillis) .append(", active ").append(activeCount) .append(", maxActive ").append(maxActive) .append(", creating ").append(creatingCount); if (creatingCount > 0 && createStartNanos > 0) { long createElapseMillis = (System.nanoTime() - createStartNanos) / (1000 * 1000); if (createElapseMillis > 0) { buf.append(", createElapseMillis ").append(createElapseMillis); } } if (createErrorCount > 0) { buf.append(", createErrorCount ").append(createErrorCount); } List<JdbcSqlStatValue> sqlList = this.getDataSourceStat().getRuningSqlList(); for (int i = 0; i < sqlList.size(); ++i) { if (i != 0) { buf.append('\n'); } else { buf.append(", "); } JdbcSqlStatValue sql = sqlList.get(i); buf.append("runningSqlCount ").append(sql.getRunningCount()); buf.append(" : "); buf.append(sql.getSql()); } String errorMessage = buf.toString(); if (createError != null) { throw new GetConnectionTimeoutException(errorMessage, createError); } else { throw new GetConnectionTimeoutException(errorMessage); } } holder.incrementUseCount(); return new DruidPooledConnection(holder); } public void handleConnectionException( DruidPooledConnection pooledConnection, Throwable t, String sql ) throws SQLException { final DruidConnectionHolder holder = pooledConnection.getConnectionHolder(); if (holder == null) { return; } errorCountUpdater.incrementAndGet(this); lastError = t; lastErrorTimeMillis = System.currentTimeMillis(); if (t instanceof SQLException) { SQLException sqlEx = (SQLException) t; // broadcastConnectionError ConnectionEvent event = new ConnectionEvent(pooledConnection, sqlEx); for (ConnectionEventListener eventListener : holder.getConnectionEventListeners()) { eventListener.connectionErrorOccurred(event); } // exceptionSorter.isExceptionFatal if (exceptionSorter != null && exceptionSorter.isExceptionFatal(sqlEx)) { handleFatalError(pooledConnection, sqlEx, sql); } throw sqlEx; } else { throw new SQLException("Error", t); } } protected final void handleFatalError( DruidPooledConnection conn, SQLException error, String sql ) throws SQLException { final DruidConnectionHolder holder = conn.holder; if (conn.isTraceEnable()) { activeConnectionLock.lock(); try { if (conn.isTraceEnable()) { activeConnections.remove(conn); conn.setTraceEnable(false); } } finally { activeConnectionLock.unlock(); } } long lastErrorTimeMillis = this.lastErrorTimeMillis; if (lastErrorTimeMillis == 0) { lastErrorTimeMillis = System.currentTimeMillis(); } if (sql != null && sql.length() > 1024) { sql = sql.substring(0, 1024); } boolean requireDiscard = false; // using dataSourceLock when holder dataSource isn't null because shrink used it to access fatal error variables. boolean hasHolderDataSource = (holder != null && holder.getDataSource() != null); ReentrantLock fatalErrorCountLock = hasHolderDataSource ? holder.getDataSource().lock : conn.lock; fatalErrorCountLock.lock(); try { if ((!conn.closed) && !conn.disable) { conn.disable(error); requireDiscard = true; } lastFatalErrorTimeMillis = lastErrorTimeMillis; fatalErrorCount++; if (fatalErrorCount - fatalErrorCountLastShrink > onFatalErrorMaxActive) { // increase fatalErrorCountLastShrink to avoid that emptySignal would be called again by shrink. fatalErrorCountLastShrink++; onFatalError = true; } else { onFatalError = false; } lastFatalError = error; lastFatalErrorSql = sql; } finally { fatalErrorCountLock.unlock(); } boolean emptySignalCalled = false; if (requireDiscard) { if (holder != null && holder.statementTrace != null) { holder.lock.lock(); try { for (Statement stmt : holder.statementTrace) { JdbcUtils.close(stmt); } } finally { holder.lock.unlock(); } } // decrease activeCount first to make sure the following emptySignal should be called successfully. emptySignalCalled = this.discardConnection(holder); } // holder. LOG.error("{conn-" + (holder != null ? holder.getConnectionId() : "null") + "} discard", error); if (!emptySignalCalled && onFatalError && hasHolderDataSource) { fatalErrorCountLock.lock(); try { emptySignal(); } finally { fatalErrorCountLock.unlock(); } } } /** * 回收连接 */ protected void recycle(DruidPooledConnection pooledConnection) throws SQLException { final DruidConnectionHolder holder = pooledConnection.holder; if (holder == null) { LOG.warn("connectionHolder is null"); return; } boolean asyncCloseConnectionEnable = this.removeAbandoned || this.asyncCloseConnectionEnable; boolean isSameThread = pooledConnection.ownerThread == Thread.currentThread(); if (logDifferentThread // && (!asyncCloseConnectionEnable) // && !isSameThread ) { LOG.warn("get/close not same thread"); } final Connection physicalConnection = holder.conn; if (pooledConnection.traceEnable) { Object oldInfo = null; activeConnectionLock.lock(); try { if (pooledConnection.traceEnable) { oldInfo = activeConnections.remove(pooledConnection); pooledConnection.traceEnable = false; } } finally { activeConnectionLock.unlock(); } if (oldInfo == null) { if (LOG.isWarnEnabled()) { LOG.warn("remove abandoned failed. activeConnections.size " + activeConnections.size()); } } } final boolean isAutoCommit = holder.underlyingAutoCommit; final boolean isReadOnly = holder.underlyingReadOnly; final boolean testOnReturn = this.testOnReturn; try { // check need to rollback? if ((!isAutoCommit) && (!isReadOnly)) { pooledConnection.rollback(); } // reset holder, restore default settings, clear warnings if (!isSameThread) { final ReentrantLock lock = pooledConnection.lock; lock.lock(); try { holder.reset(); } finally { lock.unlock(); } } else { holder.reset(); } if (holder.discard) { return; } if (phyMaxUseCount > 0 && holder.useCount >= phyMaxUseCount) { discardConnection(holder); return; } if (physicalConnection.isClosed()) { lock.lock(); try { if (holder.active) { activeCount--; holder.active = false; } closeCount++; } finally { lock.unlock(); } return; } if (testOnReturn) { boolean validated = testConnectionInternal(holder, physicalConnection); if (!validated) { JdbcUtils.close(physicalConnection); destroyCountUpdater.incrementAndGet(this); lock.lock(); try { if (holder.active) { activeCount--; holder.active = false; } closeCount++; } finally { lock.unlock(); } return; } } if (holder.initSchema != null) { holder.conn.setSchema(holder.initSchema); holder.initSchema = null; } if (!enable) { discardConnection(holder); return; } boolean result; final long currentTimeMillis = System.currentTimeMillis(); if (phyTimeoutMillis > 0) { long phyConnectTimeMillis = currentTimeMillis - holder.connectTimeMillis; if (phyConnectTimeMillis > phyTimeoutMillis) { discardConnection(holder); return; } } lock.lock(); try { if (holder.active) { activeCount--; holder.active = false; } closeCount++; result = putLast(holder, currentTimeMillis); recycleCount++; } finally { lock.unlock(); } if (!result) { JdbcUtils.close(holder.conn); LOG.info("connection recycle failed."); } } catch (Throwable e) { holder.clearStatementCache(); if (!holder.discard) { discardConnection(holder); holder.discard = true; } LOG.error("recycle error", e); recycleErrorCountUpdater.incrementAndGet(this); } } public long getRecycleErrorCount() { return recycleErrorCount; } public void clearStatementCache() throws SQLException { lock.lock(); try { for (int i = 0; i < poolingCount; ++i) { DruidConnectionHolder conn = connections[i]; if (conn.statementPool != null) { conn.statementPool.clear(); } } } finally { lock.unlock(); } } /** * close datasource */ public void close() { if (LOG.isInfoEnabled()) { LOG.info("{dataSource-" + this.getID() + "} closing ..."); } lock.lock(); try { if (this.closed) { return; } if (!this.inited) { return; } this.closing = true; if (logStatsThread != null) { logStatsThread.interrupt(); } if (createConnectionThread != null) { createConnectionThread.interrupt(); } if (destroyConnectionThread != null) { destroyConnectionThread.interrupt(); } for (Future<?> createSchedulerFuture : createSchedulerFutures.values()) { createSchedulerFuture.cancel(true); } if (destroySchedulerFuture != null) { destroySchedulerFuture.cancel(true); } for (int i = 0; i < poolingCount; ++i) { DruidConnectionHolder connHolder = connections[i]; for (PreparedStatementHolder stmtHolder : connHolder.getStatementPool().getMap().values()) { connHolder.getStatementPool().closeRemovedStatement(stmtHolder); } connHolder.getStatementPool().getMap().clear(); Connection physicalConnection = connHolder.getConnection(); try { physicalConnection.close(); } catch (Exception ex) { LOG.warn("close connection error", ex); } connections[i] = null; destroyCountUpdater.incrementAndGet(this); } poolingCount = 0; unregisterMbean(); enable = false; notEmpty.signalAll(); notEmptySignalCount++; this.closed = true; this.closeTimeMillis = System.currentTimeMillis(); disableException = new DataSourceDisableException(); for (Filter filter : filters) { filter.destroy(); } } finally { this.closing = false; lock.unlock(); } if (LOG.isInfoEnabled()) { LOG.info("{dataSource-" + this.getID() + "} closed"); } } public void registerMbean() { if (!mbeanRegistered) { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { ObjectName objectName = DruidDataSourceStatManager.addDataSource(DruidDataSource.this, DruidDataSource.this.name); DruidDataSource.this.setObjectName(objectName); DruidDataSource.this.mbeanRegistered = true; return null; } }); } } public void unregisterMbean() { if (mbeanRegistered) { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { DruidDataSourceStatManager.removeDataSource(DruidDataSource.this); DruidDataSource.this.mbeanRegistered = false; return null; } }); } } public boolean isMbeanRegistered() { return mbeanRegistered; } boolean putLast(DruidConnectionHolder e, long lastActiveTimeMillis) { if (activeCount + poolingCount >= maxActive || e.discard || this.closed || this.closing) { return false; } e.lastActiveTimeMillis = lastActiveTimeMillis; connections[poolingCount] = e; incrementPoolingCount(); if (poolingCount > poolingPeak) { poolingPeak = poolingCount; poolingPeakTime = lastActiveTimeMillis; } notEmpty.signal(); notEmptySignalCount++; return true; } private DruidConnectionHolder takeLast(long startTime) throws InterruptedException, SQLException { return pollLast(startTime, 0); } private DruidConnectionHolder pollLast(long startTime, long expiredTime) throws InterruptedException, SQLException { try { long awaitStartTime; long estimate = 0; while (poolingCount == 0) { // send signal to CreateThread create connection emptySignal(); if (failFast && isFailContinuous()) { throw new DataSourceNotAvailableException(createError); } awaitStartTime = System.currentTimeMillis(); if (expiredTime != 0) { estimate = expiredTime - awaitStartTime; if (estimate <= 0) { return null; } } notEmptyWaitThreadCount++; if (notEmptyWaitThreadCount > notEmptyWaitThreadPeak) { notEmptyWaitThreadPeak = notEmptyWaitThreadCount; } try { // signal by recycle or creator if (estimate == 0) { notEmpty.await(); } else { notEmpty.await(estimate, TimeUnit.MILLISECONDS); } } finally { notEmptyWaitThreadCount--; notEmptyWaitCount++; notEmptyWaitNanos += TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis() - awaitStartTime); } if (!enable) { connectErrorCountUpdater.incrementAndGet(this); if (disableException != null) { throw disableException; } throw new DataSourceDisableException(); } } } catch (InterruptedException ie) { notEmpty.signal(); // propagate to non-interrupted thread notEmptySignalCount++; throw ie; } decrementPoolingCount(); DruidConnectionHolder last = connections[poolingCount]; connections[poolingCount] = null; long waitNanos = System.currentTimeMillis() - startTime; last.setLastNotEmptyWaitNanos(waitNanos); return last; } private final void decrementPoolingCount() { poolingCount--; } private final void incrementPoolingCount() { poolingCount++; } @Override public Connection getConnection(String username, String password) throws SQLException { if (this.username == null && this.password == null && username != null && password != null) { this.username = username; this.password = password; return getConnection(); } if (!StringUtils.equals(username, this.username)) { throw new UnsupportedOperationException("Not supported by DruidDataSource"); } if (!StringUtils.equals(password, this.password)) { throw new UnsupportedOperationException("Not supported by DruidDataSource"); } return getConnection(); } public long getCreateCount() { lock.lock(); try { return createCount; } finally { lock.unlock(); } } public long getDestroyCount() { lock.lock(); try { return destroyCount; } finally { lock.unlock(); } } public long getConnectCount() { lock.lock(); try { return connectCount; } finally { lock.unlock(); } } public long getCloseCount() { return closeCount; } public long getConnectErrorCount() { return connectErrorCountUpdater.get(this); } @Override public int getPoolingCount() { lock.lock(); try { return poolingCount; } finally { lock.unlock(); } } public int getPoolingPeak() { lock.lock(); try { return poolingPeak; } finally { lock.unlock(); } } public Date getPoolingPeakTime() { if (poolingPeakTime <= 0) { return null; } return new Date(poolingPeakTime); } public long getRecycleCount() { return recycleCount; } public int getActiveCount() { lock.lock(); try { return activeCount; } finally { lock.unlock(); } } public void logStats() { final DruidDataSourceStatLogger statLogger = this.statLogger; if (statLogger == null) { return; } DruidDataSourceStatValue statValue = getStatValueAndReset(); statLogger.log(statValue); } public DruidDataSourceStatValue getStatValueAndReset() { DruidDataSourceStatValue value = new DruidDataSourceStatValue(); lock.lock(); try { value.setPoolingCount(this.poolingCount); value.setPoolingPeak(this.poolingPeak); value.setPoolingPeakTime(this.poolingPeakTime); value.setActiveCount(this.activeCount); value.setActivePeak(this.activePeak); value.setActivePeakTime(this.activePeakTime); value.setConnectCount(this.connectCount); value.setCloseCount(this.closeCount); value.setWaitThreadCount(lock.getWaitQueueLength(notEmpty)); value.setNotEmptyWaitCount(this.notEmptyWaitCount); value.setNotEmptyWaitNanos(this.notEmptyWaitNanos); value.setKeepAliveCheckCount(this.keepAliveCheckCount); // reset this.poolingPeak = 0; this.poolingPeakTime = 0; this.activePeak = 0; this.activePeakTime = 0; this.connectCount = 0; this.closeCount = 0; this.keepAliveCheckCount = 0; this.notEmptyWaitCount = 0; this.notEmptyWaitNanos = 0; } finally { lock.unlock(); } value.setName(this.getName()); value.setDbType(this.dbTypeName); value.setDriverClassName(this.getDriverClassName()); value.setUrl(this.getUrl()); value.setUserName(this.getUsername()); value.setFilterClassNames(this.getFilterClassNames()); value.setInitialSize(this.getInitialSize()); value.setMinIdle(this.getMinIdle()); value.setMaxActive(this.getMaxActive()); value.setQueryTimeout(this.getQueryTimeout()); value.setTransactionQueryTimeout(this.getTransactionQueryTimeout()); value.setLoginTimeout(this.getLoginTimeout()); value.setValidConnectionCheckerClassName(this.getValidConnectionCheckerClassName()); value.setExceptionSorterClassName(this.getExceptionSorterClassName()); value.setTestOnBorrow(this.testOnBorrow); value.setTestOnReturn(this.testOnReturn); value.setTestWhileIdle(this.testWhileIdle); value.setDefaultAutoCommit(this.isDefaultAutoCommit()); if (defaultReadOnly != null) { value.setDefaultReadOnly(defaultReadOnly); } value.setDefaultTransactionIsolation(this.getDefaultTransactionIsolation()); value.setLogicConnectErrorCount(connectErrorCountUpdater.getAndSet(this, 0)); value.setPhysicalConnectCount(createCountUpdater.getAndSet(this, 0)); value.setPhysicalCloseCount(destroyCountUpdater.getAndSet(this, 0)); value.setPhysicalConnectErrorCount(createErrorCountUpdater.getAndSet(this, 0)); value.setExecuteCount(this.getAndResetExecuteCount()); value.setErrorCount(errorCountUpdater.getAndSet(this, 0)); value.setCommitCount(commitCountUpdater.getAndSet(this, 0)); value.setRollbackCount(rollbackCountUpdater.getAndSet(this, 0)); value.setPstmtCacheHitCount(cachedPreparedStatementHitCountUpdater.getAndSet(this, 0)); value.setPstmtCacheMissCount(cachedPreparedStatementMissCountUpdater.getAndSet(this, 0)); value.setStartTransactionCount(startTransactionCountUpdater.getAndSet(this, 0)); value.setTransactionHistogram(this.getTransactionHistogram().toArrayAndReset()); value.setConnectionHoldTimeHistogram(this.getDataSourceStat().getConnectionHoldHistogram().toArrayAndReset()); value.setRemoveAbandoned(this.isRemoveAbandoned()); value.setClobOpenCount(this.getDataSourceStat().getClobOpenCountAndReset()); value.setBlobOpenCount(this.getDataSourceStat().getBlobOpenCountAndReset()); value.setSqlSkipCount(this.getDataSourceStat().getSkipSqlCountAndReset()); value.setSqlList(this.getDataSourceStat().getSqlStatMapAndReset()); return value; } public long getRemoveAbandonedCount() { return removeAbandonedCount; } protected boolean put(PhysicalConnectionInfo physicalConnectionInfo) { DruidConnectionHolder holder = null; try { holder = new DruidConnectionHolder(DruidDataSource.this, physicalConnectionInfo); } catch (SQLException ex) { lock.lock(); try { if (createScheduler != null) { clearCreateTask(physicalConnectionInfo.createTaskId); } } finally { lock.unlock(); } LOG.error("create connection holder error", ex); return false; } return put(holder, physicalConnectionInfo.createTaskId, false); } private boolean put(DruidConnectionHolder holder, long createTaskId, boolean checkExists) { lock.lock(); try { if (this.closing || this.closed) { return false; } if (activeCount + poolingCount >= maxActive) { if (createScheduler != null) { clearCreateTask(createTaskId); } return false; } if (checkExists) { for (int i = 0; i < poolingCount; i++) { if (connections[i] == holder) { return false; } } } connections[poolingCount] = holder; incrementPoolingCount(); if (poolingCount > poolingPeak) { poolingPeak = poolingCount; poolingPeakTime = System.currentTimeMillis(); } notEmpty.signal(); notEmptySignalCount++; if (createScheduler != null) { clearCreateTask(createTaskId); if (poolingCount + createTaskCount < notEmptyWaitThreadCount) { emptySignal(); } } } finally { lock.unlock(); } return true; } public class CreateConnectionTask implements Runnable { private int errorCount; private boolean initTask; private final long taskId; public CreateConnectionTask() { taskId = createTaskIdSeedUpdater.getAndIncrement(DruidDataSource.this); } public CreateConnectionTask(boolean initTask) { taskId = createTaskIdSeedUpdater.getAndIncrement(DruidDataSource.this); this.initTask = initTask; } @Override public void run() { runInternal(); } private void runInternal() { for (; ; ) { // addLast lock.lock(); try { if (closed || closing) { clearCreateTask(taskId); return; } boolean emptyWait = createError == null || poolingCount != 0; if (emptyWait) { // 必须存在线程等待,才创建连接 if (poolingCount >= notEmptyWaitThreadCount // && (!(keepAlive && activeCount + poolingCount < minIdle)) // 在keepAlive场景不能放弃创建 && (!initTask) // 线程池初始化时的任务不能放弃创建 && !isFailContinuous() // failContinuous时不能放弃创建,否则会无法创建线程 && !isOnFatalError() // onFatalError时不能放弃创建,否则会无法创建线程 ) { clearCreateTask(taskId); return; } } // 防止创建超过maxActive数量的连接 if (activeCount + poolingCount >= maxActive) { clearCreateTask(taskId); return; } } finally { lock.unlock(); } PhysicalConnectionInfo physicalConnection = null; try { physicalConnection = createPhysicalConnection(); } catch (OutOfMemoryError e) { LOG.error("create connection OutOfMemoryError, out memory. ", e); errorCount++; if (errorCount > connectionErrorRetryAttempts && timeBetweenConnectErrorMillis > 0) { // fail over retry attempts setFailContinuous(true); if (failFast) { lock.lock(); try { notEmpty.signalAll(); } finally { lock.unlock(); } } if (breakAfterAcquireFailure || closing || closed) { lock.lock(); try { clearCreateTask(taskId); } finally { lock.unlock(); } return; } // reset errorCount this.errorCount = 0; createSchedulerFutures.put(this, createScheduler.schedule(this, timeBetweenConnectErrorMillis, TimeUnit.MILLISECONDS)); return; } } catch (SQLException e) { LOG.error("create connection SQLException, url: " + sanitizedUrl(jdbcUrl), e); errorCount++; if (errorCount > connectionErrorRetryAttempts && timeBetweenConnectErrorMillis > 0) { // fail over retry attempts setFailContinuous(true); if (failFast) { lock.lock(); try { notEmpty.signalAll(); } finally { lock.unlock(); } } if (breakAfterAcquireFailure || closing || closed) { lock.lock(); try { clearCreateTask(taskId); } finally { lock.unlock(); } return; } // reset errorCount this.errorCount = 0; createSchedulerFutures.put(this, createScheduler.schedule(this, timeBetweenConnectErrorMillis, TimeUnit.MILLISECONDS)); return; } } catch (RuntimeException e) { LOG.error("create connection RuntimeException", e); // unknown fatal exception setFailContinuous(true); continue; } catch (Error e) { lock.lock(); try { clearCreateTask(taskId); } finally { lock.unlock(); } LOG.error("create connection Error", e); // unknown fatal exception setFailContinuous(true); break; } catch (Throwable e) { lock.lock(); try { clearCreateTask(taskId); } finally { lock.unlock(); } LOG.error("create connection unexpected error.", e); break; } if (physicalConnection == null) { continue; } physicalConnection.createTaskId = taskId; boolean result = put(physicalConnection); if (!result) { JdbcUtils.close(physicalConnection.getPhysicalConnection()); LOG.info("put physical connection to pool failed."); } break; } } } public class CreateConnectionThread extends Thread { private final CountDownLatch initedLatch = new CountDownLatch(1); public CreateConnectionThread(String name) { super(name); this.setDaemon(true); } public CountDownLatch getInitedLatch() { return initedLatch; } public void run() { initedLatch.countDown(); long lastDiscardCount = 0; int errorCount = 0; while (!closing && !closed && !Thread.currentThread().isInterrupted()) { // addLast try { lock.lockInterruptibly(); } catch (InterruptedException e2) { break; } long discardCount = DruidDataSource.this.discardCount; boolean discardChanged = discardCount - lastDiscardCount > 0; lastDiscardCount = discardCount; try { boolean emptyWait = createError == null || poolingCount != 0 || discardChanged; if (emptyWait && asyncInit && createCount < initialSize) { emptyWait = false; } if (emptyWait) { // 必须存在线程等待,才创建连接 if (poolingCount >= notEmptyWaitThreadCount // && (!(keepAlive && activeCount + poolingCount < minIdle)) && !isFailContinuous() ) { empty.await(); } } // 防止创建超过maxActive数量的连接 if (activeCount + poolingCount >= maxActive) { empty.await(); continue; } } catch (InterruptedException e) { lastCreateError = e; lastErrorTimeMillis = System.currentTimeMillis(); if ((!closing) && (!closed)) { LOG.error("create connection thread interrupted, url: " + sanitizedUrl(jdbcUrl), e); } break; } finally { lock.unlock(); } PhysicalConnectionInfo connection = null; try { connection = createPhysicalConnection(); } catch (SQLException e) { LOG.error("create connection SQLException, url: " + sanitizedUrl(jdbcUrl) + ", errorCode " + e.getErrorCode() + ", state " + e.getSQLState(), e); errorCount++; if (errorCount > connectionErrorRetryAttempts && timeBetweenConnectErrorMillis > 0) { // fail over retry attempts setFailContinuous(true); if (failFast) { lock.lock(); try { notEmpty.signalAll(); } finally { lock.unlock(); } } if (breakAfterAcquireFailure || closing || closed) { break; } try { Thread.sleep(timeBetweenConnectErrorMillis); } catch (InterruptedException interruptEx) { break; } } } catch (RuntimeException e) { LOG.error("create connection RuntimeException", e); setFailContinuous(true); continue; } catch (Error e) { LOG.error("create connection Error", e); break; } if (connection == null) { continue; } boolean result = put(connection); if (!result) { JdbcUtils.close(connection.getPhysicalConnection()); LOG.info("put physical connection to pool failed."); } // reset errorCount errorCount = 0; } } } public class DestroyConnectionThread extends Thread { private final CountDownLatch initedLatch = new CountDownLatch(1); public DestroyConnectionThread(String name) { super(name); this.setDaemon(true); } public CountDownLatch getInitedLatch() { return initedLatch; } public void run() { initedLatch.countDown(); for (; !Thread.currentThread().isInterrupted(); ) { // 从前面开始删除 try { if (closed || closing) { break; } if (timeBetweenEvictionRunsMillis > 0) { Thread.sleep(timeBetweenEvictionRunsMillis); } else { Thread.sleep(1000); // } if (Thread.interrupted()) { break; } destroyTask.run(); } catch (InterruptedException e) { break; } } } } public class DestroyTask implements Runnable { public DestroyTask() { } @Override public void run() { shrink(true, keepAlive); if (isRemoveAbandoned()) { removeAbandoned(); } } } public class LogStatsThread extends Thread { public LogStatsThread(String name) { super(name); this.setDaemon(true); } public void run() { try { for (; ; ) { try { logStats(); } catch (Exception e) { LOG.error("logStats error", e); } Thread.sleep(timeBetweenLogStatsMillis); } } catch (InterruptedException e) { // skip } } } public int removeAbandoned() { int removeCount = 0; if (activeConnections.size() == 0) { return removeCount; } long currrentNanos = System.nanoTime(); List<DruidPooledConnection> abandonedList = new ArrayList<DruidPooledConnection>(); activeConnectionLock.lock(); try { Iterator<DruidPooledConnection> iter = activeConnections.keySet().iterator(); for (; iter.hasNext(); ) { DruidPooledConnection pooledConnection = iter.next(); if (pooledConnection.isRunning()) { continue; } long timeMillis = (currrentNanos - pooledConnection.getConnectedTimeNano()) / (1000 * 1000); if (timeMillis >= removeAbandonedTimeoutMillis) { iter.remove(); pooledConnection.setTraceEnable(false); abandonedList.add(pooledConnection); } } } finally { activeConnectionLock.unlock(); } if (abandonedList.size() > 0) { for (DruidPooledConnection pooledConnection : abandonedList) { final ReentrantLock lock = pooledConnection.lock; lock.lock(); try { if (pooledConnection.isDisable()) { continue; } } finally { lock.unlock(); } JdbcUtils.close(pooledConnection); pooledConnection.abandond(); removeAbandonedCount++; removeCount++; if (isLogAbandoned()) { StringBuilder buf = new StringBuilder(); buf.append("abandon connection, owner thread: "); buf.append(pooledConnection.getOwnerThread().getName()); buf.append(", connected at : "); buf.append(pooledConnection.getConnectedTimeMillis()); buf.append(", open stackTrace\n"); StackTraceElement[] trace = pooledConnection.getConnectStackTrace(); for (int i = 0; i < trace.length; i++) { buf.append("\tat "); buf.append(trace[i].toString()); buf.append("\n"); } buf.append("ownerThread current state is ") .append(pooledConnection.getOwnerThread().getState()) .append(", current stackTrace\n"); trace = pooledConnection.getOwnerThread().getStackTrace(); for (int i = 0; i < trace.length; i++) { buf.append("\tat "); buf.append(trace[i].toString()); buf.append("\n"); } LOG.error(buf.toString()); } } } return removeCount; } /** * Instance key */ protected String instanceKey; public Reference getReference() throws NamingException { final String className = getClass().getName(); final String factoryName = className + "Factory"; // XXX: not robust Reference ref = new Reference(className, factoryName, null); ref.add(new StringRefAddr("instanceKey", instanceKey)); ref.add(new StringRefAddr("url", this.getUrl())); ref.add(new StringRefAddr("username", this.getUsername())); ref.add(new StringRefAddr("password", this.getPassword())); // TODO ADD OTHER PROPERTIES return ref; } @Override public List<String> getFilterClassNames() { List<String> names = new ArrayList<String>(); for (Filter filter : filters) { names.add(filter.getClass().getName()); } return names; } public int getRawDriverMajorVersion() { int version = -1; if (this.driver != null) { version = driver.getMajorVersion(); } return version; } public int getRawDriverMinorVersion() { int version = -1; if (this.driver != null) { version = driver.getMinorVersion(); } return version; } public String getProperties() { Properties properties = new Properties(); properties.putAll(connectProperties); if (properties.containsKey("password")) { properties.put("password", "******"); } return properties.toString(); } @Override public void shrink() { shrink(false, false); } public void shrink(boolean checkTime) { shrink(checkTime, keepAlive); } public void shrink(boolean checkTime, boolean keepAlive) { if (poolingCount == 0) { return; } final Lock lock = this.lock; try { lock.lockInterruptibly(); } catch (InterruptedException e) { return; } boolean needFill = false; int evictCount = 0; int keepAliveCount = 0; int fatalErrorIncrement = fatalErrorCount - fatalErrorCountLastShrink; fatalErrorCountLastShrink = fatalErrorCount; try { if (!inited) { return; } final int checkCount = poolingCount - minIdle; final long currentTimeMillis = System.currentTimeMillis(); // remaining is the position of the next connection should be retained in the pool. int remaining = 0; int i = 0; for (; i < poolingCount; ++i) { DruidConnectionHolder connection = connections[i]; if ((onFatalError || fatalErrorIncrement > 0) && (lastFatalErrorTimeMillis > connection.connectTimeMillis)) { keepAliveConnections[keepAliveCount++] = connection; continue; } if (checkTime) { if (phyTimeoutMillis > 0) { long phyConnectTimeMillis = currentTimeMillis - connection.connectTimeMillis; if (phyConnectTimeMillis > phyTimeoutMillis) { evictConnections[evictCount++] = connection; continue; } } long idleMillis = currentTimeMillis - connection.lastActiveTimeMillis; if (idleMillis < minEvictableIdleTimeMillis && idleMillis < keepAliveBetweenTimeMillis) { break; } if (idleMillis >= minEvictableIdleTimeMillis) { if (i < checkCount) { evictConnections[evictCount++] = connection; continue; } else if (idleMillis > maxEvictableIdleTimeMillis) { evictConnections[evictCount++] = connection; continue; } } if (keepAlive && idleMillis >= keepAliveBetweenTimeMillis && currentTimeMillis - connection.lastKeepTimeMillis >= keepAliveBetweenTimeMillis) { keepAliveConnections[keepAliveCount++] = connection; } else { if (i != remaining) { // move the connection to the new position for retaining it in the pool. connections[remaining] = connection; } remaining++; } } else { if (i < checkCount) { evictConnections[evictCount++] = connection; } else { break; } } } // shrink connections by HotSpot intrinsic function _arraycopy for performance optimization. int removeCount = evictCount + keepAliveCount; if (removeCount > 0) { int breakedCount = poolingCount - i; if (breakedCount > 0) { // retains the connections that start at the break position. System.arraycopy(connections, i, connections, remaining, breakedCount); remaining += breakedCount; } // clean the old references of the connections that have been moved forward to the new positions. System.arraycopy(nullConnections, 0, connections, remaining, removeCount); poolingCount -= removeCount; } keepAliveCheckCount += keepAliveCount; if (keepAlive && poolingCount + activeCount < minIdle) { needFill = true; } } finally { lock.unlock(); } if (evictCount > 0) { for (int i = 0; i < evictCount; ++i) { DruidConnectionHolder item = evictConnections[i]; Connection connection = item.getConnection(); JdbcUtils.close(connection); destroyCountUpdater.incrementAndGet(this); } // use HotSpot intrinsic function _arraycopy for performance optimization. System.arraycopy(nullConnections, 0, evictConnections, 0, evictConnections.length); } if (keepAliveCount > 0) { // keep order for (int i = keepAliveCount - 1; i >= 0; --i) { DruidConnectionHolder holder = keepAliveConnections[i]; Connection connection = holder.getConnection(); holder.incrementKeepAliveCheckCount(); boolean validate = false; try { this.validateConnection(connection); validate = true; } catch (Throwable error) { keepAliveCheckErrorLast = error; keepAliveCheckErrorCountUpdater.incrementAndGet(this); if (LOG.isDebugEnabled()) { LOG.debug("keepAliveErr", error); } } boolean discard = !validate; if (validate) { holder.lastKeepTimeMillis = System.currentTimeMillis(); boolean putOk = put(holder, 0L, true); if (!putOk) { discard = true; } } if (discard) { try { connection.close(); } catch (Exception error) { discardErrorLast = error; discardErrorCountUpdater.incrementAndGet(DruidDataSource.this); if (LOG.isErrorEnabled()) { LOG.error("discard connection error", error); } } if (holder.socket != null) { try { holder.socket.close(); } catch (Exception error) { discardErrorLast = error; discardErrorCountUpdater.incrementAndGet(DruidDataSource.this); if (LOG.isErrorEnabled()) { LOG.error("discard connection error", error); } } } lock.lock(); try { holder.discard = true; discardCount++; if (activeCount + poolingCount + createTaskCount < minIdle) { needFill = true; } } finally { lock.unlock(); } } } this.getDataSourceStat().addKeepAliveCheckCount(keepAliveCount); // use HotSpot intrinsic function _arraycopy for performance optimization. System.arraycopy(nullConnections, 0, keepAliveConnections, 0, keepAliveConnections.length); } if (needFill) { lock.lock(); try { int fillCount = minIdle - (activeCount + poolingCount + createTaskCount); emptySignal(fillCount); } finally { lock.unlock(); } } else if (fatalErrorIncrement > 0) { lock.lock(); try { emptySignal(); } finally { lock.unlock(); } } } public int getWaitThreadCount() { lock.lock(); try { return lock.getWaitQueueLength(notEmpty); } finally { lock.unlock(); } } public long getNotEmptyWaitCount() { return notEmptyWaitCount; } public int getNotEmptyWaitThreadCount() { lock.lock(); try { return notEmptyWaitThreadCount; } finally { lock.unlock(); } } public int getNotEmptyWaitThreadPeak() { lock.lock(); try { return notEmptyWaitThreadPeak; } finally { lock.unlock(); } } public long getNotEmptySignalCount() { return notEmptySignalCount; } public long getNotEmptyWaitMillis() { return notEmptyWaitNanos / (1000 * 1000); } public long getNotEmptyWaitNanos() { return notEmptyWaitNanos; } public int getLockQueueLength() { return lock.getQueueLength(); } public int getActivePeak() { return activePeak; } public Date getActivePeakTime() { if (activePeakTime <= 0) { return null; } return new Date(activePeakTime); } public String dump() { lock.lock(); try { return this.toString(); } finally { lock.unlock(); } } public long getErrorCount() { return this.errorCount; } public String toString() { StringBuilder buf = new StringBuilder(); buf.append("{"); buf.append("\n\tCreateTime:\""); buf.append(Utils.toString(getCreatedTime())); buf.append("\""); buf.append(",\n\tActiveCount:"); buf.append(getActiveCount()); buf.append(",\n\tPoolingCount:"); buf.append(getPoolingCount()); buf.append(",\n\tCreateCount:"); buf.append(getCreateCount()); buf.append(",\n\tDestroyCount:"); buf.append(getDestroyCount()); buf.append(",\n\tCloseCount:"); buf.append(getCloseCount()); buf.append(",\n\tConnectCount:"); buf.append(getConnectCount()); buf.append(",\n\tConnections:["); for (int i = 0; i < poolingCount; ++i) { DruidConnectionHolder conn = connections[i]; if (conn != null) { if (i != 0) { buf.append(","); } buf.append("\n\t\t"); buf.append(conn.toString()); } } buf.append("\n\t]"); buf.append("\n}"); if (this.isPoolPreparedStatements()) { buf.append("\n\n["); for (int i = 0; i < poolingCount; ++i) { DruidConnectionHolder conn = connections[i]; if (conn != null) { if (i != 0) { buf.append(","); } buf.append("\n\t{\n\tID:"); buf.append(System.identityHashCode(conn.getConnection())); PreparedStatementPool pool = conn.getStatementPool(); buf.append(", \n\tpoolStatements:["); int entryIndex = 0; try { for (Map.Entry<PreparedStatementKey, PreparedStatementHolder> entry : pool.getMap().entrySet()) { if (entryIndex != 0) { buf.append(","); } buf.append("\n\t\t{hitCount:"); buf.append(entry.getValue().getHitCount()); buf.append(",sql:\""); buf.append(entry.getKey().getSql()); buf.append("\""); buf.append("\t}"); entryIndex++; } } catch (ConcurrentModificationException e) { // skip .. } buf.append("\n\t\t]"); buf.append("\n\t}"); } } buf.append("\n]"); } return buf.toString(); } public List<Map<String, Object>> getPoolingConnectionInfo() { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); lock.lock(); try { for (int i = 0; i < poolingCount; ++i) { DruidConnectionHolder connHolder = connections[i]; Connection conn = connHolder.getConnection(); Map<String, Object> map = new LinkedHashMap<String, Object>(); map.put("id", System.identityHashCode(conn)); map.put("connectionId", connHolder.getConnectionId()); map.put("useCount", connHolder.getUseCount()); if (connHolder.lastActiveTimeMillis > 0) { map.put("lastActiveTime", new Date(connHolder.lastActiveTimeMillis)); } if (connHolder.lastKeepTimeMillis > 0) { map.put("lastKeepTimeMillis", new Date(connHolder.lastKeepTimeMillis)); } map.put("connectTime", new Date(connHolder.getTimeMillis())); map.put("holdability", connHolder.getUnderlyingHoldability()); map.put("transactionIsolation", connHolder.getUnderlyingTransactionIsolation()); map.put("autoCommit", connHolder.underlyingAutoCommit); map.put("readoOnly", connHolder.isUnderlyingReadOnly()); if (connHolder.isPoolPreparedStatements()) { List<Map<String, Object>> stmtCache = new ArrayList<Map<String, Object>>(); PreparedStatementPool stmtPool = connHolder.getStatementPool(); for (PreparedStatementHolder stmtHolder : stmtPool.getMap().values()) { Map<String, Object> stmtInfo = new LinkedHashMap<String, Object>(); stmtInfo.put("sql", stmtHolder.key.getSql()); stmtInfo.put("defaultRowPrefetch", stmtHolder.getDefaultRowPrefetch()); stmtInfo.put("rowPrefetch", stmtHolder.getRowPrefetch()); stmtInfo.put("hitCount", stmtHolder.getHitCount()); stmtCache.add(stmtInfo); } map.put("pscache", stmtCache); } map.put("keepAliveCheckCount", connHolder.getKeepAliveCheckCount()); list.add(map); } } finally { lock.unlock(); } return list; } public void logTransaction(TransactionInfo info) { long transactionMillis = info.getEndTimeMillis() - info.getStartTimeMillis(); if (transactionThresholdMillis > 0 && transactionMillis > transactionThresholdMillis) { StringBuilder buf = new StringBuilder(); buf.append("long time transaction, take "); buf.append(transactionMillis); buf.append(" ms : "); for (String sql : info.getSqlList()) { buf.append(sql); buf.append(";"); } LOG.error(buf.toString(), new TransactionTimeoutException()); } } @Override public String getVersion() { return VERSION.getVersionNumber(); } @Override public JdbcDataSourceStat getDataSourceStat() { return dataSourceStat; } public Object clone() { return cloneDruidDataSource(); } public DruidDataSource cloneDruidDataSource() { DruidDataSource x = new DruidDataSource(); cloneTo(x); return x; } public Map<String, Object> getStatDataForMBean() { try { Map<String, Object> map = new HashMap<String, Object>(); // 0 - 4 map.put("Name", this.getName()); map.put("URL", this.getUrl()); map.put("CreateCount", this.getCreateCount()); map.put("DestroyCount", this.getDestroyCount()); map.put("ConnectCount", this.getConnectCount()); // 5 - 9 map.put("CloseCount", this.getCloseCount()); map.put("ActiveCount", this.getActiveCount()); map.put("PoolingCount", this.getPoolingCount()); map.put("LockQueueLength", this.getLockQueueLength()); map.put("WaitThreadCount", this.getNotEmptyWaitThreadCount()); // 10 - 14 map.put("InitialSize", this.getInitialSize()); map.put("MaxActive", this.getMaxActive()); map.put("MinIdle", this.getMinIdle()); map.put("PoolPreparedStatements", this.isPoolPreparedStatements()); map.put("TestOnBorrow", this.isTestOnBorrow()); // 15 - 19 map.put("TestOnReturn", this.isTestOnReturn()); map.put("MinEvictableIdleTimeMillis", this.minEvictableIdleTimeMillis); map.put("ConnectErrorCount", this.getConnectErrorCount()); map.put("CreateTimespanMillis", this.getCreateTimespanMillis()); map.put("DbType", this.dbTypeName); // 20 - 24 map.put("ValidationQuery", this.getValidationQuery()); map.put("ValidationQueryTimeout", this.getValidationQueryTimeout()); map.put("DriverClassName", this.getDriverClassName()); map.put("Username", this.getUsername()); map.put("RemoveAbandonedCount", this.getRemoveAbandonedCount()); // 25 - 29 map.put("NotEmptyWaitCount", this.getNotEmptyWaitCount()); map.put("NotEmptyWaitNanos", this.getNotEmptyWaitNanos()); map.put("ErrorCount", this.getErrorCount()); map.put("ReusePreparedStatementCount", this.getCachedPreparedStatementHitCount()); map.put("StartTransactionCount", this.getStartTransactionCount()); // 30 - 34 map.put("CommitCount", this.getCommitCount()); map.put("RollbackCount", this.getRollbackCount()); map.put("LastError", JMXUtils.getErrorCompositeData(this.getLastError())); map.put("LastCreateError", JMXUtils.getErrorCompositeData(this.getLastCreateError())); map.put("PreparedStatementCacheDeleteCount", this.getCachedPreparedStatementDeleteCount()); // 35 - 39 map.put("PreparedStatementCacheAccessCount", this.getCachedPreparedStatementAccessCount()); map.put("PreparedStatementCacheMissCount", this.getCachedPreparedStatementMissCount()); map.put("PreparedStatementCacheHitCount", this.getCachedPreparedStatementHitCount()); map.put("PreparedStatementCacheCurrentCount", this.getCachedPreparedStatementCount()); map.put("Version", this.getVersion()); // 40 - map.put("LastErrorTime", this.getLastErrorTime()); map.put("LastCreateErrorTime", this.getLastCreateErrorTime()); map.put("CreateErrorCount", this.getCreateErrorCount()); map.put("DiscardCount", this.getDiscardCount()); map.put("ExecuteQueryCount", this.getExecuteQueryCount()); map.put("ExecuteUpdateCount", this.getExecuteUpdateCount()); map.put("InitStackTrace", this.getInitStackTrace()); return map; } catch (JMException ex) { throw new IllegalStateException("getStatData error", ex); } } public Map<String, Object> getStatData() { final int activeCount; final int activePeak; final Date activePeakTime; final int poolingCount; final int poolingPeak; final Date poolingPeakTime; final long connectCount; final long closeCount; lock.lock(); try { poolingCount = this.poolingCount; poolingPeak = this.poolingPeak; poolingPeakTime = this.getPoolingPeakTime(); activeCount = this.activeCount; activePeak = this.activePeak; activePeakTime = this.getActivePeakTime(); connectCount = this.connectCount; closeCount = this.closeCount; } finally { lock.unlock(); } Map<String, Object> dataMap = new LinkedHashMap<String, Object>(); dataMap.put("Identity", System.identityHashCode(this)); dataMap.put("Name", this.getName()); dataMap.put("DbType", this.dbTypeName); dataMap.put("DriverClassName", this.getDriverClassName()); dataMap.put("URL", this.getUrl()); dataMap.put("UserName", this.getUsername()); dataMap.put("FilterClassNames", this.getFilterClassNames()); dataMap.put("WaitThreadCount", this.getWaitThreadCount()); dataMap.put("NotEmptyWaitCount", this.getNotEmptyWaitCount()); dataMap.put("NotEmptyWaitMillis", this.getNotEmptyWaitMillis()); dataMap.put("PoolingCount", poolingCount); dataMap.put("PoolingPeak", poolingPeak); dataMap.put("PoolingPeakTime", poolingPeakTime); dataMap.put("ActiveCount", activeCount); dataMap.put("ActivePeak", activePeak); dataMap.put("ActivePeakTime", activePeakTime); dataMap.put("InitialSize", this.getInitialSize()); dataMap.put("MinIdle", this.getMinIdle()); dataMap.put("MaxActive", this.getMaxActive()); dataMap.put("QueryTimeout", this.getQueryTimeout()); dataMap.put("TransactionQueryTimeout", this.getTransactionQueryTimeout()); dataMap.put("LoginTimeout", this.getLoginTimeout()); dataMap.put("ValidConnectionCheckerClassName", this.getValidConnectionCheckerClassName()); dataMap.put("ExceptionSorterClassName", this.getExceptionSorterClassName()); dataMap.put("TestOnBorrow", this.isTestOnBorrow()); dataMap.put("TestOnReturn", this.isTestOnReturn()); dataMap.put("TestWhileIdle", this.isTestWhileIdle()); dataMap.put("DefaultAutoCommit", this.isDefaultAutoCommit()); dataMap.put("DefaultReadOnly", this.getDefaultReadOnly()); dataMap.put("DefaultTransactionIsolation", this.getDefaultTransactionIsolation()); dataMap.put("LogicConnectCount", connectCount); dataMap.put("LogicCloseCount", closeCount); dataMap.put("LogicConnectErrorCount", this.getConnectErrorCount()); dataMap.put("PhysicalConnectCount", this.getCreateCount()); dataMap.put("PhysicalCloseCount", this.getDestroyCount()); dataMap.put("PhysicalConnectErrorCount", this.getCreateErrorCount()); dataMap.put("DiscardCount", this.getDiscardCount()); dataMap.put("ExecuteCount", this.getExecuteCount()); dataMap.put("ExecuteUpdateCount", this.getExecuteUpdateCount()); dataMap.put("ExecuteQueryCount", this.getExecuteQueryCount()); dataMap.put("ExecuteBatchCount", this.getExecuteBatchCount()); dataMap.put("ErrorCount", this.getErrorCount()); dataMap.put("CommitCount", this.getCommitCount()); dataMap.put("RollbackCount", this.getRollbackCount()); dataMap.put("PSCacheAccessCount", this.getCachedPreparedStatementAccessCount()); dataMap.put("PSCacheHitCount", this.getCachedPreparedStatementHitCount()); dataMap.put("PSCacheMissCount", this.getCachedPreparedStatementMissCount()); dataMap.put("StartTransactionCount", this.getStartTransactionCount()); dataMap.put("TransactionHistogram", this.getTransactionHistogramValues()); dataMap.put("ConnectionHoldTimeHistogram", this.getDataSourceStat().getConnectionHoldHistogram().toArray()); dataMap.put("RemoveAbandoned", this.isRemoveAbandoned()); dataMap.put("ClobOpenCount", this.getDataSourceStat().getClobOpenCount()); dataMap.put("BlobOpenCount", this.getDataSourceStat().getBlobOpenCount()); dataMap.put("KeepAliveCheckCount", this.getDataSourceStat().getKeepAliveCheckCount()); dataMap.put("KeepAlive", this.isKeepAlive()); dataMap.put("FailFast", this.isFailFast()); dataMap.put("MaxWait", this.getMaxWait()); dataMap.put("MaxWaitThreadCount", this.getMaxWaitThreadCount()); dataMap.put("PoolPreparedStatements", this.isPoolPreparedStatements()); dataMap.put("MaxPoolPreparedStatementPerConnectionSize", this.getMaxPoolPreparedStatementPerConnectionSize()); dataMap.put("MinEvictableIdleTimeMillis", this.minEvictableIdleTimeMillis); dataMap.put("MaxEvictableIdleTimeMillis", this.maxEvictableIdleTimeMillis); dataMap.put("LogDifferentThread", isLogDifferentThread()); dataMap.put("RecycleErrorCount", getRecycleErrorCount()); dataMap.put("PreparedStatementOpenCount", getPreparedStatementCount()); dataMap.put("PreparedStatementClosedCount", getClosedPreparedStatementCount()); dataMap.put("UseUnfairLock", isUseUnfairLock()); dataMap.put("InitGlobalVariants", isInitGlobalVariants()); dataMap.put("InitVariants", isInitVariants()); return dataMap; } public JdbcSqlStat getSqlStat(int sqlId) { return this.getDataSourceStat().getSqlStat(sqlId); } public JdbcSqlStat getSqlStat(long sqlId) { return this.getDataSourceStat().getSqlStat(sqlId); } public Map<String, JdbcSqlStat> getSqlStatMap() { return this.getDataSourceStat().getSqlStatMap(); } public Map<String, Object> getWallStatMap() { WallProviderStatValue wallStatValue = getWallStatValue(false); if (wallStatValue != null) { return wallStatValue.toMap(); } return null; } public WallProviderStatValue getWallStatValue(boolean reset) { for (Filter filter : this.filters) { if (filter instanceof WallFilter) { WallFilter wallFilter = (WallFilter) filter; return wallFilter.getProvider().getStatValue(reset); } } return null; } public Lock getLock() { return lock; } @Override public boolean isWrapperFor(Class<?> iface) { for (Filter filter : this.filters) { if (filter.isWrapperFor(iface)) { return true; } } if (this.statLogger != null && (this.statLogger.getClass() == iface || DruidDataSourceStatLogger.class == iface)) { return true; } return super.isWrapperFor(iface); } @SuppressWarnings("unchecked") public <T> T unwrap(Class<T> iface) { for (Filter filter : this.filters) { if (filter.isWrapperFor(iface)) { return (T) filter; } } if (this.statLogger != null && (this.statLogger.getClass() == iface || DruidDataSourceStatLogger.class == iface)) { return (T) statLogger; } return super.unwrap(iface); } public boolean isLogDifferentThread() { return logDifferentThread; } public void setLogDifferentThread(boolean logDifferentThread) { this.logDifferentThread = logDifferentThread; } public DruidPooledConnection tryGetConnection() throws SQLException { if (poolingCount == 0) { return null; } return getConnection(); } @Override public int fill() throws SQLException { return this.fill(this.maxActive); } @Override public int fill(int toCount) throws SQLException { if (closed) { throw new DataSourceClosedException("dataSource already closed at " + new Date(closeTimeMillis)); } if (toCount < 0) { throw new IllegalArgumentException("toCount can't not be less than zero"); } init(); if (toCount > this.maxActive) { toCount = this.maxActive; } int fillCount = 0; for (; ; ) { try { lock.lockInterruptibly(); } catch (InterruptedException e) { connectErrorCountUpdater.incrementAndGet(this); throw new SQLException("interrupt", e); } boolean fillable = this.isFillable(toCount); lock.unlock(); if (!fillable) { break; } DruidConnectionHolder holder; try { PhysicalConnectionInfo pyConnInfo = createPhysicalConnection(); holder = new DruidConnectionHolder(this, pyConnInfo); } catch (SQLException e) { LOG.error("fill connection error, url: " + sanitizedUrl(this.jdbcUrl), e); connectErrorCountUpdater.incrementAndGet(this); throw e; } try { lock.lockInterruptibly(); } catch (InterruptedException e) { connectErrorCountUpdater.incrementAndGet(this); throw new SQLException("interrupt", e); } boolean result; try { if (!this.isFillable(toCount)) { JdbcUtils.close(holder.getConnection()); LOG.info("fill connections skip."); break; } result = this.putLast(holder, System.currentTimeMillis()); fillCount++; } finally { lock.unlock(); } if (!result) { JdbcUtils.close(holder.getConnection()); LOG.info("connection fill failed."); } } if (LOG.isInfoEnabled()) { LOG.info("fill " + fillCount + " connections"); } return fillCount; } static String sanitizedUrl(String url) { if (url == null) { return null; } for (String pwdKeyNamesInMysql : new String[]{ "password=", "password1=", "password2=", "password3=", "trustCertificateKeyStorePassword=", "clientCertificateKeyStorePassword=", }) { if (url.contains(pwdKeyNamesInMysql)) { url = url.replaceAll("([?&;]" + pwdKeyNamesInMysql + ")[^&#;]*(.*)", "$1<masked>$2"); } } return url; } private boolean isFillable(int toCount) { int currentCount = this.poolingCount + this.activeCount; return currentCount < toCount && currentCount < this.maxActive; } public boolean isFull() { lock.lock(); try { return this.poolingCount + this.activeCount >= this.maxActive; } finally { lock.unlock(); } } private void emptySignal() { emptySignal(1); } private void emptySignal(int fillCount) { if (createScheduler == null) { if (activeCount + poolingCount >= maxActive) { return; } empty.signal(); return; } for (int i = 0; i < fillCount; i++) { if (activeCount + poolingCount + createTaskCount >= maxActive) { return; } if (createTaskCount >= maxCreateTaskCount) { return; } submitCreateTask(false); } } @Override public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { if (server != null) { try { if (server.isRegistered(name)) { server.unregisterMBean(name); } } catch (Exception ex) { LOG.warn("DruidDataSource preRegister error", ex); } } return name; } @Override public void postRegister(Boolean registrationDone) { } @Override public void preDeregister() throws Exception { } @Override public void postDeregister() { } public boolean isClosed() { return this.closed; } public boolean isCheckExecuteTime() { return checkExecuteTime; } public void setCheckExecuteTime(boolean checkExecuteTime) { this.checkExecuteTime = checkExecuteTime; } public void forEach(Connection conn) { } }
alibaba/druid
core/src/main/java/com/alibaba/druid/pool/DruidDataSource.java
44,927
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.common.lucene; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.core.KeywordAnalyzer; import org.apache.lucene.analysis.core.WhitespaceAnalyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.codecs.CodecUtil; import org.apache.lucene.codecs.StoredFieldsReader; import org.apache.lucene.document.LatLonDocValuesField; import org.apache.lucene.document.NumericDocValuesField; import org.apache.lucene.index.ConcurrentMergeScheduler; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.FilterCodecReader; import org.apache.lucene.index.FilterDirectoryReader; import org.apache.lucene.index.FilterLeafReader; import org.apache.lucene.index.IndexCommit; import org.apache.lucene.index.IndexFileNames; import org.apache.lucene.index.IndexFormatTooNewException; import org.apache.lucene.index.IndexFormatTooOldException; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.LeafReader; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.NoMergePolicy; import org.apache.lucene.index.NoMergeScheduler; import org.apache.lucene.index.SegmentCommitInfo; import org.apache.lucene.index.SegmentInfos; import org.apache.lucene.index.SegmentReader; import org.apache.lucene.search.DocIdSetIterator; import org.apache.lucene.search.Explanation; import org.apache.lucene.search.FieldDoc; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.ScoreMode; import org.apache.lucene.search.Scorer; import org.apache.lucene.search.ScorerSupplier; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.apache.lucene.search.SortedNumericSortField; import org.apache.lucene.search.SortedSetSortField; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.TopFieldDocs; import org.apache.lucene.search.TotalHits; import org.apache.lucene.search.TwoPhaseIterator; import org.apache.lucene.search.Weight; import org.apache.lucene.store.Directory; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexInput; import org.apache.lucene.store.Lock; import org.apache.lucene.util.Bits; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.Version; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.lucene.index.SequentialStoredFieldsLeafReader; import org.elasticsearch.common.lucene.search.TopDocsAndMaxScore; import org.elasticsearch.common.util.iterable.Iterables; import org.elasticsearch.core.Nullable; import org.elasticsearch.core.SuppressForbidden; import org.elasticsearch.index.analysis.AnalyzerScope; import org.elasticsearch.index.analysis.NamedAnalyzer; import org.elasticsearch.index.fielddata.IndexFieldData; import org.elasticsearch.lucene.grouping.TopFieldGroups; import org.elasticsearch.search.sort.ShardDocSortField; import java.io.IOException; import java.math.BigInteger; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; public class Lucene { public static final String LATEST_CODEC = "Lucene99"; public static final String SOFT_DELETES_FIELD = "__soft_deletes"; public static final NamedAnalyzer STANDARD_ANALYZER = new NamedAnalyzer("_standard", AnalyzerScope.GLOBAL, new StandardAnalyzer()); public static final NamedAnalyzer KEYWORD_ANALYZER = new NamedAnalyzer("_keyword", AnalyzerScope.GLOBAL, new KeywordAnalyzer()); public static final NamedAnalyzer WHITESPACE_ANALYZER = new NamedAnalyzer( "_whitespace", AnalyzerScope.GLOBAL, new WhitespaceAnalyzer() ); public static final ScoreDoc[] EMPTY_SCORE_DOCS = new ScoreDoc[0]; public static final TopDocs EMPTY_TOP_DOCS = new TopDocs(new TotalHits(0, TotalHits.Relation.EQUAL_TO), EMPTY_SCORE_DOCS); private Lucene() {} /** * Reads the segments infos, failing if it fails to load */ public static SegmentInfos readSegmentInfos(Directory directory) throws IOException { return SegmentInfos.readLatestCommit(directory); } /** * Returns an iterable that allows to iterate over all files in this segments info */ public static Iterable<String> files(SegmentInfos infos) throws IOException { final List<Collection<String>> list = new ArrayList<>(); list.add(Collections.singleton(infos.getSegmentsFileName())); for (SegmentCommitInfo info : infos) { list.add(info.files()); } return Iterables.flatten(list); } /** * Returns the number of documents in the index referenced by this {@link SegmentInfos} */ public static int getNumDocs(SegmentInfos info) { int numDocs = 0; for (SegmentCommitInfo si : info) { numDocs += si.info.maxDoc() - si.getDelCount() - si.getSoftDelCount(); } return numDocs; } /** * Reads the segments infos from the given commit, failing if it fails to load */ public static SegmentInfos readSegmentInfos(IndexCommit commit) throws IOException { // Using commit.getSegmentsFileName() does NOT work here, have to // manually create the segment filename String filename = IndexFileNames.fileNameFromGeneration(IndexFileNames.SEGMENTS, "", commit.getGeneration()); return SegmentInfos.readCommit(commit.getDirectory(), filename); } /** * Reads the segments infos from the given segments file name, failing if it fails to load */ private static SegmentInfos readSegmentInfos(String segmentsFileName, Directory directory) throws IOException { return SegmentInfos.readCommit(directory, segmentsFileName); } /** * This method removes all files from the given directory that are not referenced by the given segments file. * This method will open an IndexWriter and relies on index file deleter to remove all unreferenced files. Segment files * that are newer than the given segments file are removed forcefully to prevent problems with IndexWriter opening a potentially * broken commit point / leftover. * <b>Note:</b> this method will fail if there is another IndexWriter open on the given directory. This method will also acquire * a write lock from the directory while pruning unused files. This method expects an existing index in the given directory that has * the given segments file. */ public static SegmentInfos pruneUnreferencedFiles(String segmentsFileName, Directory directory) throws IOException { final SegmentInfos si = readSegmentInfos(segmentsFileName, directory); try (Lock writeLock = directory.obtainLock(IndexWriter.WRITE_LOCK_NAME)) { int foundSegmentFiles = 0; for (final String file : directory.listAll()) { /* * we could also use a deletion policy here but in the case of snapshot and restore * sometimes we restore an index and override files that were referenced by a "future" * commit. If such a commit is opened by the IW it would likely throw a corrupted index exception * since checksums don's match anymore. that's why we prune the name here directly. * We also want the caller to know if we were not able to remove a segments_N file. */ if (file.startsWith(IndexFileNames.SEGMENTS)) { foundSegmentFiles++; if (file.equals(si.getSegmentsFileName()) == false) { directory.deleteFile(file); // remove all segment_N files except of the one we wanna keep } } } assert SegmentInfos.getLastCommitSegmentsFileName(directory).equals(segmentsFileName); if (foundSegmentFiles == 0) { throw new IllegalStateException("no commit found in the directory"); } } final IndexCommit cp = getIndexCommit(si, directory); try ( IndexWriter writer = new IndexWriter( directory, indexWriterConfigWithNoMerging(Lucene.STANDARD_ANALYZER).setSoftDeletesField(Lucene.SOFT_DELETES_FIELD) .setIndexCommit(cp) .setCommitOnClose(false) .setOpenMode(IndexWriterConfig.OpenMode.APPEND) ) ) { // do nothing and close this will kick off IndexFileDeleter which will remove all pending files } return si; } /** * Returns an index commit for the given {@link SegmentInfos} in the given directory. */ public static IndexCommit getIndexCommit(SegmentInfos si, Directory directory) throws IOException { return new CommitPoint(si, directory); } /** * This method removes all lucene files from the given directory. It will first try to delete all commit points / segments * files to ensure broken commits or corrupted indices will not be opened in the future. If any of the segment files can't be deleted * this operation fails. */ public static void cleanLuceneIndex(Directory directory) throws IOException { try (Lock writeLock = directory.obtainLock(IndexWriter.WRITE_LOCK_NAME)) { for (final String file : directory.listAll()) { if (file.startsWith(IndexFileNames.SEGMENTS)) { directory.deleteFile(file); // remove all segment_N files } } } try ( IndexWriter writer = new IndexWriter( directory, indexWriterConfigWithNoMerging(Lucene.STANDARD_ANALYZER).setSoftDeletesField(Lucene.SOFT_DELETES_FIELD) .setCommitOnClose(false) // no commits .setOpenMode(IndexWriterConfig.OpenMode.CREATE) // force creation - don't append... ) ) { // do nothing and close this will kick of IndexFileDeleter which will remove all pending files } } public static void checkSegmentInfoIntegrity(final Directory directory) throws IOException { new SegmentInfos.FindSegmentsFile<>(directory) { @Override protected Object doBody(String segmentFileName) throws IOException { try (IndexInput input = directory.openInput(segmentFileName, IOContext.READ)) { CodecUtil.checksumEntireFile(input); } return null; } }.run(); } /** * Check whether there is one or more documents matching the provided query. */ public static boolean exists(IndexSearcher searcher, Query query) throws IOException { final Weight weight = searcher.createWeight(searcher.rewrite(query), ScoreMode.COMPLETE_NO_SCORES, 1f); // the scorer API should be more efficient at stopping after the first // match than the bulk scorer API for (LeafReaderContext context : searcher.getIndexReader().leaves()) { final Scorer scorer = weight.scorer(context); if (scorer == null) { continue; } final Bits liveDocs = context.reader().getLiveDocs(); final DocIdSetIterator iterator = scorer.iterator(); for (int doc = iterator.nextDoc(); doc != DocIdSetIterator.NO_MORE_DOCS; doc = iterator.nextDoc()) { if (liveDocs == null || liveDocs.get(doc)) { return true; } } } return false; } public static TotalHits readTotalHits(StreamInput in) throws IOException { long totalHits = in.readVLong(); TotalHits.Relation totalHitsRelation = in.readEnum(TotalHits.Relation.class); return new TotalHits(totalHits, totalHitsRelation); } public static TopDocsAndMaxScore readTopDocs(StreamInput in) throws IOException { byte type = in.readByte(); if (type == 0) { TotalHits totalHits = readTotalHits(in); float maxScore = in.readFloat(); final int scoreDocCount = in.readVInt(); final ScoreDoc[] scoreDocs; if (scoreDocCount == 0) { scoreDocs = EMPTY_SCORE_DOCS; } else { scoreDocs = new ScoreDoc[scoreDocCount]; for (int i = 0; i < scoreDocs.length; i++) { scoreDocs[i] = new ScoreDoc(in.readVInt(), in.readFloat()); } } return new TopDocsAndMaxScore(new TopDocs(totalHits, scoreDocs), maxScore); } else if (type == 1) { TotalHits totalHits = readTotalHits(in); float maxScore = in.readFloat(); SortField[] fields = in.readArray(Lucene::readSortField, SortField[]::new); FieldDoc[] fieldDocs = new FieldDoc[in.readVInt()]; for (int i = 0; i < fieldDocs.length; i++) { fieldDocs[i] = readFieldDoc(in); } return new TopDocsAndMaxScore(new TopFieldDocs(totalHits, fieldDocs, fields), maxScore); } else if (type == 2) { TotalHits totalHits = readTotalHits(in); float maxScore = in.readFloat(); String field = in.readString(); SortField[] fields = in.readArray(Lucene::readSortField, SortField[]::new); int size = in.readVInt(); Object[] collapseValues = new Object[size]; FieldDoc[] fieldDocs = new FieldDoc[size]; for (int i = 0; i < fieldDocs.length; i++) { fieldDocs[i] = readFieldDoc(in); collapseValues[i] = readSortValue(in); } return new TopDocsAndMaxScore(new TopFieldGroups(field, totalHits, fieldDocs, fields, collapseValues), maxScore); } else { throw new IllegalStateException("Unknown type " + type); } } public static FieldDoc readFieldDoc(StreamInput in) throws IOException { Comparable<?>[] cFields = new Comparable<?>[in.readVInt()]; for (int j = 0; j < cFields.length; j++) { byte type = in.readByte(); if (type == 0) { cFields[j] = null; } else if (type == 1) { cFields[j] = in.readString(); } else if (type == 2) { cFields[j] = in.readInt(); } else if (type == 3) { cFields[j] = in.readLong(); } else if (type == 4) { cFields[j] = in.readFloat(); } else if (type == 5) { cFields[j] = in.readDouble(); } else if (type == 6) { cFields[j] = in.readByte(); } else if (type == 7) { cFields[j] = in.readShort(); } else if (type == 8) { cFields[j] = in.readBoolean(); } else if (type == 9) { cFields[j] = in.readBytesRef(); } else if (type == 10) { cFields[j] = new BigInteger(in.readString()); } else { throw new IOException("Can't match type [" + type + "]"); } } return new FieldDoc(in.readVInt(), in.readFloat(), cFields); } public static Comparable<?> readSortValue(StreamInput in) throws IOException { byte type = in.readByte(); if (type == 0) { return null; } else if (type == 1) { return in.readString(); } else if (type == 2) { return in.readInt(); } else if (type == 3) { return in.readLong(); } else if (type == 4) { return in.readFloat(); } else if (type == 5) { return in.readDouble(); } else if (type == 6) { return in.readByte(); } else if (type == 7) { return in.readShort(); } else if (type == 8) { return in.readBoolean(); } else if (type == 9) { return in.readBytesRef(); } else if (type == 10) { return new BigInteger(in.readString()); } else { throw new IOException("Can't match type [" + type + "]"); } } public static ScoreDoc readScoreDoc(StreamInput in) throws IOException { return new ScoreDoc(in.readVInt(), in.readFloat()); } private static final Class<?> GEO_DISTANCE_SORT_TYPE_CLASS = LatLonDocValuesField.newDistanceSort("some_geo_field", 0, 0).getClass(); public static void writeTotalHits(StreamOutput out, TotalHits totalHits) throws IOException { out.writeVLong(totalHits.value); out.writeEnum(totalHits.relation); } public static void writeTopDocs(StreamOutput out, TopDocsAndMaxScore topDocs) throws IOException { if (topDocs.topDocs instanceof TopFieldGroups topFieldGroups) { out.writeByte((byte) 2); writeTotalHits(out, topDocs.topDocs.totalHits); out.writeFloat(topDocs.maxScore); out.writeString(topFieldGroups.field); out.writeArray(Lucene::writeSortField, topFieldGroups.fields); out.writeVInt(topDocs.topDocs.scoreDocs.length); for (int i = 0; i < topDocs.topDocs.scoreDocs.length; i++) { ScoreDoc doc = topFieldGroups.scoreDocs[i]; writeFieldDoc(out, (FieldDoc) doc); writeSortValue(out, topFieldGroups.groupValues[i]); } } else if (topDocs.topDocs instanceof TopFieldDocs topFieldDocs) { out.writeByte((byte) 1); writeTotalHits(out, topDocs.topDocs.totalHits); out.writeFloat(topDocs.maxScore); out.writeArray(Lucene::writeSortField, topFieldDocs.fields); out.writeArray((o, doc) -> writeFieldDoc(o, (FieldDoc) doc), topFieldDocs.scoreDocs); } else { out.writeByte((byte) 0); writeTotalHits(out, topDocs.topDocs.totalHits); out.writeFloat(topDocs.maxScore); out.writeArray(Lucene::writeScoreDoc, topDocs.topDocs.scoreDocs); } } private static void writeMissingValue(StreamOutput out, Object missingValue) throws IOException { if (missingValue == SortField.STRING_FIRST) { out.writeByte((byte) 1); } else if (missingValue == SortField.STRING_LAST) { out.writeByte((byte) 2); } else { out.writeByte((byte) 0); out.writeGenericValue(missingValue); } } private static Object readMissingValue(StreamInput in) throws IOException { final byte id = in.readByte(); return switch (id) { case 0 -> in.readGenericValue(); case 1 -> SortField.STRING_FIRST; case 2 -> SortField.STRING_LAST; default -> throw new IOException("Unknown missing value id: " + id); }; } public static void writeSortValue(StreamOutput out, Object field) throws IOException { if (field == null) { out.writeByte((byte) 0); } else { Class<?> type = field.getClass(); if (type == String.class) { out.writeByte((byte) 1); out.writeString((String) field); } else if (type == Integer.class) { out.writeByte((byte) 2); out.writeInt((Integer) field); } else if (type == Long.class) { out.writeByte((byte) 3); out.writeLong((Long) field); } else if (type == Float.class) { out.writeByte((byte) 4); out.writeFloat((Float) field); } else if (type == Double.class) { out.writeByte((byte) 5); out.writeDouble((Double) field); } else if (type == Byte.class) { out.writeByte((byte) 6); out.writeByte((Byte) field); } else if (type == Short.class) { out.writeByte((byte) 7); out.writeShort((Short) field); } else if (type == Boolean.class) { out.writeByte((byte) 8); out.writeBoolean((Boolean) field); } else if (type == BytesRef.class) { out.writeByte((byte) 9); out.writeBytesRef((BytesRef) field); } else if (type == BigInteger.class) { // TODO: improve serialization of BigInteger out.writeByte((byte) 10); out.writeString(field.toString()); } else { throw new IOException("Can't handle sort field value of type [" + type + "]"); } } } public static void writeFieldDoc(StreamOutput out, FieldDoc fieldDoc) throws IOException { out.writeArray(Lucene::writeSortValue, fieldDoc.fields); out.writeVInt(fieldDoc.doc); out.writeFloat(fieldDoc.score); } public static void writeScoreDoc(StreamOutput out, ScoreDoc scoreDoc) throws IOException { if (scoreDoc.getClass().equals(ScoreDoc.class) == false) { throw new IllegalArgumentException("This method can only be used to serialize a ScoreDoc, not a " + scoreDoc.getClass()); } out.writeVInt(scoreDoc.doc); out.writeFloat(scoreDoc.score); } // LUCENE 4 UPGRADE: We might want to maintain our own ordinal, instead of Lucene's ordinal public static SortField.Type readSortType(StreamInput in) throws IOException { return SortField.Type.values()[in.readVInt()]; } public static SortField readSortField(StreamInput in) throws IOException { String field = null; if (in.readBoolean()) { field = in.readString(); } SortField.Type sortType = readSortType(in); Object missingValue = readMissingValue(in); boolean reverse = in.readBoolean(); SortField sortField = new SortField(field, sortType, reverse); if (missingValue != null) { sortField.setMissingValue(missingValue); } return sortField; } public static void writeSortType(StreamOutput out, SortField.Type sortType) throws IOException { out.writeVInt(sortType.ordinal()); } /** * Returns the generic version of the provided {@link SortField} that * can be used to merge documents coming from different shards. */ private static SortField rewriteMergeSortField(SortField sortField) { if (sortField.getClass() == GEO_DISTANCE_SORT_TYPE_CLASS) { SortField newSortField = new SortField(sortField.getField(), SortField.Type.DOUBLE); newSortField.setMissingValue(sortField.getMissingValue()); return newSortField; } else if (sortField.getClass() == SortedSetSortField.class) { SortField newSortField = new SortField(sortField.getField(), SortField.Type.STRING, sortField.getReverse()); newSortField.setMissingValue(sortField.getMissingValue()); return newSortField; } else if (sortField.getClass() == SortedNumericSortField.class) { SortField newSortField = new SortField( sortField.getField(), ((SortedNumericSortField) sortField).getNumericType(), sortField.getReverse() ); newSortField.setMissingValue(sortField.getMissingValue()); return newSortField; } else if (sortField.getClass() == ShardDocSortField.class) { return new SortField(sortField.getField(), SortField.Type.LONG, sortField.getReverse()); } else { return sortField; } } public static void writeSortField(StreamOutput out, SortField sortField) throws IOException { sortField = rewriteMergeSortField(sortField); if (sortField.getClass() != SortField.class) { throw new IllegalArgumentException("Cannot serialize SortField impl [" + sortField + "]"); } if (sortField.getField() == null) { out.writeBoolean(false); } else { out.writeBoolean(true); out.writeString(sortField.getField()); } if (sortField.getComparatorSource() != null) { IndexFieldData.XFieldComparatorSource comparatorSource = (IndexFieldData.XFieldComparatorSource) sortField .getComparatorSource(); writeSortType(out, comparatorSource.reducedType()); writeMissingValue(out, comparatorSource.missingValue(sortField.getReverse())); } else { writeSortType(out, sortField.getType()); writeMissingValue(out, sortField.getMissingValue()); } out.writeBoolean(sortField.getReverse()); } private static Number readExplanationValue(StreamInput in) throws IOException { final int numberType = in.readByte(); return switch (numberType) { case 0 -> in.readFloat(); case 1 -> in.readDouble(); case 2 -> in.readZLong(); default -> throw new IOException("Unexpected number type: " + numberType); }; } public static Explanation readExplanation(StreamInput in) throws IOException { boolean match = in.readBoolean(); String description = in.readString(); final Explanation[] subExplanations = new Explanation[in.readVInt()]; for (int i = 0; i < subExplanations.length; ++i) { subExplanations[i] = readExplanation(in); } if (match) { return Explanation.match(readExplanationValue(in), description, subExplanations); } else { return Explanation.noMatch(description, subExplanations); } } private static void writeExplanationValue(StreamOutput out, Number value) throws IOException { if (value instanceof Float) { out.writeByte((byte) 0); out.writeFloat(value.floatValue()); } else if (value instanceof Double) { out.writeByte((byte) 1); out.writeDouble(value.doubleValue()); } else { out.writeByte((byte) 2); out.writeZLong(value.longValue()); } } public static void writeExplanation(StreamOutput out, Explanation explanation) throws IOException { out.writeBoolean(explanation.isMatch()); out.writeString(explanation.getDescription()); Explanation[] subExplanations = explanation.getDetails(); out.writeArray(Lucene::writeExplanation, subExplanations); if (explanation.isMatch()) { writeExplanationValue(out, explanation.getValue()); } } public static boolean indexExists(final Directory directory) throws IOException { return DirectoryReader.indexExists(directory); } /** * Returns {@code true} iff the given exception or * one of it's causes is an instance of {@link CorruptIndexException}, * {@link IndexFormatTooOldException}, or {@link IndexFormatTooNewException} otherwise {@code false}. */ public static boolean isCorruptionException(Throwable t) { return ExceptionsHelper.unwrapCorruption(t) != null; } /** * Parses the version string lenient and returns the default value if the given string is null or empty */ public static Version parseVersionLenient(String toParse, Version defaultValue) { return LenientParser.parse(toParse, defaultValue); } /** * Tries to extract a segment reader from the given index reader. * If no SegmentReader can be extracted an {@link IllegalStateException} is thrown. */ public static SegmentReader segmentReader(LeafReader reader) { if (reader instanceof SegmentReader) { return (SegmentReader) reader; } else if (reader instanceof final FilterLeafReader fReader) { return segmentReader(FilterLeafReader.unwrap(fReader)); } else if (reader instanceof final FilterCodecReader fReader) { return segmentReader(FilterCodecReader.unwrap(fReader)); } // hard fail - we can't get a SegmentReader throw new IllegalStateException("Can not extract segment reader from given index reader [" + reader + "]"); } @SuppressForbidden(reason = "Version#parseLeniently() used in a central place") private static final class LenientParser { public static Version parse(String toParse, Version defaultValue) { if (Strings.hasLength(toParse)) { try { return Version.parseLeniently(toParse); } catch (ParseException e) { // pass to default } } return defaultValue; } } private static final class CommitPoint extends IndexCommit { private final String segmentsFileName; private final Collection<String> files; private final Directory dir; private final long generation; private final Map<String, String> userData; private final int segmentCount; private CommitPoint(SegmentInfos infos, Directory dir) throws IOException { segmentsFileName = infos.getSegmentsFileName(); this.dir = dir; userData = infos.getUserData(); files = Collections.unmodifiableCollection(infos.files(true)); generation = infos.getGeneration(); segmentCount = infos.size(); } @Override public String toString() { return "DirectoryReader.ReaderCommit(" + segmentsFileName + ")"; } @Override public int getSegmentCount() { return segmentCount; } @Override public String getSegmentsFileName() { return segmentsFileName; } @Override public Collection<String> getFileNames() { return files; } @Override public Directory getDirectory() { return dir; } @Override public long getGeneration() { return generation; } @Override public boolean isDeleted() { return false; } @Override public Map<String, String> getUserData() { return userData; } @Override public void delete() { throw new UnsupportedOperationException("This IndexCommit does not support deletions"); } } /** * Return a {@link Bits} view of the provided scorer. * <b>NOTE</b>: that the returned {@link Bits} instance MUST be consumed in order. * @see #asSequentialAccessBits(int, ScorerSupplier, long) */ public static Bits asSequentialAccessBits(final int maxDoc, @Nullable ScorerSupplier scorerSupplier) throws IOException { return asSequentialAccessBits(maxDoc, scorerSupplier, 0L); } /** * Given a {@link ScorerSupplier}, return a {@link Bits} instance that will match * all documents contained in the set. * <b>NOTE</b>: that the returned {@link Bits} instance MUST be consumed in order. * @param estimatedGetCount an estimation of the number of times that {@link Bits#get} will get called */ public static Bits asSequentialAccessBits(final int maxDoc, @Nullable ScorerSupplier scorerSupplier, long estimatedGetCount) throws IOException { if (scorerSupplier == null) { return new Bits.MatchNoBits(maxDoc); } // Since we want bits, we need random-access final Scorer scorer = scorerSupplier.get(estimatedGetCount); // this never returns null final TwoPhaseIterator twoPhase = scorer.twoPhaseIterator(); final DocIdSetIterator iterator; if (twoPhase == null) { iterator = scorer.iterator(); } else { iterator = twoPhase.approximation(); } return new Bits() { int previous = -1; boolean previousMatched = false; @Override public boolean get(int index) { Objects.checkIndex(index, maxDoc); if (index < previous) { throw new IllegalArgumentException( "This Bits instance can only be consumed in order. " + "Got called on [" + index + "] while previously called on [" + previous + "]" ); } if (index == previous) { // we cache whether it matched because it is illegal to call // twoPhase.matches() twice return previousMatched; } previous = index; int doc = iterator.docID(); if (doc < index) { try { doc = iterator.advance(index); } catch (IOException e) { throw new IllegalStateException("Cannot advance iterator", e); } } if (index == doc) { try { return previousMatched = twoPhase == null || twoPhase.matches(); } catch (IOException e) { throw new IllegalStateException("Cannot validate match", e); } } return previousMatched = false; } @Override public int length() { return maxDoc; } }; } /** * Whether a query sorted by {@code searchSort} can be early-terminated if the index is sorted by {@code indexSort}. */ public static boolean canEarlyTerminate(Sort searchSort, Sort indexSort) { final SortField[] fields1 = searchSort.getSort(); final SortField[] fields2 = indexSort.getSort(); // early termination is possible if fields1 is a prefix of fields2 if (fields1.length > fields2.length) { return false; } return Arrays.asList(fields1).equals(Arrays.asList(fields2).subList(0, fields1.length)); } /** * Wraps a directory reader to make all documents live except those were rolled back * or hard-deleted due to non-aborting exceptions during indexing. * The wrapped reader can be used to query all documents. * * @param in the input directory reader * @return the wrapped reader */ public static DirectoryReader wrapAllDocsLive(DirectoryReader in) throws IOException { return new DirectoryReaderWithAllLiveDocs(in); } private static final class DirectoryReaderWithAllLiveDocs extends FilterDirectoryReader { static final class LeafReaderWithLiveDocs extends SequentialStoredFieldsLeafReader { final Bits liveDocs; final int numDocs; LeafReaderWithLiveDocs(LeafReader in, Bits liveDocs, int numDocs) { super(in); this.liveDocs = liveDocs; this.numDocs = numDocs; } @Override public Bits getLiveDocs() { return liveDocs; } @Override public int numDocs() { return numDocs; } @Override public CacheHelper getCoreCacheHelper() { return in.getCoreCacheHelper(); } @Override public CacheHelper getReaderCacheHelper() { return null; // Modifying liveDocs } @Override protected StoredFieldsReader doGetSequentialStoredFieldsReader(StoredFieldsReader reader) { return reader; } } DirectoryReaderWithAllLiveDocs(DirectoryReader in) throws IOException { super(in, new SubReaderWrapper() { @Override public LeafReader wrap(LeafReader leaf) { final SegmentReader segmentReader = segmentReader(leaf); final Bits hardLiveDocs = segmentReader.getHardLiveDocs(); if (hardLiveDocs == null) { return new LeafReaderWithLiveDocs(leaf, null, leaf.maxDoc()); } // Once soft-deletes is enabled, we no longer hard-update or hard-delete documents directly. // Two scenarios that we have hard-deletes: (1) from old segments where soft-deletes was disabled, // (2) when IndexWriter hits non-aborted exceptions. These two cases, IW flushes SegmentInfos // before exposing the hard-deletes, thus we can use the hard-delete count of SegmentInfos. final int numDocs = segmentReader.maxDoc() - segmentReader.getSegmentInfo().getDelCount(); assert numDocs == popCount(hardLiveDocs) : numDocs + " != " + popCount(hardLiveDocs); return new LeafReaderWithLiveDocs(segmentReader, hardLiveDocs, numDocs); } }); } @Override protected DirectoryReader doWrapDirectoryReader(DirectoryReader in) throws IOException { return wrapAllDocsLive(in); } @Override public CacheHelper getReaderCacheHelper() { return null; // Modifying liveDocs } } private static int popCount(Bits bits) { assert bits != null; int onBits = 0; for (int i = 0; i < bits.length(); i++) { if (bits.get(i)) { onBits++; } } return onBits; } /** * Returns a numeric docvalues which can be used to soft-delete documents. */ public static NumericDocValuesField newSoftDeletesField() { return new NumericDocValuesField(SOFT_DELETES_FIELD, 1); } /** * Prepares a new {@link IndexWriterConfig} that does not do any merges, by setting both the merge policy and the merge scheduler. * Setting just the merge policy means that constructing the index writer will create a {@link ConcurrentMergeScheduler} by default, * which is quite heavyweight. */ @SuppressForbidden(reason = "NoMergePolicy#INSTANCE is safe to use since we also set NoMergeScheduler#INSTANCE") public static IndexWriterConfig indexWriterConfigWithNoMerging(Analyzer analyzer) { return new IndexWriterConfig(analyzer).setMergePolicy(NoMergePolicy.INSTANCE).setMergeScheduler(NoMergeScheduler.INSTANCE); } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/common/lucene/Lucene.java
44,928
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.rocketmq.store; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import org.apache.rocketmq.common.BoundaryType; import org.apache.rocketmq.common.Pair; import org.apache.rocketmq.common.SystemClock; import org.apache.rocketmq.common.message.MessageExt; import org.apache.rocketmq.common.message.MessageExtBatch; import org.apache.rocketmq.common.message.MessageExtBrokerInner; import org.apache.rocketmq.remoting.protocol.body.HARuntimeInfo; import org.apache.rocketmq.store.config.MessageStoreConfig; import org.apache.rocketmq.store.ha.HAService; import org.apache.rocketmq.store.hook.PutMessageHook; import org.apache.rocketmq.store.hook.SendMessageBackHook; import org.apache.rocketmq.store.logfile.MappedFile; import org.apache.rocketmq.store.queue.ConsumeQueueInterface; import org.apache.rocketmq.store.queue.ConsumeQueueStoreInterface; import org.apache.rocketmq.store.stats.BrokerStatsManager; import org.apache.rocketmq.store.timer.TimerMessageStore; import org.apache.rocketmq.store.util.PerfCounter; import org.rocksdb.RocksDBException; import io.opentelemetry.api.common.AttributesBuilder; import io.opentelemetry.api.metrics.Meter; import io.opentelemetry.sdk.metrics.InstrumentSelector; import io.opentelemetry.sdk.metrics.ViewBuilder; /** * This class defines contracting interfaces to implement, allowing third-party vendor to use customized message store. */ public interface MessageStore { /** * Load previously stored messages. * * @return true if success; false otherwise. */ boolean load(); /** * Launch this message store. * * @throws Exception if there is any error. */ void start() throws Exception; /** * Shutdown this message store. */ void shutdown(); /** * Destroy this message store. Generally, all persistent files should be removed after invocation. */ void destroy(); /** * Store a message into store in async manner, the processor can process the next request rather than wait for * result when result is completed, notify the client in async manner * * @param msg MessageInstance to store * @return a CompletableFuture for the result of store operation */ default CompletableFuture<PutMessageResult> asyncPutMessage(final MessageExtBrokerInner msg) { return CompletableFuture.completedFuture(putMessage(msg)); } /** * Store a batch of messages in async manner * * @param messageExtBatch the message batch * @return a CompletableFuture for the result of store operation */ default CompletableFuture<PutMessageResult> asyncPutMessages(final MessageExtBatch messageExtBatch) { return CompletableFuture.completedFuture(putMessages(messageExtBatch)); } /** * Store a message into store. * * @param msg Message instance to store * @return result of store operation. */ PutMessageResult putMessage(final MessageExtBrokerInner msg); /** * Store a batch of messages. * * @param messageExtBatch Message batch. * @return result of storing batch messages. */ PutMessageResult putMessages(final MessageExtBatch messageExtBatch); /** * Query at most <code>maxMsgNums</code> messages belonging to <code>topic</code> at <code>queueId</code> starting * from given <code>offset</code>. Resulting messages will further be screened using provided message filter. * * @param group Consumer group that launches this query. * @param topic Topic to query. * @param queueId Queue ID to query. * @param offset Logical offset to start from. * @param maxMsgNums Maximum count of messages to query. * @param messageFilter Message filter used to screen desired messages. * @return Matched messages. */ GetMessageResult getMessage(final String group, final String topic, final int queueId, final long offset, final int maxMsgNums, final MessageFilter messageFilter); /** * Asynchronous get message * @see #getMessage(String, String, int, long, int, MessageFilter) getMessage * * @param group Consumer group that launches this query. * @param topic Topic to query. * @param queueId Queue ID to query. * @param offset Logical offset to start from. * @param maxMsgNums Maximum count of messages to query. * @param messageFilter Message filter used to screen desired messages. * @return Matched messages. */ CompletableFuture<GetMessageResult> getMessageAsync(final String group, final String topic, final int queueId, final long offset, final int maxMsgNums, final MessageFilter messageFilter); /** * Query at most <code>maxMsgNums</code> messages belonging to <code>topic</code> at <code>queueId</code> starting * from given <code>offset</code>. Resulting messages will further be screened using provided message filter. * * @param group Consumer group that launches this query. * @param topic Topic to query. * @param queueId Queue ID to query. * @param offset Logical offset to start from. * @param maxMsgNums Maximum count of messages to query. * @param maxTotalMsgSize Maximum total msg size of the messages * @param messageFilter Message filter used to screen desired messages. * @return Matched messages. */ GetMessageResult getMessage(final String group, final String topic, final int queueId, final long offset, final int maxMsgNums, final int maxTotalMsgSize, final MessageFilter messageFilter); /** * Asynchronous get message * @see #getMessage(String, String, int, long, int, int, MessageFilter) getMessage * * @param group Consumer group that launches this query. * @param topic Topic to query. * @param queueId Queue ID to query. * @param offset Logical offset to start from. * @param maxMsgNums Maximum count of messages to query. * @param maxTotalMsgSize Maximum total msg size of the messages * @param messageFilter Message filter used to screen desired messages. * @return Matched messages. */ CompletableFuture<GetMessageResult> getMessageAsync(final String group, final String topic, final int queueId, final long offset, final int maxMsgNums, final int maxTotalMsgSize, final MessageFilter messageFilter); /** * Get maximum offset of the topic queue. * * @param topic Topic name. * @param queueId Queue ID. * @return Maximum offset at present. */ long getMaxOffsetInQueue(final String topic, final int queueId); /** * Get maximum offset of the topic queue. * * @param topic Topic name. * @param queueId Queue ID. * @param committed return the max offset in ConsumeQueue if true, or the max offset in CommitLog if false * @return Maximum offset at present. */ long getMaxOffsetInQueue(final String topic, final int queueId, final boolean committed); /** * Get the minimum offset of the topic queue. * * @param topic Topic name. * @param queueId Queue ID. * @return Minimum offset at present. */ long getMinOffsetInQueue(final String topic, final int queueId); TimerMessageStore getTimerMessageStore(); void setTimerMessageStore(TimerMessageStore timerMessageStore); /** * Get the offset of the message in the commit log, which is also known as physical offset. * * @param topic Topic of the message to lookup. * @param queueId Queue ID. * @param consumeQueueOffset offset of consume queue. * @return physical offset. */ long getCommitLogOffsetInQueue(final String topic, final int queueId, final long consumeQueueOffset); /** * Look up the physical offset of the message whose store timestamp is as specified. * * @param topic Topic of the message. * @param queueId Queue ID. * @param timestamp Timestamp to look up. * @return physical offset which matches. */ long getOffsetInQueueByTime(final String topic, final int queueId, final long timestamp); /** * Look up the physical offset of the message whose store timestamp is as specified with specific boundaryType. * * @param topic Topic of the message. * @param queueId Queue ID. * @param timestamp Timestamp to look up. * @param boundaryType Lower or Upper * @return physical offset which matches. */ long getOffsetInQueueByTime(final String topic, final int queueId, final long timestamp, final BoundaryType boundaryType); /** * Look up the message by given commit log offset. * * @param commitLogOffset physical offset. * @return Message whose physical offset is as specified. */ MessageExt lookMessageByOffset(final long commitLogOffset); /** * Look up the message by given commit log offset and size. * * @param commitLogOffset physical offset. * @param size message size * @return Message whose physical offset is as specified. */ MessageExt lookMessageByOffset(long commitLogOffset, int size); /** * Get one message from the specified commit log offset. * * @param commitLogOffset commit log offset. * @return wrapped result of the message. */ SelectMappedBufferResult selectOneMessageByOffset(final long commitLogOffset); /** * Get one message from the specified commit log offset. * * @param commitLogOffset commit log offset. * @param msgSize message size. * @return wrapped result of the message. */ SelectMappedBufferResult selectOneMessageByOffset(final long commitLogOffset, final int msgSize); /** * Get the running information of this store. * * @return message store running info. */ String getRunningDataInfo(); long getTimingMessageCount(String topic); /** * Message store runtime information, which should generally contains various statistical information. * * @return runtime information of the message store in format of key-value pairs. */ HashMap<String, String> getRuntimeInfo(); /** * HA runtime information * @return runtime information of ha */ HARuntimeInfo getHARuntimeInfo(); /** * Get the maximum commit log offset. * * @return maximum commit log offset. */ long getMaxPhyOffset(); /** * Get the minimum commit log offset. * * @return minimum commit log offset. */ long getMinPhyOffset(); /** * Get the store time of the earliest message in the given queue. * * @param topic Topic of the messages to query. * @param queueId Queue ID to find. * @return store time of the earliest message. */ long getEarliestMessageTime(final String topic, final int queueId); /** * Get the store time of the earliest message in this store. * * @return timestamp of the earliest message in this store. */ long getEarliestMessageTime(); /** * Asynchronous get the store time of the earliest message in this store. * @see #getEarliestMessageTime() getEarliestMessageTime * * @return timestamp of the earliest message in this store. */ CompletableFuture<Long> getEarliestMessageTimeAsync(final String topic, final int queueId); /** * Get the store time of the message specified. * * @param topic message topic. * @param queueId queue ID. * @param consumeQueueOffset consume queue offset. * @return store timestamp of the message. */ long getMessageStoreTimeStamp(final String topic, final int queueId, final long consumeQueueOffset); /** * Asynchronous get the store time of the message specified. * @see #getMessageStoreTimeStamp(String, int, long) getMessageStoreTimeStamp * * @param topic message topic. * @param queueId queue ID. * @param consumeQueueOffset consume queue offset. * @return store timestamp of the message. */ CompletableFuture<Long> getMessageStoreTimeStampAsync(final String topic, final int queueId, final long consumeQueueOffset); /** * Get the total number of the messages in the specified queue. * * @param topic Topic * @param queueId Queue ID. * @return total number. */ long getMessageTotalInQueue(final String topic, final int queueId); /** * Get the raw commit log data starting from the given offset, which should used for replication purpose. * * @param offset starting offset. * @return commit log data. */ SelectMappedBufferResult getCommitLogData(final long offset); /** * Get the raw commit log data starting from the given offset, across multiple mapped files. * * @param offset starting offset. * @param size size of data to get * @return commit log data. */ List<SelectMappedBufferResult> getBulkCommitLogData(final long offset, final int size); /** * Append data to commit log. * * @param startOffset starting offset. * @param data data to append. * @param dataStart the start index of data array * @param dataLength the length of data array * @return true if success; false otherwise. */ boolean appendToCommitLog(final long startOffset, final byte[] data, int dataStart, int dataLength); /** * Execute file deletion manually. */ void executeDeleteFilesManually(); /** * Query messages by given key. * * @param topic topic of the message. * @param key message key. * @param maxNum maximum number of the messages possible. * @param begin begin timestamp. * @param end end timestamp. */ QueryMessageResult queryMessage(final String topic, final String key, final int maxNum, final long begin, final long end); /** * Asynchronous query messages by given key. * @see #queryMessage(String, String, int, long, long) queryMessage * * @param topic topic of the message. * @param key message key. * @param maxNum maximum number of the messages possible. * @param begin begin timestamp. * @param end end timestamp. */ CompletableFuture<QueryMessageResult> queryMessageAsync(final String topic, final String key, final int maxNum, final long begin, final long end); /** * Update HA master address. * * @param newAddr new address. */ void updateHaMasterAddress(final String newAddr); /** * Update master address. * * @param newAddr new address. */ void updateMasterAddress(final String newAddr); /** * Return how much the slave falls behind. * * @return number of bytes that slave falls behind. */ long slaveFallBehindMuch(); /** * Return the current timestamp of the store. * * @return current time in milliseconds since 1970-01-01. */ long now(); /** * Delete topic's consume queue file and unused stats. * This interface allows user delete system topic. * * @param deleteTopics unused topic name set * @return the number of the topics which has been deleted. */ int deleteTopics(final Set<String> deleteTopics); /** * Clean unused topics which not in retain topic name set. * * @param retainTopics all valid topics. * @return number of the topics deleted. */ int cleanUnusedTopic(final Set<String> retainTopics); /** * Clean expired consume queues. */ void cleanExpiredConsumerQueue(); /** * Check if the given message has been swapped out of the memory. * * @param topic topic. * @param queueId queue ID. * @param consumeOffset consume queue offset. * @return true if the message is no longer in memory; false otherwise. * @deprecated As of RIP-57, replaced by {@link #checkInMemByConsumeOffset(String, int, long, int)}, see <a href="https://github.com/apache/rocketmq/issues/5837">this issue</a> for more details */ @Deprecated boolean checkInDiskByConsumeOffset(final String topic, final int queueId, long consumeOffset); /** * Check if the given message is in the page cache. * * @param topic topic. * @param queueId queue ID. * @param consumeOffset consume queue offset. * @return true if the message is in page cache; false otherwise. */ boolean checkInMemByConsumeOffset(final String topic, final int queueId, long consumeOffset, int batchSize); /** * Check if the given message is in store. * * @param topic topic. * @param queueId queue ID. * @param consumeOffset consume queue offset. * @return true if the message is in store; false otherwise. */ boolean checkInStoreByConsumeOffset(final String topic, final int queueId, long consumeOffset); /** * Get number of the bytes that have been stored in commit log and not yet dispatched to consume queue. * * @return number of the bytes to dispatch. */ long dispatchBehindBytes(); /** * Flush the message store to persist all data. * * @return maximum offset flushed to persistent storage device. */ long flush(); /** * Get the current flushed offset. * * @return flushed offset */ long getFlushedWhere(); /** * Reset written offset. * * @param phyOffset new offset. * @return true if success; false otherwise. */ boolean resetWriteOffset(long phyOffset); /** * Get confirm offset. * * @return confirm offset. */ long getConfirmOffset(); /** * Set confirm offset. * * @param phyOffset confirm offset to set. */ void setConfirmOffset(long phyOffset); /** * Check if the operating system page cache is busy or not. * * @return true if the OS page cache is busy; false otherwise. */ boolean isOSPageCacheBusy(); /** * Get lock time in milliseconds of the store by far. * * @return lock time in milliseconds. */ long lockTimeMills(); /** * Check if the transient store pool is deficient. * * @return true if the transient store pool is running out; false otherwise. */ boolean isTransientStorePoolDeficient(); /** * Get the dispatcher list. * * @return list of the dispatcher. */ LinkedList<CommitLogDispatcher> getDispatcherList(); /** * Add dispatcher. * * @param dispatcher commit log dispatcher to add */ void addDispatcher(CommitLogDispatcher dispatcher); /** * Get consume queue of the topic/queue. If consume queue not exist, will return null * * @param topic Topic. * @param queueId Queue ID. * @return Consume queue. */ ConsumeQueueInterface getConsumeQueue(String topic, int queueId); /** * Get consume queue of the topic/queue. If consume queue not exist, will create one then return it. * @param topic Topic. * @param queueId Queue ID. * @return Consume queue. */ ConsumeQueueInterface findConsumeQueue(String topic, int queueId); /** * Get BrokerStatsManager of the messageStore. * * @return BrokerStatsManager. */ BrokerStatsManager getBrokerStatsManager(); /** * Will be triggered when a new message is appended to commit log. * * @param msg the msg that is appended to commit log * @param result append message result * @param commitLogFile commit log file */ void onCommitLogAppend(MessageExtBrokerInner msg, AppendMessageResult result, MappedFile commitLogFile); /** * Will be triggered when a new dispatch request is sent to message store. * * @param dispatchRequest dispatch request * @param doDispatch do dispatch if true * @param commitLogFile commit log file * @param isRecover is from recover process * @param isFileEnd if the dispatch request represents 'file end' * @throws RocksDBException only in rocksdb mode */ void onCommitLogDispatch(DispatchRequest dispatchRequest, boolean doDispatch, MappedFile commitLogFile, boolean isRecover, boolean isFileEnd) throws RocksDBException; /** * Only used in rocksdb mode, because we build consumeQueue in batch(default 16 dispatchRequests) * It will be triggered in two cases: * @see org.apache.rocketmq.store.DefaultMessageStore.ReputMessageService#doReput * @see CommitLog#recoverAbnormally */ void finishCommitLogDispatch(); /** * Get the message store config * * @return the message store config */ MessageStoreConfig getMessageStoreConfig(); /** * Get the statistics service * * @return the statistics service */ StoreStatsService getStoreStatsService(); /** * Get the store checkpoint component * * @return the checkpoint component */ StoreCheckpoint getStoreCheckpoint(); /** * Get the system clock * * @return the system clock */ SystemClock getSystemClock(); /** * Get the commit log * * @return the commit log */ CommitLog getCommitLog(); /** * Get running flags * * @return running flags */ RunningFlags getRunningFlags(); /** * Get the transient store pool * * @return the transient store pool */ TransientStorePool getTransientStorePool(); /** * Get the HA service * * @return the HA service */ HAService getHaService(); /** * Get the allocate-mappedFile service * * @return the allocate-mappedFile service */ AllocateMappedFileService getAllocateMappedFileService(); /** * Truncate dirty logic files * * @param phyOffset physical offset * @throws RocksDBException only in rocksdb mode */ void truncateDirtyLogicFiles(long phyOffset) throws RocksDBException; /** * Unlock mappedFile * * @param unlockMappedFile the file that needs to be unlocked */ void unlockMappedFile(MappedFile unlockMappedFile); /** * Get the perf counter component * * @return the perf counter component */ PerfCounter.Ticks getPerfCounter(); /** * Get the queue store * * @return the queue store */ ConsumeQueueStoreInterface getQueueStore(); /** * If 'sync disk flush' is configured in this message store * * @return yes if true, no if false */ boolean isSyncDiskFlush(); /** * If this message store is sync master role * * @return yes if true, no if false */ boolean isSyncMaster(); /** * Assign a message to queue offset. If there is a race condition, you need to lock/unlock this method * yourself. * * @param msg message * @throws RocksDBException */ void assignOffset(MessageExtBrokerInner msg) throws RocksDBException; /** * Increase queue offset in memory table. If there is a race condition, you need to lock/unlock this method * * @param msg message * @param messageNum message num */ void increaseOffset(MessageExtBrokerInner msg, short messageNum); /** * Get master broker message store in process in broker container * * @return */ MessageStore getMasterStoreInProcess(); /** * Set master broker message store in process * * @param masterStoreInProcess */ void setMasterStoreInProcess(MessageStore masterStoreInProcess); /** * Use FileChannel to get data * * @param offset * @param size * @param byteBuffer * @return */ boolean getData(long offset, int size, ByteBuffer byteBuffer); /** * Set the number of alive replicas in group. * * @param aliveReplicaNums number of alive replicas */ void setAliveReplicaNumInGroup(int aliveReplicaNums); /** * Get the number of alive replicas in group. * * @return number of alive replicas */ int getAliveReplicaNumInGroup(); /** * Wake up AutoRecoverHAClient to start HA connection. */ void wakeupHAClient(); /** * Get master flushed offset. * * @return master flushed offset */ long getMasterFlushedOffset(); /** * Get broker init max offset. * * @return broker max offset in startup */ long getBrokerInitMaxOffset(); /** * Set master flushed offset. * * @param masterFlushedOffset master flushed offset */ void setMasterFlushedOffset(long masterFlushedOffset); /** * Set broker init max offset. * * @param brokerInitMaxOffset broker init max offset */ void setBrokerInitMaxOffset(long brokerInitMaxOffset); /** * Calculate the checksum of a certain range of data. * * @param from begin offset * @param to end offset * @return checksum */ byte[] calcDeltaChecksum(long from, long to); /** * Truncate commitLog and consume queue to certain offset. * * @param offsetToTruncate offset to truncate * @return true if truncate succeed, false otherwise * @throws RocksDBException only in rocksdb mode */ boolean truncateFiles(long offsetToTruncate) throws RocksDBException; /** * Check if the offset is aligned with one message. * * @param offset offset to check * @return true if aligned, false otherwise */ boolean isOffsetAligned(long offset); /** * Get put message hook list * * @return List of PutMessageHook */ List<PutMessageHook> getPutMessageHookList(); /** * Set send message back hook * * @param sendMessageBackHook */ void setSendMessageBackHook(SendMessageBackHook sendMessageBackHook); /** * Get send message back hook * * @return SendMessageBackHook */ SendMessageBackHook getSendMessageBackHook(); //The following interfaces are used for duplication mode /** * Get last mapped file and return lase file first Offset * * @return lastMappedFile first Offset */ long getLastFileFromOffset(); /** * Get last mapped file * * @param startOffset * @return true when get the last mapped file, false when get null */ boolean getLastMappedFile(long startOffset); /** * Set physical offset * * @param phyOffset */ void setPhysicalOffset(long phyOffset); /** * Return whether mapped file is empty * * @return whether mapped file is empty */ boolean isMappedFilesEmpty(); /** * Get state machine version * * @return state machine version */ long getStateMachineVersion(); /** * Check message and return size * * @param byteBuffer * @param checkCRC * @param checkDupInfo * @param readBody * @return DispatchRequest */ DispatchRequest checkMessageAndReturnSize(final ByteBuffer byteBuffer, final boolean checkCRC, final boolean checkDupInfo, final boolean readBody); /** * Get remain transientStoreBuffer numbers * * @return remain transientStoreBuffer numbers */ int remainTransientStoreBufferNumbs(); /** * Get remain how many data to commit * * @return remain how many data to commit */ long remainHowManyDataToCommit(); /** * Get remain how many data to flush * * @return remain how many data to flush */ long remainHowManyDataToFlush(); /** * Get whether message store is shutdown * * @return whether shutdown */ boolean isShutdown(); /** * Estimate number of messages, within [from, to], which match given filter * * @param topic Topic name * @param queueId Queue ID * @param from Lower boundary of the range, inclusive. * @param to Upper boundary of the range, inclusive. * @param filter The message filter. * @return Estimate number of messages matching given filter. */ long estimateMessageCount(String topic, int queueId, long from, long to, MessageFilter filter); /** * Get metrics view of store * * @return List of metrics selector and view pair */ List<Pair<InstrumentSelector, ViewBuilder>> getMetricsView(); /** * Init store metrics * * @param meter opentelemetry meter * @param attributesBuilderSupplier metrics attributes builder */ void initMetrics(Meter meter, Supplier<AttributesBuilder> attributesBuilderSupplier); /** * Recover topic queue table */ void recoverTopicQueueTable(); /** * notify message arrive if necessary */ void notifyMessageArriveIfNecessary(DispatchRequest dispatchRequest); }
apache/rocketmq
store/src/main/java/org/apache/rocketmq/store/MessageStore.java
44,929
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.tools; import joptsimple.ArgumentAcceptingOptionSpec; import joptsimple.OptionSpec; import joptsimple.OptionSpecBuilder; import org.apache.kafka.clients.admin.Admin; import org.apache.kafka.clients.admin.AdminClientConfig; import org.apache.kafka.clients.admin.Config; import org.apache.kafka.clients.admin.ConfigEntry; import org.apache.kafka.clients.admin.CreatePartitionsOptions; import org.apache.kafka.clients.admin.CreateTopicsOptions; import org.apache.kafka.clients.admin.CreateTopicsResult; import org.apache.kafka.clients.admin.DeleteTopicsOptions; import org.apache.kafka.clients.admin.DescribeTopicsOptions; import org.apache.kafka.clients.admin.ListTopicsOptions; import org.apache.kafka.clients.admin.ListTopicsResult; import org.apache.kafka.clients.admin.NewPartitions; import org.apache.kafka.clients.admin.NewTopic; import org.apache.kafka.clients.admin.PartitionReassignment; import org.apache.kafka.clients.admin.TopicListing; import org.apache.kafka.common.KafkaFuture; import org.apache.kafka.common.Node; import org.apache.kafka.common.TopicCollection; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.TopicPartitionInfo; import org.apache.kafka.common.Uuid; import org.apache.kafka.common.config.ConfigResource; import org.apache.kafka.common.config.TopicConfig; import org.apache.kafka.common.errors.ClusterAuthorizationException; import org.apache.kafka.common.errors.TopicExistsException; import org.apache.kafka.common.errors.UnsupportedVersionException; import org.apache.kafka.common.internals.Topic; import org.apache.kafka.common.utils.Exit; import org.apache.kafka.common.utils.Utils; import org.apache.kafka.server.common.AdminCommandFailedException; import org.apache.kafka.server.common.AdminOperationException; import org.apache.kafka.server.util.CommandDefaultOptions; import org.apache.kafka.server.util.CommandLineUtils; import org.apache.kafka.server.util.TopicFilter.IncludeList; import org.apache.kafka.storage.internals.log.LogConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Properties; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; public abstract class TopicCommand { private static final Logger LOG = LoggerFactory.getLogger(TopicCommand.class); public static void main(String... args) { Exit.exit(mainNoExit(args)); } private static int mainNoExit(String... args) { try { execute(args); return 0; } catch (Throwable e) { System.err.println(e.getMessage()); System.err.println(Utils.stackTrace(e)); return 1; } } static void execute(String... args) throws Exception { TopicCommandOptions opts = new TopicCommandOptions(args); TopicService topicService = new TopicService(opts.commandConfig(), opts.bootstrapServer()); int exitCode = 0; try { if (opts.hasCreateOption()) { topicService.createTopic(opts); } else if (opts.hasAlterOption()) { topicService.alterTopic(opts); } else if (opts.hasListOption()) { topicService.listTopics(opts); } else if (opts.hasDescribeOption()) { topicService.describeTopic(opts); } else if (opts.hasDeleteOption()) { topicService.deleteTopic(opts); } } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause != null) { printException(cause); } else { printException(e); } exitCode = 1; } catch (Throwable e) { printException(e); exitCode = 1; } finally { topicService.close(); Exit.exit(exitCode); } } private static void printException(Throwable e) { System.out.println("Error while executing topic command : " + e.getMessage()); LOG.error(Utils.stackTrace(e)); } static Map<Integer, List<Integer>> parseReplicaAssignment(String replicaAssignmentList) { String[] partitionList = replicaAssignmentList.split(","); Map<Integer, List<Integer>> ret = new LinkedHashMap<>(); for (int i = 0; i < partitionList.length; i++) { List<Integer> brokerList = Arrays.stream(partitionList[i].split(":")) .map(String::trim) .mapToInt(Integer::parseInt) .boxed() .collect(Collectors.toList()); Collection<Integer> duplicateBrokers = ToolsUtils.duplicates(brokerList); if (!duplicateBrokers.isEmpty()) { throw new AdminCommandFailedException("Partition replica lists may not contain duplicate entries: " + duplicateBrokers.stream() .map(Object::toString) .collect(Collectors.joining(",")) ); } ret.put(i, brokerList); if (ret.get(i).size() != ret.get(0).size()) { throw new AdminOperationException("Partition " + i + " has different replication factor: " + brokerList); } } return ret; } @SuppressWarnings("deprecation") private static Properties parseTopicConfigsToBeAdded(TopicCommandOptions opts) { List<List<String>> configsToBeAdded = opts.topicConfig().orElse(Collections.emptyList()) .stream() .map(s -> Arrays.asList(s.split("\\s*=\\s*"))) .collect(Collectors.toList()); if (!configsToBeAdded.stream().allMatch(config -> config.size() == 2)) { throw new IllegalArgumentException("requirement failed: Invalid topic config: all configs to be added must be in the format \"key=val\"."); } Properties props = new Properties(); configsToBeAdded.stream() .forEach(pair -> props.setProperty(pair.get(0).trim(), pair.get(1).trim())); LogConfig.validate(props); if (props.containsKey(TopicConfig.MESSAGE_FORMAT_VERSION_CONFIG)) { System.out.println("WARNING: The configuration ${TopicConfig.MESSAGE_FORMAT_VERSION_CONFIG}=${props.getProperty(TopicConfig.MESSAGE_FORMAT_VERSION_CONFIG)} is specified. " + "This configuration will be ignored if the version is newer than the inter.broker.protocol.version specified in the broker or " + "if the inter.broker.protocol.version is 3.0 or newer. This configuration is deprecated and it will be removed in Apache Kafka 4.0."); } return props; } // It is possible for a reassignment to complete between the time we have fetched its state and the time // we fetch partition metadata. In this case, we ignore the reassignment when determining replication factor. public static boolean isReassignmentInProgress(TopicPartitionInfo tpi, PartitionReassignment ra) { // Reassignment is still in progress as long as the removing and adding replicas are still present Set<Integer> allReplicaIds = tpi.replicas().stream().map(Node::id).collect(Collectors.toSet()); Set<Integer> changingReplicaIds = new HashSet<>(); if (ra != null) { changingReplicaIds.addAll(ra.removingReplicas()); changingReplicaIds.addAll(ra.addingReplicas()); } return allReplicaIds.stream().anyMatch(changingReplicaIds::contains); } private static Integer getReplicationFactor(TopicPartitionInfo tpi, PartitionReassignment reassignment) { return isReassignmentInProgress(tpi, reassignment) ? reassignment.replicas().size() - reassignment.addingReplicas().size() : tpi.replicas().size(); } /** * ensures topic existence and throws exception if topic doesn't exist * * @param foundTopics Topics that were found to match the requested topic name. * @param requestedTopic Name of the topic that was requested. * @param requireTopicExists Indicates if the topic needs to exist for the operation to be successful. * If set to true, the command will throw an exception if the topic with the * requested name does not exist. */ private static void ensureTopicExists(List<String> foundTopics, Optional<String> requestedTopic, Boolean requireTopicExists) { // If no topic name was mentioned, do not need to throw exception. if (requestedTopic.isPresent() && !requestedTopic.get().isEmpty() && requireTopicExists && foundTopics.isEmpty()) { // If given topic doesn't exist then throw exception throw new IllegalArgumentException(String.format("Topic '%s' does not exist as expected", requestedTopic)); } } private static List<String> doGetTopics(List<String> allTopics, Optional<String> topicIncludeList, Boolean excludeInternalTopics) { if (topicIncludeList.isPresent()) { IncludeList topicsFilter = new IncludeList(topicIncludeList.get()); return allTopics.stream() .filter(topic -> topicsFilter.isTopicAllowed(topic, excludeInternalTopics)) .collect(Collectors.toList()); } else { return allTopics.stream() .filter(topic -> !(Topic.isInternal(topic) && excludeInternalTopics)) .collect(Collectors.toList()); } } /** * ensures topic existence and throws exception if topic doesn't exist * * @param foundTopicIds Topics that were found to match the requested topic id. * @param requestedTopicId Id of the topic that was requested. * @param requireTopicIdExists Indicates if the topic needs to exist for the operation to be successful. * If set to true, the command will throw an exception if the topic with the * requested id does not exist. */ private static void ensureTopicIdExists(List<Uuid> foundTopicIds, Uuid requestedTopicId, Boolean requireTopicIdExists) { // If no topic id was mentioned, do not need to throw exception. if (requestedTopicId != null && requireTopicIdExists && foundTopicIds.isEmpty()) { // If given topicId doesn't exist then throw exception throw new IllegalArgumentException(String.format("TopicId '%s' does not exist as expected", requestedTopicId)); } } static class CommandTopicPartition { private final String name; private final Optional<Integer> partitions; private final Optional<Integer> replicationFactor; private final Map<Integer, List<Integer>> replicaAssignment; private final Properties configsToAdd; private final TopicCommandOptions opts; public CommandTopicPartition(TopicCommandOptions options) { opts = options; name = options.topic().get(); partitions = options.partitions(); replicationFactor = options.replicationFactor(); replicaAssignment = options.replicaAssignment().orElse(Collections.emptyMap()); configsToAdd = parseTopicConfigsToBeAdded(options); } public Boolean hasReplicaAssignment() { return !replicaAssignment.isEmpty(); } public Boolean ifTopicDoesntExist() { return opts.ifNotExists(); } } static class TopicDescription { private final String topic; private final Uuid topicId; private final Integer numPartitions; private final Integer replicationFactor; private final Config config; private final Boolean markedForDeletion; public TopicDescription(String topic, Uuid topicId, Integer numPartitions, Integer replicationFactor, Config config, Boolean markedForDeletion) { this.topic = topic; this.topicId = topicId; this.numPartitions = numPartitions; this.replicationFactor = replicationFactor; this.config = config; this.markedForDeletion = markedForDeletion; } public void printDescription() { String configsAsString = config.entries().stream() .filter(config -> !config.isDefault()) .map(ce -> ce.name() + "=" + ce.value()) .collect(Collectors.joining(",")); System.out.print("Topic: " + topic); if (!topicId.equals(Uuid.ZERO_UUID)) System.out.print("\tTopicId: " + topicId); System.out.print("\tPartitionCount: " + numPartitions); System.out.print("\tReplicationFactor: " + replicationFactor); System.out.print("\tConfigs: " + configsAsString); System.out.print(markedForDeletion ? "\tMarkedForDeletion: true" : ""); System.out.println(); } } static class PartitionDescription { private final String topic; private final TopicPartitionInfo info; private final Config config; private final Boolean markedForDeletion; private final PartitionReassignment reassignment; PartitionDescription(String topic, TopicPartitionInfo info, Config config, Boolean markedForDeletion, PartitionReassignment reassignment) { this.topic = topic; this.info = info; this.config = config; this.markedForDeletion = markedForDeletion; this.reassignment = reassignment; } public Integer minIsrCount() { return Integer.parseInt(config.get(TopicConfig.MIN_IN_SYNC_REPLICAS_CONFIG).value()); } public Boolean isUnderReplicated() { return getReplicationFactor(info, reassignment) - info.isr().size() > 0; } public boolean hasLeader() { return info.leader() != null; } public Boolean isUnderMinIsr() { return !hasLeader() || info.isr().size() < minIsrCount(); } public Boolean isAtMinIsrPartitions() { return minIsrCount() == info.isr().size(); } public Boolean hasUnavailablePartitions(Set<Integer> liveBrokers) { return !hasLeader() || !liveBrokers.contains(info.leader().id()); } public void printDescription() { System.out.print("\tTopic: " + topic); System.out.print("\tPartition: " + info.partition()); System.out.print("\tLeader: " + (hasLeader() ? info.leader().id() : "none")); System.out.print("\tReplicas: " + info.replicas().stream() .map(node -> Integer.toString(node.id())) .collect(Collectors.joining(","))); System.out.print("\tIsr: " + info.isr().stream() .map(node -> Integer.toString(node.id())) .collect(Collectors.joining(","))); if (reassignment != null) { System.out.print("\tAdding Replicas: " + reassignment.addingReplicas().stream() .map(node -> node.toString()) .collect(Collectors.joining(","))); System.out.print("\tRemoving Replicas: " + reassignment.removingReplicas().stream() .map(node -> node.toString()) .collect(Collectors.joining(","))); } if (info.elr() != null) { System.out.print("\tElr: " + info.elr().stream() .map(node -> Integer.toString(node.id())) .collect(Collectors.joining(","))); } else { System.out.print("\tElr: N/A"); } if (info.lastKnownElr() != null) { System.out.print("\tLastKnownElr: " + info.lastKnownElr().stream() .map(node -> Integer.toString(node.id())) .collect(Collectors.joining(","))); } else { System.out.print("\tLastKnownElr: N/A"); } System.out.print(markedForDeletion ? "\tMarkedForDeletion: true" : ""); System.out.println(); } } static class DescribeOptions { private final TopicCommandOptions opts; private final Set<Integer> liveBrokers; private final boolean describeConfigs; private final boolean describePartitions; public DescribeOptions(TopicCommandOptions opts, Set<Integer> liveBrokers) { this.opts = opts; this.liveBrokers = liveBrokers; this.describeConfigs = !opts.reportUnavailablePartitions() && !opts.reportUnderReplicatedPartitions() && !opts.reportUnderMinIsrPartitions() && !opts.reportAtMinIsrPartitions(); this.describePartitions = !opts.reportOverriddenConfigs(); } private boolean shouldPrintUnderReplicatedPartitions(PartitionDescription partitionDescription) { return opts.reportUnderReplicatedPartitions() && partitionDescription.isUnderReplicated(); } private boolean shouldPrintUnavailablePartitions(PartitionDescription partitionDescription) { return opts.reportUnavailablePartitions() && partitionDescription.hasUnavailablePartitions(liveBrokers); } private boolean shouldPrintUnderMinIsrPartitions(PartitionDescription partitionDescription) { return opts.reportUnderMinIsrPartitions() && partitionDescription.isUnderMinIsr(); } private boolean shouldPrintAtMinIsrPartitions(PartitionDescription partitionDescription) { return opts.reportAtMinIsrPartitions() && partitionDescription.isAtMinIsrPartitions(); } private boolean shouldPrintTopicPartition(PartitionDescription partitionDesc) { return describeConfigs || shouldPrintUnderReplicatedPartitions(partitionDesc) || shouldPrintUnavailablePartitions(partitionDesc) || shouldPrintUnderMinIsrPartitions(partitionDesc) || shouldPrintAtMinIsrPartitions(partitionDesc); } public void maybePrintPartitionDescription(PartitionDescription desc) { if (shouldPrintTopicPartition(desc)) { desc.printDescription(); } } } public static class TopicService implements AutoCloseable { private final Admin adminClient; public TopicService(Properties commandConfig, Optional<String> bootstrapServer) { this.adminClient = createAdminClient(commandConfig, bootstrapServer); } public TopicService(Admin admin) { this.adminClient = admin; } private static Admin createAdminClient(Properties commandConfig, Optional<String> bootstrapServer) { if (bootstrapServer.isPresent()) { commandConfig.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServer.get()); } return Admin.create(commandConfig); } public void createTopic(TopicCommandOptions opts) throws Exception { CommandTopicPartition topic = new CommandTopicPartition(opts); if (Topic.hasCollisionChars(topic.name)) { System.out.println("WARNING: Due to limitations in metric names, topics with a period ('.') or underscore ('_') could " + "collide. To avoid issues it is best to use either, but not both."); } createTopic(topic); } public void createTopic(CommandTopicPartition topic) throws Exception { if (topic.replicationFactor.filter(rf -> rf > Short.MAX_VALUE || rf < 1).isPresent()) { throw new IllegalArgumentException("The replication factor must be between 1 and " + Short.MAX_VALUE + " inclusive"); } if (topic.partitions.filter(p -> p < 1).isPresent()) { throw new IllegalArgumentException("The partitions must be greater than 0"); } try { NewTopic newTopic; if (topic.hasReplicaAssignment()) { newTopic = new NewTopic(topic.name, topic.replicaAssignment); } else { newTopic = new NewTopic(topic.name, topic.partitions, topic.replicationFactor.map(Integer::shortValue)); } Map<String, String> configsMap = topic.configsToAdd.stringPropertyNames().stream() .collect(Collectors.toMap(name -> name, name -> topic.configsToAdd.getProperty(name))); newTopic.configs(configsMap); CreateTopicsResult createResult = adminClient.createTopics(Collections.singleton(newTopic), new CreateTopicsOptions().retryOnQuotaViolation(false)); createResult.all().get(); System.out.println("Created topic " + topic.name + "."); } catch (ExecutionException e) { if (e.getCause() == null) { throw e; } if (!(e.getCause() instanceof TopicExistsException && topic.ifTopicDoesntExist())) { throw (Exception) e.getCause(); } } } public void listTopics(TopicCommandOptions opts) throws ExecutionException, InterruptedException { String results = getTopics(opts.topic(), opts.excludeInternalTopics()) .stream() .collect(Collectors.joining("\n")); System.out.println(results); } public void alterTopic(TopicCommandOptions opts) throws ExecutionException, InterruptedException { CommandTopicPartition topic = new CommandTopicPartition(opts); List<String> topics = getTopics(opts.topic(), opts.excludeInternalTopics()); ensureTopicExists(topics, opts.topic(), !opts.ifExists()); if (!topics.isEmpty()) { Map<String, KafkaFuture<org.apache.kafka.clients.admin.TopicDescription>> topicsInfo = adminClient.describeTopics(topics).topicNameValues(); Map<String, NewPartitions> newPartitions = topics.stream() .map(topicName -> topicNewPartitions(topic, topicsInfo, topicName)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); adminClient.createPartitions(newPartitions, new CreatePartitionsOptions().retryOnQuotaViolation(false)).all().get(); } } private AbstractMap.SimpleEntry<String, NewPartitions> topicNewPartitions( CommandTopicPartition topic, Map<String, KafkaFuture<org.apache.kafka.clients.admin.TopicDescription>> topicsInfo, String topicName) { if (topic.hasReplicaAssignment()) { try { Integer startPartitionId = topicsInfo.get(topicName).get().partitions().size(); Map<Integer, List<Integer>> replicaMap = topic.replicaAssignment.entrySet().stream() .skip(startPartitionId) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); List<List<Integer>> newAssignment = new ArrayList<>(replicaMap.values()); return new AbstractMap.SimpleEntry<>(topicName, NewPartitions.increaseTo(topic.partitions.get(), newAssignment)); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } return new AbstractMap.SimpleEntry<>(topicName, NewPartitions.increaseTo(topic.partitions.get())); } public Map<TopicPartition, PartitionReassignment> listAllReassignments(Set<TopicPartition> topicPartitions) { try { return adminClient.listPartitionReassignments(topicPartitions).reassignments().get(); } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause instanceof UnsupportedVersionException || cause instanceof ClusterAuthorizationException) { LOG.debug("Couldn't query reassignments through the AdminClient API: " + cause.getMessage(), cause); return Collections.emptyMap(); } else { throw new RuntimeException(e); } } catch (InterruptedException e) { throw new RuntimeException(e); } } public void describeTopic(TopicCommandOptions opts) throws ExecutionException, InterruptedException { // If topicId is provided and not zero, will use topicId regardless of topic name Optional<Uuid> inputTopicId = opts.topicId() .map(Uuid::fromString).filter(uuid -> !uuid.equals(Uuid.ZERO_UUID)); Boolean useTopicId = inputTopicId.isPresent(); List<Uuid> topicIds; List<String> topics; if (useTopicId) { topicIds = getTopicIds(inputTopicId.get(), opts.excludeInternalTopics()); topics = Collections.emptyList(); } else { topicIds = Collections.emptyList(); topics = getTopics(opts.topic(), opts.excludeInternalTopics()); } // Only check topic name when topicId is not provided if (useTopicId) { ensureTopicIdExists(topicIds, inputTopicId.get(), !opts.ifExists()); } else { ensureTopicExists(topics, opts.topic(), !opts.ifExists()); } List<org.apache.kafka.clients.admin.TopicDescription> topicDescriptions = new ArrayList<>(); if (!topicIds.isEmpty()) { Map<Uuid, org.apache.kafka.clients.admin.TopicDescription> descTopics = adminClient.describeTopics(TopicCollection.ofTopicIds(topicIds)).allTopicIds().get(); topicDescriptions = new ArrayList<>(descTopics.values()); } if (!topics.isEmpty()) { Map<String, org.apache.kafka.clients.admin.TopicDescription> descTopics = adminClient.describeTopics(TopicCollection.ofTopicNames(topics), new DescribeTopicsOptions() .partitionSizeLimitPerResponse(opts.partitionSizeLimitPerResponse().orElse(2000))).allTopicNames().get(); topicDescriptions = new ArrayList<>(descTopics.values()); } List<String> topicNames = topicDescriptions.stream() .map(org.apache.kafka.clients.admin.TopicDescription::name) .collect(Collectors.toList()); Map<ConfigResource, KafkaFuture<Config>> allConfigs = adminClient.describeConfigs( topicNames.stream() .map(name -> new ConfigResource(ConfigResource.Type.TOPIC, name)) .collect(Collectors.toList()) ).values(); List<Integer> liveBrokers = adminClient.describeCluster().nodes().get().stream() .map(Node::id) .collect(Collectors.toList()); DescribeOptions describeOptions = new DescribeOptions(opts, new HashSet<>(liveBrokers)); Set<TopicPartition> topicPartitions = topicDescriptions .stream() .flatMap(td -> td.partitions().stream() .map(p -> new TopicPartition(td.name(), p.partition()))) .collect(Collectors.toSet()); Map<TopicPartition, PartitionReassignment> reassignments = listAllReassignments(topicPartitions); for (org.apache.kafka.clients.admin.TopicDescription td : topicDescriptions) { String topicName = td.name(); Uuid topicId = td.topicId(); Config config = allConfigs.get(new ConfigResource(ConfigResource.Type.TOPIC, topicName)).get(); ArrayList<TopicPartitionInfo> sortedPartitions = new ArrayList<>(td.partitions()); sortedPartitions.sort(Comparator.comparingInt(TopicPartitionInfo::partition)); printDescribeConfig(opts, describeOptions, reassignments, td, topicName, topicId, config, sortedPartitions); printPartitionDescription(describeOptions, reassignments, td, topicName, config, sortedPartitions); } } private void printPartitionDescription(DescribeOptions describeOptions, Map<TopicPartition, PartitionReassignment> reassignments, org.apache.kafka.clients.admin.TopicDescription td, String topicName, Config config, ArrayList<TopicPartitionInfo> sortedPartitions) { if (describeOptions.describePartitions) { for (TopicPartitionInfo partition : sortedPartitions) { PartitionReassignment reassignment = reassignments.get(new TopicPartition(td.name(), partition.partition())); PartitionDescription partitionDesc = new PartitionDescription(topicName, partition, config, false, reassignment); describeOptions.maybePrintPartitionDescription(partitionDesc); } } } private void printDescribeConfig(TopicCommandOptions opts, DescribeOptions describeOptions, Map<TopicPartition, PartitionReassignment> reassignments, org.apache.kafka.clients.admin.TopicDescription td, String topicName, Uuid topicId, Config config, ArrayList<TopicPartitionInfo> sortedPartitions) { if (describeOptions.describeConfigs) { List<ConfigEntry> entries = new ArrayList<>(config.entries()); boolean hasNonDefault = entries.stream().anyMatch(e -> !e.isDefault()); if (!opts.reportOverriddenConfigs() || hasNonDefault) { int numPartitions = td.partitions().size(); TopicPartitionInfo firstPartition = sortedPartitions.get(0); PartitionReassignment reassignment = reassignments.get(new TopicPartition(td.name(), firstPartition.partition())); TopicDescription topicDesc = new TopicDescription(topicName, topicId, numPartitions, getReplicationFactor(firstPartition, reassignment), config, false); topicDesc.printDescription(); } } } public void deleteTopic(TopicCommandOptions opts) throws ExecutionException, InterruptedException { List<String> topics = getTopics(opts.topic(), opts.excludeInternalTopics()); ensureTopicExists(topics, opts.topic(), !opts.ifExists()); adminClient.deleteTopics(Collections.unmodifiableList(topics), new DeleteTopicsOptions().retryOnQuotaViolation(false) ).all().get(); } public List<String> getTopics(Optional<String> topicIncludeList, boolean excludeInternalTopics) throws ExecutionException, InterruptedException { ListTopicsOptions listTopicsOptions = new ListTopicsOptions(); if (!excludeInternalTopics) { listTopicsOptions.listInternal(true); } Set<String> allTopics = adminClient.listTopics(listTopicsOptions).names().get(); return doGetTopics(allTopics.stream().sorted().collect(Collectors.toList()), topicIncludeList, excludeInternalTopics); } public List<Uuid> getTopicIds(Uuid topicIdIncludeList, boolean excludeInternalTopics) throws ExecutionException, InterruptedException { ListTopicsResult allTopics = excludeInternalTopics ? adminClient.listTopics() : adminClient.listTopics(new ListTopicsOptions().listInternal(true)); List<Uuid> allTopicIds = allTopics.listings().get().stream() .map(TopicListing::topicId) .sorted() .collect(Collectors.toList()); return allTopicIds.contains(topicIdIncludeList) ? Collections.singletonList(topicIdIncludeList) : Collections.emptyList(); } @Override public void close() throws Exception { adminClient.close(); } } public final static class TopicCommandOptions extends CommandDefaultOptions { private final ArgumentAcceptingOptionSpec<String> bootstrapServerOpt; private final ArgumentAcceptingOptionSpec<String> commandConfigOpt; private final OptionSpecBuilder listOpt; private final OptionSpecBuilder createOpt; private final OptionSpecBuilder deleteOpt; private final OptionSpecBuilder alterOpt; private final OptionSpecBuilder describeOpt; private final ArgumentAcceptingOptionSpec<String> topicOpt; private final ArgumentAcceptingOptionSpec<String> topicIdOpt; private final String nl; private static final String KAFKA_CONFIGS_CLI_SUPPORTS_ALTERING_TOPIC_CONFIGS_WITH_A_BOOTSTRAP_SERVER = " (the kafka-configs CLI supports altering topic configs with a --bootstrap-server option)"; private final ArgumentAcceptingOptionSpec<String> configOpt; private final ArgumentAcceptingOptionSpec<String> deleteConfigOpt; private final ArgumentAcceptingOptionSpec<Integer> partitionsOpt; private final ArgumentAcceptingOptionSpec<Integer> replicationFactorOpt; private final ArgumentAcceptingOptionSpec<String> replicaAssignmentOpt; private final OptionSpecBuilder reportUnderReplicatedPartitionsOpt; private final OptionSpecBuilder reportUnavailablePartitionsOpt; private final OptionSpecBuilder reportUnderMinIsrPartitionsOpt; private final OptionSpecBuilder reportAtMinIsrPartitionsOpt; private final OptionSpecBuilder topicsWithOverridesOpt; private final OptionSpecBuilder ifExistsOpt; private final OptionSpecBuilder ifNotExistsOpt; private final OptionSpecBuilder excludeInternalTopicOpt; private final ArgumentAcceptingOptionSpec<Integer> partitionSizeLimitPerResponseOpt; private final Set<OptionSpec<?>> allTopicLevelOpts; private final Set<OptionSpecBuilder> allReplicationReportOpts; public TopicCommandOptions(String[] args) { super(args); bootstrapServerOpt = parser.accepts("bootstrap-server", "REQUIRED: The Kafka server to connect to.") .withRequiredArg() .describedAs("server to connect to") .ofType(String.class); commandConfigOpt = parser.accepts("command-config", "Property file containing configs to be passed to Admin Client. " + "This is used only with --bootstrap-server option for describing and altering broker configs.") .withRequiredArg() .describedAs("command config property file") .ofType(String.class); String kafkaConfigsCanAlterTopicConfigsViaBootstrapServer = " (the kafka-configs CLI supports altering topic configs with a --bootstrap-server option)"; listOpt = parser.accepts("list", "List all available topics."); createOpt = parser.accepts("create", "Create a new topic."); deleteOpt = parser.accepts("delete", "Delete a topic"); alterOpt = parser.accepts("alter", "Alter the number of partitions and replica assignment. " + "Update the configuration of an existing topic via --alter is no longer supported here" + kafkaConfigsCanAlterTopicConfigsViaBootstrapServer + "."); describeOpt = parser.accepts("describe", "List details for the given topics."); topicOpt = parser.accepts("topic", "The topic to create, alter, describe or delete. It also accepts a regular " + "expression, except for --create option. Put topic name in double quotes and use the '\\' prefix " + "to escape regular expression symbols; e.g. \"test\\.topic\".") .withRequiredArg() .describedAs("topic") .ofType(String.class); topicIdOpt = parser.accepts("topic-id", "The topic-id to describe." + "This is used only with --bootstrap-server option for describing topics.") .withRequiredArg() .describedAs("topic-id") .ofType(String.class); nl = System.lineSeparator(); String logConfigNames = LogConfig.configNames().stream().map(config -> "\t" + config).collect(Collectors.joining(nl)); configOpt = parser.accepts("config", "A topic configuration override for the topic being created." + " The following is a list of valid configurations: " + nl + logConfigNames + nl + "See the Kafka documentation for full details on the topic configs." + " It is supported only in combination with --create if --bootstrap-server option is used" + kafkaConfigsCanAlterTopicConfigsViaBootstrapServer + ".") .withRequiredArg() .describedAs("name=value") .ofType(String.class); deleteConfigOpt = parser.accepts("delete-config", "A topic configuration override to be removed for an existing topic (see the list of configurations under the --config option). " + "Not supported with the --bootstrap-server option.") .withRequiredArg() .describedAs("name") .ofType(String.class); partitionsOpt = parser.accepts("partitions", "The number of partitions for the topic being created or " + "altered (WARNING: If partitions are increased for a topic that has a key, the partition logic or ordering of the messages will be affected). If not supplied for create, defaults to the cluster default.") .withRequiredArg() .describedAs("# of partitions") .ofType(java.lang.Integer.class); replicationFactorOpt = parser.accepts("replication-factor", "The replication factor for each partition in the topic being created. If not supplied, defaults to the cluster default.") .withRequiredArg() .describedAs("replication factor") .ofType(java.lang.Integer.class); replicaAssignmentOpt = parser.accepts("replica-assignment", "A list of manual partition-to-broker assignments for the topic being created or altered.") .withRequiredArg() .describedAs("broker_id_for_part1_replica1 : broker_id_for_part1_replica2 , " + "broker_id_for_part2_replica1 : broker_id_for_part2_replica2 , ...") .ofType(String.class); reportUnderReplicatedPartitionsOpt = parser.accepts("under-replicated-partitions", "if set when describing topics, only show under replicated partitions"); reportUnavailablePartitionsOpt = parser.accepts("unavailable-partitions", "if set when describing topics, only show partitions whose leader is not available"); reportUnderMinIsrPartitionsOpt = parser.accepts("under-min-isr-partitions", "if set when describing topics, only show partitions whose isr count is less than the configured minimum."); reportAtMinIsrPartitionsOpt = parser.accepts("at-min-isr-partitions", "if set when describing topics, only show partitions whose isr count is equal to the configured minimum."); topicsWithOverridesOpt = parser.accepts("topics-with-overrides", "if set when describing topics, only show topics that have overridden configs"); ifExistsOpt = parser.accepts("if-exists", "if set when altering or deleting or describing topics, the action will only execute if the topic exists."); ifNotExistsOpt = parser.accepts("if-not-exists", "if set when creating topics, the action will only execute if the topic does not already exist."); excludeInternalTopicOpt = parser.accepts("exclude-internal", "exclude internal topics when running list or describe command. The internal topics will be listed by default"); partitionSizeLimitPerResponseOpt = parser.accepts("partition-size-limit-per-response", "the maximum partition size to be included in one DescribeTopicPartitions response.") .withRequiredArg() .describedAs("maximum number of partitions in one response.") .ofType(java.lang.Integer.class); options = parser.parse(args); allTopicLevelOpts = new HashSet<>(Arrays.asList(alterOpt, createOpt, describeOpt, listOpt, deleteOpt)); allReplicationReportOpts = new HashSet<>(Arrays.asList(reportUnderReplicatedPartitionsOpt, reportUnderMinIsrPartitionsOpt, reportAtMinIsrPartitionsOpt, reportUnavailablePartitionsOpt)); checkArgs(); } public Boolean has(OptionSpec<?> builder) { return options.has(builder); } public <A> Optional<A> valueAsOption(OptionSpec<A> option) { return valueAsOption(option, Optional.empty()); } public <A> Optional<List<A>> valuesAsOption(OptionSpec<A> option) { return valuesAsOption(option, Collections.emptyList()); } public <A> Optional<A> valueAsOption(OptionSpec<A> option, Optional<A> defaultValue) { if (has(option)) { return Optional.of(options.valueOf(option)); } else { return defaultValue; } } public <A> Optional<List<A>> valuesAsOption(OptionSpec<A> option, List<A> defaultValue) { return options.has(option) ? Optional.of(options.valuesOf(option)) : Optional.of(defaultValue); } public Boolean hasCreateOption() { return has(createOpt); } public Boolean hasAlterOption() { return has(alterOpt); } public Boolean hasListOption() { return has(listOpt); } public Boolean hasDescribeOption() { return has(describeOpt); } public Boolean hasDeleteOption() { return has(deleteOpt); } public Optional<String> bootstrapServer() { return valueAsOption(bootstrapServerOpt); } public Properties commandConfig() throws IOException { if (has(commandConfigOpt)) { return Utils.loadProps(options.valueOf(commandConfigOpt)); } else { return new Properties(); } } public Optional<String> topic() { return valueAsOption(topicOpt); } public Optional<String> topicId() { return valueAsOption(topicIdOpt); } public Optional<Integer> partitions() { return valueAsOption(partitionsOpt); } public Optional<Integer> replicationFactor() { return valueAsOption(replicationFactorOpt); } public Optional<Map<Integer, List<Integer>>> replicaAssignment() { if (has(replicaAssignmentOpt) && !Optional.of(options.valueOf(replicaAssignmentOpt)).orElse("").isEmpty()) return Optional.of(parseReplicaAssignment(options.valueOf(replicaAssignmentOpt))); else return Optional.empty(); } public Boolean reportUnderReplicatedPartitions() { return has(reportUnderReplicatedPartitionsOpt); } public Boolean reportUnavailablePartitions() { return has(reportUnavailablePartitionsOpt); } public Boolean reportUnderMinIsrPartitions() { return has(reportUnderMinIsrPartitionsOpt); } public Boolean reportAtMinIsrPartitions() { return has(reportAtMinIsrPartitionsOpt); } public Boolean reportOverriddenConfigs() { return has(topicsWithOverridesOpt); } public Boolean ifExists() { return has(ifExistsOpt); } public Boolean ifNotExists() { return has(ifNotExistsOpt); } public Boolean excludeInternalTopics() { return has(excludeInternalTopicOpt); } public Optional<Integer> partitionSizeLimitPerResponse() { return valueAsOption(partitionSizeLimitPerResponseOpt); } public Optional<List<String>> topicConfig() { return valuesAsOption(configOpt); } public void checkArgs() { if (args.length == 0) CommandLineUtils.printUsageAndExit(parser, "Create, delete, describe, or change a topic."); CommandLineUtils.maybePrintHelpOrVersion(this, "This tool helps to create, delete, describe, or change a topic."); // should have exactly one action long actions = Arrays.asList(createOpt, listOpt, alterOpt, describeOpt, deleteOpt) .stream().filter(options::has) .count(); if (actions != 1) CommandLineUtils.printUsageAndExit(parser, "Command must include exactly one action: --list, --describe, --create, --alter or --delete"); checkRequiredArgs(); checkInvalidArgs(); } private void checkRequiredArgs() { // check required args if (!has(bootstrapServerOpt)) throw new IllegalArgumentException("--bootstrap-server must be specified"); if (has(describeOpt) && has(ifExistsOpt)) { if (!has(topicOpt) && !has(topicIdOpt)) CommandLineUtils.printUsageAndExit(parser, "--topic or --topic-id is required to describe a topic"); if (has(topicOpt) && has(topicIdOpt)) System.out.println("Only topic id will be used when both --topic and --topic-id are specified and topicId is not Uuid.ZERO_UUID"); } if (!has(listOpt) && !has(describeOpt)) CommandLineUtils.checkRequiredArgs(parser, options, topicOpt); if (has(alterOpt)) { Set<OptionSpec<?>> usedOptions = new HashSet<>(Arrays.asList(bootstrapServerOpt, configOpt)); Set<OptionSpec<?>> invalidOptions = new HashSet<>(Arrays.asList(alterOpt)); CommandLineUtils.checkInvalidArgsSet(parser, options, usedOptions, invalidOptions, Optional.of(KAFKA_CONFIGS_CLI_SUPPORTS_ALTERING_TOPIC_CONFIGS_WITH_A_BOOTSTRAP_SERVER)); CommandLineUtils.checkRequiredArgs(parser, options, partitionsOpt); } } private void checkInvalidArgs() { // check invalid args CommandLineUtils.checkInvalidArgs(parser, options, configOpt, invalidOptions(Arrays.asList(alterOpt, createOpt))); CommandLineUtils.checkInvalidArgs(parser, options, deleteConfigOpt, invalidOptions(new HashSet<>(Arrays.asList(bootstrapServerOpt)), Arrays.asList(alterOpt))); CommandLineUtils.checkInvalidArgs(parser, options, partitionsOpt, invalidOptions(Arrays.asList(alterOpt, createOpt))); CommandLineUtils.checkInvalidArgs(parser, options, replicationFactorOpt, invalidOptions(Arrays.asList(createOpt))); CommandLineUtils.checkInvalidArgs(parser, options, replicaAssignmentOpt, invalidOptions(Arrays.asList(alterOpt, createOpt))); if (options.has(createOpt)) { CommandLineUtils.checkInvalidArgs(parser, options, replicaAssignmentOpt, partitionsOpt, replicationFactorOpt); } CommandLineUtils.checkInvalidArgs(parser, options, reportUnderReplicatedPartitionsOpt, invalidOptions(Collections.singleton(topicsWithOverridesOpt), Arrays.asList(describeOpt, reportUnderReplicatedPartitionsOpt))); CommandLineUtils.checkInvalidArgs(parser, options, reportUnderMinIsrPartitionsOpt, invalidOptions(Collections.singleton(topicsWithOverridesOpt), Arrays.asList(describeOpt, reportUnderMinIsrPartitionsOpt))); CommandLineUtils.checkInvalidArgs(parser, options, reportAtMinIsrPartitionsOpt, invalidOptions(Collections.singleton(topicsWithOverridesOpt), Arrays.asList(describeOpt, reportAtMinIsrPartitionsOpt))); CommandLineUtils.checkInvalidArgs(parser, options, reportUnavailablePartitionsOpt, invalidOptions(Collections.singleton(topicsWithOverridesOpt), Arrays.asList(describeOpt, reportUnavailablePartitionsOpt))); CommandLineUtils.checkInvalidArgs(parser, options, topicsWithOverridesOpt, invalidOptions(new HashSet<>(allReplicationReportOpts), Arrays.asList(describeOpt))); CommandLineUtils.checkInvalidArgs(parser, options, ifExistsOpt, invalidOptions(Arrays.asList(alterOpt, deleteOpt, describeOpt))); CommandLineUtils.checkInvalidArgs(parser, options, ifNotExistsOpt, invalidOptions(Arrays.asList(createOpt))); CommandLineUtils.checkInvalidArgs(parser, options, excludeInternalTopicOpt, invalidOptions(Arrays.asList(listOpt, describeOpt))); } private Set<OptionSpec<?>> invalidOptions(List<OptionSpec<?>> removeOptions) { return invalidOptions(new HashSet<>(), removeOptions); } private LinkedHashSet<OptionSpec<?>> invalidOptions(Set<OptionSpec<?>> addOptions, List<OptionSpec<?>> removeOptions) { LinkedHashSet<OptionSpec<?>> finalOptions = new LinkedHashSet<>(allTopicLevelOpts); finalOptions.removeAll(removeOptions); finalOptions.addAll(addOptions); return finalOptions; } } }
apache/kafka
tools/src/main/java/org/apache/kafka/tools/TopicCommand.java
44,930
/* * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.jms.core; import io.micrometer.jakarta9.instrument.jms.JmsInstrumentation; import io.micrometer.observation.ObservationRegistry; import jakarta.jms.Connection; import jakarta.jms.ConnectionFactory; import jakarta.jms.DeliveryMode; import jakarta.jms.Destination; import jakarta.jms.JMSException; import jakarta.jms.Message; import jakarta.jms.MessageConsumer; import jakarta.jms.MessageProducer; import jakarta.jms.Queue; import jakarta.jms.QueueBrowser; import jakarta.jms.Session; import jakarta.jms.TemporaryQueue; import org.springframework.jms.JmsException; import org.springframework.jms.connection.ConnectionFactoryUtils; import org.springframework.jms.connection.JmsResourceHolder; import org.springframework.jms.support.JmsUtils; import org.springframework.jms.support.QosSettings; import org.springframework.jms.support.converter.MessageConverter; import org.springframework.jms.support.converter.SimpleMessageConverter; import org.springframework.jms.support.destination.JmsDestinationAccessor; import org.springframework.lang.Nullable; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; /** * Helper class that simplifies synchronous JMS access code. * * <p>If you want to use dynamic destination creation, you must specify * the type of JMS destination to create, using the "pubSubDomain" property. * For other operations, this is not necessary. Point-to-Point (Queues) is the default * domain. * * <p>Default settings for JMS Sessions are "not transacted" and "auto-acknowledge". * As defined by the Jakarta EE specification, the transaction and acknowledgement * parameters are ignored when a JMS Session is created inside an active * transaction, no matter if a JTA transaction or a Spring-managed transaction. * To configure them for native JMS usage, specify appropriate values for * the "sessionTransacted" and "sessionAcknowledgeMode" bean properties. * * <p>This template uses a * {@link org.springframework.jms.support.destination.DynamicDestinationResolver} * and a {@link org.springframework.jms.support.converter.SimpleMessageConverter} * as default strategies for resolving a destination name or converting a message, * respectively. These defaults can be overridden through the "destinationResolver" * and "messageConverter" bean properties. * * <p><b>NOTE: The {@code ConnectionFactory} used with this template should * return pooled Connections (or a single shared Connection) as well as pooled * Sessions and MessageProducers. Otherwise, performance of ad-hoc JMS operations * is going to suffer.</b> The simplest option is to use the Spring-provided * {@link org.springframework.jms.connection.SingleConnectionFactory} as a * decorator for your target {@code ConnectionFactory}, reusing a single * JMS Connection in a thread-safe fashion; this is often good enough for the * purpose of sending messages via this template. In a Jakarta EE environment, * make sure that the {@code ConnectionFactory} is obtained from the * application's environment naming context via JNDI; application servers * typically expose pooled, transaction-aware factories there. * * @author Mark Pollack * @author Juergen Hoeller * @author Stephane Nicoll * @author Brian Clozel * @since 1.1 * @see #setConnectionFactory * @see #setPubSubDomain * @see #setDestinationResolver * @see #setMessageConverter * @see jakarta.jms.MessageProducer * @see jakarta.jms.MessageConsumer */ public class JmsTemplate extends JmsDestinationAccessor implements JmsOperations { private static final boolean micrometerJakartaPresent = ClassUtils.isPresent( "io.micrometer.jakarta9.instrument.jms.JmsInstrumentation", JmsTemplate.class.getClassLoader()); /** Internal ResourceFactory adapter for interacting with ConnectionFactoryUtils. */ private final JmsTemplateResourceFactory transactionalResourceFactory = new JmsTemplateResourceFactory(); @Nullable private Object defaultDestination; @Nullable private MessageConverter messageConverter; private boolean messageIdEnabled = true; private boolean messageTimestampEnabled = true; private boolean pubSubNoLocal = false; private long receiveTimeout = RECEIVE_TIMEOUT_INDEFINITE_WAIT; private long deliveryDelay = -1; private boolean explicitQosEnabled = false; private int deliveryMode = Message.DEFAULT_DELIVERY_MODE; private int priority = Message.DEFAULT_PRIORITY; private long timeToLive = Message.DEFAULT_TIME_TO_LIVE; @Nullable private ObservationRegistry observationRegistry; /** * Create a new JmsTemplate for bean-style usage. * <p>Note: The ConnectionFactory has to be set before using the instance. * This constructor can be used to prepare a JmsTemplate via a BeanFactory, * typically setting the ConnectionFactory via setConnectionFactory. * @see #setConnectionFactory */ public JmsTemplate() { initDefaultStrategies(); } /** * Create a new JmsTemplate, given a ConnectionFactory. * @param connectionFactory the ConnectionFactory to obtain Connections from */ public JmsTemplate(ConnectionFactory connectionFactory) { this(); setConnectionFactory(connectionFactory); afterPropertiesSet(); } /** * Initialize the default implementations for the template's strategies: * DynamicDestinationResolver and SimpleMessageConverter. * @see #setDestinationResolver * @see #setMessageConverter * @see org.springframework.jms.support.destination.DynamicDestinationResolver * @see org.springframework.jms.support.converter.SimpleMessageConverter */ protected void initDefaultStrategies() { setMessageConverter(new SimpleMessageConverter()); } /** * Set the destination to be used on send/receive operations that do not * have a destination parameter. * <p>Alternatively, specify a "defaultDestinationName", to be * dynamically resolved via the DestinationResolver. * @see #send(MessageCreator) * @see #convertAndSend(Object) * @see #convertAndSend(Object, MessagePostProcessor) * @see #setDefaultDestinationName(String) */ public void setDefaultDestination(@Nullable Destination destination) { this.defaultDestination = destination; } /** * Return the destination to be used on send/receive operations that do not * have a destination parameter. */ @Nullable public Destination getDefaultDestination() { return (this.defaultDestination instanceof Destination dest ? dest : null); } @Nullable private Queue getDefaultQueue() { Destination defaultDestination = getDefaultDestination(); if (defaultDestination == null) { return null; } if (!(defaultDestination instanceof Queue queue)) { throw new IllegalStateException( "'defaultDestination' does not correspond to a Queue. Check configuration of JmsTemplate."); } return queue; } /** * Set the destination name to be used on send/receive operations that * do not have a destination parameter. The specified name will be * dynamically resolved via the DestinationResolver. * <p>Alternatively, specify a JMS Destination object as "defaultDestination". * @see #send(MessageCreator) * @see #convertAndSend(Object) * @see #convertAndSend(Object, MessagePostProcessor) * @see #setDestinationResolver * @see #setDefaultDestination(jakarta.jms.Destination) */ public void setDefaultDestinationName(@Nullable String destinationName) { this.defaultDestination = destinationName; } /** * Return the destination name to be used on send/receive operations that * do not have a destination parameter. */ @Nullable public String getDefaultDestinationName() { return (this.defaultDestination instanceof String name ? name : null); } private String getRequiredDefaultDestinationName() throws IllegalStateException { String name = getDefaultDestinationName(); if (name == null) { throw new IllegalStateException( "No 'defaultDestination' or 'defaultDestinationName' specified. Check configuration of JmsTemplate."); } return name; } /** * Set the message converter for this template. Used to resolve * Object parameters to convertAndSend methods and Object results * from receiveAndConvert methods. * <p>The default converter is a SimpleMessageConverter, which is able * to handle BytesMessages, TextMessages and ObjectMessages. * @see #convertAndSend * @see #receiveAndConvert * @see org.springframework.jms.support.converter.SimpleMessageConverter */ public void setMessageConverter(@Nullable MessageConverter messageConverter) { this.messageConverter = messageConverter; } /** * Return the message converter for this template. */ @Nullable public MessageConverter getMessageConverter() { return this.messageConverter; } private MessageConverter getRequiredMessageConverter() throws IllegalStateException { MessageConverter converter = getMessageConverter(); if (converter == null) { throw new IllegalStateException("No 'messageConverter' specified. Check configuration of JmsTemplate."); } return converter; } /** * Set whether message IDs are enabled. Default is "true". * <p>This is only a hint to the JMS producer. * See the JMS javadocs for details. * @see jakarta.jms.MessageProducer#setDisableMessageID */ public void setMessageIdEnabled(boolean messageIdEnabled) { this.messageIdEnabled = messageIdEnabled; } /** * Return whether message IDs are enabled. */ public boolean isMessageIdEnabled() { return this.messageIdEnabled; } /** * Set whether message timestamps are enabled. Default is "true". * <p>This is only a hint to the JMS producer. * See the JMS javadocs for details. * @see jakarta.jms.MessageProducer#setDisableMessageTimestamp */ public void setMessageTimestampEnabled(boolean messageTimestampEnabled) { this.messageTimestampEnabled = messageTimestampEnabled; } /** * Return whether message timestamps are enabled. */ public boolean isMessageTimestampEnabled() { return this.messageTimestampEnabled; } /** * Set whether to inhibit the delivery of messages published by its own connection. * Default is "false". * @see jakarta.jms.Session#createConsumer(jakarta.jms.Destination, String, boolean) */ public void setPubSubNoLocal(boolean pubSubNoLocal) { this.pubSubNoLocal = pubSubNoLocal; } /** * Return whether to inhibit the delivery of messages published by its own connection. */ public boolean isPubSubNoLocal() { return this.pubSubNoLocal; } /** * Set the timeout to use for receive calls (in milliseconds). * <p>The default is {@link #RECEIVE_TIMEOUT_INDEFINITE_WAIT}, which indicates * a blocking receive without timeout. * <p>Specify {@link #RECEIVE_TIMEOUT_NO_WAIT} (or any other negative value) * to indicate that a receive operation should check if a message is * immediately available without blocking. * @see #receiveFromConsumer(MessageConsumer, long) * @see jakarta.jms.MessageConsumer#receive(long) * @see jakarta.jms.MessageConsumer#receiveNoWait() * @see jakarta.jms.MessageConsumer#receive() */ public void setReceiveTimeout(long receiveTimeout) { this.receiveTimeout = receiveTimeout; } /** * Return the timeout to use for receive calls (in milliseconds). */ public long getReceiveTimeout() { return this.receiveTimeout; } /** * Set the delivery delay to use for send calls (in milliseconds). * <p>The default is -1 (no delivery delay passed on to the broker). * Note that this feature requires JMS 2.0. */ public void setDeliveryDelay(long deliveryDelay) { this.deliveryDelay = deliveryDelay; } /** * Return the delivery delay to use for send calls (in milliseconds). */ public long getDeliveryDelay() { return this.deliveryDelay; } /** * Set if the QOS values (deliveryMode, priority, timeToLive) * should be used for sending a message. * @see #setDeliveryMode * @see #setPriority * @see #setTimeToLive */ public void setExplicitQosEnabled(boolean explicitQosEnabled) { this.explicitQosEnabled = explicitQosEnabled; } /** * If "true", then the values of deliveryMode, priority, and timeToLive * will be used when sending a message. Otherwise, the default values, * that may be set administratively, will be used. * @return true if overriding default values of QOS parameters * (deliveryMode, priority, and timeToLive) * @see #setDeliveryMode * @see #setPriority * @see #setTimeToLive */ public boolean isExplicitQosEnabled() { return this.explicitQosEnabled; } /** * Set the {@link QosSettings} to use when sending a message. * @param settings the deliveryMode, priority, and timeToLive settings to use * @since 5.0 * @see #setExplicitQosEnabled(boolean) * @see #setDeliveryMode(int) * @see #setPriority(int) * @see #setTimeToLive(long) */ public void setQosSettings(QosSettings settings) { Assert.notNull(settings, "Settings must not be null"); setExplicitQosEnabled(true); setDeliveryMode(settings.getDeliveryMode()); setPriority(settings.getPriority()); setTimeToLive(settings.getTimeToLive()); } /** * Set whether message delivery should be persistent or non-persistent, * specified as boolean value ("true" or "false"). This will set the delivery * mode accordingly, to either "PERSISTENT" (2) or "NON_PERSISTENT" (1). * <p>Default is "true" a.k.a. delivery mode "PERSISTENT". * @see #setDeliveryMode(int) * @see jakarta.jms.DeliveryMode#PERSISTENT * @see jakarta.jms.DeliveryMode#NON_PERSISTENT */ public void setDeliveryPersistent(boolean deliveryPersistent) { this.deliveryMode = (deliveryPersistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT); } /** * Set the delivery mode to use when sending a message. * Default is the JMS Message default: "PERSISTENT". * <p>Since a default value may be defined administratively, * this is only used when "isExplicitQosEnabled" equals "true". * @param deliveryMode the delivery mode to use * @see #isExplicitQosEnabled * @see jakarta.jms.DeliveryMode#PERSISTENT * @see jakarta.jms.DeliveryMode#NON_PERSISTENT * @see jakarta.jms.Message#DEFAULT_DELIVERY_MODE * @see jakarta.jms.MessageProducer#send(jakarta.jms.Message, int, int, long) */ public void setDeliveryMode(int deliveryMode) { this.deliveryMode = deliveryMode; } /** * Return the delivery mode to use when sending a message. */ public int getDeliveryMode() { return this.deliveryMode; } /** * Set the priority of a message when sending. * <p>Since a default value may be defined administratively, * this is only used when "isExplicitQosEnabled" equals "true". * @see #isExplicitQosEnabled * @see jakarta.jms.Message#DEFAULT_PRIORITY * @see jakarta.jms.MessageProducer#send(jakarta.jms.Message, int, int, long) */ public void setPriority(int priority) { this.priority = priority; } /** * Return the priority of a message when sending. */ public int getPriority() { return this.priority; } /** * Set the time-to-live of the message when sending. * <p>Since a default value may be defined administratively, * this is only used when "isExplicitQosEnabled" equals "true". * @param timeToLive the message's lifetime (in milliseconds) * @see #isExplicitQosEnabled * @see jakarta.jms.Message#DEFAULT_TIME_TO_LIVE * @see jakarta.jms.MessageProducer#send(jakarta.jms.Message, int, int, long) */ public void setTimeToLive(long timeToLive) { this.timeToLive = timeToLive; } /** * Return the time-to-live of the message when sending. */ public long getTimeToLive() { return this.timeToLive; } /** * Configure the {@link ObservationRegistry} to use for recording JMS observations. * @param observationRegistry the observation registry to use. * @since 6.1 * @see io.micrometer.jakarta9.instrument.jms.JmsInstrumentation */ public void setObservationRegistry(ObservationRegistry observationRegistry) { this.observationRegistry = observationRegistry; } //--------------------------------------------------------------------------------------- // JmsOperations execute methods //--------------------------------------------------------------------------------------- @Override @Nullable public <T> T execute(SessionCallback<T> action) throws JmsException { return execute(action, false); } /** * Execute the action specified by the given action object within a * JMS Session. Generalized version of {@code execute(SessionCallback)}, * allowing the JMS Connection to be started on the fly. * <p>Use {@code execute(SessionCallback)} for the general case. * Starting the JMS Connection is just necessary for receiving messages, * which is preferably achieved through the {@code receive} methods. * @param action callback object that exposes the Session * @param startConnection whether to start the Connection * @return the result object from working with the Session * @throws JmsException if there is any problem * @see #execute(SessionCallback) * @see #receive */ @SuppressWarnings("resource") @Nullable public <T> T execute(SessionCallback<T> action, boolean startConnection) throws JmsException { Assert.notNull(action, "Callback object must not be null"); Connection conToClose = null; Session sessionToClose = null; try { Session sessionToUse = ConnectionFactoryUtils.doGetTransactionalSession( obtainConnectionFactory(), this.transactionalResourceFactory, startConnection); if (sessionToUse == null) { conToClose = createConnection(); sessionToClose = createSession(conToClose); if (startConnection) { conToClose.start(); } sessionToUse = sessionToClose; } if (logger.isDebugEnabled()) { logger.debug("Executing callback on JMS Session: " + sessionToUse); } if (micrometerJakartaPresent && this.observationRegistry != null) { sessionToUse = MicrometerInstrumentation.instrumentSession(sessionToUse, this.observationRegistry); } return action.doInJms(sessionToUse); } catch (JMSException ex) { throw convertJmsAccessException(ex); } finally { JmsUtils.closeSession(sessionToClose); ConnectionFactoryUtils.releaseConnection(conToClose, getConnectionFactory(), startConnection); } } @Override @Nullable public <T> T execute(ProducerCallback<T> action) throws JmsException { String defaultDestinationName = getDefaultDestinationName(); if (defaultDestinationName != null) { return execute(defaultDestinationName, action); } else { return execute(getDefaultDestination(), action); } } @Override @Nullable public <T> T execute(final @Nullable Destination destination, final ProducerCallback<T> action) throws JmsException { Assert.notNull(action, "Callback object must not be null"); return execute(session -> { MessageProducer producer = createProducer(session, destination); try { return action.doInJms(session, producer); } finally { JmsUtils.closeMessageProducer(producer); } }, false); } @Override @Nullable public <T> T execute(final String destinationName, final ProducerCallback<T> action) throws JmsException { Assert.notNull(action, "Callback object must not be null"); return execute(session -> { Destination destination = resolveDestinationName(session, destinationName); MessageProducer producer = createProducer(session, destination); try { return action.doInJms(session, producer); } finally { JmsUtils.closeMessageProducer(producer); } }, false); } //--------------------------------------------------------------------------------------- // Convenience methods for sending messages //--------------------------------------------------------------------------------------- @Override public void send(MessageCreator messageCreator) throws JmsException { Destination defaultDestination = getDefaultDestination(); if (defaultDestination != null) { send(defaultDestination, messageCreator); } else { send(getRequiredDefaultDestinationName(), messageCreator); } } @Override public void send(final Destination destination, final MessageCreator messageCreator) throws JmsException { execute(session -> { doSend(session, destination, messageCreator); return null; }, false); } @Override public void send(final String destinationName, final MessageCreator messageCreator) throws JmsException { execute(session -> { Destination destination = resolveDestinationName(session, destinationName); doSend(session, destination, messageCreator); return null; }, false); } /** * Send the given JMS message. * @param session the JMS Session to operate on * @param destination the JMS Destination to send to * @param messageCreator callback to create a JMS Message * @throws JMSException if thrown by JMS API methods */ protected void doSend(Session session, Destination destination, MessageCreator messageCreator) throws JMSException { Assert.notNull(messageCreator, "MessageCreator must not be null"); MessageProducer producer = createProducer(session, destination); try { Message message = messageCreator.createMessage(session); if (logger.isDebugEnabled()) { logger.debug("Sending created message: " + message); } doSend(producer, message); // Check commit - avoid commit call within a JTA transaction. if (session.getTransacted() && isSessionLocallyTransacted(session)) { // Transacted session created by this template -> commit. JmsUtils.commitIfNecessary(session); } } finally { JmsUtils.closeMessageProducer(producer); } } /** * Actually send the given JMS message. * @param producer the JMS MessageProducer to send with * @param message the JMS Message to send * @throws JMSException if thrown by JMS API methods */ protected void doSend(MessageProducer producer, Message message) throws JMSException { if (this.deliveryDelay >= 0) { producer.setDeliveryDelay(this.deliveryDelay); } if (isExplicitQosEnabled()) { producer.send(message, getDeliveryMode(), getPriority(), getTimeToLive()); } else { producer.send(message); } } //--------------------------------------------------------------------------------------- // Convenience methods for sending auto-converted messages //--------------------------------------------------------------------------------------- @Override public void convertAndSend(Object message) throws JmsException { Destination defaultDestination = getDefaultDestination(); if (defaultDestination != null) { convertAndSend(defaultDestination, message); } else { convertAndSend(getRequiredDefaultDestinationName(), message); } } @Override public void convertAndSend(Destination destination, final Object message) throws JmsException { send(destination, session -> getRequiredMessageConverter().toMessage(message, session)); } @Override public void convertAndSend(String destinationName, final Object message) throws JmsException { send(destinationName, session -> getRequiredMessageConverter().toMessage(message, session)); } @Override public void convertAndSend(Object message, MessagePostProcessor postProcessor) throws JmsException { Destination defaultDestination = getDefaultDestination(); if (defaultDestination != null) { convertAndSend(defaultDestination, message, postProcessor); } else { convertAndSend(getRequiredDefaultDestinationName(), message, postProcessor); } } @Override public void convertAndSend( Destination destination, final Object message, final MessagePostProcessor postProcessor) throws JmsException { send(destination, session -> { Message msg = getRequiredMessageConverter().toMessage(message, session); return postProcessor.postProcessMessage(msg); }); } @Override public void convertAndSend( String destinationName, final Object message, final MessagePostProcessor postProcessor) throws JmsException { send(destinationName, session -> { Message msg = getRequiredMessageConverter().toMessage(message, session); return postProcessor.postProcessMessage(msg); }); } //--------------------------------------------------------------------------------------- // Convenience methods for receiving messages //--------------------------------------------------------------------------------------- @Override @Nullable public Message receive() throws JmsException { Destination defaultDestination = getDefaultDestination(); if (defaultDestination != null) { return receive(defaultDestination); } else { return receive(getRequiredDefaultDestinationName()); } } @Override @Nullable public Message receive(Destination destination) throws JmsException { return receiveSelected(destination, null); } @Override @Nullable public Message receive(String destinationName) throws JmsException { return receiveSelected(destinationName, null); } @Override @Nullable public Message receiveSelected(String messageSelector) throws JmsException { Destination defaultDestination = getDefaultDestination(); if (defaultDestination != null) { return receiveSelected(defaultDestination, messageSelector); } else { return receiveSelected(getRequiredDefaultDestinationName(), messageSelector); } } @Override @Nullable public Message receiveSelected(final Destination destination, @Nullable final String messageSelector) throws JmsException { return execute(session -> doReceive(session, destination, messageSelector), true); } @Override @Nullable public Message receiveSelected(final String destinationName, @Nullable final String messageSelector) throws JmsException { return execute(session -> { Destination destination = resolveDestinationName(session, destinationName); return doReceive(session, destination, messageSelector); }, true); } /** * Receive a JMS message. * @param session the JMS Session to operate on * @param destination the JMS Destination to receive from * @param messageSelector the message selector for this consumer (can be {@code null}) * @return the JMS Message received, or {@code null} if none * @throws JMSException if thrown by JMS API methods */ @Nullable protected Message doReceive(Session session, Destination destination, @Nullable String messageSelector) throws JMSException { return doReceive(session, createConsumer(session, destination, messageSelector)); } /** * Actually receive a JMS message. * @param session the JMS Session to operate on * @param consumer the JMS MessageConsumer to receive with * @return the JMS Message received, or {@code null} if none * @throws JMSException if thrown by JMS API methods */ @Nullable protected Message doReceive(Session session, MessageConsumer consumer) throws JMSException { try { // Use transaction timeout (if available). long timeout = getReceiveTimeout(); ConnectionFactory connectionFactory = getConnectionFactory(); JmsResourceHolder resourceHolder = null; if (connectionFactory != null) { resourceHolder = (JmsResourceHolder) TransactionSynchronizationManager.getResource(connectionFactory); } if (resourceHolder != null && resourceHolder.hasTimeout()) { timeout = Math.min(timeout, resourceHolder.getTimeToLiveInMillis()); } Message message = receiveFromConsumer(consumer, timeout); if (session.getTransacted()) { // Commit necessary - but avoid commit call within a JTA transaction. if (isSessionLocallyTransacted(session)) { // Transacted session created by this template -> commit. JmsUtils.commitIfNecessary(session); } } else if (isClientAcknowledge(session)) { // Manually acknowledge message, if any. if (message != null) { message.acknowledge(); } } return message; } finally { JmsUtils.closeMessageConsumer(consumer); } } //--------------------------------------------------------------------------------------- // Convenience methods for receiving auto-converted messages //--------------------------------------------------------------------------------------- @Override @Nullable public Object receiveAndConvert() throws JmsException { return doConvertFromMessage(receive()); } @Override @Nullable public Object receiveAndConvert(Destination destination) throws JmsException { return doConvertFromMessage(receive(destination)); } @Override @Nullable public Object receiveAndConvert(String destinationName) throws JmsException { return doConvertFromMessage(receive(destinationName)); } @Override @Nullable public Object receiveSelectedAndConvert(String messageSelector) throws JmsException { return doConvertFromMessage(receiveSelected(messageSelector)); } @Override @Nullable public Object receiveSelectedAndConvert(Destination destination, String messageSelector) throws JmsException { return doConvertFromMessage(receiveSelected(destination, messageSelector)); } @Override @Nullable public Object receiveSelectedAndConvert(String destinationName, String messageSelector) throws JmsException { return doConvertFromMessage(receiveSelected(destinationName, messageSelector)); } /** * Extract the content from the given JMS message. * @param message the JMS Message to convert (can be {@code null}) * @return the content of the message, or {@code null} if none */ @Nullable protected Object doConvertFromMessage(@Nullable Message message) { if (message != null) { try { return getRequiredMessageConverter().fromMessage(message); } catch (JMSException ex) { throw convertJmsAccessException(ex); } } return null; } //--------------------------------------------------------------------------------------- // Convenience methods for sending messages to and receiving the reply from a destination //--------------------------------------------------------------------------------------- @Override @Nullable public Message sendAndReceive(MessageCreator messageCreator) throws JmsException { Destination defaultDestination = getDefaultDestination(); if (defaultDestination != null) { return sendAndReceive(defaultDestination, messageCreator); } else { return sendAndReceive(getRequiredDefaultDestinationName(), messageCreator); } } @Override @Nullable public Message sendAndReceive(final Destination destination, final MessageCreator messageCreator) throws JmsException { return executeLocal(session -> doSendAndReceive(session, destination, messageCreator), true); } @Override @Nullable public Message sendAndReceive(final String destinationName, final MessageCreator messageCreator) throws JmsException { return executeLocal(session -> { Destination destination = resolveDestinationName(session, destinationName); return doSendAndReceive(session, destination, messageCreator); }, true); } /** * Send a request message to the given {@link Destination} and block until * a reply has been received on a temporary queue created on-the-fly. * <p>Return the response message or {@code null} if no message has * @throws JMSException if thrown by JMS API methods */ @Nullable protected Message doSendAndReceive(Session session, Destination destination, MessageCreator messageCreator) throws JMSException { Assert.notNull(messageCreator, "MessageCreator must not be null"); TemporaryQueue responseQueue = null; MessageProducer producer = null; MessageConsumer consumer = null; try { Message requestMessage = messageCreator.createMessage(session); responseQueue = session.createTemporaryQueue(); producer = session.createProducer(destination); consumer = session.createConsumer(responseQueue); requestMessage.setJMSReplyTo(responseQueue); if (logger.isDebugEnabled()) { logger.debug("Sending created message: " + requestMessage); } doSend(producer, requestMessage); return receiveFromConsumer(consumer, getReceiveTimeout()); } finally { JmsUtils.closeMessageConsumer(consumer); JmsUtils.closeMessageProducer(producer); if (responseQueue != null) { responseQueue.delete(); } } } /** * A variant of {@link #execute(SessionCallback, boolean)} that explicitly * creates a non-transactional {@link Session}. The given {@link SessionCallback} * does not participate in an existing transaction. */ @Nullable private <T> T executeLocal(SessionCallback<T> action, boolean startConnection) throws JmsException { Assert.notNull(action, "Callback object must not be null"); Connection con = null; Session session = null; try { con = createConnection(); session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); if (micrometerJakartaPresent && this.observationRegistry != null) { session = MicrometerInstrumentation.instrumentSession(session, this.observationRegistry); } if (startConnection) { con.start(); } if (logger.isDebugEnabled()) { logger.debug("Executing callback on JMS Session: " + session); } return action.doInJms(session); } catch (JMSException ex) { throw convertJmsAccessException(ex); } finally { JmsUtils.closeSession(session); ConnectionFactoryUtils.releaseConnection(con, getConnectionFactory(), startConnection); } } //--------------------------------------------------------------------------------------- // Convenience methods for browsing messages //--------------------------------------------------------------------------------------- @Override @Nullable public <T> T browse(BrowserCallback<T> action) throws JmsException { Queue defaultQueue = getDefaultQueue(); if (defaultQueue != null) { return browse(defaultQueue, action); } else { return browse(getRequiredDefaultDestinationName(), action); } } @Override @Nullable public <T> T browse(Queue queue, BrowserCallback<T> action) throws JmsException { return browseSelected(queue, null, action); } @Override @Nullable public <T> T browse(String queueName, BrowserCallback<T> action) throws JmsException { return browseSelected(queueName, null, action); } @Override @Nullable public <T> T browseSelected(String messageSelector, BrowserCallback<T> action) throws JmsException { Queue defaultQueue = getDefaultQueue(); if (defaultQueue != null) { return browseSelected(defaultQueue, messageSelector, action); } else { return browseSelected(getRequiredDefaultDestinationName(), messageSelector, action); } } @Override @Nullable public <T> T browseSelected(final Queue queue, @Nullable final String messageSelector, final BrowserCallback<T> action) throws JmsException { Assert.notNull(action, "Callback object must not be null"); return execute(session -> { QueueBrowser browser = createBrowser(session, queue, messageSelector); try { return action.doInJms(session, browser); } finally { JmsUtils.closeQueueBrowser(browser); } }, true); } @Override @Nullable public <T> T browseSelected(final String queueName, @Nullable final String messageSelector, final BrowserCallback<T> action) throws JmsException { Assert.notNull(action, "Callback object must not be null"); return execute(session -> { Queue queue = (Queue) getDestinationResolver().resolveDestinationName(session, queueName, false); QueueBrowser browser = createBrowser(session, queue, messageSelector); try { return action.doInJms(session, browser); } finally { JmsUtils.closeQueueBrowser(browser); } }, true); } /** * Fetch an appropriate Connection from the given JmsResourceHolder. * <p>This implementation accepts any JMS 1.1 Connection. * @param holder the JmsResourceHolder * @return an appropriate Connection fetched from the holder, * or {@code null} if none found */ @Nullable protected Connection getConnection(JmsResourceHolder holder) { return holder.getConnection(); } /** * Fetch an appropriate Session from the given JmsResourceHolder. * <p>This implementation accepts any JMS 1.1 Session. * @param holder the JmsResourceHolder * @return an appropriate Session fetched from the holder, * or {@code null} if none found */ @Nullable protected Session getSession(JmsResourceHolder holder) { return holder.getSession(); } /** * Check whether the given Session is locally transacted, that is, whether * its transaction is managed by this listener container's Session handling * and not by an external transaction coordinator. * <p>Note: The Session's own transacted flag will already have been checked * before. This method is about finding out whether the Session's transaction * is local or externally coordinated. * @param session the Session to check * @return whether the given Session is locally transacted * @see #isSessionTransacted() * @see org.springframework.jms.connection.ConnectionFactoryUtils#isSessionTransactional */ protected boolean isSessionLocallyTransacted(Session session) { return isSessionTransacted() && !ConnectionFactoryUtils.isSessionTransactional(session, getConnectionFactory()); } /** * Create a JMS MessageProducer for the given Session and Destination, * configuring it to disable message ids and/or timestamps (if necessary). * <p>Delegates to {@link #doCreateProducer} for creation of the raw * JMS MessageProducer. * @param session the JMS Session to create a MessageProducer for * @param destination the JMS Destination to create a MessageProducer for * @return the new JMS MessageProducer * @throws JMSException if thrown by JMS API methods * @see #setMessageIdEnabled * @see #setMessageTimestampEnabled */ protected MessageProducer createProducer(Session session, @Nullable Destination destination) throws JMSException { MessageProducer producer = doCreateProducer(session, destination); if (!isMessageIdEnabled()) { producer.setDisableMessageID(true); } if (!isMessageTimestampEnabled()) { producer.setDisableMessageTimestamp(true); } return producer; } /** * Create a raw JMS MessageProducer for the given Session and Destination. * <p>This implementation uses JMS 1.1 API. * @param session the JMS Session to create a MessageProducer for * @param destination the JMS Destination to create a MessageProducer for * @return the new JMS MessageProducer * @throws JMSException if thrown by JMS API methods */ protected MessageProducer doCreateProducer(Session session, @Nullable Destination destination) throws JMSException { return session.createProducer(destination); } /** * Create a JMS MessageConsumer for the given Session and Destination. * <p>This implementation uses JMS 1.1 API. * @param session the JMS Session to create a MessageConsumer for * @param destination the JMS Destination to create a MessageConsumer for * @param messageSelector the message selector for this consumer (can be {@code null}) * @return the new JMS MessageConsumer * @throws JMSException if thrown by JMS API methods */ protected MessageConsumer createConsumer(Session session, Destination destination, @Nullable String messageSelector) throws JMSException { // Only pass in the NoLocal flag in case of a Topic: // Some JMS providers, such as WebSphere MQ 6.0, throw IllegalStateException // in case of the NoLocal flag being specified for a Queue. if (isPubSubDomain()) { return session.createConsumer(destination, messageSelector, isPubSubNoLocal()); } else { return session.createConsumer(destination, messageSelector); } } /** * Create a JMS MessageProducer for the given Session and Destination, * configuring it to disable message ids and/or timestamps (if necessary). * <p>Delegates to {@link #doCreateProducer} for creation of the raw * JMS MessageProducer. * @param session the JMS Session to create a QueueBrowser for * @param queue the JMS Queue to create a QueueBrowser for * @param messageSelector the message selector for this consumer (can be {@code null}) * @return the new JMS QueueBrowser * @throws JMSException if thrown by JMS API methods * @see #setMessageIdEnabled * @see #setMessageTimestampEnabled */ protected QueueBrowser createBrowser(Session session, Queue queue, @Nullable String messageSelector) throws JMSException { return session.createBrowser(queue, messageSelector); } /** * ResourceFactory implementation that delegates to this template's protected callback methods. */ private class JmsTemplateResourceFactory implements ConnectionFactoryUtils.ResourceFactory { @Override @Nullable public Connection getConnection(JmsResourceHolder holder) { return JmsTemplate.this.getConnection(holder); } @Override @Nullable public Session getSession(JmsResourceHolder holder) { return JmsTemplate.this.getSession(holder); } @Override public Connection createConnection() throws JMSException { return JmsTemplate.this.createConnection(); } @Override public Session createSession(Connection con) throws JMSException { return JmsTemplate.this.createSession(con); } @Override public boolean isSynchedLocalTransactionAllowed() { return JmsTemplate.this.isSessionTransacted(); } } private abstract static class MicrometerInstrumentation { static Session instrumentSession(Session session, ObservationRegistry registry) { return JmsInstrumentation.instrumentSession(session, registry); } } }
spring-projects/spring-framework
spring-jms/src/main/java/org/springframework/jms/core/JmsTemplate.java
44,931
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.index.engine; import org.apache.lucene.util.BytesRef; /** * Keeps track of the old map of a LiveVersionMap that gets evacuated on a refresh */ public interface LiveVersionMapArchive { /** * Archive the old map evacuated due to a refresh * * @param old is the old map that is evacuated on a refresh */ void afterRefresh(LiveVersionMap.VersionLookup old); /** * Look up the given uid in the archive */ VersionValue get(BytesRef uid); /** * Returns the min delete timestamp across all archived maps. */ long getMinDeleteTimestamp(); /** * Returns whether the archive has seen an unsafe old map (passed via {@link LiveVersionMapArchive#afterRefresh}) * which has not yet been refreshed on the unpromotable shards. */ default boolean isUnsafe() { return false; } /** * Returns the total memory usage if the Archive. */ default long getRamBytesUsed() { return 0L; } /** * Returns how much memory could be freed up by creating a new commit and issuing a new unpromotable refresh. */ default long getReclaimableRamBytes() { return 0; } /** * Returns how much memory will be freed once the current ongoing unpromotable refresh is finished. */ default long getRefreshingRamBytes() { return 0; } LiveVersionMapArchive NOOP_ARCHIVE = new LiveVersionMapArchive() { @Override public void afterRefresh(LiveVersionMap.VersionLookup old) {} @Override public VersionValue get(BytesRef uid) { return null; } @Override public long getMinDeleteTimestamp() { return Long.MAX_VALUE; } }; }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/index/engine/LiveVersionMapArchive.java
44,933
/* Copyright (c) 2007 Timothy Wall, All Rights Reserved * * The contents of this file is dual-licensed under 2 * alternative Open Source/Free licenses: LGPL 2.1 or later and * Apache License 2.0. (starting with JNA version 4.0.0). * * You can freely decide which license you want to apply to * the project. * * You may obtain a copy of the LGPL License at: * * http://www.gnu.org/licenses/licenses.html * * A copy is also included in the downloadable source code package * containing JNA, in file "LGPL2.1". * * You may obtain a copy of the Apache License at: * * http://www.apache.org/licenses/ * * A copy is also included in the downloadable source code package * containing JNA, in file "AL2.0". */ package com.sun.jna; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * All callback definitions must derive from this interface. Any derived * interfaces must define a single public method (which may not be named * "hashCode", "equals", or "toString"), or one public method named "callback". * You are responsible for deregistering your callback (if necessary). If native * code attempts to call a callback which has been GC'd, you will likely crash * the VM. If there is no method to deregister the callback (e.g. * <code>atexit</code> in the C library), you must ensure that you always keep a * live reference to the callback object.<p> * A callback should generally never throw an exception, since it doesn't * necessarily have an encompassing Java environment to catch it. Any * exceptions thrown will be passed to the default callback exception * handler. */ public interface Callback { interface UncaughtExceptionHandler { /** Method invoked when the given callback throws an uncaught * exception.<p> * Any exception thrown by this method will be ignored. */ void uncaughtException(Callback c, Throwable e); } /** You must use this method name if your callback interface has multiple public methods. Typically a callback will have only one such method, in which case any method name may be used, with the exception of those in {@link #FORBIDDEN_NAMES}. */ String METHOD_NAME = "callback"; /** These method names may not be used for a callback method. */ List<String> FORBIDDEN_NAMES = Collections.unmodifiableList( Arrays.asList("hashCode", "equals", "toString")); }
java-native-access/jna
src/com/sun/jna/Callback.java
44,934
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.streams; import org.apache.kafka.clients.CommonClientConfigs; import org.apache.kafka.clients.admin.Admin; import org.apache.kafka.clients.admin.ListOffsetsResult.ListOffsetsResultInfo; import org.apache.kafka.clients.admin.MemberToRemove; import org.apache.kafka.clients.admin.RemoveMembersFromConsumerGroupOptions; import org.apache.kafka.clients.admin.RemoveMembersFromConsumerGroupResult; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.common.KafkaFuture; import org.apache.kafka.common.Metric; import org.apache.kafka.common.MetricName; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.Uuid; import org.apache.kafka.common.annotation.InterfaceStability.Evolving; import org.apache.kafka.common.errors.TimeoutException; import org.apache.kafka.common.metrics.KafkaMetricsContext; import org.apache.kafka.common.metrics.MetricConfig; import org.apache.kafka.common.metrics.Metrics; import org.apache.kafka.common.metrics.MetricsContext; import org.apache.kafka.common.metrics.MetricsReporter; import org.apache.kafka.common.metrics.Sensor; import org.apache.kafka.common.metrics.Sensor.RecordingLevel; import org.apache.kafka.common.serialization.Serializer; import org.apache.kafka.common.utils.LogContext; import org.apache.kafka.common.utils.Time; import org.apache.kafka.common.utils.Timer; import org.apache.kafka.common.utils.Utils; import org.apache.kafka.streams.errors.InvalidStateStoreException; import org.apache.kafka.streams.errors.InvalidStateStorePartitionException; import org.apache.kafka.streams.errors.ProcessorStateException; import org.apache.kafka.streams.errors.StreamsException; import org.apache.kafka.streams.errors.StreamsNotStartedException; import org.apache.kafka.streams.errors.StreamsStoppedException; import org.apache.kafka.streams.errors.StreamsUncaughtExceptionHandler; import org.apache.kafka.streams.errors.UnknownStateStoreException; import org.apache.kafka.streams.internals.ClientInstanceIdsImpl; import org.apache.kafka.streams.internals.metrics.ClientMetrics; import org.apache.kafka.streams.processor.StandbyUpdateListener; import org.apache.kafka.streams.processor.StateRestoreListener; import org.apache.kafka.streams.processor.StateStore; import org.apache.kafka.streams.processor.StreamPartitioner; import org.apache.kafka.streams.processor.TaskId; import org.apache.kafka.streams.processor.internals.ClientUtils; import org.apache.kafka.streams.processor.internals.GlobalStreamThread; import org.apache.kafka.streams.processor.internals.StateDirectory; import org.apache.kafka.streams.processor.internals.StreamThread; import org.apache.kafka.streams.processor.internals.StreamsMetadataState; import org.apache.kafka.streams.processor.internals.Task; import org.apache.kafka.streams.processor.internals.ThreadStateTransitionValidator; import org.apache.kafka.streams.processor.internals.TopologyMetadata; import org.apache.kafka.streams.processor.internals.assignment.AssignorError; import org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl; import org.apache.kafka.streams.processor.internals.namedtopology.NamedTopology; import org.apache.kafka.streams.query.FailureReason; import org.apache.kafka.streams.query.PositionBound; import org.apache.kafka.streams.query.QueryConfig; import org.apache.kafka.streams.query.QueryResult; import org.apache.kafka.streams.query.StateQueryRequest; import org.apache.kafka.streams.query.StateQueryResult; import org.apache.kafka.streams.state.HostInfo; import org.apache.kafka.streams.state.internals.GlobalStateStoreProvider; import org.apache.kafka.streams.state.internals.QueryableStoreProvider; import org.apache.kafka.streams.state.internals.StreamThreadStateStoreProvider; import org.slf4j.Logger; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Properties; import java.util.Set; import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.stream.Collectors; import static org.apache.kafka.streams.errors.StreamsUncaughtExceptionHandler.StreamThreadExceptionResponse.SHUTDOWN_CLIENT; import static org.apache.kafka.streams.internals.ApiUtils.prepareMillisCheckFailMsgPrefix; import static org.apache.kafka.streams.internals.ApiUtils.validateMillisecondDuration; import static org.apache.kafka.streams.internals.StreamsConfigUtils.getTotalCacheSize; import static org.apache.kafka.streams.processor.internals.ClientUtils.fetchEndOffsets; import static org.apache.kafka.streams.processor.internals.TopologyMetadata.UNNAMED_TOPOLOGY; /** * A Kafka client that allows for performing continuous computation on input coming from one or more input topics and * sends output to zero, one, or more output topics. * <p> * The computational logic can be specified either by using the {@link Topology} to define a DAG topology of * {@link org.apache.kafka.streams.processor.api.Processor}s or by using the {@link StreamsBuilder} which provides the high-level DSL to define * transformations. * <p> * One {@code KafkaStreams} instance can contain one or more threads specified in the configs for the processing work. * <p> * A {@code KafkaStreams} instance can co-ordinate with any other instances with the same * {@link StreamsConfig#APPLICATION_ID_CONFIG application ID} (whether in the same process, on other processes on this * machine, or on remote machines) as a single (possibly distributed) stream processing application. * These instances will divide up the work based on the assignment of the input topic partitions so that all partitions * are being consumed. * If instances are added or fail, all (remaining) instances will rebalance the partition assignment among themselves * to balance processing load and ensure that all input topic partitions are processed. * <p> * Internally a {@code KafkaStreams} instance contains a normal {@link KafkaProducer} and {@link KafkaConsumer} instance * that is used for reading input and writing output. * <p> * A simple example might look like this: * <pre>{@code * Properties props = new Properties(); * props.put(StreamsConfig.APPLICATION_ID_CONFIG, "my-stream-processing-application"); * props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); * props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass()); * props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass()); * * StreamsBuilder builder = new StreamsBuilder(); * builder.<String, String>stream("my-input-topic").mapValues(value -> String.valueOf(value.length())).to("my-output-topic"); * * KafkaStreams streams = new KafkaStreams(builder.build(), props); * streams.start(); * }</pre> * * @see org.apache.kafka.streams.StreamsBuilder * @see org.apache.kafka.streams.Topology */ public class KafkaStreams implements AutoCloseable { private static final String JMX_PREFIX = "kafka.streams"; // processId is expected to be unique across JVMs and to be used // in userData of the subscription request to allow assignor be aware // of the co-location of stream thread's consumers. It is for internal // usage only and should not be exposed to users at all. private final Time time; private final Logger log; protected final String clientId; private final Metrics metrics; protected final StreamsConfig applicationConfigs; protected final List<StreamThread> threads; protected final StreamsMetadataState streamsMetadataState; private final ScheduledExecutorService stateDirCleaner; private final ScheduledExecutorService rocksDBMetricsRecordingService; protected final Admin adminClient; private final StreamsMetricsImpl streamsMetrics; private final long totalCacheSize; private final StreamStateListener streamStateListener; private final DelegatingStateRestoreListener delegatingStateRestoreListener; private final Map<Long, StreamThread.State> threadState; private final UUID processId; private final KafkaClientSupplier clientSupplier; protected final TopologyMetadata topologyMetadata; private final QueryableStoreProvider queryableStoreProvider; private final DelegatingStandbyUpdateListener delegatingStandbyUpdateListener; GlobalStreamThread globalStreamThread; protected StateDirectory stateDirectory = null; private KafkaStreams.StateListener stateListener; private boolean oldHandler; private BiConsumer<Throwable, Boolean> streamsUncaughtExceptionHandler; private final Object changeThreadCount = new Object(); // container states /** * Kafka Streams states are the possible state that a Kafka Streams instance can be in. * An instance must only be in one state at a time. * The expected state transition with the following defined states is: * * <pre> * +--------------+ * +&lt;----- | Created (0) | * | +-----+--------+ * | | * | v * | +----+--+------+ * | | Re- | * +&lt;----- | Balancing (1)| --------&gt;+ * | +-----+-+------+ | * | | ^ | * | v | | * | +--------------+ v * | | Running (2) | --------&gt;+ * | +------+-------+ | * | | | * | v | * | +------+-------+ +----+-------+ * +-----&gt; | Pending | | Pending | * | Shutdown (3) | | Error (5) | * +------+-------+ +-----+------+ * | | * v v * +------+-------+ +-----+--------+ * | Not | | Error (6) | * | Running (4) | +--------------+ * +--------------+ * * * </pre> * Note the following: * - RUNNING state will transit to REBALANCING if any of its threads is in PARTITION_REVOKED or PARTITIONS_ASSIGNED state * - REBALANCING state will transit to RUNNING if all of its threads are in RUNNING state * - Any state except NOT_RUNNING, PENDING_ERROR or ERROR can go to PENDING_SHUTDOWN (whenever close is called) * - Of special importance: If the global stream thread dies, or all stream threads die (or both) then * the instance will be in the ERROR state. The user will not need to close it. */ public enum State { // Note: if you add a new state, check the below methods and how they are used within Streams to see if // any of them should be updated to include the new state. For example a new shutdown path or terminal // state would likely need to be included in methods like isShuttingDown(), hasCompletedShutdown(), etc. CREATED(1, 3), // 0 REBALANCING(2, 3, 5), // 1 RUNNING(1, 2, 3, 5), // 2 PENDING_SHUTDOWN(4), // 3 NOT_RUNNING, // 4 PENDING_ERROR(6), // 5 ERROR; // 6 private final Set<Integer> validTransitions = new HashSet<>(); State(final Integer... validTransitions) { this.validTransitions.addAll(Arrays.asList(validTransitions)); } public boolean hasNotStarted() { return equals(CREATED); } public boolean isRunningOrRebalancing() { return equals(RUNNING) || equals(REBALANCING); } public boolean isShuttingDown() { return equals(PENDING_SHUTDOWN) || equals(PENDING_ERROR); } public boolean hasCompletedShutdown() { return equals(NOT_RUNNING) || equals(ERROR); } public boolean hasStartedOrFinishedShuttingDown() { return isShuttingDown() || hasCompletedShutdown(); } public boolean isValidTransition(final State newState) { return validTransitions.contains(newState.ordinal()); } } private final Object stateLock = new Object(); protected volatile State state = State.CREATED; private boolean waitOnState(final State targetState, final long waitMs) { final long begin = time.milliseconds(); synchronized (stateLock) { boolean interrupted = false; long elapsedMs = 0L; try { while (state != targetState) { if (waitMs > elapsedMs) { final long remainingMs = waitMs - elapsedMs; try { stateLock.wait(remainingMs); } catch (final InterruptedException e) { interrupted = true; } } else { log.debug("Cannot transit to {} within {}ms", targetState, waitMs); return false; } elapsedMs = time.milliseconds() - begin; } } finally { // Make sure to restore the interruption status before returning. // We do not always own the current thread that executes this method, i.e., we do not know the // interruption policy of the thread. The least we can do is restore the interruption status before // the current thread exits this method. if (interrupted) { Thread.currentThread().interrupt(); } } return true; } } /** * Sets the state * @param newState New state */ private boolean setState(final State newState) { final State oldState; synchronized (stateLock) { oldState = state; if (state == State.PENDING_SHUTDOWN && newState != State.NOT_RUNNING) { // when the state is already in PENDING_SHUTDOWN, all other transitions than NOT_RUNNING (due to thread dying) will be // refused but we do not throw exception here, to allow appropriate error handling return false; } else if (state == State.NOT_RUNNING && (newState == State.PENDING_SHUTDOWN || newState == State.NOT_RUNNING)) { // when the state is already in NOT_RUNNING, its transition to PENDING_SHUTDOWN or NOT_RUNNING (due to consecutive close calls) // will be refused but we do not throw exception here, to allow idempotent close calls return false; } else if (state == State.REBALANCING && newState == State.REBALANCING) { // when the state is already in REBALANCING, it should not transit to REBALANCING again return false; } else if (state == State.ERROR && (newState == State.PENDING_ERROR || newState == State.ERROR)) { // when the state is already in ERROR, its transition to PENDING_ERROR or ERROR (due to consecutive close calls) return false; } else if (state == State.PENDING_ERROR && newState != State.ERROR) { // when the state is already in PENDING_ERROR, all other transitions than ERROR (due to thread dying) will be // refused but we do not throw exception here, to allow appropriate error handling return false; } else if (!state.isValidTransition(newState)) { throw new IllegalStateException("Stream-client " + clientId + ": Unexpected state transition from " + oldState + " to " + newState); } else { log.info("State transition from {} to {}", oldState, newState); } state = newState; stateLock.notifyAll(); } // we need to call the user customized state listener outside the state lock to avoid potential deadlocks if (stateListener != null) { stateListener.onChange(newState, oldState); } return true; } /** * Return the current {@link State} of this {@code KafkaStreams} instance. * * @return the current state of this Kafka Streams instance */ public State state() { return state; } protected boolean isRunningOrRebalancing() { synchronized (stateLock) { return state.isRunningOrRebalancing(); } } protected boolean hasStartedOrFinishedShuttingDown() { synchronized (stateLock) { return state.hasStartedOrFinishedShuttingDown(); } } protected void validateIsRunningOrRebalancing() { synchronized (stateLock) { if (state.hasNotStarted()) { throw new StreamsNotStartedException("KafkaStreams has not been started, you can retry after calling start()"); } if (!state.isRunningOrRebalancing()) { throw new IllegalStateException("KafkaStreams is not running. State is " + state + "."); } } } /** * Listen to {@link State} change events. */ public interface StateListener { /** * Called when state changes. * * @param newState new state * @param oldState previous state */ void onChange(final State newState, final State oldState); } /** * An app can set a single {@link KafkaStreams.StateListener} so that the app is notified when state changes. * * @param listener a new state listener * @throws IllegalStateException if this {@code KafkaStreams} instance has already been started. */ public void setStateListener(final KafkaStreams.StateListener listener) { synchronized (stateLock) { if (state.hasNotStarted()) { stateListener = listener; } else { throw new IllegalStateException("Can only set StateListener before calling start(). Current state is: " + state); } } } /** * Set the handler invoked when an internal {@link StreamsConfig#NUM_STREAM_THREADS_CONFIG stream thread} abruptly * terminates due to an uncaught exception. * * @param uncaughtExceptionHandler the uncaught exception handler for all internal threads; {@code null} deletes the current handler * @throws IllegalStateException if this {@code KafkaStreams} instance has already been started. * * @deprecated Since 2.8.0. Use {@link KafkaStreams#setUncaughtExceptionHandler(StreamsUncaughtExceptionHandler)} instead. * */ @Deprecated public void setUncaughtExceptionHandler(final Thread.UncaughtExceptionHandler uncaughtExceptionHandler) { synchronized (stateLock) { if (state.hasNotStarted()) { oldHandler = true; processStreamThread(thread -> thread.setUncaughtExceptionHandler(uncaughtExceptionHandler)); if (globalStreamThread != null) { globalStreamThread.setUncaughtExceptionHandler(uncaughtExceptionHandler); } } else { throw new IllegalStateException("Can only set UncaughtExceptionHandler before calling start(). " + "Current state is: " + state); } } } /** * Set the handler invoked when an internal {@link StreamsConfig#NUM_STREAM_THREADS_CONFIG stream thread} * throws an unexpected exception. * These might be exceptions indicating rare bugs in Kafka Streams, or they * might be exceptions thrown by your code, for example a NullPointerException thrown from your processor logic. * The handler will execute on the thread that produced the exception. * In order to get the thread that threw the exception, use {@code Thread.currentThread()}. * <p> * Note, this handler must be threadsafe, since it will be shared among all threads, and invoked from any * thread that encounters such an exception. * * @param userStreamsUncaughtExceptionHandler the uncaught exception handler of type {@link StreamsUncaughtExceptionHandler} for all internal threads * @throws IllegalStateException if this {@code KafkaStreams} instance has already been started. * @throws NullPointerException if userStreamsUncaughtExceptionHandler is null. */ public void setUncaughtExceptionHandler(final StreamsUncaughtExceptionHandler userStreamsUncaughtExceptionHandler) { synchronized (stateLock) { if (state.hasNotStarted()) { Objects.requireNonNull(userStreamsUncaughtExceptionHandler); streamsUncaughtExceptionHandler = (exception, skipThreadReplacement) -> handleStreamsUncaughtException(exception, userStreamsUncaughtExceptionHandler, skipThreadReplacement); processStreamThread(thread -> thread.setStreamsUncaughtExceptionHandler(streamsUncaughtExceptionHandler)); if (globalStreamThread != null) { globalStreamThread.setUncaughtExceptionHandler( exception -> handleStreamsUncaughtException(exception, userStreamsUncaughtExceptionHandler, false) ); } processStreamThread(thread -> thread.setUncaughtExceptionHandler((t, e) -> { } )); if (globalStreamThread != null) { globalStreamThread.setUncaughtExceptionHandler((t, e) -> { } ); } } else { throw new IllegalStateException("Can only set UncaughtExceptionHandler before calling start(). " + "Current state is: " + state); } } } private void defaultStreamsUncaughtExceptionHandler(final Throwable throwable, final boolean skipThreadReplacement) { if (oldHandler) { threads.remove(Thread.currentThread()); if (throwable instanceof RuntimeException) { throw (RuntimeException) throwable; } else if (throwable instanceof Error) { throw (Error) throwable; } else { throw new RuntimeException("Unexpected checked exception caught in the uncaught exception handler", throwable); } } else { handleStreamsUncaughtException(throwable, t -> SHUTDOWN_CLIENT, skipThreadReplacement); } } private void replaceStreamThread(final Throwable throwable) { if (globalStreamThread != null && Thread.currentThread().getName().equals(globalStreamThread.getName())) { log.warn("The global thread cannot be replaced. Reverting to shutting down the client."); log.error("Encountered the following exception during processing " + " The streams client is going to shut down now. ", throwable); closeToError(); } final StreamThread deadThread = (StreamThread) Thread.currentThread(); deadThread.shutdown(); addStreamThread(); if (throwable instanceof RuntimeException) { throw (RuntimeException) throwable; } else if (throwable instanceof Error) { throw (Error) throwable; } else { throw new RuntimeException("Unexpected checked exception caught in the uncaught exception handler", throwable); } } private void handleStreamsUncaughtException(final Throwable throwable, final StreamsUncaughtExceptionHandler streamsUncaughtExceptionHandler, final boolean skipThreadReplacement) { final StreamsUncaughtExceptionHandler.StreamThreadExceptionResponse action = streamsUncaughtExceptionHandler.handle(throwable); if (oldHandler) { log.warn("Stream's new uncaught exception handler is set as well as the deprecated old handler." + "The old handler will be ignored as long as a new handler is set."); } switch (action) { case REPLACE_THREAD: if (!skipThreadReplacement) { log.error("Replacing thread in the streams uncaught exception handler", throwable); replaceStreamThread(throwable); } else { log.debug("Skipping thread replacement for recoverable error"); } break; case SHUTDOWN_CLIENT: log.error("Encountered the following exception during processing " + "and the registered exception handler opted to " + action + "." + " The streams client is going to shut down now. ", throwable); closeToError(); break; case SHUTDOWN_APPLICATION: if (getNumLiveStreamThreads() == 1) { log.warn("Attempt to shut down the application requires adding a thread to communicate the shutdown. No processing will be done on this thread"); addStreamThread(); } if (throwable instanceof Error) { log.error("This option requires running threads to shut down the application." + "but the uncaught exception was an Error, which means this runtime is no " + "longer in a well-defined state. Attempting to send the shutdown command anyway.", throwable); } if (Thread.currentThread().equals(globalStreamThread) && getNumLiveStreamThreads() == 0) { log.error("Exception in global thread caused the application to attempt to shutdown." + " This action will succeed only if there is at least one StreamThread running on this client." + " Currently there are no running threads so will now close the client."); closeToError(); break; } processStreamThread(thread -> thread.sendShutdownRequest(AssignorError.SHUTDOWN_REQUESTED)); log.error("Encountered the following exception during processing " + "and sent shutdown request for the entire application.", throwable); break; } } /** * Set the listener which is triggered whenever a {@link StateStore} is being restored in order to resume * processing. * * @param globalStateRestoreListener The listener triggered when {@link StateStore} is being restored. * @throws IllegalStateException if this {@code KafkaStreams} instance has already been started. */ public void setGlobalStateRestoreListener(final StateRestoreListener globalStateRestoreListener) { synchronized (stateLock) { if (state.hasNotStarted()) { delegatingStateRestoreListener.setUserStateRestoreListener(globalStateRestoreListener); } else { throw new IllegalStateException("Can only set GlobalStateRestoreListener before calling start(). " + "Current state is: " + state); } } } /** * Set the listener which is triggered whenever a standby task is updated * * @param standbyListener The listener triggered when a standby task is updated. * @throws IllegalStateException if this {@code KafkaStreams} instance has already been started. */ public void setStandbyUpdateListener(final StandbyUpdateListener standbyListener) { synchronized (stateLock) { if (state.hasNotStarted()) { this.delegatingStandbyUpdateListener.setUserStandbyListener(standbyListener); } else { throw new IllegalStateException("Can only set StandbyUpdateListener before calling start(). " + "Current state is: " + state); } } } /** * Get read-only handle on global metrics registry, including streams client's own metrics plus * its embedded producer, consumer and admin clients' metrics. * * @return Map of all metrics. */ public Map<MetricName, ? extends Metric> metrics() { final Map<MetricName, Metric> result = new LinkedHashMap<>(); // producer and consumer clients are per-thread processStreamThread(thread -> { result.putAll(thread.producerMetrics()); result.putAll(thread.consumerMetrics()); // admin client is shared, so we can actually move it // to result.putAll(adminClient.metrics()). // we did it intentionally just for flexibility. result.putAll(thread.adminClientMetrics()); }); // global thread's consumer client if (globalStreamThread != null) { result.putAll(globalStreamThread.consumerMetrics()); } // self streams metrics result.putAll(metrics.metrics()); return Collections.unmodifiableMap(result); } /** * Class that handles stream thread transitions */ final class StreamStateListener implements StreamThread.StateListener { private final Map<Long, StreamThread.State> threadState; private GlobalStreamThread.State globalThreadState; // this lock should always be held before the state lock private final Object threadStatesLock; StreamStateListener(final Map<Long, StreamThread.State> threadState, final GlobalStreamThread.State globalThreadState) { this.threadState = threadState; this.globalThreadState = globalThreadState; this.threadStatesLock = new Object(); } /** * If all threads are up, including the global thread, set to RUNNING */ private void maybeSetRunning() { // state can be transferred to RUNNING if // 1) all threads are either RUNNING or DEAD // 2) thread is pending-shutdown and there are still other threads running final boolean hasRunningThread = threadState.values().stream().anyMatch(s -> s == StreamThread.State.RUNNING); for (final StreamThread.State state : threadState.values()) { if (state == StreamThread.State.PENDING_SHUTDOWN && hasRunningThread) continue; if (state != StreamThread.State.RUNNING && state != StreamThread.State.DEAD) { return; } } // the global state thread is relevant only if it is started. There are cases // when we don't have a global state thread at all, e.g., when we don't have global KTables if (globalThreadState != null && globalThreadState != GlobalStreamThread.State.RUNNING) { return; } setState(State.RUNNING); } @Override public synchronized void onChange(final Thread thread, final ThreadStateTransitionValidator abstractNewState, final ThreadStateTransitionValidator abstractOldState) { synchronized (threadStatesLock) { // StreamThreads first if (thread instanceof StreamThread) { final StreamThread.State newState = (StreamThread.State) abstractNewState; threadState.put(thread.getId(), newState); if (newState == StreamThread.State.PARTITIONS_REVOKED || newState == StreamThread.State.PARTITIONS_ASSIGNED) { setState(State.REBALANCING); } else if (newState == StreamThread.State.RUNNING) { maybeSetRunning(); } } else if (thread instanceof GlobalStreamThread) { // global stream thread has different invariants final GlobalStreamThread.State newState = (GlobalStreamThread.State) abstractNewState; globalThreadState = newState; if (newState == GlobalStreamThread.State.RUNNING) { maybeSetRunning(); } else if (newState == GlobalStreamThread.State.DEAD) { if (state != State.PENDING_SHUTDOWN) { log.error("Global thread has died. The streams application or client will now close to ERROR."); closeToError(); } } } } } } static final class DelegatingStateRestoreListener implements StateRestoreListener { private StateRestoreListener userStateRestoreListener; private void throwOnFatalException(final Exception fatalUserException, final TopicPartition topicPartition, final String storeName) { throw new StreamsException( String.format("Fatal user code error in store restore listener for store %s, partition %s.", storeName, topicPartition), fatalUserException); } void setUserStateRestoreListener(final StateRestoreListener userStateRestoreListener) { this.userStateRestoreListener = userStateRestoreListener; } @Override public void onRestoreStart(final TopicPartition topicPartition, final String storeName, final long startingOffset, final long endingOffset) { if (userStateRestoreListener != null) { try { userStateRestoreListener.onRestoreStart(topicPartition, storeName, startingOffset, endingOffset); } catch (final Exception fatalUserException) { throwOnFatalException(fatalUserException, topicPartition, storeName); } } } @Override public void onBatchRestored(final TopicPartition topicPartition, final String storeName, final long batchEndOffset, final long numRestored) { if (userStateRestoreListener != null) { try { userStateRestoreListener.onBatchRestored(topicPartition, storeName, batchEndOffset, numRestored); } catch (final Exception fatalUserException) { throwOnFatalException(fatalUserException, topicPartition, storeName); } } } @Override public void onRestoreEnd(final TopicPartition topicPartition, final String storeName, final long totalRestored) { if (userStateRestoreListener != null) { try { userStateRestoreListener.onRestoreEnd(topicPartition, storeName, totalRestored); } catch (final Exception fatalUserException) { throwOnFatalException(fatalUserException, topicPartition, storeName); } } } @Override public void onRestoreSuspended(final TopicPartition topicPartition, final String storeName, final long totalRestored) { if (userStateRestoreListener != null) { try { userStateRestoreListener.onRestoreSuspended(topicPartition, storeName, totalRestored); } catch (final Exception fatalUserException) { throwOnFatalException(fatalUserException, topicPartition, storeName); } } } } final static class DelegatingStandbyUpdateListener implements StandbyUpdateListener { private StandbyUpdateListener userStandbyListener; private void throwOnFatalException(final Exception fatalUserException, final TopicPartition topicPartition, final String storeName) { throw new StreamsException( String.format("Fatal user code error in standby update listener for store %s, partition %s.", storeName, topicPartition), fatalUserException); } @Override public void onUpdateStart(final TopicPartition topicPartition, final String storeName, final long startingOffset) { if (userStandbyListener != null) { try { userStandbyListener.onUpdateStart(topicPartition, storeName, startingOffset); } catch (final Exception fatalUserException) { throwOnFatalException(fatalUserException, topicPartition, storeName); } } } @Override public void onBatchLoaded(final TopicPartition topicPartition, final String storeName, final TaskId taskId, final long batchEndOffset, final long batchSize, final long currentEndOffset) { if (userStandbyListener != null) { try { userStandbyListener.onBatchLoaded(topicPartition, storeName, taskId, batchEndOffset, batchSize, currentEndOffset); } catch (final Exception fatalUserException) { throwOnFatalException(fatalUserException, topicPartition, storeName); } } } @Override public void onUpdateSuspended(final TopicPartition topicPartition, final String storeName, final long storeOffset, final long currentEndOffset, final SuspendReason reason) { if (userStandbyListener != null) { try { userStandbyListener.onUpdateSuspended(topicPartition, storeName, storeOffset, currentEndOffset, reason); } catch (final Exception fatalUserException) { throwOnFatalException(fatalUserException, topicPartition, storeName); } } } void setUserStandbyListener(final StandbyUpdateListener userStandbyListener) { this.userStandbyListener = userStandbyListener; } } /** * Create a {@code KafkaStreams} instance. * <p> * Note: even if you never call {@link #start()} on a {@code KafkaStreams} instance, * you still must {@link #close()} it to avoid resource leaks. * * @param topology the topology specifying the computational logic * @param props properties for {@link StreamsConfig} * @throws StreamsException if any fatal error occurs */ public KafkaStreams(final Topology topology, final Properties props) { this(topology, new StreamsConfig(props)); } /** * Create a {@code KafkaStreams} instance. * <p> * Note: even if you never call {@link #start()} on a {@code KafkaStreams} instance, * you still must {@link #close()} it to avoid resource leaks. * * @param topology the topology specifying the computational logic * @param props properties for {@link StreamsConfig} * @param clientSupplier the Kafka clients supplier which provides underlying producer and consumer clients * for the new {@code KafkaStreams} instance * @throws StreamsException if any fatal error occurs */ public KafkaStreams(final Topology topology, final Properties props, final KafkaClientSupplier clientSupplier) { this(topology, new StreamsConfig(props), clientSupplier, Time.SYSTEM); } /** * Create a {@code KafkaStreams} instance. * <p> * Note: even if you never call {@link #start()} on a {@code KafkaStreams} instance, * you still must {@link #close()} it to avoid resource leaks. * * @param topology the topology specifying the computational logic * @param props properties for {@link StreamsConfig} * @param time {@code Time} implementation; cannot be null * @throws StreamsException if any fatal error occurs */ public KafkaStreams(final Topology topology, final Properties props, final Time time) { this(topology, new StreamsConfig(props), time); } /** * Create a {@code KafkaStreams} instance. * <p> * Note: even if you never call {@link #start()} on a {@code KafkaStreams} instance, * you still must {@link #close()} it to avoid resource leaks. * * @param topology the topology specifying the computational logic * @param props properties for {@link StreamsConfig} * @param clientSupplier the Kafka clients supplier which provides underlying producer and consumer clients * for the new {@code KafkaStreams} instance * @param time {@code Time} implementation; cannot be null * @throws StreamsException if any fatal error occurs */ public KafkaStreams(final Topology topology, final Properties props, final KafkaClientSupplier clientSupplier, final Time time) { this(topology, new StreamsConfig(props), clientSupplier, time); } /** * Create a {@code KafkaStreams} instance. * <p> * Note: even if you never call {@link #start()} on a {@code KafkaStreams} instance, * you still must {@link #close()} it to avoid resource leaks. * * @param topology the topology specifying the computational logic * @param applicationConfigs configs for Kafka Streams * @throws StreamsException if any fatal error occurs */ public KafkaStreams(final Topology topology, final StreamsConfig applicationConfigs) { this(topology, applicationConfigs, applicationConfigs.getKafkaClientSupplier()); } /** * Create a {@code KafkaStreams} instance. * <p> * Note: even if you never call {@link #start()} on a {@code KafkaStreams} instance, * you still must {@link #close()} it to avoid resource leaks. * * @param topology the topology specifying the computational logic * @param applicationConfigs configs for Kafka Streams * @param clientSupplier the Kafka clients supplier which provides underlying producer and consumer clients * for the new {@code KafkaStreams} instance * @throws StreamsException if any fatal error occurs */ public KafkaStreams(final Topology topology, final StreamsConfig applicationConfigs, final KafkaClientSupplier clientSupplier) { this(new TopologyMetadata(topology.internalTopologyBuilder, applicationConfigs), applicationConfigs, clientSupplier); } /** * Create a {@code KafkaStreams} instance. * <p> * Note: even if you never call {@link #start()} on a {@code KafkaStreams} instance, * you still must {@link #close()} it to avoid resource leaks. * * @param topology the topology specifying the computational logic * @param applicationConfigs configs for Kafka Streams * @param time {@code Time} implementation; cannot be null * @throws StreamsException if any fatal error occurs */ public KafkaStreams(final Topology topology, final StreamsConfig applicationConfigs, final Time time) { this(new TopologyMetadata(topology.internalTopologyBuilder, applicationConfigs), applicationConfigs, applicationConfigs.getKafkaClientSupplier(), time); } private KafkaStreams(final Topology topology, final StreamsConfig applicationConfigs, final KafkaClientSupplier clientSupplier, final Time time) throws StreamsException { this(new TopologyMetadata(topology.internalTopologyBuilder, applicationConfigs), applicationConfigs, clientSupplier, time); } protected KafkaStreams(final TopologyMetadata topologyMetadata, final StreamsConfig applicationConfigs, final KafkaClientSupplier clientSupplier) throws StreamsException { this(topologyMetadata, applicationConfigs, clientSupplier, Time.SYSTEM); } @SuppressWarnings("this-escape") private KafkaStreams(final TopologyMetadata topologyMetadata, final StreamsConfig applicationConfigs, final KafkaClientSupplier clientSupplier, final Time time) throws StreamsException { this.applicationConfigs = applicationConfigs; this.time = time; this.topologyMetadata = topologyMetadata; this.topologyMetadata.buildAndRewriteTopology(); final boolean hasGlobalTopology = topologyMetadata.hasGlobalTopology(); try { stateDirectory = new StateDirectory(applicationConfigs, time, topologyMetadata.hasPersistentStores(), topologyMetadata.hasNamedTopologies()); processId = stateDirectory.initializeProcessId(); } catch (final ProcessorStateException fatal) { Utils.closeQuietly(stateDirectory, "streams state directory"); throw new StreamsException(fatal); } // The application ID is a required config and hence should always have value final String userClientId = applicationConfigs.getString(StreamsConfig.CLIENT_ID_CONFIG); final String applicationId = applicationConfigs.getString(StreamsConfig.APPLICATION_ID_CONFIG); if (userClientId.length() <= 0) { clientId = applicationId + "-" + processId; } else { clientId = userClientId; } final LogContext logContext = new LogContext(String.format("stream-client [%s] ", clientId)); this.log = logContext.logger(getClass()); topologyMetadata.setLog(logContext); // use client id instead of thread client id since this admin client may be shared among threads this.clientSupplier = clientSupplier; adminClient = clientSupplier.getAdmin(applicationConfigs.getAdminConfigs(ClientUtils.getSharedAdminClientId(clientId))); log.info("Kafka Streams version: {}", ClientMetrics.version()); log.info("Kafka Streams commit ID: {}", ClientMetrics.commitId()); metrics = getMetrics(applicationConfigs, time, clientId); streamsMetrics = new StreamsMetricsImpl( metrics, clientId, applicationConfigs.getString(StreamsConfig.BUILT_IN_METRICS_VERSION_CONFIG), time ); ClientMetrics.addVersionMetric(streamsMetrics); ClientMetrics.addCommitIdMetric(streamsMetrics); ClientMetrics.addApplicationIdMetric(streamsMetrics, applicationConfigs.getString(StreamsConfig.APPLICATION_ID_CONFIG)); ClientMetrics.addTopologyDescriptionMetric(streamsMetrics, (metricsConfig, now) -> this.topologyMetadata.topologyDescriptionString()); ClientMetrics.addStateMetric(streamsMetrics, (metricsConfig, now) -> state); threads = Collections.synchronizedList(new LinkedList<>()); ClientMetrics.addNumAliveStreamThreadMetric(streamsMetrics, (metricsConfig, now) -> getNumLiveStreamThreads()); streamsMetadataState = new StreamsMetadataState( this.topologyMetadata, parseHostInfo(applicationConfigs.getString(StreamsConfig.APPLICATION_SERVER_CONFIG)), logContext ); oldHandler = false; streamsUncaughtExceptionHandler = this::defaultStreamsUncaughtExceptionHandler; delegatingStateRestoreListener = new DelegatingStateRestoreListener(); delegatingStandbyUpdateListener = new DelegatingStandbyUpdateListener(); totalCacheSize = getTotalCacheSize(applicationConfigs); final int numStreamThreads = topologyMetadata.getNumStreamThreads(applicationConfigs); final long cacheSizePerThread = getCacheSizePerThread(numStreamThreads); GlobalStreamThread.State globalThreadState = null; if (hasGlobalTopology) { final String globalThreadId = clientId + "-GlobalStreamThread"; globalStreamThread = new GlobalStreamThread( topologyMetadata.globalTaskTopology(), applicationConfigs, clientSupplier.getGlobalConsumer(applicationConfigs.getGlobalConsumerConfigs(clientId)), stateDirectory, cacheSizePerThread, streamsMetrics, time, globalThreadId, delegatingStateRestoreListener, exception -> defaultStreamsUncaughtExceptionHandler(exception, false) ); globalThreadState = globalStreamThread.state(); } threadState = new HashMap<>(numStreamThreads); streamStateListener = new StreamStateListener(threadState, globalThreadState); final GlobalStateStoreProvider globalStateStoreProvider = new GlobalStateStoreProvider(this.topologyMetadata.globalStateStores()); if (hasGlobalTopology) { globalStreamThread.setStateListener(streamStateListener); } queryableStoreProvider = new QueryableStoreProvider(globalStateStoreProvider); for (int i = 1; i <= numStreamThreads; i++) { createAndAddStreamThread(cacheSizePerThread, i); } stateDirCleaner = setupStateDirCleaner(); rocksDBMetricsRecordingService = maybeCreateRocksDBMetricsRecordingService(clientId, applicationConfigs); } private StreamThread createAndAddStreamThread(final long cacheSizePerThread, final int threadIdx) { final StreamThread streamThread = StreamThread.create( topologyMetadata, applicationConfigs, clientSupplier, adminClient, processId, clientId, streamsMetrics, time, streamsMetadataState, cacheSizePerThread, stateDirectory, delegatingStateRestoreListener, delegatingStandbyUpdateListener, threadIdx, KafkaStreams.this::closeToError, streamsUncaughtExceptionHandler ); streamThread.setStateListener(streamStateListener); threads.add(streamThread); threadState.put(streamThread.getId(), streamThread.state()); queryableStoreProvider.addStoreProviderForThread(streamThread.getName(), new StreamThreadStateStoreProvider(streamThread)); return streamThread; } static Metrics getMetrics(final StreamsConfig config, final Time time, final String clientId) { final MetricConfig metricConfig = new MetricConfig() .samples(config.getInt(StreamsConfig.METRICS_NUM_SAMPLES_CONFIG)) .recordLevel(Sensor.RecordingLevel.forName(config.getString(StreamsConfig.METRICS_RECORDING_LEVEL_CONFIG))) .timeWindow(config.getLong(StreamsConfig.METRICS_SAMPLE_WINDOW_MS_CONFIG), TimeUnit.MILLISECONDS); final List<MetricsReporter> reporters = CommonClientConfigs.metricsReporters(clientId, config); final MetricsContext metricsContext = new KafkaMetricsContext(JMX_PREFIX, config.originalsWithPrefix(CommonClientConfigs.METRICS_CONTEXT_PREFIX)); return new Metrics(metricConfig, reporters, time, metricsContext); } /** * Adds and starts a stream thread in addition to the stream threads that are already running in this * Kafka Streams client. * <p> * Since the number of stream threads increases, the sizes of the caches in the new stream thread * and the existing stream threads are adapted so that the sum of the cache sizes over all stream * threads does not exceed the total cache size specified in configuration * {@link StreamsConfig#STATESTORE_CACHE_MAX_BYTES_CONFIG}. * <p> * Stream threads can only be added if this Kafka Streams client is in state RUNNING or REBALANCING. * * @return name of the added stream thread or empty if a new stream thread could not be added */ public Optional<String> addStreamThread() { if (isRunningOrRebalancing()) { final StreamThread streamThread; synchronized (changeThreadCount) { final int threadIdx = getNextThreadIndex(); final int numLiveThreads = getNumLiveStreamThreads(); final long cacheSizePerThread = getCacheSizePerThread(numLiveThreads + 1); log.info("Adding StreamThread-{}, there will now be {} live threads and the new cache size per thread is {}", threadIdx, numLiveThreads + 1, cacheSizePerThread); resizeThreadCache(cacheSizePerThread); // Creating thread should hold the lock in order to avoid duplicate thread index. // If the duplicate index happen, the metadata of thread may be duplicate too. streamThread = createAndAddStreamThread(cacheSizePerThread, threadIdx); } synchronized (stateLock) { if (isRunningOrRebalancing()) { streamThread.start(); return Optional.of(streamThread.getName()); } else { log.warn("Terminating the new thread because the Kafka Streams client is in state {}", state); streamThread.shutdown(); threads.remove(streamThread); final long cacheSizePerThread = getCacheSizePerThread(getNumLiveStreamThreads()); log.info("Resizing thread cache due to terminating added thread, new cache size per thread is {}", cacheSizePerThread); resizeThreadCache(cacheSizePerThread); return Optional.empty(); } } } else { log.warn("Cannot add a stream thread when Kafka Streams client is in state {}", state); return Optional.empty(); } } /** * Removes one stream thread out of the running stream threads from this Kafka Streams client. * <p> * The removed stream thread is gracefully shut down. This method does not specify which stream * thread is shut down. * <p> * Since the number of stream threads decreases, the sizes of the caches in the remaining stream * threads are adapted so that the sum of the cache sizes over all stream threads equals the total * cache size specified in configuration {@link StreamsConfig#STATESTORE_CACHE_MAX_BYTES_CONFIG}. * * @return name of the removed stream thread or empty if a stream thread could not be removed because * no stream threads are alive */ public Optional<String> removeStreamThread() { return removeStreamThread(Long.MAX_VALUE); } /** * Removes one stream thread out of the running stream threads from this Kafka Streams client. * <p> * The removed stream thread is gracefully shut down. This method does not specify which stream * thread is shut down. * <p> * Since the number of stream threads decreases, the sizes of the caches in the remaining stream * threads are adapted so that the sum of the cache sizes over all stream threads equals the total * cache size specified in configuration {@link StreamsConfig#STATESTORE_CACHE_MAX_BYTES_CONFIG}. * * @param timeout The length of time to wait for the thread to shut down * @throws org.apache.kafka.common.errors.TimeoutException if the thread does not stop in time * @return name of the removed stream thread or empty if a stream thread could not be removed because * no stream threads are alive */ public Optional<String> removeStreamThread(final Duration timeout) { final String msgPrefix = prepareMillisCheckFailMsgPrefix(timeout, "timeout"); final long timeoutMs = validateMillisecondDuration(timeout, msgPrefix); return removeStreamThread(timeoutMs); } private Optional<String> removeStreamThread(final long timeoutMs) throws TimeoutException { final long startMs = time.milliseconds(); if (isRunningOrRebalancing()) { synchronized (changeThreadCount) { // make a copy of threads to avoid holding lock for (final StreamThread streamThread : new ArrayList<>(threads)) { final boolean callingThreadIsNotCurrentStreamThread = !streamThread.getName().equals(Thread.currentThread().getName()); if (streamThread.isThreadAlive() && (callingThreadIsNotCurrentStreamThread || getNumLiveStreamThreads() == 1)) { log.info("Removing StreamThread " + streamThread.getName()); final Optional<String> groupInstanceID = streamThread.getGroupInstanceID(); streamThread.requestLeaveGroupDuringShutdown(); streamThread.shutdown(); if (!streamThread.getName().equals(Thread.currentThread().getName())) { final long remainingTimeMs = timeoutMs - (time.milliseconds() - startMs); if (remainingTimeMs <= 0 || !streamThread.waitOnThreadState(StreamThread.State.DEAD, remainingTimeMs)) { log.warn("{} did not shutdown in the allotted time.", streamThread.getName()); // Don't remove from threads until shutdown is complete. We will trim it from the // list once it reaches DEAD, and if for some reason it's hanging indefinitely in the // shutdown then we should just consider this thread.id to be burned } else { log.info("Successfully removed {} in {}ms", streamThread.getName(), time.milliseconds() - startMs); threads.remove(streamThread); queryableStoreProvider.removeStoreProviderForThread(streamThread.getName()); } } else { log.info("{} is the last remaining thread and must remove itself, therefore we cannot wait " + "for it to complete shutdown as this will result in deadlock.", streamThread.getName()); } final long cacheSizePerThread = getCacheSizePerThread(getNumLiveStreamThreads()); log.info("Resizing thread cache due to thread removal, new cache size per thread is {}", cacheSizePerThread); resizeThreadCache(cacheSizePerThread); if (groupInstanceID.isPresent() && callingThreadIsNotCurrentStreamThread) { final MemberToRemove memberToRemove = new MemberToRemove(groupInstanceID.get()); final Collection<MemberToRemove> membersToRemove = Collections.singletonList(memberToRemove); final RemoveMembersFromConsumerGroupResult removeMembersFromConsumerGroupResult = adminClient.removeMembersFromConsumerGroup( applicationConfigs.getString(StreamsConfig.APPLICATION_ID_CONFIG), new RemoveMembersFromConsumerGroupOptions(membersToRemove) ); try { final long remainingTimeMs = timeoutMs - (time.milliseconds() - startMs); removeMembersFromConsumerGroupResult.memberResult(memberToRemove).get(remainingTimeMs, TimeUnit.MILLISECONDS); } catch (final java.util.concurrent.TimeoutException exception) { log.error( String.format( "Could not remove static member %s from consumer group %s due to a timeout:", groupInstanceID.get(), applicationConfigs.getString(StreamsConfig.APPLICATION_ID_CONFIG) ), exception ); throw new TimeoutException(exception.getMessage(), exception); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); } catch (final ExecutionException exception) { log.error( String.format( "Could not remove static member %s from consumer group %s due to:", groupInstanceID.get(), applicationConfigs.getString(StreamsConfig.APPLICATION_ID_CONFIG) ), exception ); throw new StreamsException( "Could not remove static member " + groupInstanceID.get() + " from consumer group " + applicationConfigs.getString(StreamsConfig.APPLICATION_ID_CONFIG) + " for the following reason: ", exception.getCause() ); } } final long remainingTimeMs = timeoutMs - (time.milliseconds() - startMs); if (remainingTimeMs <= 0) { throw new TimeoutException("Thread " + streamThread.getName() + " did not stop in the allotted time"); } return Optional.of(streamThread.getName()); } } } log.warn("There are no threads eligible for removal"); } else { log.warn("Cannot remove a stream thread when Kafka Streams client is in state " + state()); } return Optional.empty(); } /* * Takes a snapshot and counts the number of stream threads which are not in PENDING_SHUTDOWN or DEAD * * note: iteration over SynchronizedList is not thread safe so it must be manually synchronized. However, we may * require other locks when looping threads and it could cause deadlock. Hence, we create a copy to avoid holding * threads lock when looping threads. * @return number of alive stream threads */ private int getNumLiveStreamThreads() { final AtomicInteger numLiveThreads = new AtomicInteger(0); synchronized (threads) { processStreamThread(thread -> { if (thread.state() == StreamThread.State.DEAD) { log.debug("Trimming thread {} from the threads list since it's state is {}", thread.getName(), StreamThread.State.DEAD); threads.remove(thread); } else if (thread.state() == StreamThread.State.PENDING_SHUTDOWN) { log.debug("Skipping thread {} from num live threads computation since it's state is {}", thread.getName(), StreamThread.State.PENDING_SHUTDOWN); } else { numLiveThreads.incrementAndGet(); } }); return numLiveThreads.get(); } } private int getNextThreadIndex() { final HashSet<String> allLiveThreadNames = new HashSet<>(); final AtomicInteger maxThreadId = new AtomicInteger(1); synchronized (threads) { processStreamThread(thread -> { // trim any DEAD threads from the list so we can reuse the thread.id // this is only safe to do once the thread has fully completed shutdown if (thread.state() == StreamThread.State.DEAD) { threads.remove(thread); } else { allLiveThreadNames.add(thread.getName()); // Assume threads are always named with the "-StreamThread-<threadId>" suffix final int threadId = Integer.parseInt(thread.getName().substring(thread.getName().lastIndexOf("-") + 1)); if (threadId > maxThreadId.get()) { maxThreadId.set(threadId); } } }); final String baseName = clientId + "-StreamThread-"; for (int i = 1; i <= maxThreadId.get(); i++) { final String name = baseName + i; if (!allLiveThreadNames.contains(name)) { return i; } } // It's safe to use threads.size() rather than getNumLiveStreamThreads() to infer the number of threads // here since we trimmed any DEAD threads earlier in this method while holding the lock return threads.size() + 1; } } private long getCacheSizePerThread(final int numStreamThreads) { if (numStreamThreads == 0) { return totalCacheSize; } return totalCacheSize / (numStreamThreads + (topologyMetadata.hasGlobalTopology() ? 1 : 0)); } private void resizeThreadCache(final long cacheSizePerThread) { processStreamThread(thread -> thread.resizeCache(cacheSizePerThread)); if (globalStreamThread != null) { globalStreamThread.resize(cacheSizePerThread); } } private ScheduledExecutorService setupStateDirCleaner() { return Executors.newSingleThreadScheduledExecutor(r -> { final Thread thread = new Thread(r, clientId + "-CleanupThread"); thread.setDaemon(true); return thread; }); } private static ScheduledExecutorService maybeCreateRocksDBMetricsRecordingService(final String clientId, final StreamsConfig config) { if (RecordingLevel.forName(config.getString(StreamsConfig.METRICS_RECORDING_LEVEL_CONFIG)) == RecordingLevel.DEBUG) { return Executors.newSingleThreadScheduledExecutor(r -> { final Thread thread = new Thread(r, clientId + "-RocksDBMetricsRecordingTrigger"); thread.setDaemon(true); return thread; }); } return null; } private static HostInfo parseHostInfo(final String endPoint) { final HostInfo hostInfo = HostInfo.buildFromEndpoint(endPoint); if (hostInfo == null) { return StreamsMetadataState.UNKNOWN_HOST; } else { return hostInfo; } } /** * Start the {@code KafkaStreams} instance by starting all its threads. * This function is expected to be called only once during the life cycle of the client. * <p> * Because threads are started in the background, this method does not block. * However, if you have global stores in your topology, this method blocks until all global stores are restored. * As a consequence, any fatal exception that happens during processing is by default only logged. * If you want to be notified about dying threads, you can * {@link #setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler) register an uncaught exception handler} * before starting the {@code KafkaStreams} instance. * <p> * Note, for brokers with version {@code 0.9.x} or lower, the broker version cannot be checked. * There will be no error and the client will hang and retry to verify the broker version until it * {@link StreamsConfig#REQUEST_TIMEOUT_MS_CONFIG times out}. * @throws IllegalStateException if process was already started * @throws StreamsException if the Kafka brokers have version 0.10.0.x or * if {@link StreamsConfig#PROCESSING_GUARANTEE_CONFIG exactly-once} is enabled for pre 0.11.0.x brokers */ public synchronized void start() throws IllegalStateException, StreamsException { if (setState(State.REBALANCING)) { log.debug("Starting Streams client"); if (globalStreamThread != null) { globalStreamThread.start(); } final int numThreads = processStreamThread(StreamThread::start); log.info("Started {} stream threads", numThreads); final Long cleanupDelay = applicationConfigs.getLong(StreamsConfig.STATE_CLEANUP_DELAY_MS_CONFIG); stateDirCleaner.scheduleAtFixedRate(() -> { // we do not use lock here since we only read on the value and act on it if (state == State.RUNNING) { stateDirectory.cleanRemovedTasks(cleanupDelay); } }, cleanupDelay, cleanupDelay, TimeUnit.MILLISECONDS); final long recordingDelay = 0; final long recordingInterval = 1; if (rocksDBMetricsRecordingService != null) { rocksDBMetricsRecordingService.scheduleAtFixedRate( streamsMetrics.rocksDBMetricsRecordingTrigger(), recordingDelay, recordingInterval, TimeUnit.MINUTES ); } } else { throw new IllegalStateException("The client is either already started or already stopped, cannot re-start"); } } /** * Class that handles options passed in case of {@code KafkaStreams} instance scale down */ public static class CloseOptions { private Duration timeout = Duration.ofMillis(Long.MAX_VALUE); private boolean leaveGroup = false; public CloseOptions timeout(final Duration timeout) { this.timeout = timeout; return this; } public CloseOptions leaveGroup(final boolean leaveGroup) { this.leaveGroup = leaveGroup; return this; } } /** * Shutdown this {@code KafkaStreams} instance by signaling all the threads to stop, and then wait for them to join. * This will block until all threads have stopped. */ public void close() { close(Long.MAX_VALUE, false); } private Thread shutdownHelper(final boolean error, final long timeoutMs, final boolean leaveGroup) { stateDirCleaner.shutdownNow(); if (rocksDBMetricsRecordingService != null) { rocksDBMetricsRecordingService.shutdownNow(); } // wait for all threads to join in a separate thread; // save the current thread so that if it is a stream thread // we don't attempt to join it and cause a deadlock return new Thread(() -> { // notify all the threads to stop; avoid deadlocks by stopping any // further state reports from the thread since we're shutting down int numStreamThreads = processStreamThread(StreamThread::shutdown); log.info("Shutting down {} stream threads", numStreamThreads); topologyMetadata.wakeupThreads(); numStreamThreads = processStreamThread(thread -> { try { if (!thread.isRunning()) { log.debug("Shutdown {} complete", thread.getName()); thread.join(); } } catch (final InterruptedException ex) { log.warn("Shutdown {} interrupted", thread.getName()); Thread.currentThread().interrupt(); } }); if (leaveGroup) { processStreamThread(streamThreadLeaveConsumerGroup(timeoutMs)); } log.info("Shutdown {} stream threads complete", numStreamThreads); if (globalStreamThread != null) { log.info("Shutting down the global stream threads"); globalStreamThread.shutdown(); } if (globalStreamThread != null && !globalStreamThread.stillRunning()) { try { globalStreamThread.join(); } catch (final InterruptedException e) { log.warn("Shutdown the global stream thread interrupted"); Thread.currentThread().interrupt(); } globalStreamThread = null; log.info("Shutdown global stream threads complete"); } stateDirectory.close(); adminClient.close(); streamsMetrics.removeAllClientLevelSensorsAndMetrics(); metrics.close(); if (!error) { setState(State.NOT_RUNNING); } else { setState(State.ERROR); } }, clientId + "-CloseThread"); } private boolean close(final long timeoutMs, final boolean leaveGroup) { if (state.hasCompletedShutdown()) { log.info("Streams client is already in the terminal {} state, all resources are closed and the client has stopped.", state); return true; } if (state.isShuttingDown()) { log.info("Streams client is in {}, all resources are being closed and the client will be stopped.", state); if (state == State.PENDING_ERROR && waitOnState(State.ERROR, timeoutMs)) { log.info("Streams client stopped to ERROR completely"); return true; } else if (state == State.PENDING_SHUTDOWN && waitOnState(State.NOT_RUNNING, timeoutMs)) { log.info("Streams client stopped to NOT_RUNNING completely"); return true; } else { log.warn("Streams client cannot transition to {} completely within the timeout", state == State.PENDING_SHUTDOWN ? State.NOT_RUNNING : State.ERROR); return false; } } if (!setState(State.PENDING_SHUTDOWN)) { // if we can't transition to PENDING_SHUTDOWN but not because we're already shutting down, then it must be fatal log.error("Failed to transition to PENDING_SHUTDOWN, current state is {}", state); throw new StreamsException("Failed to shut down while in state " + state); } else { final Thread shutdownThread = shutdownHelper(false, timeoutMs, leaveGroup); shutdownThread.setDaemon(true); shutdownThread.start(); } if (waitOnState(State.NOT_RUNNING, timeoutMs)) { log.info("Streams client stopped completely"); return true; } else { log.info("Streams client cannot stop completely within the {}ms timeout", timeoutMs); return false; } } private void closeToError() { if (!setState(State.PENDING_ERROR)) { log.info("Skipping shutdown since we are already in " + state()); } else { final Thread shutdownThread = shutdownHelper(true, -1, false); shutdownThread.setDaemon(true); shutdownThread.start(); } } /** * Shutdown this {@code KafkaStreams} by signaling all the threads to stop, and then wait up to the timeout for the * threads to join. * A {@code timeout} of Duration.ZERO (or any other zero duration) makes the close operation asynchronous. * Negative-duration timeouts are rejected. * * @param timeout how long to wait for the threads to shutdown * @return {@code true} if all threads were successfully stopped&mdash;{@code false} if the timeout was reached * before all threads stopped * Note that this method must not be called in the {@link StateListener#onChange(KafkaStreams.State, KafkaStreams.State)} callback of {@link StateListener}. * @throws IllegalArgumentException if {@code timeout} can't be represented as {@code long milliseconds} */ public synchronized boolean close(final Duration timeout) throws IllegalArgumentException { final String msgPrefix = prepareMillisCheckFailMsgPrefix(timeout, "timeout"); final long timeoutMs = validateMillisecondDuration(timeout, msgPrefix); if (timeoutMs < 0) { throw new IllegalArgumentException("Timeout can't be negative."); } log.debug("Stopping Streams client with timeoutMillis = {} ms.", timeoutMs); return close(timeoutMs, false); } /** * Shutdown this {@code KafkaStreams} by signaling all the threads to stop, and then wait up to the timeout for the * threads to join. * @param options contains timeout to specify how long to wait for the threads to shutdown, and a flag leaveGroup to * trigger consumer leave call * @return {@code true} if all threads were successfully stopped&mdash;{@code false} if the timeout was reached * before all threads stopped * Note that this method must not be called in the {@link StateListener#onChange(KafkaStreams.State, KafkaStreams.State)} callback of {@link StateListener}. * @throws IllegalArgumentException if {@code timeout} can't be represented as {@code long milliseconds} */ public synchronized boolean close(final CloseOptions options) throws IllegalArgumentException { Objects.requireNonNull(options, "options cannot be null"); final String msgPrefix = prepareMillisCheckFailMsgPrefix(options.timeout, "timeout"); final long timeoutMs = validateMillisecondDuration(options.timeout, msgPrefix); if (timeoutMs < 0) { throw new IllegalArgumentException("Timeout can't be negative."); } log.debug("Stopping Streams client with timeoutMillis = {} ms.", timeoutMs); return close(timeoutMs, options.leaveGroup); } private Consumer<StreamThread> streamThreadLeaveConsumerGroup(final long remainingTimeMs) { return thread -> { final Optional<String> groupInstanceId = thread.getGroupInstanceID(); if (groupInstanceId.isPresent()) { log.debug("Sending leave group trigger to removing instance from consumer group: {}.", groupInstanceId.get()); final MemberToRemove memberToRemove = new MemberToRemove(groupInstanceId.get()); final Collection<MemberToRemove> membersToRemove = Collections.singletonList(memberToRemove); final RemoveMembersFromConsumerGroupResult removeMembersFromConsumerGroupResult = adminClient .removeMembersFromConsumerGroup( applicationConfigs.getString(StreamsConfig.APPLICATION_ID_CONFIG), new RemoveMembersFromConsumerGroupOptions(membersToRemove) ); try { removeMembersFromConsumerGroupResult.memberResult(memberToRemove) .get(remainingTimeMs, TimeUnit.MILLISECONDS); } catch (final Exception e) { final String msg = String.format("Could not remove static member %s from consumer group %s.", groupInstanceId.get(), applicationConfigs.getString(StreamsConfig.APPLICATION_ID_CONFIG)); log.error(msg, e); } } }; } /** * Do a clean up of the local {@link StateStore} directory ({@link StreamsConfig#STATE_DIR_CONFIG}) by deleting all * data with regard to the {@link StreamsConfig#APPLICATION_ID_CONFIG application ID}. * <p> * May only be called either before this {@code KafkaStreams} instance is {@link #start() started} or after the * instance is {@link #close() closed}. * <p> * Calling this method triggers a restore of local {@link StateStore}s on the next {@link #start() application start}. * * @throws IllegalStateException if this {@code KafkaStreams} instance has been started and hasn't fully shut down * @throws StreamsException if cleanup failed */ public void cleanUp() { if (!(state.hasNotStarted() || state.hasCompletedShutdown())) { throw new IllegalStateException("Cannot clean up while running."); } stateDirectory.clean(); } /** * Find all currently running {@code KafkaStreams} instances (potentially remotely) that use the same * {@link StreamsConfig#APPLICATION_ID_CONFIG application ID} as this instance (i.e., all instances that belong to * the same Kafka Streams application) and return {@link StreamsMetadata} for each discovered instance. * <p> * Note: this is a point in time view and it may change due to partition reassignment. * * @return {@link StreamsMetadata} for each {@code KafkaStreams} instances of this application * @deprecated since 3.0.0 use {@link KafkaStreams#metadataForAllStreamsClients} */ @Deprecated public Collection<org.apache.kafka.streams.state.StreamsMetadata> allMetadata() { validateIsRunningOrRebalancing(); return streamsMetadataState.getAllMetadata().stream().map(streamsMetadata -> new org.apache.kafka.streams.state.StreamsMetadata(streamsMetadata.hostInfo(), streamsMetadata.stateStoreNames(), streamsMetadata.topicPartitions(), streamsMetadata.standbyStateStoreNames(), streamsMetadata.standbyTopicPartitions())) .collect(Collectors.toSet()); } /** * Find all currently running {@code KafkaStreams} instances (potentially remotely) that use the same * {@link StreamsConfig#APPLICATION_ID_CONFIG application ID} as this instance (i.e., all instances that belong to * the same Kafka Streams application) and return {@link StreamsMetadata} for each discovered instance. * <p> * Note: this is a point in time view and it may change due to partition reassignment. * * @return {@link StreamsMetadata} for each {@code KafkaStreams} instances of this application */ public Collection<StreamsMetadata> metadataForAllStreamsClients() { validateIsRunningOrRebalancing(); return streamsMetadataState.getAllMetadata(); } /** * Find all currently running {@code KafkaStreams} instances (potentially remotely) that * <ul> * <li>use the same {@link StreamsConfig#APPLICATION_ID_CONFIG application ID} as this instance (i.e., all * instances that belong to the same Kafka Streams application)</li> * <li>and that contain a {@link StateStore} with the given {@code storeName}</li> * </ul> * and return {@link StreamsMetadata} for each discovered instance. * <p> * Note: this is a point in time view and it may change due to partition reassignment. * * @param storeName the {@code storeName} to find metadata for * @return {@link StreamsMetadata} for each {@code KafkaStreams} instances with the provide {@code storeName} of * this application * @deprecated since 3.0.0 use {@link KafkaStreams#streamsMetadataForStore} instead */ @Deprecated public Collection<org.apache.kafka.streams.state.StreamsMetadata> allMetadataForStore(final String storeName) { validateIsRunningOrRebalancing(); return streamsMetadataState.getAllMetadataForStore(storeName).stream().map(streamsMetadata -> new org.apache.kafka.streams.state.StreamsMetadata(streamsMetadata.hostInfo(), streamsMetadata.stateStoreNames(), streamsMetadata.topicPartitions(), streamsMetadata.standbyStateStoreNames(), streamsMetadata.standbyTopicPartitions())) .collect(Collectors.toSet()); } /** * Find all currently running {@code KafkaStreams} instances (potentially remotely) that * <ul> * <li>use the same {@link StreamsConfig#APPLICATION_ID_CONFIG application ID} as this instance (i.e., all * instances that belong to the same Kafka Streams application)</li> * <li>and that contain a {@link StateStore} with the given {@code storeName}</li> * </ul> * and return {@link StreamsMetadata} for each discovered instance. * <p> * Note: this is a point in time view and it may change due to partition reassignment. * * @param storeName the {@code storeName} to find metadata for * @return {@link StreamsMetadata} for each {@code KafkaStreams} instances with the provide {@code storeName} of * this application */ public Collection<StreamsMetadata> streamsMetadataForStore(final String storeName) { validateIsRunningOrRebalancing(); return streamsMetadataState.getAllMetadataForStore(storeName); } /** * Finds the metadata containing the active hosts and standby hosts where the key being queried would reside. * * @param storeName the {@code storeName} to find metadata for * @param key the key to find metadata for * @param keySerializer serializer for the key * @param <K> key type * Returns {@link KeyQueryMetadata} containing all metadata about hosting the given key for the given store, * or {@code null} if no matching metadata could be found. */ public <K> KeyQueryMetadata queryMetadataForKey(final String storeName, final K key, final Serializer<K> keySerializer) { validateIsRunningOrRebalancing(); return streamsMetadataState.getKeyQueryMetadataForKey(storeName, key, keySerializer); } /** * Finds the metadata containing the active hosts and standby hosts where the key being queried would reside. * * @param storeName the {@code storeName} to find metadata for * @param key the key to find metadata for * @param partitioner the partitioner to be use to locate the host for the key * @param <K> key type * Returns {@link KeyQueryMetadata} containing all metadata about hosting the given key for the given store, using the * the supplied partitioner, or {@code null} if no matching metadata could be found. */ public <K> KeyQueryMetadata queryMetadataForKey(final String storeName, final K key, final StreamPartitioner<? super K, ?> partitioner) { validateIsRunningOrRebalancing(); return streamsMetadataState.getKeyQueryMetadataForKey(storeName, key, partitioner); } /** * Get a facade wrapping the local {@link StateStore} instances with the provided {@link StoreQueryParameters}. * The returned object can be used to query the {@link StateStore} instances. * * @param storeQueryParameters the parameters used to fetch a queryable store * @return A facade wrapping the local {@link StateStore} instances * @throws StreamsNotStartedException If Streams has not yet been started. Just call {@link KafkaStreams#start()} * and then retry this call. * @throws UnknownStateStoreException If the specified store name does not exist in the topology. * @throws InvalidStateStorePartitionException If the specified partition does not exist. * @throws InvalidStateStoreException If the Streams instance isn't in a queryable state. * If the store's type does not match the QueryableStoreType, * the Streams instance is not in a queryable state with respect * to the parameters, or if the store is not available locally, then * an InvalidStateStoreException is thrown upon store access. */ public <T> T store(final StoreQueryParameters<T> storeQueryParameters) { validateIsRunningOrRebalancing(); final String storeName = storeQueryParameters.storeName(); if (!topologyMetadata.hasStore(storeName)) { throw new UnknownStateStoreException( "Cannot get state store " + storeName + " because no such store is registered in the topology." ); } return queryableStoreProvider.getStore(storeQueryParameters); } /** * This method pauses processing for the KafkaStreams instance. * * <p>Paused topologies will only skip over a) processing, b) punctuation, and c) standby tasks. * Notably, paused topologies will still poll Kafka consumers, and commit offsets. * This method sets transient state that is not maintained or managed among instances. * Note that pause() can be called before start() in order to start a KafkaStreams instance * in a manner where the processing is paused as described, but the consumers are started up. */ public void pause() { if (topologyMetadata.hasNamedTopologies()) { for (final NamedTopology namedTopology : topologyMetadata.getAllNamedTopologies()) { topologyMetadata.pauseTopology(namedTopology.name()); } } else { topologyMetadata.pauseTopology(UNNAMED_TOPOLOGY); } } /** * @return true when the KafkaStreams instance has its processing paused. */ public boolean isPaused() { if (topologyMetadata.hasNamedTopologies()) { return topologyMetadata.getAllNamedTopologies().stream() .map(NamedTopology::name) .allMatch(topologyMetadata::isPaused); } else { return topologyMetadata.isPaused(UNNAMED_TOPOLOGY); } } /** * This method resumes processing for the KafkaStreams instance. */ public void resume() { if (topologyMetadata.hasNamedTopologies()) { for (final NamedTopology namedTopology : topologyMetadata.getAllNamedTopologies()) { topologyMetadata.resumeTopology(namedTopology.name()); } } else { topologyMetadata.resumeTopology(UNNAMED_TOPOLOGY); } threads.forEach(StreamThread::signalResume); } /** * handle each stream thread in a snapshot of threads. * noted: iteration over SynchronizedList is not thread safe so it must be manually synchronized. However, we may * require other locks when looping threads and it could cause deadlock. Hence, we create a copy to avoid holding * threads lock when looping threads. * @param consumer handler */ protected int processStreamThread(final Consumer<StreamThread> consumer) { final List<StreamThread> copy = new ArrayList<>(threads); for (final StreamThread thread : copy) consumer.accept(thread); return copy.size(); } /** * Returns the internal clients' assigned {@code client instance ids}. * * @return The internal clients' assigned instance ids used for metrics collection. * * @throws IllegalArgumentException If {@code timeout} is negative. * @throws IllegalStateException If {@code KafkaStreams} is not running. * @throws TimeoutException Indicates that a request timed out. * @throws StreamsException For any other error that might occur. */ public synchronized ClientInstanceIds clientInstanceIds(final Duration timeout) { if (timeout.isNegative()) { throw new IllegalArgumentException("The timeout cannot be negative."); } if (state().hasNotStarted()) { throw new IllegalStateException("KafkaStreams has not been started, you can retry after calling start()."); } if (state().isShuttingDown() || state.hasCompletedShutdown()) { throw new IllegalStateException("KafkaStreams has been stopped (" + state + ")."); } final Timer remainingTime = time.timer(timeout.toMillis()); final ClientInstanceIdsImpl clientInstanceIds = new ClientInstanceIdsImpl(); // (1) fan-out calls to threads // StreamThread for main/restore consumers and producer(s) final Map<String, KafkaFuture<Uuid>> consumerFutures = new HashMap<>(); final Map<String, KafkaFuture<Map<String, KafkaFuture<Uuid>>>> producerFutures = new HashMap<>(); synchronized (changeThreadCount) { for (final StreamThread streamThread : threads) { consumerFutures.putAll(streamThread.consumerClientInstanceIds(timeout)); producerFutures.put(streamThread.getName(), streamThread.producersClientInstanceIds(timeout)); } } // GlobalThread KafkaFuture<Uuid> globalThreadFuture = null; if (globalStreamThread != null) { globalThreadFuture = globalStreamThread.globalConsumerInstanceId(timeout); } // (2) get admin client instance id in a blocking fashion, while Stream/GlobalThreads work in parallel try { clientInstanceIds.setAdminInstanceId(adminClient.clientInstanceId(timeout)); remainingTime.update(time.milliseconds()); } catch (final IllegalStateException telemetryDisabledError) { // swallow log.debug("Telemetry is disabled on the admin client."); } catch (final TimeoutException timeoutException) { throw timeoutException; } catch (final Exception error) { throw new StreamsException("Could not retrieve admin client instance id.", error); } // (3) collect client instance ids from threads // (3a) collect consumers from StreamsThread for (final Map.Entry<String, KafkaFuture<Uuid>> consumerFuture : consumerFutures.entrySet()) { final Uuid instanceId = getOrThrowException( consumerFuture.getValue(), remainingTime.remainingMs(), () -> String.format( "Could not retrieve consumer instance id for %s.", consumerFuture.getKey() ) ); remainingTime.update(time.milliseconds()); // could be `null` if telemetry is disabled on the consumer itself if (instanceId != null) { clientInstanceIds.addConsumerInstanceId( consumerFuture.getKey(), instanceId ); } else { log.debug(String.format("Telemetry is disabled for %s.", consumerFuture.getKey())); } } // (3b) collect producers from StreamsThread for (final Map.Entry<String, KafkaFuture<Map<String, KafkaFuture<Uuid>>>> threadProducerFuture : producerFutures.entrySet()) { final Map<String, KafkaFuture<Uuid>> streamThreadProducerFutures = getOrThrowException( threadProducerFuture.getValue(), remainingTime.remainingMs(), () -> String.format( "Could not retrieve producer instance id for %s.", threadProducerFuture.getKey() ) ); remainingTime.update(time.milliseconds()); for (final Map.Entry<String, KafkaFuture<Uuid>> producerFuture : streamThreadProducerFutures.entrySet()) { final Uuid instanceId = getOrThrowException( producerFuture.getValue(), remainingTime.remainingMs(), () -> String.format( "Could not retrieve producer instance id for %s.", producerFuture.getKey() ) ); remainingTime.update(time.milliseconds()); // could be `null` if telemetry is disabled on the producer itself if (instanceId != null) { clientInstanceIds.addProducerInstanceId( producerFuture.getKey(), instanceId ); } else { log.debug(String.format("Telemetry is disabled for %s.", producerFuture.getKey())); } } } // (3c) collect from GlobalThread if (globalThreadFuture != null) { final Uuid instanceId = getOrThrowException( globalThreadFuture, remainingTime.remainingMs(), () -> "Could not retrieve global consumer client instance id." ); remainingTime.update(time.milliseconds()); // could be `null` if telemetry is disabled on the client itself if (instanceId != null) { clientInstanceIds.addConsumerInstanceId( globalStreamThread.getName(), instanceId ); } else { log.debug("Telemetry is disabled for the global consumer."); } } return clientInstanceIds; } private <T> T getOrThrowException( final KafkaFuture<T> future, final long timeoutMs, final Supplier<String> errorMessage) { final Throwable cause; try { return future.get(timeoutMs, TimeUnit.MILLISECONDS); } catch (final java.util.concurrent.TimeoutException timeout) { throw new TimeoutException(errorMessage.get(), timeout); } catch (final ExecutionException exception) { cause = exception.getCause(); if (cause instanceof TimeoutException) { throw (TimeoutException) cause; } } catch (final InterruptedException error) { cause = error; } throw new StreamsException(errorMessage.get(), cause); } /** * Returns runtime information about the local threads of this {@link KafkaStreams} instance. * * @return the set of {@link org.apache.kafka.streams.processor.ThreadMetadata}. * @deprecated since 3.0 use {@link #metadataForLocalThreads()} */ @Deprecated public Set<org.apache.kafka.streams.processor.ThreadMetadata> localThreadsMetadata() { return metadataForLocalThreads().stream().map(threadMetadata -> new org.apache.kafka.streams.processor.ThreadMetadata( threadMetadata.threadName(), threadMetadata.threadState(), threadMetadata.consumerClientId(), threadMetadata.restoreConsumerClientId(), threadMetadata.producerClientIds(), threadMetadata.adminClientId(), threadMetadata.activeTasks().stream().map(taskMetadata -> new org.apache.kafka.streams.processor.TaskMetadata( taskMetadata.taskId().toString(), taskMetadata.topicPartitions(), taskMetadata.committedOffsets(), taskMetadata.endOffsets(), taskMetadata.timeCurrentIdlingStarted()) ).collect(Collectors.toSet()), threadMetadata.standbyTasks().stream().map(taskMetadata -> new org.apache.kafka.streams.processor.TaskMetadata( taskMetadata.taskId().toString(), taskMetadata.topicPartitions(), taskMetadata.committedOffsets(), taskMetadata.endOffsets(), taskMetadata.timeCurrentIdlingStarted()) ).collect(Collectors.toSet()))) .collect(Collectors.toSet()); } /** * Returns runtime information about the local threads of this {@link KafkaStreams} instance. * * @return the set of {@link ThreadMetadata}. */ public Set<ThreadMetadata> metadataForLocalThreads() { final Set<ThreadMetadata> threadMetadata = new HashSet<>(); processStreamThread(thread -> { synchronized (thread.getStateLock()) { if (thread.state() != StreamThread.State.DEAD) { threadMetadata.add(thread.threadMetadata()); } } }); return threadMetadata; } /** * Returns {@link LagInfo}, for all store partitions (active or standby) local to this Streams instance. Note that the * values returned are just estimates and meant to be used for making soft decisions on whether the data in the store * partition is fresh enough for querying. * * <p>Note: Each invocation of this method issues a call to the Kafka brokers. Thus, it's advisable to limit the frequency * of invocation to once every few seconds. * * @return map of store names to another map of partition to {@link LagInfo}s * @throws StreamsException if the admin client request throws exception */ public Map<String, Map<Integer, LagInfo>> allLocalStorePartitionLags() { final List<Task> allTasks = new ArrayList<>(); processStreamThread(thread -> allTasks.addAll(thread.readyOnlyAllTasks())); return allLocalStorePartitionLags(allTasks); } protected Map<String, Map<Integer, LagInfo>> allLocalStorePartitionLags(final List<Task> tasksToCollectLagFor) { final Map<String, Map<Integer, LagInfo>> localStorePartitionLags = new TreeMap<>(); final Collection<TopicPartition> allPartitions = new LinkedList<>(); final Map<TopicPartition, Long> allChangelogPositions = new HashMap<>(); // Obtain the current positions, of all the active-restoring and standby tasks for (final Task task : tasksToCollectLagFor) { allPartitions.addAll(task.changelogPartitions()); // Note that not all changelog partitions, will have positions; since some may not have started allChangelogPositions.putAll(task.changelogOffsets()); } log.debug("Current changelog positions: {}", allChangelogPositions); final Map<TopicPartition, ListOffsetsResultInfo> allEndOffsets; allEndOffsets = fetchEndOffsets(allPartitions, adminClient); log.debug("Current end offsets :{}", allEndOffsets); for (final Map.Entry<TopicPartition, ListOffsetsResultInfo> entry : allEndOffsets.entrySet()) { // Avoiding an extra admin API lookup by computing lags for not-yet-started restorations // from zero instead of the real "earliest offset" for the changelog. // This will yield the correct relative order of lagginess for the tasks in the cluster, // but it is an over-estimate of how much work remains to restore the task from scratch. final long earliestOffset = 0L; final long changelogPosition = allChangelogPositions.getOrDefault(entry.getKey(), earliestOffset); final long latestOffset = entry.getValue().offset(); final LagInfo lagInfo = new LagInfo(changelogPosition == Task.LATEST_OFFSET ? latestOffset : changelogPosition, latestOffset); final String storeName = streamsMetadataState.getStoreForChangelogTopic(entry.getKey().topic()); localStorePartitionLags.computeIfAbsent(storeName, ignored -> new TreeMap<>()) .put(entry.getKey().partition(), lagInfo); } return Collections.unmodifiableMap(localStorePartitionLags); } /** * Run an interactive query against a state store. * <p> * This method allows callers outside of the Streams runtime to access the internal state of * stateful processors. See <a href="https://kafka.apache.org/documentation/streams/developer-guide/interactive-queries.html">IQ docs</a> * for more information. * <p> * NOTICE: This functionality is {@link Evolving} and subject to change in minor versions. * Once it is stabilized, this notice and the evolving annotation will be removed. * * @param <R> The result type specified by the query. * @throws StreamsNotStartedException If Streams has not yet been started. Just call {@link * KafkaStreams#start()} and then retry this call. * @throws StreamsStoppedException If Streams is in a terminal state like PENDING_SHUTDOWN, * NOT_RUNNING, PENDING_ERROR, or ERROR. The caller should * discover a new instance to query. * @throws UnknownStateStoreException If the specified store name does not exist in the * topology. */ @Evolving public <R> StateQueryResult<R> query(final StateQueryRequest<R> request) { final String storeName = request.getStoreName(); if (!topologyMetadata.hasStore(storeName)) { throw new UnknownStateStoreException( "Cannot get state store " + storeName + " because no such store is registered in the topology." ); } if (state().hasNotStarted()) { throw new StreamsNotStartedException( "KafkaStreams has not been started, you can retry after calling start()." ); } if (state().isShuttingDown() || state.hasCompletedShutdown()) { throw new StreamsStoppedException( "KafkaStreams has been stopped (" + state + ")." + " This instance can no longer serve queries." ); } final StateQueryResult<R> result = new StateQueryResult<>(); final Map<String, StateStore> globalStateStores = topologyMetadata.globalStateStores(); if (globalStateStores.containsKey(storeName)) { // See KAFKA-13523 result.setGlobalResult( QueryResult.forFailure( FailureReason.UNKNOWN_QUERY_TYPE, "Global stores do not yet support the KafkaStreams#query API. Use KafkaStreams#store instead." ) ); } else { for (final StreamThread thread : threads) { final Set<Task> tasks = thread.readyOnlyAllTasks(); for (final Task task : tasks) { final TaskId taskId = task.id(); final int partition = taskId.partition(); if (request.isAllPartitions() || request.getPartitions().contains(partition)) { final StateStore store = task.getStore(storeName); if (store != null) { final StreamThread.State state = thread.state(); final boolean active = task.isActive(); if (request.isRequireActive() && (state != StreamThread.State.RUNNING || !active)) { result.addResult( partition, QueryResult.forFailure( FailureReason.NOT_ACTIVE, "Query requires a running active task," + " but partition was in state " + state + " and was " + (active ? "active" : "not active") + "." ) ); } else { final QueryResult<R> r = store.query( request.getQuery(), request.isRequireActive() ? PositionBound.unbounded() : request.getPositionBound(), new QueryConfig(request.executionInfoEnabled()) ); result.addResult(partition, r); } // optimization: if we have handled all the requested partitions, // we can return right away. if (!request.isAllPartitions() && result.getPartitionResults().keySet().containsAll(request.getPartitions())) { return result; } } } } } } if (!request.isAllPartitions()) { for (final Integer partition : request.getPartitions()) { if (!result.getPartitionResults().containsKey(partition)) { result.addResult(partition, QueryResult.forFailure( FailureReason.NOT_PRESENT, "The requested partition was not present at the time of the query." )); } } } return result; } }
apache/kafka
streams/src/main/java/org/apache/kafka/streams/KafkaStreams.java
44,935
package org.opencv.android; import java.util.List; import org.opencv.BuildConfig; import org.opencv.R; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.Size; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import android.util.AttributeSet; import android.util.Log; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.WindowManager; /** * This is a basic class, implementing the interaction with Camera and OpenCV library. * The main responsibility of it - is to control when camera can be enabled, process the frame, * call external listener to make any adjustments to the frame and then draw the resulting * frame to the screen. * The clients shall implement CvCameraViewListener. */ public abstract class CameraBridgeViewBase extends SurfaceView implements SurfaceHolder.Callback { private static final String TAG = "CameraBridge"; protected static final int MAX_UNSPECIFIED = -1; private static final int STOPPED = 0; private static final int STARTED = 1; private int mState = STOPPED; private Bitmap mCacheBitmap; private CvCameraViewListener2 mListener; private boolean mSurfaceExist; private final Object mSyncObject = new Object(); protected int mFrameWidth; protected int mFrameHeight; protected int mMaxHeight; protected int mMaxWidth; protected float mScale = 0; protected int mPreviewFormat = RGBA; protected int mCameraIndex = CAMERA_ID_ANY; protected boolean mEnabled; protected boolean mCameraPermissionGranted = false; protected FpsMeter mFpsMeter = null; public static final int CAMERA_ID_ANY = -1; public static final int CAMERA_ID_BACK = 99; public static final int CAMERA_ID_FRONT = 98; public static final int RGBA = 1; public static final int GRAY = 2; public CameraBridgeViewBase(Context context, int cameraId) { super(context); mCameraIndex = cameraId; getHolder().addCallback(this); mMaxWidth = MAX_UNSPECIFIED; mMaxHeight = MAX_UNSPECIFIED; } public CameraBridgeViewBase(Context context, AttributeSet attrs) { super(context, attrs); int count = attrs.getAttributeCount(); Log.d(TAG, "Attr count: " + Integer.valueOf(count)); TypedArray styledAttrs = getContext().obtainStyledAttributes(attrs, R.styleable.CameraBridgeViewBase); if (styledAttrs.getBoolean(R.styleable.CameraBridgeViewBase_show_fps, false)) enableFpsMeter(); mCameraIndex = styledAttrs.getInt(R.styleable.CameraBridgeViewBase_camera_id, -1); getHolder().addCallback(this); mMaxWidth = MAX_UNSPECIFIED; mMaxHeight = MAX_UNSPECIFIED; styledAttrs.recycle(); } /** * Sets the camera index * @param cameraIndex new camera index */ public void setCameraIndex(int cameraIndex) { this.mCameraIndex = cameraIndex; } public interface CvCameraViewListener { /** * This method is invoked when camera preview has started. After this method is invoked * the frames will start to be delivered to client via the onCameraFrame() callback. * @param width - the width of the frames that will be delivered * @param height - the height of the frames that will be delivered */ public void onCameraViewStarted(int width, int height); /** * This method is invoked when camera preview has been stopped for some reason. * No frames will be delivered via onCameraFrame() callback after this method is called. */ public void onCameraViewStopped(); /** * This method is invoked when delivery of the frame needs to be done. * The returned values - is a modified frame which needs to be displayed on the screen. * TODO: pass the parameters specifying the format of the frame (BPP, YUV or RGB and etc) */ public Mat onCameraFrame(Mat inputFrame); } public interface CvCameraViewListener2 { /** * This method is invoked when camera preview has started. After this method is invoked * the frames will start to be delivered to client via the onCameraFrame() callback. * @param width - the width of the frames that will be delivered * @param height - the height of the frames that will be delivered */ public void onCameraViewStarted(int width, int height); /** * This method is invoked when camera preview has been stopped for some reason. * No frames will be delivered via onCameraFrame() callback after this method is called. */ public void onCameraViewStopped(); /** * This method is invoked when delivery of the frame needs to be done. * The returned values - is a modified frame which needs to be displayed on the screen. * TODO: pass the parameters specifying the format of the frame (BPP, YUV or RGB and etc) */ public Mat onCameraFrame(CvCameraViewFrame inputFrame); }; protected class CvCameraViewListenerAdapter implements CvCameraViewListener2 { public CvCameraViewListenerAdapter(CvCameraViewListener oldStypeListener) { mOldStyleListener = oldStypeListener; } public void onCameraViewStarted(int width, int height) { mOldStyleListener.onCameraViewStarted(width, height); } public void onCameraViewStopped() { mOldStyleListener.onCameraViewStopped(); } public Mat onCameraFrame(CvCameraViewFrame inputFrame) { Mat result = null; switch (mPreviewFormat) { case RGBA: result = mOldStyleListener.onCameraFrame(inputFrame.rgba()); break; case GRAY: result = mOldStyleListener.onCameraFrame(inputFrame.gray()); break; default: Log.e(TAG, "Invalid frame format! Only RGBA and Gray Scale are supported!"); }; return result; } public void setFrameFormat(int format) { mPreviewFormat = format; } private int mPreviewFormat = RGBA; private CvCameraViewListener mOldStyleListener; }; /** * This class interface is abstract representation of single frame from camera for onCameraFrame callback * Attention: Do not use objects, that represents this interface out of onCameraFrame callback! */ public interface CvCameraViewFrame { /** * This method returns RGBA Mat with frame */ public Mat rgba(); /** * This method returns single channel gray scale Mat with frame */ public Mat gray(); public void release(); }; public class RotatedCameraFrame implements CvCameraViewFrame { @Override public Mat gray() { if (mRotation != 0) { Core.rotate(mFrame.gray(), mGrayRotated, getCvRotationCode(mRotation)); return mGrayRotated; } else { return mFrame.gray(); } } @Override public Mat rgba() { if (mRotation != 0) { Core.rotate(mFrame.rgba(), mRgbaRotated, getCvRotationCode(mRotation)); return mRgbaRotated; } else { return mFrame.rgba(); } } private int getCvRotationCode(int degrees) { if (degrees == 90) { return Core.ROTATE_90_CLOCKWISE; } else if (degrees == 180) { return Core.ROTATE_180; } else { return Core.ROTATE_90_COUNTERCLOCKWISE; } } public RotatedCameraFrame(CvCameraViewFrame frame, int rotation) { super(); mFrame = frame; mRgbaRotated = new Mat(); mGrayRotated = new Mat(); mRotation = rotation; } @Override public void release() { mRgbaRotated.release(); mGrayRotated.release(); } public CvCameraViewFrame mFrame; private Mat mRgbaRotated; private Mat mGrayRotated; private int mRotation; }; /** * Calculates how to rotate camera frame to match current screen orientation */ protected int getFrameRotation(boolean cameraFacingFront, int cameraSensorOrientation) { WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); int screenOrientation = windowManager.getDefaultDisplay().getRotation(); int screenRotation = 0; switch (screenOrientation) { case Surface.ROTATION_0: screenRotation = 0; break; case Surface.ROTATION_90: screenRotation = 90; break; case Surface.ROTATION_180: screenRotation = 180; break; case Surface.ROTATION_270: screenRotation = 270; break; } int frameRotation; if (cameraFacingFront) { frameRotation = (cameraSensorOrientation + screenRotation) % 360; } else { frameRotation = (cameraSensorOrientation - screenRotation + 360) % 360; } return frameRotation; } public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) { Log.d(TAG, "call surfaceChanged event"); synchronized(mSyncObject) { if (!mSurfaceExist) { mSurfaceExist = true; checkCurrentState(); } else { /** Surface changed. We need to stop camera and restart with new parameters */ /* Pretend that old surface has been destroyed */ mSurfaceExist = false; checkCurrentState(); /* Now use new surface. Say we have it now */ mSurfaceExist = true; checkCurrentState(); } } } public void surfaceCreated(SurfaceHolder holder) { /* Do nothing. Wait until surfaceChanged delivered */ } public void surfaceDestroyed(SurfaceHolder holder) { synchronized(mSyncObject) { mSurfaceExist = false; checkCurrentState(); } } /** * This method is provided for clients, so they can signal camera permission has been granted. * The actual onCameraViewStarted callback will be delivered only after setCameraPermissionGranted * and enableView have been called and surface is available */ public void setCameraPermissionGranted() { synchronized(mSyncObject) { mCameraPermissionGranted = true; checkCurrentState(); } } /** * This method is provided for clients, so they can enable the camera connection. * The actual onCameraViewStarted callback will be delivered only after setCameraPermissionGranted * and enableView have been called and surface is available */ public void enableView() { synchronized(mSyncObject) { mEnabled = true; checkCurrentState(); } } /** * This method is provided for clients, so they can disable camera connection and stop * the delivery of frames even though the surface view itself is not destroyed and still stays on the screen */ public void disableView() { synchronized(mSyncObject) { mEnabled = false; checkCurrentState(); } } /** * This method enables label with fps value on the screen */ public void enableFpsMeter() { if (mFpsMeter == null) { mFpsMeter = new FpsMeter(); mFpsMeter.setResolution(mFrameWidth, mFrameHeight); } } public void disableFpsMeter() { mFpsMeter = null; } /** * * @param listener */ public void setCvCameraViewListener(CvCameraViewListener2 listener) { mListener = listener; } public void setCvCameraViewListener(CvCameraViewListener listener) { CvCameraViewListenerAdapter adapter = new CvCameraViewListenerAdapter(listener); adapter.setFrameFormat(mPreviewFormat); mListener = adapter; } /** * This method sets the maximum size that camera frame is allowed to be. When selecting * size - the biggest size which less or equal the size set will be selected. * As an example - we set setMaxFrameSize(200,200) and we have 176x152 and 320x240 sizes. The * preview frame will be selected with 176x152 size. * This method is useful when need to restrict the size of preview frame for some reason (for example for video recording) * @param maxWidth - the maximum width allowed for camera frame. * @param maxHeight - the maximum height allowed for camera frame */ public void setMaxFrameSize(int maxWidth, int maxHeight) { mMaxWidth = maxWidth; mMaxHeight = maxHeight; } public void SetCaptureFormat(int format) { mPreviewFormat = format; if (mListener instanceof CvCameraViewListenerAdapter) { CvCameraViewListenerAdapter adapter = (CvCameraViewListenerAdapter) mListener; adapter.setFrameFormat(mPreviewFormat); } } /** * Called when mSyncObject lock is held */ private void checkCurrentState() { Log.d(TAG, "call checkCurrentState"); int targetState; if (mEnabled && mCameraPermissionGranted && mSurfaceExist && getVisibility() == VISIBLE) { targetState = STARTED; } else { targetState = STOPPED; } if (targetState != mState) { /* The state change detected. Need to exit the current state and enter target state */ processExitState(mState); mState = targetState; processEnterState(mState); } } private void processEnterState(int state) { Log.d(TAG, "call processEnterState: " + state); switch(state) { case STARTED: onEnterStartedState(); if (mListener != null) { mListener.onCameraViewStarted(mFrameWidth, mFrameHeight); } break; case STOPPED: onEnterStoppedState(); if (mListener != null) { mListener.onCameraViewStopped(); } break; }; } private void processExitState(int state) { Log.d(TAG, "call processExitState: " + state); switch(state) { case STARTED: onExitStartedState(); break; case STOPPED: onExitStoppedState(); break; }; } private void onEnterStoppedState() { /* nothing to do */ } private void onExitStoppedState() { /* nothing to do */ } // NOTE: The order of bitmap constructor and camera connection is important for android 4.1.x // Bitmap must be constructed before surface private void onEnterStartedState() { Log.d(TAG, "call onEnterStartedState"); /* Connect camera */ if (!connectCamera(getWidth(), getHeight())) { AlertDialog ad = new AlertDialog.Builder(getContext()).create(); ad.setCancelable(false); // This blocks the 'BACK' button ad.setMessage("It seems that your device does not support camera (or it is locked). Application will be closed."); ad.setButton(DialogInterface.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); ((Activity) getContext()).finish(); } }); ad.show(); } } private void onExitStartedState() { disconnectCamera(); if (mCacheBitmap != null) { mCacheBitmap.recycle(); } } /** * This method shall be called by the subclasses when they have valid * object and want it to be delivered to external client (via callback) and * then displayed on the screen. * @param frame - the current frame to be delivered */ protected void deliverAndDrawFrame(CvCameraViewFrame frame) { Mat modified; if (mListener != null) { modified = mListener.onCameraFrame(frame); } else { modified = frame.rgba(); } boolean bmpValid = true; if (modified != null) { try { Utils.matToBitmap(modified, mCacheBitmap); } catch(Exception e) { Log.e(TAG, "Mat type: " + modified); Log.e(TAG, "Bitmap type: " + mCacheBitmap.getWidth() + "*" + mCacheBitmap.getHeight()); Log.e(TAG, "Utils.matToBitmap() throws an exception: " + e.getMessage()); bmpValid = false; } } if (bmpValid && mCacheBitmap != null) { Canvas canvas = getHolder().lockCanvas(); if (canvas != null) { canvas.drawColor(0, android.graphics.PorterDuff.Mode.CLEAR); if (BuildConfig.DEBUG) Log.d(TAG, "mStretch value: " + mScale); if (mScale != 0) { canvas.drawBitmap(mCacheBitmap, new Rect(0,0,mCacheBitmap.getWidth(), mCacheBitmap.getHeight()), new Rect((int)((canvas.getWidth() - mScale*mCacheBitmap.getWidth()) / 2), (int)((canvas.getHeight() - mScale*mCacheBitmap.getHeight()) / 2), (int)((canvas.getWidth() - mScale*mCacheBitmap.getWidth()) / 2 + mScale*mCacheBitmap.getWidth()), (int)((canvas.getHeight() - mScale*mCacheBitmap.getHeight()) / 2 + mScale*mCacheBitmap.getHeight())), null); } else { canvas.drawBitmap(mCacheBitmap, new Rect(0,0,mCacheBitmap.getWidth(), mCacheBitmap.getHeight()), new Rect((canvas.getWidth() - mCacheBitmap.getWidth()) / 2, (canvas.getHeight() - mCacheBitmap.getHeight()) / 2, (canvas.getWidth() - mCacheBitmap.getWidth()) / 2 + mCacheBitmap.getWidth(), (canvas.getHeight() - mCacheBitmap.getHeight()) / 2 + mCacheBitmap.getHeight()), null); } if (mFpsMeter != null) { mFpsMeter.measure(); mFpsMeter.draw(canvas, 20, 30); } getHolder().unlockCanvasAndPost(canvas); } } } /** * This method is invoked shall perform concrete operation to initialize the camera. * CONTRACT: as a result of this method variables mFrameWidth and mFrameHeight MUST be * initialized with the size of the Camera frames that will be delivered to external processor. * @param width - the width of this SurfaceView * @param height - the height of this SurfaceView */ protected abstract boolean connectCamera(int width, int height); /** * Disconnects and release the particular camera object being connected to this surface view. * Called when syncObject lock is held */ protected abstract void disconnectCamera(); // NOTE: On Android 4.1.x the function must be called before SurfaceTexture constructor! protected void AllocateCache() { mCacheBitmap = Bitmap.createBitmap(mFrameWidth, mFrameHeight, Bitmap.Config.ARGB_8888); } public interface ListItemAccessor { public int getWidth(Object obj); public int getHeight(Object obj); }; /** * This helper method can be called by subclasses to select camera preview size. * It goes over the list of the supported preview sizes and selects the maximum one which * fits both values set via setMaxFrameSize() and surface frame allocated for this view * @param supportedSizes * @param surfaceWidth * @param surfaceHeight * @return optimal frame size */ protected Size calculateCameraFrameSize(List<?> supportedSizes, ListItemAccessor accessor, int surfaceWidth, int surfaceHeight) { int calcWidth = 0; int calcHeight = 0; int maxAllowedWidth = (mMaxWidth != MAX_UNSPECIFIED && mMaxWidth < surfaceWidth)? mMaxWidth : surfaceWidth; int maxAllowedHeight = (mMaxHeight != MAX_UNSPECIFIED && mMaxHeight < surfaceHeight)? mMaxHeight : surfaceHeight; for (Object size : supportedSizes) { int width = accessor.getWidth(size); int height = accessor.getHeight(size); Log.d(TAG, "trying size: " + width + "x" + height); if (width <= maxAllowedWidth && height <= maxAllowedHeight) { if (width >= calcWidth && height >= calcHeight) { calcWidth = (int) width; calcHeight = (int) height; } } } if ((calcWidth == 0 || calcHeight == 0) && supportedSizes.size() > 0) { Log.i(TAG, "fallback to the first frame size"); Object size = supportedSizes.get(0); calcWidth = accessor.getWidth(size); calcHeight = accessor.getHeight(size); } return new Size(calcWidth, calcHeight); } }
opencv/opencv
modules/java/generator/android/java/org/opencv/android/CameraBridgeViewBase.java
44,936
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.lockableobject.domain; import com.iluwatar.lockableobject.Lockable; import java.security.SecureRandom; import lombok.NonNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** A Feind is a creature that wants to possess a Lockable object. */ public class Feind implements Runnable { private final Creature creature; private final Lockable target; private final SecureRandom random; private static final Logger LOGGER = LoggerFactory.getLogger(Feind.class.getName()); /** * public constructor. * * @param feind as the creature to lock to he lockable. * @param target as the target object. */ public Feind(@NonNull Creature feind, @NonNull Lockable target) { this.creature = feind; this.target = target; this.random = new SecureRandom(); } @Override public void run() { if (!creature.acquire(target)) { fightForTheSword(creature, target.getLocker(), target); } else { LOGGER.info("{} has acquired the sword!", target.getLocker().getName()); } } /** * Keeps on fighting until the Lockable is possessed. * * @param reacher as the source creature. * @param holder as the foe. * @param sword as the Lockable to possess. */ private void fightForTheSword(Creature reacher, @NonNull Creature holder, Lockable sword) { LOGGER.info("A duel between {} and {} has been started!", reacher.getName(), holder.getName()); boolean randBool; while (this.target.isLocked() && reacher.isAlive() && holder.isAlive()) { randBool = random.nextBoolean(); if (randBool) { reacher.attack(holder); } else { holder.attack(reacher); } } if (reacher.isAlive()) { if (!reacher.acquire(sword)) { fightForTheSword(reacher, sword.getLocker(), sword); } else { LOGGER.info("{} has acquired the sword!", reacher.getName()); } } } }
iluwatar/java-design-patterns
lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Feind.java
44,937
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.uimanager; import android.graphics.Color; import android.graphics.Paint; import android.os.Build; import android.text.TextUtils; import android.view.View; import android.view.ViewParent; import android.view.accessibility.AccessibilityEvent; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.view.ViewCompat; import com.facebook.common.logging.FLog; import com.facebook.react.R; import com.facebook.react.bridge.Dynamic; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableMapKeySetIterator; import com.facebook.react.bridge.ReadableType; import com.facebook.react.common.MapBuilder; import com.facebook.react.common.ReactConstants; import com.facebook.react.uimanager.ReactAccessibilityDelegate.AccessibilityRole; import com.facebook.react.uimanager.ReactAccessibilityDelegate.Role; import com.facebook.react.uimanager.annotations.ReactProp; import com.facebook.react.uimanager.events.PointerEventHelper; import com.facebook.react.uimanager.util.ReactFindViewUtil; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Base class that should be suitable for the majority of subclasses of {@link ViewManager}. It * provides support for base view properties such as backgroundColor, opacity, etc. */ public abstract class BaseViewManager<T extends View, C extends LayoutShadowNode> extends ViewManager<T, C> implements BaseViewManagerInterface<T>, View.OnLayoutChangeListener { private static final int PERSPECTIVE_ARRAY_INVERTED_CAMERA_DISTANCE_INDEX = 2; private static final float CAMERA_DISTANCE_NORMALIZATION_MULTIPLIER = (float) Math.sqrt(5); private static final MatrixMathHelper.MatrixDecompositionContext sMatrixDecompositionContext = new MatrixMathHelper.MatrixDecompositionContext(); private static final double[] sTransformDecompositionArray = new double[16]; private static final String STATE_CHECKED = "checked"; // Special case for mixed state checkboxes private static final String STATE_BUSY = "busy"; private static final String STATE_EXPANDED = "expanded"; private static final String STATE_MIXED = "mixed"; public BaseViewManager() { super(null); } public BaseViewManager(@Nullable ReactApplicationContext reactContext) { super(reactContext); } @Override protected T prepareToRecycleView(@NonNull ThemedReactContext reactContext, T view) { // Reset tags view.setTag(null); view.setTag(R.id.pointer_events, null); view.setTag(R.id.react_test_id, null); view.setTag(R.id.view_tag_native_id, null); view.setTag(R.id.labelled_by, null); view.setTag(R.id.accessibility_label, null); view.setTag(R.id.accessibility_hint, null); view.setTag(R.id.accessibility_role, null); view.setTag(R.id.accessibility_state, null); view.setTag(R.id.accessibility_actions, null); view.setTag(R.id.accessibility_value, null); view.setTag(R.id.accessibility_state_expanded, null); // This indirectly calls (and resets): // setTranslationX // setTranslationY // setRotation // setRotationX // setRotationY // setScaleX // setScaleY // setCameraDistance setTransformProperty(view, null, null); // RenderNode params not covered by setTransformProperty above view.resetPivot(); view.setTop(0); view.setBottom(0); view.setLeft(0); view.setRight(0); view.setElevation(0); view.setAnimationMatrix(null); view.setTag(R.id.transform, null); view.setTag(R.id.transform_origin, null); view.setTag(R.id.invalidate_transform, null); view.removeOnLayoutChangeListener(this); view.setTag(R.id.use_hardware_layer, null); view.setTag(R.id.filter, null); applyFilter(view, null); // setShadowColor if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { view.setOutlineAmbientShadowColor(Color.BLACK); view.setOutlineSpotShadowColor(Color.BLACK); } // Focus IDs // Also see in AOSP source: // https://android.googlesource.com/platform/frameworks/base/+/a175a5b/core/java/android/view/View.java#4493 view.setNextFocusDownId(View.NO_ID); view.setNextFocusForwardId(View.NO_ID); view.setNextFocusRightId(View.NO_ID); view.setNextFocusUpId(View.NO_ID); // This is possibly subject to change and overridable per-platform, but these // are the default view flags in View.java: // https://android.googlesource.com/platform/frameworks/base/+/a175a5b/core/java/android/view/View.java#2712 // `mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | LAYOUT_DIRECTION_INHERIT` // Therefore we set the following options as such: view.setFocusable(false); view.setFocusableInTouchMode(false); // https://android.googlesource.com/platform/frameworks/base/+/refs/tags/android-mainline-12.0.0_r96/core/java/android/view/View.java#5491 view.setElevation(0); // Predictably, alpha defaults to 1: // https://android.googlesource.com/platform/frameworks/base/+/a175a5b/core/java/android/view/View.java#2186 // This accounts for resetting mBackfaceOpacity and mBackfaceVisibility view.setAlpha(1); // setPadding is a noop for most View types, but it is not for Text setPadding(view, 0, 0, 0, 0); // Other stuff view.setForeground(null); return view; } // Currently. onLayout listener is only attached when transform origin prop is being used. @Override public void onLayoutChange( View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { // Old width and height int oldWidth = oldRight - oldLeft; int oldHeight = oldBottom - oldTop; // Current width and height int currentWidth = right - left; int currentHeight = bottom - top; if ((currentHeight != oldHeight || currentWidth != oldWidth)) { ReadableArray transformOrigin = (ReadableArray) v.getTag(R.id.transform_origin); ReadableArray transformMatrix = (ReadableArray) v.getTag(R.id.transform); if (transformMatrix != null && transformOrigin != null) { setTransformProperty((T) v, transformMatrix, transformOrigin); } } } @Override @ReactProp( name = ViewProps.BACKGROUND_COLOR, defaultInt = Color.TRANSPARENT, customType = "Color") public void setBackgroundColor(@NonNull T view, int backgroundColor) { view.setBackgroundColor(backgroundColor); } @Override @ReactProp(name = ViewProps.FILTER, customType = "Filter") public void setFilter(@NonNull T view, @Nullable ReadableArray filter) { view.setTag(R.id.filter, filter); } @Override @ReactProp(name = ViewProps.TRANSFORM) public void setTransform(@NonNull T view, @Nullable ReadableArray matrix) { view.setTag(R.id.transform, matrix); view.setTag(R.id.invalidate_transform, true); } @Override @ReactProp(name = ViewProps.TRANSFORM_ORIGIN) public void setTransformOrigin(@NonNull T view, @Nullable ReadableArray transformOrigin) { view.setTag(R.id.transform_origin, transformOrigin); view.setTag(R.id.invalidate_transform, true); if (transformOrigin != null) { view.addOnLayoutChangeListener(this); } else { view.removeOnLayoutChangeListener(this); } } @Override @ReactProp(name = ViewProps.OPACITY, defaultFloat = 1.f) public void setOpacity(@NonNull T view, float opacity) { view.setAlpha(opacity); } @Override @ReactProp(name = ViewProps.ELEVATION) public void setElevation(@NonNull T view, float elevation) { ViewCompat.setElevation(view, PixelUtil.toPixelFromDIP(elevation)); } @Override @ReactProp(name = ViewProps.SHADOW_COLOR, defaultInt = Color.BLACK, customType = "Color") public void setShadowColor(@NonNull T view, int shadowColor) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { view.setOutlineAmbientShadowColor(shadowColor); view.setOutlineSpotShadowColor(shadowColor); } } @Override @ReactProp(name = ViewProps.Z_INDEX) public void setZIndex(@NonNull T view, float zIndex) { int integerZIndex = Math.round(zIndex); ViewGroupManager.setViewZIndex(view, integerZIndex); ViewParent parent = view.getParent(); if (parent instanceof ReactZIndexedViewGroup) { ((ReactZIndexedViewGroup) parent).updateDrawingOrder(); } } @Override @ReactProp(name = ViewProps.RENDER_TO_HARDWARE_TEXTURE) public void setRenderToHardwareTexture(@NonNull T view, boolean useHWTexture) { view.setTag(R.id.use_hardware_layer, useHWTexture); } @Override @ReactProp(name = ViewProps.TEST_ID) public void setTestId(@NonNull T view, @Nullable String testId) { view.setTag(R.id.react_test_id, testId); // temporarily set the tag and keyed tags to avoid end to end test regressions view.setTag(testId); } @Override @ReactProp(name = ViewProps.NATIVE_ID) public void setNativeId(@NonNull T view, @Nullable String nativeId) { view.setTag(R.id.view_tag_native_id, nativeId); ReactFindViewUtil.notifyViewRendered(view); } @Override @ReactProp(name = ViewProps.ACCESSIBILITY_LABELLED_BY) public void setAccessibilityLabelledBy(@NonNull T view, @Nullable Dynamic nativeId) { if (nativeId.isNull()) { return; } if (nativeId.getType() == ReadableType.String) { view.setTag(R.id.labelled_by, nativeId.asString()); } else if (nativeId.getType() == ReadableType.Array) { // On Android, this takes a single View as labeledBy. If an array is specified, set the first // element in the tag. view.setTag(R.id.labelled_by, nativeId.asArray().getString(0)); } } @Override @ReactProp(name = ViewProps.ACCESSIBILITY_LABEL) public void setAccessibilityLabel(@NonNull T view, @Nullable String accessibilityLabel) { view.setTag(R.id.accessibility_label, accessibilityLabel); updateViewContentDescription(view); } @Override @ReactProp(name = ViewProps.ACCESSIBILITY_HINT) public void setAccessibilityHint(@NonNull T view, @Nullable String accessibilityHint) { view.setTag(R.id.accessibility_hint, accessibilityHint); updateViewContentDescription(view); } @Override @ReactProp(name = ViewProps.ACCESSIBILITY_ROLE) public void setAccessibilityRole(@NonNull T view, @Nullable String accessibilityRole) { if (accessibilityRole == null) { view.setTag(R.id.accessibility_role, null); } else { view.setTag(R.id.accessibility_role, AccessibilityRole.fromValue(accessibilityRole)); } } @Override @ReactProp(name = ViewProps.ACCESSIBILITY_COLLECTION) public void setAccessibilityCollection( @NonNull T view, @Nullable ReadableMap accessibilityCollection) { view.setTag(R.id.accessibility_collection, accessibilityCollection); } @Override @ReactProp(name = ViewProps.ACCESSIBILITY_COLLECTION_ITEM) public void setAccessibilityCollectionItem( @NonNull T view, @Nullable ReadableMap accessibilityCollectionItem) { view.setTag(R.id.accessibility_collection_item, accessibilityCollectionItem); } @Override @ReactProp(name = ViewProps.ACCESSIBILITY_STATE) public void setViewState(@NonNull T view, @Nullable ReadableMap accessibilityState) { if (accessibilityState == null) { return; } if (accessibilityState.hasKey("expanded")) { view.setTag(R.id.accessibility_state_expanded, accessibilityState.getBoolean("expanded")); } if (accessibilityState.hasKey("selected")) { boolean prevSelected = view.isSelected(); boolean nextSelected = accessibilityState.getBoolean("selected"); view.setSelected(nextSelected); // For some reason, Android does not announce "unselected" when state changes. // This is inconsistent with other platforms, but also with the "checked" state. // So manually announce this. if (view.isAccessibilityFocused() && prevSelected && !nextSelected) { view.announceForAccessibility( view.getContext().getString(R.string.state_unselected_description)); } } else { view.setSelected(false); } view.setTag(R.id.accessibility_state, accessibilityState); if (accessibilityState.hasKey("disabled") && !accessibilityState.getBoolean("disabled")) { view.setEnabled(true); } // For states which don't have corresponding methods in // AccessibilityNodeInfo, update the view's content description // here final ReadableMapKeySetIterator i = accessibilityState.keySetIterator(); while (i.hasNextKey()) { final String state = i.nextKey(); if (state.equals(STATE_BUSY) || state.equals(STATE_EXPANDED) || (state.equals(STATE_CHECKED) && accessibilityState.getType(STATE_CHECKED) == ReadableType.String)) { updateViewContentDescription(view); break; } else if (view.isAccessibilityFocused()) { // Internally Talkback ONLY uses TYPE_VIEW_CLICKED for "checked" and // "selected" announcements. Send a click event to make sure Talkback // get notified for the state changes that don't happen upon users' click. // For the state changes that happens immediately, Talkback will skip // the duplicated click event. view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); } } } private void updateViewContentDescription(@NonNull T view) { final String accessibilityLabel = (String) view.getTag(R.id.accessibility_label); final ReadableMap accessibilityState = (ReadableMap) view.getTag(R.id.accessibility_state); final List<String> contentDescription = new ArrayList<>(); final ReadableMap accessibilityValue = (ReadableMap) view.getTag(R.id.accessibility_value); if (accessibilityLabel != null) { contentDescription.add(accessibilityLabel); } if (accessibilityState != null) { final ReadableMapKeySetIterator i = accessibilityState.keySetIterator(); while (i.hasNextKey()) { final String state = i.nextKey(); final Dynamic value = accessibilityState.getDynamic(state); if (state.equals(STATE_CHECKED) && value.getType() == ReadableType.String && value.asString().equals(STATE_MIXED)) { contentDescription.add(view.getContext().getString(R.string.state_mixed_description)); } else if (state.equals(STATE_BUSY) && value.getType() == ReadableType.Boolean && value.asBoolean()) { contentDescription.add(view.getContext().getString(R.string.state_busy_description)); } } } if (accessibilityValue != null && accessibilityValue.hasKey("text")) { final Dynamic text = accessibilityValue.getDynamic("text"); if (text != null && text.getType() == ReadableType.String) { contentDescription.add(text.asString()); } } if (contentDescription.size() > 0) { view.setContentDescription(TextUtils.join(", ", contentDescription)); } } @Override @ReactProp(name = ViewProps.ACCESSIBILITY_ACTIONS) public void setAccessibilityActions(T view, ReadableArray accessibilityActions) { if (accessibilityActions == null) { return; } view.setTag(R.id.accessibility_actions, accessibilityActions); } @ReactProp(name = ViewProps.ACCESSIBILITY_VALUE) public void setAccessibilityValue(T view, ReadableMap accessibilityValue) { if (accessibilityValue == null) { view.setTag(R.id.accessibility_value, null); view.setContentDescription(null); } else { view.setTag(R.id.accessibility_value, accessibilityValue); if (accessibilityValue.hasKey("text")) { updateViewContentDescription(view); } } } @Override @ReactProp(name = ViewProps.IMPORTANT_FOR_ACCESSIBILITY) public void setImportantForAccessibility( @NonNull T view, @Nullable String importantForAccessibility) { if (importantForAccessibility == null || importantForAccessibility.equals("auto")) { ViewCompat.setImportantForAccessibility(view, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO); } else if (importantForAccessibility.equals("yes")) { ViewCompat.setImportantForAccessibility(view, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES); } else if (importantForAccessibility.equals("no")) { ViewCompat.setImportantForAccessibility(view, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO); } else if (importantForAccessibility.equals("no-hide-descendants")) { ViewCompat.setImportantForAccessibility( view, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); } } @Override @ReactProp(name = ViewProps.ROLE) public void setRole(@NonNull T view, @Nullable String role) { if (role == null) { view.setTag(R.id.role, null); } else { view.setTag(R.id.role, Role.fromValue(role)); } } @Override @Deprecated @ReactProp(name = ViewProps.ROTATION) public void setRotation(@NonNull T view, float rotation) { view.setRotation(rotation); } @Override @Deprecated @ReactProp(name = ViewProps.SCALE_X, defaultFloat = 1f) public void setScaleX(@NonNull T view, float scaleX) { view.setScaleX(scaleX); } @Override @Deprecated @ReactProp(name = ViewProps.SCALE_Y, defaultFloat = 1f) public void setScaleY(@NonNull T view, float scaleY) { view.setScaleY(scaleY); } @Override @Deprecated @ReactProp(name = ViewProps.TRANSLATE_X, defaultFloat = 0f) public void setTranslateX(@NonNull T view, float translateX) { view.setTranslationX(PixelUtil.toPixelFromDIP(translateX)); } @Override @Deprecated @ReactProp(name = ViewProps.TRANSLATE_Y, defaultFloat = 0f) public void setTranslateY(@NonNull T view, float translateY) { view.setTranslationY(PixelUtil.toPixelFromDIP(translateY)); } @Override @ReactProp(name = ViewProps.ACCESSIBILITY_LIVE_REGION) public void setAccessibilityLiveRegion(@NonNull T view, @Nullable String liveRegion) { if (liveRegion == null || liveRegion.equals("none")) { ViewCompat.setAccessibilityLiveRegion(view, ViewCompat.ACCESSIBILITY_LIVE_REGION_NONE); } else if (liveRegion.equals("polite")) { ViewCompat.setAccessibilityLiveRegion(view, ViewCompat.ACCESSIBILITY_LIVE_REGION_POLITE); } else if (liveRegion.equals("assertive")) { ViewCompat.setAccessibilityLiveRegion(view, ViewCompat.ACCESSIBILITY_LIVE_REGION_ASSERTIVE); } } private void applyFilter(@NonNull T view, @Nullable ReadableArray filter) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { view.setRenderEffect(null); } Boolean useHWLayer = (Boolean) view.getTag(R.id.use_hardware_layer); int layerType = useHWLayer != null && useHWLayer ? View.LAYER_TYPE_HARDWARE : View.LAYER_TYPE_NONE; view.setLayerType(layerType, null); if (filter == null) { return; } if (FilterHelper.isOnlyColorMatrixFilters(filter)) { Paint p = new Paint(); p.setColorFilter(FilterHelper.parseColorMatrixFilters(filter)); view.setLayerType(View.LAYER_TYPE_HARDWARE, p); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { view.setRenderEffect(FilterHelper.parseFilters(filter)); } } protected void setTransformProperty( @NonNull T view, @Nullable ReadableArray transforms, @Nullable ReadableArray transformOrigin) { if (transforms == null) { view.setTranslationX(PixelUtil.toPixelFromDIP(0)); view.setTranslationY(PixelUtil.toPixelFromDIP(0)); view.setRotation(0); view.setRotationX(0); view.setRotationY(0); view.setScaleX(1); view.setScaleY(1); view.setCameraDistance(0); return; } sMatrixDecompositionContext.reset(); TransformHelper.processTransform( transforms, sTransformDecompositionArray, PixelUtil.toDIPFromPixel(view.getWidth()), PixelUtil.toDIPFromPixel(view.getHeight()), transformOrigin); MatrixMathHelper.decomposeMatrix(sTransformDecompositionArray, sMatrixDecompositionContext); view.setTranslationX( PixelUtil.toPixelFromDIP( sanitizeFloatPropertyValue((float) sMatrixDecompositionContext.translation[0]))); view.setTranslationY( PixelUtil.toPixelFromDIP( sanitizeFloatPropertyValue((float) sMatrixDecompositionContext.translation[1]))); view.setRotation( sanitizeFloatPropertyValue((float) sMatrixDecompositionContext.rotationDegrees[2])); view.setRotationX( sanitizeFloatPropertyValue((float) sMatrixDecompositionContext.rotationDegrees[0])); view.setRotationY( sanitizeFloatPropertyValue((float) sMatrixDecompositionContext.rotationDegrees[1])); view.setScaleX(sanitizeFloatPropertyValue((float) sMatrixDecompositionContext.scale[0])); view.setScaleY(sanitizeFloatPropertyValue((float) sMatrixDecompositionContext.scale[1])); double[] perspectiveArray = sMatrixDecompositionContext.perspective; if (perspectiveArray.length > PERSPECTIVE_ARRAY_INVERTED_CAMERA_DISTANCE_INDEX) { float invertedCameraDistance = (float) perspectiveArray[PERSPECTIVE_ARRAY_INVERTED_CAMERA_DISTANCE_INDEX]; if (invertedCameraDistance == 0) { // Default camera distance, before scale multiplier (1280) invertedCameraDistance = 0.00078125f; } float cameraDistance = -1 / invertedCameraDistance; float scale = DisplayMetricsHolder.getScreenDisplayMetrics().density; // The following converts the matrix's perspective to a camera distance // such that the camera perspective looks the same on Android and iOS. // The native Android implementation removed the screen density from the // calculation, so squaring and a normalization value of // sqrt(5) produces an exact replica with iOS. // For more information, see https://github.com/facebook/react-native/pull/18302 float normalizedCameraDistance = sanitizeFloatPropertyValue( scale * scale * cameraDistance * CAMERA_DISTANCE_NORMALIZATION_MULTIPLIER); view.setCameraDistance(normalizedCameraDistance); } } /** * Prior to Android P things like setScaleX() allowed passing float values that were bogus such as * Float.NaN. If the app is targeting Android P or later then passing these values will result in * an exception being thrown. Since JS might still send Float.NaN, we want to keep the code * backward compatible and continue using the fallback value if an invalid float is passed. */ private static float sanitizeFloatPropertyValue(float value) { if (value >= -Float.MAX_VALUE && value <= Float.MAX_VALUE) { return value; } if (value < -Float.MAX_VALUE || value == Float.NEGATIVE_INFINITY) { return -Float.MAX_VALUE; } if (value > Float.MAX_VALUE || value == Float.POSITIVE_INFINITY) { return Float.MAX_VALUE; } if (Float.isNaN(value)) { return 0; } // Shouldn't be possible to reach this point. throw new IllegalStateException("Invalid float property value: " + value); } private void updateViewAccessibility(@NonNull T view) { ReactAccessibilityDelegate.setDelegate( view, view.isFocusable(), view.getImportantForAccessibility()); } @Override protected void onAfterUpdateTransaction(@NonNull T view) { super.onAfterUpdateTransaction(view); updateViewAccessibility(view); Boolean invalidateTransform = (Boolean) view.getTag(R.id.invalidate_transform); if (invalidateTransform != null && invalidateTransform) { ReadableArray transformOrigin = (ReadableArray) view.getTag(R.id.transform_origin); ReadableArray transformMatrix = (ReadableArray) view.getTag(R.id.transform); setTransformProperty(view, transformMatrix, transformOrigin); view.setTag(R.id.invalidate_transform, false); } Boolean useHWLayer = (Boolean) view.getTag(R.id.use_hardware_layer); if (useHWLayer != null) { view.setLayerType(useHWLayer ? View.LAYER_TYPE_HARDWARE : View.LAYER_TYPE_NONE, null); } ReadableArray filter = (ReadableArray) view.getTag(R.id.filter); applyFilter(view, filter); } @Override public @Nullable Map<String, Object> getExportedCustomBubblingEventTypeConstants() { Map<String, Object> baseEventTypeConstants = super.getExportedCustomDirectEventTypeConstants(); Map<String, Object> eventTypeConstants = baseEventTypeConstants == null ? new HashMap<String, Object>() : baseEventTypeConstants; eventTypeConstants.putAll( MapBuilder.<String, Object>builder() .put( "topPointerCancel", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of( "bubbled", "onPointerCancel", "captured", "onPointerCancelCapture"))) .put( "topPointerDown", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onPointerDown", "captured", "onPointerDownCapture"))) .put( "topPointerEnter", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of( "bubbled", "onPointerEnter", "captured", "onPointerEnterCapture", "skipBubbling", true))) .put( "topPointerLeave", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of( "bubbled", "onPointerLeave", "captured", "onPointerLeaveCapture", "skipBubbling", true))) .put( "topPointerMove", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onPointerMove", "captured", "onPointerMoveCapture"))) .put( "topPointerUp", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onPointerUp", "captured", "onPointerUpCapture"))) .put( "topPointerOut", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onPointerOut", "captured", "onPointerOutCapture"))) .put( "topPointerOver", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onPointerOver", "captured", "onPointerOverCapture"))) .put( "topClick", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onClick", "captured", "onClickCapture"))) .build()); return eventTypeConstants; } @Override public @Nullable Map<String, Object> getExportedCustomDirectEventTypeConstants() { @Nullable Map<String, Object> baseEventTypeConstants = super.getExportedCustomDirectEventTypeConstants(); Map<String, Object> eventTypeConstants = baseEventTypeConstants == null ? new HashMap<String, Object>() : baseEventTypeConstants; eventTypeConstants.putAll( MapBuilder.<String, Object>builder() .put( "topAccessibilityAction", MapBuilder.of("registrationName", "onAccessibilityAction")) .build()); return eventTypeConstants; } @Override public void setBorderRadius(T view, float borderRadius) { logUnsupportedPropertyWarning(ViewProps.BORDER_RADIUS); } @Override public void setBorderBottomLeftRadius(T view, float borderRadius) { logUnsupportedPropertyWarning(ViewProps.BORDER_BOTTOM_LEFT_RADIUS); } @Override public void setBorderBottomRightRadius(T view, float borderRadius) { logUnsupportedPropertyWarning(ViewProps.BORDER_BOTTOM_RIGHT_RADIUS); } @Override public void setBorderTopLeftRadius(T view, float borderRadius) { logUnsupportedPropertyWarning(ViewProps.BORDER_TOP_LEFT_RADIUS); } @Override public void setBorderTopRightRadius(T view, float borderRadius) { logUnsupportedPropertyWarning(ViewProps.BORDER_TOP_RIGHT_RADIUS); } private void logUnsupportedPropertyWarning(String propName) { FLog.w(ReactConstants.TAG, "%s doesn't support property '%s'", getName(), propName); } private static void setPointerEventsFlag( @NonNull View view, PointerEventHelper.EVENT event, boolean isListening) { Integer tag = (Integer) view.getTag(R.id.pointer_events); int currentValue = tag != null ? tag.intValue() : 0; int flag = 1 << event.ordinal(); view.setTag(R.id.pointer_events, isListening ? (currentValue | flag) : (currentValue & ~flag)); } /* Experimental W3C Pointer events start */ @ReactProp(name = "onPointerEnter") public void setPointerEnter(@NonNull T view, boolean value) { setPointerEventsFlag(view, PointerEventHelper.EVENT.ENTER, value); } @ReactProp(name = "onPointerEnterCapture") public void setPointerEnterCapture(@NonNull T view, boolean value) { setPointerEventsFlag(view, PointerEventHelper.EVENT.ENTER_CAPTURE, value); } @ReactProp(name = "onPointerOver") public void setPointerOver(@NonNull T view, boolean value) { setPointerEventsFlag(view, PointerEventHelper.EVENT.OVER, value); } @ReactProp(name = "onPointerOverCapture") public void setPointerOverCapture(@NonNull T view, boolean value) { setPointerEventsFlag(view, PointerEventHelper.EVENT.OVER_CAPTURE, value); } @ReactProp(name = "onPointerOut") public void setPointerOut(@NonNull T view, boolean value) { setPointerEventsFlag(view, PointerEventHelper.EVENT.OUT, value); } @ReactProp(name = "onPointerOutCapture") public void setPointerOutCapture(@NonNull T view, boolean value) { setPointerEventsFlag(view, PointerEventHelper.EVENT.OUT_CAPTURE, value); } @ReactProp(name = "onPointerLeave") public void setPointerLeave(@NonNull T view, boolean value) { setPointerEventsFlag(view, PointerEventHelper.EVENT.LEAVE, value); } @ReactProp(name = "onPointerLeaveCapture") public void setPointerLeaveCapture(@NonNull T view, boolean value) { setPointerEventsFlag(view, PointerEventHelper.EVENT.LEAVE_CAPTURE, value); } @ReactProp(name = "onPointerMove") public void setPointerMove(@NonNull T view, boolean value) { setPointerEventsFlag(view, PointerEventHelper.EVENT.MOVE, value); } @ReactProp(name = "onPointerMoveCapture") public void setPointerMoveCapture(@NonNull T view, boolean value) { setPointerEventsFlag(view, PointerEventHelper.EVENT.MOVE_CAPTURE, value); } @ReactProp(name = "onClick") public void setClick(@NonNull T view, boolean value) { setPointerEventsFlag(view, PointerEventHelper.EVENT.CLICK, value); } @ReactProp(name = "onClickCapture") public void setClickCapture(@NonNull T view, boolean value) { setPointerEventsFlag(view, PointerEventHelper.EVENT.CLICK_CAPTURE, value); } /* Experimental W3C Pointer events end */ @ReactProp(name = "onMoveShouldSetResponder") public void setMoveShouldSetResponder(@NonNull T view, boolean value) { // no-op, handled by JSResponder } @ReactProp(name = "onMoveShouldSetResponderCapture") public void setMoveShouldSetResponderCapture(@NonNull T view, boolean value) { // no-op, handled by JSResponder } @ReactProp(name = "onStartShouldSetResponder") public void setStartShouldSetResponder(@NonNull T view, boolean value) { // no-op, handled by JSResponder } @ReactProp(name = "onStartShouldSetResponderCapture") public void setStartShouldSetResponderCapture(@NonNull T view, boolean value) { // no-op, handled by JSResponder } @ReactProp(name = "onResponderGrant") public void setResponderGrant(@NonNull T view, boolean value) { // no-op, handled by JSResponder } @ReactProp(name = "onResponderReject") public void setResponderReject(@NonNull T view, boolean value) { // no-op, handled by JSResponder } @ReactProp(name = "onResponderStart") public void setResponderStart(@NonNull T view, boolean value) { // no-op, handled by JSResponder } @ReactProp(name = "onResponderEnd") public void setResponderEnd(@NonNull T view, boolean value) { // no-op, handled by JSResponder } @ReactProp(name = "onResponderRelease") public void setResponderRelease(@NonNull T view, boolean value) { // no-op, handled by JSResponder } @ReactProp(name = "onResponderMove") public void setResponderMove(@NonNull T view, boolean value) { // no-op, handled by JSResponder } @ReactProp(name = "onResponderTerminate") public void setResponderTerminate(@NonNull T view, boolean value) { // no-op, handled by JSResponder } @ReactProp(name = "onResponderTerminationRequest") public void setResponderTerminationRequest(@NonNull T view, boolean value) { // no-op, handled by JSResponder } @ReactProp(name = "onShouldBlockNativeResponder") public void setShouldBlockNativeResponder(@NonNull T view, boolean value) { // no-op, handled by JSResponder } @ReactProp(name = "onTouchStart") public void setTouchStart(@NonNull T view, boolean value) { // no-op, handled by JSResponder } @ReactProp(name = "onTouchMove") public void setTouchMove(@NonNull T view, boolean value) { // no-op, handled by JSResponder } @ReactProp(name = "onTouchEnd") public void setTouchEnd(@NonNull T view, boolean value) { // no-op, handled by JSResponder } @ReactProp(name = "onTouchCancel") public void setTouchCancel(@NonNull T view, boolean value) { // no-op, handled by JSResponder } }
facebook/react-native
packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/BaseViewManager.java
44,938
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.search; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.core.TimeValue; import java.io.IOException; import java.util.Objects; /** * A scroll enables scrolling of search request. It holds a {@link #keepAlive()} time that * will control how long to keep the scrolling resources open. * * */ public final class Scroll implements Writeable { private final TimeValue keepAlive; public Scroll(StreamInput in) throws IOException { this.keepAlive = in.readTimeValue(); } /** * Constructs a new scroll of the provided keep alive. */ public Scroll(TimeValue keepAlive) { this.keepAlive = Objects.requireNonNull(keepAlive, "keepAlive must not be null"); } /** * How long the resources will be kept open to support the scroll request. */ public TimeValue keepAlive() { return keepAlive; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeTimeValue(keepAlive); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Scroll scroll = (Scroll) o; return Objects.equals(keepAlive, scroll.keepAlive); } @Override public int hashCode() { return Objects.hash(keepAlive); } @Override public String toString() { return "Scroll{keepAlive=" + keepAlive + '}'; } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/search/Scroll.java
44,939
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.http; public class HttpUtils { static final String CLOSE = "close"; static final String CONNECTION = "connection"; static final String KEEP_ALIVE = "keep-alive"; // Determine if the request connection should be closed on completion. public static boolean shouldCloseConnection(HttpRequest httpRequest) { try { final boolean http10 = httpRequest.protocolVersion() == HttpRequest.HttpVersion.HTTP_1_0; return CLOSE.equalsIgnoreCase(httpRequest.header(CONNECTION)) || (http10 && KEEP_ALIVE.equalsIgnoreCase(httpRequest.header(CONNECTION)) == false); } catch (Exception e) { // In case we fail to parse the http protocol version out of the request we always close the connection return true; } } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/http/HttpUtils.java
44,940
package com.genymobile.scrcpy; import android.media.MediaCodec; import android.media.MediaCodecInfo; import android.media.MediaFormat; import android.os.Looper; import android.os.SystemClock; import android.view.Surface; import java.io.IOException; import java.nio.ByteBuffer; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; public class SurfaceEncoder implements AsyncProcessor { private static final int DEFAULT_I_FRAME_INTERVAL = 10; // seconds private static final int REPEAT_FRAME_DELAY_US = 100_000; // repeat after 100ms private static final String KEY_MAX_FPS_TO_ENCODER = "max-fps-to-encoder"; // Keep the values in descending order private static final int[] MAX_SIZE_FALLBACK = {2560, 1920, 1600, 1280, 1024, 800}; private static final int MAX_CONSECUTIVE_ERRORS = 3; private final SurfaceCapture capture; private final Streamer streamer; private final String encoderName; private final List<CodecOption> codecOptions; private final int videoBitRate; private final int maxFps; private final boolean downsizeOnError; private boolean firstFrameSent; private int consecutiveErrors; private Thread thread; private final AtomicBoolean stopped = new AtomicBoolean(); public SurfaceEncoder(SurfaceCapture capture, Streamer streamer, int videoBitRate, int maxFps, List<CodecOption> codecOptions, String encoderName, boolean downsizeOnError) { this.capture = capture; this.streamer = streamer; this.videoBitRate = videoBitRate; this.maxFps = maxFps; this.codecOptions = codecOptions; this.encoderName = encoderName; this.downsizeOnError = downsizeOnError; } private void streamScreen() throws IOException, ConfigurationException { Codec codec = streamer.getCodec(); MediaCodec mediaCodec = createMediaCodec(codec, encoderName); MediaFormat format = createFormat(codec.getMimeType(), videoBitRate, maxFps, codecOptions); capture.init(); try { streamer.writeVideoHeader(capture.getSize()); boolean alive; do { Size size = capture.getSize(); format.setInteger(MediaFormat.KEY_WIDTH, size.getWidth()); format.setInteger(MediaFormat.KEY_HEIGHT, size.getHeight()); Surface surface = null; try { mediaCodec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); surface = mediaCodec.createInputSurface(); capture.start(surface); mediaCodec.start(); alive = encode(mediaCodec, streamer); // do not call stop() on exception, it would trigger an IllegalStateException mediaCodec.stop(); } catch (IllegalStateException | IllegalArgumentException e) { Ln.e("Encoding error: " + e.getClass().getName() + ": " + e.getMessage()); if (!prepareRetry(size)) { throw e; } Ln.i("Retrying..."); alive = true; } finally { mediaCodec.reset(); if (surface != null) { surface.release(); } } } while (alive); } finally { mediaCodec.release(); capture.release(); } } private boolean prepareRetry(Size currentSize) { if (firstFrameSent) { ++consecutiveErrors; if (consecutiveErrors >= MAX_CONSECUTIVE_ERRORS) { // Definitively fail return false; } // Wait a bit to increase the probability that retrying will fix the problem SystemClock.sleep(50); return true; } if (!downsizeOnError) { // Must fail immediately return false; } // Downsizing on error is only enabled if an encoding failure occurs before the first frame (downsizing later could be surprising) int newMaxSize = chooseMaxSizeFallback(currentSize); if (newMaxSize == 0) { // Must definitively fail return false; } boolean accepted = capture.setMaxSize(newMaxSize); if (!accepted) { return false; } // Retry with a smaller size Ln.i("Retrying with -m" + newMaxSize + "..."); return true; } private static int chooseMaxSizeFallback(Size failedSize) { int currentMaxSize = Math.max(failedSize.getWidth(), failedSize.getHeight()); for (int value : MAX_SIZE_FALLBACK) { if (value < currentMaxSize) { // We found a smaller value to reduce the video size return value; } } // No fallback, fail definitively return 0; } private boolean encode(MediaCodec codec, Streamer streamer) throws IOException { boolean eof = false; boolean alive = true; MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo(); while (!capture.consumeReset() && !eof) { if (stopped.get()) { alive = false; break; } int outputBufferId = codec.dequeueOutputBuffer(bufferInfo, -1); try { if (capture.consumeReset()) { // must restart encoding with new size break; } eof = (bufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0; if (outputBufferId >= 0) { ByteBuffer codecBuffer = codec.getOutputBuffer(outputBufferId); boolean isConfig = (bufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0; if (!isConfig) { // If this is not a config packet, then it contains a frame firstFrameSent = true; consecutiveErrors = 0; } streamer.writePacket(codecBuffer, bufferInfo); } } finally { if (outputBufferId >= 0) { codec.releaseOutputBuffer(outputBufferId, false); } } } if (capture.isClosed()) { // The capture might have been closed internally (for example if the camera is disconnected) alive = false; } return !eof && alive; } private static MediaCodec createMediaCodec(Codec codec, String encoderName) throws IOException, ConfigurationException { if (encoderName != null) { Ln.d("Creating encoder by name: '" + encoderName + "'"); try { return MediaCodec.createByCodecName(encoderName); } catch (IllegalArgumentException e) { Ln.e("Video encoder '" + encoderName + "' for " + codec.getName() + " not found\n" + LogUtils.buildVideoEncoderListMessage()); throw new ConfigurationException("Unknown encoder: " + encoderName); } catch (IOException e) { Ln.e("Could not create video encoder '" + encoderName + "' for " + codec.getName() + "\n" + LogUtils.buildVideoEncoderListMessage()); throw e; } } try { MediaCodec mediaCodec = MediaCodec.createEncoderByType(codec.getMimeType()); Ln.d("Using video encoder: '" + mediaCodec.getName() + "'"); return mediaCodec; } catch (IOException | IllegalArgumentException e) { Ln.e("Could not create default video encoder for " + codec.getName() + "\n" + LogUtils.buildVideoEncoderListMessage()); throw e; } } private static MediaFormat createFormat(String videoMimeType, int bitRate, int maxFps, List<CodecOption> codecOptions) { MediaFormat format = new MediaFormat(); format.setString(MediaFormat.KEY_MIME, videoMimeType); format.setInteger(MediaFormat.KEY_BIT_RATE, bitRate); // must be present to configure the encoder, but does not impact the actual frame rate, which is variable format.setInteger(MediaFormat.KEY_FRAME_RATE, 60); format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface); format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, DEFAULT_I_FRAME_INTERVAL); // display the very first frame, and recover from bad quality when no new frames format.setLong(MediaFormat.KEY_REPEAT_PREVIOUS_FRAME_AFTER, REPEAT_FRAME_DELAY_US); // µs if (maxFps > 0) { // The key existed privately before Android 10: // <https://android.googlesource.com/platform/frameworks/base/+/625f0aad9f7a259b6881006ad8710adce57d1384%5E%21/> // <https://github.com/Genymobile/scrcpy/issues/488#issuecomment-567321437> format.setFloat(KEY_MAX_FPS_TO_ENCODER, maxFps); } if (codecOptions != null) { for (CodecOption option : codecOptions) { String key = option.getKey(); Object value = option.getValue(); CodecUtils.setCodecOption(format, key, value); Ln.d("Video codec option set: " + key + " (" + value.getClass().getSimpleName() + ") = " + value); } } return format; } @Override public void start(TerminationListener listener) { thread = new Thread(() -> { // Some devices (Meizu) deadlock if the video encoding thread has no Looper // <https://github.com/Genymobile/scrcpy/issues/4143> Looper.prepare(); try { streamScreen(); } catch (ConfigurationException e) { // Do not print stack trace, a user-friendly error-message has already been logged } catch (IOException e) { // Broken pipe is expected on close, because the socket is closed by the client if (!IO.isBrokenPipe(e)) { Ln.e("Video encoding error", e); } } finally { Ln.d("Screen streaming stopped"); listener.onTerminated(true); } }, "video"); thread.start(); } @Override public void stop() { if (thread != null) { stopped.set(true); } } @Override public void join() throws InterruptedException { if (thread != null) { thread.join(); } } }
Genymobile/scrcpy
server/src/main/java/com/genymobile/scrcpy/SurfaceEncoder.java
44,941
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderelection.ring; import com.iluwatar.leaderelection.AbstractInstance; import com.iluwatar.leaderelection.Message; import com.iluwatar.leaderelection.MessageManager; import java.util.Arrays; import lombok.extern.slf4j.Slf4j; /** * Implementation with token ring algorithm. The instances in the system are organized as a ring. * Each instance should have a sequential id and the instance with smallest (or largest) id should * be the initial leader. All the other instances send heartbeat message to leader periodically to * check its health. If one certain instance finds the server done, it will send an election message * to the next alive instance in the ring, which contains its own ID. Then the next instance add its * ID into the message and pass it to the next. After all the alive instances' ID are add to the * message, the message is send back to the first instance, and it will choose the instance with the * smallest ID to be the new leader, and then send a leader message to other instances to inform the * result. */ @Slf4j public class RingInstance extends AbstractInstance { private static final String INSTANCE = "Instance "; /** * Constructor of RingInstance. */ public RingInstance(MessageManager messageManager, int localId, int leaderId) { super(messageManager, localId, leaderId); } /** * Process the heartbeat invoke message. After receiving the message, the instance will send a * heartbeat to leader to check its health. If alive, it will inform the next instance to do the * heartbeat. If not, it will start the election process. */ @Override protected void handleHeartbeatInvokeMessage() { try { var isLeaderAlive = messageManager.sendHeartbeatMessage(this.leaderId); if (isLeaderAlive) { LOGGER.info(INSTANCE + localId + "- Leader is alive. Start next heartbeat in 5 second."); Thread.sleep(HEARTBEAT_INTERVAL); messageManager.sendHeartbeatInvokeMessage(this.localId); } else { LOGGER.info(INSTANCE + localId + "- Leader is not alive. Start election."); messageManager.sendElectionMessage(this.localId, String.valueOf(this.localId)); } } catch (InterruptedException e) { LOGGER.info(INSTANCE + localId + "- Interrupted."); } } /** * Process election message. If the local ID is contained in the ID list, the instance will select * the alive instance with the smallest ID to be the new leader, and send the leader inform message. * If not, it will add its local ID to the list and send the message to the next instance in the * ring. */ @Override protected void handleElectionMessage(Message message) { var content = message.getContent(); LOGGER.info(INSTANCE + localId + " - Election Message: " + content); var candidateList = Arrays.stream(content.trim().split(",")) .map(Integer::valueOf) .sorted() .toList(); if (candidateList.contains(localId)) { var newLeaderId = candidateList.get(0); LOGGER.info(INSTANCE + localId + " - New leader should be " + newLeaderId + "."); messageManager.sendLeaderMessage(localId, newLeaderId); } else { content += "," + localId; messageManager.sendElectionMessage(localId, content); } } /** * Process leader Message. The instance will set the leader ID to be the new one and send the * message to the next instance until all the alive instance in the ring is informed. */ @Override protected void handleLeaderMessage(Message message) { var newLeaderId = Integer.valueOf(message.getContent()); if (this.leaderId != newLeaderId) { LOGGER.info(INSTANCE + localId + " - Update leaderID"); this.leaderId = newLeaderId; messageManager.sendLeaderMessage(localId, newLeaderId); } else { LOGGER.info(INSTANCE + localId + " - Leader update done. Start heartbeat."); messageManager.sendHeartbeatInvokeMessage(localId); } } /** * Not used in Ring instance. */ @Override protected void handleLeaderInvokeMessage() { // Not used in Ring instance. } @Override protected void handleHeartbeatMessage(Message message) { // Not used in Ring instance. } @Override protected void handleElectionInvokeMessage() { // Not used in Ring instance. } }
iluwatar/java-design-patterns
leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingInstance.java
44,942
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderelection.bully; import com.iluwatar.leaderelection.AbstractInstance; import com.iluwatar.leaderelection.Message; import com.iluwatar.leaderelection.MessageManager; import lombok.extern.slf4j.Slf4j; /** * Impelemetation with bully algorithm. Each instance should have a sequential id and is able to * communicate with other instances in the system. Initially the instance with smallest (or largest) * ID is selected to be the leader. All the other instances send heartbeat message to leader * periodically to check its health. If one certain instance finds the server done, it will send an * election message to all the instances of which the ID is larger. If the target instance is alive, * it will return an alive message (in this sample return true) and then send election message with * its ID. If not, the original instance will send leader message to all the other instances. */ @Slf4j public class BullyInstance extends AbstractInstance { private static final String INSTANCE = "Instance "; /** * Constructor of BullyInstance. */ public BullyInstance(MessageManager messageManager, int localId, int leaderId) { super(messageManager, localId, leaderId); } /** * Process the heartbeat invoke message. After receiving the message, the instance will send a * heartbeat to leader to check its health. If alive, it will inform the next instance to do the * heartbeat. If not, it will start the election process. */ @Override protected void handleHeartbeatInvokeMessage() { try { boolean isLeaderAlive = messageManager.sendHeartbeatMessage(leaderId); if (isLeaderAlive) { LOGGER.info(INSTANCE + localId + "- Leader is alive."); Thread.sleep(HEARTBEAT_INTERVAL); messageManager.sendHeartbeatInvokeMessage(localId); } else { LOGGER.info(INSTANCE + localId + "- Leader is not alive. Start election."); boolean electionResult = messageManager.sendElectionMessage(localId, String.valueOf(localId)); if (electionResult) { LOGGER.info(INSTANCE + localId + "- Succeed in election. Start leader notification."); messageManager.sendLeaderMessage(localId, localId); } } } catch (InterruptedException e) { LOGGER.info(INSTANCE + localId + "- Interrupted."); } } /** * Process election invoke message. Send election message to all the instances with smaller ID. If * any one of them is alive, do nothing. If no instance alive, send leader message to all the * alive instance and restart heartbeat. */ @Override protected void handleElectionInvokeMessage() { if (!isLeader()) { LOGGER.info(INSTANCE + localId + "- Start election."); boolean electionResult = messageManager.sendElectionMessage(localId, String.valueOf(localId)); if (electionResult) { LOGGER.info(INSTANCE + localId + "- Succeed in election. Start leader notification."); leaderId = localId; messageManager.sendLeaderMessage(localId, localId); messageManager.sendHeartbeatInvokeMessage(localId); } } } /** * Process leader message. Update local leader information. */ @Override protected void handleLeaderMessage(Message message) { leaderId = Integer.parseInt(message.getContent()); LOGGER.info(INSTANCE + localId + " - Leader update done."); } private boolean isLeader() { return localId == leaderId; } @Override protected void handleLeaderInvokeMessage() { // Not used in Bully Instance } @Override protected void handleHeartbeatMessage(Message message) { // Not used in Bully Instance } @Override protected void handleElectionMessage(Message message) { // Not used in Bully Instance } }
iluwatar/java-design-patterns
leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyInstance.java
44,943
package com.twitter.search.earlybird.ml; import java.io.IOException; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.twitter.search.common.file.AbstractFile; import com.twitter.search.common.file.FileUtils; import com.twitter.search.common.metrics.SearchStatsReceiver; import com.twitter.search.common.schema.DynamicSchema; import com.twitter.search.common.util.ml.prediction_engine.CompositeFeatureContext; import com.twitter.search.common.util.ml.prediction_engine.LightweightLinearModel; import com.twitter.search.common.util.ml.prediction_engine.ModelLoader; import static com.twitter.search.modeling.tweet_ranking.TweetScoringFeatures.CONTEXT; import static com.twitter.search.modeling.tweet_ranking.TweetScoringFeatures.FeatureContextVersion.CURRENT_VERSION; /** * Loads the scoring models for tweets and provides access to them. * * This class relies on a list of ModelLoader objects to retrieve the objects from them. It will * return the first model found according to the order in the list. * * For production, we load models from 2 sources: classpath and HDFS. If a model is available * from HDFS, we return it, otherwise we use the model from the classpath. * * The models used for default requests (i.e. not experiments) MUST be present in the * classpath, this allows us to avoid errors if they can't be loaded from HDFS. * Models for experiments can live only in HDFS, so we don't need to redeploy Earlybird if we * want to test them. */ public class ScoringModelsManager { private static final Logger LOG = LoggerFactory.getLogger(ScoringModelsManager.class); /** * Used when * 1. Testing * 2. The scoring models are disabled in the config * 3. Exceptions thrown during loading the scoring models */ public static final ScoringModelsManager NO_OP_MANAGER = new ScoringModelsManager() { @Override public boolean isEnabled() { return false; } }; private final ModelLoader[] loaders; private final DynamicSchema dynamicSchema; public ScoringModelsManager(ModelLoader... loaders) { this.loaders = loaders; this.dynamicSchema = null; } public ScoringModelsManager(DynamicSchema dynamicSchema, ModelLoader... loaders) { this.loaders = loaders; this.dynamicSchema = dynamicSchema; } /** * Indicates that the scoring models were enabled in the config and were loaded successfully */ public boolean isEnabled() { return true; } public void reload() { for (ModelLoader loader : loaders) { loader.run(); } } /** * Loads and returns the model with the given name, if one exists. */ public Optional<LightweightLinearModel> getModel(String modelName) { for (ModelLoader loader : loaders) { Optional<LightweightLinearModel> model = loader.getModel(modelName); if (model.isPresent()) { return model; } } return Optional.absent(); } /** * Creates an instance that loads models first from HDFS and the classpath resources. * * If the models are not found in HDFS, it uses the models from the classpath as fallback. */ public static ScoringModelsManager create( SearchStatsReceiver serverStats, String hdfsNameNode, String hdfsBasedPath, DynamicSchema dynamicSchema) throws IOException { // Create a composite feature context so we can load both legacy and schema-based models CompositeFeatureContext featureContext = new CompositeFeatureContext( CONTEXT, dynamicSchema::getSearchFeatureSchema); ModelLoader hdfsLoader = createHdfsLoader( serverStats, hdfsNameNode, hdfsBasedPath, featureContext); ModelLoader classpathLoader = createClasspathLoader( serverStats, featureContext); // Explicitly load the models from the classpath classpathLoader.run(); ScoringModelsManager manager = new ScoringModelsManager(hdfsLoader, classpathLoader); LOG.info("Initialized ScoringModelsManager for loading models from HDFS and the classpath"); return manager; } protected static ModelLoader createHdfsLoader( SearchStatsReceiver serverStats, String hdfsNameNode, String hdfsBasedPath, CompositeFeatureContext featureContext) { String hdfsVersionedPath = hdfsBasedPath + "/" + CURRENT_VERSION.getVersionDirectory(); LOG.info("Starting to load scoring models from HDFS: {}:{}", hdfsNameNode, hdfsVersionedPath); return ModelLoader.forHdfsDirectory( hdfsNameNode, hdfsVersionedPath, featureContext, "scoring_models_hdfs_", serverStats); } /** * Creates a loader that loads models from a default location in the classpath. */ @VisibleForTesting public static ModelLoader createClasspathLoader( SearchStatsReceiver serverStats, CompositeFeatureContext featureContext) throws IOException { AbstractFile defaultModelsBaseDir = FileUtils.getTmpDirHandle( ScoringModelsManager.class, "/com/twitter/search/earlybird/ml/default_models"); AbstractFile defaultModelsDir = defaultModelsBaseDir.getChild( CURRENT_VERSION.getVersionDirectory()); LOG.info("Starting to load scoring models from the classpath: {}", defaultModelsDir.getPath()); return ModelLoader.forDirectory( defaultModelsDir, featureContext, "scoring_models_classpath_", serverStats); } }
twitter/the-algorithm
src/java/com/twitter/search/earlybird/ml/ScoringModelsManager.java
44,944
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.index.engine; import org.apache.logging.log4j.Logger; import org.apache.lucene.document.LongPoint; import org.apache.lucene.document.NumericDocValuesField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexCommit; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.LiveIndexWriterConfig; import org.apache.lucene.index.MergePolicy; import org.apache.lucene.index.SegmentCommitInfo; import org.apache.lucene.index.SegmentInfos; import org.apache.lucene.index.SoftDeletesRetentionMergePolicy; import org.apache.lucene.index.Term; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.DocIdSetIterator; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ReferenceManager; import org.apache.lucene.search.ScoreMode; import org.apache.lucene.search.Scorer; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.Weight; import org.apache.lucene.store.AlreadyClosedException; import org.apache.lucene.store.Directory; import org.apache.lucene.store.LockObtainFailedException; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.InfoStream; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.support.PlainActionFuture; import org.elasticsearch.action.support.SubscribableListener; import org.elasticsearch.cluster.metadata.DataStream; import org.elasticsearch.cluster.service.ClusterApplierService; import org.elasticsearch.common.lucene.LoggerInfoStream; import org.elasticsearch.common.lucene.Lucene; import org.elasticsearch.common.lucene.index.ElasticsearchDirectoryReader; import org.elasticsearch.common.lucene.search.Queries; import org.elasticsearch.common.lucene.uid.Versions; import org.elasticsearch.common.lucene.uid.VersionsAndSeqNoResolver; import org.elasticsearch.common.lucene.uid.VersionsAndSeqNoResolver.DocIdAndSeqNo; import org.elasticsearch.common.metrics.CounterMetric; import org.elasticsearch.common.metrics.MeanMetric; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.util.Maps; import org.elasticsearch.common.util.concurrent.AbstractRunnable; import org.elasticsearch.common.util.concurrent.AsyncIOProcessor; import org.elasticsearch.common.util.concurrent.KeyedLock; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.core.Assertions; import org.elasticsearch.core.Booleans; import org.elasticsearch.core.IOUtils; import org.elasticsearch.core.Nullable; import org.elasticsearch.core.Releasable; import org.elasticsearch.core.SuppressForbidden; import org.elasticsearch.core.Tuple; import org.elasticsearch.env.Environment; import org.elasticsearch.index.IndexMode; import org.elasticsearch.index.IndexSettings; import org.elasticsearch.index.IndexVersion; import org.elasticsearch.index.VersionType; import org.elasticsearch.index.cache.query.TrivialQueryCachingPolicy; import org.elasticsearch.index.mapper.DocumentParser; import org.elasticsearch.index.mapper.IdFieldMapper; import org.elasticsearch.index.mapper.LuceneDocument; import org.elasticsearch.index.mapper.MappingLookup; import org.elasticsearch.index.mapper.ParsedDocument; import org.elasticsearch.index.mapper.SeqNoFieldMapper; import org.elasticsearch.index.mapper.SourceFieldMapper; import org.elasticsearch.index.mapper.Uid; import org.elasticsearch.index.merge.MergeStats; import org.elasticsearch.index.merge.OnGoingMerge; import org.elasticsearch.index.seqno.LocalCheckpointTracker; import org.elasticsearch.index.seqno.SeqNoStats; import org.elasticsearch.index.seqno.SequenceNumbers; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.index.shard.ShardLongFieldRange; import org.elasticsearch.index.store.Store; import org.elasticsearch.index.translog.Translog; import org.elasticsearch.index.translog.TranslogConfig; import org.elasticsearch.index.translog.TranslogCorruptedException; import org.elasticsearch.index.translog.TranslogDeletionPolicy; import org.elasticsearch.index.translog.TranslogStats; import org.elasticsearch.search.suggest.completion.CompletionStats; import org.elasticsearch.threadpool.ThreadPool; import java.io.Closeable; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.ReentrantLock; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.LongConsumer; import java.util.function.LongSupplier; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.elasticsearch.core.Strings.format; public class InternalEngine extends Engine { /** * When we last pruned expired tombstones from versionMap.deletes: */ private volatile long lastDeleteVersionPruneTimeMSec; private final Translog translog; private final ElasticsearchConcurrentMergeScheduler mergeScheduler; private final IndexWriter indexWriter; private final ExternalReaderManager externalReaderManager; private final ElasticsearchReaderManager internalReaderManager; private final ReentrantLock flushLock = new ReentrantLock(); private final ReentrantLock optimizeLock = new ReentrantLock(); // A uid (in the form of BytesRef) to the version map // we use the hashed variant since we iterate over it and check removal and additions on existing keys private final LiveVersionMap versionMap; private final LiveVersionMapArchive liveVersionMapArchive; // Records the last known generation during which LiveVersionMap was in unsafe mode. This indicates that only after this // generation it is safe to rely on the LiveVersionMap for a real-time get. // TODO: move the following two to the stateless plugin private final AtomicLong lastUnsafeSegmentGenerationForGets; // Records the segment generation for the currently ongoing commit if any, or the last finished commit otherwise. private final AtomicLong preCommitSegmentGeneration = new AtomicLong(-1); private volatile SegmentInfos lastCommittedSegmentInfos; private final IndexThrottle throttle; private final LocalCheckpointTracker localCheckpointTracker; private final CombinedDeletionPolicy combinedDeletionPolicy; // How many callers are currently requesting index throttling. Currently there are only two situations where we do this: when merges // are falling behind and when writing indexing buffer to disk is too slow. When this is 0, there is no throttling, else we throttling // incoming indexing ops to a single thread: private final AtomicInteger throttleRequestCount = new AtomicInteger(); private final AtomicBoolean pendingTranslogRecovery = new AtomicBoolean(false); private final AtomicLong maxUnsafeAutoIdTimestamp = new AtomicLong(-1); private final AtomicLong maxSeenAutoIdTimestamp = new AtomicLong(-1); // max_seq_no_of_updates_or_deletes tracks the max seq_no of update or delete operations that have been processed in this engine. // An index request is considered as an update if it overwrites existing documents with the same docId in the Lucene index. // The value of this marker never goes backwards, and is tracked/updated differently on primary and replica. private final AtomicLong maxSeqNoOfUpdatesOrDeletes; private final CounterMetric numVersionLookups = new CounterMetric(); private final CounterMetric numIndexVersionsLookups = new CounterMetric(); // Lucene operations since this engine was opened - not include operations from existing segments. private final CounterMetric numDocDeletes = new CounterMetric(); private final CounterMetric numDocAppends = new CounterMetric(); private final CounterMetric numDocUpdates = new CounterMetric(); private final MeanMetric totalFlushTimeExcludingWaitingOnLock = new MeanMetric(); private final NumericDocValuesField softDeletesField = Lucene.newSoftDeletesField(); private final SoftDeletesPolicy softDeletesPolicy; private final LastRefreshedCheckpointListener lastRefreshedCheckpointListener; private final FlushListeners flushListener; private final AsyncIOProcessor<Tuple<Long, Translog.Location>> translogSyncProcessor; private final CompletionStatsCache completionStatsCache; private final AtomicBoolean trackTranslogLocation = new AtomicBoolean(false); private final KeyedLock<Long> noOpKeyedLock = new KeyedLock<>(); private final AtomicBoolean shouldPeriodicallyFlushAfterBigMerge = new AtomicBoolean(false); /** * If multiple writes passed {@link InternalEngine#tryAcquireInFlightDocs(Operation, int)} but they haven't adjusted * {@link IndexWriter#getPendingNumDocs()} yet, then IndexWriter can fail with too many documents. In this case, we have to fail * the engine because we already generated sequence numbers for write operations; otherwise we will have gaps in sequence numbers. * To avoid this, we keep track the number of documents that are being added to IndexWriter, and account it in * {@link InternalEngine#tryAcquireInFlightDocs(Operation, int)}. Although we can double count some inFlight documents in IW and Engine, * this shouldn't be an issue because it happens for a short window and we adjust the inFlightDocCount once an indexing is completed. */ private final AtomicLong inFlightDocCount = new AtomicLong(); private final int maxDocs; @Nullable private final String historyUUID; /** * UUID value that is updated every time the engine is force merged. */ @Nullable private volatile String forceMergeUUID; private final LongSupplier relativeTimeInNanosSupplier; private volatile long lastFlushTimestamp; private final ByteSizeValue totalDiskSpace; protected static final String REAL_TIME_GET_REFRESH_SOURCE = "realtime_get"; protected static final String UNSAFE_VERSION_MAP_REFRESH_SOURCE = "unsafe_version_map"; @SuppressWarnings("this-escape") public InternalEngine(EngineConfig engineConfig) { this(engineConfig, IndexWriter.MAX_DOCS, LocalCheckpointTracker::new); } @SuppressWarnings("this-escape") InternalEngine(EngineConfig engineConfig, int maxDocs, BiFunction<Long, Long, LocalCheckpointTracker> localCheckpointTrackerSupplier) { super(engineConfig); this.maxDocs = maxDocs; this.relativeTimeInNanosSupplier = config().getRelativeTimeInNanosSupplier(); this.lastFlushTimestamp = relativeTimeInNanosSupplier.getAsLong(); // default to creation timestamp this.liveVersionMapArchive = createLiveVersionMapArchive(); this.versionMap = new LiveVersionMap(liveVersionMapArchive); final TranslogDeletionPolicy translogDeletionPolicy = new TranslogDeletionPolicy(); store.incRef(); IndexWriter writer = null; Translog translog = null; ExternalReaderManager externalReaderManager = null; ElasticsearchReaderManager internalReaderManager = null; EngineMergeScheduler scheduler = null; boolean success = false; try { this.lastDeleteVersionPruneTimeMSec = engineConfig.getThreadPool().relativeTimeInMillis(); mergeScheduler = scheduler = new EngineMergeScheduler(engineConfig.getShardId(), engineConfig.getIndexSettings()); throttle = new IndexThrottle(); try { store.trimUnsafeCommits(config().getTranslogConfig().getTranslogPath()); translog = openTranslog( engineConfig, translogDeletionPolicy, engineConfig.getGlobalCheckpointSupplier(), translogPersistedSeqNoConsumer() ); assert translog.getGeneration() != null; this.translog = translog; this.totalDiskSpace = new ByteSizeValue(Environment.getFileStore(translog.location()).getTotalSpace(), ByteSizeUnit.BYTES); this.softDeletesPolicy = newSoftDeletesPolicy(); this.combinedDeletionPolicy = new CombinedDeletionPolicy( logger, translogDeletionPolicy, softDeletesPolicy, translog::getLastSyncedGlobalCheckpoint, newCommitsListener() ); this.localCheckpointTracker = createLocalCheckpointTracker(localCheckpointTrackerSupplier); writer = createWriter(); bootstrapAppendOnlyInfoFromWriter(writer); final Map<String, String> commitData = commitDataAsMap(writer); historyUUID = loadHistoryUUID(commitData); forceMergeUUID = commitData.get(FORCE_MERGE_UUID_KEY); indexWriter = writer; } catch (IOException | TranslogCorruptedException e) { throw new EngineCreationFailureException(shardId, "failed to create engine", e); } catch (AssertionError e) { // IndexWriter throws AssertionError on init, if asserts are enabled, if any files don't exist, but tests that // randomly throw FNFE/NSFE can also hit this: if (ExceptionsHelper.stackTrace(e).contains("org.apache.lucene.index.IndexWriter.filesExist")) { throw new EngineCreationFailureException(shardId, "failed to create engine", e); } else { throw e; } } externalReaderManager = createReaderManager(new RefreshWarmerListener(logger, isClosed, engineConfig)); internalReaderManager = externalReaderManager.internalReaderManager; this.internalReaderManager = internalReaderManager; this.externalReaderManager = externalReaderManager; internalReaderManager.addListener(versionMap); this.lastUnsafeSegmentGenerationForGets = new AtomicLong(lastCommittedSegmentInfos.getGeneration()); assert pendingTranslogRecovery.get() == false : "translog recovery can't be pending before we set it"; // don't allow commits until we are done with recovering pendingTranslogRecovery.set(true); for (ReferenceManager.RefreshListener listener : engineConfig.getExternalRefreshListener()) { this.externalReaderManager.addListener(listener); } for (ReferenceManager.RefreshListener listener : engineConfig.getInternalRefreshListener()) { this.internalReaderManager.addListener(listener); } this.lastRefreshedCheckpointListener = new LastRefreshedCheckpointListener(localCheckpointTracker.getProcessedCheckpoint()); this.internalReaderManager.addListener(lastRefreshedCheckpointListener); maxSeqNoOfUpdatesOrDeletes = new AtomicLong(SequenceNumbers.max(localCheckpointTracker.getMaxSeqNo(), translog.getMaxSeqNo())); if (localCheckpointTracker.getPersistedCheckpoint() < localCheckpointTracker.getMaxSeqNo()) { try (Searcher searcher = acquireSearcher("restore_version_map_and_checkpoint_tracker", SearcherScope.INTERNAL)) { restoreVersionMapAndCheckpointTracker( Lucene.wrapAllDocsLive(searcher.getDirectoryReader()), engineConfig.getIndexSettings().getIndexVersionCreated() ); } catch (IOException e) { throw new EngineCreationFailureException( config().getShardId(), "failed to restore version map and local checkpoint tracker", e ); } } completionStatsCache = new CompletionStatsCache(() -> acquireSearcher("completion_stats")); this.externalReaderManager.addListener(completionStatsCache); this.flushListener = new FlushListeners(logger, engineConfig.getThreadPool().getThreadContext()); this.translogSyncProcessor = createTranslogSyncProcessor(logger, engineConfig.getThreadPool().getThreadContext()); success = true; } finally { if (success == false) { IOUtils.closeWhileHandlingException(writer, translog, internalReaderManager, externalReaderManager, scheduler); if (isClosed.get() == false) { // failure we need to dec the store reference store.decRef(); } } } logger.trace("created new InternalEngine"); } private LocalCheckpointTracker createLocalCheckpointTracker( BiFunction<Long, Long, LocalCheckpointTracker> localCheckpointTrackerSupplier ) throws IOException { final long maxSeqNo; final long localCheckpoint; final SequenceNumbers.CommitInfo seqNoStats = SequenceNumbers.loadSeqNoInfoFromLuceneCommit( store.readLastCommittedSegmentsInfo().userData.entrySet() ); maxSeqNo = seqNoStats.maxSeqNo; localCheckpoint = seqNoStats.localCheckpoint; logger.trace("recovered maximum sequence number [{}] and local checkpoint [{}]", maxSeqNo, localCheckpoint); return localCheckpointTrackerSupplier.apply(maxSeqNo, localCheckpoint); } protected LongConsumer translogPersistedSeqNoConsumer() { return seqNo -> { final LocalCheckpointTracker tracker = getLocalCheckpointTracker(); assert tracker != null || getTranslog().isOpen() == false; if (tracker != null) { tracker.markSeqNoAsPersisted(seqNo); } }; } private SoftDeletesPolicy newSoftDeletesPolicy() throws IOException { final Map<String, String> commitUserData = store.readLastCommittedSegmentsInfo().userData; final long lastMinRetainedSeqNo; if (commitUserData.containsKey(Engine.MIN_RETAINED_SEQNO)) { lastMinRetainedSeqNo = Long.parseLong(commitUserData.get(Engine.MIN_RETAINED_SEQNO)); } else { lastMinRetainedSeqNo = Long.parseLong(commitUserData.get(SequenceNumbers.MAX_SEQ_NO)) + 1; } return new SoftDeletesPolicy( translog::getLastSyncedGlobalCheckpoint, lastMinRetainedSeqNo, engineConfig.getIndexSettings().getSoftDeleteRetentionOperations(), engineConfig.retentionLeasesSupplier() ); } @Nullable private CombinedDeletionPolicy.CommitsListener newCommitsListener() { Engine.IndexCommitListener listener = engineConfig.getIndexCommitListener(); if (listener != null) { final IndexCommitListener wrappedListener = Assertions.ENABLED ? assertingCommitsOrderListener(listener) : listener; return new CombinedDeletionPolicy.CommitsListener() { @Override public void onNewAcquiredCommit(final IndexCommit commit, final Set<String> additionalFiles) { final IndexCommitRef indexCommitRef = acquireIndexCommitRef(() -> commit); var primaryTerm = config().getPrimaryTermSupplier().getAsLong(); assert indexCommitRef.getIndexCommit() == commit; wrappedListener.onNewCommit(shardId, store, primaryTerm, indexCommitRef, additionalFiles); } @Override public void onDeletedCommit(IndexCommit commit) { wrappedListener.onIndexCommitDelete(shardId, commit); } }; } return null; } private IndexCommitListener assertingCommitsOrderListener(final IndexCommitListener listener) { final AtomicLong generation = new AtomicLong(0L); return new IndexCommitListener() { @Override public void onNewCommit( ShardId shardId, Store store, long primaryTerm, IndexCommitRef indexCommitRef, Set<String> additionalFiles ) { final long nextGen = indexCommitRef.getIndexCommit().getGeneration(); final long prevGen = generation.getAndSet(nextGen); assert prevGen < nextGen : "Expect new commit generation " + nextGen + " to be greater than previous commit generation " + prevGen + " for shard " + shardId; listener.onNewCommit(shardId, store, primaryTerm, indexCommitRef, additionalFiles); } @Override public void onIndexCommitDelete(ShardId shardId, IndexCommit deletedCommit) { listener.onIndexCommitDelete(shardId, deletedCommit); } }; } @Override public CompletionStats completionStats(String... fieldNamePatterns) { return completionStatsCache.get(fieldNamePatterns); } /** * This reference manager delegates all it's refresh calls to another (internal) ReaderManager * The main purpose for this is that if we have external refreshes happening we don't issue extra * refreshes to clear version map memory etc. this can cause excessive segment creation if heavy indexing * is happening and the refresh interval is low (ie. 1 sec) * * This also prevents segment starvation where an internal reader holds on to old segments literally forever * since no indexing is happening and refreshes are only happening to the external reader manager, while with * this specialized implementation an external refresh will immediately be reflected on the internal reader * and old segments can be released in the same way previous version did this (as a side-effect of _refresh) */ @SuppressForbidden(reason = "reference counting is required here") private static final class ExternalReaderManager extends ReferenceManager<ElasticsearchDirectoryReader> { private final BiConsumer<ElasticsearchDirectoryReader, ElasticsearchDirectoryReader> refreshListener; private final ElasticsearchReaderManager internalReaderManager; private boolean isWarmedUp; // guarded by refreshLock ExternalReaderManager( ElasticsearchReaderManager internalReaderManager, BiConsumer<ElasticsearchDirectoryReader, ElasticsearchDirectoryReader> refreshListener ) throws IOException { this.refreshListener = refreshListener; this.internalReaderManager = internalReaderManager; this.current = internalReaderManager.acquire(); // steal the reference without warming up } @Override protected ElasticsearchDirectoryReader refreshIfNeeded(ElasticsearchDirectoryReader referenceToRefresh) throws IOException { // we simply run a blocking refresh on the internal reference manager and then steal it's reader // it's a save operation since we acquire the reader which incs it's reference but then down the road // steal it by calling incRef on the "stolen" reader internalReaderManager.maybeRefreshBlocking(); final ElasticsearchDirectoryReader newReader = internalReaderManager.acquire(); if (isWarmedUp == false || newReader != referenceToRefresh) { boolean success = false; try { refreshListener.accept(newReader, isWarmedUp ? referenceToRefresh : null); isWarmedUp = true; success = true; } finally { if (success == false) { internalReaderManager.release(newReader); } } } // nothing has changed - both ref managers share the same instance so we can use reference equality if (referenceToRefresh == newReader) { internalReaderManager.release(newReader); return null; } else { return newReader; // steal the reference } } @Override protected boolean tryIncRef(ElasticsearchDirectoryReader reference) { return reference.tryIncRef(); } @Override protected int getRefCount(ElasticsearchDirectoryReader reference) { return reference.getRefCount(); } @Override protected void decRef(ElasticsearchDirectoryReader reference) throws IOException { reference.decRef(); } } @Override final boolean assertSearcherIsWarmedUp(String source, SearcherScope scope) { if (scope == SearcherScope.EXTERNAL) { switch (source) { // we can access segment_stats while a shard is still in the recovering state. case "segments": case "segments_stats": break; default: assert externalReaderManager.isWarmedUp : "searcher was not warmed up yet for source[" + source + "]"; } } return true; } @Override public int restoreLocalHistoryFromTranslog(TranslogRecoveryRunner translogRecoveryRunner) throws IOException { try (var ignored = acquireEnsureOpenRef()) { final long localCheckpoint = localCheckpointTracker.getProcessedCheckpoint(); try (Translog.Snapshot snapshot = getTranslog().newSnapshot(localCheckpoint + 1, Long.MAX_VALUE)) { return translogRecoveryRunner.run(this, snapshot); } } } @Override public int fillSeqNoGaps(long primaryTerm) throws IOException { try (var ignored = acquireEnsureOpenRef()) { final long localCheckpoint = localCheckpointTracker.getProcessedCheckpoint(); final long maxSeqNo = localCheckpointTracker.getMaxSeqNo(); int numNoOpsAdded = 0; for (long seqNo = localCheckpoint + 1; seqNo <= maxSeqNo; seqNo = localCheckpointTracker.getProcessedCheckpoint() + 1 /* leap-frog the local checkpoint */) { innerNoOp(new NoOp(seqNo, primaryTerm, Operation.Origin.PRIMARY, System.nanoTime(), "filling gaps")); numNoOpsAdded++; assert seqNo <= localCheckpointTracker.getProcessedCheckpoint() : "local checkpoint did not advance; was [" + seqNo + "], now [" + localCheckpointTracker.getProcessedCheckpoint() + "]"; } syncTranslog(); // to persist noops associated with the advancement of the local checkpoint assert localCheckpointTracker.getPersistedCheckpoint() == maxSeqNo : "persisted local checkpoint did not advance to max seq no; is [" + localCheckpointTracker.getPersistedCheckpoint() + "], max seq no [" + maxSeqNo + "]"; return numNoOpsAdded; } } private void bootstrapAppendOnlyInfoFromWriter(IndexWriter writer) { for (Map.Entry<String, String> entry : writer.getLiveCommitData()) { if (MAX_UNSAFE_AUTO_ID_TIMESTAMP_COMMIT_ID.equals(entry.getKey())) { assert maxUnsafeAutoIdTimestamp.get() == -1 : "max unsafe timestamp was assigned already [" + maxUnsafeAutoIdTimestamp.get() + "]"; updateAutoIdTimestamp(Long.parseLong(entry.getValue()), true); } } } @Override public void recoverFromTranslog(TranslogRecoveryRunner translogRecoveryRunner, long recoverUpToSeqNo, ActionListener<Void> listener) { ActionListener.runWithResource(listener, this::acquireEnsureOpenRef, (l, ignoredRef) -> { if (pendingTranslogRecovery.get() == false) { throw new IllegalStateException("Engine has already been recovered"); } recoverFromTranslogInternal(translogRecoveryRunner, recoverUpToSeqNo, l.delegateResponse((ll, e) -> { try { pendingTranslogRecovery.set(true); // just play safe and never allow commits on this see #ensureCanFlush failEngine("failed to recover from translog", e); } catch (Exception inner) { e.addSuppressed(inner); } ll.onFailure(e); })); }); } @Override public void skipTranslogRecovery() { assert pendingTranslogRecovery.get() : "translogRecovery is not pending but should be"; pendingTranslogRecovery.set(false); // we are good - now we can commit } private void recoverFromTranslogInternal( TranslogRecoveryRunner translogRecoveryRunner, long recoverUpToSeqNo, ActionListener<Void> listener ) { ActionListener.run(listener, l -> { final int opsRecovered; final long localCheckpoint = getProcessedLocalCheckpoint(); if (localCheckpoint < recoverUpToSeqNo) { try (Translog.Snapshot snapshot = newTranslogSnapshot(localCheckpoint + 1, recoverUpToSeqNo)) { opsRecovered = translogRecoveryRunner.run(this, snapshot); } catch (Exception e) { throw new EngineException(shardId, "failed to recover from translog", e); } } else { opsRecovered = 0; } // flush if we recovered something or if we have references to older translogs // note: if opsRecovered == 0 and we have older translogs it means they are corrupted or 0 length. assert pendingTranslogRecovery.get() : "translogRecovery is not pending but should be"; pendingTranslogRecovery.set(false); // we are good - now we can commit logger.trace( () -> format( "flushing post recovery from translog: ops recovered [%s], current translog generation [%s]", opsRecovered, translog.currentFileGeneration() ) ); // flush might do something async and complete the listener on a different thread, from which we must fork back to a generic // thread to continue with recovery, but if it doesn't do anything async then there's no need to fork, hence why we use a // SubscribableListener here final var flushListener = new SubscribableListener<FlushResult>(); flush(false, true, flushListener); flushListener.addListener(l.delegateFailureAndWrap((ll, r) -> { translog.trimUnreferencedReaders(); ll.onResponse(null); }), engineConfig.getThreadPool().generic(), null); }); } protected Translog.Snapshot newTranslogSnapshot(long fromSeqNo, long toSeqNo) throws IOException { return translog.newSnapshot(fromSeqNo, toSeqNo); } private Translog openTranslog( EngineConfig engineConfig, TranslogDeletionPolicy translogDeletionPolicy, LongSupplier globalCheckpointSupplier, LongConsumer persistedSequenceNumberConsumer ) throws IOException { final TranslogConfig translogConfig = engineConfig.getTranslogConfig(); final Map<String, String> userData = store.readLastCommittedSegmentsInfo().getUserData(); final String translogUUID = Objects.requireNonNull(userData.get(Translog.TRANSLOG_UUID_KEY)); // We expect that this shard already exists, so it must already have an existing translog else something is badly wrong! return new Translog( translogConfig, translogUUID, translogDeletionPolicy, globalCheckpointSupplier, engineConfig.getPrimaryTermSupplier(), persistedSequenceNumberConsumer ); } // Package private for testing purposes only Translog getTranslog() { ensureOpen(); return translog; } // Package private for testing purposes only boolean hasAcquiredIndexCommits() { return combinedDeletionPolicy.hasAcquiredIndexCommits(); } @Override public boolean isTranslogSyncNeeded() { return getTranslog().syncNeeded(); } private AsyncIOProcessor<Tuple<Long, Translog.Location>> createTranslogSyncProcessor(Logger logger, ThreadContext threadContext) { return new AsyncIOProcessor<>(logger, 1024, threadContext) { @Override protected void write(List<Tuple<Tuple<Long, Translog.Location>, Consumer<Exception>>> candidates) throws IOException { try { Translog.Location location = Translog.Location.EMPTY; long processGlobalCheckpoint = SequenceNumbers.UNASSIGNED_SEQ_NO; for (Tuple<Tuple<Long, Translog.Location>, Consumer<Exception>> syncMarkers : candidates) { Tuple<Long, Translog.Location> marker = syncMarkers.v1(); long globalCheckpointToSync = marker.v1(); if (globalCheckpointToSync != SequenceNumbers.UNASSIGNED_SEQ_NO) { processGlobalCheckpoint = SequenceNumbers.max(processGlobalCheckpoint, globalCheckpointToSync); } location = location.compareTo(marker.v2()) >= 0 ? location : marker.v2(); } final boolean synced = translog.ensureSynced(location, processGlobalCheckpoint); if (synced) { revisitIndexDeletionPolicyOnTranslogSynced(); } } catch (AlreadyClosedException ex) { // that's fine since we already synced everything on engine close - this also is conform with the methods // documentation } catch (IOException ex) { // if this fails we are in deep shit - fail the request logger.debug("failed to sync translog", ex); throw ex; } } }; } @Override public void asyncEnsureTranslogSynced(Translog.Location location, Consumer<Exception> listener) { translogSyncProcessor.put(new Tuple<>(SequenceNumbers.NO_OPS_PERFORMED, location), listener); } @Override public void asyncEnsureGlobalCheckpointSynced(long globalCheckpoint, Consumer<Exception> listener) { translogSyncProcessor.put(new Tuple<>(globalCheckpoint, Translog.Location.EMPTY), listener); } @Override public void syncTranslog() throws IOException { translog.sync(); revisitIndexDeletionPolicyOnTranslogSynced(); } @Override public TranslogStats getTranslogStats() { return getTranslog().stats(); } @Override public Translog.Location getTranslogLastWriteLocation() { return getTranslog().getLastWriteLocation(); } private void revisitIndexDeletionPolicyOnTranslogSynced() throws IOException { if (combinedDeletionPolicy.hasUnreferencedCommits()) { indexWriter.deleteUnusedFiles(); } translog.trimUnreferencedReaders(); } @Override public String getHistoryUUID() { return historyUUID; } /** returns the force merge uuid for the engine */ @Nullable public String getForceMergeUUID() { return forceMergeUUID; } /** Returns how many bytes we are currently moving from indexing buffer to segments on disk */ @Override public long getWritingBytes() { return indexWriter.getFlushingBytes() + versionMap.getRefreshingBytes(); } /** * Reads the current stored history ID from the IW commit data. */ private static String loadHistoryUUID(Map<String, String> commitData) { final String uuid = commitData.get(HISTORY_UUID_KEY); if (uuid == null) { throw new IllegalStateException("commit doesn't contain history uuid"); } return uuid; } private ExternalReaderManager createReaderManager(RefreshWarmerListener externalRefreshListener) throws EngineException { boolean success = false; ElasticsearchDirectoryReader directoryReader = null; ElasticsearchReaderManager internalReaderManager = null; try { try { directoryReader = ElasticsearchDirectoryReader.wrap(DirectoryReader.open(indexWriter), shardId); lastCommittedSegmentInfos = store.readLastCommittedSegmentsInfo(); internalReaderManager = createInternalReaderManager(directoryReader); ExternalReaderManager externalReaderManager = new ExternalReaderManager(internalReaderManager, externalRefreshListener); success = true; return externalReaderManager; } catch (IOException e) { maybeFailEngine("start", e); try { indexWriter.rollback(); } catch (IOException inner) { // iw is closed below e.addSuppressed(inner); } throw new EngineCreationFailureException(shardId, "failed to open reader on writer", e); } } finally { if (success == false) { // release everything we created on a failure // make sure that we close the directory reader even if the internal reader manager has failed to initialize var reader = internalReaderManager == null ? directoryReader : internalReaderManager; IOUtils.closeWhileHandlingException(reader, indexWriter); } } } protected ElasticsearchReaderManager createInternalReaderManager(ElasticsearchDirectoryReader directoryReader) { return new ElasticsearchReaderManager(directoryReader); } public final AtomicLong translogGetCount = new AtomicLong(); // number of times realtime get was done on translog public final AtomicLong translogInMemorySegmentsCount = new AtomicLong(); // number of times in-memory index needed to be created private GetResult getFromTranslog( Get get, Translog.Index index, MappingLookup mappingLookup, DocumentParser documentParser, Function<Searcher, Searcher> searcherWrapper ) throws IOException { assert get.isReadFromTranslog(); translogGetCount.incrementAndGet(); final TranslogDirectoryReader inMemoryReader = new TranslogDirectoryReader( shardId, index, mappingLookup, documentParser, config(), translogInMemorySegmentsCount::incrementAndGet ); final Engine.Searcher searcher = new Engine.Searcher( "realtime_get", ElasticsearchDirectoryReader.wrap(inMemoryReader, shardId), config().getSimilarity(), null /*query cache disabled*/, TrivialQueryCachingPolicy.NEVER, inMemoryReader ); final Searcher wrappedSearcher = searcherWrapper.apply(searcher); return getFromSearcher(get, wrappedSearcher, true); } @Override public GetResult get( Get get, MappingLookup mappingLookup, DocumentParser documentParser, Function<Engine.Searcher, Engine.Searcher> searcherWrapper ) { assert assertGetUsesIdField(get); try (var ignored = acquireEnsureOpenRef()) { if (get.realtime()) { var result = realtimeGetUnderLock(get, mappingLookup, documentParser, searcherWrapper, true); assert result != null : "real-time get result must not be null"; return result; } else { // we expose what has been externally expose in a point in time snapshot via an explicit refresh return getFromSearcher(get, acquireSearcher("get", SearcherScope.EXTERNAL, searcherWrapper), false); } } } @Override public GetResult getFromTranslog( Get get, MappingLookup mappingLookup, DocumentParser documentParser, Function<Searcher, Searcher> searcherWrapper ) { assert assertGetUsesIdField(get); try (var ignored = acquireEnsureOpenRef()) { return realtimeGetUnderLock(get, mappingLookup, documentParser, searcherWrapper, false); } } /** * @param getFromSearcher indicates whether we also try the internal searcher if not found in translog. In the case where * we just started tracking locations in the translog, we always use the internal searcher. */ protected GetResult realtimeGetUnderLock( Get get, MappingLookup mappingLookup, DocumentParser documentParser, Function<Engine.Searcher, Engine.Searcher> searcherWrapper, boolean getFromSearcher ) { assert isDrainedForClose() == false; assert get.realtime(); final VersionValue versionValue; try (Releasable ignore = versionMap.acquireLock(get.uid().bytes())) { // we need to lock here to access the version map to do this truly in RT versionValue = getVersionFromMap(get.uid().bytes()); } try { boolean getFromSearcherIfNotInTranslog = getFromSearcher; if (versionValue != null) { /* * Once we've seen the ID in the live version map, in two cases it is still possible not to * be able to follow up with serving the get from the translog: * 1. It is possible that once attempt handling the get, we won't see the doc in the translog * since it might have been moved out. * TODO: ideally we should keep around translog entries long enough to cover this case * 2. We might not be tracking translog locations in the live version map (see @link{trackTranslogLocation}) * * In these cases, we should always fall back to get the doc from the internal searcher. */ getFromSearcherIfNotInTranslog = true; if (versionValue.isDelete()) { return GetResult.NOT_EXISTS; } if (get.versionType().isVersionConflictForReads(versionValue.version, get.version())) { throw new VersionConflictEngineException( shardId, "[" + get.id() + "]", get.versionType().explainConflictForReads(versionValue.version, get.version()) ); } if (get.getIfSeqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO && (get.getIfSeqNo() != versionValue.seqNo || get.getIfPrimaryTerm() != versionValue.term)) { throw new VersionConflictEngineException( shardId, get.id(), get.getIfSeqNo(), get.getIfPrimaryTerm(), versionValue.seqNo, versionValue.term ); } if (get.isReadFromTranslog()) { if (versionValue.getLocation() != null) { try { final Translog.Operation operation = translog.readOperation(versionValue.getLocation()); if (operation != null) { return getFromTranslog(get, (Translog.Index) operation, mappingLookup, documentParser, searcherWrapper); } } catch (IOException e) { maybeFailEngine("realtime_get", e); // lets check if the translog has failed with a tragic event throw new EngineException(shardId, "failed to read operation from translog", e); } } else { // We need to start tracking translog locations in the live version map. trackTranslogLocation.set(true); } } assert versionValue.seqNo >= 0 : versionValue; refreshIfNeeded(REAL_TIME_GET_REFRESH_SOURCE, versionValue.seqNo); } if (getFromSearcherIfNotInTranslog) { return getFromSearcher(get, acquireSearcher("realtime_get", SearcherScope.INTERNAL, searcherWrapper), false); } return null; } finally { assert isDrainedForClose() == false; } } /** * the status of the current doc version in lucene, compared to the version in an incoming * operation */ enum OpVsLuceneDocStatus { /** the op is more recent than the one that last modified the doc found in lucene*/ OP_NEWER, /** the op is older or the same as the one that last modified the doc found in lucene*/ OP_STALE_OR_EQUAL, /** no doc was found in lucene */ LUCENE_DOC_NOT_FOUND } private static OpVsLuceneDocStatus compareOpToVersionMapOnSeqNo(String id, long seqNo, long primaryTerm, VersionValue versionValue) { Objects.requireNonNull(versionValue); if (seqNo > versionValue.seqNo) { return OpVsLuceneDocStatus.OP_NEWER; } else if (seqNo == versionValue.seqNo) { assert versionValue.term == primaryTerm : "primary term not matched; id=" + id + " seq_no=" + seqNo + " op_term=" + primaryTerm + " existing_term=" + versionValue.term; return OpVsLuceneDocStatus.OP_STALE_OR_EQUAL; } else { return OpVsLuceneDocStatus.OP_STALE_OR_EQUAL; } } private OpVsLuceneDocStatus compareOpToLuceneDocBasedOnSeqNo(final Operation op) throws IOException { assert op.seqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO : "resolving ops based on seq# but no seqNo is found"; final OpVsLuceneDocStatus status; VersionValue versionValue = getVersionFromMap(op.uid().bytes()); assert incrementVersionLookup(); if (versionValue != null) { status = compareOpToVersionMapOnSeqNo(op.id(), op.seqNo(), op.primaryTerm(), versionValue); } else { // load from index assert incrementIndexVersionLookup(); try (Searcher searcher = acquireSearcher("load_seq_no", SearcherScope.INTERNAL)) { final DocIdAndSeqNo docAndSeqNo = VersionsAndSeqNoResolver.loadDocIdAndSeqNo(searcher.getIndexReader(), op.uid()); if (docAndSeqNo == null) { status = OpVsLuceneDocStatus.LUCENE_DOC_NOT_FOUND; } else if (op.seqNo() > docAndSeqNo.seqNo) { status = OpVsLuceneDocStatus.OP_NEWER; } else if (op.seqNo() == docAndSeqNo.seqNo) { assert localCheckpointTracker.hasProcessed(op.seqNo()) : "local checkpoint tracker is not updated seq_no=" + op.seqNo() + " id=" + op.id(); status = OpVsLuceneDocStatus.OP_STALE_OR_EQUAL; } else { status = OpVsLuceneDocStatus.OP_STALE_OR_EQUAL; } } } return status; } /** resolves the current version of the document, returning null if not found */ private VersionValue resolveDocVersion(final Operation op, boolean loadSeqNo) throws IOException { assert incrementVersionLookup(); // used for asserting in tests VersionValue versionValue = getVersionFromMap(op.uid().bytes()); if (versionValue == null) { assert incrementIndexVersionLookup(); // used for asserting in tests final VersionsAndSeqNoResolver.DocIdAndVersion docIdAndVersion; try (Searcher searcher = acquireSearcher("load_version", SearcherScope.INTERNAL)) { if (engineConfig.getIndexSettings().getMode() == IndexMode.TIME_SERIES) { assert engineConfig.getLeafSorter() == DataStream.TIMESERIES_LEAF_READERS_SORTER; docIdAndVersion = VersionsAndSeqNoResolver.timeSeriesLoadDocIdAndVersion( searcher.getIndexReader(), op.uid(), op.id(), loadSeqNo ); } else { docIdAndVersion = VersionsAndSeqNoResolver.timeSeriesLoadDocIdAndVersion( searcher.getIndexReader(), op.uid(), loadSeqNo ); } } if (docIdAndVersion != null) { versionValue = new IndexVersionValue(null, docIdAndVersion.version, docIdAndVersion.seqNo, docIdAndVersion.primaryTerm); } } else if (engineConfig.isEnableGcDeletes() && versionValue.isDelete() && (engineConfig.getThreadPool().relativeTimeInMillis() - ((DeleteVersionValue) versionValue).time) > getGcDeletesInMillis()) { versionValue = null; } return versionValue; } private VersionValue getVersionFromMap(BytesRef id) { if (versionMap.isUnsafe()) { synchronized (versionMap) { // we are switching from an unsafe map to a safe map. This might happen concurrently // but we only need to do this once since the last operation per ID is to add to the version // map so once we pass this point we can safely lookup from the version map. if (versionMap.isUnsafe()) { refreshInternalSearcher(UNSAFE_VERSION_MAP_REFRESH_SOURCE, true); // After the refresh, the doc that triggered it must now be part of the last commit. // In rare cases, there could be other flush cycles completed in between the above line // and the line below which push the last commit generation further. But that's OK. // The invariant here is that doc is available within the generations of commits upto // lastUnsafeSegmentGenerationForGets (inclusive). Therefore it is ok for it be larger // which means the search shard needs to wait for extra generations and these generations // are guaranteed to happen since they are all committed. lastUnsafeSegmentGenerationForGets.set(lastCommittedSegmentInfos.getGeneration()); } versionMap.enforceSafeAccess(); } // The versionMap can still be unsafe at this point due to archive being unsafe } return versionMap.getUnderLock(id); } private boolean canOptimizeAddDocument(Index index) { if (index.getAutoGeneratedIdTimestamp() != IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP) { assert index.getAutoGeneratedIdTimestamp() >= 0 : "autoGeneratedIdTimestamp must be positive but was: " + index.getAutoGeneratedIdTimestamp(); return switch (index.origin()) { case PRIMARY -> { assert assertPrimaryCanOptimizeAddDocument(index); yield true; } case PEER_RECOVERY, REPLICA -> { assert index.version() == 1 && index.versionType() == null : "version: " + index.version() + " type: " + index.versionType(); yield true; } case LOCAL_TRANSLOG_RECOVERY, LOCAL_RESET -> { assert index.isRetry(); yield true; // allow to optimize in order to update the max safe time stamp } }; } return false; } protected boolean assertPrimaryCanOptimizeAddDocument(final Index index) { assert (index.version() == Versions.MATCH_DELETED || index.version() == Versions.MATCH_ANY) && index.versionType() == VersionType.INTERNAL : "version: " + index.version() + " type: " + index.versionType(); return true; } private boolean assertIncomingSequenceNumber(final Engine.Operation.Origin origin, final long seqNo) { if (origin == Operation.Origin.PRIMARY) { assert assertPrimaryIncomingSequenceNumber(origin, seqNo); } else { // sequence number should be set when operation origin is not primary assert seqNo >= 0 : "recovery or replica ops should have an assigned seq no.; origin: " + origin; } return true; } protected boolean assertPrimaryIncomingSequenceNumber(final Engine.Operation.Origin origin, final long seqNo) { // sequence number should not be set when operation origin is primary assert seqNo == SequenceNumbers.UNASSIGNED_SEQ_NO : "primary operations must never have an assigned sequence number but was [" + seqNo + "]"; return true; } protected long generateSeqNoForOperationOnPrimary(final Operation operation) { assert operation.origin() == Operation.Origin.PRIMARY; assert operation.seqNo() == SequenceNumbers.UNASSIGNED_SEQ_NO : "ops should not have an assigned seq no. but was: " + operation.seqNo(); return doGenerateSeqNoForOperation(operation); } protected void advanceMaxSeqNoOfUpdatesOnPrimary(long seqNo) { advanceMaxSeqNoOfUpdatesOrDeletes(seqNo); } protected void advanceMaxSeqNoOfDeletesOnPrimary(long seqNo) { advanceMaxSeqNoOfUpdatesOrDeletes(seqNo); } /** * Generate the sequence number for the specified operation. * * @param operation the operation * @return the sequence number */ long doGenerateSeqNoForOperation(final Operation operation) { return localCheckpointTracker.generateSeqNo(); } @Override public IndexResult index(Index index) throws IOException { assert Objects.equals(index.uid().field(), IdFieldMapper.NAME) : index.uid().field(); final boolean doThrottle = index.origin().isRecovery() == false; try (var ignored1 = acquireEnsureOpenRef()) { assert assertIncomingSequenceNumber(index.origin(), index.seqNo()); int reservedDocs = 0; try ( Releasable ignored = versionMap.acquireLock(index.uid().bytes()); Releasable indexThrottle = doThrottle ? throttle.acquireThrottle() : () -> {} ) { lastWriteNanos = index.startTime(); /* A NOTE ABOUT APPEND ONLY OPTIMIZATIONS: * if we have an autoGeneratedID that comes into the engine we can potentially optimize * and just use addDocument instead of updateDocument and skip the entire version and index lookupVersion across the board. * Yet, we have to deal with multiple document delivery, for this we use a property of the document that is added * to detect if it has potentially been added before. We use the documents timestamp for this since it's something * that: * - doesn't change per document * - is preserved in the transaction log * - and is assigned before we start to index / replicate * NOTE: it's not important for this timestamp to be consistent across nodes etc. it's just a number that is in the common * case increasing and can be used in the failure case when we retry and resent documents to establish a happens before * relationship. For instance: * - doc A has autoGeneratedIdTimestamp = 10, isRetry = false * - doc B has autoGeneratedIdTimestamp = 9, isRetry = false * * while both docs are in flight, we disconnect on one node, reconnect and send doc A again * - now doc A' has autoGeneratedIdTimestamp = 10, isRetry = true * * if A' arrives on the shard first we update maxUnsafeAutoIdTimestamp to 10 and use update document. All subsequent * documents that arrive (A and B) will also use updateDocument since their timestamps are less than * maxUnsafeAutoIdTimestamp. While this is not strictly needed for doc B it is just much simpler to implement since it * will just de-optimize some doc in the worst case. * * if A arrives on the shard first we use addDocument since maxUnsafeAutoIdTimestamp is < 10. A` will then just be skipped * or calls updateDocument. */ final IndexingStrategy plan = indexingStrategyForOperation(index); reservedDocs = plan.reservedDocs; final IndexResult indexResult; if (plan.earlyResultOnPreFlightError.isPresent()) { assert index.origin() == Operation.Origin.PRIMARY : index.origin(); indexResult = plan.earlyResultOnPreFlightError.get(); assert indexResult.getResultType() == Result.Type.FAILURE : indexResult.getResultType(); } else { // generate or register sequence number if (index.origin() == Operation.Origin.PRIMARY) { index = new Index( index.uid(), index.parsedDoc(), generateSeqNoForOperationOnPrimary(index), index.primaryTerm(), index.version(), index.versionType(), index.origin(), index.startTime(), index.getAutoGeneratedIdTimestamp(), index.isRetry(), index.getIfSeqNo(), index.getIfPrimaryTerm() ); final boolean toAppend = plan.indexIntoLucene && plan.useLuceneUpdateDocument == false; if (toAppend == false) { advanceMaxSeqNoOfUpdatesOnPrimary(index.seqNo()); } } else { markSeqNoAsSeen(index.seqNo()); } assert index.seqNo() >= 0 : "ops should have an assigned seq no.; origin: " + index.origin(); if (plan.indexIntoLucene || plan.addStaleOpToLucene) { indexResult = indexIntoLucene(index, plan); } else { indexResult = new IndexResult( plan.versionForIndexing, index.primaryTerm(), index.seqNo(), plan.currentNotFoundOrDeleted, index.id() ); } } if (index.origin().isFromTranslog() == false) { final Translog.Location location; if (indexResult.getResultType() == Result.Type.SUCCESS) { location = translog.add(new Translog.Index(index, indexResult)); } else if (indexResult.getSeqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO) { // if we have document failure, record it as a no-op in the translog and Lucene with the generated seq_no final NoOp noOp = new NoOp( indexResult.getSeqNo(), index.primaryTerm(), index.origin(), index.startTime(), indexResult.getFailure().toString() ); location = innerNoOp(noOp).getTranslogLocation(); } else { location = null; } indexResult.setTranslogLocation(location); } if (plan.indexIntoLucene && indexResult.getResultType() == Result.Type.SUCCESS) { final Translog.Location translogLocation = trackTranslogLocation.get() ? indexResult.getTranslogLocation() : null; versionMap.maybePutIndexUnderLock( index.uid().bytes(), new IndexVersionValue(translogLocation, plan.versionForIndexing, index.seqNo(), index.primaryTerm()) ); } localCheckpointTracker.markSeqNoAsProcessed(indexResult.getSeqNo()); if (indexResult.getTranslogLocation() == null) { // the op is coming from the translog (and is hence persisted already) or it does not have a sequence number assert index.origin().isFromTranslog() || indexResult.getSeqNo() == SequenceNumbers.UNASSIGNED_SEQ_NO; localCheckpointTracker.markSeqNoAsPersisted(indexResult.getSeqNo()); } indexResult.setTook(relativeTimeInNanosSupplier.getAsLong() - index.startTime()); indexResult.freeze(); return indexResult; } finally { releaseInFlightDocs(reservedDocs); } } catch (RuntimeException | IOException e) { try { if (e instanceof AlreadyClosedException == false && treatDocumentFailureAsTragicError(index)) { failEngine("index id[" + index.id() + "] origin[" + index.origin() + "] seq#[" + index.seqNo() + "]", e); } else { maybeFailEngine("index id[" + index.id() + "] origin[" + index.origin() + "] seq#[" + index.seqNo() + "]", e); } } catch (Exception inner) { e.addSuppressed(inner); } throw e; } } protected final IndexingStrategy planIndexingAsNonPrimary(Index index) throws IOException { assert assertNonPrimaryOrigin(index); // needs to maintain the auto_id timestamp in case this replica becomes primary if (canOptimizeAddDocument(index)) { mayHaveBeenIndexedBefore(index); } final IndexingStrategy plan; // unlike the primary, replicas don't really care to about creation status of documents // this allows to ignore the case where a document was found in the live version maps in // a delete state and return false for the created flag in favor of code simplicity final long maxSeqNoOfUpdatesOrDeletes = getMaxSeqNoOfUpdatesOrDeletes(); if (hasBeenProcessedBefore(index)) { // the operation seq# was processed and thus the same operation was already put into lucene // this can happen during recovery where older operations are sent from the translog that are already // part of the lucene commit (either from a peer recovery or a local translog) // or due to concurrent indexing & recovery. For the former it is important to skip lucene as the operation in // question may have been deleted in an out of order op that is not replayed. // See testRecoverFromStoreWithOutOfOrderDelete for an example of local recovery // See testRecoveryWithOutOfOrderDelete for an example of peer recovery plan = IndexingStrategy.processButSkipLucene(false, index.version()); } else if (maxSeqNoOfUpdatesOrDeletes <= localCheckpointTracker.getProcessedCheckpoint()) { // see Engine#getMaxSeqNoOfUpdatesOrDeletes for the explanation of the optimization using sequence numbers assert maxSeqNoOfUpdatesOrDeletes < index.seqNo() : index.seqNo() + ">=" + maxSeqNoOfUpdatesOrDeletes; plan = IndexingStrategy.optimizedAppendOnly(index.version(), 0); } else { versionMap.enforceSafeAccess(); final OpVsLuceneDocStatus opVsLucene = compareOpToLuceneDocBasedOnSeqNo(index); if (opVsLucene == OpVsLuceneDocStatus.OP_STALE_OR_EQUAL) { plan = IndexingStrategy.processAsStaleOp(index.version(), 0); } else { plan = IndexingStrategy.processNormally(opVsLucene == OpVsLuceneDocStatus.LUCENE_DOC_NOT_FOUND, index.version(), 0); } } return plan; } protected IndexingStrategy indexingStrategyForOperation(final Index index) throws IOException { if (index.origin() == Operation.Origin.PRIMARY) { return planIndexingAsPrimary(index); } else { // non-primary mode (i.e., replica or recovery) return planIndexingAsNonPrimary(index); } } private IndexingStrategy planIndexingAsPrimary(Index index) throws IOException { assert index.origin() == Operation.Origin.PRIMARY : "planing as primary but origin isn't. got " + index.origin(); final int reservingDocs = index.parsedDoc().docs().size(); final IndexingStrategy plan; // resolve an external operation into an internal one which is safe to replay final boolean canOptimizeAddDocument = canOptimizeAddDocument(index); if (canOptimizeAddDocument && mayHaveBeenIndexedBefore(index) == false) { final Exception reserveError = tryAcquireInFlightDocs(index, reservingDocs); if (reserveError != null) { plan = IndexingStrategy.failAsTooManyDocs(reserveError, index.id()); } else { plan = IndexingStrategy.optimizedAppendOnly(1L, reservingDocs); } } else { versionMap.enforceSafeAccess(); // resolves incoming version final VersionValue versionValue = resolveDocVersion(index, index.getIfSeqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO); final long currentVersion; final boolean currentNotFoundOrDeleted; if (versionValue == null) { currentVersion = Versions.NOT_FOUND; currentNotFoundOrDeleted = true; } else { currentVersion = versionValue.version; currentNotFoundOrDeleted = versionValue.isDelete(); } if (index.getIfSeqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO && currentNotFoundOrDeleted) { final VersionConflictEngineException e = new VersionConflictEngineException( shardId, index.id(), index.getIfSeqNo(), index.getIfPrimaryTerm(), SequenceNumbers.UNASSIGNED_SEQ_NO, SequenceNumbers.UNASSIGNED_PRIMARY_TERM ); plan = IndexingStrategy.skipDueToVersionConflict(e, true, currentVersion, index.id()); } else if (index.getIfSeqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO && (versionValue.seqNo != index.getIfSeqNo() || versionValue.term != index.getIfPrimaryTerm())) { final VersionConflictEngineException e = new VersionConflictEngineException( shardId, index.id(), index.getIfSeqNo(), index.getIfPrimaryTerm(), versionValue.seqNo, versionValue.term ); plan = IndexingStrategy.skipDueToVersionConflict(e, currentNotFoundOrDeleted, currentVersion, index.id()); } else if (index.versionType().isVersionConflictForWrites(currentVersion, index.version(), currentNotFoundOrDeleted)) { final VersionConflictEngineException e = new VersionConflictEngineException( shardId, index.parsedDoc().documentDescription(), index.versionType().explainConflictForWrites(currentVersion, index.version(), true) ); plan = IndexingStrategy.skipDueToVersionConflict(e, currentNotFoundOrDeleted, currentVersion, index.id()); } else { final Exception reserveError = tryAcquireInFlightDocs(index, reservingDocs); if (reserveError != null) { plan = IndexingStrategy.failAsTooManyDocs(reserveError, index.id()); } else { plan = IndexingStrategy.processNormally( currentNotFoundOrDeleted, canOptimizeAddDocument ? 1L : index.versionType().updateVersion(currentVersion, index.version()), reservingDocs ); } } } return plan; } private IndexResult indexIntoLucene(Index index, IndexingStrategy plan) throws IOException { assert index.seqNo() >= 0 : "ops should have an assigned seq no.; origin: " + index.origin(); assert plan.versionForIndexing >= 0 : "version must be set. got " + plan.versionForIndexing; assert plan.indexIntoLucene || plan.addStaleOpToLucene; /* Update the document's sequence number and primary term; the sequence number here is derived here from either the sequence * number service if this is on the primary, or the existing document's sequence number if this is on the replica. The * primary term here has already been set, see IndexShard#prepareIndex where the Engine$Index operation is created. */ index.parsedDoc().updateSeqID(index.seqNo(), index.primaryTerm()); index.parsedDoc().version().setLongValue(plan.versionForIndexing); try { if (plan.addStaleOpToLucene) { addStaleDocs(index.docs(), indexWriter); } else if (plan.useLuceneUpdateDocument) { assert assertMaxSeqNoOfUpdatesIsAdvanced(index.uid(), index.seqNo(), true, true); updateDocs(index.uid(), index.docs(), indexWriter); } else { // document does not exists, we can optimize for create, but double check if assertions are running assert assertDocDoesNotExist(index, canOptimizeAddDocument(index) == false); addDocs(index.docs(), indexWriter); } return new IndexResult(plan.versionForIndexing, index.primaryTerm(), index.seqNo(), plan.currentNotFoundOrDeleted, index.id()); } catch (Exception ex) { if (ex instanceof AlreadyClosedException == false && indexWriter.getTragicException() == null && treatDocumentFailureAsTragicError(index) == false) { /* There is no tragic event recorded so this must be a document failure. * * The handling inside IW doesn't guarantee that an tragic / aborting exception * will be used as THE tragicEventException since if there are multiple exceptions causing an abort in IW * only one wins. Yet, only the one that wins will also close the IW and in turn fail the engine such that * we can potentially handle the exception before the engine is failed. * Bottom line is that we can only rely on the fact that if it's a document failure then * `indexWriter.getTragicException()` will be null otherwise we have to rethrow and treat it as fatal or rather * non-document failure * * we return a `MATCH_ANY` version to indicate no document was index. The value is * not used anyway */ return new IndexResult(ex, Versions.MATCH_ANY, index.primaryTerm(), index.seqNo(), index.id()); } else { throw ex; } } } /** * Whether we should treat any document failure as tragic error. * If we hit any failure while processing an indexing on a replica, we should treat that error as tragic and fail the engine. * However, we prefer to fail a request individually (instead of a shard) if we hit a document failure on the primary. */ private static boolean treatDocumentFailureAsTragicError(Index index) { // TODO: can we enable this check for all origins except primary on the leader? return index.origin() == Operation.Origin.REPLICA || index.origin() == Operation.Origin.PEER_RECOVERY || index.origin() == Operation.Origin.LOCAL_RESET; } /** * returns true if the indexing operation may have already be processed by this engine. * Note that it is OK to rarely return true even if this is not the case. However a `false` * return value must always be correct. * */ private boolean mayHaveBeenIndexedBefore(Index index) { assert canOptimizeAddDocument(index); final boolean mayHaveBeenIndexBefore; if (index.isRetry()) { mayHaveBeenIndexBefore = true; updateAutoIdTimestamp(index.getAutoGeneratedIdTimestamp(), true); assert maxUnsafeAutoIdTimestamp.get() >= index.getAutoGeneratedIdTimestamp(); } else { // in this case we force mayHaveBeenIndexBefore = maxUnsafeAutoIdTimestamp.get() >= index.getAutoGeneratedIdTimestamp(); updateAutoIdTimestamp(index.getAutoGeneratedIdTimestamp(), false); } return mayHaveBeenIndexBefore; } private void addDocs(final List<LuceneDocument> docs, final IndexWriter indexWriter) throws IOException { if (docs.size() > 1) { indexWriter.addDocuments(docs); } else { indexWriter.addDocument(docs.get(0)); } numDocAppends.inc(docs.size()); } private void addStaleDocs(final List<LuceneDocument> docs, final IndexWriter indexWriter) throws IOException { for (LuceneDocument doc : docs) { doc.add(softDeletesField); // soft-deleted every document before adding to Lucene } if (docs.size() > 1) { indexWriter.addDocuments(docs); } else { indexWriter.addDocument(docs.get(0)); } } protected static final class IndexingStrategy { final boolean currentNotFoundOrDeleted; final boolean useLuceneUpdateDocument; final long versionForIndexing; final boolean indexIntoLucene; final boolean addStaleOpToLucene; final int reservedDocs; final Optional<IndexResult> earlyResultOnPreFlightError; private IndexingStrategy( boolean currentNotFoundOrDeleted, boolean useLuceneUpdateDocument, boolean indexIntoLucene, boolean addStaleOpToLucene, long versionForIndexing, int reservedDocs, IndexResult earlyResultOnPreFlightError ) { assert useLuceneUpdateDocument == false || indexIntoLucene : "use lucene update is set to true, but we're not indexing into lucene"; assert (indexIntoLucene && earlyResultOnPreFlightError != null) == false : "can only index into lucene or have a preflight result but not both." + "indexIntoLucene: " + indexIntoLucene + " earlyResultOnPreFlightError:" + earlyResultOnPreFlightError; assert reservedDocs == 0 || indexIntoLucene || addStaleOpToLucene : reservedDocs; this.currentNotFoundOrDeleted = currentNotFoundOrDeleted; this.useLuceneUpdateDocument = useLuceneUpdateDocument; this.versionForIndexing = versionForIndexing; this.indexIntoLucene = indexIntoLucene; this.addStaleOpToLucene = addStaleOpToLucene; this.reservedDocs = reservedDocs; this.earlyResultOnPreFlightError = earlyResultOnPreFlightError == null ? Optional.empty() : Optional.of(earlyResultOnPreFlightError); } static IndexingStrategy optimizedAppendOnly(long versionForIndexing, int reservedDocs) { return new IndexingStrategy(true, false, true, false, versionForIndexing, reservedDocs, null); } public static IndexingStrategy skipDueToVersionConflict( VersionConflictEngineException e, boolean currentNotFoundOrDeleted, long currentVersion, String id ) { final IndexResult result = new IndexResult(e, currentVersion, id); return new IndexingStrategy(currentNotFoundOrDeleted, false, false, false, Versions.NOT_FOUND, 0, result); } static IndexingStrategy processNormally(boolean currentNotFoundOrDeleted, long versionForIndexing, int reservedDocs) { return new IndexingStrategy( currentNotFoundOrDeleted, currentNotFoundOrDeleted == false, true, false, versionForIndexing, reservedDocs, null ); } public static IndexingStrategy processButSkipLucene(boolean currentNotFoundOrDeleted, long versionForIndexing) { return new IndexingStrategy(currentNotFoundOrDeleted, false, false, false, versionForIndexing, 0, null); } static IndexingStrategy processAsStaleOp(long versionForIndexing, int reservedDocs) { return new IndexingStrategy(false, false, false, true, versionForIndexing, reservedDocs, null); } static IndexingStrategy failAsTooManyDocs(Exception e, String id) { final IndexResult result = new IndexResult(e, Versions.NOT_FOUND, id); return new IndexingStrategy(false, false, false, false, Versions.NOT_FOUND, 0, result); } } /** * Asserts that the doc in the index operation really doesn't exist */ private boolean assertDocDoesNotExist(final Index index, final boolean allowDeleted) throws IOException { // NOTE this uses direct access to the version map since we are in the assertion code where we maintain a secondary // map in the version map such that we don't need to refresh if we are unsafe; final VersionValue versionValue = versionMap.getVersionForAssert(index.uid().bytes()); if (versionValue != null) { if (versionValue.isDelete() == false || allowDeleted == false) { throw new AssertionError("doc [" + index.id() + "] exists in version map (version " + versionValue + ")"); } } else { try (Searcher searcher = acquireSearcher("assert doc doesn't exist", SearcherScope.INTERNAL)) { searcher.setQueryCache(null); // so that it does not interfere with tests that check caching behavior final long docsWithId = searcher.count(new TermQuery(index.uid())); if (docsWithId > 0) { throw new AssertionError("doc [" + index.id() + "] exists [" + docsWithId + "] times in index"); } } } return true; } private void updateDocs(final Term uid, final List<LuceneDocument> docs, final IndexWriter indexWriter) throws IOException { if (docs.size() > 1) { indexWriter.softUpdateDocuments(uid, docs, softDeletesField); } else { indexWriter.softUpdateDocument(uid, docs.get(0), softDeletesField); } numDocUpdates.inc(docs.size()); } @Override public DeleteResult delete(Delete delete) throws IOException { versionMap.enforceSafeAccess(); assert Objects.equals(delete.uid().field(), IdFieldMapper.NAME) : delete.uid().field(); assert assertIncomingSequenceNumber(delete.origin(), delete.seqNo()); final DeleteResult deleteResult; int reservedDocs = 0; // NOTE: we don't throttle this when merges fall behind because delete-by-id does not create new segments: try (var ignored = acquireEnsureOpenRef(); Releasable ignored2 = versionMap.acquireLock(delete.uid().bytes())) { lastWriteNanos = delete.startTime(); final DeletionStrategy plan = deletionStrategyForOperation(delete); reservedDocs = plan.reservedDocs; if (plan.earlyResultOnPreflightError.isPresent()) { assert delete.origin() == Operation.Origin.PRIMARY : delete.origin(); deleteResult = plan.earlyResultOnPreflightError.get(); } else { // generate or register sequence number if (delete.origin() == Operation.Origin.PRIMARY) { delete = new Delete( delete.id(), delete.uid(), generateSeqNoForOperationOnPrimary(delete), delete.primaryTerm(), delete.version(), delete.versionType(), delete.origin(), delete.startTime(), delete.getIfSeqNo(), delete.getIfPrimaryTerm() ); advanceMaxSeqNoOfDeletesOnPrimary(delete.seqNo()); } else { markSeqNoAsSeen(delete.seqNo()); } assert delete.seqNo() >= 0 : "ops should have an assigned seq no.; origin: " + delete.origin(); if (plan.deleteFromLucene || plan.addStaleOpToLucene) { deleteResult = deleteInLucene(delete, plan); } else { deleteResult = new DeleteResult( plan.versionOfDeletion, delete.primaryTerm(), delete.seqNo(), plan.currentlyDeleted == false, delete.id() ); } if (plan.deleteFromLucene) { numDocDeletes.inc(); versionMap.putDeleteUnderLock( delete.uid().bytes(), new DeleteVersionValue( plan.versionOfDeletion, delete.seqNo(), delete.primaryTerm(), engineConfig.getThreadPool().relativeTimeInMillis() ) ); } } if (delete.origin().isFromTranslog() == false && deleteResult.getResultType() == Result.Type.SUCCESS) { final Translog.Location location = translog.add(new Translog.Delete(delete, deleteResult)); deleteResult.setTranslogLocation(location); } localCheckpointTracker.markSeqNoAsProcessed(deleteResult.getSeqNo()); if (deleteResult.getTranslogLocation() == null) { // the op is coming from the translog (and is hence persisted already) or does not have a sequence number (version conflict) assert delete.origin().isFromTranslog() || deleteResult.getSeqNo() == SequenceNumbers.UNASSIGNED_SEQ_NO; localCheckpointTracker.markSeqNoAsPersisted(deleteResult.getSeqNo()); } deleteResult.setTook(System.nanoTime() - delete.startTime()); deleteResult.freeze(); } catch (RuntimeException | IOException e) { try { maybeFailEngine("delete", e); } catch (Exception inner) { e.addSuppressed(inner); } throw e; } finally { releaseInFlightDocs(reservedDocs); } maybePruneDeletes(); return deleteResult; } private Exception tryAcquireInFlightDocs(Operation operation, int addingDocs) { assert operation.origin() == Operation.Origin.PRIMARY : operation; assert operation.seqNo() == SequenceNumbers.UNASSIGNED_SEQ_NO : operation; assert addingDocs > 0 : addingDocs; final long totalDocs = indexWriter.getPendingNumDocs() + inFlightDocCount.addAndGet(addingDocs); if (totalDocs > maxDocs) { releaseInFlightDocs(addingDocs); return new IllegalArgumentException("Number of documents in the index can't exceed [" + maxDocs + "]"); } else { return null; } } private void releaseInFlightDocs(int numDocs) { assert numDocs >= 0 : numDocs; final long newValue = inFlightDocCount.addAndGet(-numDocs); assert newValue >= 0 : "inFlightDocCount must not be negative [" + newValue + "]"; } long getInFlightDocCount() { return inFlightDocCount.get(); } protected DeletionStrategy deletionStrategyForOperation(final Delete delete) throws IOException { if (delete.origin() == Operation.Origin.PRIMARY) { return planDeletionAsPrimary(delete); } else { // non-primary mode (i.e., replica or recovery) return planDeletionAsNonPrimary(delete); } } protected final DeletionStrategy planDeletionAsNonPrimary(Delete delete) throws IOException { assert assertNonPrimaryOrigin(delete); final DeletionStrategy plan; if (hasBeenProcessedBefore(delete)) { // the operation seq# was processed thus this operation was already put into lucene // this can happen during recovery where older operations are sent from the translog that are already // part of the lucene commit (either from a peer recovery or a local translog) // or due to concurrent indexing & recovery. For the former it is important to skip lucene as the operation in // question may have been deleted in an out of order op that is not replayed. // See testRecoverFromStoreWithOutOfOrderDelete for an example of local recovery // See testRecoveryWithOutOfOrderDelete for an example of peer recovery plan = DeletionStrategy.processButSkipLucene(false, delete.version()); } else { final OpVsLuceneDocStatus opVsLucene = compareOpToLuceneDocBasedOnSeqNo(delete); if (opVsLucene == OpVsLuceneDocStatus.OP_STALE_OR_EQUAL) { plan = DeletionStrategy.processAsStaleOp(delete.version()); } else { plan = DeletionStrategy.processNormally(opVsLucene == OpVsLuceneDocStatus.LUCENE_DOC_NOT_FOUND, delete.version(), 0); } } return plan; } protected boolean assertNonPrimaryOrigin(final Operation operation) { assert operation.origin() != Operation.Origin.PRIMARY : "planing as primary but got " + operation.origin(); return true; } private DeletionStrategy planDeletionAsPrimary(Delete delete) throws IOException { assert delete.origin() == Operation.Origin.PRIMARY : "planing as primary but got " + delete.origin(); // resolve operation from external to internal final VersionValue versionValue = resolveDocVersion(delete, delete.getIfSeqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO); assert incrementVersionLookup(); final long currentVersion; final boolean currentlyDeleted; if (versionValue == null) { currentVersion = Versions.NOT_FOUND; currentlyDeleted = true; } else { currentVersion = versionValue.version; currentlyDeleted = versionValue.isDelete(); } final DeletionStrategy plan; if (delete.getIfSeqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO && currentlyDeleted) { final VersionConflictEngineException e = new VersionConflictEngineException( shardId, delete.id(), delete.getIfSeqNo(), delete.getIfPrimaryTerm(), SequenceNumbers.UNASSIGNED_SEQ_NO, SequenceNumbers.UNASSIGNED_PRIMARY_TERM ); plan = DeletionStrategy.skipDueToVersionConflict(e, currentVersion, true, delete.id()); } else if (delete.getIfSeqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO && (versionValue.seqNo != delete.getIfSeqNo() || versionValue.term != delete.getIfPrimaryTerm())) { final VersionConflictEngineException e = new VersionConflictEngineException( shardId, delete.id(), delete.getIfSeqNo(), delete.getIfPrimaryTerm(), versionValue.seqNo, versionValue.term ); plan = DeletionStrategy.skipDueToVersionConflict(e, currentVersion, currentlyDeleted, delete.id()); } else if (delete.versionType().isVersionConflictForWrites(currentVersion, delete.version(), currentlyDeleted)) { final VersionConflictEngineException e = new VersionConflictEngineException( shardId, "[" + delete.id() + "]", delete.versionType().explainConflictForWrites(currentVersion, delete.version(), true) ); plan = DeletionStrategy.skipDueToVersionConflict(e, currentVersion, currentlyDeleted, delete.id()); } else { final Exception reserveError = tryAcquireInFlightDocs(delete, 1); if (reserveError != null) { plan = DeletionStrategy.failAsTooManyDocs(reserveError, delete.id()); } else { final long versionOfDeletion = delete.versionType().updateVersion(currentVersion, delete.version()); plan = DeletionStrategy.processNormally(currentlyDeleted, versionOfDeletion, 1); } } return plan; } private DeleteResult deleteInLucene(Delete delete, DeletionStrategy plan) throws IOException { assert assertMaxSeqNoOfUpdatesIsAdvanced(delete.uid(), delete.seqNo(), false, false); try { final ParsedDocument tombstone = ParsedDocument.deleteTombstone(delete.id()); assert tombstone.docs().size() == 1 : "Tombstone doc should have single doc [" + tombstone + "]"; tombstone.updateSeqID(delete.seqNo(), delete.primaryTerm()); tombstone.version().setLongValue(plan.versionOfDeletion); final LuceneDocument doc = tombstone.docs().get(0); assert doc.getField(SeqNoFieldMapper.TOMBSTONE_NAME) != null : "Delete tombstone document but _tombstone field is not set [" + doc + " ]"; doc.add(softDeletesField); if (plan.addStaleOpToLucene || plan.currentlyDeleted) { indexWriter.addDocument(doc); } else { indexWriter.softUpdateDocument(delete.uid(), doc, softDeletesField); } return new DeleteResult( plan.versionOfDeletion, delete.primaryTerm(), delete.seqNo(), plan.currentlyDeleted == false, delete.id() ); } catch (final Exception ex) { /* * Document level failures when deleting are unexpected, we likely hit something fatal such as the Lucene index being corrupt, * or the Lucene document limit. We have already issued a sequence number here so this is fatal, fail the engine. */ if (ex instanceof AlreadyClosedException == false && indexWriter.getTragicException() == null) { final String reason = String.format( Locale.ROOT, "delete id[%s] origin [%s] seq#[%d] failed at the document level", delete.id(), delete.origin(), delete.seqNo() ); failEngine(reason, ex); } throw ex; } } protected static final class DeletionStrategy { // of a rare double delete final boolean deleteFromLucene; final boolean addStaleOpToLucene; final boolean currentlyDeleted; final long versionOfDeletion; final Optional<DeleteResult> earlyResultOnPreflightError; final int reservedDocs; private DeletionStrategy( boolean deleteFromLucene, boolean addStaleOpToLucene, boolean currentlyDeleted, long versionOfDeletion, int reservedDocs, DeleteResult earlyResultOnPreflightError ) { assert (deleteFromLucene && earlyResultOnPreflightError != null) == false : "can only delete from lucene or have a preflight result but not both." + "deleteFromLucene: " + deleteFromLucene + " earlyResultOnPreFlightError:" + earlyResultOnPreflightError; this.deleteFromLucene = deleteFromLucene; this.addStaleOpToLucene = addStaleOpToLucene; this.currentlyDeleted = currentlyDeleted; this.versionOfDeletion = versionOfDeletion; this.reservedDocs = reservedDocs; assert reservedDocs == 0 || deleteFromLucene || addStaleOpToLucene : reservedDocs; this.earlyResultOnPreflightError = earlyResultOnPreflightError == null ? Optional.empty() : Optional.of(earlyResultOnPreflightError); } public static DeletionStrategy skipDueToVersionConflict( VersionConflictEngineException e, long currentVersion, boolean currentlyDeleted, String id ) { final DeleteResult deleteResult = new DeleteResult( e, currentVersion, SequenceNumbers.UNASSIGNED_PRIMARY_TERM, SequenceNumbers.UNASSIGNED_SEQ_NO, currentlyDeleted == false, id ); return new DeletionStrategy(false, false, currentlyDeleted, Versions.NOT_FOUND, 0, deleteResult); } static DeletionStrategy processNormally(boolean currentlyDeleted, long versionOfDeletion, int reservedDocs) { return new DeletionStrategy(true, false, currentlyDeleted, versionOfDeletion, reservedDocs, null); } public static DeletionStrategy processButSkipLucene(boolean currentlyDeleted, long versionOfDeletion) { return new DeletionStrategy(false, false, currentlyDeleted, versionOfDeletion, 0, null); } static DeletionStrategy processAsStaleOp(long versionOfDeletion) { return new DeletionStrategy(false, true, false, versionOfDeletion, 0, null); } static DeletionStrategy failAsTooManyDocs(Exception e, String id) { final DeleteResult deleteResult = new DeleteResult( e, Versions.NOT_FOUND, SequenceNumbers.UNASSIGNED_PRIMARY_TERM, SequenceNumbers.UNASSIGNED_SEQ_NO, false, id ); return new DeletionStrategy(false, false, false, Versions.NOT_FOUND, 0, deleteResult); } } @Override public void maybePruneDeletes() { // It's expensive to prune because we walk the deletes map acquiring dirtyLock for each uid so we only do it // every 1/4 of gcDeletesInMillis: if (engineConfig.isEnableGcDeletes() && engineConfig.getThreadPool().relativeTimeInMillis() - lastDeleteVersionPruneTimeMSec > getGcDeletesInMillis() * 0.25) { pruneDeletedTombstones(); } } @Override public NoOpResult noOp(final NoOp noOp) throws IOException { final NoOpResult noOpResult; try (var ignored = acquireEnsureOpenRef()) { noOpResult = innerNoOp(noOp); } catch (final Exception e) { try { maybeFailEngine("noop", e); } catch (Exception inner) { e.addSuppressed(inner); } throw e; } return noOpResult; } private NoOpResult innerNoOp(final NoOp noOp) throws IOException { assert isDrainedForClose() == false; assert noOp.seqNo() > SequenceNumbers.NO_OPS_PERFORMED; final long seqNo = noOp.seqNo(); try (Releasable ignored = noOpKeyedLock.acquire(seqNo)) { final NoOpResult noOpResult; final Optional<Exception> preFlightError = preFlightCheckForNoOp(noOp); if (preFlightError.isPresent()) { noOpResult = new NoOpResult( SequenceNumbers.UNASSIGNED_PRIMARY_TERM, SequenceNumbers.UNASSIGNED_SEQ_NO, preFlightError.get() ); } else { markSeqNoAsSeen(noOp.seqNo()); if (hasBeenProcessedBefore(noOp) == false) { try { final ParsedDocument tombstone = ParsedDocument.noopTombstone(noOp.reason()); tombstone.updateSeqID(noOp.seqNo(), noOp.primaryTerm()); // A noop tombstone does not require a _version but it's added to have a fully dense docvalues for the version // field. 1L is selected to optimize the compression because it might probably be the most common value in // version field. tombstone.version().setLongValue(1L); assert tombstone.docs().size() == 1 : "Tombstone should have a single doc [" + tombstone + "]"; final LuceneDocument doc = tombstone.docs().get(0); assert doc.getField(SeqNoFieldMapper.TOMBSTONE_NAME) != null : "Noop tombstone document but _tombstone field is not set [" + doc + " ]"; doc.add(softDeletesField); indexWriter.addDocument(doc); } catch (final Exception ex) { /* * Document level failures when adding a no-op are unexpected, we likely hit something fatal such as the Lucene * index being corrupt, or the Lucene document limit. We have already issued a sequence number here so this is * fatal, fail the engine. */ if (ex instanceof AlreadyClosedException == false && indexWriter.getTragicException() == null) { failEngine("no-op origin[" + noOp.origin() + "] seq#[" + noOp.seqNo() + "] failed at document level", ex); } throw ex; } } noOpResult = new NoOpResult(noOp.primaryTerm(), noOp.seqNo()); if (noOp.origin().isFromTranslog() == false && noOpResult.getResultType() == Result.Type.SUCCESS) { final Translog.Location location = translog.add(new Translog.NoOp(noOp.seqNo(), noOp.primaryTerm(), noOp.reason())); noOpResult.setTranslogLocation(location); } } localCheckpointTracker.markSeqNoAsProcessed(noOpResult.getSeqNo()); if (noOpResult.getTranslogLocation() == null) { // the op is coming from the translog (and is hence persisted already) or it does not have a sequence number assert noOp.origin().isFromTranslog() || noOpResult.getSeqNo() == SequenceNumbers.UNASSIGNED_SEQ_NO; localCheckpointTracker.markSeqNoAsPersisted(noOpResult.getSeqNo()); } noOpResult.setTook(System.nanoTime() - noOp.startTime()); noOpResult.freeze(); return noOpResult; } finally { assert isDrainedForClose() == false; } } /** * Executes a pre-flight check for a given NoOp. * If this method returns a non-empty result, the engine won't process this NoOp and returns a failure. */ protected Optional<Exception> preFlightCheckForNoOp(final NoOp noOp) throws IOException { return Optional.empty(); } @Override public RefreshResult refresh(String source) throws EngineException { return refresh(source, SearcherScope.EXTERNAL, true); } @Override public void maybeRefresh(String source, ActionListener<RefreshResult> listener) throws EngineException { ActionListener.completeWith(listener, () -> refresh(source, SearcherScope.EXTERNAL, false)); } protected RefreshResult refreshInternalSearcher(String source, boolean block) throws EngineException { return refresh(source, SearcherScope.INTERNAL, block); } protected final RefreshResult refresh(String source, SearcherScope scope, boolean block) throws EngineException { // both refresh types will result in an internal refresh but only the external will also // pass the new reader reference to the external reader manager. final long localCheckpointBeforeRefresh = localCheckpointTracker.getProcessedCheckpoint(); boolean refreshed; long segmentGeneration = RefreshResult.UNKNOWN_GENERATION; try { // refresh does not need to hold readLock as ReferenceManager can handle correctly if the engine is closed in mid-way. if (store.tryIncRef()) { // increment the ref just to ensure nobody closes the store during a refresh try { // even though we maintain 2 managers we really do the heavy-lifting only once. // the second refresh will only do the extra work we have to do for warming caches etc. ReferenceManager<ElasticsearchDirectoryReader> referenceManager = getReferenceManager(scope); long generationBeforeRefresh = lastCommittedSegmentInfos.getGeneration(); // it is intentional that we never refresh both internal / external together if (block) { referenceManager.maybeRefreshBlocking(); refreshed = true; } else { refreshed = referenceManager.maybeRefresh(); } if (refreshed) { final ElasticsearchDirectoryReader current = referenceManager.acquire(); try { // Just use the generation from the reader when https://github.com/apache/lucene/pull/12177 is included. segmentGeneration = Math.max(current.getIndexCommit().getGeneration(), generationBeforeRefresh); } finally { referenceManager.release(current); } } } finally { store.decRef(); } if (refreshed) { lastRefreshedCheckpointListener.updateRefreshedCheckpoint(localCheckpointBeforeRefresh); } } else { refreshed = false; } } catch (AlreadyClosedException e) { failOnTragicEvent(e); throw e; } catch (Exception e) { try { failEngine("refresh failed source[" + source + "]", e); } catch (Exception inner) { e.addSuppressed(inner); } throw new RefreshFailedEngineException(shardId, e); } assert refreshed == false || lastRefreshedCheckpoint() >= localCheckpointBeforeRefresh : "refresh checkpoint was not advanced; " + "local_checkpoint=" + localCheckpointBeforeRefresh + " refresh_checkpoint=" + lastRefreshedCheckpoint(); // TODO: maybe we should just put a scheduled job in threadPool? // We check for pruning in each delete request, but we also prune here e.g. in case a delete burst comes in and then no more deletes // for a long time: maybePruneDeletes(); mergeScheduler.refreshConfig(); long primaryTerm = config().getPrimaryTermSupplier().getAsLong(); return new RefreshResult(refreshed, primaryTerm, segmentGeneration); } @Override public void writeIndexingBuffer() throws IOException { final long reclaimableVersionMapBytes = versionMap.reclaimableRefreshRamBytes(); // Only count bytes that are not already being written to disk. Note: this number may be negative at times if these two metrics get // updated concurrently. It's fine as it's only being used as a heuristic to decide on a full refresh vs. writing a single segment. // TODO: it might be more relevant to use the RAM usage of the largest DWPT as opposed to the overall RAM usage? Can we get this // exposed in Lucene? final long indexWriterBytesUsed = indexWriter.ramBytesUsed() - indexWriter.getFlushingBytes(); if (reclaimableVersionMapBytes >= indexWriterBytesUsed) { // This method expects to reclaim memory quickly, so if the version map is using more memory than the IndexWriter buffer then we // do a refresh, which is the only way to reclaim memory from the version map. IndexWriter#flushNextBuffer has similar logic: if // pending deletes occupy more than half of RAMBufferSizeMB then deletes are applied too. reclaimVersionMapMemory(); } else { // Write the largest pending segment. indexWriter.flushNextBuffer(); } } protected void reclaimVersionMapMemory() { // If we're already halfway through the flush thresholds, then we do a flush. This will save us from writing segments twice // independently in a short period of time, once to reclaim version map memory and then to reclaim the translog. For // memory-constrained deployments that need to refresh often to reclaim memory, this may require flushing 2x more often than // expected, but the general assumption is that this downside is an ok trade-off given the benefit of flushing the whole content of // the indexing buffer less often. final long flushThresholdSizeInBytes = Math.max( Translog.DEFAULT_HEADER_SIZE_IN_BYTES + 1, config().getIndexSettings().getFlushThresholdSize(totalDiskSpace).getBytes() / 2 ); final long flushThresholdAgeInNanos = config().getIndexSettings().getFlushThresholdAge().getNanos() / 2; if (shouldPeriodicallyFlush(flushThresholdSizeInBytes, flushThresholdAgeInNanos)) { flush(false, false, ActionListener.noop()); } else { refresh("write indexing buffer", SearcherScope.INTERNAL, false); } } @Override public boolean shouldPeriodicallyFlush() { final long flushThresholdSizeInBytes = config().getIndexSettings().getFlushThresholdSize(totalDiskSpace).getBytes(); final long flushThresholdAgeInNanos = config().getIndexSettings().getFlushThresholdAge().getNanos(); return shouldPeriodicallyFlush(flushThresholdSizeInBytes, flushThresholdAgeInNanos); } private boolean shouldPeriodicallyFlush(long flushThresholdSizeInBytes, long flushThresholdAgeInNanos) { ensureOpen(); if (shouldPeriodicallyFlushAfterBigMerge.get()) { return true; } final long localCheckpointOfLastCommit = Long.parseLong( lastCommittedSegmentInfos.userData.get(SequenceNumbers.LOCAL_CHECKPOINT_KEY) ); final long translogGenerationOfLastCommit = translog.getMinGenerationForSeqNo( localCheckpointOfLastCommit + 1 ).translogFileGeneration; if (translog.sizeInBytesByMinGen(translogGenerationOfLastCommit) < flushThresholdSizeInBytes && relativeTimeInNanosSupplier.getAsLong() - lastFlushTimestamp < flushThresholdAgeInNanos) { return false; } /* * We flush to reduce the size of uncommitted translog but strictly speaking the uncommitted size won't always be * below the flush-threshold after a flush. To avoid getting into an endless loop of flushing, we only enable the * periodically flush condition if this condition is disabled after a flush. The condition will change if the new * commit points to the later generation the last commit's(eg. gen-of-last-commit < gen-of-new-commit)[1]. * * When the local checkpoint equals to max_seqno, and translog-gen of the last commit equals to translog-gen of * the new commit, we know that the last generation must contain operations because its size is above the flush * threshold and the flush-threshold is guaranteed to be higher than an empty translog by the setting validation. * This guarantees that the new commit will point to the newly rolled generation. In fact, this scenario only * happens when the generation-threshold is close to or above the flush-threshold; otherwise we have rolled * generations as the generation-threshold was reached, then the first condition (eg. [1]) is already satisfied. * * This method is to maintain translog only, thus IndexWriter#hasUncommittedChanges condition is not considered. */ final long translogGenerationOfNewCommit = translog.getMinGenerationForSeqNo( localCheckpointTracker.getProcessedCheckpoint() + 1 ).translogFileGeneration; return translogGenerationOfLastCommit < translogGenerationOfNewCommit || localCheckpointTracker.getProcessedCheckpoint() == localCheckpointTracker.getMaxSeqNo(); } @Override protected void flushHoldingLock(boolean force, boolean waitIfOngoing, ActionListener<FlushResult> listener) throws EngineException { ensureOpen(); // best-effort, a concurrent failEngine() can still happen but that's ok if (force && waitIfOngoing == false) { final String message = "wait_if_ongoing must be true for a force flush: force=" + force + " wait_if_ongoing=" + waitIfOngoing; assert false : message; throw new IllegalArgumentException(message); } final long generation; if (flushLock.tryLock() == false) { // if we can't get the lock right away we block if needed otherwise barf if (waitIfOngoing == false) { logger.trace("detected an in-flight flush, not blocking to wait for it's completion"); listener.onResponse(FlushResult.NO_FLUSH); return; } logger.trace("waiting for in-flight flush to finish"); flushLock.lock(); logger.trace("acquired flush lock after blocking"); } else { logger.trace("acquired flush lock immediately"); } final long startTime = System.nanoTime(); try { // Only flush if (1) Lucene has uncommitted docs, or (2) forced by caller, or (3) the // newly created commit points to a different translog generation (can free translog), // or (4) the local checkpoint information in the last commit is stale, which slows down future recoveries. boolean hasUncommittedChanges = hasUncommittedChanges(); if (hasUncommittedChanges || force || shouldPeriodicallyFlush() || getProcessedLocalCheckpoint() > Long.parseLong( lastCommittedSegmentInfos.userData.get(SequenceNumbers.LOCAL_CHECKPOINT_KEY) )) { ensureCanFlush(); Translog.Location commitLocation = getTranslogLastWriteLocation(); try { translog.rollGeneration(); logger.trace("starting commit for flush; commitTranslog=true"); long lastFlushTimestamp = relativeTimeInNanosSupplier.getAsLong(); // Pre-emptively recording the upcoming segment generation so that the live version map archive records // the correct segment generation for doc IDs that go to the archive while a flush is happening. Otherwise, // if right after committing the IndexWriter new docs get indexed/updated and a refresh moves them to the archive, // we clear them from the archive once we see that segment generation on the search shards, but those changes // were not included in the commit since they happened right after it. preCommitSegmentGeneration.set(lastCommittedSegmentInfos.getGeneration() + 1); commitIndexWriter(indexWriter, translog); logger.trace("finished commit for flush"); // we need to refresh in order to clear older version values refresh("version_table_flush", SearcherScope.INTERNAL, true); translog.trimUnreferencedReaders(); // Use the timestamp from when the flush started, but only update it in case of success, so that any exception in // the above lines would not lead the engine to think that it recently flushed, when it did not. this.lastFlushTimestamp = lastFlushTimestamp; } catch (AlreadyClosedException e) { failOnTragicEvent(e); throw e; } catch (Exception e) { throw new FlushFailedEngineException(shardId, e); } refreshLastCommittedSegmentInfos(); generation = lastCommittedSegmentInfos.getGeneration(); flushListener.afterFlush(generation, commitLocation); } else { generation = lastCommittedSegmentInfos.getGeneration(); } } catch (FlushFailedEngineException ex) { maybeFailEngine("flush", ex); listener.onFailure(ex); return; } catch (Exception e) { listener.onFailure(e); return; } finally { totalFlushTimeExcludingWaitingOnLock.inc(System.nanoTime() - startTime); flushLock.unlock(); logger.trace("released flush lock"); } afterFlush(generation); // We don't have to do this here; we do it defensively to make sure that even if wall clock time is misbehaving // (e.g., moves backwards) we will at least still sometimes prune deleted tombstones: if (engineConfig.isEnableGcDeletes()) { pruneDeletedTombstones(); } waitForCommitDurability(generation, listener.map(v -> new FlushResult(true, generation))); } protected final boolean isFlushLockIsHeldByCurrentThread() { return flushLock.isHeldByCurrentThread(); } protected boolean hasUncommittedChanges() { return indexWriter.hasUncommittedChanges(); } private void refreshLastCommittedSegmentInfos() { /* * we have to inc-ref the store here since if the engine is closed by a tragic event * we don't acquire the write lock and wait until we have exclusive access. This might also * dec the store reference which can essentially close the store and unless we can inc the reference * we can't use it. */ store.incRef(); try { // reread the last committed segment infos lastCommittedSegmentInfos = store.readLastCommittedSegmentsInfo(); } catch (Exception e) { if (isClosed.get() == false) { logger.warn("failed to read latest segment infos on flush", e); if (Lucene.isCorruptionException(e)) { throw new FlushFailedEngineException(shardId, e); } } } finally { store.decRef(); } } protected void afterFlush(long generation) {} @Override public void rollTranslogGeneration() throws EngineException { try (var ignored = acquireEnsureOpenRef()) { translog.rollGeneration(); translog.trimUnreferencedReaders(); } catch (AlreadyClosedException e) { failOnTragicEvent(e); throw e; } catch (Exception e) { try { failEngine("translog trimming failed", e); } catch (Exception inner) { e.addSuppressed(inner); } throw new EngineException(shardId, "failed to roll translog", e); } } @Override public void trimUnreferencedTranslogFiles() throws EngineException { try (var ignored = acquireEnsureOpenRef()) { translog.trimUnreferencedReaders(); } catch (AlreadyClosedException e) { failOnTragicEvent(e); throw e; } catch (Exception e) { try { failEngine("translog trimming failed", e); } catch (Exception inner) { e.addSuppressed(inner); } throw new EngineException(shardId, "failed to trim translog", e); } } @Override public boolean shouldRollTranslogGeneration() { return getTranslog().shouldRollGeneration(); } @Override public void trimOperationsFromTranslog(long belowTerm, long aboveSeqNo) throws EngineException { try (var ignored = acquireEnsureOpenRef()) { translog.trimOperations(belowTerm, aboveSeqNo); } catch (AlreadyClosedException e) { failOnTragicEvent(e); throw e; } catch (Exception e) { try { failEngine("translog operations trimming failed", e); } catch (Exception inner) { e.addSuppressed(inner); } throw new EngineException(shardId, "failed to trim translog operations", e); } } private void pruneDeletedTombstones() { /* * We need to deploy two different trimming strategies for GC deletes on primary and replicas. Delete operations on primary * are remembered for at least one GC delete cycle and trimmed periodically. This is, at the moment, the best we can do on * primary for user facing APIs but this arbitrary time limit is problematic for replicas. On replicas however we should * trim only deletes whose seqno at most the local checkpoint. This requirement is explained as follows. * * Suppose o1 and o2 are two operations on the same document with seq#(o1) < seq#(o2), and o2 arrives before o1 on the replica. * o2 is processed normally since it arrives first; when o1 arrives it should be discarded: * - If seq#(o1) <= LCP, then it will be not be added to Lucene, as it was already previously added. * - If seq#(o1) > LCP, then it depends on the nature of o2: * *) If o2 is a delete then its seq# is recorded in the VersionMap, since seq#(o2) > seq#(o1) > LCP, * so a lookup can find it and determine that o1 is stale. * *) If o2 is an indexing then its seq# is either in Lucene (if refreshed) or the VersionMap (if not refreshed yet), * so a real-time lookup can find it and determine that o1 is stale. * * Here we prefer to deploy a single trimming strategy, which satisfies two constraints, on both primary and replicas because: * - It's simpler - no need to distinguish if an engine is running at primary mode or replica mode or being promoted. * - If a replica subsequently is promoted, user experience is maintained as that replica remembers deletes for the last GC cycle. * * However, the version map may consume less memory if we deploy two different trimming strategies for primary and replicas. */ final long timeMSec = engineConfig.getThreadPool().relativeTimeInMillis(); final long maxTimestampToPrune = timeMSec - engineConfig.getIndexSettings().getGcDeletesInMillis(); versionMap.pruneTombstones(maxTimestampToPrune, localCheckpointTracker.getProcessedCheckpoint()); lastDeleteVersionPruneTimeMSec = timeMSec; } // testing void clearDeletedTombstones() { versionMap.pruneTombstones(Long.MAX_VALUE, localCheckpointTracker.getMaxSeqNo()); } // for testing final Map<BytesRef, VersionValue> getVersionMap() { return Stream.concat(versionMap.getAllCurrent().entrySet().stream(), versionMap.getAllTombstones().entrySet().stream()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } @Override public void forceMerge(final boolean flush, int maxNumSegments, boolean onlyExpungeDeletes, final String forceMergeUUID) throws EngineException, IOException { if (onlyExpungeDeletes && maxNumSegments >= 0) { throw new IllegalArgumentException("only_expunge_deletes and max_num_segments are mutually exclusive"); } /* * We do NOT acquire the readlock here since we are waiting on the merges to finish * that's fine since the IW.rollback should stop all the threads and trigger an IOException * causing us to fail the forceMerge */ optimizeLock.lock(); try { ensureOpen(); store.incRef(); // increment the ref just to ensure nobody closes the store while we optimize try { if (onlyExpungeDeletes) { indexWriter.forceMergeDeletes(true /* blocks and waits for merges*/); } else if (maxNumSegments <= 0) { indexWriter.maybeMerge(); } else { indexWriter.forceMerge(maxNumSegments, true /* blocks and waits for merges*/); this.forceMergeUUID = forceMergeUUID; } if (flush) { // TODO: Migrate to using async apic flush(false, true); // If any merges happened then we need to release the unmerged input segments so they can be deleted. A periodic refresh // will do this eventually unless the user has disabled refreshes or isn't searching this shard frequently, in which // case we should do something here to ensure a timely refresh occurs. However there's no real need to defer it nor to // have any should-we-actually-refresh-here logic: we're already doing an expensive force-merge operation at the user's // request and therefore don't expect any further writes so we may as well do the final refresh immediately and get it // out of the way. refresh("force-merge"); } } finally { store.decRef(); } } catch (AlreadyClosedException ex) { /* in this case we first check if the engine is still open. If so this exception is just fine * and expected. We don't hold any locks while we block on forceMerge otherwise it would block * closing the engine as well. If we are not closed we pass it on to failOnTragicEvent which ensures * we are handling a tragic even exception here */ ensureOpen(ex); failOnTragicEvent(ex); throw ex; } catch (Exception e) { try { maybeFailEngine("force merge", e); } catch (Exception inner) { e.addSuppressed(inner); } throw e; } finally { optimizeLock.unlock(); } } private IndexCommitRef acquireIndexCommitRef(final Supplier<IndexCommit> indexCommitSupplier) { store.incRef(); boolean success = false; try { final IndexCommit indexCommit = indexCommitSupplier.get(); final IndexCommitRef commitRef = new IndexCommitRef( indexCommit, () -> IOUtils.close(() -> releaseIndexCommit(indexCommit), store::decRef) ); success = true; return commitRef; } finally { if (success == false) { store.decRef(); } } } @Override public IndexCommitRef acquireLastIndexCommit(final boolean flushFirst) throws EngineException { // we have to flush outside of the readlock otherwise we might have a problem upgrading // the to a write lock when we fail the engine in this operation if (flushFirst) { logger.trace("start flush for snapshot"); // TODO: Split acquireLastIndexCommit into two apis one with blocking flushes one without PlainActionFuture<FlushResult> future = new PlainActionFuture<>(); flush(false, true, future); future.actionGet(); logger.trace("finish flush for snapshot"); } return acquireIndexCommitRef(() -> combinedDeletionPolicy.acquireIndexCommit(false)); } @Override public IndexCommitRef acquireSafeIndexCommit() throws EngineException { return acquireIndexCommitRef(() -> combinedDeletionPolicy.acquireIndexCommit(true)); } private void releaseIndexCommit(IndexCommit snapshot) throws IOException { // Revisit the deletion policy if we can clean up the snapshotting commit. if (combinedDeletionPolicy.releaseCommit(snapshot)) { try { // Here we don't have to trim translog because snapshotting an index commit // does not lock translog or prevents unreferenced files from trimming. indexWriter.deleteUnusedFiles(); } catch (AlreadyClosedException ignored) { // That's ok, we'll clean up unused files the next time it's opened. } } } @Override public SafeCommitInfo getSafeCommitInfo() { return combinedDeletionPolicy.getSafeCommitInfo(); } private boolean failOnTragicEvent(AlreadyClosedException ex) { final boolean engineFailed; // if we are already closed due to some tragic exception // we need to fail the engine. it might have already been failed before // but we are double-checking it's failed and closed if (indexWriter.isOpen() == false && indexWriter.getTragicException() != null) { final Exception tragicException; if (indexWriter.getTragicException() instanceof Exception) { tragicException = (Exception) indexWriter.getTragicException(); } else { tragicException = new RuntimeException(indexWriter.getTragicException()); } failEngine("already closed by tragic event on the index writer", tragicException); engineFailed = true; } else if (translog.isOpen() == false && translog.getTragicException() != null) { failEngine("already closed by tragic event on the translog", translog.getTragicException()); engineFailed = true; } else if (failedEngine.get() == null && isClosing() == false && isClosed.get() == false) { // we are closed but the engine is not failed yet? // this smells like a bug - we only expect ACE if we are in a fatal case ie. either translog or IW is closed by // a tragic event or has closed itself. if that is not the case we are in a buggy state and raise an assertion error throw new AssertionError("Unexpected AlreadyClosedException", ex); } else { engineFailed = false; } return engineFailed; } @Override protected boolean maybeFailEngine(String source, Exception e) { boolean shouldFail = super.maybeFailEngine(source, e); if (shouldFail) { return true; } // Check for AlreadyClosedException -- ACE is a very special // exception that should only be thrown in a tragic event. we pass on the checks to failOnTragicEvent which will // throw and AssertionError if the tragic event condition is not met. if (e instanceof AlreadyClosedException) { return failOnTragicEvent((AlreadyClosedException) e); } else if (e != null && ((indexWriter.isOpen() == false && indexWriter.getTragicException() == e) || (translog.isOpen() == false && translog.getTragicException() == e))) { // this spot on - we are handling the tragic event exception here so we have to fail the engine // right away failEngine(source, e); return true; } return false; } @Override public SegmentInfos getLastCommittedSegmentInfos() { return lastCommittedSegmentInfos; } @Override protected final void writerSegmentStats(SegmentsStats stats) { stats.addVersionMapMemoryInBytes(versionMap.ramBytesUsed()); stats.addIndexWriterMemoryInBytes(indexWriter.ramBytesUsed()); stats.updateMaxUnsafeAutoIdTimestamp(maxUnsafeAutoIdTimestamp.get()); } @Override public long getIndexBufferRAMBytesUsed() { // We don't guard w/ readLock here, so we could throw AlreadyClosedException return indexWriter.ramBytesUsed() + versionMap.ramBytesUsedForRefresh(); } @Override public List<Segment> segments() { return segments(false); } @Override public List<Segment> segments(boolean includeVectorFormatsInfo) { try (var ignored = acquireEnsureOpenRef()) { Segment[] segmentsArr = getSegmentInfo(lastCommittedSegmentInfos, includeVectorFormatsInfo); // fill in the merges flag Set<OnGoingMerge> onGoingMerges = mergeScheduler.onGoingMerges(); for (OnGoingMerge onGoingMerge : onGoingMerges) { for (SegmentCommitInfo segmentInfoPerCommit : onGoingMerge.getMergedSegments()) { for (Segment segment : segmentsArr) { if (segment.getName().equals(segmentInfoPerCommit.info.name)) { segment.mergeId = onGoingMerge.getId(); break; } } } } return Arrays.asList(segmentsArr); } } @Override protected final void closeNoLock(String reason, CountDownLatch closedLatch) { if (isClosed.compareAndSet(false, true)) { assert isDrainedForClose() || failEngineLock.isHeldByCurrentThread() : "Either all operations must have been drained or the engine must be currently be failing itself"; try { this.versionMap.clear(); if (internalReaderManager != null) { internalReaderManager.removeListener(versionMap); } try { IOUtils.close(flushListener, externalReaderManager, internalReaderManager); } catch (Exception e) { logger.warn("Failed to close ReaderManager", e); } try { IOUtils.close(translog); } catch (Exception e) { logger.warn("Failed to close translog", e); } // no need to commit in this case!, we snapshot before we close the shard, so translog and all sync'ed logger.trace("rollback indexWriter"); try { assert ClusterApplierService.assertNotApplyingClusterState(); indexWriter.rollback(); } catch (AlreadyClosedException ex) { failOnTragicEvent(ex); throw ex; } logger.trace("rollback indexWriter done"); } catch (Exception e) { logger.warn("failed to rollback writer on close", e); } finally { try { store.decRef(); logger.debug("engine closed [{}]", reason); } finally { closedLatch.countDown(); } } } } @Override protected final ReferenceManager<ElasticsearchDirectoryReader> getReferenceManager(SearcherScope scope) { return switch (scope) { case INTERNAL -> internalReaderManager; case EXTERNAL -> externalReaderManager; }; } private IndexWriter createWriter() throws IOException { try { final IndexWriterConfig iwc = getIndexWriterConfig(); return createWriter(store.directory(), iwc); } catch (LockObtainFailedException ex) { logger.warn("could not lock IndexWriter", ex); throw ex; } } // pkg-private for testing IndexWriter createWriter(Directory directory, IndexWriterConfig iwc) throws IOException { if (Assertions.ENABLED) { return new AssertingIndexWriter(directory, iwc); } else { return new IndexWriter(directory, iwc); } } private IndexWriterConfig getIndexWriterConfig() { final IndexWriterConfig iwc = new IndexWriterConfig(engineConfig.getAnalyzer()); iwc.setCommitOnClose(false); // we by default don't commit on close iwc.setOpenMode(IndexWriterConfig.OpenMode.APPEND); iwc.setIndexDeletionPolicy(combinedDeletionPolicy); // with tests.verbose, lucene sets this up: plumb to align with filesystem stream boolean verbose = false; try { verbose = Boolean.parseBoolean(System.getProperty("tests.verbose")); } catch (Exception ignore) {} iwc.setInfoStream(verbose ? InfoStream.getDefault() : new LoggerInfoStream(logger)); iwc.setMergeScheduler(mergeScheduler); // Give us the opportunity to upgrade old segments while performing // background merges MergePolicy mergePolicy = config().getMergePolicy(); // always configure soft-deletes field so an engine with soft-deletes disabled can open a Lucene index with soft-deletes. iwc.setSoftDeletesField(Lucene.SOFT_DELETES_FIELD); mergePolicy = new RecoverySourcePruneMergePolicy( SourceFieldMapper.RECOVERY_SOURCE_NAME, engineConfig.getIndexSettings().getMode() == IndexMode.TIME_SERIES, softDeletesPolicy::getRetentionQuery, new SoftDeletesRetentionMergePolicy( Lucene.SOFT_DELETES_FIELD, softDeletesPolicy::getRetentionQuery, new PrunePostingsMergePolicy(mergePolicy, IdFieldMapper.NAME) ) ); boolean shuffleForcedMerge = Booleans.parseBoolean(System.getProperty("es.shuffle_forced_merge", Boolean.TRUE.toString())); if (shuffleForcedMerge) { // We wrap the merge policy for all indices even though it is mostly useful for time-based indices // but there should be no overhead for other type of indices so it's simpler than adding a setting // to enable it. mergePolicy = new ShuffleForcedMergePolicy(mergePolicy); } iwc.setMergePolicy(mergePolicy); // TODO: Introduce an index setting for setMaxFullFlushMergeWaitMillis iwc.setMaxFullFlushMergeWaitMillis(-1); iwc.setSimilarity(engineConfig.getSimilarity()); iwc.setRAMBufferSizeMB(engineConfig.getIndexingBufferSize().getMbFrac()); iwc.setCodec(engineConfig.getCodec()); boolean useCompoundFile = engineConfig.getUseCompoundFile(); iwc.setUseCompoundFile(useCompoundFile); if (useCompoundFile == false) { logger.warn( "[{}] is set to false, this should only be used in tests and can cause serious problems in production environments", EngineConfig.USE_COMPOUND_FILE ); } if (config().getIndexSort() != null) { iwc.setIndexSort(config().getIndexSort()); } // Provide a custom leaf sorter, so that index readers opened from this writer // will have its leaves sorted according the given leaf sorter. if (engineConfig.getLeafSorter() != null) { iwc.setLeafSorter(engineConfig.getLeafSorter()); } return iwc; } /** A listener that warms the segments if needed when acquiring a new reader */ static final class RefreshWarmerListener implements BiConsumer<ElasticsearchDirectoryReader, ElasticsearchDirectoryReader> { private final Engine.Warmer warmer; private final Logger logger; private final AtomicBoolean isEngineClosed; RefreshWarmerListener(Logger logger, AtomicBoolean isEngineClosed, EngineConfig engineConfig) { warmer = engineConfig.getWarmer(); this.logger = logger; this.isEngineClosed = isEngineClosed; } @Override public void accept(ElasticsearchDirectoryReader reader, ElasticsearchDirectoryReader previousReader) { if (warmer != null) { try { warmer.warm(reader); } catch (Exception e) { if (isEngineClosed.get() == false) { logger.warn("failed to prepare/warm", e); } } } } } @Override public void activateThrottling() { int count = throttleRequestCount.incrementAndGet(); assert count >= 1 : "invalid post-increment throttleRequestCount=" + count; if (count == 1) { throttle.activate(); } } @Override public void deactivateThrottling() { int count = throttleRequestCount.decrementAndGet(); assert count >= 0 : "invalid post-decrement throttleRequestCount=" + count; if (count == 0) { throttle.deactivate(); } } @Override public boolean isThrottled() { return throttle.isThrottled(); } boolean throttleLockIsHeldByCurrentThread() { // to be used in assertions and tests only return throttle.throttleLockIsHeldByCurrentThread(); } @Override public long getIndexThrottleTimeInMillis() { return throttle.getThrottleTimeInMillis(); } long getGcDeletesInMillis() { return engineConfig.getIndexSettings().getGcDeletesInMillis(); } LiveIndexWriterConfig getCurrentIndexWriterConfig() { return indexWriter.getConfig(); } private final class EngineMergeScheduler extends ElasticsearchConcurrentMergeScheduler { private final AtomicInteger numMergesInFlight = new AtomicInteger(0); private final AtomicBoolean isThrottling = new AtomicBoolean(); EngineMergeScheduler(ShardId shardId, IndexSettings indexSettings) { super(shardId, indexSettings); } @Override public synchronized void beforeMerge(OnGoingMerge merge) { int maxNumMerges = mergeScheduler.getMaxMergeCount(); if (numMergesInFlight.incrementAndGet() > maxNumMerges) { if (isThrottling.getAndSet(true) == false) { logger.info("now throttling indexing: numMergesInFlight={}, maxNumMerges={}", numMergesInFlight, maxNumMerges); activateThrottling(); } } } @Override public synchronized void afterMerge(OnGoingMerge merge) { int maxNumMerges = mergeScheduler.getMaxMergeCount(); if (numMergesInFlight.decrementAndGet() < maxNumMerges) { if (isThrottling.getAndSet(false)) { logger.info("stop throttling indexing: numMergesInFlight={}, maxNumMerges={}", numMergesInFlight, maxNumMerges); deactivateThrottling(); } } if (indexWriter.hasPendingMerges() == false && System.nanoTime() - lastWriteNanos >= engineConfig.getFlushMergesAfter().nanos()) { // NEVER do this on a merge thread since we acquire some locks blocking here and if we concurrently rollback the writer // we deadlock on engine#close for instance. engineConfig.getThreadPool().executor(ThreadPool.Names.FLUSH).execute(new AbstractRunnable() { @Override public void onFailure(Exception e) { if (isClosed.get() == false) { logger.warn("failed to flush after merge has finished"); } } @Override protected void doRun() { // if we have no pending merges and we are supposed to flush once merges have finished to // free up transient disk usage of the (presumably biggish) segments that were just merged flush(); } }); } else if (merge.getTotalBytesSize() >= engineConfig.getIndexSettings().getFlushAfterMergeThresholdSize().getBytes()) { // we hit a significant merge which would allow us to free up memory if we'd commit it hence on the next change // we should execute a flush on the next operation if that's a flush after inactive or indexing a document. // we could fork a thread and do it right away but we try to minimize forking and piggyback on outside events. shouldPeriodicallyFlushAfterBigMerge.set(true); } } @Override protected void handleMergeException(final Throwable exc) { engineConfig.getThreadPool().generic().execute(new AbstractRunnable() { @Override public void onFailure(Exception e) { logger.debug("merge failure action rejected", e); } @Override protected void doRun() throws Exception { /* * We do this on another thread rather than the merge thread that we are initially called on so that we have complete * confidence that the call stack does not contain catch statements that would cause the error that might be thrown * here from being caught and never reaching the uncaught exception handler. */ failEngine("merge failed", new MergePolicy.MergeException(exc)); } }); } } /** * Commits the specified index writer. * * @param writer the index writer to commit * @param translog the translog */ protected void commitIndexWriter(final IndexWriter writer, final Translog translog) throws IOException { assert isFlushLockIsHeldByCurrentThread(); ensureCanFlush(); try { final long localCheckpoint = localCheckpointTracker.getProcessedCheckpoint(); writer.setLiveCommitData(() -> { /* * The user data captured above (e.g. local checkpoint) contains data that must be evaluated *before* Lucene flushes * segments, including the local checkpoint amongst other values. The maximum sequence number is different, we never want * the maximum sequence number to be less than the last sequence number to go into a Lucene commit, otherwise we run the * risk of re-using a sequence number for two different documents when restoring from this commit point and subsequently * writing new documents to the index. Since we only know which Lucene documents made it into the final commit after the * {@link IndexWriter#commit()} call flushes all documents, we defer computation of the maximum sequence number to the time * of invocation of the commit data iterator (which occurs after all documents have been flushed to Lucene). */ final Map<String, String> extraCommitUserData = getCommitExtraUserData(); final Map<String, String> commitData = Maps.newMapWithExpectedSize(8 + extraCommitUserData.size()); commitData.putAll(extraCommitUserData); commitData.put(Translog.TRANSLOG_UUID_KEY, translog.getTranslogUUID()); commitData.put(SequenceNumbers.LOCAL_CHECKPOINT_KEY, Long.toString(localCheckpoint)); commitData.put(SequenceNumbers.MAX_SEQ_NO, Long.toString(localCheckpointTracker.getMaxSeqNo())); commitData.put(MAX_UNSAFE_AUTO_ID_TIMESTAMP_COMMIT_ID, Long.toString(maxUnsafeAutoIdTimestamp.get())); commitData.put(HISTORY_UUID_KEY, historyUUID); final String currentForceMergeUUID = forceMergeUUID; if (currentForceMergeUUID != null) { commitData.put(FORCE_MERGE_UUID_KEY, currentForceMergeUUID); } commitData.put(Engine.MIN_RETAINED_SEQNO, Long.toString(softDeletesPolicy.getMinRetainedSeqNo())); commitData.put(ES_VERSION, IndexVersion.current().toString()); logger.trace("committing writer with commit data [{}]", commitData); return commitData.entrySet().iterator(); }); shouldPeriodicallyFlushAfterBigMerge.set(false); writer.commit(); } catch (final Exception ex) { try { failEngine("lucene commit failed", ex); } catch (final Exception inner) { ex.addSuppressed(inner); } throw ex; } catch (final AssertionError e) { /* * If assertions are enabled, IndexWriter throws AssertionError on commit if any files don't exist, but tests that randomly * throw FileNotFoundException or NoSuchFileException can also hit this. */ if (ExceptionsHelper.stackTrace(e).contains("org.apache.lucene.index.IndexWriter.filesExist")) { final EngineException engineException = new EngineException(shardId, "failed to commit engine", e); try { failEngine("lucene commit failed", engineException); } catch (final Exception inner) { engineException.addSuppressed(inner); } throw engineException; } else { throw e; } } } /** * Allows InternalEngine extenders to return custom key-value pairs which will be included in the Lucene commit user-data. Custom user * data keys can be overwritten by if their keys conflict keys used by InternalEngine. */ protected Map<String, String> getCommitExtraUserData() { return Collections.emptyMap(); } final void ensureCanFlush() { // translog recovery happens after the engine is fully constructed. // If we are in this stage we have to prevent flushes from this // engine otherwise we might loose documents if the flush succeeds // and the translog recovery fails when we "commit" the translog on flush. if (pendingTranslogRecovery.get()) { throw new IllegalStateException(shardId.toString() + " flushes are disabled - pending translog recovery"); } } @Override public void onSettingsChanged() { mergeScheduler.refreshConfig(); // config().isEnableGcDeletes() or config.getGcDeletesInMillis() may have changed: maybePruneDeletes(); softDeletesPolicy.setRetentionOperations(config().getIndexSettings().getSoftDeleteRetentionOperations()); } public MergeStats getMergeStats() { return mergeScheduler.stats(); } protected LocalCheckpointTracker getLocalCheckpointTracker() { return localCheckpointTracker; } @Override public long getLastSyncedGlobalCheckpoint() { return getTranslog().getLastSyncedGlobalCheckpoint(); } @Override public long getMaxSeqNo() { return localCheckpointTracker.getMaxSeqNo(); } @Override public long getProcessedLocalCheckpoint() { return localCheckpointTracker.getProcessedCheckpoint(); } @Override public long getPersistedLocalCheckpoint() { return localCheckpointTracker.getPersistedCheckpoint(); } /** * Marks the given seq_no as seen and advances the max_seq_no of this engine to at least that value. */ protected final void markSeqNoAsSeen(long seqNo) { localCheckpointTracker.advanceMaxSeqNo(seqNo); } /** * Checks if the given operation has been processed in this engine or not. * @return true if the given operation was processed; otherwise false. */ protected final boolean hasBeenProcessedBefore(Operation op) { if (Assertions.ENABLED) { assert op.seqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO : "operation is not assigned seq_no"; if (op.operationType() == Operation.TYPE.NO_OP) { assert noOpKeyedLock.isHeldByCurrentThread(op.seqNo()); } else { assert versionMap.assertKeyedLockHeldByCurrentThread(op.uid().bytes()); } } return localCheckpointTracker.hasProcessed(op.seqNo()); } @Override public SeqNoStats getSeqNoStats(long globalCheckpoint) { return localCheckpointTracker.getStats(globalCheckpoint); } /** * Returns the number of times a version was looked up either from the index. * Note this is only available if assertions are enabled */ long getNumIndexVersionsLookups() { // for testing return numIndexVersionsLookups.count(); } /** * Returns the number of times a version was looked up either from memory or from the index. * Note this is only available if assertions are enabled */ long getNumVersionLookups() { // for testing return numVersionLookups.count(); } private boolean incrementVersionLookup() { // only used by asserts numVersionLookups.inc(); return true; } private boolean incrementIndexVersionLookup() { numIndexVersionsLookups.inc(); return true; } boolean isSafeAccessRequired() { return versionMap.isSafeAccessRequired(); } /** * Returns the number of documents have been deleted since this engine was opened. * This count does not include the deletions from the existing segments before opening engine. */ long getNumDocDeletes() { return numDocDeletes.count(); } /** * Returns the number of documents have been appended since this engine was opened. * This count does not include the appends from the existing segments before opening engine. */ long getNumDocAppends() { return numDocAppends.count(); } /** * Returns the number of documents have been updated since this engine was opened. * This count does not include the updates from the existing segments before opening engine. */ long getNumDocUpdates() { return numDocUpdates.count(); } @Override public long getTotalFlushTimeExcludingWaitingOnLockInMillis() { return TimeUnit.NANOSECONDS.toMillis(totalFlushTimeExcludingWaitingOnLock.sum()); } @Override public int countChanges(String source, long fromSeqNo, long toSeqNo) throws IOException { ensureOpen(); refreshIfNeeded(source, toSeqNo); try (Searcher searcher = acquireSearcher(source, SearcherScope.INTERNAL)) { return LuceneChangesSnapshot.countOperations( searcher, fromSeqNo, toSeqNo, config().getIndexSettings().getIndexVersionCreated() ); } catch (Exception e) { try { maybeFailEngine("count changes", e); } catch (Exception inner) { e.addSuppressed(inner); } throw e; } } @Override public Translog.Snapshot newChangesSnapshot( String source, long fromSeqNo, long toSeqNo, boolean requiredFullRange, boolean singleConsumer, boolean accessStats ) throws IOException { ensureOpen(); refreshIfNeeded(source, toSeqNo); Searcher searcher = acquireSearcher(source, SearcherScope.INTERNAL); try { LuceneChangesSnapshot snapshot = new LuceneChangesSnapshot( searcher, LuceneChangesSnapshot.DEFAULT_BATCH_SIZE, fromSeqNo, toSeqNo, requiredFullRange, singleConsumer, accessStats, config().getIndexSettings().getIndexVersionCreated() ); searcher = null; return snapshot; } catch (Exception e) { try { maybeFailEngine("acquire changes snapshot", e); } catch (Exception inner) { e.addSuppressed(inner); } throw e; } finally { IOUtils.close(searcher); } } @Override public boolean hasCompleteOperationHistory(String reason, long startingSeqNo) { return getMinRetainedSeqNo() <= startingSeqNo; } /** * Returns the minimum seqno that is retained in the Lucene index. * Operations whose seq# are at least this value should exist in the Lucene index. */ public final long getMinRetainedSeqNo() { return softDeletesPolicy.getMinRetainedSeqNo(); } @Override public Closeable acquireHistoryRetentionLock() { return softDeletesPolicy.acquireRetentionLock(); } /** * Gets the commit data from {@link IndexWriter} as a map. */ private static Map<String, String> commitDataAsMap(final IndexWriter indexWriter) { final Map<String, String> commitData = Maps.newMapWithExpectedSize(8); for (Map.Entry<String, String> entry : indexWriter.getLiveCommitData()) { commitData.put(entry.getKey(), entry.getValue()); } return commitData; } private static class AssertingIndexWriter extends IndexWriter { AssertingIndexWriter(Directory d, IndexWriterConfig conf) throws IOException { super(d, conf); } @Override public long deleteDocuments(Term... terms) { throw new AssertionError("must not hard delete documents"); } @Override public long tryDeleteDocument(IndexReader readerIn, int docID) { throw new AssertionError("tryDeleteDocument is not supported. See Lucene#DirectoryReaderWithAllLiveDocs"); } } /** * Returned the last local checkpoint value has been refreshed internally. */ final long lastRefreshedCheckpoint() { return lastRefreshedCheckpointListener.refreshedCheckpoint.get(); } private final Object refreshIfNeededMutex = new Object(); /** * Refresh this engine **internally** iff the requesting seq_no is greater than the last refreshed checkpoint. */ protected final void refreshIfNeeded(String source, long requestingSeqNo) { if (lastRefreshedCheckpoint() < requestingSeqNo) { synchronized (refreshIfNeededMutex) { if (lastRefreshedCheckpoint() < requestingSeqNo) { refreshInternalSearcher(source, true); } } } } private final class LastRefreshedCheckpointListener implements ReferenceManager.RefreshListener { final AtomicLong refreshedCheckpoint; private long pendingCheckpoint; LastRefreshedCheckpointListener(long initialLocalCheckpoint) { this.refreshedCheckpoint = new AtomicLong(initialLocalCheckpoint); } @Override public void beforeRefresh() { // all changes until this point should be visible after refresh pendingCheckpoint = localCheckpointTracker.getProcessedCheckpoint(); } @Override public void afterRefresh(boolean didRefresh) { if (didRefresh) { updateRefreshedCheckpoint(pendingCheckpoint); } } void updateRefreshedCheckpoint(long checkpoint) { refreshedCheckpoint.accumulateAndGet(checkpoint, Math::max); assert refreshedCheckpoint.get() >= checkpoint : refreshedCheckpoint.get() + " < " + checkpoint; } } @Override public final long getMaxSeenAutoIdTimestamp() { return maxSeenAutoIdTimestamp.get(); } @Override public final void updateMaxUnsafeAutoIdTimestamp(long newTimestamp) { updateAutoIdTimestamp(newTimestamp, true); } private void updateAutoIdTimestamp(long newTimestamp, boolean unsafe) { assert newTimestamp >= -1 : "invalid timestamp [" + newTimestamp + "]"; maxSeenAutoIdTimestamp.accumulateAndGet(newTimestamp, Math::max); if (unsafe) { maxUnsafeAutoIdTimestamp.accumulateAndGet(newTimestamp, Math::max); } assert maxUnsafeAutoIdTimestamp.get() <= maxSeenAutoIdTimestamp.get(); } @Override public long getMaxSeqNoOfUpdatesOrDeletes() { return maxSeqNoOfUpdatesOrDeletes.get(); } @Override public void advanceMaxSeqNoOfUpdatesOrDeletes(long maxSeqNoOfUpdatesOnPrimary) { if (maxSeqNoOfUpdatesOnPrimary == SequenceNumbers.UNASSIGNED_SEQ_NO) { assert false : "max_seq_no_of_updates on primary is unassigned"; throw new IllegalArgumentException("max_seq_no_of_updates on primary is unassigned"); } this.maxSeqNoOfUpdatesOrDeletes.accumulateAndGet(maxSeqNoOfUpdatesOnPrimary, Math::max); } private boolean assertMaxSeqNoOfUpdatesIsAdvanced(Term id, long seqNo, boolean allowDeleted, boolean relaxIfGapInSeqNo) { final long maxSeqNoOfUpdates = getMaxSeqNoOfUpdatesOrDeletes(); // We treat a delete on the tombstones on replicas as a regular document, then use updateDocument (not addDocument). if (allowDeleted) { final VersionValue versionValue = versionMap.getVersionForAssert(id.bytes()); if (versionValue != null && versionValue.isDelete()) { return true; } } // Operations can be processed on a replica in a different order than on the primary. If the order on the primary is index-1, // delete-2, index-3, and the order on a replica is index-1, index-3, delete-2, then the msu of index-3 on the replica is 2 // even though it is an update (overwrites index-1). We should relax this assertion if there is a pending gap in the seq_no. if (relaxIfGapInSeqNo && localCheckpointTracker.getProcessedCheckpoint() < maxSeqNoOfUpdates) { return true; } assert seqNo <= maxSeqNoOfUpdates : "id=" + id + " seq_no=" + seqNo + " msu=" + maxSeqNoOfUpdates; return true; } /** * Restores the live version map and local checkpoint of this engine using documents (including soft-deleted) * after the local checkpoint in the safe commit. This step ensures the live version map and checkpoint tracker * are in sync with the Lucene commit. */ private void restoreVersionMapAndCheckpointTracker(DirectoryReader directoryReader, IndexVersion indexVersionCreated) throws IOException { final IndexSearcher searcher = new IndexSearcher(directoryReader); searcher.setQueryCache(null); final Query query = new BooleanQuery.Builder().add( LongPoint.newRangeQuery(SeqNoFieldMapper.NAME, getPersistedLocalCheckpoint() + 1, Long.MAX_VALUE), BooleanClause.Occur.MUST ) .add(Queries.newNonNestedFilter(indexVersionCreated), BooleanClause.Occur.MUST) // exclude non-root nested documents .build(); final Weight weight = searcher.createWeight(searcher.rewrite(query), ScoreMode.COMPLETE_NO_SCORES, 1.0f); for (LeafReaderContext leaf : directoryReader.leaves()) { final Scorer scorer = weight.scorer(leaf); if (scorer == null) { continue; } final CombinedDocValues dv = new CombinedDocValues(leaf.reader()); final IdStoredFieldLoader idFieldLoader = new IdStoredFieldLoader(leaf.reader()); final DocIdSetIterator iterator = scorer.iterator(); int docId; while ((docId = iterator.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { final long primaryTerm = dv.docPrimaryTerm(docId); final long seqNo = dv.docSeqNo(docId); localCheckpointTracker.markSeqNoAsProcessed(seqNo); localCheckpointTracker.markSeqNoAsPersisted(seqNo); String id = idFieldLoader.id(docId); if (id == null) { assert dv.isTombstone(docId); continue; } final BytesRef uid = new Term(IdFieldMapper.NAME, Uid.encodeId(id)).bytes(); try (Releasable ignored = versionMap.acquireLock(uid)) { final VersionValue curr = versionMap.getUnderLock(uid); if (curr == null || compareOpToVersionMapOnSeqNo(id, seqNo, primaryTerm, curr) == OpVsLuceneDocStatus.OP_NEWER) { if (dv.isTombstone(docId)) { // use 0L for the start time so we can prune this delete tombstone quickly // when the local checkpoint advances (i.e., after a recovery completed). final long startTime = 0L; versionMap.putDeleteUnderLock(uid, new DeleteVersionValue(dv.docVersion(docId), seqNo, primaryTerm, startTime)); } else { versionMap.putIndexUnderLock(uid, new IndexVersionValue(null, dv.docVersion(docId), seqNo, primaryTerm)); } } } } } // remove live entries in the version map refresh("restore_version_map_and_checkpoint_tracker", SearcherScope.INTERNAL, true); } @Override public ShardLongFieldRange getRawFieldRange(String field) { return ShardLongFieldRange.UNKNOWN; } @Override public void addFlushListener(Translog.Location location, ActionListener<Long> listener) { this.flushListener.addOrNotify(location, new ActionListener<>() { @Override public void onResponse(Long generation) { waitForCommitDurability(generation, listener.map(v -> generation)); } @Override public void onFailure(Exception e) { listener.onFailure(e); } }); } protected void waitForCommitDurability(long generation, ActionListener<Void> listener) { try { ensureOpen(); } catch (AlreadyClosedException e) { listener.onFailure(e); return; } if (lastCommittedSegmentInfos.getGeneration() < generation) { listener.onFailure(new IllegalStateException("Cannot wait on generation which has not been committed")); } else { listener.onResponse(null); } } public long getLastUnsafeSegmentGenerationForGets() { return lastUnsafeSegmentGenerationForGets.get(); } protected LiveVersionMapArchive createLiveVersionMapArchive() { return LiveVersionMapArchive.NOOP_ARCHIVE; } protected LiveVersionMapArchive getLiveVersionMapArchive() { return liveVersionMapArchive; } // Visible for testing purposes only public LiveVersionMap getLiveVersionMap() { return versionMap; } private static boolean assertGetUsesIdField(Get get) { assert Objects.equals(get.uid().field(), IdFieldMapper.NAME) : get.uid().field(); return true; } protected long getPreCommitSegmentGeneration() { return preCommitSegmentGeneration.get(); } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/index/engine/InternalEngine.java
44,945
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderelection; import java.util.Map; /** * Abstract class of all the message manager classes. */ public abstract class AbstractMessageManager implements MessageManager { /** * Contain all the instances in the system. Key is its ID, and value is the instance itself. */ protected Map<Integer, Instance> instanceMap; /** * Constructor of AbstractMessageManager. */ public AbstractMessageManager(Map<Integer, Instance> instanceMap) { this.instanceMap = instanceMap; } /** * Find the next instance with the smallest ID. * * @return The next instance. */ protected Instance findNextInstance(int currentId) { Instance result = null; var candidateList = instanceMap.keySet() .stream() .filter((i) -> i > currentId && instanceMap.get(i).isAlive()) .sorted() .toList(); if (candidateList.isEmpty()) { var index = instanceMap.keySet() .stream() .filter((i) -> instanceMap.get(i).isAlive()) .sorted() .toList() .get(0); result = instanceMap.get(index); } else { var index = candidateList.get(0); result = instanceMap.get(index); } return result; } }
iluwatar/java-design-patterns
leader-election/src/main/java/com/iluwatar/leaderelection/AbstractMessageManager.java
44,946
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.search.internal; import org.elasticsearch.TransportVersion; import org.elasticsearch.TransportVersions; import org.elasticsearch.action.IndicesRequest; import org.elasticsearch.action.OriginalIndices; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchShardTask; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.cluster.metadata.AliasMetadata; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.common.CheckedBiConsumer; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.hash.MessageDigests; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.core.CheckedFunction; import org.elasticsearch.core.Nullable; import org.elasticsearch.core.TimeValue; import org.elasticsearch.index.Index; import org.elasticsearch.index.mapper.SourceLoader; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.MatchNoneQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryRewriteContext; import org.elasticsearch.index.query.Rewriteable; import org.elasticsearch.index.query.SearchExecutionContext; import org.elasticsearch.index.seqno.SequenceNumbers; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.indices.AliasFilterParsingException; import org.elasticsearch.indices.InvalidAliasNameException; import org.elasticsearch.search.Scroll; import org.elasticsearch.search.SearchService; import org.elasticsearch.search.SearchSortValuesAndFormats; import org.elasticsearch.search.builder.PointInTimeBuilder; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.builder.SubSearchSourceBuilder; import org.elasticsearch.search.query.QuerySearchResult; import org.elasticsearch.search.sort.FieldSortBuilder; import org.elasticsearch.tasks.Task; import org.elasticsearch.tasks.TaskId; import org.elasticsearch.transport.TransportRequest; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.function.Function; import static java.util.Collections.emptyMap; import static org.elasticsearch.search.internal.SearchContext.TRACK_TOTAL_HITS_DISABLED; /** * Shard level request that represents a search. * It provides all the methods that the {@link SearchContext} needs. * Provides a cache key based on its content that can be used to cache shard level response. */ public class ShardSearchRequest extends TransportRequest implements IndicesRequest { private final String clusterAlias; private final ShardId shardId; private final int shardRequestIndex; private final int numberOfShards; private final long waitForCheckpoint; private final TimeValue waitForCheckpointsTimeout; private final SearchType searchType; private final Scroll scroll; private final float indexBoost; private Boolean requestCache; private final long nowInMillis; private final boolean allowPartialSearchResults; private final OriginalIndices originalIndices; private boolean canReturnNullResponseIfMatchNoDocs; private SearchSortValuesAndFormats bottomSortValues; // these are the only mutable fields, as they are subject to rewriting private AliasFilter aliasFilter; private SearchSourceBuilder source; private final ShardSearchContextId readerId; private final TimeValue keepAlive; private final TransportVersion channelVersion; /** * Should this request force {@link SourceLoader.Synthetic synthetic source}? * Use this to test if the mapping supports synthetic _source and to get a sense * of the worst case performance. Fetches with this enabled will be slower the * enabling synthetic source natively in the index. */ private final boolean forceSyntheticSource; public ShardSearchRequest( OriginalIndices originalIndices, SearchRequest searchRequest, ShardId shardId, int shardRequestIndex, int numberOfShards, AliasFilter aliasFilter, float indexBoost, long nowInMillis, @Nullable String clusterAlias ) { this( originalIndices, searchRequest, shardId, shardRequestIndex, numberOfShards, aliasFilter, indexBoost, nowInMillis, clusterAlias, null, null ); } public ShardSearchRequest( OriginalIndices originalIndices, SearchRequest searchRequest, ShardId shardId, int shardRequestIndex, int numberOfShards, AliasFilter aliasFilter, float indexBoost, long nowInMillis, @Nullable String clusterAlias, ShardSearchContextId readerId, TimeValue keepAlive ) { this( originalIndices, shardId, shardRequestIndex, numberOfShards, searchRequest.searchType(), searchRequest.source(), searchRequest.requestCache(), aliasFilter, indexBoost, searchRequest.allowPartialSearchResults(), searchRequest.scroll(), nowInMillis, clusterAlias, readerId, keepAlive, computeWaitForCheckpoint(searchRequest.getWaitForCheckpoints(), shardId, shardRequestIndex), searchRequest.getWaitForCheckpointsTimeout(), searchRequest.isForceSyntheticSource() ); // If allowPartialSearchResults is unset (ie null), the cluster-level default should have been substituted // at this stage. Any NPEs in the above are therefore an error in request preparation logic. assert searchRequest.allowPartialSearchResults() != null; } private static final long[] EMPTY_LONG_ARRAY = new long[0]; public static long computeWaitForCheckpoint(Map<String, long[]> indexToWaitForCheckpoints, ShardId shardId, int shardRequestIndex) { final long[] waitForCheckpoints = indexToWaitForCheckpoints.getOrDefault(shardId.getIndex().getName(), EMPTY_LONG_ARRAY); long waitForCheckpoint; if (waitForCheckpoints.length == 0) { waitForCheckpoint = SequenceNumbers.UNASSIGNED_SEQ_NO; } else { assert waitForCheckpoints.length > shardRequestIndex; waitForCheckpoint = waitForCheckpoints[shardRequestIndex]; } return waitForCheckpoint; } public ShardSearchRequest(ShardId shardId, long nowInMillis, AliasFilter aliasFilter) { this(shardId, nowInMillis, aliasFilter, null); } public ShardSearchRequest(ShardId shardId, long nowInMillis, AliasFilter aliasFilter, String clusterAlias) { this( OriginalIndices.NONE, shardId, -1, -1, SearchType.QUERY_THEN_FETCH, null, null, aliasFilter, 1.0f, true, null, nowInMillis, clusterAlias, null, null, SequenceNumbers.UNASSIGNED_SEQ_NO, SearchService.NO_TIMEOUT, false ); } @SuppressWarnings("this-escape") public ShardSearchRequest( OriginalIndices originalIndices, ShardId shardId, int shardRequestIndex, int numberOfShards, SearchType searchType, SearchSourceBuilder source, Boolean requestCache, AliasFilter aliasFilter, float indexBoost, boolean allowPartialSearchResults, Scroll scroll, long nowInMillis, @Nullable String clusterAlias, ShardSearchContextId readerId, TimeValue keepAlive, long waitForCheckpoint, TimeValue waitForCheckpointsTimeout, boolean forceSyntheticSource ) { this.shardId = shardId; this.shardRequestIndex = shardRequestIndex; this.numberOfShards = numberOfShards; this.searchType = searchType; this.source(source); this.requestCache = requestCache; this.aliasFilter = aliasFilter; this.indexBoost = indexBoost; this.allowPartialSearchResults = allowPartialSearchResults; this.scroll = scroll; this.nowInMillis = nowInMillis; this.clusterAlias = clusterAlias; this.originalIndices = originalIndices; this.readerId = readerId; this.keepAlive = keepAlive; assert keepAlive == null || readerId != null : "readerId: null keepAlive: " + keepAlive; this.channelVersion = TransportVersion.current(); this.waitForCheckpoint = waitForCheckpoint; this.waitForCheckpointsTimeout = waitForCheckpointsTimeout; this.forceSyntheticSource = forceSyntheticSource; } @SuppressWarnings("this-escape") public ShardSearchRequest(ShardSearchRequest clone) { this.shardId = clone.shardId; this.shardRequestIndex = clone.shardRequestIndex; this.searchType = clone.searchType; this.numberOfShards = clone.numberOfShards; this.scroll = clone.scroll; this.source(clone.source); this.aliasFilter = clone.aliasFilter; this.indexBoost = clone.indexBoost; this.nowInMillis = clone.nowInMillis; this.requestCache = clone.requestCache; this.clusterAlias = clone.clusterAlias; this.allowPartialSearchResults = clone.allowPartialSearchResults; this.canReturnNullResponseIfMatchNoDocs = clone.canReturnNullResponseIfMatchNoDocs; this.bottomSortValues = clone.bottomSortValues; this.originalIndices = clone.originalIndices; this.readerId = clone.readerId; this.keepAlive = clone.keepAlive; this.channelVersion = clone.channelVersion; this.waitForCheckpoint = clone.waitForCheckpoint; this.waitForCheckpointsTimeout = clone.waitForCheckpointsTimeout; this.forceSyntheticSource = clone.forceSyntheticSource; } public ShardSearchRequest(StreamInput in) throws IOException { super(in); shardId = new ShardId(in); searchType = SearchType.fromId(in.readByte()); shardRequestIndex = in.readVInt(); numberOfShards = in.readVInt(); scroll = in.readOptionalWriteable(Scroll::new); source = in.readOptionalWriteable(SearchSourceBuilder::new); if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_8_0) && in.getTransportVersion().before(TransportVersions.V_8_9_X)) { // to deserialize between the 8.8 and 8.500.020 version we need to translate // the rank queries into sub searches if we are ranking; if there are no rank queries // we deserialize the empty list and do nothing List<QueryBuilder> rankQueryBuilders = in.readNamedWriteableCollectionAsList(QueryBuilder.class); // if we are in the dfs phase in 8.8, we can have no rank queries // and if we are in the query/fetch phase we can have either no rank queries // for a standard query or hybrid search or 2+ rank queries, but we cannot have // exactly 1 rank query ever so we check for this assert rankQueryBuilders.size() != 1 : "[rank] requires at least [2] sub searches, but only found [1]"; // if we have 2+ rank queries we know we are ranking, so we set our // sub searches from this; note this will override the boolean query deserialized from source // because we use the same data structure for a single query and multiple queries // but we will just re-create it as necessary if (rankQueryBuilders.size() >= 2) { assert source != null && source.rankBuilder() != null; List<SubSearchSourceBuilder> subSearchSourceBuilders = new ArrayList<>(); for (QueryBuilder queryBuilder : rankQueryBuilders) { subSearchSourceBuilders.add(new SubSearchSourceBuilder(queryBuilder)); } source.subSearches(subSearchSourceBuilders); } } if (in.getTransportVersion().before(TransportVersions.V_8_0_0)) { // types no longer relevant so ignore String[] types = in.readStringArray(); if (types.length > 0) { throw new IllegalStateException( "types are no longer supported in search requests but found [" + Arrays.toString(types) + "]" ); } } aliasFilter = AliasFilter.readFrom(in); indexBoost = in.readFloat(); nowInMillis = in.readVLong(); requestCache = in.readOptionalBoolean(); clusterAlias = in.readOptionalString(); allowPartialSearchResults = in.readBoolean(); canReturnNullResponseIfMatchNoDocs = in.readBoolean(); bottomSortValues = in.readOptionalWriteable(SearchSortValuesAndFormats::new); readerId = in.readOptionalWriteable(ShardSearchContextId::new); keepAlive = in.readOptionalTimeValue(); assert keepAlive == null || readerId != null : "readerId: null keepAlive: " + keepAlive; channelVersion = TransportVersion.min(TransportVersion.readVersion(in), in.getTransportVersion()); waitForCheckpoint = in.readLong(); waitForCheckpointsTimeout = in.readTimeValue(); if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_4_0)) { forceSyntheticSource = in.readBoolean(); } else { /* * Synthetic source is not supported before 8.3.0 so any request * from a coordinating node of that version will not want to * force it. */ forceSyntheticSource = false; } originalIndices = OriginalIndices.readOriginalIndices(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); innerWriteTo(out, false); OriginalIndices.writeOriginalIndices(originalIndices, out); } protected final void innerWriteTo(StreamOutput out, boolean asKey) throws IOException { shardId.writeTo(out); out.writeByte(searchType.id()); if (asKey == false) { out.writeVInt(shardRequestIndex); out.writeVInt(numberOfShards); } out.writeOptionalWriteable(scroll); out.writeOptionalWriteable(source); if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_8_0) && out.getTransportVersion().before(TransportVersions.V_8_9_X)) { // to serialize between the 8.8 and 8.500.020 version we need to translate // the sub searches into rank queries if we are ranking, otherwise, we // ignore this because linear combination will have multiple sub searches in // 8.500.020+, but only use the combined boolean query in prior versions List<QueryBuilder> rankQueryBuilders = new ArrayList<>(); if (source != null && source.rankBuilder() != null && source.subSearches().size() >= 2) { for (SubSearchSourceBuilder subSearchSourceBuilder : source.subSearches()) { rankQueryBuilders.add(subSearchSourceBuilder.getQueryBuilder()); } } out.writeNamedWriteableCollection(rankQueryBuilders); } if (out.getTransportVersion().before(TransportVersions.V_8_0_0)) { // types not supported so send an empty array to previous versions out.writeStringArray(Strings.EMPTY_ARRAY); } aliasFilter.writeTo(out); out.writeFloat(indexBoost); if (asKey == false) { out.writeVLong(nowInMillis); } out.writeOptionalBoolean(requestCache); out.writeOptionalString(clusterAlias); out.writeBoolean(allowPartialSearchResults); if (asKey == false) { out.writeBoolean(canReturnNullResponseIfMatchNoDocs); out.writeOptionalWriteable(bottomSortValues); out.writeOptionalWriteable(readerId); out.writeOptionalTimeValue(keepAlive); } TransportVersion.writeVersion(channelVersion, out); out.writeLong(waitForCheckpoint); out.writeTimeValue(waitForCheckpointsTimeout); if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_4_0)) { out.writeBoolean(forceSyntheticSource); } else { if (forceSyntheticSource) { throw new IllegalArgumentException("force_synthetic_source is not supported before 8.4.0"); } } } @Override public String[] indices() { if (originalIndices == null) { return null; } return originalIndices.indices(); } @Override public IndicesOptions indicesOptions() { if (originalIndices == null) { return null; } return originalIndices.indicesOptions(); } public ShardId shardId() { return shardId; } public SearchSourceBuilder source() { return source; } public AliasFilter getAliasFilter() { return aliasFilter; } public void setAliasFilter(AliasFilter aliasFilter) { this.aliasFilter = aliasFilter; } public void source(SearchSourceBuilder source) { if (source != null && source.pointInTimeBuilder() != null) { // Discard the actual point in time as data nodes don't use it to reduce the memory usage and the serialization cost // of shard-level search requests. However, we need to assign as a dummy PIT instead of null as we verify PIT for // slice requests on data nodes. source = source.shallowCopy(); source.pointInTimeBuilder(new PointInTimeBuilder(BytesArray.EMPTY)); } this.source = source; } /** * Returns the shard request ordinal that is used by the main search request * to reference this shard. */ public int shardRequestIndex() { return shardRequestIndex; } public int numberOfShards() { return numberOfShards; } public SearchType searchType() { return searchType; } public float indexBoost() { return indexBoost; } public long nowInMillis() { return nowInMillis; } public Boolean requestCache() { return requestCache; } public void requestCache(Boolean requestCache) { this.requestCache = requestCache; } public boolean allowPartialSearchResults() { return allowPartialSearchResults; } public Scroll scroll() { return scroll; } /** * Sets the bottom sort values that can be used by the searcher to filter documents * that are after it. This value is computed by coordinating nodes that throttles the * query phase. After a partial merge of successful shards the sort values of the * bottom top document are passed as an hint on subsequent shard requests. */ public void setBottomSortValues(SearchSortValuesAndFormats values) { this.bottomSortValues = values; } public SearchSortValuesAndFormats getBottomSortValues() { return bottomSortValues; } /** * Returns true if the caller can handle null response {@link QuerySearchResult#nullInstance()}. * Defaults to false since the coordinator node needs at least one shard response to build the global * response. */ public boolean canReturnNullResponseIfMatchNoDocs() { return canReturnNullResponseIfMatchNoDocs; } public void canReturnNullResponseIfMatchNoDocs(boolean value) { this.canReturnNullResponseIfMatchNoDocs = value; } private static final ThreadLocal<BytesStreamOutput> scratch = ThreadLocal.withInitial(BytesStreamOutput::new); /** * Returns a non-null value if this request should execute using a specific point-in-time reader; * otherwise, using the most up to date point-in-time reader. */ public ShardSearchContextId readerId() { return readerId; } /** * Returns a non-null to specify the time to live of the point-in-time reader that is used to execute this request. */ public TimeValue keepAlive() { return keepAlive; } public long waitForCheckpoint() { return waitForCheckpoint; } public TimeValue getWaitForCheckpointsTimeout() { return waitForCheckpointsTimeout; } /** * Returns the cache key for this shard search request, based on its content */ public BytesReference cacheKey(CheckedBiConsumer<ShardSearchRequest, StreamOutput, IOException> differentiator) throws IOException { BytesStreamOutput out = scratch.get(); try { this.innerWriteTo(out, true); if (differentiator != null) { differentiator.accept(this, out); } return new BytesArray(MessageDigests.digest(out.bytes(), MessageDigests.sha256())); } finally { out.reset(); } } public String getClusterAlias() { return clusterAlias; } @Override public Task createTask(long id, String type, String action, TaskId parentTaskId, Map<String, String> headers) { return new SearchShardTask(id, type, action, getDescription(), parentTaskId, headers); } @Override public String getDescription() { // Shard id is enough here, the request itself can be found by looking at the parent task description return "shardId[" + shardId() + "]"; } @SuppressWarnings("rawtypes") public Rewriteable<Rewriteable> getRewriteable() { return new RequestRewritable(this); } @SuppressWarnings("rawtypes") static class RequestRewritable implements Rewriteable<Rewriteable> { final ShardSearchRequest request; RequestRewritable(ShardSearchRequest request) { this.request = request; } @Override public Rewriteable rewrite(QueryRewriteContext ctx) throws IOException { SearchSourceBuilder newSource = request.source() == null ? null : Rewriteable.rewrite(request.source(), ctx); AliasFilter newAliasFilter = Rewriteable.rewrite(request.getAliasFilter(), ctx); SearchExecutionContext searchExecutionContext = ctx.convertToSearchExecutionContext(); FieldSortBuilder primarySort = FieldSortBuilder.getPrimaryFieldSortOrNull(newSource); if (searchExecutionContext != null && primarySort != null && primarySort.isBottomSortShardDisjoint(searchExecutionContext, request.getBottomSortValues())) { assert newSource != null : "source should contain a primary sort field"; newSource = newSource.shallowCopy(); int trackTotalHitsUpTo = SearchRequest.resolveTrackTotalHitsUpTo(request.scroll, request.source); if (trackTotalHitsUpTo == TRACK_TOTAL_HITS_DISABLED && newSource.suggest() == null && newSource.aggregations() == null) { newSource.query(new MatchNoneQueryBuilder()); } else { newSource.size(0); } request.source(newSource); request.setBottomSortValues(null); } if (newSource == request.source() && newAliasFilter == request.getAliasFilter()) { return this; } else { request.source(newSource); request.setAliasFilter(newAliasFilter); return new RequestRewritable(request); } } } /** * Returns the filter associated with listed filtering aliases. * <p> * The list of filtering aliases should be obtained by calling Metadata.filteringAliases. * Returns {@code null} if no filtering is required.</p> */ public static QueryBuilder parseAliasFilter( CheckedFunction<BytesReference, QueryBuilder, IOException> filterParser, IndexMetadata metadata, String... aliasNames ) { if (aliasNames == null || aliasNames.length == 0) { return null; } Index index = metadata.getIndex(); Map<String, AliasMetadata> aliases = metadata.getAliases(); Function<AliasMetadata, QueryBuilder> parserFunction = (alias) -> { if (alias.filter() == null) { return null; } try { return filterParser.apply(alias.filter().uncompressed()); } catch (IOException ex) { throw new AliasFilterParsingException(index, alias.getAlias(), "Invalid alias filter", ex); } }; if (aliasNames.length == 1) { AliasMetadata alias = aliases.get(aliasNames[0]); if (alias == null) { // This shouldn't happen unless alias disappeared after filteringAliases was called. throw new InvalidAliasNameException(index, aliasNames[0], "Unknown alias name was passed to alias Filter"); } return parserFunction.apply(alias); } else { // we need to bench here a bit, to see maybe it makes sense to use OrFilter BoolQueryBuilder combined = new BoolQueryBuilder(); for (String aliasName : aliasNames) { AliasMetadata alias = aliases.get(aliasName); if (alias == null) { // This shouldn't happen unless alias disappeared after filteringAliases was called. throw new InvalidAliasNameException(index, aliasNames[0], "Unknown alias name was passed to alias Filter"); } QueryBuilder parsedFilter = parserFunction.apply(alias); if (parsedFilter != null) { combined.should(parsedFilter); } else { // The filter might be null only if filter was removed after filteringAliases was called return null; } } return combined; } } public final Map<String, Object> getRuntimeMappings() { return source == null ? emptyMap() : source.runtimeMappings(); } /** * Returns the minimum version of the channel that the request has been passed. If the request never passes around, then the channel * version is {@link TransportVersion#current()}; otherwise, it's the minimum transport version of the coordinating node and data node * (and the proxy node in case the request is sent to the proxy node of the remote cluster before reaching the data node). */ public TransportVersion getChannelVersion() { return channelVersion; } /** * Should this request force {@link SourceLoader.Synthetic synthetic source}? * Use this to test if the mapping supports synthetic _source and to get a sense * of the worst case performance. Fetches with this enabled will be slower the * enabling synthetic source natively in the index. */ public boolean isForceSyntheticSource() { return forceSyntheticSource; } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/search/internal/ShardSearchRequest.java
44,947
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under both the GPLv2 (found in the // COPYING file in the root directory) and Apache 2.0 License // (found in the LICENSE.Apache file in the root directory). package org.rocksdb; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import org.rocksdb.util.Environment; /** * A RocksDB is a persistent ordered map from keys to values. It is safe for * concurrent access from multiple threads without any external synchronization. * All methods of this class could potentially throw RocksDBException, which * indicates sth wrong at the RocksDB library side and the call failed. */ public class RocksDB extends RocksObject { public static final byte[] DEFAULT_COLUMN_FAMILY = "default".getBytes(); public static final int NOT_FOUND = -1; private enum LibraryState { NOT_LOADED, LOADING, LOADED } private static AtomicReference<LibraryState> libraryLoaded = new AtomicReference<>(LibraryState.NOT_LOADED); static { RocksDB.loadLibrary(); } private List<ColumnFamilyHandle> ownedColumnFamilyHandles = new ArrayList<>(); /** * Loads the necessary library files. * Calling this method twice will have no effect. * By default the method extracts the shared library for loading at * java.io.tmpdir, however, you can override this temporary location by * setting the environment variable ROCKSDB_SHAREDLIB_DIR. */ public static void loadLibrary() { if (libraryLoaded.get() == LibraryState.LOADED) { return; } if (libraryLoaded.compareAndSet(LibraryState.NOT_LOADED, LibraryState.LOADING)) { final String tmpDir = System.getenv("ROCKSDB_SHAREDLIB_DIR"); // loading possibly necessary libraries. for (final CompressionType compressionType : CompressionType.values()) { try { if (compressionType.getLibraryName() != null) { System.loadLibrary(compressionType.getLibraryName()); } } catch (final UnsatisfiedLinkError e) { // since it may be optional, we ignore its loading failure here. } } try { NativeLibraryLoader.getInstance().loadLibrary(tmpDir); } catch (final IOException e) { libraryLoaded.set(LibraryState.NOT_LOADED); throw new RuntimeException("Unable to load the RocksDB shared library", e); } final int encodedVersion = version(); version = Version.fromEncodedVersion(encodedVersion); libraryLoaded.set(LibraryState.LOADED); return; } while (libraryLoaded.get() == LibraryState.LOADING) { try { Thread.sleep(10); } catch(final InterruptedException e) { //ignore } } } /** * Tries to load the necessary library files from the given list of * directories. * * @param paths a list of strings where each describes a directory * of a library. */ public static void loadLibrary(final List<String> paths) { if (libraryLoaded.get() == LibraryState.LOADED) { return; } if (libraryLoaded.compareAndSet(LibraryState.NOT_LOADED, LibraryState.LOADING)) { for (final CompressionType compressionType : CompressionType.values()) { if (compressionType.equals(CompressionType.NO_COMPRESSION)) { continue; } for (final String path : paths) { try { System.load(path + "/" + Environment.getSharedLibraryFileName( compressionType.getLibraryName())); break; } catch (final UnsatisfiedLinkError e) { // since they are optional, we ignore loading fails. } } } boolean success = false; UnsatisfiedLinkError err = null; for (final String path : paths) { try { System.load(path + "/" + Environment.getJniLibraryFileName("rocksdbjni")); success = true; break; } catch (final UnsatisfiedLinkError e) { err = e; } } if (!success) { libraryLoaded.set(LibraryState.NOT_LOADED); throw err; } final int encodedVersion = version(); version = Version.fromEncodedVersion(encodedVersion); libraryLoaded.set(LibraryState.LOADED); return; } while (libraryLoaded.get() == LibraryState.LOADING) { try { Thread.sleep(10); } catch(final InterruptedException e) { //ignore } } } public static Version rocksdbVersion() { return version; } /** * Private constructor. * * @param nativeHandle The native handle of the C++ RocksDB object */ protected RocksDB(final long nativeHandle) { super(nativeHandle); } /** * The factory constructor of RocksDB that opens a RocksDB instance given * the path to the database using the default options w/ createIfMissing * set to true. * * @param path the path to the rocksdb. * @return a {@link RocksDB} instance on success, null if the specified * {@link RocksDB} can not be opened. * * @throws RocksDBException thrown if error happens in underlying * native library. * @see Options#setCreateIfMissing(boolean) */ public static RocksDB open(final String path) throws RocksDBException { final Options options = new Options(); options.setCreateIfMissing(true); return open(options, path); } /** * The factory constructor of RocksDB that opens a RocksDB instance given * the path to the database using the specified options and db path and a list * of column family names. * <p> * If opened in read write mode every existing column family name must be * passed within the list to this method.</p> * <p> * If opened in read-only mode only a subset of existing column families must * be passed to this method.</p> * <p> * Options instance *should* not be disposed before all DBs using this options * instance have been closed. If user doesn't call options dispose explicitly, * then this options instance will be GC'd automatically</p> * <p> * ColumnFamily handles are disposed when the RocksDB instance is disposed. * </p> * * @param path the path to the rocksdb. * @param columnFamilyDescriptors list of column family descriptors * @param columnFamilyHandles will be filled with ColumnFamilyHandle instances * on open. * @return a {@link RocksDB} instance on success, null if the specified * {@link RocksDB} can not be opened. * * @throws RocksDBException thrown if error happens in underlying * native library. * @see DBOptions#setCreateIfMissing(boolean) */ public static RocksDB open(final String path, final List<ColumnFamilyDescriptor> columnFamilyDescriptors, final List<ColumnFamilyHandle> columnFamilyHandles) throws RocksDBException { final DBOptions options = new DBOptions(); return open(options, path, columnFamilyDescriptors, columnFamilyHandles); } /** * The factory constructor of RocksDB that opens a RocksDB instance given * the path to the database using the specified options and db path. * * <p> * Options instance *should* not be disposed before all DBs using this options * instance have been closed. If user doesn't call options dispose explicitly, * then this options instance will be GC'd automatically.</p> * <p> * Options instance can be re-used to open multiple DBs if DB statistics is * not used. If DB statistics are required, then its recommended to open DB * with new Options instance as underlying native statistics instance does not * use any locks to prevent concurrent updates.</p> * * @param options {@link org.rocksdb.Options} instance. * @param path the path to the rocksdb. * @return a {@link RocksDB} instance on success, null if the specified * {@link RocksDB} can not be opened. * * @throws RocksDBException thrown if error happens in underlying * native library. * * @see Options#setCreateIfMissing(boolean) */ public static RocksDB open(final Options options, final String path) throws RocksDBException { // when non-default Options is used, keeping an Options reference // in RocksDB can prevent Java to GC during the life-time of // the currently-created RocksDB. final RocksDB db = new RocksDB(open(options.nativeHandle_, path)); db.storeOptionsInstance(options); return db; } /** * The factory constructor of RocksDB that opens a RocksDB instance given * the path to the database using the specified options and db path and a list * of column family names. * <p> * If opened in read write mode every existing column family name must be * passed within the list to this method.</p> * <p> * If opened in read-only mode only a subset of existing column families must * be passed to this method.</p> * <p> * Options instance *should* not be disposed before all DBs using this options * instance have been closed. If user doesn't call options dispose explicitly, * then this options instance will be GC'd automatically.</p> * <p> * Options instance can be re-used to open multiple DBs if DB statistics is * not used. If DB statistics are required, then its recommended to open DB * with new Options instance as underlying native statistics instance does not * use any locks to prevent concurrent updates.</p> * <p> * ColumnFamily handles are disposed when the RocksDB instance is disposed. * </p> * * @param options {@link org.rocksdb.DBOptions} instance. * @param path the path to the rocksdb. * @param columnFamilyDescriptors list of column family descriptors * @param columnFamilyHandles will be filled with ColumnFamilyHandle instances * on open. * @return a {@link RocksDB} instance on success, null if the specified * {@link RocksDB} can not be opened. * * @throws RocksDBException thrown if error happens in underlying * native library. * * @see DBOptions#setCreateIfMissing(boolean) */ public static RocksDB open(final DBOptions options, final String path, final List<ColumnFamilyDescriptor> columnFamilyDescriptors, final List<ColumnFamilyHandle> columnFamilyHandles) throws RocksDBException { final byte[][] cfNames = new byte[columnFamilyDescriptors.size()][]; final long[] cfOptionHandles = new long[columnFamilyDescriptors.size()]; for (int i = 0; i < columnFamilyDescriptors.size(); i++) { final ColumnFamilyDescriptor cfDescriptor = columnFamilyDescriptors .get(i); cfNames[i] = cfDescriptor.getName(); cfOptionHandles[i] = cfDescriptor.getOptions().nativeHandle_; } final long[] handles = open(options.nativeHandle_, path, cfNames, cfOptionHandles); final RocksDB db = new RocksDB(handles[0]); db.storeOptionsInstance(options); for (int i = 1; i < handles.length; i++) { final ColumnFamilyHandle columnFamilyHandle = new ColumnFamilyHandle(db, handles[i]); columnFamilyHandles.add(columnFamilyHandle); } db.ownedColumnFamilyHandles.addAll(columnFamilyHandles); return db; } /** * The factory constructor of RocksDB that opens a RocksDB instance in * Read-Only mode given the path to the database using the default * options. * * @param path the path to the RocksDB. * @return a {@link RocksDB} instance on success, null if the specified * {@link RocksDB} can not be opened. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public static RocksDB openReadOnly(final String path) throws RocksDBException { // This allows to use the rocksjni default Options instead of // the c++ one. final Options options = new Options(); return openReadOnly(options, path); } /** * The factory constructor of RocksDB that opens a RocksDB instance in * Read-Only mode given the path to the database using the specified * options and db path. * * Options instance *should* not be disposed before all DBs using this options * instance have been closed. If user doesn't call options dispose explicitly, * then this options instance will be GC'd automatically. * * @param options {@link Options} instance. * @param path the path to the RocksDB. * @return a {@link RocksDB} instance on success, null if the specified * {@link RocksDB} can not be opened. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public static RocksDB openReadOnly(final Options options, final String path) throws RocksDBException { return openReadOnly(options, path, false); } /** * The factory constructor of RocksDB that opens a RocksDB instance in * Read-Only mode given the path to the database using the specified * options and db path. * * Options instance *should* not be disposed before all DBs using this options * instance have been closed. If user doesn't call options dispose explicitly, * then this options instance will be GC'd automatically. * * @param options {@link Options} instance. * @param path the path to the RocksDB. * @param errorIfWalFileExists true to raise an error when opening the db * if a Write Ahead Log file exists, false otherwise. * @return a {@link RocksDB} instance on success, null if the specified * {@link RocksDB} can not be opened. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public static RocksDB openReadOnly(final Options options, final String path, final boolean errorIfWalFileExists) throws RocksDBException { // when non-default Options is used, keeping an Options reference // in RocksDB can prevent Java to GC during the life-time of // the currently-created RocksDB. final RocksDB db = new RocksDB(openROnly(options.nativeHandle_, path, errorIfWalFileExists)); db.storeOptionsInstance(options); return db; } /** * The factory constructor of RocksDB that opens a RocksDB instance in * Read-Only mode given the path to the database using the default * options. * * @param path the path to the RocksDB. * @param columnFamilyDescriptors list of column family descriptors * @param columnFamilyHandles will be filled with ColumnFamilyHandle instances * on open. * @return a {@link RocksDB} instance on success, null if the specified * {@link RocksDB} can not be opened. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public static RocksDB openReadOnly(final String path, final List<ColumnFamilyDescriptor> columnFamilyDescriptors, final List<ColumnFamilyHandle> columnFamilyHandles) throws RocksDBException { // This allows to use the rocksjni default Options instead of // the c++ one. final DBOptions options = new DBOptions(); return openReadOnly(options, path, columnFamilyDescriptors, columnFamilyHandles, false); } /** * The factory constructor of RocksDB that opens a RocksDB instance in * Read-Only mode given the path to the database using the specified * options and db path. * * <p>This open method allows to open RocksDB using a subset of available * column families</p> * <p>Options instance *should* not be disposed before all DBs using this * options instance have been closed. If user doesn't call options dispose * explicitly,then this options instance will be GC'd automatically.</p> * * @param options {@link DBOptions} instance. * @param path the path to the RocksDB. * @param columnFamilyDescriptors list of column family descriptors * @param columnFamilyHandles will be filled with ColumnFamilyHandle instances * on open. * @return a {@link RocksDB} instance on success, null if the specified * {@link RocksDB} can not be opened. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public static RocksDB openReadOnly(final DBOptions options, final String path, final List<ColumnFamilyDescriptor> columnFamilyDescriptors, final List<ColumnFamilyHandle> columnFamilyHandles) throws RocksDBException { return openReadOnly(options, path, columnFamilyDescriptors, columnFamilyHandles, false); } /** * The factory constructor of RocksDB that opens a RocksDB instance in * Read-Only mode given the path to the database using the specified * options and db path. * * <p>This open method allows to open RocksDB using a subset of available * column families</p> * <p>Options instance *should* not be disposed before all DBs using this * options instance have been closed. If user doesn't call options dispose * explicitly,then this options instance will be GC'd automatically.</p> * * @param options {@link DBOptions} instance. * @param path the path to the RocksDB. * @param columnFamilyDescriptors list of column family descriptors * @param columnFamilyHandles will be filled with ColumnFamilyHandle instances * on open. * @param errorIfWalFileExists true to raise an error when opening the db * if a Write Ahead Log file exists, false otherwise. * @return a {@link RocksDB} instance on success, null if the specified * {@link RocksDB} can not be opened. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public static RocksDB openReadOnly(final DBOptions options, final String path, final List<ColumnFamilyDescriptor> columnFamilyDescriptors, final List<ColumnFamilyHandle> columnFamilyHandles, final boolean errorIfWalFileExists) throws RocksDBException { // when non-default Options is used, keeping an Options reference // in RocksDB can prevent Java to GC during the life-time of // the currently-created RocksDB. final byte[][] cfNames = new byte[columnFamilyDescriptors.size()][]; final long[] cfOptionHandles = new long[columnFamilyDescriptors.size()]; for (int i = 0; i < columnFamilyDescriptors.size(); i++) { final ColumnFamilyDescriptor cfDescriptor = columnFamilyDescriptors .get(i); cfNames[i] = cfDescriptor.getName(); cfOptionHandles[i] = cfDescriptor.getOptions().nativeHandle_; } final long[] handles = openROnly(options.nativeHandle_, path, cfNames, cfOptionHandles, errorIfWalFileExists); final RocksDB db = new RocksDB(handles[0]); db.storeOptionsInstance(options); for (int i = 1; i < handles.length; i++) { final ColumnFamilyHandle columnFamilyHandle = new ColumnFamilyHandle(db, handles[i]); columnFamilyHandles.add(columnFamilyHandle); } db.ownedColumnFamilyHandles.addAll(columnFamilyHandles); return db; } /** * Open DB as secondary instance with only the default column family. * * The secondary instance can dynamically tail the MANIFEST of * a primary that must have already been created. User can call * {@link #tryCatchUpWithPrimary()} to make the secondary instance catch up * with primary (WAL tailing is NOT supported now) whenever the user feels * necessary. Column families created by the primary after the secondary * instance starts are currently ignored by the secondary instance. * Column families opened by secondary and dropped by the primary will be * dropped by secondary as well. However the user of the secondary instance * can still access the data of such dropped column family as long as they * do not destroy the corresponding column family handle. * WAL tailing is not supported at present, but will arrive soon. * * @param options the options to open the secondary instance. * @param path the path to the primary RocksDB instance. * @param secondaryPath points to a directory where the secondary instance * stores its info log * * @return a {@link RocksDB} instance on success, null if the specified * {@link RocksDB} can not be opened. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public static RocksDB openAsSecondary(final Options options, final String path, final String secondaryPath) throws RocksDBException { // when non-default Options is used, keeping an Options reference // in RocksDB can prevent Java to GC during the life-time of // the currently-created RocksDB. final RocksDB db = new RocksDB(openAsSecondary(options.nativeHandle_, path, secondaryPath)); db.storeOptionsInstance(options); return db; } /** * Open DB as secondary instance with column families. * You can open a subset of column families in secondary mode. * * The secondary instance can dynamically tail the MANIFEST of * a primary that must have already been created. User can call * {@link #tryCatchUpWithPrimary()} to make the secondary instance catch up * with primary (WAL tailing is NOT supported now) whenever the user feels * necessary. Column families created by the primary after the secondary * instance starts are currently ignored by the secondary instance. * Column families opened by secondary and dropped by the primary will be * dropped by secondary as well. However the user of the secondary instance * can still access the data of such dropped column family as long as they * do not destroy the corresponding column family handle. * WAL tailing is not supported at present, but will arrive soon. * * @param options the options to open the secondary instance. * @param path the path to the primary RocksDB instance. * @param secondaryPath points to a directory where the secondary instance * stores its info log. * @param columnFamilyDescriptors list of column family descriptors * @param columnFamilyHandles will be filled with ColumnFamilyHandle instances * on open. * * @return a {@link RocksDB} instance on success, null if the specified * {@link RocksDB} can not be opened. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public static RocksDB openAsSecondary(final DBOptions options, final String path, final String secondaryPath, final List<ColumnFamilyDescriptor> columnFamilyDescriptors, final List<ColumnFamilyHandle> columnFamilyHandles) throws RocksDBException { // when non-default Options is used, keeping an Options reference // in RocksDB can prevent Java to GC during the life-time of // the currently-created RocksDB. final byte[][] cfNames = new byte[columnFamilyDescriptors.size()][]; final long[] cfOptionHandles = new long[columnFamilyDescriptors.size()]; for (int i = 0; i < columnFamilyDescriptors.size(); i++) { final ColumnFamilyDescriptor cfDescriptor = columnFamilyDescriptors.get(i); cfNames[i] = cfDescriptor.getName(); cfOptionHandles[i] = cfDescriptor.getOptions().nativeHandle_; } final long[] handles = openAsSecondary(options.nativeHandle_, path, secondaryPath, cfNames, cfOptionHandles); final RocksDB db = new RocksDB(handles[0]); db.storeOptionsInstance(options); for (int i = 1; i < handles.length; i++) { final ColumnFamilyHandle columnFamilyHandle = new ColumnFamilyHandle(db, handles[i]); columnFamilyHandles.add(columnFamilyHandle); } db.ownedColumnFamilyHandles.addAll(columnFamilyHandles); return db; } /** * This is similar to {@link #close()} except that it * throws an exception if any error occurs. * * This will not fsync the WAL files. * If syncing is required, the caller must first call {@link #syncWal()} * or {@link #write(WriteOptions, WriteBatch)} using an empty write batch * with {@link WriteOptions#setSync(boolean)} set to true. * * See also {@link #close()}. * * @throws RocksDBException if an error occurs whilst closing. */ public void closeE() throws RocksDBException { for (final ColumnFamilyHandle columnFamilyHandle : ownedColumnFamilyHandles) { columnFamilyHandle.close(); } ownedColumnFamilyHandles.clear(); if (owningHandle_.compareAndSet(true, false)) { try { closeDatabase(nativeHandle_); } finally { disposeInternal(); } } } /** * This is similar to {@link #closeE()} except that it * silently ignores any errors. * * This will not fsync the WAL files. * If syncing is required, the caller must first call {@link #syncWal()} * or {@link #write(WriteOptions, WriteBatch)} using an empty write batch * with {@link WriteOptions#setSync(boolean)} set to true. * * See also {@link #close()}. */ @Override public void close() { for (final ColumnFamilyHandle columnFamilyHandle : ownedColumnFamilyHandles) { columnFamilyHandle.close(); } ownedColumnFamilyHandles.clear(); if (owningHandle_.compareAndSet(true, false)) { try { closeDatabase(nativeHandle_); } catch (final RocksDBException e) { // silently ignore the error report } finally { disposeInternal(); } } } /** * Static method to determine all available column families for a * rocksdb database identified by path * * @param options Options for opening the database * @param path Absolute path to rocksdb database * @return List&lt;byte[]&gt; List containing the column family names * * @throws RocksDBException thrown if error happens in underlying * native library. */ public static List<byte[]> listColumnFamilies(final Options options, final String path) throws RocksDBException { return Arrays.asList(RocksDB.listColumnFamilies(options.nativeHandle_, path)); } /** * Creates a new column family with the name columnFamilyName and * allocates a ColumnFamilyHandle within an internal structure. * The ColumnFamilyHandle is automatically disposed with DB disposal. * * @param columnFamilyDescriptor column family to be created. * @return {@link org.rocksdb.ColumnFamilyHandle} instance. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public ColumnFamilyHandle createColumnFamily( final ColumnFamilyDescriptor columnFamilyDescriptor) throws RocksDBException { final ColumnFamilyHandle columnFamilyHandle = new ColumnFamilyHandle(this, createColumnFamily(nativeHandle_, columnFamilyDescriptor.getName(), columnFamilyDescriptor.getName().length, columnFamilyDescriptor.getOptions().nativeHandle_)); ownedColumnFamilyHandles.add(columnFamilyHandle); return columnFamilyHandle; } /** * Bulk create column families with the same column family options. * * @param columnFamilyOptions the options for the column families. * @param columnFamilyNames the names of the column families. * * @return the handles to the newly created column families. * * @throws RocksDBException if an error occurs whilst creating * the column families */ public List<ColumnFamilyHandle> createColumnFamilies( final ColumnFamilyOptions columnFamilyOptions, final List<byte[]> columnFamilyNames) throws RocksDBException { final byte[][] cfNames = columnFamilyNames.toArray( new byte[0][]); final long[] cfHandles = createColumnFamilies(nativeHandle_, columnFamilyOptions.nativeHandle_, cfNames); final List<ColumnFamilyHandle> columnFamilyHandles = new ArrayList<>(cfHandles.length); for (int i = 0; i < cfHandles.length; i++) { final ColumnFamilyHandle columnFamilyHandle = new ColumnFamilyHandle(this, cfHandles[i]); columnFamilyHandles.add(columnFamilyHandle); } ownedColumnFamilyHandles.addAll(columnFamilyHandles); return columnFamilyHandles; } /** * Bulk create column families with the same column family options. * * @param columnFamilyDescriptors the descriptions of the column families. * * @return the handles to the newly created column families. * * @throws RocksDBException if an error occurs whilst creating * the column families */ public List<ColumnFamilyHandle> createColumnFamilies( final List<ColumnFamilyDescriptor> columnFamilyDescriptors) throws RocksDBException { final long[] cfOptsHandles = new long[columnFamilyDescriptors.size()]; final byte[][] cfNames = new byte[columnFamilyDescriptors.size()][]; for (int i = 0; i < columnFamilyDescriptors.size(); i++) { final ColumnFamilyDescriptor columnFamilyDescriptor = columnFamilyDescriptors.get(i); cfOptsHandles[i] = columnFamilyDescriptor.getOptions().nativeHandle_; cfNames[i] = columnFamilyDescriptor.getName(); } final long[] cfHandles = createColumnFamilies(nativeHandle_, cfOptsHandles, cfNames); final List<ColumnFamilyHandle> columnFamilyHandles = new ArrayList<>(cfHandles.length); for (int i = 0; i < cfHandles.length; i++) { final ColumnFamilyHandle columnFamilyHandle = new ColumnFamilyHandle(this, cfHandles[i]); columnFamilyHandles.add(columnFamilyHandle); } ownedColumnFamilyHandles.addAll(columnFamilyHandles); return columnFamilyHandles; } /** * Drops the column family specified by {@code columnFamilyHandle}. This call * only records a drop record in the manifest and prevents the column * family from flushing and compacting. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void dropColumnFamily(final ColumnFamilyHandle columnFamilyHandle) throws RocksDBException { dropColumnFamily(nativeHandle_, columnFamilyHandle.nativeHandle_); } // Bulk drop column families. This call only records drop records in the // manifest and prevents the column families from flushing and compacting. // In case of error, the request may succeed partially. User may call // ListColumnFamilies to check the result. public void dropColumnFamilies( final List<ColumnFamilyHandle> columnFamilies) throws RocksDBException { final long[] cfHandles = new long[columnFamilies.size()]; for (int i = 0; i < columnFamilies.size(); i++) { cfHandles[i] = columnFamilies.get(i).nativeHandle_; } dropColumnFamilies(nativeHandle_, cfHandles); } /** * Deletes native column family handle of given {@link ColumnFamilyHandle} Java object * and removes reference from {@link RocksDB#ownedColumnFamilyHandles}. * * @param columnFamilyHandle column family handle object. */ public void destroyColumnFamilyHandle(final ColumnFamilyHandle columnFamilyHandle) { for (int i = 0; i < ownedColumnFamilyHandles.size(); ++i) { final ColumnFamilyHandle ownedHandle = ownedColumnFamilyHandles.get(i); if (ownedHandle.equals(columnFamilyHandle)) { columnFamilyHandle.close(); ownedColumnFamilyHandles.remove(i); return; } } } /** * Set the database entry for "key" to "value". * * @param key the specified key to be inserted. * @param value the value associated with the specified key. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void put(final byte[] key, final byte[] value) throws RocksDBException { put(nativeHandle_, key, 0, key.length, value, 0, value.length); } /** * Set the database entry for "key" to "value". * * @param key The specified key to be inserted * @param offset the offset of the "key" array to be used, must be * non-negative and no larger than "key".length * @param len the length of the "key" array to be used, must be non-negative * and no larger than ("key".length - offset) * @param value the value associated with the specified key * @param vOffset the offset of the "value" array to be used, must be * non-negative and no longer than "key".length * @param vLen the length of the "value" array to be used, must be * non-negative and no larger than ("value".length - offset) * * @throws RocksDBException thrown if errors happens in underlying native * library. * @throws IndexOutOfBoundsException if an offset or length is out of bounds */ public void put(final byte[] key, final int offset, final int len, final byte[] value, final int vOffset, final int vLen) throws RocksDBException { checkBounds(offset, len, key.length); checkBounds(vOffset, vLen, value.length); put(nativeHandle_, key, offset, len, value, vOffset, vLen); } /** * Set the database entry for "key" to "value" in the specified * column family. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param key the specified key to be inserted. * @param value the value associated with the specified key. * * throws IllegalArgumentException if column family is not present * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void put(final ColumnFamilyHandle columnFamilyHandle, final byte[] key, final byte[] value) throws RocksDBException { put(nativeHandle_, key, 0, key.length, value, 0, value.length, columnFamilyHandle.nativeHandle_); } /** * Set the database entry for "key" to "value" in the specified * column family. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param key The specified key to be inserted * @param offset the offset of the "key" array to be used, must * be non-negative and no larger than "key".length * @param len the length of the "key" array to be used, must be non-negative * and no larger than ("key".length - offset) * @param value the value associated with the specified key * @param vOffset the offset of the "value" array to be used, must be * non-negative and no longer than "key".length * @param vLen the length of the "value" array to be used, must be * non-negative and no larger than ("value".length - offset) * * @throws RocksDBException thrown if errors happens in underlying native * library. * @throws IndexOutOfBoundsException if an offset or length is out of bounds */ public void put(final ColumnFamilyHandle columnFamilyHandle, final byte[] key, final int offset, final int len, final byte[] value, final int vOffset, final int vLen) throws RocksDBException { checkBounds(offset, len, key.length); checkBounds(vOffset, vLen, value.length); put(nativeHandle_, key, offset, len, value, vOffset, vLen, columnFamilyHandle.nativeHandle_); } /** * Set the database entry for "key" to "value". * * @param writeOpts {@link org.rocksdb.WriteOptions} instance. * @param key the specified key to be inserted. * @param value the value associated with the specified key. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void put(final WriteOptions writeOpts, final byte[] key, final byte[] value) throws RocksDBException { put(nativeHandle_, writeOpts.nativeHandle_, key, 0, key.length, value, 0, value.length); } /** * Set the database entry for "key" to "value". * * @param writeOpts {@link org.rocksdb.WriteOptions} instance. * @param key The specified key to be inserted * @param offset the offset of the "key" array to be used, must be * non-negative and no larger than "key".length * @param len the length of the "key" array to be used, must be non-negative * and no larger than ("key".length - offset) * @param value the value associated with the specified key * @param vOffset the offset of the "value" array to be used, must be * non-negative and no longer than "key".length * @param vLen the length of the "value" array to be used, must be * non-negative and no larger than ("value".length - offset) * * @throws RocksDBException thrown if error happens in underlying * native library. * @throws IndexOutOfBoundsException if an offset or length is out of bounds */ public void put(final WriteOptions writeOpts, final byte[] key, final int offset, final int len, final byte[] value, final int vOffset, final int vLen) throws RocksDBException { checkBounds(offset, len, key.length); checkBounds(vOffset, vLen, value.length); put(nativeHandle_, writeOpts.nativeHandle_, key, offset, len, value, vOffset, vLen); } /** * Set the database entry for "key" to "value" for the specified * column family. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param writeOpts {@link org.rocksdb.WriteOptions} instance. * @param key the specified key to be inserted. * @param value the value associated with the specified key. * * throws IllegalArgumentException if column family is not present * * @throws RocksDBException thrown if error happens in underlying * native library. * @see IllegalArgumentException */ public void put(final ColumnFamilyHandle columnFamilyHandle, final WriteOptions writeOpts, final byte[] key, final byte[] value) throws RocksDBException { put(nativeHandle_, writeOpts.nativeHandle_, key, 0, key.length, value, 0, value.length, columnFamilyHandle.nativeHandle_); } /** * Set the database entry for "key" to "value" for the specified * column family. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param writeOpts {@link org.rocksdb.WriteOptions} instance. * @param key the specified key to be inserted. Position and limit is used. * Supports direct buffer only. * @param value the value associated with the specified key. Position and limit is used. * Supports direct buffer only. * * throws IllegalArgumentException if column family is not present * * @throws RocksDBException thrown if error happens in underlying * native library. * @see IllegalArgumentException */ public void put(final ColumnFamilyHandle columnFamilyHandle, final WriteOptions writeOpts, final ByteBuffer key, final ByteBuffer value) throws RocksDBException { assert key.isDirect() && value.isDirect(); putDirect(nativeHandle_, writeOpts.nativeHandle_, key, key.position(), key.remaining(), value, value.position(), value.remaining(), columnFamilyHandle.nativeHandle_); key.position(key.limit()); value.position(value.limit()); } /** * Set the database entry for "key" to "value". * * @param writeOpts {@link org.rocksdb.WriteOptions} instance. * @param key the specified key to be inserted. Position and limit is used. * Supports direct buffer only. * @param value the value associated with the specified key. Position and limit is used. * Supports direct buffer only. * * throws IllegalArgumentException if column family is not present * * @throws RocksDBException thrown if error happens in underlying * native library. * @see IllegalArgumentException */ public void put(final WriteOptions writeOpts, final ByteBuffer key, final ByteBuffer value) throws RocksDBException { assert key.isDirect() && value.isDirect(); putDirect(nativeHandle_, writeOpts.nativeHandle_, key, key.position(), key.remaining(), value, value.position(), value.remaining(), 0); key.position(key.limit()); value.position(value.limit()); } /** * Set the database entry for "key" to "value" for the specified * column family. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param writeOpts {@link org.rocksdb.WriteOptions} instance. * @param key The specified key to be inserted * @param offset the offset of the "key" array to be used, must be * non-negative and no larger than "key".length * @param len the length of the "key" array to be used, must be non-negative * and no larger than ("key".length - offset) * @param value the value associated with the specified key * @param vOffset the offset of the "value" array to be used, must be * non-negative and no longer than "key".length * @param vLen the length of the "value" array to be used, must be * non-negative and no larger than ("value".length - offset) * * @throws RocksDBException thrown if error happens in underlying * native library. * @throws IndexOutOfBoundsException if an offset or length is out of bounds */ public void put(final ColumnFamilyHandle columnFamilyHandle, final WriteOptions writeOpts, final byte[] key, final int offset, final int len, final byte[] value, final int vOffset, final int vLen) throws RocksDBException { checkBounds(offset, len, key.length); checkBounds(vOffset, vLen, value.length); put(nativeHandle_, writeOpts.nativeHandle_, key, offset, len, value, vOffset, vLen, columnFamilyHandle.nativeHandle_); } /** * Remove the database entry (if any) for "key". Returns OK on * success, and a non-OK status on error. It is not an error if "key" * did not exist in the database. * * @param key Key to delete within database * * @throws RocksDBException thrown if error happens in underlying * native library. * * @deprecated Use {@link #delete(byte[])} */ @Deprecated public void remove(final byte[] key) throws RocksDBException { delete(key); } /** * Delete the database entry (if any) for "key". Returns OK on * success, and a non-OK status on error. It is not an error if "key" * did not exist in the database. * * @param key Key to delete within database * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void delete(final byte[] key) throws RocksDBException { delete(nativeHandle_, key, 0, key.length); } /** * Delete the database entry (if any) for "key". Returns OK on * success, and a non-OK status on error. It is not an error if "key" * did not exist in the database. * * @param key Key to delete within database * @param offset the offset of the "key" array to be used, must be * non-negative and no larger than "key".length * @param len the length of the "key" array to be used, must be * non-negative and no larger than ("key".length - offset) * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void delete(final byte[] key, final int offset, final int len) throws RocksDBException { delete(nativeHandle_, key, offset, len); } /** * Remove the database entry (if any) for "key". Returns OK on * success, and a non-OK status on error. It is not an error if "key" * did not exist in the database. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param key Key to delete within database * * @throws RocksDBException thrown if error happens in underlying * native library. * * @deprecated Use {@link #delete(ColumnFamilyHandle, byte[])} */ @Deprecated public void remove(final ColumnFamilyHandle columnFamilyHandle, final byte[] key) throws RocksDBException { delete(columnFamilyHandle, key); } /** * Delete the database entry (if any) for "key". Returns OK on * success, and a non-OK status on error. It is not an error if "key" * did not exist in the database. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param key Key to delete within database * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void delete(final ColumnFamilyHandle columnFamilyHandle, final byte[] key) throws RocksDBException { delete(nativeHandle_, key, 0, key.length, columnFamilyHandle.nativeHandle_); } /** * Delete the database entry (if any) for "key". Returns OK on * success, and a non-OK status on error. It is not an error if "key" * did not exist in the database. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param key Key to delete within database * @param offset the offset of the "key" array to be used, * must be non-negative and no larger than "key".length * @param len the length of the "key" array to be used, must be non-negative * and no larger than ("value".length - offset) * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void delete(final ColumnFamilyHandle columnFamilyHandle, final byte[] key, final int offset, final int len) throws RocksDBException { delete(nativeHandle_, key, offset, len, columnFamilyHandle.nativeHandle_); } /** * Remove the database entry (if any) for "key". Returns OK on * success, and a non-OK status on error. It is not an error if "key" * did not exist in the database. * * @param writeOpt WriteOptions to be used with delete operation * @param key Key to delete within database * * @throws RocksDBException thrown if error happens in underlying * native library. * * @deprecated Use {@link #delete(WriteOptions, byte[])} */ @Deprecated public void remove(final WriteOptions writeOpt, final byte[] key) throws RocksDBException { delete(writeOpt, key); } /** * Delete the database entry (if any) for "key". Returns OK on * success, and a non-OK status on error. It is not an error if "key" * did not exist in the database. * * @param writeOpt WriteOptions to be used with delete operation * @param key Key to delete within database * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void delete(final WriteOptions writeOpt, final byte[] key) throws RocksDBException { delete(nativeHandle_, writeOpt.nativeHandle_, key, 0, key.length); } /** * Delete the database entry (if any) for "key". Returns OK on * success, and a non-OK status on error. It is not an error if "key" * did not exist in the database. * * @param writeOpt WriteOptions to be used with delete operation * @param key Key to delete within database * @param offset the offset of the "key" array to be used, must be * non-negative and no larger than "key".length * @param len the length of the "key" array to be used, must be * non-negative and no larger than ("key".length - offset) * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void delete(final WriteOptions writeOpt, final byte[] key, final int offset, final int len) throws RocksDBException { delete(nativeHandle_, writeOpt.nativeHandle_, key, offset, len); } /** * Remove the database entry (if any) for "key". Returns OK on * success, and a non-OK status on error. It is not an error if "key" * did not exist in the database. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param writeOpt WriteOptions to be used with delete operation * @param key Key to delete within database * * @throws RocksDBException thrown if error happens in underlying * native library. * * @deprecated Use {@link #delete(ColumnFamilyHandle, WriteOptions, byte[])} */ @Deprecated public void remove(final ColumnFamilyHandle columnFamilyHandle, final WriteOptions writeOpt, final byte[] key) throws RocksDBException { delete(columnFamilyHandle, writeOpt, key); } /** * Delete the database entry (if any) for "key". Returns OK on * success, and a non-OK status on error. It is not an error if "key" * did not exist in the database. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param writeOpt WriteOptions to be used with delete operation * @param key Key to delete within database * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void delete(final ColumnFamilyHandle columnFamilyHandle, final WriteOptions writeOpt, final byte[] key) throws RocksDBException { delete(nativeHandle_, writeOpt.nativeHandle_, key, 0, key.length, columnFamilyHandle.nativeHandle_); } /** * Delete the database entry (if any) for "key". Returns OK on * success, and a non-OK status on error. It is not an error if "key" * did not exist in the database. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param writeOpt WriteOptions to be used with delete operation * @param key Key to delete within database * @param offset the offset of the "key" array to be used, must be * non-negative and no larger than "key".length * @param len the length of the "key" array to be used, must be * non-negative and no larger than ("key".length - offset) * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void delete(final ColumnFamilyHandle columnFamilyHandle, final WriteOptions writeOpt, final byte[] key, final int offset, final int len) throws RocksDBException { delete(nativeHandle_, writeOpt.nativeHandle_, key, offset, len, columnFamilyHandle.nativeHandle_); } /** * Get the value associated with the specified key within column family. * * @param opt {@link org.rocksdb.ReadOptions} instance. * @param key the key to retrieve the value. It is using position and limit. * Supports direct buffer only. * @param value the out-value to receive the retrieved value. * It is using position and limit. Limit is set according to value size. * Supports direct buffer only. * @return The size of the actual value that matches the specified * {@code key} in byte. If the return value is greater than the * length of {@code value}, then it indicates that the size of the * input buffer {@code value} is insufficient and partial result will * be returned. RocksDB.NOT_FOUND will be returned if the value not * found. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public int get(final ReadOptions opt, final ByteBuffer key, final ByteBuffer value) throws RocksDBException { assert key.isDirect() && value.isDirect(); int result = getDirect(nativeHandle_, opt.nativeHandle_, key, key.position(), key.remaining(), value, value.position(), value.remaining(), 0); if (result != NOT_FOUND) { value.limit(Math.min(value.limit(), value.position() + result)); } key.position(key.limit()); return result; } /** * Get the value associated with the specified key within column family. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param opt {@link org.rocksdb.ReadOptions} instance. * @param key the key to retrieve the value. It is using position and limit. * Supports direct buffer only. * @param value the out-value to receive the retrieved value. * It is using position and limit. Limit is set according to value size. * Supports direct buffer only. * @return The size of the actual value that matches the specified * {@code key} in byte. If the return value is greater than the * length of {@code value}, then it indicates that the size of the * input buffer {@code value} is insufficient and partial result will * be returned. RocksDB.NOT_FOUND will be returned if the value not * found. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public int get(final ColumnFamilyHandle columnFamilyHandle, final ReadOptions opt, final ByteBuffer key, final ByteBuffer value) throws RocksDBException { assert key.isDirect() && value.isDirect(); int result = getDirect(nativeHandle_, opt.nativeHandle_, key, key.position(), key.remaining(), value, value.position(), value.remaining(), columnFamilyHandle.nativeHandle_); if (result != NOT_FOUND) { value.limit(Math.min(value.limit(), value.position() + result)); } key.position(key.limit()); return result; } /** * Remove the database entry for {@code key}. Requires that the key exists * and was not overwritten. It is not an error if the key did not exist * in the database. * * If a key is overwritten (by calling {@link #put(byte[], byte[])} multiple * times), then the result of calling SingleDelete() on this key is undefined. * SingleDelete() only behaves correctly if there has been only one Put() * for this key since the previous call to SingleDelete() for this key. * * This feature is currently an experimental performance optimization * for a very specific workload. It is up to the caller to ensure that * SingleDelete is only used for a key that is not deleted using Delete() or * written using Merge(). Mixing SingleDelete operations with Deletes and * Merges can result in undefined behavior. * * @param key Key to delete within database * * @throws RocksDBException thrown if error happens in underlying * native library. */ @Experimental("Performance optimization for a very specific workload") public void singleDelete(final byte[] key) throws RocksDBException { singleDelete(nativeHandle_, key, key.length); } /** * Remove the database entry for {@code key}. Requires that the key exists * and was not overwritten. It is not an error if the key did not exist * in the database. * * If a key is overwritten (by calling {@link #put(byte[], byte[])} multiple * times), then the result of calling SingleDelete() on this key is undefined. * SingleDelete() only behaves correctly if there has been only one Put() * for this key since the previous call to SingleDelete() for this key. * * This feature is currently an experimental performance optimization * for a very specific workload. It is up to the caller to ensure that * SingleDelete is only used for a key that is not deleted using Delete() or * written using Merge(). Mixing SingleDelete operations with Deletes and * Merges can result in undefined behavior. * * @param columnFamilyHandle The column family to delete the key from * @param key Key to delete within database * * @throws RocksDBException thrown if error happens in underlying * native library. */ @Experimental("Performance optimization for a very specific workload") public void singleDelete(final ColumnFamilyHandle columnFamilyHandle, final byte[] key) throws RocksDBException { singleDelete(nativeHandle_, key, key.length, columnFamilyHandle.nativeHandle_); } /** * Remove the database entry for {@code key}. Requires that the key exists * and was not overwritten. It is not an error if the key did not exist * in the database. * * If a key is overwritten (by calling {@link #put(byte[], byte[])} multiple * times), then the result of calling SingleDelete() on this key is undefined. * SingleDelete() only behaves correctly if there has been only one Put() * for this key since the previous call to SingleDelete() for this key. * * This feature is currently an experimental performance optimization * for a very specific workload. It is up to the caller to ensure that * SingleDelete is only used for a key that is not deleted using Delete() or * written using Merge(). Mixing SingleDelete operations with Deletes and * Merges can result in undefined behavior. * * Note: consider setting {@link WriteOptions#setSync(boolean)} true. * * @param writeOpt Write options for the delete * @param key Key to delete within database * * @throws RocksDBException thrown if error happens in underlying * native library. */ @Experimental("Performance optimization for a very specific workload") public void singleDelete(final WriteOptions writeOpt, final byte[] key) throws RocksDBException { singleDelete(nativeHandle_, writeOpt.nativeHandle_, key, key.length); } /** * Remove the database entry for {@code key}. Requires that the key exists * and was not overwritten. It is not an error if the key did not exist * in the database. * * If a key is overwritten (by calling {@link #put(byte[], byte[])} multiple * times), then the result of calling SingleDelete() on this key is undefined. * SingleDelete() only behaves correctly if there has been only one Put() * for this key since the previous call to SingleDelete() for this key. * * This feature is currently an experimental performance optimization * for a very specific workload. It is up to the caller to ensure that * SingleDelete is only used for a key that is not deleted using Delete() or * written using Merge(). Mixing SingleDelete operations with Deletes and * Merges can result in undefined behavior. * * Note: consider setting {@link WriteOptions#setSync(boolean)} true. * * @param columnFamilyHandle The column family to delete the key from * @param writeOpt Write options for the delete * @param key Key to delete within database * * @throws RocksDBException thrown if error happens in underlying * native library. */ @Experimental("Performance optimization for a very specific workload") public void singleDelete(final ColumnFamilyHandle columnFamilyHandle, final WriteOptions writeOpt, final byte[] key) throws RocksDBException { singleDelete(nativeHandle_, writeOpt.nativeHandle_, key, key.length, columnFamilyHandle.nativeHandle_); } /** * Removes the database entries in the range ["beginKey", "endKey"), i.e., * including "beginKey" and excluding "endKey". a non-OK status on error. It * is not an error if no keys exist in the range ["beginKey", "endKey"). * * Delete the database entry (if any) for "key". Returns OK on success, and a * non-OK status on error. It is not an error if "key" did not exist in the * database. * * @param beginKey First key to delete within database (inclusive) * @param endKey Last key to delete within database (exclusive) * * @throws RocksDBException thrown if error happens in underlying native * library. */ public void deleteRange(final byte[] beginKey, final byte[] endKey) throws RocksDBException { deleteRange(nativeHandle_, beginKey, 0, beginKey.length, endKey, 0, endKey.length); } /** * Removes the database entries in the range ["beginKey", "endKey"), i.e., * including "beginKey" and excluding "endKey". a non-OK status on error. It * is not an error if no keys exist in the range ["beginKey", "endKey"). * * Delete the database entry (if any) for "key". Returns OK on success, and a * non-OK status on error. It is not an error if "key" did not exist in the * database. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} instance * @param beginKey First key to delete within database (inclusive) * @param endKey Last key to delete within database (exclusive) * * @throws RocksDBException thrown if error happens in underlying native * library. */ public void deleteRange(final ColumnFamilyHandle columnFamilyHandle, final byte[] beginKey, final byte[] endKey) throws RocksDBException { deleteRange(nativeHandle_, beginKey, 0, beginKey.length, endKey, 0, endKey.length, columnFamilyHandle.nativeHandle_); } /** * Removes the database entries in the range ["beginKey", "endKey"), i.e., * including "beginKey" and excluding "endKey". a non-OK status on error. It * is not an error if no keys exist in the range ["beginKey", "endKey"). * * Delete the database entry (if any) for "key". Returns OK on success, and a * non-OK status on error. It is not an error if "key" did not exist in the * database. * * @param writeOpt WriteOptions to be used with delete operation * @param beginKey First key to delete within database (inclusive) * @param endKey Last key to delete within database (exclusive) * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void deleteRange(final WriteOptions writeOpt, final byte[] beginKey, final byte[] endKey) throws RocksDBException { deleteRange(nativeHandle_, writeOpt.nativeHandle_, beginKey, 0, beginKey.length, endKey, 0, endKey.length); } /** * Removes the database entries in the range ["beginKey", "endKey"), i.e., * including "beginKey" and excluding "endKey". a non-OK status on error. It * is not an error if no keys exist in the range ["beginKey", "endKey"). * * Delete the database entry (if any) for "key". Returns OK on success, and a * non-OK status on error. It is not an error if "key" did not exist in the * database. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} instance * @param writeOpt WriteOptions to be used with delete operation * @param beginKey First key to delete within database (included) * @param endKey Last key to delete within database (excluded) * * @throws RocksDBException thrown if error happens in underlying native * library. */ public void deleteRange(final ColumnFamilyHandle columnFamilyHandle, final WriteOptions writeOpt, final byte[] beginKey, final byte[] endKey) throws RocksDBException { deleteRange(nativeHandle_, writeOpt.nativeHandle_, beginKey, 0, beginKey.length, endKey, 0, endKey.length, columnFamilyHandle.nativeHandle_); } /** * Add merge operand for key/value pair. * * @param key the specified key to be merged. * @param value the value to be merged with the current value for the * specified key. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void merge(final byte[] key, final byte[] value) throws RocksDBException { merge(nativeHandle_, key, 0, key.length, value, 0, value.length); } /** * Add merge operand for key/value pair. * * @param key the specified key to be merged. * @param offset the offset of the "key" array to be used, must be * non-negative and no larger than "key".length * @param len the length of the "key" array to be used, must be non-negative * and no larger than ("key".length - offset) * @param value the value to be merged with the current value for the * specified key. * @param vOffset the offset of the "value" array to be used, must be * non-negative and no longer than "key".length * @param vLen the length of the "value" array to be used, must be * non-negative and must be non-negative and no larger than * ("value".length - offset) * * @throws RocksDBException thrown if error happens in underlying * native library. * @throws IndexOutOfBoundsException if an offset or length is out of bounds */ public void merge(final byte[] key, int offset, int len, final byte[] value, final int vOffset, final int vLen) throws RocksDBException { checkBounds(offset, len, key.length); checkBounds(vOffset, vLen, value.length); merge(nativeHandle_, key, offset, len, value, vOffset, vLen); } /** * Add merge operand for key/value pair in a ColumnFamily. * * @param columnFamilyHandle {@link ColumnFamilyHandle} instance * @param key the specified key to be merged. * @param value the value to be merged with the current value for * the specified key. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void merge(final ColumnFamilyHandle columnFamilyHandle, final byte[] key, final byte[] value) throws RocksDBException { merge(nativeHandle_, key, 0, key.length, value, 0, value.length, columnFamilyHandle.nativeHandle_); } /** * Add merge operand for key/value pair in a ColumnFamily. * * @param columnFamilyHandle {@link ColumnFamilyHandle} instance * @param key the specified key to be merged. * @param offset the offset of the "key" array to be used, must be * non-negative and no larger than "key".length * @param len the length of the "key" array to be used, must be non-negative * and no larger than ("key".length - offset) * @param value the value to be merged with the current value for * the specified key. * @param vOffset the offset of the "value" array to be used, must be * non-negative and no longer than "key".length * @param vLen the length of the "value" array to be used, must be * must be non-negative and no larger than ("value".length - offset) * * @throws RocksDBException thrown if error happens in underlying * native library. * @throws IndexOutOfBoundsException if an offset or length is out of bounds */ public void merge(final ColumnFamilyHandle columnFamilyHandle, final byte[] key, final int offset, final int len, final byte[] value, final int vOffset, final int vLen) throws RocksDBException { checkBounds(offset, len, key.length); checkBounds(vOffset, vLen, value.length); merge(nativeHandle_, key, offset, len, value, vOffset, vLen, columnFamilyHandle.nativeHandle_); } /** * Add merge operand for key/value pair. * * @param writeOpts {@link WriteOptions} for this write. * @param key the specified key to be merged. * @param value the value to be merged with the current value for * the specified key. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void merge(final WriteOptions writeOpts, final byte[] key, final byte[] value) throws RocksDBException { merge(nativeHandle_, writeOpts.nativeHandle_, key, 0, key.length, value, 0, value.length); } /** * Add merge operand for key/value pair. * * @param writeOpts {@link WriteOptions} for this write. * @param key the specified key to be merged. * @param offset the offset of the "key" array to be used, must be * non-negative and no larger than "key".length * @param len the length of the "key" array to be used, must be non-negative * and no larger than ("value".length - offset) * @param value the value to be merged with the current value for * the specified key. * @param vOffset the offset of the "value" array to be used, must be * non-negative and no longer than "key".length * @param vLen the length of the "value" array to be used, must be * non-negative and no larger than ("value".length - offset) * * @throws RocksDBException thrown if error happens in underlying * native library. * @throws IndexOutOfBoundsException if an offset or length is out of bounds */ public void merge(final WriteOptions writeOpts, final byte[] key, final int offset, final int len, final byte[] value, final int vOffset, final int vLen) throws RocksDBException { checkBounds(offset, len, key.length); checkBounds(vOffset, vLen, value.length); merge(nativeHandle_, writeOpts.nativeHandle_, key, offset, len, value, vOffset, vLen); } /** * Delete the database entry (if any) for "key". Returns OK on * success, and a non-OK status on error. It is not an error if "key" * did not exist in the database. * * @param writeOpt WriteOptions to be used with delete operation * @param key Key to delete within database. It is using position and limit. * Supports direct buffer only. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void delete(final WriteOptions writeOpt, final ByteBuffer key) throws RocksDBException { assert key.isDirect(); deleteDirect(nativeHandle_, writeOpt.nativeHandle_, key, key.position(), key.remaining(), 0); key.position(key.limit()); } /** * Delete the database entry (if any) for "key". Returns OK on * success, and a non-OK status on error. It is not an error if "key" * did not exist in the database. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param writeOpt WriteOptions to be used with delete operation * @param key Key to delete within database. It is using position and limit. * Supports direct buffer only. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void delete(final ColumnFamilyHandle columnFamilyHandle, final WriteOptions writeOpt, final ByteBuffer key) throws RocksDBException { assert key.isDirect(); deleteDirect(nativeHandle_, writeOpt.nativeHandle_, key, key.position(), key.remaining(), columnFamilyHandle.nativeHandle_); key.position(key.limit()); } /** * Add merge operand for key/value pair. * * @param columnFamilyHandle {@link ColumnFamilyHandle} instance * @param writeOpts {@link WriteOptions} for this write. * @param key the specified key to be merged. * @param value the value to be merged with the current value for the * specified key. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void merge(final ColumnFamilyHandle columnFamilyHandle, final WriteOptions writeOpts, final byte[] key, final byte[] value) throws RocksDBException { merge(nativeHandle_, writeOpts.nativeHandle_, key, 0, key.length, value, 0, value.length, columnFamilyHandle.nativeHandle_); } /** * Add merge operand for key/value pair. * * @param columnFamilyHandle {@link ColumnFamilyHandle} instance * @param writeOpts {@link WriteOptions} for this write. * @param key the specified key to be merged. * @param offset the offset of the "key" array to be used, must be * non-negative and no larger than "key".length * @param len the length of the "key" array to be used, must be non-negative * and no larger than ("key".length - offset) * @param value the value to be merged with the current value for * the specified key. * @param vOffset the offset of the "value" array to be used, must be * non-negative and no longer than "key".length * @param vLen the length of the "value" array to be used, must be * non-negative and no larger than ("value".length - offset) * * @throws RocksDBException thrown if error happens in underlying * native library. * @throws IndexOutOfBoundsException if an offset or length is out of bounds */ public void merge( final ColumnFamilyHandle columnFamilyHandle, final WriteOptions writeOpts, final byte[] key, final int offset, final int len, final byte[] value, final int vOffset, final int vLen) throws RocksDBException { checkBounds(offset, len, key.length); checkBounds(vOffset, vLen, value.length); merge(nativeHandle_, writeOpts.nativeHandle_, key, offset, len, value, vOffset, vLen, columnFamilyHandle.nativeHandle_); } /** * Apply the specified updates to the database. * * @param writeOpts WriteOptions instance * @param updates WriteBatch instance * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void write(final WriteOptions writeOpts, final WriteBatch updates) throws RocksDBException { write0(nativeHandle_, writeOpts.nativeHandle_, updates.nativeHandle_); } /** * Apply the specified updates to the database. * * @param writeOpts WriteOptions instance * @param updates WriteBatchWithIndex instance * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void write(final WriteOptions writeOpts, final WriteBatchWithIndex updates) throws RocksDBException { write1(nativeHandle_, writeOpts.nativeHandle_, updates.nativeHandle_); } // TODO(AR) we should improve the #get() API, returning -1 (RocksDB.NOT_FOUND) is not very nice // when we could communicate better status into, also the C++ code show that -2 could be returned /** * Get the value associated with the specified key within column family* * * @param key the key to retrieve the value. * @param value the out-value to receive the retrieved value. * * @return The size of the actual value that matches the specified * {@code key} in byte. If the return value is greater than the * length of {@code value}, then it indicates that the size of the * input buffer {@code value} is insufficient and partial result will * be returned. RocksDB.NOT_FOUND will be returned if the value not * found. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public int get(final byte[] key, final byte[] value) throws RocksDBException { return get(nativeHandle_, key, 0, key.length, value, 0, value.length); } /** * Get the value associated with the specified key within column family* * * @param key the key to retrieve the value. * @param offset the offset of the "key" array to be used, must be * non-negative and no larger than "key".length * @param len the length of the "key" array to be used, must be non-negative * and no larger than ("key".length - offset) * @param value the out-value to receive the retrieved value. * @param vOffset the offset of the "value" array to be used, must be * non-negative and no longer than "value".length * @param vLen the length of the "value" array to be used, must be * non-negative and and no larger than ("value".length - offset) * * @return The size of the actual value that matches the specified * {@code key} in byte. If the return value is greater than the * length of {@code value}, then it indicates that the size of the * input buffer {@code value} is insufficient and partial result will * be returned. RocksDB.NOT_FOUND will be returned if the value not * found. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public int get(final byte[] key, final int offset, final int len, final byte[] value, final int vOffset, final int vLen) throws RocksDBException { checkBounds(offset, len, key.length); checkBounds(vOffset, vLen, value.length); return get(nativeHandle_, key, offset, len, value, vOffset, vLen); } /** * Get the value associated with the specified key within column family. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param key the key to retrieve the value. * @param value the out-value to receive the retrieved value. * @return The size of the actual value that matches the specified * {@code key} in byte. If the return value is greater than the * length of {@code value}, then it indicates that the size of the * input buffer {@code value} is insufficient and partial result will * be returned. RocksDB.NOT_FOUND will be returned if the value not * found. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public int get(final ColumnFamilyHandle columnFamilyHandle, final byte[] key, final byte[] value) throws RocksDBException, IllegalArgumentException { return get(nativeHandle_, key, 0, key.length, value, 0, value.length, columnFamilyHandle.nativeHandle_); } /** * Get the value associated with the specified key within column family. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param key the key to retrieve the value. * @param offset the offset of the "key" array to be used, must be * non-negative and no larger than "key".length * @param len the length of the "key" array to be used, must be non-negative * an no larger than ("key".length - offset) * @param value the out-value to receive the retrieved value. * @param vOffset the offset of the "value" array to be used, must be * non-negative and no longer than "key".length * @param vLen the length of the "value" array to be used, must be * non-negative and no larger than ("value".length - offset) * * @return The size of the actual value that matches the specified * {@code key} in byte. If the return value is greater than the * length of {@code value}, then it indicates that the size of the * input buffer {@code value} is insufficient and partial result will * be returned. RocksDB.NOT_FOUND will be returned if the value not * found. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public int get(final ColumnFamilyHandle columnFamilyHandle, final byte[] key, final int offset, final int len, final byte[] value, final int vOffset, final int vLen) throws RocksDBException, IllegalArgumentException { checkBounds(offset, len, key.length); checkBounds(vOffset, vLen, value.length); return get(nativeHandle_, key, offset, len, value, vOffset, vLen, columnFamilyHandle.nativeHandle_); } /** * Get the value associated with the specified key. * * @param opt {@link org.rocksdb.ReadOptions} instance. * @param key the key to retrieve the value. * @param value the out-value to receive the retrieved value. * @return The size of the actual value that matches the specified * {@code key} in byte. If the return value is greater than the * length of {@code value}, then it indicates that the size of the * input buffer {@code value} is insufficient and partial result will * be returned. RocksDB.NOT_FOUND will be returned if the value not * found. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public int get(final ReadOptions opt, final byte[] key, final byte[] value) throws RocksDBException { return get(nativeHandle_, opt.nativeHandle_, key, 0, key.length, value, 0, value.length); } /** * Get the value associated with the specified key. * * @param opt {@link org.rocksdb.ReadOptions} instance. * @param key the key to retrieve the value. * @param offset the offset of the "key" array to be used, must be * non-negative and no larger than "key".length * @param len the length of the "key" array to be used, must be non-negative * and no larger than ("key".length - offset) * @param value the out-value to receive the retrieved value. * @param vOffset the offset of the "value" array to be used, must be * non-negative and no longer than "key".length * @param vLen the length of the "value" array to be used, must be * non-negative and no larger than ("value".length - offset) * @return The size of the actual value that matches the specified * {@code key} in byte. If the return value is greater than the * length of {@code value}, then it indicates that the size of the * input buffer {@code value} is insufficient and partial result will * be returned. RocksDB.NOT_FOUND will be returned if the value not * found. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public int get(final ReadOptions opt, final byte[] key, final int offset, final int len, final byte[] value, final int vOffset, final int vLen) throws RocksDBException { checkBounds(offset, len, key.length); checkBounds(vOffset, vLen, value.length); return get(nativeHandle_, opt.nativeHandle_, key, offset, len, value, vOffset, vLen); } /** * Get the value associated with the specified key within column family. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param opt {@link org.rocksdb.ReadOptions} instance. * @param key the key to retrieve the value. * @param value the out-value to receive the retrieved value. * @return The size of the actual value that matches the specified * {@code key} in byte. If the return value is greater than the * length of {@code value}, then it indicates that the size of the * input buffer {@code value} is insufficient and partial result will * be returned. RocksDB.NOT_FOUND will be returned if the value not * found. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public int get(final ColumnFamilyHandle columnFamilyHandle, final ReadOptions opt, final byte[] key, final byte[] value) throws RocksDBException { return get(nativeHandle_, opt.nativeHandle_, key, 0, key.length, value, 0, value.length, columnFamilyHandle.nativeHandle_); } /** * Get the value associated with the specified key within column family. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param opt {@link org.rocksdb.ReadOptions} instance. * @param key the key to retrieve the value. * @param offset the offset of the "key" array to be used, must be * non-negative and no larger than "key".length * @param len the length of the "key" array to be used, must be * non-negative and and no larger than ("key".length - offset) * @param value the out-value to receive the retrieved value. * @param vOffset the offset of the "value" array to be used, must be * non-negative and no longer than "key".length * @param vLen the length of the "value" array to be used, and must be * non-negative and no larger than ("value".length - offset) * @return The size of the actual value that matches the specified * {@code key} in byte. If the return value is greater than the * length of {@code value}, then it indicates that the size of the * input buffer {@code value} is insufficient and partial result will * be returned. RocksDB.NOT_FOUND will be returned if the value not * found. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public int get(final ColumnFamilyHandle columnFamilyHandle, final ReadOptions opt, final byte[] key, final int offset, final int len, final byte[] value, final int vOffset, final int vLen) throws RocksDBException { checkBounds(offset, len, key.length); checkBounds(vOffset, vLen, value.length); return get(nativeHandle_, opt.nativeHandle_, key, offset, len, value, vOffset, vLen, columnFamilyHandle.nativeHandle_); } /** * The simplified version of get which returns a new byte array storing * the value associated with the specified input key if any. null will be * returned if the specified key is not found. * * @param key the key retrieve the value. * @return a byte array storing the value associated with the input key if * any. null if it does not find the specified key. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public byte[] get(final byte[] key) throws RocksDBException { return get(nativeHandle_, key, 0, key.length); } /** * The simplified version of get which returns a new byte array storing * the value associated with the specified input key if any. null will be * returned if the specified key is not found. * * @param key the key retrieve the value. * @param offset the offset of the "key" array to be used, must be * non-negative and no larger than "key".length * @param len the length of the "key" array to be used, must be non-negative * and no larger than ("key".length - offset) * @return a byte array storing the value associated with the input key if * any. null if it does not find the specified key. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public byte[] get(final byte[] key, final int offset, final int len) throws RocksDBException { checkBounds(offset, len, key.length); return get(nativeHandle_, key, offset, len); } /** * The simplified version of get which returns a new byte array storing * the value associated with the specified input key if any. null will be * returned if the specified key is not found. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param key the key retrieve the value. * @return a byte array storing the value associated with the input key if * any. null if it does not find the specified key. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public byte[] get(final ColumnFamilyHandle columnFamilyHandle, final byte[] key) throws RocksDBException { return get(nativeHandle_, key, 0, key.length, columnFamilyHandle.nativeHandle_); } /** * The simplified version of get which returns a new byte array storing * the value associated with the specified input key if any. null will be * returned if the specified key is not found. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param key the key retrieve the value. * @param offset the offset of the "key" array to be used, must be * non-negative and no larger than "key".length * @param len the length of the "key" array to be used, must be non-negative * and no larger than ("key".length - offset) * @return a byte array storing the value associated with the input key if * any. null if it does not find the specified key. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public byte[] get(final ColumnFamilyHandle columnFamilyHandle, final byte[] key, final int offset, final int len) throws RocksDBException { checkBounds(offset, len, key.length); return get(nativeHandle_, key, offset, len, columnFamilyHandle.nativeHandle_); } /** * The simplified version of get which returns a new byte array storing * the value associated with the specified input key if any. null will be * returned if the specified key is not found. * * @param key the key retrieve the value. * @param opt Read options. * @return a byte array storing the value associated with the input key if * any. null if it does not find the specified key. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public byte[] get(final ReadOptions opt, final byte[] key) throws RocksDBException { return get(nativeHandle_, opt.nativeHandle_, key, 0, key.length); } /** * The simplified version of get which returns a new byte array storing * the value associated with the specified input key if any. null will be * returned if the specified key is not found. * * @param key the key retrieve the value. * @param offset the offset of the "key" array to be used, must be * non-negative and no larger than "key".length * @param len the length of the "key" array to be used, must be non-negative * and no larger than ("key".length - offset) * @param opt Read options. * @return a byte array storing the value associated with the input key if * any. null if it does not find the specified key. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public byte[] get(final ReadOptions opt, final byte[] key, final int offset, final int len) throws RocksDBException { checkBounds(offset, len, key.length); return get(nativeHandle_, opt.nativeHandle_, key, offset, len); } /** * The simplified version of get which returns a new byte array storing * the value associated with the specified input key if any. null will be * returned if the specified key is not found. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param key the key retrieve the value. * @param opt Read options. * @return a byte array storing the value associated with the input key if * any. null if it does not find the specified key. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public byte[] get(final ColumnFamilyHandle columnFamilyHandle, final ReadOptions opt, final byte[] key) throws RocksDBException { return get(nativeHandle_, opt.nativeHandle_, key, 0, key.length, columnFamilyHandle.nativeHandle_); } /** * The simplified version of get which returns a new byte array storing * the value associated with the specified input key if any. null will be * returned if the specified key is not found. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param key the key retrieve the value. * @param offset the offset of the "key" array to be used, must be * non-negative and no larger than "key".length * @param len the length of the "key" array to be used, must be non-negative * and no larger than ("key".length - offset) * @param opt Read options. * @return a byte array storing the value associated with the input key if * any. null if it does not find the specified key. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public byte[] get(final ColumnFamilyHandle columnFamilyHandle, final ReadOptions opt, final byte[] key, final int offset, final int len) throws RocksDBException { checkBounds(offset, len, key.length); return get(nativeHandle_, opt.nativeHandle_, key, offset, len, columnFamilyHandle.nativeHandle_); } /** * Returns a map of keys for which values were found in DB. * * @param keys List of keys for which values need to be retrieved. * @return Map where key of map is the key passed by user and value for map * entry is the corresponding value in DB. * * @throws RocksDBException thrown if error happens in underlying * native library. * * @deprecated Consider {@link #multiGetAsList(List)} instead. */ @Deprecated public Map<byte[], byte[]> multiGet(final List<byte[]> keys) throws RocksDBException { assert(keys.size() != 0); final byte[][] keysArray = keys.toArray(new byte[0][]); final int keyOffsets[] = new int[keysArray.length]; final int keyLengths[] = new int[keysArray.length]; for(int i = 0; i < keyLengths.length; i++) { keyLengths[i] = keysArray[i].length; } final byte[][] values = multiGet(nativeHandle_, keysArray, keyOffsets, keyLengths); final Map<byte[], byte[]> keyValueMap = new HashMap<>(computeCapacityHint(values.length)); for(int i = 0; i < values.length; i++) { if(values[i] == null) { continue; } keyValueMap.put(keys.get(i), values[i]); } return keyValueMap; } /** * Returns a map of keys for which values were found in DB. * <p> * Note: Every key needs to have a related column family name in * {@code columnFamilyHandleList}. * </p> * * @param columnFamilyHandleList {@link java.util.List} containing * {@link org.rocksdb.ColumnFamilyHandle} instances. * @param keys List of keys for which values need to be retrieved. * @return Map where key of map is the key passed by user and value for map * entry is the corresponding value in DB. * * @throws RocksDBException thrown if error happens in underlying * native library. * @throws IllegalArgumentException thrown if the size of passed keys is not * equal to the amount of passed column family handles. * * @deprecated Consider {@link #multiGetAsList(List, List)} instead. */ @Deprecated public Map<byte[], byte[]> multiGet( final List<ColumnFamilyHandle> columnFamilyHandleList, final List<byte[]> keys) throws RocksDBException, IllegalArgumentException { assert(keys.size() != 0); // Check if key size equals cfList size. If not a exception must be // thrown. If not a Segmentation fault happens. if (keys.size() != columnFamilyHandleList.size()) { throw new IllegalArgumentException( "For each key there must be a ColumnFamilyHandle."); } final long[] cfHandles = new long[columnFamilyHandleList.size()]; for (int i = 0; i < columnFamilyHandleList.size(); i++) { cfHandles[i] = columnFamilyHandleList.get(i).nativeHandle_; } final byte[][] keysArray = keys.toArray(new byte[0][]); final int keyOffsets[] = new int[keysArray.length]; final int keyLengths[] = new int[keysArray.length]; for(int i = 0; i < keyLengths.length; i++) { keyLengths[i] = keysArray[i].length; } final byte[][] values = multiGet(nativeHandle_, keysArray, keyOffsets, keyLengths, cfHandles); final Map<byte[], byte[]> keyValueMap = new HashMap<>(computeCapacityHint(values.length)); for(int i = 0; i < values.length; i++) { if (values[i] == null) { continue; } keyValueMap.put(keys.get(i), values[i]); } return keyValueMap; } /** * Returns a map of keys for which values were found in DB. * * @param opt Read options. * @param keys of keys for which values need to be retrieved. * @return Map where key of map is the key passed by user and value for map * entry is the corresponding value in DB. * * @throws RocksDBException thrown if error happens in underlying * native library. * * @deprecated Consider {@link #multiGetAsList(ReadOptions, List)} instead. */ @Deprecated public Map<byte[], byte[]> multiGet(final ReadOptions opt, final List<byte[]> keys) throws RocksDBException { assert(keys.size() != 0); final byte[][] keysArray = keys.toArray(new byte[0][]); final int keyOffsets[] = new int[keysArray.length]; final int keyLengths[] = new int[keysArray.length]; for(int i = 0; i < keyLengths.length; i++) { keyLengths[i] = keysArray[i].length; } final byte[][] values = multiGet(nativeHandle_, opt.nativeHandle_, keysArray, keyOffsets, keyLengths); final Map<byte[], byte[]> keyValueMap = new HashMap<>(computeCapacityHint(values.length)); for(int i = 0; i < values.length; i++) { if(values[i] == null) { continue; } keyValueMap.put(keys.get(i), values[i]); } return keyValueMap; } /** * Returns a map of keys for which values were found in DB. * <p> * Note: Every key needs to have a related column family name in * {@code columnFamilyHandleList}. * </p> * * @param opt Read options. * @param columnFamilyHandleList {@link java.util.List} containing * {@link org.rocksdb.ColumnFamilyHandle} instances. * @param keys of keys for which values need to be retrieved. * @return Map where key of map is the key passed by user and value for map * entry is the corresponding value in DB. * * @throws RocksDBException thrown if error happens in underlying * native library. * @throws IllegalArgumentException thrown if the size of passed keys is not * equal to the amount of passed column family handles. * * @deprecated Consider {@link #multiGetAsList(ReadOptions, List, List)} * instead. */ @Deprecated public Map<byte[], byte[]> multiGet(final ReadOptions opt, final List<ColumnFamilyHandle> columnFamilyHandleList, final List<byte[]> keys) throws RocksDBException { assert(keys.size() != 0); // Check if key size equals cfList size. If not a exception must be // thrown. If not a Segmentation fault happens. if (keys.size()!=columnFamilyHandleList.size()){ throw new IllegalArgumentException( "For each key there must be a ColumnFamilyHandle."); } final long[] cfHandles = new long[columnFamilyHandleList.size()]; for (int i = 0; i < columnFamilyHandleList.size(); i++) { cfHandles[i] = columnFamilyHandleList.get(i).nativeHandle_; } final byte[][] keysArray = keys.toArray(new byte[0][]); final int keyOffsets[] = new int[keysArray.length]; final int keyLengths[] = new int[keysArray.length]; for(int i = 0; i < keyLengths.length; i++) { keyLengths[i] = keysArray[i].length; } final byte[][] values = multiGet(nativeHandle_, opt.nativeHandle_, keysArray, keyOffsets, keyLengths, cfHandles); final Map<byte[], byte[]> keyValueMap = new HashMap<>(computeCapacityHint(values.length)); for(int i = 0; i < values.length; i++) { if(values[i] == null) { continue; } keyValueMap.put(keys.get(i), values[i]); } return keyValueMap; } /** * Takes a list of keys, and returns a list of values for the given list of * keys. List will contain null for keys which could not be found. * * @param keys List of keys for which values need to be retrieved. * @return List of values for the given list of keys. List will contain * null for keys which could not be found. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public List<byte[]> multiGetAsList(final List<byte[]> keys) throws RocksDBException { assert(keys.size() != 0); final byte[][] keysArray = keys.toArray(new byte[keys.size()][]); final int keyOffsets[] = new int[keysArray.length]; final int keyLengths[] = new int[keysArray.length]; for(int i = 0; i < keyLengths.length; i++) { keyLengths[i] = keysArray[i].length; } return Arrays.asList(multiGet(nativeHandle_, keysArray, keyOffsets, keyLengths)); } /** * Returns a list of values for the given list of keys. List will contain * null for keys which could not be found. * <p> * Note: Every key needs to have a related column family name in * {@code columnFamilyHandleList}. * </p> * * @param columnFamilyHandleList {@link java.util.List} containing * {@link org.rocksdb.ColumnFamilyHandle} instances. * @param keys List of keys for which values need to be retrieved. * @return List of values for the given list of keys. List will contain * null for keys which could not be found. * * @throws RocksDBException thrown if error happens in underlying * native library. * @throws IllegalArgumentException thrown if the size of passed keys is not * equal to the amount of passed column family handles. */ public List<byte[]> multiGetAsList( final List<ColumnFamilyHandle> columnFamilyHandleList, final List<byte[]> keys) throws RocksDBException, IllegalArgumentException { assert(keys.size() != 0); // Check if key size equals cfList size. If not a exception must be // thrown. If not a Segmentation fault happens. if (keys.size() != columnFamilyHandleList.size()) { throw new IllegalArgumentException( "For each key there must be a ColumnFamilyHandle."); } final long[] cfHandles = new long[columnFamilyHandleList.size()]; for (int i = 0; i < columnFamilyHandleList.size(); i++) { cfHandles[i] = columnFamilyHandleList.get(i).nativeHandle_; } final byte[][] keysArray = keys.toArray(new byte[keys.size()][]); final int keyOffsets[] = new int[keysArray.length]; final int keyLengths[] = new int[keysArray.length]; for(int i = 0; i < keyLengths.length; i++) { keyLengths[i] = keysArray[i].length; } return Arrays.asList(multiGet(nativeHandle_, keysArray, keyOffsets, keyLengths, cfHandles)); } /** * Returns a list of values for the given list of keys. List will contain * null for keys which could not be found. * * @param opt Read options. * @param keys of keys for which values need to be retrieved. * @return List of values for the given list of keys. List will contain * null for keys which could not be found. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public List<byte[]> multiGetAsList(final ReadOptions opt, final List<byte[]> keys) throws RocksDBException { assert(keys.size() != 0); final byte[][] keysArray = keys.toArray(new byte[keys.size()][]); final int keyOffsets[] = new int[keysArray.length]; final int keyLengths[] = new int[keysArray.length]; for(int i = 0; i < keyLengths.length; i++) { keyLengths[i] = keysArray[i].length; } return Arrays.asList(multiGet(nativeHandle_, opt.nativeHandle_, keysArray, keyOffsets, keyLengths)); } /** * Returns a list of values for the given list of keys. List will contain * null for keys which could not be found. * <p> * Note: Every key needs to have a related column family name in * {@code columnFamilyHandleList}. * </p> * * @param opt Read options. * @param columnFamilyHandleList {@link java.util.List} containing * {@link org.rocksdb.ColumnFamilyHandle} instances. * @param keys of keys for which values need to be retrieved. * @return List of values for the given list of keys. List will contain * null for keys which could not be found. * * @throws RocksDBException thrown if error happens in underlying * native library. * @throws IllegalArgumentException thrown if the size of passed keys is not * equal to the amount of passed column family handles. */ public List<byte[]> multiGetAsList(final ReadOptions opt, final List<ColumnFamilyHandle> columnFamilyHandleList, final List<byte[]> keys) throws RocksDBException { assert(keys.size() != 0); // Check if key size equals cfList size. If not a exception must be // thrown. If not a Segmentation fault happens. if (keys.size()!=columnFamilyHandleList.size()){ throw new IllegalArgumentException( "For each key there must be a ColumnFamilyHandle."); } final long[] cfHandles = new long[columnFamilyHandleList.size()]; for (int i = 0; i < columnFamilyHandleList.size(); i++) { cfHandles[i] = columnFamilyHandleList.get(i).nativeHandle_; } final byte[][] keysArray = keys.toArray(new byte[keys.size()][]); final int keyOffsets[] = new int[keysArray.length]; final int keyLengths[] = new int[keysArray.length]; for(int i = 0; i < keyLengths.length; i++) { keyLengths[i] = keysArray[i].length; } return Arrays.asList(multiGet(nativeHandle_, opt.nativeHandle_, keysArray, keyOffsets, keyLengths, cfHandles)); } /** * If the key definitely does not exist in the database, then this method * returns null, else it returns an instance of KeyMayExistResult * * If the caller wants to obtain value when the key * is found in memory, then {@code valueHolder} must be set. * * This check is potentially lighter-weight than invoking * {@link #get(byte[])}. One way to make this lighter weight is to avoid * doing any IOs. * * @param key byte array of a key to search for * @param valueHolder non-null to retrieve the value if it is found, or null * if the value is not needed. If non-null, upon return of the function, * the {@code value} will be set if it could be retrieved. * * @return false if the key definitely does not exist in the database, * otherwise true. */ public boolean keyMayExist(final byte[] key, /* @Nullable */ final Holder<byte[]> valueHolder) { return keyMayExist(key, 0, key.length, valueHolder); } /** * If the key definitely does not exist in the database, then this method * returns null, else it returns an instance of KeyMayExistResult * * If the caller wants to obtain value when the key * is found in memory, then {@code valueHolder} must be set. * * This check is potentially lighter-weight than invoking * {@link #get(byte[], int, int)}. One way to make this lighter weight is to * avoid doing any IOs. * * @param key byte array of a key to search for * @param offset the offset of the "key" array to be used, must be * non-negative and no larger than "key".length * @param len the length of the "key" array to be used, must be non-negative * and no larger than "key".length * @param valueHolder non-null to retrieve the value if it is found, or null * if the value is not needed. If non-null, upon return of the function, * the {@code value} will be set if it could be retrieved. * * @return false if the key definitely does not exist in the database, * otherwise true. */ public boolean keyMayExist(final byte[] key, final int offset, final int len, /* @Nullable */ final Holder<byte[]> valueHolder) { return keyMayExist((ColumnFamilyHandle)null, key, offset, len, valueHolder); } /** * If the key definitely does not exist in the database, then this method * returns null, else it returns an instance of KeyMayExistResult * * If the caller wants to obtain value when the key * is found in memory, then {@code valueHolder} must be set. * * This check is potentially lighter-weight than invoking * {@link #get(ColumnFamilyHandle,byte[])}. One way to make this lighter * weight is to avoid doing any IOs. * * @param columnFamilyHandle {@link ColumnFamilyHandle} instance * @param key byte array of a key to search for * @param valueHolder non-null to retrieve the value if it is found, or null * if the value is not needed. If non-null, upon return of the function, * the {@code value} will be set if it could be retrieved. * * @return false if the key definitely does not exist in the database, * otherwise true. */ public boolean keyMayExist( final ColumnFamilyHandle columnFamilyHandle, final byte[] key, /* @Nullable */ final Holder<byte[]> valueHolder) { return keyMayExist(columnFamilyHandle, key, 0, key.length, valueHolder); } /** * If the key definitely does not exist in the database, then this method * returns null, else it returns an instance of KeyMayExistResult * * If the caller wants to obtain value when the key * is found in memory, then {@code valueHolder} must be set. * * This check is potentially lighter-weight than invoking * {@link #get(ColumnFamilyHandle, byte[], int, int)}. One way to make this * lighter weight is to avoid doing any IOs. * * @param columnFamilyHandle {@link ColumnFamilyHandle} instance * @param key byte array of a key to search for * @param offset the offset of the "key" array to be used, must be * non-negative and no larger than "key".length * @param len the length of the "key" array to be used, must be non-negative * and no larger than "key".length * @param valueHolder non-null to retrieve the value if it is found, or null * if the value is not needed. If non-null, upon return of the function, * the {@code value} will be set if it could be retrieved. * * @return false if the key definitely does not exist in the database, * otherwise true. */ public boolean keyMayExist( final ColumnFamilyHandle columnFamilyHandle, final byte[] key, int offset, int len, /* @Nullable */ final Holder<byte[]> valueHolder) { return keyMayExist(columnFamilyHandle, null, key, offset, len, valueHolder); } /** * If the key definitely does not exist in the database, then this method * returns null, else it returns an instance of KeyMayExistResult * * If the caller wants to obtain value when the key * is found in memory, then {@code valueHolder} must be set. * * This check is potentially lighter-weight than invoking * {@link #get(ReadOptions, byte[])}. One way to make this * lighter weight is to avoid doing any IOs. * * @param readOptions {@link ReadOptions} instance * @param key byte array of a key to search for * @param valueHolder non-null to retrieve the value if it is found, or null * if the value is not needed. If non-null, upon return of the function, * the {@code value} will be set if it could be retrieved. * * @return false if the key definitely does not exist in the database, * otherwise true. */ public boolean keyMayExist( final ReadOptions readOptions, final byte[] key, /* @Nullable */ final Holder<byte[]> valueHolder) { return keyMayExist(readOptions, key, 0, key.length, valueHolder); } /** * If the key definitely does not exist in the database, then this method * returns null, else it returns an instance of KeyMayExistResult * * If the caller wants to obtain value when the key * is found in memory, then {@code valueHolder} must be set. * * This check is potentially lighter-weight than invoking * {@link #get(ReadOptions, byte[], int, int)}. One way to make this * lighter weight is to avoid doing any IOs. * * @param readOptions {@link ReadOptions} instance * @param key byte array of a key to search for * @param offset the offset of the "key" array to be used, must be * non-negative and no larger than "key".length * @param len the length of the "key" array to be used, must be non-negative * and no larger than "key".length * @param valueHolder non-null to retrieve the value if it is found, or null * if the value is not needed. If non-null, upon return of the function, * the {@code value} will be set if it could be retrieved. * * @return false if the key definitely does not exist in the database, * otherwise true. */ public boolean keyMayExist( final ReadOptions readOptions, final byte[] key, final int offset, final int len, /* @Nullable */ final Holder<byte[]> valueHolder) { return keyMayExist(null, readOptions, key, offset, len, valueHolder); } /** * If the key definitely does not exist in the database, then this method * returns null, else it returns an instance of KeyMayExistResult * * If the caller wants to obtain value when the key * is found in memory, then {@code valueHolder} must be set. * * This check is potentially lighter-weight than invoking * {@link #get(ColumnFamilyHandle, ReadOptions, byte[])}. One way to make this * lighter weight is to avoid doing any IOs. * * @param columnFamilyHandle {@link ColumnFamilyHandle} instance * @param readOptions {@link ReadOptions} instance * @param key byte array of a key to search for * @param valueHolder non-null to retrieve the value if it is found, or null * if the value is not needed. If non-null, upon return of the function, * the {@code value} will be set if it could be retrieved. * * @return false if the key definitely does not exist in the database, * otherwise true. */ public boolean keyMayExist( final ColumnFamilyHandle columnFamilyHandle, final ReadOptions readOptions, final byte[] key, /* @Nullable */ final Holder<byte[]> valueHolder) { return keyMayExist(columnFamilyHandle, readOptions, key, 0, key.length, valueHolder); } /** * If the key definitely does not exist in the database, then this method * returns null, else it returns an instance of KeyMayExistResult * * If the caller wants to obtain value when the key * is found in memory, then {@code valueHolder} must be set. * * This check is potentially lighter-weight than invoking * {@link #get(ColumnFamilyHandle, ReadOptions, byte[], int, int)}. * One way to make this lighter weight is to avoid doing any IOs. * * @param columnFamilyHandle {@link ColumnFamilyHandle} instance * @param readOptions {@link ReadOptions} instance * @param key byte array of a key to search for * @param offset the offset of the "key" array to be used, must be * non-negative and no larger than "key".length * @param len the length of the "key" array to be used, must be non-negative * and no larger than "key".length * @param valueHolder non-null to retrieve the value if it is found, or null * if the value is not needed. If non-null, upon return of the function, * the {@code value} will be set if it could be retrieved. * * @return false if the key definitely does not exist in the database, * otherwise true. */ public boolean keyMayExist( final ColumnFamilyHandle columnFamilyHandle, final ReadOptions readOptions, final byte[] key, final int offset, final int len, /* @Nullable */ final Holder<byte[]> valueHolder) { checkBounds(offset, len, key.length); if (valueHolder == null) { return keyMayExist(nativeHandle_, columnFamilyHandle == null ? 0 : columnFamilyHandle.nativeHandle_, readOptions == null ? 0 : readOptions.nativeHandle_, key, offset, len); } else { final byte[][] result = keyMayExistFoundValue( nativeHandle_, columnFamilyHandle == null ? 0 : columnFamilyHandle.nativeHandle_, readOptions == null ? 0 : readOptions.nativeHandle_, key, offset, len); if (result[0][0] == 0x0) { valueHolder.setValue(null); return false; } else if (result[0][0] == 0x1) { valueHolder.setValue(null); return true; } else { valueHolder.setValue(result[1]); return true; } } } /** * <p>Return a heap-allocated iterator over the contents of the * database. The result of newIterator() is initially invalid * (caller must call one of the Seek methods on the iterator * before using it).</p> * * <p>Caller should close the iterator when it is no longer needed. * The returned iterator should be closed before this db is closed. * </p> * * @return instance of iterator object. */ public RocksIterator newIterator() { return new RocksIterator(this, iterator(nativeHandle_)); } /** * <p>Return a heap-allocated iterator over the contents of the * database. The result of newIterator() is initially invalid * (caller must call one of the Seek methods on the iterator * before using it).</p> * * <p>Caller should close the iterator when it is no longer needed. * The returned iterator should be closed before this db is closed. * </p> * * @param readOptions {@link ReadOptions} instance. * @return instance of iterator object. */ public RocksIterator newIterator(final ReadOptions readOptions) { return new RocksIterator(this, iterator(nativeHandle_, readOptions.nativeHandle_)); } /** * <p>Return a heap-allocated iterator over the contents of a * ColumnFamily. The result of newIterator() is initially invalid * (caller must call one of the Seek methods on the iterator * before using it).</p> * * <p>Caller should close the iterator when it is no longer needed. * The returned iterator should be closed before this db is closed. * </p> * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @return instance of iterator object. */ public RocksIterator newIterator( final ColumnFamilyHandle columnFamilyHandle) { return new RocksIterator(this, iteratorCF(nativeHandle_, columnFamilyHandle.nativeHandle_)); } /** * <p>Return a heap-allocated iterator over the contents of a * ColumnFamily. The result of newIterator() is initially invalid * (caller must call one of the Seek methods on the iterator * before using it).</p> * * <p>Caller should close the iterator when it is no longer needed. * The returned iterator should be closed before this db is closed. * </p> * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param readOptions {@link ReadOptions} instance. * @return instance of iterator object. */ public RocksIterator newIterator(final ColumnFamilyHandle columnFamilyHandle, final ReadOptions readOptions) { return new RocksIterator(this, iteratorCF(nativeHandle_, columnFamilyHandle.nativeHandle_, readOptions.nativeHandle_)); } /** * Returns iterators from a consistent database state across multiple * column families. Iterators are heap allocated and need to be deleted * before the db is deleted * * @param columnFamilyHandleList {@link java.util.List} containing * {@link org.rocksdb.ColumnFamilyHandle} instances. * @return {@link java.util.List} containing {@link org.rocksdb.RocksIterator} * instances * * @throws RocksDBException thrown if error happens in underlying * native library. */ public List<RocksIterator> newIterators( final List<ColumnFamilyHandle> columnFamilyHandleList) throws RocksDBException { return newIterators(columnFamilyHandleList, new ReadOptions()); } /** * Returns iterators from a consistent database state across multiple * column families. Iterators are heap allocated and need to be deleted * before the db is deleted * * @param columnFamilyHandleList {@link java.util.List} containing * {@link org.rocksdb.ColumnFamilyHandle} instances. * @param readOptions {@link ReadOptions} instance. * @return {@link java.util.List} containing {@link org.rocksdb.RocksIterator} * instances * * @throws RocksDBException thrown if error happens in underlying * native library. */ public List<RocksIterator> newIterators( final List<ColumnFamilyHandle> columnFamilyHandleList, final ReadOptions readOptions) throws RocksDBException { final long[] columnFamilyHandles = new long[columnFamilyHandleList.size()]; for (int i = 0; i < columnFamilyHandleList.size(); i++) { columnFamilyHandles[i] = columnFamilyHandleList.get(i).nativeHandle_; } final long[] iteratorRefs = iterators(nativeHandle_, columnFamilyHandles, readOptions.nativeHandle_); final List<RocksIterator> iterators = new ArrayList<>( columnFamilyHandleList.size()); for (int i=0; i<columnFamilyHandleList.size(); i++){ iterators.add(new RocksIterator(this, iteratorRefs[i])); } return iterators; } /** * <p>Return a handle to the current DB state. Iterators created with * this handle will all observe a stable snapshot of the current DB * state. The caller must call ReleaseSnapshot(result) when the * snapshot is no longer needed.</p> * * <p>nullptr will be returned if the DB fails to take a snapshot or does * not support snapshot.</p> * * @return Snapshot {@link Snapshot} instance */ public Snapshot getSnapshot() { long snapshotHandle = getSnapshot(nativeHandle_); if (snapshotHandle != 0) { return new Snapshot(snapshotHandle); } return null; } /** * Release a previously acquired snapshot. * * The caller must not use "snapshot" after this call. * * @param snapshot {@link Snapshot} instance */ public void releaseSnapshot(final Snapshot snapshot) { if (snapshot != null) { releaseSnapshot(nativeHandle_, snapshot.nativeHandle_); } } /** * DB implements can export properties about their state * via this method on a per column family level. * * <p>If {@code property} is a valid property understood by this DB * implementation, fills {@code value} with its current value and * returns true. Otherwise returns false.</p> * * <p>Valid property names include: * <ul> * <li>"rocksdb.num-files-at-level&lt;N&gt;" - return the number of files at * level &lt;N&gt;, where &lt;N&gt; is an ASCII representation of a level * number (e.g. "0").</li> * <li>"rocksdb.stats" - returns a multi-line string that describes statistics * about the internal operation of the DB.</li> * <li>"rocksdb.sstables" - returns a multi-line string that describes all * of the sstables that make up the db contents.</li> * </ul> * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance, or null for the default column family. * @param property to be fetched. See above for examples * @return property value * * @throws RocksDBException thrown if error happens in underlying * native library. */ public String getProperty( /* @Nullable */ final ColumnFamilyHandle columnFamilyHandle, final String property) throws RocksDBException { return getProperty(nativeHandle_, columnFamilyHandle == null ? 0 : columnFamilyHandle.nativeHandle_, property, property.length()); } /** * DB implementations can export properties about their state * via this method. If "property" is a valid property understood by this * DB implementation, fills "*value" with its current value and returns * true. Otherwise returns false. * * <p>Valid property names include: * <ul> * <li>"rocksdb.num-files-at-level&lt;N&gt;" - return the number of files at * level &lt;N&gt;, where &lt;N&gt; is an ASCII representation of a level * number (e.g. "0").</li> * <li>"rocksdb.stats" - returns a multi-line string that describes statistics * about the internal operation of the DB.</li> * <li>"rocksdb.sstables" - returns a multi-line string that describes all * of the sstables that make up the db contents.</li> *</ul> * * @param property to be fetched. See above for examples * @return property value * * @throws RocksDBException thrown if error happens in underlying * native library. */ public String getProperty(final String property) throws RocksDBException { return getProperty(null, property); } /** * Gets a property map. * * @param property to be fetched. * * @return the property map * * @throws RocksDBException if an error happens in the underlying native code. */ public Map<String, String> getMapProperty(final String property) throws RocksDBException { return getMapProperty(null, property); } /** * Gets a property map. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance, or null for the default column family. * @param property to be fetched. * * @return the property map * * @throws RocksDBException if an error happens in the underlying native code. */ public Map<String, String> getMapProperty( /* @Nullable */ final ColumnFamilyHandle columnFamilyHandle, final String property) throws RocksDBException { return getMapProperty(nativeHandle_, columnFamilyHandle == null ? 0 : columnFamilyHandle.nativeHandle_, property, property.length()); } /** * <p> Similar to GetProperty(), but only works for a subset of properties * whose return value is a numerical value. Return the value as long.</p> * * <p><strong>Note</strong>: As the returned property is of type * {@code uint64_t} on C++ side the returning value can be negative * because Java supports in Java 7 only signed long values.</p> * * <p><strong>Java 7</strong>: To mitigate the problem of the non * existent unsigned long tpye, values should be encapsulated using * {@link java.math.BigInteger} to reflect the correct value. The correct * behavior is guaranteed if {@code 2^64} is added to negative values.</p> * * <p><strong>Java 8</strong>: In Java 8 the value should be treated as * unsigned long using provided methods of type {@link Long}.</p> * * @param property to be fetched. * * @return numerical property value. * * @throws RocksDBException if an error happens in the underlying native code. */ public long getLongProperty(final String property) throws RocksDBException { return getLongProperty(null, property); } /** * <p> Similar to GetProperty(), but only works for a subset of properties * whose return value is a numerical value. Return the value as long.</p> * * <p><strong>Note</strong>: As the returned property is of type * {@code uint64_t} on C++ side the returning value can be negative * because Java supports in Java 7 only signed long values.</p> * * <p><strong>Java 7</strong>: To mitigate the problem of the non * existent unsigned long tpye, values should be encapsulated using * {@link java.math.BigInteger} to reflect the correct value. The correct * behavior is guaranteed if {@code 2^64} is added to negative values.</p> * * <p><strong>Java 8</strong>: In Java 8 the value should be treated as * unsigned long using provided methods of type {@link Long}.</p> * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance, or null for the default column family * @param property to be fetched. * * @return numerical property value * * @throws RocksDBException if an error happens in the underlying native code. */ public long getLongProperty( /* @Nullable */ final ColumnFamilyHandle columnFamilyHandle, final String property) throws RocksDBException { return getLongProperty(nativeHandle_, columnFamilyHandle == null ? 0 : columnFamilyHandle.nativeHandle_, property, property.length()); } /** * Reset internal stats for DB and all column families. * * Note this doesn't reset {@link Options#statistics()} as it is not * owned by DB. * * @throws RocksDBException if an error occurs whilst reseting the stats */ public void resetStats() throws RocksDBException { resetStats(nativeHandle_); } /** * <p> Return sum of the getLongProperty of all the column families</p> * * <p><strong>Note</strong>: As the returned property is of type * {@code uint64_t} on C++ side the returning value can be negative * because Java supports in Java 7 only signed long values.</p> * * <p><strong>Java 7</strong>: To mitigate the problem of the non * existent unsigned long tpye, values should be encapsulated using * {@link java.math.BigInteger} to reflect the correct value. The correct * behavior is guaranteed if {@code 2^64} is added to negative values.</p> * * <p><strong>Java 8</strong>: In Java 8 the value should be treated as * unsigned long using provided methods of type {@link Long}.</p> * * @param property to be fetched. * * @return numerical property value * * @throws RocksDBException if an error happens in the underlying native code. */ public long getAggregatedLongProperty(final String property) throws RocksDBException { return getAggregatedLongProperty(nativeHandle_, property, property.length()); } /** * Get the approximate file system space used by keys in each range. * * Note that the returned sizes measure file system space usage, so * if the user data compresses by a factor of ten, the returned * sizes will be one-tenth the size of the corresponding user data size. * * If {@code sizeApproximationFlags} defines whether the returned size * should include the recently written data in the mem-tables (if * the mem-table type supports it), data serialized to disk, or both. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance, or null for the default column family * @param ranges the ranges over which to approximate sizes * @param sizeApproximationFlags flags to determine what to include in the * approximation. * * @return the sizes */ public long[] getApproximateSizes( /*@Nullable*/ final ColumnFamilyHandle columnFamilyHandle, final List<Range> ranges, final SizeApproximationFlag... sizeApproximationFlags) { byte flags = 0x0; for (final SizeApproximationFlag sizeApproximationFlag : sizeApproximationFlags) { flags |= sizeApproximationFlag.getValue(); } return getApproximateSizes(nativeHandle_, columnFamilyHandle == null ? 0 : columnFamilyHandle.nativeHandle_, toRangeSliceHandles(ranges), flags); } /** * Get the approximate file system space used by keys in each range for * the default column family. * * Note that the returned sizes measure file system space usage, so * if the user data compresses by a factor of ten, the returned * sizes will be one-tenth the size of the corresponding user data size. * * If {@code sizeApproximationFlags} defines whether the returned size * should include the recently written data in the mem-tables (if * the mem-table type supports it), data serialized to disk, or both. * * @param ranges the ranges over which to approximate sizes * @param sizeApproximationFlags flags to determine what to include in the * approximation. * * @return the sizes. */ public long[] getApproximateSizes(final List<Range> ranges, final SizeApproximationFlag... sizeApproximationFlags) { return getApproximateSizes(null, ranges, sizeApproximationFlags); } public static class CountAndSize { public final long count; public final long size; public CountAndSize(final long count, final long size) { this.count = count; this.size = size; } } /** * This method is similar to * {@link #getApproximateSizes(ColumnFamilyHandle, List, SizeApproximationFlag...)}, * except that it returns approximate number of records and size in memtables. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance, or null for the default column family * @param range the ranges over which to get the memtable stats * * @return the count and size for the range */ public CountAndSize getApproximateMemTableStats( /*@Nullable*/ final ColumnFamilyHandle columnFamilyHandle, final Range range) { final long[] result = getApproximateMemTableStats(nativeHandle_, columnFamilyHandle == null ? 0 : columnFamilyHandle.nativeHandle_, range.start.getNativeHandle(), range.limit.getNativeHandle()); return new CountAndSize(result[0], result[1]); } /** * This method is similar to * {@link #getApproximateSizes(ColumnFamilyHandle, List, SizeApproximationFlag...)}, * except that it returns approximate number of records and size in memtables. * * @param range the ranges over which to get the memtable stats * * @return the count and size for the range */ public CountAndSize getApproximateMemTableStats( final Range range) { return getApproximateMemTableStats(null, range); } /** * <p>Range compaction of database.</p> * <p><strong>Note</strong>: After the database has been compacted, * all data will have been pushed down to the last level containing * any data.</p> * * <p><strong>See also</strong></p> * <ul> * <li>{@link #compactRange(boolean, int, int)}</li> * <li>{@link #compactRange(byte[], byte[])}</li> * <li>{@link #compactRange(byte[], byte[], boolean, int, int)}</li> * </ul> * * @throws RocksDBException thrown if an error occurs within the native * part of the library. */ public void compactRange() throws RocksDBException { compactRange(null); } /** * <p>Range compaction of column family.</p> * <p><strong>Note</strong>: After the database has been compacted, * all data will have been pushed down to the last level containing * any data.</p> * * <p><strong>See also</strong></p> * <ul> * <li> * {@link #compactRange(ColumnFamilyHandle, boolean, int, int)} * </li> * <li> * {@link #compactRange(ColumnFamilyHandle, byte[], byte[])} * </li> * <li> * {@link #compactRange(ColumnFamilyHandle, byte[], byte[], * boolean, int, int)} * </li> * </ul> * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance, or null for the default column family. * * @throws RocksDBException thrown if an error occurs within the native * part of the library. */ public void compactRange( /* @Nullable */ final ColumnFamilyHandle columnFamilyHandle) throws RocksDBException { compactRange(nativeHandle_, null, -1, null, -1, 0, columnFamilyHandle == null ? 0 : columnFamilyHandle.nativeHandle_); } /** * <p>Range compaction of database.</p> * <p><strong>Note</strong>: After the database has been compacted, * all data will have been pushed down to the last level containing * any data.</p> * * <p><strong>See also</strong></p> * <ul> * <li>{@link #compactRange()}</li> * <li>{@link #compactRange(boolean, int, int)}</li> * <li>{@link #compactRange(byte[], byte[], boolean, int, int)}</li> * </ul> * * @param begin start of key range (included in range) * @param end end of key range (excluded from range) * * @throws RocksDBException thrown if an error occurs within the native * part of the library. */ public void compactRange(final byte[] begin, final byte[] end) throws RocksDBException { compactRange(null, begin, end); } /** * <p>Range compaction of column family.</p> * <p><strong>Note</strong>: After the database has been compacted, * all data will have been pushed down to the last level containing * any data.</p> * * <p><strong>See also</strong></p> * <ul> * <li>{@link #compactRange(ColumnFamilyHandle)}</li> * <li> * {@link #compactRange(ColumnFamilyHandle, boolean, int, int)} * </li> * <li> * {@link #compactRange(ColumnFamilyHandle, byte[], byte[], * boolean, int, int)} * </li> * </ul> * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance, or null for the default column family. * @param begin start of key range (included in range) * @param end end of key range (excluded from range) * * @throws RocksDBException thrown if an error occurs within the native * part of the library. */ public void compactRange( /* @Nullable */ final ColumnFamilyHandle columnFamilyHandle, final byte[] begin, final byte[] end) throws RocksDBException { compactRange(nativeHandle_, begin, begin == null ? -1 : begin.length, end, end == null ? -1 : end.length, 0, columnFamilyHandle == null ? 0: columnFamilyHandle.nativeHandle_); } /** * <p>Range compaction of database.</p> * <p><strong>Note</strong>: After the database has been compacted, * all data will have been pushed down to the last level containing * any data.</p> * * <p>Compaction outputs should be placed in options.db_paths * [target_path_id]. Behavior is undefined if target_path_id is * out of range.</p> * * <p><strong>See also</strong></p> * <ul> * <li>{@link #compactRange()}</li> * <li>{@link #compactRange(byte[], byte[])}</li> * <li>{@link #compactRange(byte[], byte[], boolean, int, int)}</li> * </ul> * * @deprecated Use {@link #compactRange(ColumnFamilyHandle, byte[], byte[], CompactRangeOptions)} instead * * @param changeLevel reduce level after compaction * @param targetLevel target level to compact to * @param targetPathId the target path id of output path * * @throws RocksDBException thrown if an error occurs within the native * part of the library. */ @Deprecated public void compactRange(final boolean changeLevel, final int targetLevel, final int targetPathId) throws RocksDBException { compactRange(null, changeLevel, targetLevel, targetPathId); } /** * <p>Range compaction of column family.</p> * <p><strong>Note</strong>: After the database has been compacted, * all data will have been pushed down to the last level containing * any data.</p> * * <p>Compaction outputs should be placed in options.db_paths * [target_path_id]. Behavior is undefined if target_path_id is * out of range.</p> * * <p><strong>See also</strong></p> * <ul> * <li>{@link #compactRange(ColumnFamilyHandle)}</li> * <li> * {@link #compactRange(ColumnFamilyHandle, byte[], byte[])} * </li> * <li> * {@link #compactRange(ColumnFamilyHandle, byte[], byte[], * boolean, int, int)} * </li> * </ul> * * @deprecated Use {@link #compactRange(ColumnFamilyHandle, byte[], byte[], CompactRangeOptions)} instead * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance, or null for the default column family. * @param changeLevel reduce level after compaction * @param targetLevel target level to compact to * @param targetPathId the target path id of output path * * @throws RocksDBException thrown if an error occurs within the native * part of the library. */ @Deprecated public void compactRange( /* @Nullable */ final ColumnFamilyHandle columnFamilyHandle, final boolean changeLevel, final int targetLevel, final int targetPathId) throws RocksDBException { final CompactRangeOptions options = new CompactRangeOptions(); options.setChangeLevel(changeLevel); options.setTargetLevel(targetLevel); options.setTargetPathId(targetPathId); compactRange(nativeHandle_, null, -1, null, -1, options.nativeHandle_, columnFamilyHandle == null ? 0 : columnFamilyHandle.nativeHandle_); } /** * <p>Range compaction of database.</p> * <p><strong>Note</strong>: After the database has been compacted, * all data will have been pushed down to the last level containing * any data.</p> * * <p>Compaction outputs should be placed in options.db_paths * [target_path_id]. Behavior is undefined if target_path_id is * out of range.</p> * * <p><strong>See also</strong></p> * <ul> * <li>{@link #compactRange()}</li> * <li>{@link #compactRange(boolean, int, int)}</li> * <li>{@link #compactRange(byte[], byte[])}</li> * </ul> * * @deprecated Use {@link #compactRange(ColumnFamilyHandle, byte[], byte[], CompactRangeOptions)} * instead * * @param begin start of key range (included in range) * @param end end of key range (excluded from range) * @param changeLevel reduce level after compaction * @param targetLevel target level to compact to * @param targetPathId the target path id of output path * * @throws RocksDBException thrown if an error occurs within the native * part of the library. */ @Deprecated public void compactRange(final byte[] begin, final byte[] end, final boolean changeLevel, final int targetLevel, final int targetPathId) throws RocksDBException { compactRange(null, begin, end, changeLevel, targetLevel, targetPathId); } /** * <p>Range compaction of column family.</p> * <p><strong>Note</strong>: After the database has been compacted, * all data will have been pushed down to the last level containing * any data.</p> * * <p>Compaction outputs should be placed in options.db_paths * [target_path_id]. Behavior is undefined if target_path_id is * out of range.</p> * * <p><strong>See also</strong></p> * <ul> * <li>{@link #compactRange(ColumnFamilyHandle)}</li> * <li> * {@link #compactRange(ColumnFamilyHandle, boolean, int, int)} * </li> * <li> * {@link #compactRange(ColumnFamilyHandle, byte[], byte[])} * </li> * </ul> * * @deprecated Use {@link #compactRange(ColumnFamilyHandle, byte[], byte[], CompactRangeOptions)} instead * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance. * @param begin start of key range (included in range) * @param end end of key range (excluded from range) * @param changeLevel reduce level after compaction * @param targetLevel target level to compact to * @param targetPathId the target path id of output path * * @throws RocksDBException thrown if an error occurs within the native * part of the library. */ @Deprecated public void compactRange( /* @Nullable */ final ColumnFamilyHandle columnFamilyHandle, final byte[] begin, final byte[] end, final boolean changeLevel, final int targetLevel, final int targetPathId) throws RocksDBException { final CompactRangeOptions options = new CompactRangeOptions(); options.setChangeLevel(changeLevel); options.setTargetLevel(targetLevel); options.setTargetPathId(targetPathId); compactRange(nativeHandle_, begin, begin == null ? -1 : begin.length, end, end == null ? -1 : end.length, options.nativeHandle_, columnFamilyHandle == null ? 0 : columnFamilyHandle.nativeHandle_); } /** * <p>Range compaction of column family.</p> * <p><strong>Note</strong>: After the database has been compacted, * all data will have been pushed down to the last level containing * any data.</p> * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} instance. * @param begin start of key range (included in range) * @param end end of key range (excluded from range) * @param compactRangeOptions options for the compaction * * @throws RocksDBException thrown if an error occurs within the native * part of the library. */ public void compactRange( /* @Nullable */ final ColumnFamilyHandle columnFamilyHandle, final byte[] begin, final byte[] end, final CompactRangeOptions compactRangeOptions) throws RocksDBException { compactRange(nativeHandle_, begin, begin == null ? -1 : begin.length, end, end == null ? -1 : end.length, compactRangeOptions.nativeHandle_, columnFamilyHandle == null ? 0 : columnFamilyHandle.nativeHandle_); } /** * Change the options for the column family handle. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance, or null for the default column family. * @param mutableColumnFamilyOptions the options. * * @throws RocksDBException if an error occurs whilst setting the options */ public void setOptions( /* @Nullable */final ColumnFamilyHandle columnFamilyHandle, final MutableColumnFamilyOptions mutableColumnFamilyOptions) throws RocksDBException { setOptions(nativeHandle_, columnFamilyHandle == null ? 0 : columnFamilyHandle.nativeHandle_, mutableColumnFamilyOptions.getKeys(), mutableColumnFamilyOptions.getValues()); } /** * Change the options for the default column family handle. * * @param mutableColumnFamilyOptions the options. * * @throws RocksDBException if an error occurs whilst setting the options */ public void setOptions( final MutableColumnFamilyOptions mutableColumnFamilyOptions) throws RocksDBException { setOptions(null, mutableColumnFamilyOptions); } /** * Set the options for the column family handle. * * @param mutableDBoptions the options. * * @throws RocksDBException if an error occurs whilst setting the options */ public void setDBOptions(final MutableDBOptions mutableDBoptions) throws RocksDBException { setDBOptions(nativeHandle_, mutableDBoptions.getKeys(), mutableDBoptions.getValues()); } /** * Takes a list of files specified by file names and * compacts them to the specified level. * * Note that the behavior is different from * {@link #compactRange(ColumnFamilyHandle, byte[], byte[])} * in that CompactFiles() performs the compaction job using the CURRENT * thread. * * @param compactionOptions compaction options * @param inputFileNames the name of the files to compact * @param outputLevel the level to which they should be compacted * @param outputPathId the id of the output path, or -1 * @param compactionJobInfo the compaction job info, this parameter * will be updated with the info from compacting the files, * can just be null if you don't need it. * * @return the list of compacted files * * @throws RocksDBException if an error occurs during compaction */ public List<String> compactFiles( final CompactionOptions compactionOptions, final List<String> inputFileNames, final int outputLevel, final int outputPathId, /* @Nullable */ final CompactionJobInfo compactionJobInfo) throws RocksDBException { return compactFiles(compactionOptions, null, inputFileNames, outputLevel, outputPathId, compactionJobInfo); } /** * Takes a list of files specified by file names and * compacts them to the specified level. * * Note that the behavior is different from * {@link #compactRange(ColumnFamilyHandle, byte[], byte[])} * in that CompactFiles() performs the compaction job using the CURRENT * thread. * * @param compactionOptions compaction options * @param columnFamilyHandle columnFamilyHandle, or null for the * default column family * @param inputFileNames the name of the files to compact * @param outputLevel the level to which they should be compacted * @param outputPathId the id of the output path, or -1 * @param compactionJobInfo the compaction job info, this parameter * will be updated with the info from compacting the files, * can just be null if you don't need it. * * @return the list of compacted files * * @throws RocksDBException if an error occurs during compaction */ public List<String> compactFiles( final CompactionOptions compactionOptions, /* @Nullable */ final ColumnFamilyHandle columnFamilyHandle, final List<String> inputFileNames, final int outputLevel, final int outputPathId, /* @Nullable */ final CompactionJobInfo compactionJobInfo) throws RocksDBException { return Arrays.asList(compactFiles(nativeHandle_, compactionOptions.nativeHandle_, columnFamilyHandle == null ? 0 : columnFamilyHandle.nativeHandle_, inputFileNames.toArray(new String[0]), outputLevel, outputPathId, compactionJobInfo == null ? 0 : compactionJobInfo.nativeHandle_)); } /** * This function will cancel all currently running background processes. * * @param wait if true, wait for all background work to be cancelled before * returning. * */ public void cancelAllBackgroundWork(boolean wait) { cancelAllBackgroundWork(nativeHandle_, wait); } /** * This function will wait until all currently running background processes * finish. After it returns, no background process will be run until * {@link #continueBackgroundWork()} is called * * @throws RocksDBException if an error occurs when pausing background work */ public void pauseBackgroundWork() throws RocksDBException { pauseBackgroundWork(nativeHandle_); } /** * Resumes background work which was suspended by * previously calling {@link #pauseBackgroundWork()} * * @throws RocksDBException if an error occurs when resuming background work */ public void continueBackgroundWork() throws RocksDBException { continueBackgroundWork(nativeHandle_); } /** * Enable automatic compactions for the given column * families if they were previously disabled. * * The function will first set the * {@link ColumnFamilyOptions#disableAutoCompactions()} option for each * column family to false, after which it will schedule a flush/compaction. * * NOTE: Setting disableAutoCompactions to 'false' through * {@link #setOptions(ColumnFamilyHandle, MutableColumnFamilyOptions)} * does NOT schedule a flush/compaction afterwards, and only changes the * parameter itself within the column family option. * * @param columnFamilyHandles the column family handles * * @throws RocksDBException if an error occurs whilst enabling auto-compaction */ public void enableAutoCompaction( final List<ColumnFamilyHandle> columnFamilyHandles) throws RocksDBException { enableAutoCompaction(nativeHandle_, toNativeHandleList(columnFamilyHandles)); } /** * Number of levels used for this DB. * * @return the number of levels */ public int numberLevels() { return numberLevels(null); } /** * Number of levels used for a column family in this DB. * * @param columnFamilyHandle the column family handle, or null * for the default column family * * @return the number of levels */ public int numberLevels(/* @Nullable */final ColumnFamilyHandle columnFamilyHandle) { return numberLevels(nativeHandle_, columnFamilyHandle == null ? 0 : columnFamilyHandle.nativeHandle_); } /** * Maximum level to which a new compacted memtable is pushed if it * does not create overlap. * * @return the maximum level */ public int maxMemCompactionLevel() { return maxMemCompactionLevel(null); } /** * Maximum level to which a new compacted memtable is pushed if it * does not create overlap. * * @param columnFamilyHandle the column family handle * * @return the maximum level */ public int maxMemCompactionLevel( /* @Nullable */ final ColumnFamilyHandle columnFamilyHandle) { return maxMemCompactionLevel(nativeHandle_, columnFamilyHandle == null ? 0 : columnFamilyHandle.nativeHandle_); } /** * Number of files in level-0 that would stop writes. * * @return the number of files */ public int level0StopWriteTrigger() { return level0StopWriteTrigger(null); } /** * Number of files in level-0 that would stop writes. * * @param columnFamilyHandle the column family handle * * @return the number of files */ public int level0StopWriteTrigger( /* @Nullable */final ColumnFamilyHandle columnFamilyHandle) { return level0StopWriteTrigger(nativeHandle_, columnFamilyHandle == null ? 0 : columnFamilyHandle.nativeHandle_); } /** * Get DB name -- the exact same name that was provided as an argument to * as path to {@link #open(Options, String)}. * * @return the DB name */ public String getName() { return getName(nativeHandle_); } /** * Get the Env object from the DB * * @return the env */ public Env getEnv() { final long envHandle = getEnv(nativeHandle_); if (envHandle == Env.getDefault().nativeHandle_) { return Env.getDefault(); } else { final Env env = new RocksEnv(envHandle); env.disOwnNativeHandle(); // we do not own the Env! return env; } } /** * <p>Flush all memory table data.</p> * * <p>Note: it must be ensured that the FlushOptions instance * is not GC'ed before this method finishes. If the wait parameter is * set to false, flush processing is asynchronous.</p> * * @param flushOptions {@link org.rocksdb.FlushOptions} instance. * @throws RocksDBException thrown if an error occurs within the native * part of the library. */ public void flush(final FlushOptions flushOptions) throws RocksDBException { flush(flushOptions, (List<ColumnFamilyHandle>) null); } /** * <p>Flush all memory table data.</p> * * <p>Note: it must be ensured that the FlushOptions instance * is not GC'ed before this method finishes. If the wait parameter is * set to false, flush processing is asynchronous.</p> * * @param flushOptions {@link org.rocksdb.FlushOptions} instance. * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} instance. * @throws RocksDBException thrown if an error occurs within the native * part of the library. */ public void flush(final FlushOptions flushOptions, /* @Nullable */ final ColumnFamilyHandle columnFamilyHandle) throws RocksDBException { flush(flushOptions, columnFamilyHandle == null ? null : Arrays.asList(columnFamilyHandle)); } /** * Flushes multiple column families. * * If atomic flush is not enabled, this is equivalent to calling * {@link #flush(FlushOptions, ColumnFamilyHandle)} multiple times. * * If atomic flush is enabled, this will flush all column families * specified up to the latest sequence number at the time when flush is * requested. * * @param flushOptions {@link org.rocksdb.FlushOptions} instance. * @param columnFamilyHandles column family handles. * @throws RocksDBException thrown if an error occurs within the native * part of the library. */ public void flush(final FlushOptions flushOptions, /* @Nullable */ final List<ColumnFamilyHandle> columnFamilyHandles) throws RocksDBException { flush(nativeHandle_, flushOptions.nativeHandle_, toNativeHandleList(columnFamilyHandles)); } /** * Flush the WAL memory buffer to the file. If {@code sync} is true, * it calls {@link #syncWal()} afterwards. * * @param sync true to also fsync to disk. * * @throws RocksDBException if an error occurs whilst flushing */ public void flushWal(final boolean sync) throws RocksDBException { flushWal(nativeHandle_, sync); } /** * Sync the WAL. * * Note that {@link #write(WriteOptions, WriteBatch)} followed by * {@link #syncWal()} is not exactly the same as * {@link #write(WriteOptions, WriteBatch)} with * {@link WriteOptions#sync()} set to true; In the latter case the changes * won't be visible until the sync is done. * * Currently only works if {@link Options#allowMmapWrites()} is set to false. * * @throws RocksDBException if an error occurs whilst syncing */ public void syncWal() throws RocksDBException { syncWal(nativeHandle_); } /** * <p>The sequence number of the most recent transaction.</p> * * @return sequence number of the most * recent transaction. */ public long getLatestSequenceNumber() { return getLatestSequenceNumber(nativeHandle_); } /** * Instructs DB to preserve deletes with sequence numbers &gt;= sequenceNumber. * * Has no effect if DBOptions#preserveDeletes() is set to false. * * This function assumes that user calls this function with monotonically * increasing seqnums (otherwise we can't guarantee that a particular delete * hasn't been already processed). * * @param sequenceNumber the minimum sequence number to preserve * * @return true if the value was successfully updated, * false if user attempted to call if with * sequenceNumber &lt;= current value. */ public boolean setPreserveDeletesSequenceNumber(final long sequenceNumber) { return setPreserveDeletesSequenceNumber(nativeHandle_, sequenceNumber); } /** * <p>Prevent file deletions. Compactions will continue to occur, * but no obsolete files will be deleted. Calling this multiple * times have the same effect as calling it once.</p> * * @throws RocksDBException thrown if operation was not performed * successfully. */ public void disableFileDeletions() throws RocksDBException { disableFileDeletions(nativeHandle_); } /** * <p>Allow compactions to delete obsolete files. * If force == true, the call to EnableFileDeletions() * will guarantee that file deletions are enabled after * the call, even if DisableFileDeletions() was called * multiple times before.</p> * * <p>If force == false, EnableFileDeletions will only * enable file deletion after it's been called at least * as many times as DisableFileDeletions(), enabling * the two methods to be called by two threads * concurrently without synchronization * -- i.e., file deletions will be enabled only after both * threads call EnableFileDeletions()</p> * * @param force boolean value described above. * * @throws RocksDBException thrown if operation was not performed * successfully. */ public void enableFileDeletions(final boolean force) throws RocksDBException { enableFileDeletions(nativeHandle_, force); } public static class LiveFiles { /** * The valid size of the manifest file. The manifest file is an ever growing * file, but only the portion specified here is valid for this snapshot. */ public final long manifestFileSize; /** * The files are relative to the {@link #getName()} and are not * absolute paths. Despite being relative paths, the file names begin * with "/". */ public final List<String> files; LiveFiles(final long manifestFileSize, final List<String> files) { this.manifestFileSize = manifestFileSize; this.files = files; } } /** * Retrieve the list of all files in the database after flushing the memtable. * * See {@link #getLiveFiles(boolean)}. * * @return the live files * * @throws RocksDBException if an error occurs whilst retrieving the list * of live files */ public LiveFiles getLiveFiles() throws RocksDBException { return getLiveFiles(true); } /** * Retrieve the list of all files in the database. * * In case you have multiple column families, even if {@code flushMemtable} * is true, you still need to call {@link #getSortedWalFiles()} * after {@link #getLiveFiles(boolean)} to compensate for new data that * arrived to already-flushed column families while other column families * were flushing. * * NOTE: Calling {@link #getLiveFiles(boolean)} followed by * {@link #getSortedWalFiles()} can generate a lossless backup. * * @param flushMemtable set to true to flush before recoding the live * files. Setting to false is useful when we don't want to wait for flush * which may have to wait for compaction to complete taking an * indeterminate time. * * @return the live files * * @throws RocksDBException if an error occurs whilst retrieving the list * of live files */ public LiveFiles getLiveFiles(final boolean flushMemtable) throws RocksDBException { final String[] result = getLiveFiles(nativeHandle_, flushMemtable); if (result == null) { return null; } final String[] files = Arrays.copyOf(result, result.length - 1); final long manifestFileSize = Long.parseLong(result[result.length - 1]); return new LiveFiles(manifestFileSize, Arrays.asList(files)); } /** * Retrieve the sorted list of all wal files with earliest file first. * * @return the log files * * @throws RocksDBException if an error occurs whilst retrieving the list * of sorted WAL files */ public List<LogFile> getSortedWalFiles() throws RocksDBException { final LogFile[] logFiles = getSortedWalFiles(nativeHandle_); return Arrays.asList(logFiles); } /** * <p>Returns an iterator that is positioned at a write-batch containing * seq_number. If the sequence number is non existent, it returns an iterator * at the first available seq_no after the requested seq_no.</p> * * <p>Must set WAL_ttl_seconds or WAL_size_limit_MB to large values to * use this api, else the WAL files will get * cleared aggressively and the iterator might keep getting invalid before * an update is read.</p> * * @param sequenceNumber sequence number offset * * @return {@link org.rocksdb.TransactionLogIterator} instance. * * @throws org.rocksdb.RocksDBException if iterator cannot be retrieved * from native-side. */ public TransactionLogIterator getUpdatesSince(final long sequenceNumber) throws RocksDBException { return new TransactionLogIterator( getUpdatesSince(nativeHandle_, sequenceNumber)); } /** * Delete the file name from the db directory and update the internal state to * reflect that. Supports deletion of sst and log files only. 'name' must be * path relative to the db directory. eg. 000001.sst, /archive/000003.log * * @param name the file name * * @throws RocksDBException if an error occurs whilst deleting the file */ public void deleteFile(final String name) throws RocksDBException { deleteFile(nativeHandle_, name); } /** * Gets a list of all table files metadata. * * @return table files metadata. */ public List<LiveFileMetaData> getLiveFilesMetaData() { return Arrays.asList(getLiveFilesMetaData(nativeHandle_)); } /** * Obtains the meta data of the specified column family of the DB. * * @param columnFamilyHandle the column family * * @return the column family metadata */ public ColumnFamilyMetaData getColumnFamilyMetaData( /* @Nullable */ final ColumnFamilyHandle columnFamilyHandle) { return getColumnFamilyMetaData(nativeHandle_, columnFamilyHandle == null ? 0 : columnFamilyHandle.nativeHandle_); } /** * Obtains the meta data of the default column family of the DB. * * @return the column family metadata */ public ColumnFamilyMetaData getColumnFamilyMetaData() { return getColumnFamilyMetaData(null); } /** * ingestExternalFile will load a list of external SST files (1) into the DB * We will try to find the lowest possible level that the file can fit in, and * ingest the file into this level (2). A file that have a key range that * overlap with the memtable key range will require us to Flush the memtable * first before ingesting the file. * * (1) External SST files can be created using {@link SstFileWriter} * (2) We will try to ingest the files to the lowest possible level * even if the file compression doesn't match the level compression * * @param filePathList The list of files to ingest * @param ingestExternalFileOptions the options for the ingestion * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void ingestExternalFile(final List<String> filePathList, final IngestExternalFileOptions ingestExternalFileOptions) throws RocksDBException { ingestExternalFile(nativeHandle_, getDefaultColumnFamily().nativeHandle_, filePathList.toArray(new String[0]), filePathList.size(), ingestExternalFileOptions.nativeHandle_); } /** * ingestExternalFile will load a list of external SST files (1) into the DB * We will try to find the lowest possible level that the file can fit in, and * ingest the file into this level (2). A file that have a key range that * overlap with the memtable key range will require us to Flush the memtable * first before ingesting the file. * * (1) External SST files can be created using {@link SstFileWriter} * (2) We will try to ingest the files to the lowest possible level * even if the file compression doesn't match the level compression * * @param columnFamilyHandle The column family for the ingested files * @param filePathList The list of files to ingest * @param ingestExternalFileOptions the options for the ingestion * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void ingestExternalFile(final ColumnFamilyHandle columnFamilyHandle, final List<String> filePathList, final IngestExternalFileOptions ingestExternalFileOptions) throws RocksDBException { ingestExternalFile(nativeHandle_, columnFamilyHandle.nativeHandle_, filePathList.toArray(new String[0]), filePathList.size(), ingestExternalFileOptions.nativeHandle_); } /** * Verify checksum * * @throws RocksDBException if the checksum is not valid */ public void verifyChecksum() throws RocksDBException { verifyChecksum(nativeHandle_); } /** * Gets the handle for the default column family * * @return The handle of the default column family */ public ColumnFamilyHandle getDefaultColumnFamily() { final ColumnFamilyHandle cfHandle = new ColumnFamilyHandle(this, getDefaultColumnFamily(nativeHandle_)); cfHandle.disOwnNativeHandle(); return cfHandle; } /** * Get the properties of all tables. * * @param columnFamilyHandle the column family handle, or null for the default * column family. * * @return the properties * * @throws RocksDBException if an error occurs whilst getting the properties */ public Map<String, TableProperties> getPropertiesOfAllTables( /* @Nullable */final ColumnFamilyHandle columnFamilyHandle) throws RocksDBException { return getPropertiesOfAllTables(nativeHandle_, columnFamilyHandle == null ? 0 : columnFamilyHandle.nativeHandle_); } /** * Get the properties of all tables in the default column family. * * @return the properties * * @throws RocksDBException if an error occurs whilst getting the properties */ public Map<String, TableProperties> getPropertiesOfAllTables() throws RocksDBException { return getPropertiesOfAllTables(null); } /** * Get the properties of tables in range. * * @param columnFamilyHandle the column family handle, or null for the default * column family. * @param ranges the ranges over which to get the table properties * * @return the properties * * @throws RocksDBException if an error occurs whilst getting the properties */ public Map<String, TableProperties> getPropertiesOfTablesInRange( /* @Nullable */final ColumnFamilyHandle columnFamilyHandle, final List<Range> ranges) throws RocksDBException { return getPropertiesOfTablesInRange(nativeHandle_, columnFamilyHandle == null ? 0 : columnFamilyHandle.nativeHandle_, toRangeSliceHandles(ranges)); } /** * Get the properties of tables in range for the default column family. * * @param ranges the ranges over which to get the table properties * * @return the properties * * @throws RocksDBException if an error occurs whilst getting the properties */ public Map<String, TableProperties> getPropertiesOfTablesInRange( final List<Range> ranges) throws RocksDBException { return getPropertiesOfTablesInRange(null, ranges); } /** * Suggest the range to compact. * * @param columnFamilyHandle the column family handle, or null for the default * column family. * * @return the suggested range. * * @throws RocksDBException if an error occurs whilst suggesting the range */ public Range suggestCompactRange( /* @Nullable */final ColumnFamilyHandle columnFamilyHandle) throws RocksDBException { final long[] rangeSliceHandles = suggestCompactRange(nativeHandle_, columnFamilyHandle == null ? 0 : columnFamilyHandle.nativeHandle_); return new Range(new Slice(rangeSliceHandles[0]), new Slice(rangeSliceHandles[1])); } /** * Suggest the range to compact for the default column family. * * @return the suggested range. * * @throws RocksDBException if an error occurs whilst suggesting the range */ public Range suggestCompactRange() throws RocksDBException { return suggestCompactRange(null); } /** * Promote L0. * * @param columnFamilyHandle the column family handle, * or null for the default column family. * @param targetLevel the target level for L0 * * @throws RocksDBException if an error occurs whilst promoting L0 */ public void promoteL0( /* @Nullable */final ColumnFamilyHandle columnFamilyHandle, final int targetLevel) throws RocksDBException { promoteL0(nativeHandle_, columnFamilyHandle == null ? 0 : columnFamilyHandle.nativeHandle_, targetLevel); } /** * Promote L0 for the default column family. * * @param targetLevel the target level for L0 * * @throws RocksDBException if an error occurs whilst promoting L0 */ public void promoteL0(final int targetLevel) throws RocksDBException { promoteL0(null, targetLevel); } /** * Trace DB operations. * * Use {@link #endTrace()} to stop tracing. * * @param traceOptions the options * @param traceWriter the trace writer * * @throws RocksDBException if an error occurs whilst starting the trace */ public void startTrace(final TraceOptions traceOptions, final AbstractTraceWriter traceWriter) throws RocksDBException { startTrace(nativeHandle_, traceOptions.getMaxTraceFileSize(), traceWriter.nativeHandle_); /** * NOTE: {@link #startTrace(long, long, long) transfers the ownership * from Java to C++, so we must disown the native handle here. */ traceWriter.disOwnNativeHandle(); } /** * Stop tracing DB operations. * * See {@link #startTrace(TraceOptions, AbstractTraceWriter)} * * @throws RocksDBException if an error occurs whilst ending the trace */ public void endTrace() throws RocksDBException { endTrace(nativeHandle_); } /** * Make the secondary instance catch up with the primary by tailing and * replaying the MANIFEST and WAL of the primary. * Column families created by the primary after the secondary instance starts * will be ignored unless the secondary instance closes and restarts with the * newly created column families. * Column families that exist before secondary instance starts and dropped by * the primary afterwards will be marked as dropped. However, as long as the * secondary instance does not delete the corresponding column family * handles, the data of the column family is still accessible to the * secondary. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void tryCatchUpWithPrimary() throws RocksDBException { tryCatchUpWithPrimary(nativeHandle_); } /** * Delete files in multiple ranges at once. * Delete files in a lot of ranges one at a time can be slow, use this API for * better performance in that case. * * @param columnFamily - The column family for operation (null for default) * @param includeEnd - Whether ranges should include end * @param ranges - pairs of ranges (from1, to1, from2, to2, ...) * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void deleteFilesInRanges(final ColumnFamilyHandle columnFamily, final List<byte[]> ranges, final boolean includeEnd) throws RocksDBException { if (ranges.size() == 0) { return; } if ((ranges.size() % 2) != 0) { throw new IllegalArgumentException("Ranges size needs to be multiple of 2 " + "(from1, to1, from2, to2, ...), but is " + ranges.size()); } final byte[][] rangesArray = ranges.toArray(new byte[ranges.size()][]); deleteFilesInRanges(nativeHandle_, columnFamily == null ? 0 : columnFamily.nativeHandle_, rangesArray, includeEnd); } /** * Static method to destroy the contents of the specified database. * Be very careful using this method. * * @param path the path to the Rocksdb database. * @param options {@link org.rocksdb.Options} instance. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public static void destroyDB(final String path, final Options options) throws RocksDBException { destroyDB(path, options.nativeHandle_); } private /* @Nullable */ long[] toNativeHandleList( /* @Nullable */ final List<? extends RocksObject> objectList) { if (objectList == null) { return null; } final int len = objectList.size(); final long[] handleList = new long[len]; for (int i = 0; i < len; i++) { handleList[i] = objectList.get(i).nativeHandle_; } return handleList; } private static long[] toRangeSliceHandles(final List<Range> ranges) { final long rangeSliceHandles[] = new long [ranges.size() * 2]; for (int i = 0, j = 0; i < ranges.size(); i++) { final Range range = ranges.get(i); rangeSliceHandles[j++] = range.start.getNativeHandle(); rangeSliceHandles[j++] = range.limit.getNativeHandle(); } return rangeSliceHandles; } protected void storeOptionsInstance(DBOptionsInterface options) { options_ = options; } private static void checkBounds(int offset, int len, int size) { if ((offset | len | (offset + len) | (size - (offset + len))) < 0) { throw new IndexOutOfBoundsException(String.format("offset(%d), len(%d), size(%d)", offset, len, size)); } } private static int computeCapacityHint(final int estimatedNumberOfItems) { // Default load factor for HashMap is 0.75, so N * 1.5 will be at the load // limit. We add +1 for a buffer. return (int)Math.ceil(estimatedNumberOfItems * 1.5 + 1.0); } // native methods private native static long open(final long optionsHandle, final String path) throws RocksDBException; /** * @param optionsHandle Native handle pointing to an Options object * @param path The directory path for the database files * @param columnFamilyNames An array of column family names * @param columnFamilyOptions An array of native handles pointing to * ColumnFamilyOptions objects * * @return An array of native handles, [0] is the handle of the RocksDB object * [1..1+n] are handles of the ColumnFamilyReferences * * @throws RocksDBException thrown if the database could not be opened */ private native static long[] open(final long optionsHandle, final String path, final byte[][] columnFamilyNames, final long[] columnFamilyOptions) throws RocksDBException; private native static long openROnly(final long optionsHandle, final String path, final boolean errorIfWalFileExists) throws RocksDBException; /** * @param optionsHandle Native handle pointing to an Options object * @param path The directory path for the database files * @param columnFamilyNames An array of column family names * @param columnFamilyOptions An array of native handles pointing to * ColumnFamilyOptions objects * * @return An array of native handles, [0] is the handle of the RocksDB object * [1..1+n] are handles of the ColumnFamilyReferences * * @throws RocksDBException thrown if the database could not be opened */ private native static long[] openROnly(final long optionsHandle, final String path, final byte[][] columnFamilyNames, final long[] columnFamilyOptions, final boolean errorIfWalFileExists) throws RocksDBException; private native static long openAsSecondary(final long optionsHandle, final String path, final String secondaryPath) throws RocksDBException; private native static long[] openAsSecondary(final long optionsHandle, final String path, final String secondaryPath, final byte[][] columnFamilyNames, final long[] columnFamilyOptions) throws RocksDBException; @Override protected native void disposeInternal(final long handle); private native static void closeDatabase(final long handle) throws RocksDBException; private native static byte[][] listColumnFamilies(final long optionsHandle, final String path) throws RocksDBException; private native long createColumnFamily(final long handle, final byte[] columnFamilyName, final int columnFamilyNamelen, final long columnFamilyOptions) throws RocksDBException; private native long[] createColumnFamilies(final long handle, final long columnFamilyOptionsHandle, final byte[][] columnFamilyNames) throws RocksDBException; private native long[] createColumnFamilies(final long handle, final long columnFamilyOptionsHandles[], final byte[][] columnFamilyNames) throws RocksDBException; private native void dropColumnFamily( final long handle, final long cfHandle) throws RocksDBException; private native void dropColumnFamilies(final long handle, final long[] cfHandles) throws RocksDBException; private native void put(final long handle, final byte[] key, final int keyOffset, final int keyLength, final byte[] value, final int valueOffset, int valueLength) throws RocksDBException; private native void put(final long handle, final byte[] key, final int keyOffset, final int keyLength, final byte[] value, final int valueOffset, final int valueLength, final long cfHandle) throws RocksDBException; private native void put(final long handle, final long writeOptHandle, final byte[] key, final int keyOffset, final int keyLength, final byte[] value, final int valueOffset, final int valueLength) throws RocksDBException; private native void put(final long handle, final long writeOptHandle, final byte[] key, final int keyOffset, final int keyLength, final byte[] value, final int valueOffset, final int valueLength, final long cfHandle) throws RocksDBException; private native void delete(final long handle, final byte[] key, final int keyOffset, final int keyLength) throws RocksDBException; private native void delete(final long handle, final byte[] key, final int keyOffset, final int keyLength, final long cfHandle) throws RocksDBException; private native void delete(final long handle, final long writeOptHandle, final byte[] key, final int keyOffset, final int keyLength) throws RocksDBException; private native void delete(final long handle, final long writeOptHandle, final byte[] key, final int keyOffset, final int keyLength, final long cfHandle) throws RocksDBException; private native void singleDelete( final long handle, final byte[] key, final int keyLen) throws RocksDBException; private native void singleDelete( final long handle, final byte[] key, final int keyLen, final long cfHandle) throws RocksDBException; private native void singleDelete( final long handle, final long writeOptHandle, final byte[] key, final int keyLen) throws RocksDBException; private native void singleDelete( final long handle, final long writeOptHandle, final byte[] key, final int keyLen, final long cfHandle) throws RocksDBException; private native void deleteRange(final long handle, final byte[] beginKey, final int beginKeyOffset, final int beginKeyLength, final byte[] endKey, final int endKeyOffset, final int endKeyLength) throws RocksDBException; private native void deleteRange(final long handle, final byte[] beginKey, final int beginKeyOffset, final int beginKeyLength, final byte[] endKey, final int endKeyOffset, final int endKeyLength, final long cfHandle) throws RocksDBException; private native void deleteRange(final long handle, final long writeOptHandle, final byte[] beginKey, final int beginKeyOffset, final int beginKeyLength, final byte[] endKey, final int endKeyOffset, final int endKeyLength) throws RocksDBException; private native void deleteRange( final long handle, final long writeOptHandle, final byte[] beginKey, final int beginKeyOffset, final int beginKeyLength, final byte[] endKey, final int endKeyOffset, final int endKeyLength, final long cfHandle) throws RocksDBException; private native void merge(final long handle, final byte[] key, final int keyOffset, final int keyLength, final byte[] value, final int valueOffset, final int valueLength) throws RocksDBException; private native void merge(final long handle, final byte[] key, final int keyOffset, final int keyLength, final byte[] value, final int valueOffset, final int valueLength, final long cfHandle) throws RocksDBException; private native void merge(final long handle, final long writeOptHandle, final byte[] key, final int keyOffset, final int keyLength, final byte[] value, final int valueOffset, final int valueLength) throws RocksDBException; private native void merge(final long handle, final long writeOptHandle, final byte[] key, final int keyOffset, final int keyLength, final byte[] value, final int valueOffset, final int valueLength, final long cfHandle) throws RocksDBException; private native void write0(final long handle, final long writeOptHandle, final long wbHandle) throws RocksDBException; private native void write1(final long handle, final long writeOptHandle, final long wbwiHandle) throws RocksDBException; private native int get(final long handle, final byte[] key, final int keyOffset, final int keyLength, final byte[] value, final int valueOffset, final int valueLength) throws RocksDBException; private native int get(final long handle, final byte[] key, final int keyOffset, final int keyLength, byte[] value, final int valueOffset, final int valueLength, final long cfHandle) throws RocksDBException; private native int get(final long handle, final long readOptHandle, final byte[] key, final int keyOffset, final int keyLength, final byte[] value, final int valueOffset, final int valueLength) throws RocksDBException; private native int get(final long handle, final long readOptHandle, final byte[] key, final int keyOffset, final int keyLength, final byte[] value, final int valueOffset, final int valueLength, final long cfHandle) throws RocksDBException; private native byte[] get(final long handle, byte[] key, final int keyOffset, final int keyLength) throws RocksDBException; private native byte[] get(final long handle, final byte[] key, final int keyOffset, final int keyLength, final long cfHandle) throws RocksDBException; private native byte[] get(final long handle, final long readOptHandle, final byte[] key, final int keyOffset, final int keyLength) throws RocksDBException; private native byte[] get(final long handle, final long readOptHandle, final byte[] key, final int keyOffset, final int keyLength, final long cfHandle) throws RocksDBException; private native byte[][] multiGet(final long dbHandle, final byte[][] keys, final int[] keyOffsets, final int[] keyLengths); private native byte[][] multiGet(final long dbHandle, final byte[][] keys, final int[] keyOffsets, final int[] keyLengths, final long[] columnFamilyHandles); private native byte[][] multiGet(final long dbHandle, final long rOptHandle, final byte[][] keys, final int[] keyOffsets, final int[] keyLengths); private native byte[][] multiGet(final long dbHandle, final long rOptHandle, final byte[][] keys, final int[] keyOffsets, final int[] keyLengths, final long[] columnFamilyHandles); private native boolean keyMayExist( final long handle, final long cfHandle, final long readOptHandle, final byte[] key, final int keyOffset, final int keyLength); private native byte[][] keyMayExistFoundValue( final long handle, final long cfHandle, final long readOptHandle, final byte[] key, final int keyOffset, final int keyLength); private native void putDirect(long handle, long writeOptHandle, ByteBuffer key, int keyOffset, int keyLength, ByteBuffer value, int valueOffset, int valueLength, long cfHandle) throws RocksDBException; private native long iterator(final long handle); private native long iterator(final long handle, final long readOptHandle); private native long iteratorCF(final long handle, final long cfHandle); private native long iteratorCF(final long handle, final long cfHandle, final long readOptHandle); private native long[] iterators(final long handle, final long[] columnFamilyHandles, final long readOptHandle) throws RocksDBException; private native long getSnapshot(final long nativeHandle); private native void releaseSnapshot( final long nativeHandle, final long snapshotHandle); private native String getProperty(final long nativeHandle, final long cfHandle, final String property, final int propertyLength) throws RocksDBException; private native Map<String, String> getMapProperty(final long nativeHandle, final long cfHandle, final String property, final int propertyLength) throws RocksDBException; private native int getDirect(long handle, long readOptHandle, ByteBuffer key, int keyOffset, int keyLength, ByteBuffer value, int valueOffset, int valueLength, long cfHandle) throws RocksDBException; private native void deleteDirect(long handle, long optHandle, ByteBuffer key, int keyOffset, int keyLength, long cfHandle) throws RocksDBException; private native long getLongProperty(final long nativeHandle, final long cfHandle, final String property, final int propertyLength) throws RocksDBException; private native void resetStats(final long nativeHandle) throws RocksDBException; private native long getAggregatedLongProperty(final long nativeHandle, final String property, int propertyLength) throws RocksDBException; private native long[] getApproximateSizes(final long nativeHandle, final long columnFamilyHandle, final long[] rangeSliceHandles, final byte includeFlags); private final native long[] getApproximateMemTableStats( final long nativeHandle, final long columnFamilyHandle, final long rangeStartSliceHandle, final long rangeLimitSliceHandle); private native void compactRange(final long handle, /* @Nullable */ final byte[] begin, final int beginLen, /* @Nullable */ final byte[] end, final int endLen, final long compactRangeOptHandle, final long cfHandle) throws RocksDBException; private native void setOptions(final long handle, final long cfHandle, final String[] keys, final String[] values) throws RocksDBException; private native void setDBOptions(final long handle, final String[] keys, final String[] values) throws RocksDBException; private native String[] compactFiles(final long handle, final long compactionOptionsHandle, final long columnFamilyHandle, final String[] inputFileNames, final int outputLevel, final int outputPathId, final long compactionJobInfoHandle) throws RocksDBException; private native void cancelAllBackgroundWork(final long handle, final boolean wait); private native void pauseBackgroundWork(final long handle) throws RocksDBException; private native void continueBackgroundWork(final long handle) throws RocksDBException; private native void enableAutoCompaction(final long handle, final long[] columnFamilyHandles) throws RocksDBException; private native int numberLevels(final long handle, final long columnFamilyHandle); private native int maxMemCompactionLevel(final long handle, final long columnFamilyHandle); private native int level0StopWriteTrigger(final long handle, final long columnFamilyHandle); private native String getName(final long handle); private native long getEnv(final long handle); private native void flush(final long handle, final long flushOptHandle, /* @Nullable */ final long[] cfHandles) throws RocksDBException; private native void flushWal(final long handle, final boolean sync) throws RocksDBException; private native void syncWal(final long handle) throws RocksDBException; private native long getLatestSequenceNumber(final long handle); private native boolean setPreserveDeletesSequenceNumber(final long handle, final long sequenceNumber); private native void disableFileDeletions(long handle) throws RocksDBException; private native void enableFileDeletions(long handle, boolean force) throws RocksDBException; private native String[] getLiveFiles(final long handle, final boolean flushMemtable) throws RocksDBException; private native LogFile[] getSortedWalFiles(final long handle) throws RocksDBException; private native long getUpdatesSince(final long handle, final long sequenceNumber) throws RocksDBException; private native void deleteFile(final long handle, final String name) throws RocksDBException; private native LiveFileMetaData[] getLiveFilesMetaData(final long handle); private native ColumnFamilyMetaData getColumnFamilyMetaData( final long handle, final long columnFamilyHandle); private native void ingestExternalFile(final long handle, final long columnFamilyHandle, final String[] filePathList, final int filePathListLen, final long ingestExternalFileOptionsHandle) throws RocksDBException; private native void verifyChecksum(final long handle) throws RocksDBException; private native long getDefaultColumnFamily(final long handle); private native Map<String, TableProperties> getPropertiesOfAllTables( final long handle, final long columnFamilyHandle) throws RocksDBException; private native Map<String, TableProperties> getPropertiesOfTablesInRange( final long handle, final long columnFamilyHandle, final long[] rangeSliceHandles); private native long[] suggestCompactRange(final long handle, final long columnFamilyHandle) throws RocksDBException; private native void promoteL0(final long handle, final long columnFamilyHandle, final int tragetLevel) throws RocksDBException; private native void startTrace(final long handle, final long maxTraceFileSize, final long traceWriterHandle) throws RocksDBException; private native void endTrace(final long handle) throws RocksDBException; private native void tryCatchUpWithPrimary(final long handle) throws RocksDBException; private native void deleteFilesInRanges(long handle, long cfHandle, final byte[][] ranges, boolean include_end) throws RocksDBException; private native static void destroyDB(final String path, final long optionsHandle) throws RocksDBException; private native static int version(); protected DBOptionsInterface options_; private static Version version; public static class Version { private final byte major; private final byte minor; private final byte patch; public Version(final byte major, final byte minor, final byte patch) { this.major = major; this.minor = minor; this.patch = patch; } public int getMajor() { return major; } public int getMinor() { return minor; } public int getPatch() { return patch; } @Override public String toString() { return getMajor() + "." + getMinor() + "." + getPatch(); } private static Version fromEncodedVersion(int encodedVersion) { final byte patch = (byte) (encodedVersion & 0xff); encodedVersion >>= 8; final byte minor = (byte) (encodedVersion & 0xff); encodedVersion >>= 8; final byte major = (byte) (encodedVersion & 0xff); return new Version(major, minor, patch); } } }
facebook/rocksdb
java/src/main/java/org/rocksdb/RocksDB.java
44,948
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderelection.ring; import com.iluwatar.leaderelection.AbstractMessageManager; import com.iluwatar.leaderelection.Instance; import com.iluwatar.leaderelection.Message; import com.iluwatar.leaderelection.MessageType; import java.util.Map; /** * Implementation of RingMessageManager. */ public class RingMessageManager extends AbstractMessageManager { /** * Constructor of RingMessageManager. */ public RingMessageManager(Map<Integer, Instance> instanceMap) { super(instanceMap); } /** * Send heartbeat message to current leader instance to check the health. * * @param leaderId leaderID * @return {@code true} if the leader is alive. */ @Override public boolean sendHeartbeatMessage(int leaderId) { var leaderInstance = instanceMap.get(leaderId); return leaderInstance.isAlive(); } /** * Send election message to the next instance. * * @param currentId currentID * @param content list contains all the IDs of instances which have received this election * message. * @return {@code true} if the election message is accepted by the target instance. */ @Override public boolean sendElectionMessage(int currentId, String content) { var nextInstance = this.findNextInstance(currentId); var electionMessage = new Message(MessageType.ELECTION, content); nextInstance.onMessage(electionMessage); return true; } /** * Send leader message to the next instance. * * @param currentId Instance ID of which sends this message. * @param leaderId Leader message content. * @return {@code true} if the leader message is accepted by the target instance. */ @Override public boolean sendLeaderMessage(int currentId, int leaderId) { var nextInstance = this.findNextInstance(currentId); var leaderMessage = new Message(MessageType.LEADER, String.valueOf(leaderId)); nextInstance.onMessage(leaderMessage); return true; } /** * Send heartbeat invoke message to the next instance. * * @param currentId Instance ID of which sends this message. */ @Override public void sendHeartbeatInvokeMessage(int currentId) { var nextInstance = this.findNextInstance(currentId); var heartbeatInvokeMessage = new Message(MessageType.HEARTBEAT_INVOKE, ""); nextInstance.onMessage(heartbeatInvokeMessage); } }
iluwatar/java-design-patterns
leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingMessageManager.java
44,949
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderelection.bully; import com.iluwatar.leaderelection.AbstractMessageManager; import com.iluwatar.leaderelection.Instance; import com.iluwatar.leaderelection.Message; import com.iluwatar.leaderelection.MessageType; import java.util.List; import java.util.Map; /** * Implementation of BullyMessageManager. */ public class BullyMessageManager extends AbstractMessageManager { /** * Constructor of BullyMessageManager. */ public BullyMessageManager(Map<Integer, Instance> instanceMap) { super(instanceMap); } /** * Send heartbeat message to current leader instance to check the health. * * @param leaderId leaderID * @return {@code true} if the leader is alive. */ @Override public boolean sendHeartbeatMessage(int leaderId) { var leaderInstance = instanceMap.get(leaderId); return leaderInstance.isAlive(); } /** * Send election message to all the instances with smaller ID. * * @param currentId Instance ID of which sends this message. * @param content Election message content. * @return {@code true} if no alive instance has smaller ID, so that the election is accepted. */ @Override public boolean sendElectionMessage(int currentId, String content) { var candidateList = findElectionCandidateInstanceList(currentId); if (candidateList.isEmpty()) { return true; } else { var electionMessage = new Message(MessageType.ELECTION_INVOKE, ""); candidateList.forEach((i) -> instanceMap.get(i).onMessage(electionMessage)); return false; } } /** * Send leader message to all the instances to notify the new leader. * * @param currentId Instance ID of which sends this message. * @param leaderId Leader message content. * @return {@code true} if the message is accepted. */ @Override public boolean sendLeaderMessage(int currentId, int leaderId) { var leaderMessage = new Message(MessageType.LEADER, String.valueOf(leaderId)); instanceMap.keySet() .stream() .filter((i) -> i != currentId) .forEach((i) -> instanceMap.get(i).onMessage(leaderMessage)); return false; } /** * Send heartbeat invoke message to the next instance. * * @param currentId Instance ID of which sends this message. */ @Override public void sendHeartbeatInvokeMessage(int currentId) { var nextInstance = this.findNextInstance(currentId); var heartbeatInvokeMessage = new Message(MessageType.HEARTBEAT_INVOKE, ""); nextInstance.onMessage(heartbeatInvokeMessage); } /** * Find all the alive instances with smaller ID than current instance. * * @param currentId ID of current instance. * @return ID list of all the candidate instance. */ private List<Integer> findElectionCandidateInstanceList(int currentId) { return instanceMap.keySet() .stream() .filter((i) -> i < currentId && instanceMap.get(i).isAlive()) .toList(); } }
iluwatar/java-design-patterns
leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyMessageManager.java
44,950
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.transport; import org.elasticsearch.common.network.NetworkService; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.core.TimeValue; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.function.Function; import static org.elasticsearch.common.settings.Setting.affixKeySetting; import static org.elasticsearch.common.settings.Setting.boolSetting; import static org.elasticsearch.common.settings.Setting.enumSetting; import static org.elasticsearch.common.settings.Setting.intSetting; import static org.elasticsearch.common.settings.Setting.listSetting; import static org.elasticsearch.common.settings.Setting.stringListSetting; import static org.elasticsearch.common.settings.Setting.timeSetting; public final class TransportSettings { public static final String DEFAULT_PROFILE = "default"; public static final String FEATURE_PREFIX = "transport.features"; public static final Setting<List<String>> HOST = stringListSetting("transport.host", Setting.Property.NodeScope); public static final Setting<List<String>> PUBLISH_HOST = listSetting( "transport.publish_host", HOST, Function.identity(), Setting.Property.NodeScope ); public static final Setting.AffixSetting<List<String>> PUBLISH_HOST_PROFILE = affixKeySetting( "transport.profiles.", "publish_host", key -> listSetting(key, PUBLISH_HOST, Function.identity(), Setting.Property.NodeScope) ); public static final Setting<List<String>> BIND_HOST = listSetting( "transport.bind_host", HOST, Function.identity(), Setting.Property.NodeScope ); public static final Setting.AffixSetting<List<String>> BIND_HOST_PROFILE = affixKeySetting( "transport.profiles.", "bind_host", key -> listSetting(key, BIND_HOST, Function.identity(), Setting.Property.NodeScope) ); public static final Setting<String> PORT = new Setting<>( "transport.port", "9300-9399", Function.identity(), Setting.Property.NodeScope ); public static final Setting.AffixSetting<String> PORT_PROFILE = affixKeySetting( "transport.profiles.", "port", key -> new Setting<>(key, PORT, Function.identity(), Setting.Property.NodeScope) ); public static final Setting<Integer> PUBLISH_PORT = intSetting("transport.publish_port", -1, -1, Setting.Property.NodeScope); public static final Setting.AffixSetting<Integer> PUBLISH_PORT_PROFILE = affixKeySetting( "transport.profiles.", "publish_port", key -> intSetting(key, -1, -1, Setting.Property.NodeScope) ); public static final Setting<Compression.Enabled> TRANSPORT_COMPRESS = enumSetting( Compression.Enabled.class, "transport.compress", Compression.Enabled.INDEXING_DATA, Setting.Property.NodeScope ); public static final Setting<Compression.Scheme> TRANSPORT_COMPRESSION_SCHEME = enumSetting( Compression.Scheme.class, "transport.compression_scheme", Compression.Scheme.LZ4, Setting.Property.NodeScope ); // the scheduled internal ping interval setting, defaults to disabled (-1) public static final Setting<TimeValue> PING_SCHEDULE = timeSetting( "transport.ping_schedule", TimeValue.timeValueSeconds(-1), Setting.Property.NodeScope ); public static final Setting<TimeValue> CONNECT_TIMEOUT = timeSetting( "transport.connect_timeout", new TimeValue(30, TimeUnit.SECONDS), Setting.Property.NodeScope ); public static final Setting<Settings> DEFAULT_FEATURES_SETTING = Setting.groupSetting(FEATURE_PREFIX + ".", Setting.Property.NodeScope); // Tcp socket settings public static final Setting<Boolean> TCP_NO_DELAY = boolSetting( "transport.tcp.no_delay", NetworkService.TCP_NO_DELAY, Setting.Property.NodeScope ); public static final Setting.AffixSetting<Boolean> TCP_NO_DELAY_PROFILE = affixKeySetting( "transport.profiles.", "tcp.no_delay", key -> boolSetting(key, TCP_NO_DELAY, Setting.Property.NodeScope) ); public static final Setting<Boolean> TCP_KEEP_ALIVE = boolSetting( "transport.tcp.keep_alive", NetworkService.TCP_KEEP_ALIVE, Setting.Property.NodeScope ); public static final Setting.AffixSetting<Boolean> TCP_KEEP_ALIVE_PROFILE = affixKeySetting( "transport.profiles.", "tcp.keep_alive", key -> boolSetting(key, TCP_KEEP_ALIVE, Setting.Property.NodeScope) ); public static final Setting<Integer> TCP_KEEP_IDLE = intSetting( "transport.tcp.keep_idle", NetworkService.TCP_KEEP_IDLE, -1, 300, Setting.Property.NodeScope ); public static final Setting.AffixSetting<Integer> TCP_KEEP_IDLE_PROFILE = affixKeySetting( "transport.profiles.", "tcp.keep_idle", key -> intSetting(key, TCP_KEEP_IDLE, -1, 300, Setting.Property.NodeScope) ); public static final Setting<Integer> TCP_KEEP_INTERVAL = intSetting( "transport.tcp.keep_interval", NetworkService.TCP_KEEP_INTERVAL, -1, 300, Setting.Property.NodeScope ); public static final Setting.AffixSetting<Integer> TCP_KEEP_INTERVAL_PROFILE = affixKeySetting( "transport.profiles.", "tcp.keep_interval", key -> intSetting(key, TCP_KEEP_INTERVAL, -1, 300, Setting.Property.NodeScope) ); public static final Setting<Integer> TCP_KEEP_COUNT = intSetting( "transport.tcp.keep_count", NetworkService.TCP_KEEP_COUNT, -1, Setting.Property.NodeScope ); public static final Setting.AffixSetting<Integer> TCP_KEEP_COUNT_PROFILE = affixKeySetting( "transport.profiles.", "tcp.keep_count", key -> intSetting(key, TCP_KEEP_COUNT, -1, Setting.Property.NodeScope) ); public static final Setting<Boolean> TCP_REUSE_ADDRESS = boolSetting( "transport.tcp.reuse_address", NetworkService.TCP_REUSE_ADDRESS, Setting.Property.NodeScope ); public static final Setting.AffixSetting<Boolean> TCP_REUSE_ADDRESS_PROFILE = affixKeySetting( "transport.profiles.", "tcp.reuse_address", key -> boolSetting(key, TCP_REUSE_ADDRESS, Setting.Property.NodeScope) ); public static final Setting<ByteSizeValue> TCP_SEND_BUFFER_SIZE = Setting.byteSizeSetting( "transport.tcp.send_buffer_size", NetworkService.TCP_SEND_BUFFER_SIZE, Setting.Property.NodeScope ); public static final Setting.AffixSetting<ByteSizeValue> TCP_SEND_BUFFER_SIZE_PROFILE = affixKeySetting( "transport.profiles.", "tcp.send_buffer_size", key -> Setting.byteSizeSetting(key, TCP_SEND_BUFFER_SIZE, Setting.Property.NodeScope) ); public static final Setting<ByteSizeValue> TCP_RECEIVE_BUFFER_SIZE = Setting.byteSizeSetting( "transport.tcp.receive_buffer_size", NetworkService.TCP_RECEIVE_BUFFER_SIZE, Setting.Property.NodeScope ); public static final Setting.AffixSetting<ByteSizeValue> TCP_RECEIVE_BUFFER_SIZE_PROFILE = affixKeySetting( "transport.profiles.", "tcp.receive_buffer_size", key -> Setting.byteSizeSetting(key, TCP_RECEIVE_BUFFER_SIZE, Setting.Property.NodeScope) ); // Connections per node settings public static final Setting<Integer> CONNECTIONS_PER_NODE_RECOVERY = intSetting( "transport.connections_per_node.recovery", 2, 1, Setting.Property.NodeScope ); public static final Setting<Integer> CONNECTIONS_PER_NODE_BULK = intSetting( "transport.connections_per_node.bulk", 3, 1, Setting.Property.NodeScope ); public static final Setting<Integer> CONNECTIONS_PER_NODE_REG = intSetting( "transport.connections_per_node.reg", 6, 1, Setting.Property.NodeScope ); public static final Setting<Integer> CONNECTIONS_PER_NODE_STATE = intSetting( "transport.connections_per_node.state", 1, 1, Setting.Property.NodeScope ); public static final Setting<Integer> CONNECTIONS_PER_NODE_PING = intSetting( "transport.connections_per_node.ping", 1, 1, Setting.Property.NodeScope ); // Tracer settings public static final Setting<List<String>> TRACE_LOG_INCLUDE_SETTING = stringListSetting( "transport.tracer.include", Setting.Property.Dynamic, Setting.Property.NodeScope ); public static final Setting<List<String>> TRACE_LOG_EXCLUDE_SETTING = stringListSetting( "transport.tracer.exclude", List.of("internal:coordination/fault_detection/*"), Setting.Property.Dynamic, Setting.Property.NodeScope ); // Time that processing an inbound message on a transport thread may take at the most before a warning is logged public static final Setting<TimeValue> SLOW_OPERATION_THRESHOLD_SETTING = Setting.positiveTimeSetting( "transport.slow_operation_logging_threshold", TimeValue.timeValueSeconds(5), Setting.Property.Dynamic, Setting.Property.NodeScope ); // only used in tests: RST connections when closing to avoid actively closing sockets to end up in time_wait in tests public static final Setting<Boolean> RST_ON_CLOSE = boolSetting("transport.rst_on_close", false, Setting.Property.NodeScope); private TransportSettings() {} }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/transport/TransportSettings.java
44,951
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderelection.ring; import com.iluwatar.leaderelection.Instance; import com.iluwatar.leaderelection.Message; import com.iluwatar.leaderelection.MessageType; import java.util.HashMap; import java.util.Map; /** * Example of how to use ring leader election. Initially 5 instances is created in the clould * system, and the instance with ID 1 is set as leader. After the system is started stop the leader * instance, and the new leader will be elected. */ public class RingApp { /** * Program entry point. */ public static void main(String[] args) { Map<Integer, Instance> instanceMap = new HashMap<>(); var messageManager = new RingMessageManager(instanceMap); var instance1 = new RingInstance(messageManager, 1, 1); var instance2 = new RingInstance(messageManager, 2, 1); var instance3 = new RingInstance(messageManager, 3, 1); var instance4 = new RingInstance(messageManager, 4, 1); var instance5 = new RingInstance(messageManager, 5, 1); instanceMap.put(1, instance1); instanceMap.put(2, instance2); instanceMap.put(3, instance3); instanceMap.put(4, instance4); instanceMap.put(5, instance5); instance2.onMessage(new Message(MessageType.HEARTBEAT_INVOKE, "")); final var thread1 = new Thread(instance1); final var thread2 = new Thread(instance2); final var thread3 = new Thread(instance3); final var thread4 = new Thread(instance4); final var thread5 = new Thread(instance5); thread1.start(); thread2.start(); thread3.start(); thread4.start(); thread5.start(); instance1.setAlive(false); } }
iluwatar/java-design-patterns
leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingApp.java
44,952
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.inject; import com.google.inject.binder.AnnotatedBindingBuilder; import com.google.inject.binder.AnnotatedConstantBindingBuilder; import com.google.inject.binder.LinkedBindingBuilder; import com.google.inject.matcher.Matcher; import com.google.inject.spi.Dependency; import com.google.inject.spi.Message; import com.google.inject.spi.ModuleAnnotatedMethodScanner; import com.google.inject.spi.ProvisionListener; import com.google.inject.spi.TypeConverter; import com.google.inject.spi.TypeListener; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import org.aopalliance.intercept.MethodInterceptor; /** * Collects configuration information (primarily <i>bindings</i>) which will be used to create an * {@link Injector}. Guice provides this object to your application's {@link Module} implementors so * they may each contribute their own bindings and other registrations. * * <h3>The Guice Binding EDSL</h3> * * Guice uses an <i>embedded domain-specific language</i>, or EDSL, to help you create bindings * simply and readably. This approach is great for overall usability, but it does come with a small * cost: <b>it is difficult to learn how to use the Binding EDSL by reading method-level * javadocs</b>. Instead, you should consult the series of examples below. To save space, these * examples omit the opening {@code binder}, just as you will if your module extends {@link * AbstractModule}. * * <pre> * bind(ServiceImpl.class);</pre> * * This statement mostly does nothing; it "binds the {@code ServiceImpl} class to itself". You may * still want to use this if you prefer your {@link Module} class to serve as an explicit * <i>manifest</i> for the services it provides. In rare cases, Guice may be unable to validate a * binding at injector creation time unless it is given explicitly. When using hierarchical * injectors (via {@code Binder.newPrivateBinder}, {@code Binder.PrivateModule}, or {@code * Injector.createChildInjector}), this guidance changes: see the note on hierarchical injectors in * {@link Injector.createChildInjector}. * * <pre> * bind(Service.class).to(ServiceImpl.class);</pre> * * Specifies that a request for a {@code Service} instance with no binding annotations should be * treated as if it were a request for a {@code ServiceImpl} instance. This <i>overrides</i> the * function of any {@link ImplementedBy @ImplementedBy} or {@link ProvidedBy @ProvidedBy} * annotations found on {@code Service}, since Guice will have already "moved on" to {@code * ServiceImpl} before it reaches the point when it starts looking for these annotations. * * <pre> * bind(Service.class).toProvider(ServiceProvider.class);</pre> * * In this example, {@code ServiceProvider} must extend or implement {@code Provider<Service>}. This * binding specifies that Guice should resolve an unannotated injection request for {@code Service} * by first resolving an instance of {@code ServiceProvider} in the regular way, then calling {@link * Provider#get get()} on the resulting Provider instance to obtain the {@code Service} instance. * * <p>The {@link Provider} you use here does not have to be a "factory"; that is, a provider which * always <i>creates</i> each instance it provides. However, this is generally a good practice to * follow. You can then use Guice's concept of {@link Scope scopes} to guide when creation should * happen -- "letting Guice work for you". * * <pre> * bind(Service.class).annotatedWith(Red.class).to(ServiceImpl.class);</pre> * * Like the previous example, but only applies to injection requests that use the binding annotation * {@code @Red}. If your module also includes bindings for particular <i>values</i> of the * {@code @Red} annotation (see below), then this binding will serve as a "catch-all" for any values * of {@code @Red} that have no exact match in the bindings. * * <pre> * bind(ServiceImpl.class).in(Singleton.class); * // or, alternatively * bind(ServiceImpl.class).in(Scopes.SINGLETON);</pre> * * Either of these statements places the {@code ServiceImpl} class into singleton scope. Guice will * create only one instance of {@code ServiceImpl} and will reuse it for all injection requests of * this type. Note that it is still possible to bind another instance of {@code ServiceImpl} if the * second binding is qualified by an annotation as in the previous example. Guice is not overly * concerned with <i>preventing</i> you from creating multiple instances of your "singletons", only * with <i>enabling</i> your application to share only one instance if that's all you tell Guice you * need. * * <p><b>Note:</b> a scope specified in this way <i>overrides</i> any scope that was specified with * an annotation on the {@code ServiceImpl} class. * * <p>Besides {@link Singleton}/{@link Scopes#SINGLETON}, there are servlet-specific scopes * available in {@code com.google.inject.servlet.ServletScopes}, and your Modules can contribute * their own custom scopes for use here as well. * * <pre>{@code * bind(new TypeLiteral<PaymentService<CreditCard>>() {}) * .to(CreditCardPaymentService.class); * }</pre> * * This admittedly odd construct is the way to bind a parameterized type. It tells Guice how to * honor an injection request for an element of type {@code PaymentService<CreditCard>}. The class * {@code CreditCardPaymentService} must implement the {@code PaymentService<CreditCard>} interface. * Guice cannot currently bind or inject a generic type, such as {@code Set<E>}; all type parameters * must be fully specified. * * <pre> * bind(Service.class).toInstance(new ServiceImpl()); * // or, alternatively * bind(Service.class).toInstance(SomeLegacyRegistry.getService());</pre> * * In this example, your module itself, <i>not Guice</i>, takes responsibility for obtaining a * {@code ServiceImpl} instance, then asks Guice to always use this single instance to fulfill all * {@code Service} injection requests. When the {@link Injector} is created, it will automatically * perform field and method injection for this instance, but any injectable constructor on {@code * ServiceImpl} is simply ignored. Note that using this approach results in "eager loading" behavior * that you can't control. * * <pre> * bindConstant().annotatedWith(ServerHost.class).to(args[0]);</pre> * * Sets up a constant binding. Constant injections must always be annotated. When a constant * binding's value is a string, it is eligible for conversion to all primitive types, to {@link * Enum#valueOf(Class, String) all enums}, and to {@link Class#forName class literals}. Conversions * for other types can be configured using {@link #convertToTypes(Matcher, TypeConverter) * convertToTypes()}. * * <pre> * {@literal @}Color("red") Color red; // A member variable (field) * . . . * red = MyModule.class.getDeclaredField("red").getAnnotation(Color.class); * bind(Service.class).annotatedWith(red).to(RedService.class);</pre> * * If your binding annotation has parameters you can apply different bindings to different specific * values of your annotation. Getting your hands on the right instance of the annotation is a bit of * a pain -- one approach, shown above, is to apply a prototype annotation to a field in your module * class, so that you can read this annotation instance and give it to Guice. * * <pre> * bind(Service.class) * .annotatedWith(Names.named("blue")) * .to(BlueService.class);</pre> * * Differentiating by names is a common enough use case that we provided a standard annotation, * {@link com.google.inject.name.Named @Named}. Because of Guice's library support, binding by name * is quite easier than in the arbitrary binding annotation case we just saw. However, remember that * these names will live in a single flat namespace with all the other names used in your * application. * * <pre>{@code * Constructor<T> loneCtor = getLoneCtorFromServiceImplViaReflection(); * bind(ServiceImpl.class) * .toConstructor(loneCtor); * }</pre> * * In this example, we directly tell Guice which constructor to use in a concrete class * implementation. It means that we do not need to place {@literal @}Inject on any of the * constructors and that Guice treats the provided constructor as though it were annotated so. It is * useful for cases where you cannot modify existing classes and is a bit simpler than using a * {@link Provider}. * * <p>The above list of examples is far from exhaustive. If you can think of how the concepts of one * example might coexist with the concepts from another, you can most likely weave the two together. * If the two concepts make no sense with each other, you most likely won't be able to do it. In a * few cases Guice will let something bogus slip by, and will then inform you of the problems at * runtime, as soon as you try to create your Injector. * * <p>The other methods of Binder such as {@link #bindScope}, {@link #bindInterceptor}, {@link * #install}, {@link #requestStaticInjection}, {@link #addError} and {@link #currentStage} are not * part of the Binding EDSL; you can learn how to use these in the usual way, from the method * documentation. * * @author [email protected] (Bob Lee) * @author [email protected] (Jesse Wilson) * @author [email protected] (Kevin Bourrillion) */ public interface Binder { /** * Binds method interceptor[s] to methods matched by class and method matchers. A method is * eligible for interception if: * * <ul> * <li>Guice created the instance the method is on * <li>Neither the enclosing type nor the method is final * <li>And the method is package-private, protected, or public * </ul> * * <p>Note: this API only works if {@code guice_bytecode_gen_option} is set to {@code ENABLED}. * * @param classMatcher matches classes the interceptor should apply to. For example: {@code * only(Runnable.class)}. * @param methodMatcher matches methods the interceptor should apply to. For example: {@code * annotatedWith(Transactional.class)}. * @param interceptors to bind. The interceptors are called in the order they are given. */ void bindInterceptor( Matcher<? super Class<?>> classMatcher, Matcher<? super Method> methodMatcher, MethodInterceptor... interceptors); /** Binds a scope to an annotation. */ void bindScope(Class<? extends Annotation> annotationType, Scope scope); /** See the EDSL examples at {@link Binder}. */ <T> LinkedBindingBuilder<T> bind(Key<T> key); /** See the EDSL examples at {@link Binder}. */ <T> AnnotatedBindingBuilder<T> bind(TypeLiteral<T> typeLiteral); /** See the EDSL examples at {@link Binder}. */ <T> AnnotatedBindingBuilder<T> bind(Class<T> type); /** See the EDSL examples at {@link Binder}. */ AnnotatedConstantBindingBuilder bindConstant(); /** * Upon successful creation, the {@link Injector} will inject instance fields and methods of the * given object. * * @param type of instance * @param instance for which members will be injected * @since 2.0 */ <T> void requestInjection(TypeLiteral<T> type, T instance); /** * Upon successful creation, the {@link Injector} will inject instance fields and methods of the * given object. * * @param instance for which members will be injected * @since 2.0 */ void requestInjection(Object instance); /** * Upon successful creation, the {@link Injector} will inject static fields and methods in the * given classes. * * @param types for which static members will be injected */ void requestStaticInjection(Class<?>... types); /** Uses the given module to configure more bindings. */ void install(Module module); /** Gets the current stage. */ Stage currentStage(); /** * Records an error message which will be presented to the user at a later time. Unlike throwing * an exception, this enable us to continue configuring the Injector and discover more errors. * Uses {@link String#format(String, Object[])} to insert the arguments into the message. */ void addError(String message, Object... arguments); /** * Records an exception, the full details of which will be logged, and the message of which will * be presented to the user at a later time. If your Module calls something that you worry may * fail, you should catch the exception and pass it into this. */ void addError(Throwable t); /** * Records an error message to be presented to the user at a later time. * * @since 2.0 */ void addError(Message message); /** * Returns the provider used to obtain instances for the given injection key. The returned * provider will not be valid until the {@link Injector} has been created. The provider will throw * an {@code IllegalStateException} if you try to use it beforehand. * * @since 2.0 */ <T> Provider<T> getProvider(Key<T> key); /** * Returns the provider used to obtain instances for the given injection key. The returned * provider will be attached to the injection point and will follow the nullability specified in * the dependency. Additionally, the returned provider will not be valid until the {@link * Injector} has been created. The provider will throw an {@code IllegalStateException} if you try * to use it beforehand. * * @since 4.0 */ <T> Provider<T> getProvider(Dependency<T> dependency); /** * Returns the provider used to obtain instances for the given injection type. The returned * provider will not be valid until the {@link Injector} has been created. The provider will throw * an {@code IllegalStateException} if you try to use it beforehand. * * @since 2.0 */ <T> Provider<T> getProvider(Class<T> type); /** * Returns the members injector used to inject dependencies into methods and fields on instances * of the given type {@code T}. The returned members injector will not be valid until the main * {@link Injector} has been created. The members injector will throw an {@code * IllegalStateException} if you try to use it beforehand. * * @param typeLiteral type to get members injector for * @since 2.0 */ <T> MembersInjector<T> getMembersInjector(TypeLiteral<T> typeLiteral); /** * Returns the members injector used to inject dependencies into methods and fields on instances * of the given type {@code T}. The returned members injector will not be valid until the main * {@link Injector} has been created. The members injector will throw an {@code * IllegalStateException} if you try to use it beforehand. * * @param type type to get members injector for * @since 2.0 */ <T> MembersInjector<T> getMembersInjector(Class<T> type); /** * Binds a type converter. The injector will use the given converter to convert string constants * to matching types as needed. * * @param typeMatcher matches types the converter can handle * @param converter converts values * @since 2.0 */ void convertToTypes(Matcher<? super TypeLiteral<?>> typeMatcher, TypeConverter converter); /** * Registers a listener for injectable types. Guice will notify the listener when it encounters * injectable types matched by the given type matcher. * * @param typeMatcher that matches injectable types the listener should be notified of * @param listener for injectable types matched by typeMatcher * @since 2.0 */ void bindListener(Matcher<? super TypeLiteral<?>> typeMatcher, TypeListener listener); /** * Registers listeners for provisioned objects. Guice will notify the listeners just before and * after the object is provisioned. Provisioned objects that are also injectable (everything * except objects provided through Providers) can also be notified through TypeListeners * registered in {@link #bindListener}. * * @param bindingMatcher that matches bindings of provisioned objects the listener should be * notified of * @param listeners for provisioned objects matched by bindingMatcher * @since 4.0 */ void bindListener(Matcher<? super Binding<?>> bindingMatcher, ProvisionListener... listeners); /** * Returns a binder that uses {@code source} as the reference location for configuration errors. * This is typically a {@link StackTraceElement} for {@code .java} source but it could any binding * source, such as the path to a {@code .properties} file. * * @param source any object representing the source location and has a concise {@link * Object#toString() toString()} value * @return a binder that shares its configuration with this binder * @since 2.0 */ Binder withSource(Object source); /** * Returns a binder that skips {@code classesToSkip} when identify the calling code. The caller's * {@link StackTraceElement} is used to locate the source of configuration errors. * * @param classesToSkip library classes that create bindings on behalf of their clients. * @return a binder that shares its configuration with this binder. * @since 2.0 */ Binder skipSources(Class<?>... classesToSkip); /** * Creates a new private child environment for bindings and other configuration. The returned * binder can be used to add and configuration information in this environment. See {@link * PrivateModule} for details. * * @return a binder that inherits configuration from this binder. Only exposed configuration on * the returned binder will be visible to this binder. * @since 2.0 */ PrivateBinder newPrivateBinder(); /** * Instructs the Injector that bindings must be listed in a Module in order to be injected. * Classes that are not explicitly bound in a module cannot be injected. Bindings created through * a linked binding (<code>bind(Foo.class).to(FooImpl.class)</code>) are allowed, but the implicit * binding (<code>FooImpl</code>) cannot be directly injected unless it is also explicitly bound ( * <code>bind(FooImpl.class)</code>). * * <p>Tools can still retrieve bindings for implicit bindings (bindings created through a linked * binding) if explicit bindings are required, however {@link Binding#getProvider} will fail. * * <p>By default, explicit bindings are not required. * * <p>If a parent injector requires explicit bindings, then all child injectors (and private * modules within that injector) also require explicit bindings. If a parent does not require * explicit bindings, a child injector or private module may optionally declare itself as * requiring explicit bindings. If it does, the behavior is limited only to that child or any * grandchildren. No siblings of the child will require explicit bindings. * * <p>In the absence of an explicit binding for the target, linked bindings in child injectors * create a binding for the target in the parent. Since this behavior can be surprising, it causes * an error instead if explicit bindings are required. To avoid this error, add an explicit * binding for the target, either in the child or the parent. * * @since 3.0 */ void requireExplicitBindings(); /** * Prevents Guice from injecting dependencies that form a cycle, unless broken by a {@link * Provider}. By default, circular dependencies are not disabled. * * <p>If a parent injector disables circular dependencies, then all child injectors (and private * modules within that injector) also disable circular dependencies. If a parent does not disable * circular dependencies, a child injector or private module may optionally declare itself as * disabling circular dependencies. If it does, the behavior is limited only to that child or any * grandchildren. No siblings of the child will disable circular dependencies. * * @since 3.0 */ void disableCircularProxies(); /** * Requires that a {@literal @}{@link Inject} annotation exists on a constructor in order for * Guice to consider it an eligible injectable class. By default, Guice will inject classes that * have a no-args constructor if no {@literal @}{@link Inject} annotation exists on any * constructor. * * <p>If the class is bound using {@link LinkedBindingBuilder#toConstructor}, Guice will still * inject that constructor regardless of annotations. * * @since 4.0 */ void requireAtInjectOnConstructors(); /** * Requires that Guice finds an exactly matching binding annotation. This disables the error-prone * feature in Guice where it can substitute a binding for <code>{@literal @}Named Foo</code> when * attempting to inject <code>{@literal @}Named("foo") Foo</code>. * * @since 4.0 */ void requireExactBindingAnnotations(); /** * Adds a scanner that will look in all installed modules for annotations the scanner can parse, * and binds them like {@literal @}Provides methods. Scanners apply to all modules installed in * the injector. Scanners installed in child injectors or private modules do not impact modules in * siblings or parents, however scanners installed in parents do apply to all child injectors and * private modules. * * @since 4.0 */ void scanModulesForAnnotatedMethods(ModuleAnnotatedMethodScanner scanner); }
google/guice
core/src/com/google/inject/Binder.java
44,953
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.lockableobject; import com.iluwatar.lockableobject.domain.Creature; import com.iluwatar.lockableobject.domain.Elf; import com.iluwatar.lockableobject.domain.Feind; import com.iluwatar.lockableobject.domain.Human; import com.iluwatar.lockableobject.domain.Orc; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; /** * The Lockable Object pattern is a concurrency pattern. Instead of using the "synchronized" word * upon the methods to be synchronized, the object which implements the Lockable interface handles * the request. * * <p>In this example, we create a new Lockable object with the SwordOfAragorn implementation of it. * Afterward we create 6 Creatures with the Elf, Orc and Human implementations and assign them each * to a Fiend object and the Sword is the target object. Because there is only one Sword, and it uses * the Lockable Object pattern, only one creature can hold the sword at a given time. When the sword * is locked, any other alive Fiends will try to lock, which will result in a race to lock the * sword. * * @author Noam Greenshtain */ @Slf4j public class App implements Runnable { private static final int WAIT_TIME = 3; private static final int WORKERS = 2; private static final int MULTIPLICATION_FACTOR = 3; /** * main method. * * @param args as arguments for the main method. */ public static void main(String[] args) { var app = new App(); app.run(); } @Override public void run() { // The target object for this example. var sword = new SwordOfAragorn(); // Creation of creatures. List<Creature> creatures = new ArrayList<>(); for (var i = 0; i < WORKERS; i++) { creatures.add(new Elf(String.format("Elf %s", i))); creatures.add(new Orc(String.format("Orc %s", i))); creatures.add(new Human(String.format("Human %s", i))); } int totalFiends = WORKERS * MULTIPLICATION_FACTOR; ExecutorService service = Executors.newFixedThreadPool(totalFiends); // Attach every creature and the sword is a Fiend to fight for the sword. for (var i = 0; i < totalFiends; i = i + MULTIPLICATION_FACTOR) { service.submit(new Feind(creatures.get(i), sword)); service.submit(new Feind(creatures.get(i + 1), sword)); service.submit(new Feind(creatures.get(i + 2), sword)); } // Wait for program to terminate. try { if (!service.awaitTermination(WAIT_TIME, TimeUnit.SECONDS)) { LOGGER.info("The master of the sword is now {}.", sword.getLocker().getName()); } } catch (InterruptedException e) { LOGGER.error(e.getMessage()); Thread.currentThread().interrupt(); } finally { service.shutdown(); } } }
iluwatar/java-design-patterns
lockable-object/src/main/java/com/iluwatar/lockableobject/App.java
44,954
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderelection.bully; import com.iluwatar.leaderelection.Instance; import com.iluwatar.leaderelection.Message; import com.iluwatar.leaderelection.MessageType; import java.util.HashMap; import java.util.Map; /** * Example of how to use bully leader election. Initially 5 instances is created in the clould * system, and the instance with ID 1 is set as leader. After the system is started stop the leader * instance, and the new leader will be elected. */ public class BullyApp { /** * Program entry point. */ public static void main(String[] args) { Map<Integer, Instance> instanceMap = new HashMap<>(); var messageManager = new BullyMessageManager(instanceMap); var instance1 = new BullyInstance(messageManager, 1, 1); var instance2 = new BullyInstance(messageManager, 2, 1); var instance3 = new BullyInstance(messageManager, 3, 1); var instance4 = new BullyInstance(messageManager, 4, 1); var instance5 = new BullyInstance(messageManager, 5, 1); instanceMap.put(1, instance1); instanceMap.put(2, instance2); instanceMap.put(3, instance3); instanceMap.put(4, instance4); instanceMap.put(5, instance5); instance4.onMessage(new Message(MessageType.HEARTBEAT_INVOKE, "")); final var thread1 = new Thread(instance1); final var thread2 = new Thread(instance2); final var thread3 = new Thread(instance3); final var thread4 = new Thread(instance4); final var thread5 = new Thread(instance5); thread1.start(); thread2.start(); thread3.start(); thread4.start(); thread5.start(); instance1.setAlive(false); } }
iluwatar/java-design-patterns
leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyApp.java
44,955
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.inject; import static com.google.common.base.Preconditions.checkState; import com.google.inject.binder.AnnotatedBindingBuilder; import com.google.inject.binder.AnnotatedConstantBindingBuilder; import com.google.inject.binder.AnnotatedElementBuilder; import com.google.inject.binder.LinkedBindingBuilder; import com.google.inject.matcher.Matcher; import com.google.inject.spi.Message; import com.google.inject.spi.ProvisionListener; import com.google.inject.spi.TypeConverter; import com.google.inject.spi.TypeListener; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import org.aopalliance.intercept.MethodInterceptor; /** * A module whose configuration information is hidden from its environment by default. Only bindings * that are explicitly exposed will be available to other modules and to the users of the injector. * This module may expose the bindings it creates and the bindings of the modules it installs. * * <p>A private module can be nested within a regular module or within another private module using * {@link Binder#install install()}. Its bindings live in a new environment that inherits bindings, * type converters, scopes, and interceptors from the surrounding ("parent") environment. When you * nest multiple private modules, the result is a tree of environments where the injector's * environment is the root. * * <p>Guice EDSL bindings can be exposed with {@link #expose(Class) expose()}. {@literal @}{@link * com.google.inject.Provides Provides} bindings can be exposed with the {@literal @}{@link Exposed} * annotation: * * <pre> * public class FooBarBazModule extends PrivateModule { * protected void configure() { * bind(Foo.class).to(RealFoo.class); * expose(Foo.class); * * install(new TransactionalBarModule()); * expose(Bar.class).annotatedWith(Transactional.class); * * bind(SomeImplementationDetail.class); * install(new MoreImplementationDetailsModule()); * } * * {@literal @}Provides {@literal @}Exposed * public Baz provideBaz() { * return new SuperBaz(); * } * } * </pre> * * <p>Private modules are implemented using {@link Injector#createChildInjector(Module[]) parent * injectors}. When it can satisfy their dependencies, just-in-time bindings will be created in the * root environment. Such bindings are shared among all environments in the tree. See the note in * {@code createChildInjector} about how hierarchical injectors change the importance of otherwise * unnecessary binding statements (such as {@code bind(ServiceImpl.class);}). * * <p>The scope of a binding is constrained to its environment. A singleton bound in a private * module will be unique to its environment. But a binding for the same type in a different private * module will yield a different instance. * * <p>A shared binding that injects the {@code Injector} gets the root injector, which only has * access to bindings in the root environment. An explicit binding that injects the {@code Injector} * gets access to all bindings in the child environment. * * <p>To promote a just-in-time binding to an explicit binding, bind it: * * <pre> * bind(FooImpl.class); * </pre> * * @author [email protected] (Jesse Wilson) * @since 2.0 */ public abstract class PrivateModule implements Module { /** Like abstract module, the binder of the current private module */ private PrivateBinder binder; @Override public final synchronized void configure(Binder binder) { checkState(this.binder == null, "Re-entry is not allowed."); // Guice treats PrivateModules specially and passes in a PrivateBinder automatically. this.binder = (PrivateBinder) binder.skipSources(PrivateModule.class); try { configure(); } finally { this.binder = null; } } /** * Creates bindings and other configurations private to this module. Use {@link #expose(Class) * expose()} to make the bindings in this module available externally. */ protected abstract void configure(); /** Makes the binding for {@code key} available to other modules and the injector. */ protected final <T> void expose(Key<T> key) { binder().expose(key); } /** * Makes a binding for {@code type} available to other modules and the injector. Use {@link * AnnotatedElementBuilder#annotatedWith(Class) annotatedWith()} to expose {@code type} with a * binding annotation. */ protected final AnnotatedElementBuilder expose(Class<?> type) { return binder().expose(type); } /** * Makes a binding for {@code type} available to other modules and the injector. Use {@link * AnnotatedElementBuilder#annotatedWith(Class) annotatedWith()} to expose {@code type} with a * binding annotation. */ protected final AnnotatedElementBuilder expose(TypeLiteral<?> type) { return binder().expose(type); } // everything below is copied from AbstractModule /** Returns the current binder. */ protected PrivateBinder binder() { checkState(binder != null, "The binder can only be used inside configure()"); return binder; } /** @see Binder#bindScope(Class, Scope) */ protected final void bindScope(Class<? extends Annotation> scopeAnnotation, Scope scope) { binder().bindScope(scopeAnnotation, scope); } /** @see Binder#bind(Key) */ protected final <T> LinkedBindingBuilder<T> bind(Key<T> key) { return binder().bind(key); } /** @see Binder#bind(TypeLiteral) */ protected final <T> AnnotatedBindingBuilder<T> bind(TypeLiteral<T> typeLiteral) { return binder().bind(typeLiteral); } /** @see Binder#bind(Class) */ protected final <T> AnnotatedBindingBuilder<T> bind(Class<T> clazz) { return binder().bind(clazz); } /** @see Binder#bindConstant() */ protected final AnnotatedConstantBindingBuilder bindConstant() { return binder().bindConstant(); } /** @see Binder#install(Module) */ protected final void install(Module module) { binder().install(module); } /** @see Binder#addError(String, Object[]) */ protected final void addError(String message, Object... arguments) { binder().addError(message, arguments); } /** @see Binder#addError(Throwable) */ protected final void addError(Throwable t) { binder().addError(t); } /** @see Binder#addError(Message) */ protected final void addError(Message message) { binder().addError(message); } /** @see Binder#requestInjection(Object) */ protected final void requestInjection(Object instance) { binder().requestInjection(instance); } /** @see Binder#requestStaticInjection(Class[]) */ protected final void requestStaticInjection(Class<?>... types) { binder().requestStaticInjection(types); } /** * @see Binder#bindInterceptor(com.google.inject.matcher.Matcher, * com.google.inject.matcher.Matcher, org.aopalliance.intercept.MethodInterceptor[]) */ protected final void bindInterceptor( Matcher<? super Class<?>> classMatcher, Matcher<? super Method> methodMatcher, MethodInterceptor... interceptors) { binder().bindInterceptor(classMatcher, methodMatcher, interceptors); } /** Instructs Guice to require a binding to the given key. */ protected final void requireBinding(Key<?> key) { binder().getProvider(key); } /** Instructs Guice to require a binding to the given type. */ protected final void requireBinding(Class<?> type) { binder().getProvider(type); } /** @see Binder#getProvider(Key) */ protected final <T> Provider<T> getProvider(Key<T> key) { return binder().getProvider(key); } /** @see Binder#getProvider(Class) */ protected final <T> Provider<T> getProvider(Class<T> type) { return binder().getProvider(type); } /** * @see Binder#convertToTypes(com.google.inject.matcher.Matcher, * com.google.inject.spi.TypeConverter) */ protected final void convertToTypes( Matcher<? super TypeLiteral<?>> typeMatcher, TypeConverter converter) { binder().convertToTypes(typeMatcher, converter); } /** @see Binder#currentStage() */ protected final Stage currentStage() { return binder().currentStage(); } /** @see Binder#getMembersInjector(Class) */ protected <T> MembersInjector<T> getMembersInjector(Class<T> type) { return binder().getMembersInjector(type); } /** @see Binder#getMembersInjector(TypeLiteral) */ protected <T> MembersInjector<T> getMembersInjector(TypeLiteral<T> type) { return binder().getMembersInjector(type); } /** * @see Binder#bindListener(com.google.inject.matcher.Matcher, com.google.inject.spi.TypeListener) */ protected void bindListener(Matcher<? super TypeLiteral<?>> typeMatcher, TypeListener listener) { binder().bindListener(typeMatcher, listener); } /** * @see Binder#bindListener(Matcher, ProvisionListener...) * @since 4.0 */ protected void bindListener( Matcher<? super Binding<?>> bindingMatcher, ProvisionListener... listeners) { binder().bindListener(bindingMatcher, listeners); } }
google/guice
core/src/com/google/inject/PrivateModule.java
44,956
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config; import org.apache.dubbo.config.support.Parameter; import java.util.ArrayList; import java.util.Arrays; /** * The service provider default configuration * * @export * @see org.apache.dubbo.config.ProtocolConfig * @see ServiceConfigBase */ public class ProviderConfig extends AbstractServiceConfig { private static final long serialVersionUID = 6913423882496634749L; // ======== protocol default values, it'll take effect when protocol's attributes are not set ======== /** * Service ip addresses (used when there are multiple network cards available) */ private String host; /** * Service port */ private Integer port; /** * Context path */ private String contextpath; /** * Thread pool */ private String threadpool; /** * Thread pool name */ private String threadname; /** * Thread pool size (fixed size) */ private Integer threads; /** * IO thread pool size (fixed size) */ private Integer iothreads; /** * Thread pool keepAliveTime, default unit TimeUnit.MILLISECONDS */ private Integer alive; /** * Thread pool queue length */ private Integer queues; /** * Max acceptable connections */ private Integer accepts; /** * Protocol codec */ private String codec; /** * The serialization charset */ private String charset; /** * Payload max length */ private Integer payload; /** * The network io buffer size */ private Integer buffer; /** * Transporter */ private String transporter; /** * How information gets exchanged */ private String exchanger; /** * Thread dispatching mode */ private String dispatcher; /** * Networker */ private String networker; /** * The server-side implementation model of the protocol */ private String server; /** * The client-side implementation model of the protocol */ private String client; /** * Supported telnet commands, separated with comma. */ private String telnet; /** * Command line prompt */ private String prompt; /** * Status check */ private String status; /** * Wait time when stop */ private Integer wait; @Deprecated public void setProtocol(String protocol) { this.protocols = new ArrayList<>(Arrays.asList(new ProtocolConfig(protocol))); } @Override @Parameter(excluded = true) public Boolean isDefault() { return isDefault; } @Parameter(excluded = true) public String getHost() { return host; } public void setHost(String host) { this.host = host; } @Parameter(excluded = true) public Integer getPort() { return port; } @Deprecated public void setPort(Integer port) { this.port = port; } @Deprecated @Parameter(excluded = true) public String getPath() { return getContextpath(); } @Deprecated public void setPath(String path) { setContextpath(path); } @Parameter(excluded = true) public String getContextpath() { return contextpath; } public void setContextpath(String contextpath) { this.contextpath = contextpath; } public String getThreadpool() { return threadpool; } public void setThreadpool(String threadpool) { this.threadpool = threadpool; } public String getThreadname() { return threadname; } public void setThreadname(String threadname) { this.threadname = threadname; } public Integer getThreads() { return threads; } public void setThreads(Integer threads) { this.threads = threads; } public Integer getIothreads() { return iothreads; } public void setIothreads(Integer iothreads) { this.iothreads = iothreads; } public Integer getAlive() { return alive; } public void setAlive(Integer alive) { this.alive = alive; } public Integer getQueues() { return queues; } public void setQueues(Integer queues) { this.queues = queues; } public Integer getAccepts() { return accepts; } public void setAccepts(Integer accepts) { this.accepts = accepts; } public String getCodec() { return codec; } public void setCodec(String codec) { this.codec = codec; } public String getCharset() { return charset; } public void setCharset(String charset) { this.charset = charset; } public Integer getPayload() { return payload; } public void setPayload(Integer payload) { this.payload = payload; } public Integer getBuffer() { return buffer; } public void setBuffer(Integer buffer) { this.buffer = buffer; } public String getServer() { return server; } public void setServer(String server) { this.server = server; } public String getClient() { return client; } public void setClient(String client) { this.client = client; } public String getTelnet() { return telnet; } public void setTelnet(String telnet) { this.telnet = telnet; } @Parameter(escaped = true) public String getPrompt() { return prompt; } public void setPrompt(String prompt) { this.prompt = prompt; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Override public String getCluster() { return super.getCluster(); } @Override public Integer getConnections() { return super.getConnections(); } @Override public Integer getTimeout() { return super.getTimeout(); } @Override public Integer getRetries() { return super.getRetries(); } @Override public String getLoadbalance() { return super.getLoadbalance(); } @Override public Boolean isAsync() { return super.isAsync(); } @Override public Integer getActives() { return super.getActives(); } public String getTransporter() { return transporter; } public void setTransporter(String transporter) { this.transporter = transporter; } public String getExchanger() { return exchanger; } public void setExchanger(String exchanger) { this.exchanger = exchanger; } /** * typo, switch to use {@link #getDispatcher()} * * @deprecated {@link #getDispatcher()} */ @Deprecated @Parameter(excluded = true) public String getDispather() { return getDispatcher(); } /** * typo, switch to use {@link #getDispatcher()} * * @deprecated {@link #setDispatcher(String)} */ @Deprecated public void setDispather(String dispather) { setDispatcher(dispather); } public String getDispatcher() { return dispatcher; } public void setDispatcher(String dispatcher) { this.dispatcher = dispatcher; } public String getNetworker() { return networker; } public void setNetworker(String networker) { this.networker = networker; } public Integer getWait() { return wait; } public void setWait(Integer wait) { this.wait = wait; } @Override public String toString() { final StringBuilder sb = new StringBuilder("ProviderConfig{"); sb.append("host='").append(host).append('\''); sb.append(", port=").append(port); sb.append(", contextpath='").append(contextpath).append('\''); sb.append(", threadpool='").append(threadpool).append('\''); sb.append(", threadname='").append(threadname).append('\''); sb.append(", threads=").append(threads); sb.append(", iothreads=").append(iothreads); sb.append(", alive=").append(alive); sb.append(", queues=").append(queues); sb.append(", accepts=").append(accepts); sb.append(", codec='").append(codec).append('\''); sb.append(", charset='").append(charset).append('\''); sb.append(", payload=").append(payload); sb.append(", buffer=").append(buffer); sb.append(", transporter='").append(transporter).append('\''); sb.append(", exchanger='").append(exchanger).append('\''); sb.append(", dispatcher='").append(dispatcher).append('\''); sb.append(", networker='").append(networker).append('\''); sb.append(", server='").append(server).append('\''); sb.append(", client='").append(client).append('\''); sb.append(", telnet='").append(telnet).append('\''); sb.append(", prompt='").append(prompt).append('\''); sb.append(", status='").append(status).append('\''); sb.append(", wait=").append(wait).append('\''); sb.append(", isDefault=").append(isDefault); sb.append('}'); return sb.toString(); } }
apache/dubbo
dubbo-common/src/main/java/org/apache/dubbo/config/ProviderConfig.java
44,957
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.action.search; import org.elasticsearch.action.OriginalIndices; import org.elasticsearch.cluster.routing.PlainShardIterator; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.common.util.Countable; import org.elasticsearch.common.util.PlainIterator; import org.elasticsearch.core.Nullable; import org.elasticsearch.core.TimeValue; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.search.SearchShardTarget; import org.elasticsearch.search.internal.ShardSearchContextId; import java.util.Comparator; import java.util.List; import java.util.Objects; /** * Extension of {@link PlainShardIterator} used in the search api, which also holds the {@link OriginalIndices} * of the search request (useful especially with cross-cluster search, as each cluster has its own set of original indices) as well as * the cluster alias. * @see OriginalIndices */ public final class SearchShardIterator implements Comparable<SearchShardIterator>, Countable { private final OriginalIndices originalIndices; private final String clusterAlias; private final ShardId shardId; private boolean skip; private final boolean prefiltered; private final ShardSearchContextId searchContextId; private final TimeValue searchContextKeepAlive; private final PlainIterator<String> targetNodesIterator; /** * Creates a {@link PlainShardIterator} instance that iterates over a subset of the given shards * this the a given <code>shardId</code>. * * @param clusterAlias the alias of the cluster where the shard is located * @param shardId shard id of the group * @param shards shards to iterate * @param originalIndices the indices that the search request originally related to (before any rewriting happened) */ public SearchShardIterator(@Nullable String clusterAlias, ShardId shardId, List<ShardRouting> shards, OriginalIndices originalIndices) { this(clusterAlias, shardId, shards.stream().map(ShardRouting::currentNodeId).toList(), originalIndices, null, null, false, false); } /** * Creates a {@link PlainShardIterator} instance that iterates over a subset of the given shards * * @param clusterAlias the alias of the cluster where the shard is located * @param shardId shard id of the group * @param targetNodeIds the list of nodes hosting shard copies * @param originalIndices the indices that the search request originally related to (before any rewriting happened) * @param searchContextId the point-in-time specified for this group if exists * @param searchContextKeepAlive the time interval that data nodes should extend the keep alive of the point-in-time * @param prefiltered if true, then this group already executed the can_match phase * @param skip if true, then this group won't have matches, and it can be safely skipped from the search */ public SearchShardIterator( @Nullable String clusterAlias, ShardId shardId, List<String> targetNodeIds, OriginalIndices originalIndices, ShardSearchContextId searchContextId, TimeValue searchContextKeepAlive, boolean prefiltered, boolean skip ) { this.shardId = shardId; this.targetNodesIterator = new PlainIterator<>(targetNodeIds); this.originalIndices = originalIndices; this.clusterAlias = clusterAlias; this.searchContextId = searchContextId; this.searchContextKeepAlive = searchContextKeepAlive; assert searchContextKeepAlive == null || searchContextId != null; this.prefiltered = prefiltered; this.skip = skip; assert skip == false || prefiltered : "only prefiltered shards are skip-able"; } /** * Returns the original indices associated with this shard iterator, specifically with the cluster that this shard belongs to. */ public OriginalIndices getOriginalIndices() { return originalIndices; } /** * Returns the alias of the cluster where the shard is located. */ @Nullable public String getClusterAlias() { return clusterAlias; } SearchShardTarget nextOrNull() { final String nodeId = targetNodesIterator.nextOrNull(); if (nodeId != null) { return new SearchShardTarget(nodeId, shardId, clusterAlias); } return null; } int remaining() { return targetNodesIterator.remaining(); } /** * Returns a non-null value if this request should use a specific search context instead of the latest one. */ ShardSearchContextId getSearchContextId() { return searchContextId; } TimeValue getSearchContextKeepAlive() { return searchContextKeepAlive; } List<String> getTargetNodeIds() { return targetNodesIterator.asList(); } void reset() { targetNodesIterator.reset(); } /** * Returns <code>true</code> if the search execution should skip this shard since it can not match any documents given the query. */ boolean skip() { return skip; } /** * Specifies if the search execution should skip this shard copies */ void skip(boolean skip) { this.skip = skip; } /** * Returns {@code true} if this iterator was applied pre-filtered */ boolean prefiltered() { return prefiltered; } @Override public int size() { return targetNodesIterator.size(); } ShardId shardId() { return shardId; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SearchShardIterator that = (SearchShardIterator) o; return shardId.equals(that.shardId) && Objects.equals(clusterAlias, that.clusterAlias); } @Override public int hashCode() { return Objects.hash(clusterAlias, shardId); } private static final Comparator<SearchShardIterator> COMPARATOR = Comparator.comparing(SearchShardIterator::shardId) .thenComparing(SearchShardIterator::getClusterAlias, Comparator.nullsFirst(String::compareTo)); @Override public int compareTo(SearchShardIterator o) { return COMPARATOR.compare(this, o); } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/action/search/SearchShardIterator.java