code
stringlengths
25
201k
docstring
stringlengths
19
96.2k
func_name
stringlengths
0
235
language
stringclasses
1 value
repo
stringlengths
8
51
path
stringlengths
11
314
url
stringlengths
62
377
license
stringclasses
7 values
protected Page newPage(final HttpServletRequest req, final HttpServletResponse resp, final String template) { final Page page = new Page(req, resp, getApplication().getVelocityEngine(), template); page.add("version", jarVersion); page.add("azkaban_name", this.name); page.add("azkaban_label", this.label); page.add("azkaban_color", this.color); page.add("azkaban_depth", this.depth); page.add("note_type", NoteServlet.type); page.add("note_message", NoteServlet.message); page.add("note_url", NoteServlet.url); page.add("timezone", TimeZone.getDefault().getID()); page.add("currentTime", (new DateTime()).getMillis()); page.add("size", getDisplayExecutionPageSize()); // @TODO, allow more than one type of viewer. For time sake, I only install // the first one if (this.viewerPlugins != null && !this.viewerPlugins.isEmpty()) { page.add("viewers", this.viewerPlugins); final ViewerPlugin plugin = this.viewerPlugins.get(0); page.add("viewerName", plugin.getPluginName()); page.add("viewerPath", plugin.getPluginPath()); } if (this.triggerPlugins != null && !this.triggerPlugins.isEmpty()) { page.add("triggers", this.triggerPlugins); } return page; }
Creates a new velocity page to use.
newPage
java
azkaban/azkaban
azkaban-web-server/src/main/java/azkaban/webapp/servlet/AbstractAzkabanServlet.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/main/java/azkaban/webapp/servlet/AbstractAzkabanServlet.java
Apache-2.0
private void ajaxFetchExecFlowLogs(final HttpServletRequest req, final HttpServletResponse resp, final HashMap<String, Object> ret, final User user, final ExecutableFlow exFlow) throws ServletException { final Project project = getProjectAjaxByPermission(ret, exFlow.getProjectId(), user, Type.READ); if (project == null) { return; } final int offset = this.getIntParam(req, "offset"); final int length = this.getIntParam(req, "length"); resp.setCharacterEncoding("utf-8"); try { final LogData data = this.executorManagerAdapter.getExecutableFlowLog(exFlow, offset, length); ret.putAll(appendLogData(data, offset)); } catch (final ExecutorManagerException e) { throw new ServletException(e); } }
Gets the logs through plain text stream to reduce memory overhead.
ajaxFetchExecFlowLogs
java
azkaban/azkaban
azkaban-web-server/src/main/java/azkaban/webapp/servlet/ExecutorServlet.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/main/java/azkaban/webapp/servlet/ExecutorServlet.java
Apache-2.0
private boolean handleOauth(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { if (hasParam(req, "nooauth")) { // cheat code to allow XML-based authN while OAuth is in use return false; // Let the old login happen } final Props props = getApplication().getServerProps(); final String oauthProviderUrlPattern = props.getString(OAUTH_PROVIDER_URI_KEY, ""); final String oauthRedirectUrl = props.getString(OAUTH_REDIRECT_URI_KEY, ""); if (oauthProviderUrlPattern.isEmpty() || oauthRedirectUrl.isEmpty()) { // no OAuth provider? return false; // Let the old login happen } // add state & redirect URL params final StringBuffer requestUrl = req.getRequestURL(); final String queryString = req.getQueryString(); if (queryString != null) { requestUrl.append('?').append(queryString); } final String stateEncoded = java.net.URLEncoder.encode(requestUrl.toString(), UTF_8); final String redirectUriEncoded = java.net.URLEncoder.encode(oauthRedirectUrl, UTF_8); final String oauthProviderUrl = oauthProviderUrlPattern .replace("{state}", stateEncoded) // OAuth gives it back to us and we redirect there .replace("{redirect_uri}", redirectUriEncoded); // OAuth calls us back there logger.debug("Redirecting to OAuth provider: " + oauthProviderUrl); resp.sendRedirect(oauthProviderUrl); return true; }
Return true if login can, should and is being handled via OAuth provider, as configured.
handleOauth
java
azkaban/azkaban
azkaban-web-server/src/main/java/azkaban/webapp/servlet/LoginAbstractAzkabanServlet.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/main/java/azkaban/webapp/servlet/LoginAbstractAzkabanServlet.java
Apache-2.0
protected Project filterProjectByPermission(final Project project, final User user, final Permission.Type type) { return filterProjectByPermission(project, user, type, null); }
Filter Project based on user authorization @param project project @param user user @param type permission allowance @return authorized project itself or null if the project is not authorized
filterProjectByPermission
java
azkaban/azkaban
azkaban-web-server/src/main/java/azkaban/webapp/servlet/LoginAbstractAzkabanServlet.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/main/java/azkaban/webapp/servlet/LoginAbstractAzkabanServlet.java
Apache-2.0
protected void handleDelete(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { }
The delete request is handed off to the implementor after the user is logged in.
handleDelete
java
azkaban/azkaban
azkaban-web-server/src/main/java/azkaban/webapp/servlet/LoginAbstractAzkabanServlet.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/main/java/azkaban/webapp/servlet/LoginAbstractAzkabanServlet.java
Apache-2.0
protected void handleMultiformPost(final HttpServletRequest req, final HttpServletResponse resp, final Map<String, Object> multipart, final Session session) throws ServletException, IOException { }
The post request is handed off to the implementor after the user is logged in.
handleMultiformPost
java
azkaban/azkaban
azkaban-web-server/src/main/java/azkaban/webapp/servlet/LoginAbstractAzkabanServlet.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/main/java/azkaban/webapp/servlet/LoginAbstractAzkabanServlet.java
Apache-2.0
protected boolean hasImageManagementPermission(final String imageTypeName, final User user, final Permission.Type type) { // Check image management APIs access permission for other users. final PermissionManager permissionManager = getApplication().getPermissionManager(); /** * Azkaban ADMIN role must have full permission to access image management APIs. Hence, no * further permission check is required. */ if (permissionManager.isAzkabanAdmin(user)) { return true; } return permissionManager.hasPermissionForImageType(imageTypeName, user.getUserId(), type); }
Method to check permission to access image management APIs. @param imageTypeName @param user @param type @return boolean
hasImageManagementPermission
java
azkaban/azkaban
azkaban-web-server/src/main/java/azkaban/webapp/servlet/LoginAbstractAzkabanServlet.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/main/java/azkaban/webapp/servlet/LoginAbstractAzkabanServlet.java
Apache-2.0
public static void hideUploadButtonWhenNeeded(final Page page, final Session session, final UserManager userManager, final Boolean lockdownUploadProjects) { final User user = session.getUser(); if (lockdownUploadProjects && !UserUtils.hasPermissionforAction(userManager, user, Permission.Type.UPLOADPROJECTS)) { page.add("hideUploadProject", true); } }
Method hides the upload button for regular users from relevant pages when the property "lockdown.upload.projects" is set. The button is displayed for admin users and users with upload permissions.
hideUploadButtonWhenNeeded
java
azkaban/azkaban
azkaban-web-server/src/main/java/azkaban/webapp/servlet/PageUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/main/java/azkaban/webapp/servlet/PageUtils.java
Apache-2.0
private void handleDownloadProject(final HttpServletRequest req, final HttpServletResponse resp, final Session session) throws ServletException, IOException { final User user = session.getUser(); final String projectName = getParam(req, "project"); logger.info(user.getUserId() + " is downloading project: " + projectName); final Project project = this.projectManager.getProject(projectName); if (project == null) { this.setErrorMessageInCookie(resp, "Project " + projectName + " doesn't exist."); resp.sendRedirect(req.getContextPath()); return; } if (!hasPermission(project, user, Type.READ)) { this.setErrorMessageInCookie(resp, "No permission to download project " + projectName + "."); resp.sendRedirect(req.getContextPath()); return; } int version = -1; if (hasParam(req, "version")) { version = getIntParam(req, "version"); } ProjectFileHandler projectFileHandler = null; FileInputStream inStream = null; OutputStream outStream = null; try { projectFileHandler = this.projectManager.getProjectFileHandler(project, version); if (projectFileHandler == null) { this.setErrorMessageInCookie(resp, "Project " + projectName + " with version " + version + " doesn't exist"); resp.sendRedirect(req.getContextPath()); return; } final File projectZipFile = projectFileHandler.getLocalFile(); final String logStr = String.format( "downloading project zip file for project \"%s\" at \"%s\"" + " size: %d type: %s fileName: \"%s\"", projectFileHandler.getFileName(), projectZipFile.getAbsolutePath(), projectZipFile.length(), projectFileHandler.getFileType(), projectFileHandler.getFileName()); logger.info(logStr); // now set up HTTP response for downloading file inStream = new FileInputStream(projectZipFile); resp.setContentType(APPLICATION_ZIP_MIME_TYPE); final String headerKey = "Content-Disposition"; final String headerValue = String.format("attachment; filename=\"%s\"", projectFileHandler.getFileName()); resp.setHeader(headerKey, headerValue); resp.setHeader("version", Integer.toString(projectFileHandler.getVersion())); resp.setHeader("projectId", Integer.toString(projectFileHandler.getProjectId())); outStream = resp.getOutputStream(); final byte[] buffer = new byte[this.downloadBufferSize]; int bytesRead = -1; while ((bytesRead = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytesRead); } } catch (final Throwable e) { logger.error( "Encountered error while downloading project zip file for project: " + projectName + " by user: " + user.getUserId(), e); throw new ServletException(e); } finally { IOUtils.closeQuietly(inStream); IOUtils.closeQuietly(outStream); if (projectFileHandler != null) { projectFileHandler.deleteLocalFile(); } } }
Download project zip file from DB and send it back client. <p> This method requires a project name and an optional project version.
handleDownloadProject
java
azkaban/azkaban
azkaban-web-server/src/main/java/azkaban/webapp/servlet/ProjectManagerServlet.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/main/java/azkaban/webapp/servlet/ProjectManagerServlet.java
Apache-2.0
private void ajaxSetFlowLock(final Project project, final HashMap<String, Object> ret, final HttpServletRequest req) throws ServletException { final String flowName = getParam(req, FLOW_NAME_PARAM); final Flow flow = project.getFlow(flowName); if (flow == null) { ret.put(ERROR_PARAM, "Flow " + flowName + " not found in project " + project.getName()); return; } final boolean isLocked = Boolean.parseBoolean(getParam(req, FLOW_IS_LOCKED_PARAM)); String flowLockErrorMessage = null; try { flowLockErrorMessage = getParam(req, FLOW_LOCK_ERROR_MESSAGE_PARAM); } catch (final Exception e) { logger.info("Unable to get flow lock error message"); } // if there is a change in the locked value, then check to see if the project has a flow trigger // that needs to be paused/resumed. if (isLocked != flow.isLocked()) { try { if (this.projectManager.hasFlowTrigger(project, flow)) { if (isLocked) { if (this.scheduler.pauseFlowTriggerIfPresent(project.getId(), flow.getId())) { logger.info("Flow trigger for flow " + project.getName() + "." + flow.getId() + " is paused"); } else { logger.warn("Flow trigger for flow " + project.getName() + "." + flow.getId() + " doesn't exist"); } } else { if (this.scheduler.resumeFlowTriggerIfPresent(project.getId(), flow.getId())) { logger.info("Flow trigger for flow " + project.getName() + "." + flow.getId() + " is resumed"); } else { logger.warn("Flow trigger for flow " + project.getName() + "." + flow.getId() + " doesn't exist"); } } } } catch (final Exception e) { ret.put(ERROR_PARAM, e); } } flow.setLocked(isLocked); flow.setFlowLockErrorMessage(isLocked ? flowLockErrorMessage : null); ret.put(FLOW_IS_LOCKED_PARAM, flow.isLocked()); ret.put(FLOW_ID_PARAM, flow.getId()); ret.put(FLOW_LOCK_ERROR_MESSAGE_PARAM, flow.getFlowLockErrorMessage()); this.projectManager.updateFlow(project, flow); }
Set if a flow is locked. @param project the project for the flow. @param ret the return value. @param req the http request.
ajaxSetFlowLock
java
azkaban/azkaban
azkaban-web-server/src/main/java/azkaban/webapp/servlet/ProjectManagerServlet.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/main/java/azkaban/webapp/servlet/ProjectManagerServlet.java
Apache-2.0
private Project validateUploadAndGetProject(final HttpServletResponse resp, final Map<String, String> ret, final User user, final String projectName) { if (projectName == null || projectName.isEmpty()) { registerError(ret, "No project name found.", resp, HttpServletResponse.SC_BAD_REQUEST); return null; } final Project project = this.projectManager.getProject(projectName); if (project == null || !project.isActive()) { final String failureCause = (project == null) ? "doesn't exist." : "was already removed."; registerError(ret, "Installation Failed. Project '" + projectName + " " + failureCause, resp, HttpServletResponse.SC_GONE); return null; } logger.info( "Upload: reference of project " + projectName + " is " + System.identityHashCode(project)); if (this.lockdownUploadProjects && !UserUtils .hasPermissionforAction(this.userManager, user, Type.UPLOADPROJECTS)) { final String message = "Project uploading is locked out. Only admin users and users with special permissions can upload projects. " + "User " + user.getUserId() + " doesn't have permission to upload project."; logger.info(message); registerError(ret, message, resp, HttpServletResponse.SC_FORBIDDEN); return null; } if (!hasPermission(project, user, Type.WRITE)) { registerError(ret, "Installation Failed. User '" + user.getUserId() + "' does not have write access.", resp, HttpServletResponse.SC_BAD_REQUEST); return null; } return project; }
@return project. Null if invalid upload params or not enough permissions to proceed.
validateUploadAndGetProject
java
azkaban/azkaban
azkaban-web-server/src/main/java/azkaban/webapp/servlet/ProjectManagerServlet.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/main/java/azkaban/webapp/servlet/ProjectManagerServlet.java
Apache-2.0
private List<Pair<String, String>> getLockedFlows(final Project project) { final List<Flow> flows = project.getFlows(); return flows.stream() .filter(flow -> flow.isLocked()) .map(flow -> new Pair<>(flow.getId(), flow.getFlowLockErrorMessage())) .collect(Collectors.toList()); }
@return the list of locked flows and corresponding error messages for the specified project.
getLockedFlows
java
azkaban/azkaban
azkaban-web-server/src/main/java/azkaban/webapp/servlet/ProjectManagerServlet.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/main/java/azkaban/webapp/servlet/ProjectManagerServlet.java
Apache-2.0
private void handleAjaxAction(final HttpServletRequest req, final HttpServletResponse resp, final Session session, final ProjectManager manager) throws ServletException, IOException { final String ajaxName = getParam(req, "ajax"); final HashMap<String, Object> ret = new HashMap<>(); if (API_FETCH_ALL_PROJECTS.equals(ajaxName)) { final List<Project> projects = manager.getProjects(); final List<SimplifiedProject> simplifiedProjects = toSimplifiedProjects(projects); ret.put("projects", simplifiedProjects); } else if (API_FETCH_USER_PROJECTS.equals(ajaxName)) { handleFetchUserProjects(req, session, manager, ret); } this.writeJSON(resp, ret); }
ProjectServlet class now handles ajax requests. It returns a @SimplifiedProject object: information regarding projects, and information regarding user and project association
handleAjaxAction
java
azkaban/azkaban
azkaban-web-server/src/main/java/azkaban/webapp/servlet/ProjectServlet.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/main/java/azkaban/webapp/servlet/ProjectServlet.java
Apache-2.0
private void handleFetchUserProjects(final HttpServletRequest req, final Session session, final ProjectManager manager, final HashMap<String, Object> ret) throws ServletException { User user = null; // if key "user" is specified, follow this logic if (hasParam(req, "user")) { final String userParam = getParam(req, "user"); if (userParam.isEmpty()) { user = session.getUser(); } else { user = new User(userParam); } } else { // if key "user" is not specified, default to the session user user = session.getUser(); } final List<Project> projects = manager.getUserProjects(user); final List<SimplifiedProject> simplifiedProjects = toSimplifiedProjects(projects); ret.put("projects", simplifiedProjects); }
We know the intention of API call is to return project ownership based on given user. <br> If user provides an user name, the method honors it <br> If user provides an empty user name, the user defaults to the session user<br> If user does not provide the user param, the user also defaults to the session user<br>
handleFetchUserProjects
java
azkaban/azkaban
azkaban-web-server/src/main/java/azkaban/webapp/servlet/ProjectServlet.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/main/java/azkaban/webapp/servlet/ProjectServlet.java
Apache-2.0
private List<SimplifiedProject> toSimplifiedProjects(final List<Project> projects) { final List<SimplifiedProject> simplifiedProjects = new ArrayList<>(); for (final Project p : projects) { final SimplifiedProject sp = new SimplifiedProject(p.getId(), p.getName(), p.getLastModifiedUser(), p.getCreateTimestamp(), p.getUserPermissions(), p.getGroupPermissions()); simplifiedProjects.add(sp); } return simplifiedProjects; }
A simple helper method that converts a List<Project> to List<SimplifiedProject>
toSimplifiedProjects
java
azkaban/azkaban
azkaban-web-server/src/main/java/azkaban/webapp/servlet/ProjectServlet.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/main/java/azkaban/webapp/servlet/ProjectServlet.java
Apache-2.0
public static Set<String> getSetFromString(final String val) { if (val == null || val.trim().length() == 0) { return Collections.emptySet(); } return new HashSet<>(Arrays.asList(val.split("\\s*,\\s*"))); }
Returns the Set of String from the comma-separated val
getSetFromString
java
azkaban/azkaban
azkaban-web-server/src/main/java/azkaban/webapp/servlet/ServletUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/main/java/azkaban/webapp/servlet/ServletUtils.java
Apache-2.0
private void handleGetAllMetricName(final int executorId, final HttpServletRequest req, final HashMap<String, Object> ret) throws IOException { final Map<String, Object> result; try { result = this.execManagerAdapter.callExecutorStats(executorId, ConnectorParams.STATS_GET_ALLMETRICSNAME, (Pair<String, String>[]) null); if (result.containsKey(ConnectorParams.RESPONSE_ERROR)) { ret.put("error", result.get(ConnectorParams.RESPONSE_ERROR).toString()); } else { ret.put("metricList", result.get("data")); } } catch (final ExecutorManagerException e) { logger.error(e.getMessage(), e); ret.put("error", "Failed to fetch metric names for executor : " + executorId); } }
Get all metrics tracked by the given executor
handleGetAllMetricName
java
azkaban/azkaban
azkaban-web-server/src/main/java/azkaban/webapp/servlet/StatsServlet.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/main/java/azkaban/webapp/servlet/StatsServlet.java
Apache-2.0
private void handleChangeConfigurationRequest(final int executorId, final String actionName, final HttpServletRequest req, final HashMap<String, Object> ret) throws ServletException, IOException { try { final Map<String, Object> result = this.execManagerAdapter.callExecutorStats(executorId, actionName, getAllParams(req)); if (result.containsKey(ConnectorParams.RESPONSE_ERROR)) { ret.put(ConnectorParams.RESPONSE_ERROR, result.get(ConnectorParams.RESPONSE_ERROR).toString()); } else { ret.put(ConnectorParams.STATUS_PARAM, result.get(ConnectorParams.STATUS_PARAM)); } } catch (final ExecutorManagerException ex) { logger.error(ex.getMessage(), ex); ret.put("error", "Failed to change config change"); } }
Generic method to facilitate actionName action using Azkaban exec server @param actionName Name of the action
handleChangeConfigurationRequest
java
azkaban/azkaban
azkaban-web-server/src/main/java/azkaban/webapp/servlet/StatsServlet.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/main/java/azkaban/webapp/servlet/StatsServlet.java
Apache-2.0
public static String getRealClientIpAddr(final Map<String, String> httpHeaders, final String remoteAddr) { // If some upstream device added an X-Forwarded-For header // use it for the client ip // This will support scenarios where load balancers or gateways // front the Azkaban web server and a changing Ip address invalidates the session String clientIp = httpHeaders.getOrDefault(X_FORWARDED_FOR_HEADER, null); if (clientIp == null) { clientIp = remoteAddr; } else { // header can contain comma separated list of upstream servers - get the first one final String[] ips = clientIp.split(","); clientIp = ips[0]; } // Strip off port and only get IP address // todo: this is broken for IPv6, where e.g. a "loopback" address looks like "0:0:0:0:0:0:0:1" final String[] parts = clientIp.split(":"); clientIp = parts[0]; return clientIp; }
Gets the actual client IP address on a best effort basis as user could be sitting behind a VPN. Get the IP by inspecting the X-Forwarded-For HTTP header or using the provided 'remote IP address' from the low level TCP connection from the client. If multiple IP addresses are provided in the X-Forwarded-For header then the first one (first hop) is used @param httpHeaders List of HTTP headers for the current request @param remoteAddr The client IP address and port from the current request's TCP connection @return The actual client IP address
getRealClientIpAddr
java
azkaban/azkaban
azkaban-web-server/src/main/java/azkaban/webapp/servlet/WebUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/main/java/azkaban/webapp/servlet/WebUtils.java
Apache-2.0
public static String getRealClientIpAddr(final HttpServletRequest req) { // If some upstream device added an X-Forwarded-For header // use it for the client ip // This will support scenarios where load balancers or gateways // front the Azkaban web server and a changing Ip address invalidates // the session final HashMap<String, String> headers = new HashMap<>(); headers.put(WebUtils.X_FORWARDED_FOR_HEADER, req.getHeader(WebUtils.X_FORWARDED_FOR_HEADER.toLowerCase())); return WebUtils.getRealClientIpAddr(headers, req.getRemoteAddr()); }
Gets the actual client IP address on a best effort basis as user could be sitting behind a VPN. Get the IP by inspecting the X-Forwarded-For HTTP header or using the provided 'remote IP address' from the low level TCP connection from the client. If multiple IP addresses are provided in the X-Forwarded-For header then the first one (first hop) is used @param req HttpServletRequest @return The actual client IP address
getRealClientIpAddr
java
azkaban/azkaban
azkaban-web-server/src/main/java/azkaban/webapp/servlet/WebUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/main/java/azkaban/webapp/servlet/WebUtils.java
Apache-2.0
public static void assertStringEqualFileContent(final String expectedFilePath, final String actual) throws IOException { final String expected = new String(Files.readAllBytes(Paths.get(expectedFilePath)), StandardCharsets.UTF_8); assertThat(actual).isEqualToIgnoringWhitespace(expected); }
Assert the given string equals the given file's content. The white space differences are ignored. @param expectedFilePath the expected file path @param actual the actual string @throws IOException the io exception
assertStringEqualFileContent
java
azkaban/azkaban
azkaban-web-server/src/test/java/azkaban/fixture/FileAssertion.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/test/java/azkaban/fixture/FileAssertion.java
Apache-2.0
public static String surroundWithHtmlTag(final String content) { return "<html>\n" + content + "</html>\n"; }
Return the html based content surrounded with the HTML tag. This is useful to compare a fragment of HTML content with a proper expected HTML file so that the expected file can be viewed more easily with a browser. @param content the content @return string
surroundWithHtmlTag
java
azkaban/azkaban
azkaban-web-server/src/test/java/azkaban/fixture/FileAssertion.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/test/java/azkaban/fixture/FileAssertion.java
Apache-2.0
public static Project getMockProject() { final Project project = new Project(1, "test_project"); project.setDescription("My project description"); project.setLastModifiedUser("last_modified_user_name"); project.setUploadLock(true); project.addFeatureFlags(FeatureFlag.ENABLE_PROJECT_ADHOC_UPLOAD, false); final DateFormat dateFormat = new SimpleDateFormat("yyyy:MM:dd:HH:mm:ss"); try { final Date modifiedDate = dateFormat.parse("2000:01:02:3:4:5"); final long modifiedTime = modifiedDate.getTime(); project.setLastModifiedTimestamp(modifiedTime); final Date createDate = dateFormat.parse("1999:06:07:8:9:10"); final long createTime = createDate.getTime(); project.setCreateTimestamp(createTime); } catch (final ParseException e) { e.printStackTrace(); } return project; }
Get mock project project. @return a mock project for testing
getMockProject
java
azkaban/azkaban
azkaban-web-server/src/test/java/azkaban/fixture/MockProject.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/test/java/azkaban/fixture/MockProject.java
Apache-2.0
public static VelocityContext getInstance() { final VelocityContext context = new VelocityContext(); context.put("esc", new EscapeTool()); context.put("TimeUtils", TimeUtils.class); return context; }
Gets an instance of the velocity context Add the utility instances that are commonly used in many templates. @return the instance
getInstance
java
azkaban/azkaban
azkaban-web-server/src/test/java/azkaban/fixture/VelocityContextTestUtil.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/test/java/azkaban/fixture/VelocityContextTestUtil.java
Apache-2.0
public static String renderTemplate(final String templateName, final VelocityContext context) { final StringWriter stringWriter = new StringWriter(); final VelocityEngine engine = new VelocityEngine(); engine.init("src/test/resources/velocity.properties"); engine.mergeTemplate(TEMPLATE_BASE_DIR + templateName + ".vm", "UTF-8", context, stringWriter); return stringWriter.getBuffer().toString(); }
Render a template and return the result @param templateName the template name only without the .vm extension @param context the context @return string
renderTemplate
java
azkaban/azkaban
azkaban-web-server/src/test/java/azkaban/fixture/VelocityTemplateTestUtil.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/test/java/azkaban/fixture/VelocityTemplateTestUtil.java
Apache-2.0
public static boolean ignoreCaseContains(final String source, final String target) { final String sourceNoSpace = source.replaceAll("\\s+", ""); final String targetNoSpace = target.replaceAll("\\s+", ""); return sourceNoSpace.contains(targetNoSpace); }
@param source the rendered template as a String @param target the String fragment within the template @return - boolean
ignoreCaseContains
java
azkaban/azkaban
azkaban-web-server/src/test/java/azkaban/fixture/VelocityTemplateTestUtil.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/test/java/azkaban/fixture/VelocityTemplateTestUtil.java
Apache-2.0
public static void assertStringEqualFileContent(final String expectedFileName, final String actual) throws IOException { final String expectedFilePath = EXPECTED_FILE_DIR + expectedFileName; FileAssertion.assertStringEqualFileContent(expectedFilePath, actual); }
Assert the string equals file content in this project's expected file directory. @param expectedFileName the expected file name @param actual the actual @throws IOException the io exception
assertStringEqualFileContent
java
azkaban/azkaban
azkaban-web-server/src/test/java/azkaban/fixture/WebFileAssertion.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/test/java/azkaban/fixture/WebFileAssertion.java
Apache-2.0
public void testValidVersionInternal(final String version) { final ImageVersionDTO dto = new ImageVersionDTO(); dto.setName("testImageType"); List<String> validationErrors = new ArrayList<>(); dto.setVersion(version); boolean result = ValidatorUtils.validateObject(dto, validationErrors, BaseDTO.ValidationOnCreate.class); Assert.assertTrue(result); Assert.assertTrue(validationErrors.isEmpty()); }
Common code for valid versions @param version the image version
testValidVersionInternal
java
azkaban/azkaban
azkaban-web-server/src/test/java/azkaban/imagemgmt/dto/ImageVersionDTOTest.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/test/java/azkaban/imagemgmt/dto/ImageVersionDTOTest.java
Apache-2.0
@Test public void testExternalAnalyzerButton() throws Exception { final VelocityContext context = VelocityContextTestUtil.getInstance(); ExternalLink externalLink1 = new ExternalLink( "topic1", "Label1", "http://topic1.linkedin.com/", true); context.put("externalAnalyzers", Arrays.asList(externalLink1)); String result = VelocityTemplateTestUtil.renderTemplate("executingflowpage", context); assertTrue(VelocityTemplateTestUtil. ignoreCaseContains(result, EXTERNAL_ANALYZER_ELEMENT1)); ExternalLink externalLink2 = new ExternalLink( "topic2", "Label2", "http://topic2.linkedin.com/", false); context.put("externalAnalyzers", Arrays.asList(externalLink1, externalLink2)); result = VelocityTemplateTestUtil.renderTemplate("executingflowpage", context); assertTrue(VelocityTemplateTestUtil. ignoreCaseContains(result, EXTERNAL_ANALYZER_ELEMENT1)); assertTrue(VelocityTemplateTestUtil. ignoreCaseContains(result, EXTERNAL_ANALYZER_ELEMENT2)); }
Test aims to check that the external analyzer button is displayed in the page. @throws Exception the exception
testExternalAnalyzerButton
java
azkaban/azkaban
azkaban-web-server/src/test/java/azkaban/webapp/servlet/ExecutionFlowViewTest.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/test/java/azkaban/webapp/servlet/ExecutionFlowViewTest.java
Apache-2.0
@Test public void postAjaxExecuteFlowWithInvalidSlaSettings() throws Exception { mockTestProjectAndFlow(); mockSubmitExecution(); this.req.addParameter("ajax", "executeFlow"); this.req.addParameter("project", "testProject"); this.req.addParameter("flow", "testFlow"); this.req.addParameter("slaSettings[1]", "broken-syntax-for-sla"); this.executorServlet.handlePost(this.req, this.res, this.session); assertEquals(200, this.res.getStatus()); assertEquals("Error parsing flow options: Error parsing SLA setting 'broken-syntax-for-sla': " + "java.lang.ArrayIndexOutOfBoundsException: 1", this.res.getResponseJson().path("error").asText()); }
When SLA options can't be parsed, API is expected to return 200 OK with JSON that has "error".
postAjaxExecuteFlowWithInvalidSlaSettings
java
azkaban/azkaban
azkaban-web-server/src/test/java/azkaban/webapp/servlet/ExecutorServletTest.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/test/java/azkaban/webapp/servlet/ExecutorServletTest.java
Apache-2.0
@Test public void postAjaxExecuteFlowWithMissingProjectParameter() throws Exception { this.req.addParameter("ajax", "executeFlow"); try { this.executorServlet.handlePost(this.req, this.res, this.session); fail("Expected exception was not thrown"); } catch (final ServletException e) { assertEquals("Missing required parameter 'project'.", e.getMessage()); } }
When executeFlow is called without project param, API is expected to raise an exception.
postAjaxExecuteFlowWithMissingProjectParameter
java
azkaban/azkaban
azkaban-web-server/src/test/java/azkaban/webapp/servlet/ExecutorServletTest.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/test/java/azkaban/webapp/servlet/ExecutorServletTest.java
Apache-2.0
@Test public void testLoginRevealingCredentialsShouldThrowFailure() throws Exception { final String clientIp = "127.0.0.1:10000"; final String sessionId = "111"; final String queryString = "action=login&username=azkaban&password=azkaban"; final String[] mockCredentials = {"azkaban"}; final HashMap<String, String[]> mockParameterMap = new HashMap<String, String[]>() { { put("username", mockCredentials); put("password", mockCredentials); } }; final HttpServletRequest req = MockLoginAzkabanServlet .getRequestWithNoUpstream(clientIp, sessionId, "POST"); when(req.getParameterMap()).thenReturn(mockParameterMap); when(req.getQueryString()).thenReturn(queryString); final StringWriter writer = new StringWriter(); final HttpServletResponse resp = getResponse(writer); final MockLoginAzkabanServlet servlet = MockLoginAzkabanServlet.getServletWithSession(sessionId, "user", "127.0.0.1"); servlet.doPost(req, resp); // Assert that expected error message is returned assertEquals("Login error. Must pass username and password in request body", writer.toString()); }
Simulates users passing username/password via URI where it would be logged by Azkaban Web Server
testLoginRevealingCredentialsShouldThrowFailure
java
azkaban/azkaban
azkaban-web-server/src/test/java/azkaban/webapp/servlet/LoginAbstractAzkabanServletTest.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/test/java/azkaban/webapp/servlet/LoginAbstractAzkabanServletTest.java
Apache-2.0
@Test public void testProjectSideBarView() throws Exception { final VelocityContext context = VelocityContextTestUtil.getInstance(); final Project project = MockProject.getMockProject(); // Intentionally tries to inject a Javascript. project.setDescription("<script>window.alert(\"hacked\")</script>"); context.put("projectName", project.getName()); context.put("description", project.getDescription()); context.put("createTimestamp",project.getCreateTimestamp()); context.put("lastModifiedTimestamp",project.getLastModifiedTimestamp()); context.put("lastModifiedUser",project.getLastModifiedUser()); context.put("projectUploadLock", project.isUploadLocked()); context.put("adhocUpload", project.isAdhocUploadEnabled()); context.put("showUploadLockPanel", true); context.put("showAdhocUploadFeature", true); context.put("admins", "admin_name"); context.put("userpermission", "admin_permission"); final String result = VelocityTemplateTestUtil.renderTemplate("projectsidebar", context); final String actual = FileAssertion.surroundWithHtmlTag(result); WebFileAssertion.assertStringEqualFileContent("project-side-bar.html", actual); }
Test project side bar view. The project description should be HTML encoded to avoid cross site scripting issues. @throws Exception the exception
testProjectSideBarView
java
azkaban/azkaban
azkaban-web-server/src/test/java/azkaban/webapp/servlet/ProjectSideBarViewTest.java
https://github.com/azkaban/azkaban/blob/master/azkaban-web-server/src/test/java/azkaban/webapp/servlet/ProjectSideBarViewTest.java
Apache-2.0
public static ConditionFactory await() { return Awaitility.await().atMost(10L, TimeUnit.SECONDS) .pollInterval(10L, TimeUnit.MILLISECONDS); }
Wait for 10 seconds, max. Poll every 10ms.
await
java
azkaban/azkaban
test/src/main/java/azkaban/test/TestUtils.java
https://github.com/azkaban/azkaban/blob/master/test/src/main/java/azkaban/test/TestUtils.java
Apache-2.0
public synchronized static void lpush(String key, String... strings) { try { Jedis jedis = RedisUtil.getJedis(); jedis.lpush(key, strings); jedis.close(); } catch (Exception e) { LOGGER.error("lpush error : " + e); } }
lrem @param key @param count @param value
lpush
java
shuzheng/zheng
zheng-common/src/main/java/com/zheng/common/util/RedisUtil.java
https://github.com/shuzheng/zheng/blob/master/zheng-common/src/main/java/com/zheng/common/util/RedisUtil.java
MIT
public synchronized static void lrem(String key, long count, String value) { try { Jedis jedis = RedisUtil.getJedis(); jedis.lrem(key, count, value); jedis.close(); } catch (Exception e) { LOGGER.error("lpush error : " + e); } }
sadd @param key @param value @param seconds
lrem
java
shuzheng/zheng
zheng-common/src/main/java/com/zheng/common/util/RedisUtil.java
https://github.com/shuzheng/zheng/blob/master/zheng-common/src/main/java/com/zheng/common/util/RedisUtil.java
MIT
@Override public void onDetachedFromWindow(RecyclerView view, RecyclerView.Recycler recycler) { cancelAnimator(); super.onDetachedFromWindow(view, recycler); }
@param recycler @param state @param delta
onDetachedFromWindow
java
CCY0122/FocusLayoutManager
focuslayoutmanager/src/main/java/ccy/focuslayoutmanager/FocusLayoutManager.java
https://github.com/CCY0122/FocusLayoutManager/blob/master/focuslayoutmanager/src/main/java/ccy/focuslayoutmanager/FocusLayoutManager.java
Apache-2.0
public synchronized String format(LogRecord record) { this.buffer.setLength(0); this.date.setTime(record.getMillis()); this.position.setBeginIndex(0); this.formatter.format(this.date, this.buffer, this.position); this.buffer.append(' '); if (record.getSourceClassName() != null) { this.buffer.append(record.getSourceClassName()); } else { this.buffer.append(record.getLoggerName()); } this.buffer.append(' '); this.buffer.append(formatMessage(record)); this.buffer.append(System.getProperty("line.separator")); if (record.getThrown() != null) { try { StringWriter writer = new StringWriter(); PrintWriter printer = new PrintWriter(writer); record.getThrown().printStackTrace(printer); writer.close(); this.buffer.append(writer.toString()); } catch (Exception e) { this.buffer.append("Failed to get stack trace: " + e.getMessage()); } } return this.buffer.toString(); }
Persistent buffer in which we conjure the log.
format
java
DarLiner/vjtools
vjmxcli/src/main/java/com/vip/vjtools/jmx/Client.java
https://github.com/DarLiner/vjtools/blob/master/vjmxcli/src/main/java/com/vip/vjtools/jmx/Client.java
Apache-2.0
public static double calcLoad(double deltaUptime, double deltaTime, int factor) { if (deltaTime <= 0 || deltaUptime == 0) { return 0.0; } return Math.min(99.99, deltaTime / (deltaUptime * factor)); }
calculates a "load", given on two deltas
calcLoad
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/Utils.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/Utils.java
Apache-2.0
public void printView() throws Exception { long iterationStartTime = System.currentTimeMillis(); long preCpuTime = operatingSystemMXBean.getProcessCpuTime(); vmInfo.update(); if (!checkState()) { return; } printJvmInfo(); if (mode == DetailMode.memory || mode == DetailMode.totalmemory) { printTopMemoryThreads(mode); } else { printTopCpuThreads(mode); } long deltaTime = System.currentTimeMillis() - iterationStartTime; long deltaCpuTime = (operatingSystemMXBean.getProcessCpuTime() - preCpuTime) / (Utils.NANOS_TO_MILLS); System.out.printf(" Cost time: %3dms, CPU time: %3dms%n", deltaTime, deltaCpuTime); System.out.print(" Input command (h for help):"); }
"detail" view, printing detail metrics of a specific jvm. Also printing the top threads (based on the current CPU usage) @author paru
printView
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VMDetailView.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VMDetailView.java
Apache-2.0
@Override public void run() { jmxClient.disconnect(); }
VMInfo retrieves or updates the metrics for a specific remote jvm, using JmxClient. @author paru
run
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
Apache-2.0
public void connect(TreeLinkNode root) { if(root == null) { return; } Queue<TreeLinkNode> queue = new LinkedList<TreeLinkNode>(); queue.add(root); while(!queue.isEmpty()) { Queue<TreeLinkNode> currentLevel = new LinkedList<TreeLinkNode>(); TreeLinkNode temp = null; while(!queue.isEmpty()) { TreeLinkNode current = queue.remove(); current.next = temp; temp = current; if(current.right != null) { currentLevel.add(current.right); } if(current.left!= null) { currentLevel.add(current.left); } } queue = currentLevel; } }
Definition for binary tree with next pointer. public class TreeLinkNode { int val; TreeLinkNode left, right, next; TreeLinkNode(int x) { val = x; } }
connect
java
kdn251/interviews
leetcode/depth-first-search/PopulatingNextRightPointersInEachNode.java
https://github.com/kdn251/interviews/blob/master/leetcode/depth-first-search/PopulatingNextRightPointersInEachNode.java
MIT
public static void main(String[] args) { Scanner input = new Scanner(System.in); int numberOfTestCases = input.nextInt(); while (numberOfTestCases != 0) { int[] numbers = new int[10]; int number = input.nextInt(); for (int i = number; i > 0; i--) { int j = i; while (j != 0) { numbers[j % 10]++; j = j / 10; } } for (int i = 0; i < 10; i++) { if (i != 0) { System.out.print(" "); } System.out.print(numbers[i]); } System.out.println(); numberOfTestCases--; } }
Trung is bored with his mathematics homeworks. He takes a piece of chalk and starts writing a sequence of consecutive integers starting with 1 to N (1 < N < 10000). After that, he counts the number of times each digit (0 to 9) appears in the sequence. For example, with N = 13, the sequence is: 12345678910111213 In this sequence, 0 appears once, 1 appears 6 times, 2 appears 2 times, 3 appears 3 times, and each digit from 4 to 9 appears once. After playing for a while, Trung gets bored again. He now wants to write a program to do this for him. Your task is to help him with writing this program. Input The input file consists of several data sets. The first line of the input file contains the number of data sets which is a positive integer and is not bigger than 20. The following lines describe the data sets. For each test case, there is one single line containing the number N. Output For each test case, write sequentially in one line the number of digit 0, 1, . . . 9 separated by a space. Sample Input 2 3 13 Sample Output 0 1 1 1 0 0 0 0 0 0 1 6 2 2 1 1 1 1 1 1
main
java
kdn251/interviews
uva/DigitCounting.java
https://github.com/kdn251/interviews/blob/master/uva/DigitCounting.java
MIT
private static void wrapRunnableField(Runnable runnable) { try { Class<? extends Runnable> runnableClass = runnable.getClass(); Optional<Field> originalRunnableFieldOpt = COMPARABLE_RUNNABLE_FIELD_MAP.computeIfAbsent(runnableClass.getName(), k -> { for (Field declaredField : runnableClass.getDeclaredFields()) { Class<?> declaredFieldType = declaredField.getType(); if (declaredFieldType.isAssignableFrom(Runnable.class) && !declaredFieldType.isAssignableFrom(Comparable.class)) { declaredField.setAccessible(true); return Optional.of(declaredField); } } return Optional.empty(); }); if (originalRunnableFieldOpt.isPresent()) { Field originalRunnableField = originalRunnableFieldOpt.get(); Runnable originalRunnable = (Runnable) originalRunnableField.get(runnable); if (originalRunnable instanceof RunnableWrapper) { return; } RunnableWrapper runnableWrapper = new RunnableWrapper(originalRunnable); originalRunnableField.set(runnable, runnableWrapper); } } catch (Exception e) { if (EXECEPTION_LOGGED.compareAndSet(false, true)) { System.err.printf("wrap original runnable %s failed.%n", runnable.getClass().getName()); } } }
issue: https://github.com/arextest/arex-agent-java/issues/516 executor with PriorityQueue ex: class PriorityRunnable extends Runnable implements Comparable<PriorityRunnable> { private final Runnable run; private final int priority; } can't wrap the PriorityRunnable because queue need runnable implement Comparable, so we need to wrap the original runnable field.
wrapRunnableField
java
arextest/arex-agent-java
arex-agent-bootstrap/src/main/java/io/arex/agent/bootstrap/ctx/RunnableWrapper.java
https://github.com/arextest/arex-agent-java/blob/master/arex-agent-bootstrap/src/main/java/io/arex/agent/bootstrap/ctx/RunnableWrapper.java
Apache-2.0
private void validateConstructorArguments() { TypeVariable<?>[] formals = rawType.getTypeParameters(); // check correct arity of actual type args if (formals.length != actualTypeArguments.length){ throw new MalformedParameterizedTypeException(); } for (int i = 0; i < actualTypeArguments.length; i++) { // check actuals against formals' bounds } }
ref: <a href="https://github.com/openjdk/jdk17/blob/master/src/java.base/share/classes/sun/reflect/generics/reflectiveObjects/ParameterizedTypeImpl.java"> sun/reflect/generics/reflectiveObjects/ParameterizedTypeImpl.java </a>
validateConstructorArguments
java
arextest/arex-agent-java
arex-agent-bootstrap/src/main/java/io/arex/agent/bootstrap/model/ParameterizedTypeImpl.java
https://github.com/arextest/arex-agent-java/blob/master/arex-agent-bootstrap/src/main/java/io/arex/agent/bootstrap/model/ParameterizedTypeImpl.java
Apache-2.0
public static ParameterizedTypeImpl make(Class<?> rawType, Type[] actualTypeArguments, Type ownerType) { return new ParameterizedTypeImpl(rawType, actualTypeArguments, ownerType); }
Static factory. Given a (generic) class, actual type arguments and an owner type, creates a parameterized type. This class can be instantiated with a a raw type that does not represent a generic type, provided the list of actual type arguments is empty. If the ownerType argument is null, the declaring class of the raw type is used as the owner type. <p> This method throws a MalformedParameterizedTypeException under the following circumstances: If the number of actual type arguments (i.e., the size of the array <tt>typeArgs</tt>) does not correspond to the number of formal type arguments. If any of the actual type arguments is not an instance of the bounds on the corresponding formal. @param rawType the Class representing the generic type declaration being instantiated @param actualTypeArguments - a (possibly empty) array of types representing the actual type arguments to the parameterized type @param ownerType - the enclosing type, if known. @return An instance of <tt>ParameterizedType</tt> @throws MalformedParameterizedTypeException - if the instantiation is invalid
make
java
arextest/arex-agent-java
arex-agent-bootstrap/src/main/java/io/arex/agent/bootstrap/model/ParameterizedTypeImpl.java
https://github.com/arextest/arex-agent-java/blob/master/arex-agent-bootstrap/src/main/java/io/arex/agent/bootstrap/model/ParameterizedTypeImpl.java
Apache-2.0
public static void deleteDirectory(File directory) throws IOException { if (!directory.exists()) { return; } cleanDirectory(directory); if (!directory.delete()) { String message = "Unable to delete directory " + directory + "."; throw new IOException(message); } }
Deletes a directory recursively. @param directory directory to delete @throws IOException in case deletion is unsuccessful
deleteDirectory
java
arextest/arex-agent-java
arex-agent-bootstrap/src/main/java/io/arex/agent/bootstrap/util/FileUtils.java
https://github.com/arextest/arex-agent-java/blob/master/arex-agent-bootstrap/src/main/java/io/arex/agent/bootstrap/util/FileUtils.java
Apache-2.0
public static void appendToClassLoaderSearch(ClassLoader classLoader, File jarFile) { try { if (classLoader instanceof URLClassLoader) { addURL.invoke(classLoader, jarFile.toURI().toURL()); } /* * Due to Java 8 vs java 9+ incompatibility issues * See https://stackoverflow.com/questions/46694600/java-9-compatability-issue-with-classloader-getsystemclassloader/51584718 */ ClassLoader urlClassLoader = ClassLoader.getSystemClassLoader(); if (!(urlClassLoader instanceof URLClassLoader)) { try (URLClassLoader tempClassLoader = new URLClassLoader(new URL[] {jarFile.toURI().toURL()}, urlClassLoader)) { addURL.invoke(tempClassLoader, jarFile.toURI().toURL()); } } else { addURL.invoke(urlClassLoader, jarFile.toURI().toURL()); } appendToAppClassLoaderSearch(classLoader, jarFile); } catch (Exception e) { System.err.printf("appendToClassLoaderSearch failed, classLoader: %s, jarFile: %s%n", classLoader.getClass().getName(), jarFile.getAbsolutePath()); } }
tomcat jdk <= 8, classLoader is ParallelWebappClassLoader, ClassLoader.getSystemClassLoader() is Launcher$AppClassLoader jdk > 8, classLoader is ParallelWebappClassLoader, ClassLoader.getSystemClassLoader() is ClassLoaders$AppClassLoader
appendToClassLoaderSearch
java
arextest/arex-agent-java
arex-agent-bootstrap/src/main/java/io/arex/agent/bootstrap/util/JarUtils.java
https://github.com/arextest/arex-agent-java/blob/master/arex-agent-bootstrap/src/main/java/io/arex/agent/bootstrap/util/JarUtils.java
Apache-2.0
private static void appendToAppClassLoaderSearch(ClassLoader classLoader, File jarFile) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Class<? extends ClassLoader> loaderClass = classLoader.getClass(); if (JdkUtils.isJdk11OrHigher() && ConfigConstants.APP_CLASSLOADER_NAME.equalsIgnoreCase(loaderClass.getName())) { Method classPathMethod = loaderClass.getDeclaredMethod("appendToClassPathForInstrumentation", String.class); classPathMethod.setAccessible(true); classPathMethod.invoke(classLoader, jarFile.getPath()); } }
append jar jdk.internal.loader.ClassLoaders.AppClassLoader if java version >= 11 need add jvm option:--add-opens=java.base/jdk.internal.loader=ALL-UNNAMED
appendToAppClassLoaderSearch
java
arextest/arex-agent-java
arex-agent-bootstrap/src/main/java/io/arex/agent/bootstrap/util/JarUtils.java
https://github.com/arextest/arex-agent-java/blob/master/arex-agent-bootstrap/src/main/java/io/arex/agent/bootstrap/util/JarUtils.java
Apache-2.0
public static String substringAfter(final String str, final String separator) { if (isEmpty(str)) { return str; } if (separator == null) { return EMPTY; } final int pos = str.indexOf(separator); if (pos == INDEX_NOT_FOUND) { return str; } return str.substring(pos + separator.length()); }
if not contains separator, return str
substringAfter
java
arextest/arex-agent-java
arex-agent-bootstrap/src/main/java/io/arex/agent/bootstrap/util/StringUtil.java
https://github.com/arextest/arex-agent-java/blob/master/arex-agent-bootstrap/src/main/java/io/arex/agent/bootstrap/util/StringUtil.java
Apache-2.0
public static Jwt generate(String jwt) { if (!ContextManager.needReplay()) { return null; } try { return parse(jwt); } catch (Throwable e) { LogManager.warn("parse jjwt error", e.getMessage()); return null; } }
refer to {@link DefaultJwtParser#parse(String)} remove the exception throw (such as ExpiredJwtException) @param jwt (token) @return if null mean execute original business code, not replay
generate
java
arextest/arex-agent-java
arex-instrumentation/authentication/arex-jwt/src/main/java/io/arex/inst/authentication/jwt/JJWTGenerator.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation/authentication/arex-jwt/src/main/java/io/arex/inst/authentication/jwt/JJWTGenerator.java
Apache-2.0
private static Jwt parse(String jwt) { if (StringUtil.isEmpty(jwt)) { return null; } String base64UrlEncodedHeader = null; String base64UrlEncodedPayload = null; String base64UrlEncodedDigest = null; int delimiterCount = 0; StringBuilder sb = new StringBuilder(128); for (char c : jwt.toCharArray()) { if (c == '.') { CharSequence tokenSeq = Strings.clean(sb.toString()); String token = tokenSeq != null ? tokenSeq.toString() : null; if (delimiterCount == 0) { base64UrlEncodedHeader = token; } else if (delimiterCount == 1) { base64UrlEncodedPayload = token; } delimiterCount++; sb.setLength(0); } else { sb.append(c); } } if (delimiterCount != 2) { return null; } if (sb.length() > 0) { base64UrlEncodedDigest = sb.toString(); } if (base64UrlEncodedPayload == null) { return null; } // =============== Header ================= Header header = null; if (base64UrlEncodedHeader != null) { String origValue = TextCodec.BASE64URL.decodeToString(base64UrlEncodedHeader); Map<String, Object> m = Serializer.deserialize(origValue, Map.class); if (m == null) { return null; } if (base64UrlEncodedDigest != null) { header = new DefaultJwsHeader(m); } else { header = new DefaultHeader(m); } } // =============== Body ================= String payload = TextCodec.BASE64URL.decodeToString(base64UrlEncodedPayload); Claims claims = null; if (payload.charAt(0) == '{' && payload.charAt(payload.length() - 1) == '}') { //likely to be json, parse it: Map<String, Object> claimsMap = Serializer.deserialize(payload, Map.class); claims = new DefaultClaims(claimsMap); } Object body = claims != null ? claims : payload; if (base64UrlEncodedDigest != null) { return new DefaultJws((JwsHeader) header, body, base64UrlEncodedDigest); } else { return new DefaultJwt<>(header, body); } }
this method is currently compatible with the following versions: jjwt: 0.1 ~ 0.9.1 jjwt-api: 0.10.0 ~ 0.11.2 (there may be differences in the future versions)
parse
java
arextest/arex-agent-java
arex-instrumentation/authentication/arex-jwt/src/main/java/io/arex/inst/authentication/jwt/JJWTGenerator.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation/authentication/arex-jwt/src/main/java/io/arex/inst/authentication/jwt/JJWTGenerator.java
Apache-2.0
public static void recordAllConfigs() { if (!ApolloConfigExtractor.needRecord()) { return; } ApolloConfigExtractor extractor = ApolloConfigExtractor.tryCreateExtractor(); if (extractor == null) { return; } Map<String, Config> configMap = getAllConfigInstance(); for (Map.Entry<String, Config> entry : configMap.entrySet()) { try { Properties properties = getConfigProperties(entry.getValue()); if (properties != null) { extractor.record(entry.getKey(), properties); } } catch (Throwable e) { LogManager.warn("record apollo config error", e); } } }
1. first record init config(full & incremental) {@link ApolloServletV3RequestHandler#postHandle} 2. then record changed config within running {@link ApolloDefaultConfigInstrumentation}
recordAllConfigs
java
arextest/arex-agent-java
arex-instrumentation/config/arex-apollo/src/main/java/io/arex/inst/config/apollo/ApolloConfigHelper.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation/config/arex-apollo/src/main/java/io/arex/inst/config/apollo/ApolloConfigHelper.java
Apache-2.0
private static String getReleaseKey() { return ArexConstants.PREFIX + ApolloConfigExtractor.currentReplayConfigBatchNo(); }
format: arex-fff55f0a-b457-4cbe-9183-ca1adcf0d851 during long polling pull configuration, the Apollo-Config-Server will determine whether it is the latest configuration based on the request param: releaseKey, if it is different between local and server, the server will return the latest configuration. the purpose of doing this is to use the real configuration after replay finished, that is, restore the real configuration.
getReleaseKey
java
arextest/arex-agent-java
arex-instrumentation/config/arex-apollo/src/main/java/io/arex/inst/config/apollo/ApolloConfigHelper.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation/config/arex-apollo/src/main/java/io/arex/inst/config/apollo/ApolloConfigHelper.java
Apache-2.0
@Advice.OnMethodEnter(skipOn = Advice.OnNonDefaultValue.class, suppress = Throwable.class) public static boolean onEnter() { return ApolloConfigExtractor.duringReplay(); }
not store config to local file during replay
onEnter
java
arextest/arex-agent-java
arex-instrumentation/config/arex-apollo/src/main/java/io/arex/inst/config/apollo/ApolloLocalFileConfigRepositoryInstrumentation.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation/config/arex-apollo/src/main/java/io/arex/inst/config/apollo/ApolloLocalFileConfigRepositoryInstrumentation.java
Apache-2.0
@Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class) public static void onExit(@Advice.FieldValue(value = "batchResultList",readOnly = false) List<BatchResult> batchResults, @Advice.FieldValue(value = "currentSql", readOnly = false) String currentSql, @Advice.Return(readOnly = false) List<BatchResult> result, @Advice.Argument(0) boolean isRollback, @Advice.Thrown(readOnly = false) Throwable throwable, @Advice.Local("extractorList") List<DatabaseExtractor> extractorList, @Advice.Local("mockResult") MockResult mockResult) { if (isRollback) { return; } if (mockResult != null && mockResult.notIgnoreMockResult()) { result = (List<BatchResult>) mockResult.getResult(); currentSql = null; batchResults.clear(); return; } if (extractorList == null || extractorList.isEmpty()) { return; } if (ContextManager.needRecord()) { int cnt = 0; for (BatchResult batchResult : result) { MappedStatement ms = batchResult.getMappedStatement(); for (Object parameterObject : batchResult.getParameterObjects()) { if (cnt >= extractorList.size()) { return; } InternalExecutor.record(extractorList.get(cnt), ms, parameterObject, StringUtil.EMPTY, throwable); cnt++; } } } }
Generate executor list in advance, because the insert operation will modify sql and parameters, resulting in inconsistent record and replay
onExit
java
arextest/arex-agent-java
arex-instrumentation/database/arex-database-mybatis3/src/main/java/io/arex/inst/database/mybatis3/ExecutorInstrumentation.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation/database/arex-database-mybatis3/src/main/java/io/arex/inst/database/mybatis3/ExecutorInstrumentation.java
Apache-2.0
@Advice.OnMethodEnter(suppress = Throwable.class) public static void onEnter(@Advice.FieldValue("requestMetadata") RequestMetadata requestMetadata, @Advice.FieldValue("listener") ClientCall.Listener listener) { if (ContextManager.needReplay()) { DubboStreamConsumerExtractor.close(listener, requestMetadata); } }
BI_stream and Client_stream these two streams may have multiple requests, only after all the requests are completed can the onClose logic be triggered
onEnter
java
arextest/arex-agent-java
arex-instrumentation/dubbo/arex-dubbo-apache-v3/src/main/java/io/arex/inst/dubbo/apache/v3/stream/DubboStreamConsumerInstrumentation.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation/dubbo/arex-dubbo-apache-v3/src/main/java/io/arex/inst/dubbo/apache/v3/stream/DubboStreamConsumerInstrumentation.java
Apache-2.0
public static String getLocatedClass(Object loader) { if (loader == null) { return StringUtil.EMPTY; } int loaderHashCode = System.identityHashCode(loader); String locatedClassName = NO_REFERENCE_MAP.get(loaderHashCode); if (locatedClassName != null) { return locatedClassName; } Class<?> loaderClass = loader.getClass(); Field field = REFERENCE_FIELD_MAP.computeIfAbsent(loaderHashCode, k -> getReferenceField(loaderClass)); if (field == null) { return generateNameWithNoReference(loaderHashCode, loaderClass); } String className = getReferenceClass(field, loader); if (StringUtil.startWith(field.getName(), EXTERNAL_VARIABLE_REFERENCE_IDENTIFIER)) { NO_REFERENCE_MAP.put(loaderHashCode, className); } return className; }
Cache loader is mainly divided into three scenarios: 1. public static final LoadingCache<String, Object> cacheStaticData = CacheBuilder.newBuilder().build(new CacheLoader<String, Object>() {...}); In this case, we can directly obtain the cache loader class name to distinguish the cache loader. <p> 2. public static final LoadingCache<String, Object> fatherCache = CacheBuilder.newBuilder().build(new CacheLoader<String, Object>() {abstract load() {...}}); <p> childCache1 extends fatherCache, childCache2 extends fatherCache. and override the load method. In this case, we need to obtain the childCache1 or childCache2 class name to distinguish the cache loader. the method parameter is the fatherCache, we can get the childCache1 or childCache2 class name from field this$0. <p> 3. public createLoadingCache(Object task) {CacheBuilder.newBuilder().build(new CacheLoader<String, Object>() {task.load()}); In this case, we need to obtain the task class name to distinguish the cache loader. the method parameter is the cacheLoader, we can get the task class name from field val$task.
getLocatedClass
java
arextest/arex-agent-java
arex-instrumentation/dynamic/arex-cache/src/main/java/io/arex/inst/cache/util/CacheLoaderUtil.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation/dynamic/arex-cache/src/main/java/io/arex/inst/cache/util/CacheLoaderUtil.java
Apache-2.0
private static String generateNameWithNoReference(int loaderHashCode, Class<?> loaderClass) { String loaderClassName = StringUtil.substringBefore(loaderClass.getName(), LAMBDA_SUFFIX); NO_REFERENCE_MAP.put(loaderHashCode, loaderClassName); return loaderClassName; }
cache loader without external references directly obtain class name, and remove lambda suffix. @return
generateNameWithNoReference
java
arextest/arex-agent-java
arex-instrumentation/dynamic/arex-cache/src/main/java/io/arex/inst/cache/util/CacheLoaderUtil.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation/dynamic/arex-cache/src/main/java/io/arex/inst/cache/util/CacheLoaderUtil.java
Apache-2.0
public static <T> FutureCallback<T> wrap(FutureCallback<T> delegate) { if (delegate instanceof FutureCallbackWrapper) { return delegate; } return new FutureCallbackWrapper<>(delegate); }
Wrap the delegate with FutureCallbackWrapper for arex trace propagation
wrap
java
arextest/arex-agent-java
arex-instrumentation/httpclient/arex-httpclient-apache-v4/src/main/java/io/arex/inst/httpclient/apache/async/FutureCallbackWrapper.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation/httpclient/arex-httpclient-apache-v4/src/main/java/io/arex/inst/httpclient/apache/async/FutureCallbackWrapper.java
Apache-2.0
@Override public void run() { try (TraceTransmitter transmit = transmitter.transmit()){ extractor.record(responseFuture.get(1, TimeUnit.SECONDS)); } catch (InterruptedException interruptedException) { Thread.currentThread().interrupt(); LogManager.warn("ResponseFutureListener.run", interruptedException); } catch (Exception exception) { LogManager.warn("ResponseFutureListener.run", exception); } }
responseFuture is com.ning.http.client.ListenableFuture, only Future.get() to get the response. only when the responseFuture is done, run will be called, record response.
run
java
arextest/arex-agent-java
arex-instrumentation/httpclient/arex-httpclient-ning/src/main/java/io/arex/inst/httpclient/ning/ResponseFutureListener.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation/httpclient/arex-httpclient-ning/src/main/java/io/arex/inst/httpclient/ning/ResponseFutureListener.java
Apache-2.0
public static StatusLine parse(String statusLine) throws IOException { // H T T P / 1 . 1 2 0 0 T e m p o r a r y R e d i r e c t // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 // Parse protocol like "HTTP/1.1" followed by a space. int codeStart; Protocol protocol; if (statusLine.startsWith("HTTP/1.")) { if (statusLine.length() < 9 || statusLine.charAt(8) != ' ') { throw new ProtocolException(EXCEPTION_PREFIX + statusLine); } int httpMinorVersion = statusLine.charAt(7) - '0'; codeStart = 9; if (httpMinorVersion == 0) { protocol = Protocol.HTTP_1_0; } else if (httpMinorVersion == 1) { protocol = Protocol.HTTP_1_1; } else { throw new ProtocolException(EXCEPTION_PREFIX + statusLine); } } else if (statusLine.startsWith("ICY ")) { // Shoutcast uses ICY instead of "HTTP/1.0". protocol = Protocol.HTTP_1_0; codeStart = 4; } else { throw new ProtocolException(EXCEPTION_PREFIX + statusLine); } // Parse response code like "200". Always 3 digits. if (statusLine.length() < codeStart + 3) { throw new ProtocolException(EXCEPTION_PREFIX + statusLine); } int code; try { code = Integer.parseInt(statusLine.substring(codeStart, codeStart + 3)); } catch (NumberFormatException e) { throw new ProtocolException(EXCEPTION_PREFIX + statusLine); } // Parse an optional response message like "OK" or "Not Modified". If it // exists, it is separated from the response code by a space. String message = ""; if (statusLine.length() > codeStart + 3) { if (statusLine.charAt(codeStart + 3) != ' ') { throw new ProtocolException(EXCEPTION_PREFIX + statusLine); } message = statusLine.substring(codeStart + 4); } return new StatusLine(protocol, code, message); }
This file is a copy of okhttp3.internal.http.StatusLine, compatible with version 3.x Version 4.x is in the Inner class StatusLine#companion#parse
parse
java
arextest/arex-agent-java
arex-instrumentation/httpclient/arex-httpclient-okhttp-v3/src/main/java/io/arex/inst/httpclient/okhttp/v3/StatusLineAdapter.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation/httpclient/arex-httpclient-okhttp-v3/src/main/java/io/arex/inst/httpclient/okhttp/v3/StatusLineAdapter.java
Apache-2.0
private static io.netty.util.AttributeKey<Mocker> initAttributeKey() { Object instance = null; try { // the user's Netty version is only known at runtime instance = ReflectUtil.getFieldOrInvokeMethod( () -> io.netty.util.AttributeKey.class.getDeclaredMethod("valueOf", Class.class, String.class), null, AttributeKey.class, "arex-netty-server-mocker"); } catch (Exception e) { // ignore, < 4.1.0 not exist valueOf method } if (instance instanceof io.netty.util.AttributeKey) { return (io.netty.util.AttributeKey<Mocker>) instance; } // direct call return new io.netty.util.AttributeKey<>("arex-netty-server-mocker"); }
compatible with different versions of netty initAttributeKey method, the reason for using a lower version of netty here is support more versions of netty, and discover many incompatible problem during compilation
initAttributeKey
java
arextest/arex-agent-java
arex-instrumentation/netty/arex-netty-v4/src/main/java/io/arex/inst/netty/v4/common/AttributeKey.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation/netty/arex-netty-v4/src/main/java/io/arex/inst/netty/v4/common/AttributeKey.java
Apache-2.0
@Test void case1() throws Exception { Mockito.when(ContextManager.needRecordOrReplay()).thenReturn(false); target.write(ctx, httpResponse, promise); verify(ctx).write(any(), any()); mockUtilsStatic.verify(() -> MockUtils.replayMocker(mocker), times(0)); mockUtilsStatic.verify(() -> MockUtils.recordMocker(mocker), times(0)); }
mock: ContextManager.needRecordOrReplay() returns true <p> verify: super.write(ctx, msg, promise) is executed once replayMocker and recordMocker are not executed
case1
java
arextest/arex-agent-java
arex-instrumentation/netty/arex-netty-v4/src/test/java/io/arex/inst/netty/v4/server/ResponseTracingHandlerTest.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation/netty/arex-netty-v4/src/test/java/io/arex/inst/netty/v4/server/ResponseTracingHandlerTest.java
Apache-2.0
@Test void case2() throws Exception { Mockito.when(ContextManager.needRecordOrReplay()).thenReturn(true); Mockito.when(ContextManager.needReplay()).thenReturn(true); Mockito.when(ContextManager.needRecord()).thenReturn(false); Mockito.when(ctx.channel()).thenReturn(channel); Mockito.when(channel.attr(any())).thenReturn(attribute); Mockito.when(attribute.get()).thenReturn(mocker); Mockito.when(NettyHelper.parseBody(any())).thenReturn("mock"); httpResponse = mock(HttpResponse.class); target.write(ctx, httpResponse, promise); verify(ctx, times(1)).write(any(), any()); mockUtilsStatic.verify(() -> MockUtils.replayMocker(mocker), times(0)); mockUtilsStatic.verify(() -> MockUtils.recordMocker(mocker), times(0)); }
mock: ContextManager.needRecordOrReplay() returns true msg is of type HttpResponse <p> verify: super.write(ctx, msg, promise) is executed once replayMocker and recordMocker are not executed
case2
java
arextest/arex-agent-java
arex-instrumentation/netty/arex-netty-v4/src/test/java/io/arex/inst/netty/v4/server/ResponseTracingHandlerTest.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation/netty/arex-netty-v4/src/test/java/io/arex/inst/netty/v4/server/ResponseTracingHandlerTest.java
Apache-2.0
@Test void case3() throws Exception { Mockito.when(ContextManager.needRecordOrReplay()).thenReturn(true); Mockito.when(ContextManager.needReplay()).thenReturn(true); Mockito.when(ContextManager.needRecord()).thenReturn(false); Mockito.when(ctx.channel()).thenReturn(channel); Mockito.when(channel.attr(any())).thenReturn(attribute); Mockito.when(attribute.get()).thenReturn(mocker); Mockito.when(NettyHelper.parseBody(any())).thenReturn("mock"); Mockito.when(ContextManager.currentContext()).thenReturn(arexContext); Mockito.when(httpResponse.headers()).thenReturn(headers); target.write(ctx, httpResponse, promise); verify(ctx, times(1)).write(any(), any()); mockUtilsStatic.verify(() -> MockUtils.replayMocker(mocker), times(1)); mockUtilsStatic.verify(() -> MockUtils.recordMocker(mocker), times(0)); }
mock: ContextManager.needRecordOrReplay() returns true needReplay is true needRecord is false <p> verify: super.write(ctx, msg, promise) is executed once MockUtils.replayBody and MockUtils.recordMocker are not executed
case3
java
arextest/arex-agent-java
arex-instrumentation/netty/arex-netty-v4/src/test/java/io/arex/inst/netty/v4/server/ResponseTracingHandlerTest.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation/netty/arex-netty-v4/src/test/java/io/arex/inst/netty/v4/server/ResponseTracingHandlerTest.java
Apache-2.0
@Test void case4() throws Exception { Mockito.when(ContextManager.needRecordOrReplay()).thenReturn(true); Mockito.when(ContextManager.needReplay()).thenReturn(false); Mockito.when(ContextManager.needRecord()).thenReturn(true); Mockito.when(ctx.channel()).thenReturn(channel); Mockito.when(channel.attr(any())).thenReturn(attribute); Mockito.when(attribute.get()).thenReturn(mocker); Mockito.when(NettyHelper.parseBody(any())).thenReturn("mock"); Mockito.when(ContextManager.currentContext()).thenReturn(arexContext); Mockito.when(httpResponse.headers()).thenReturn(headers); target.write(ctx, httpResponse, promise); verify(ctx, times(1)).write(any(), any()); mockUtilsStatic.verify(() -> MockUtils.replayMocker(mocker), times(0)); mockUtilsStatic.verify(() -> MockUtils.recordMocker(mocker), times(1)); }
mock: ContextManager.needRecordOrReplay() returns true needReplay is false needRecord is true <p> verify: super.write(ctx, msg, promise) is executed once MockUtils.replayBody is executed
case4
java
arextest/arex-agent-java
arex-instrumentation/netty/arex-netty-v4/src/test/java/io/arex/inst/netty/v4/server/ResponseTracingHandlerTest.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation/netty/arex-netty-v4/src/test/java/io/arex/inst/netty/v4/server/ResponseTracingHandlerTest.java
Apache-2.0
public static CommandAsyncExecutor getCommandAsyncExecutor(RedissonClient redisson) { if (redisson == null || getCommandExecutorMethod == null) { return null; } try { return (CommandAsyncExecutor) getCommandExecutorMethod.invoke(redisson); } catch (Exception e) { LogManager.warn("redis.commandExecutor", e); return null; } }
compatible with redisson versions lower than 3.16.0 (<3.16.0) @param redisson @return
getCommandAsyncExecutor
java
arextest/arex-agent-java
arex-instrumentation/redis/arex-redission-v3/src/main/java/io/arex/inst/redisson/v3/common/RedissonHelper.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation/redis/arex-redission-v3/src/main/java/io/arex/inst/redisson/v3/common/RedissonHelper.java
Apache-2.0
public static boolean matchAndRemoveRequestParams(Map<String, List<String>> requestParams, String name, String value) { if (MapUtils.isEmpty(requestParams)) { return false; } List<String> values = requestParams.get(name); if(CollectionUtil.isEmpty(values)){ return false; } Iterator<String> iterator = values.iterator(); while (iterator.hasNext()) { String next = iterator.next(); if (StringUtil.equals(next, value)) { iterator.remove(); return true; } } return false; }
match requset params @param requestParams @param name @param value @return
matchAndRemoveRequestParams
java
arextest/arex-agent-java
arex-instrumentation/servlet/arex-httpservlet/src/main/java/io/arex/inst/httpservlet/ServletUtil.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation/servlet/arex-httpservlet/src/main/java/io/arex/inst/httpservlet/ServletUtil.java
Apache-2.0
public static Map<String, List<String>> getRequestParams(String queryString) { if (StringUtil.isEmpty(queryString)) { return Collections.emptyMap(); } MultiValueMap<String, String> paramsKeyValueMap = UriComponentsBuilder.fromUriString( "?" + queryString).build().getQueryParams(); Map<String, List<String>> requestParamsMap = new HashMap<>(); for (Map.Entry<String, List<String>> entry : paramsKeyValueMap.entrySet()) { requestParamsMap.put(entry.getKey(), new ArrayList<>(entry.getValue())); } return requestParamsMap; }
obtain requset params @param queryString @return
getRequestParams
java
arextest/arex-agent-java
arex-instrumentation/servlet/arex-httpservlet/src/main/java/io/arex/inst/httpservlet/ServletUtil.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation/servlet/arex-httpservlet/src/main/java/io/arex/inst/httpservlet/ServletUtil.java
Apache-2.0
@Deprecated public int getStatusCode() { return getStatus(); }
Return the status code as specified on the response. @deprecated as of 5.2 in favor of {@link HttpServletResponse#getStatus()}
getStatusCode
java
arextest/arex-agent-java
arex-instrumentation/servlet/arex-httpservlet/src/main/java/io/arex/inst/httpservlet/wrapper/CachedBodyResponseWrapperV3.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation/servlet/arex-httpservlet/src/main/java/io/arex/inst/httpservlet/wrapper/CachedBodyResponseWrapperV3.java
Apache-2.0
public InputStream getContentInputStream() { return this.content.getInputStream(); }
Return an {@link InputStream} to the cached content. @since 4.2
getContentInputStream
java
arextest/arex-agent-java
arex-instrumentation/servlet/arex-httpservlet/src/main/java/io/arex/inst/httpservlet/wrapper/CachedBodyResponseWrapperV5.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation/servlet/arex-httpservlet/src/main/java/io/arex/inst/httpservlet/wrapper/CachedBodyResponseWrapperV5.java
Apache-2.0
public int getContentSize() { return this.content.size(); }
Return the current size of the cached content. @since 4.2
getContentSize
java
arextest/arex-agent-java
arex-instrumentation/servlet/arex-httpservlet/src/main/java/io/arex/inst/httpservlet/wrapper/CachedBodyResponseWrapperV5.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation/servlet/arex-httpservlet/src/main/java/io/arex/inst/httpservlet/wrapper/CachedBodyResponseWrapperV5.java
Apache-2.0
public static ArexContext currentContext(boolean createIfAbsent, String recordId) { String traceId = TraceContextManager.get(createIfAbsent); if (StringUtil.isEmpty(traceId)) { return null; } if (createIfAbsent) { final ArexContext arexContext = createContext(recordId, traceId); publish(arexContext, true); RECORD_MAP.put(traceId, arexContext); return arexContext; } return RECORD_MAP.get(traceId); }
agent will call this method record scene: recordId is map key replay scene: replayId is map key
currentContext
java
arextest/arex-agent-java
arex-instrumentation-api/src/main/java/io/arex/inst/runtime/context/ContextManager.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation-api/src/main/java/io/arex/inst/runtime/context/ContextManager.java
Apache-2.0
public static void enter() { CallDepth callDepth = Context.get(true); if (callDepth != null) { callDepth.getAndIncrement(); } }
Avoid collecting data multiple times on the call chain
enter
java
arextest/arex-agent-java
arex-instrumentation-api/src/main/java/io/arex/inst/runtime/context/RepeatedCollectManager.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation-api/src/main/java/io/arex/inst/runtime/context/RepeatedCollectManager.java
Apache-2.0
@Override boolean internalCheck(MatchStrategyContext context) { // if no request params, do next fuzzy match directly return StringUtil.isNotEmpty(context.getRequestMocker().getTargetRequest().getBody()); }
search by operationName + requestBody priority: 1. if matching and not matched before return directly 2. if matched before and find-last mode, return matched one 3. if matched multiple result, give next fuzzy match 4. if strict match mode and not matched, interrupt
internalCheck
java
arextest/arex-agent-java
arex-instrumentation-api/src/main/java/io/arex/inst/runtime/match/AccurateMatchStrategy.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation-api/src/main/java/io/arex/inst/runtime/match/AccurateMatchStrategy.java
Apache-2.0
void process(MatchStrategyContext context) { context.setMatchStrategy(MatchStrategyEnum.EIGEN); // to be implemented after database merge replay support }
search by eigen value of request
process
java
arextest/arex-agent-java
arex-instrumentation-api/src/main/java/io/arex/inst/runtime/match/EigenMatchStrategy.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation-api/src/main/java/io/arex/inst/runtime/match/EigenMatchStrategy.java
Apache-2.0
public static <T> T deserialize(String value, Class<T> clazz) { if (StringUtil.isEmpty(value) || clazz == null) { return null; } try { return INSTANCE.getSerializer().deserialize(value, clazz); } catch (Throwable ex) { LogManager.warn("serializer-deserialize", StringUtil.format("can not deserialize value %s to class %s, cause: %s", value, clazz.getName(), ex.toString())); return null; } }
Deserialize by Class @param value String to be deserialized @param clazz class to deserialize, example: com.xxx.xxxClass @return T
deserialize
java
arextest/arex-agent-java
arex-instrumentation-api/src/main/java/io/arex/inst/runtime/serializer/Serializer.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation-api/src/main/java/io/arex/inst/runtime/serializer/Serializer.java
Apache-2.0
default void addMapSerializer(Class<?> clazz) { addTypeSerializer(clazz, null); }
Method for adding serializer to handle values of Map type.
addMapSerializer
java
arextest/arex-agent-java
arex-instrumentation-api/src/main/java/io/arex/inst/runtime/serializer/StringSerializable.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation-api/src/main/java/io/arex/inst/runtime/serializer/StringSerializable.java
Apache-2.0
public static boolean ignoreMockResult(String serviceKey, String operationKey) { if (StringUtil.isEmpty(serviceKey)) { return false; } ArexContext context = ContextManager.currentContext(); if (context == null || context.getExcludeMockTemplate() == null) { return false; } Map<String, Set<String>> excludeMockTemplate = context.getExcludeMockTemplate(); if (!excludeMockTemplate.containsKey(serviceKey)) { return false; } Set<String> operationSet = excludeMockTemplate.get(serviceKey); // If empty, this service all operations ignore mock result if (operationSet == null || operationSet.isEmpty()) { LogManager.info("ignoreMock", StringUtil.format("service:%s all operations ignore mock result", serviceKey)); return true; } // Specified operation ignore mock result if (operationSet.contains(operationKey)) { LogManager.info("ignoreMock", StringUtil.format("operation:%s.%s ignore mock result", serviceKey, operationKey)); return true; } return false; }
operation cache: can not serialize args or response
ignoreMockResult
java
arextest/arex-agent-java
arex-instrumentation-api/src/main/java/io/arex/inst/runtime/util/IgnoreUtils.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation-api/src/main/java/io/arex/inst/runtime/util/IgnoreUtils.java
Apache-2.0
public static boolean includeOperation(String targetName) { if (StringUtil.isEmpty(targetName) || Config.get() == null) { return false; } Set<String> includeServiceOperations = Config.get().getIncludeServiceOperations(); return operationMatched(targetName, includeServiceOperations); }
Include the operation that need to record or replay
includeOperation
java
arextest/arex-agent-java
arex-instrumentation-api/src/main/java/io/arex/inst/runtime/util/IgnoreUtils.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation-api/src/main/java/io/arex/inst/runtime/util/IgnoreUtils.java
Apache-2.0
public static boolean excludeOperation(String targetName) { if (StringUtil.isEmpty(targetName) || Config.get() == null) { return false; } Set<String> excludeServiceOperations = Config.get().excludeServiceOperations(); boolean isOperationMatched = operationMatched(targetName, excludeServiceOperations); if (isOperationMatched && ContextManager.needReplay()) { LogManager.warn("replay.hitBlockList", StringUtil.format("Hit block list, target name: %s", targetName)); } return isOperationMatched; }
Exclude the operation that not need to record or replay
excludeOperation
java
arextest/arex-agent-java
arex-instrumentation-api/src/main/java/io/arex/inst/runtime/util/IgnoreUtils.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation-api/src/main/java/io/arex/inst/runtime/util/IgnoreUtils.java
Apache-2.0
public static boolean excludeEntranceOperation(String targetName) { if (Config.get() != null && CollectionUtil.isNotEmpty(Config.get().getIncludeServiceOperations())) { return !includeOperation(targetName); } return excludeOperation(targetName); }
Exclude entrance operation by includeServiceOperations and excludeServiceOperations. First if includeServiceOperations is not empty, only use excludeServiceOperations to judge. Second if includeServiceOperations is empty, use excludeServiceOperations to jude.
excludeEntranceOperation
java
arextest/arex-agent-java
arex-instrumentation-api/src/main/java/io/arex/inst/runtime/util/IgnoreUtils.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation-api/src/main/java/io/arex/inst/runtime/util/IgnoreUtils.java
Apache-2.0
public static void mergeRecord(Mocker requestMocker) { List<List<Mocker>> mergeList = merge(requestMocker); for (List<Mocker> mergeRecords : mergeList) { MockUtils.executeRecord(mergeRecords); } }
To solve the problem of insufficient consume capacity of downstream DataServices. by controlling the speed at which producers produce mockers. multiple producer -> single consumer
mergeRecord
java
arextest/arex-agent-java
arex-instrumentation-api/src/main/java/io/arex/inst/runtime/util/MergeRecordUtil.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation-api/src/main/java/io/arex/inst/runtime/util/MergeRecordUtil.java
Apache-2.0
public static void queryMockers() { if (!ContextManager.needReplay()) { return; } try { QueryAllMockerDTO requestMocker = new QueryAllMockerDTO(); requestMocker.setRecordId(ContextManager.currentContext().getCaseId()); requestMocker.setReplayId(ContextManager.currentContext().getReplayId()); List<Mocker> allMockerList = MockUtils.queryMockers(requestMocker); if (CollectionUtil.isEmpty(allMockerList)) { return; } filterMergeMocker(allMockerList); Map<Integer, List<Mocker>> cachedReplayResultMap = ContextManager.currentContext().getCachedReplayResultMap(); cachedReplayResultMap.clear(); buildReplayResultMap(allMockerList, cachedReplayResultMap); ascendingSortByCreationTime(cachedReplayResultMap); } catch (Exception e) { LogManager.warn("replay.all.mocker", e); } }
init replay all mocker under case and cached replay result
queryMockers
java
arextest/arex-agent-java
arex-instrumentation-api/src/main/java/io/arex/inst/runtime/util/ReplayUtil.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation-api/src/main/java/io/arex/inst/runtime/util/ReplayUtil.java
Apache-2.0
void changeRate() { if (!validate()) { return; } double targetRate = ConfigManager.INSTANCE.getRecordRate(); for (Map.Entry<String, Pair<Double, RateLimiter>> entry : RATE_LIMITER_MAP.entrySet()) { targetRate = MIN_RATE; RATE_LIMITER_MAP.put(entry.getKey(), Pair.of(targetRate, RateLimiter.create(targetRate / BASE))); } System.setProperty(ConfigConstants.CURRENT_RATE, String.format("%.2f", targetRate)); System.setProperty(ConfigConstants.DECELERATE_CODE, DecelerateReasonEnum.SERVICE_EXCEPTION.getCodeStr()); LogManager.warn("healthManager.decelerate", StringUtil.format("service exception! decrement record rate, current rate change to: %s", String.format("%.2f", targetRate))); }
Decrement record rate to {@link #MIN_RATE} trigger if service exception
changeRate
java
arextest/arex-agent-java
arex-instrumentation-foundation/src/main/java/io/arex/foundation/healthy/HealthManager.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation-foundation/src/main/java/io/arex/foundation/healthy/HealthManager.java
Apache-2.0
void decelerate() { if (!validate()) { return; } double targetRate = ConfigManager.INSTANCE.getRecordRate(); for (Map.Entry<String, Pair<Double, RateLimiter>> entry : RATE_LIMITER_MAP.entrySet()) { Pair<Double, RateLimiter> limiterPair = entry.getValue(); targetRate = Math.max(limiterPair.getFirst() * 0.8, MIN_RATE); RATE_LIMITER_MAP.put(entry.getKey(), Pair.of(targetRate, RateLimiter.create(targetRate / BASE))); } System.setProperty(ConfigConstants.CURRENT_RATE, String.format("%.2f", targetRate)); System.setProperty(ConfigConstants.DECELERATE_CODE, DecelerateReasonEnum.QUEUE_OVERFLOW.getCodeStr()); LogManager.warn("healthManager.decelerate", StringUtil.format("queue overflow! decrement record rate, current rate change to: %s", String.format("%.2f", targetRate))); }
Decrement record rate by 20% trigger if queue is full
decelerate
java
arextest/arex-agent-java
arex-instrumentation-foundation/src/main/java/io/arex/foundation/healthy/HealthManager.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation-foundation/src/main/java/io/arex/foundation/healthy/HealthManager.java
Apache-2.0
private Builder<?> getMessageBuilder(Class<?> clazz) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { Method method = clazz.getDeclaredMethod("newBuilder"); return (Builder<?>) method.invoke(null); }
Create Class.Builder based on Class reflection for Json deserialization @param clazz @return Class.Builder
getMessageBuilder
java
arextest/arex-agent-java
arex-instrumentation-foundation/src/main/java/io/arex/foundation/serializer/ProtoJsonSerializer.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation-foundation/src/main/java/io/arex/foundation/serializer/ProtoJsonSerializer.java
Apache-2.0
@Override public AbstractMessage read(JsonReader in) throws IOException { final JsonElement parse = Streams.parse(in); final String json = GSON.toJson(parse); return (AbstractMessage) ProtoJsonSerializer.getInstance().deserialize(json, rawClass); }
Streams.parse(in) will return a JsonObject object, which needs to be serialized to json first, and then deserialized and restored to the original type by ProtoJsonSerializer
read
java
arextest/arex-agent-java
arex-instrumentation-foundation/src/main/java/io/arex/foundation/serializer/gson/adapter/ProtoBufTypeAdapter.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation-foundation/src/main/java/io/arex/foundation/serializer/gson/adapter/ProtoBufTypeAdapter.java
Apache-2.0
@Override public boolean useForType(JavaType type) { Class<?> rawClass = type.getRawClass(); return rawClass.isInterface() && StringUtil.startWith(rawClass.getName(), FastUtilAdapterFactory.FASTUTIL_PACKAGE); }
@return true will serialize with runtime type info
useForType
java
arextest/arex-agent-java
arex-instrumentation-foundation/src/main/java/io/arex/foundation/serializer/jackson/JacksonSerializer.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation-foundation/src/main/java/io/arex/foundation/serializer/jackson/JacksonSerializer.java
Apache-2.0
public Date parseDate(final String source) { return parseDate(source, null); }
Parse date without timezone @param source datetime string @return Date
parseDate
java
arextest/arex-agent-java
arex-instrumentation-foundation/src/main/java/io/arex/foundation/serializer/util/DateFormatParser.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation-foundation/src/main/java/io/arex/foundation/serializer/util/DateFormatParser.java
Apache-2.0
public Date parseDate(String source, TimeZone timeZone) { if (StringUtil.isEmpty(source)) { return null; } if (timeZone == null) { timeZone = TimezoneParser.INSTANCE.parse(source); } try { if (source.length() >= TimePatternConstants.SIMPLE_DATE_FORMAT_WITH_TIMEZONE.length()) { source = source.substring(0, TimePatternConstants.SIMPLE_DATE_FORMAT_MILLIS.length()).replace('T', ' '); } String pattern = DATE_PATTERN_MAP.getOrDefault(source.length(), TimePatternConstants.SIMPLE_DATE_FORMAT_MILLIS); return FastDateFormat.getInstance(pattern, timeZone).parse(source); } catch (ParseException e) { LogManager.warn("parseDate", e); return null; } }
Parse date with timezone @param source datetime string @return Date
parseDate
java
arextest/arex-agent-java
arex-instrumentation-foundation/src/main/java/io/arex/foundation/serializer/util/DateFormatParser.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation-foundation/src/main/java/io/arex/foundation/serializer/util/DateFormatParser.java
Apache-2.0
public DateTimeFormatter getFormatter(final String source, final String defaultPattern) { String pattern = DATE_PATTERN_MAP.getOrDefault(source.length(), defaultPattern); return DEFAULT_FORMATTER_MAP.computeIfAbsent(pattern, DateTimeFormatter::ofPattern); }
Get datetime formatter @param source datetime string @param defaultPattern default datetime pattern @return DateTimeFormatter instance
getFormatter
java
arextest/arex-agent-java
arex-instrumentation-foundation/src/main/java/io/arex/foundation/serializer/util/DateFormatParser.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation-foundation/src/main/java/io/arex/foundation/serializer/util/DateFormatParser.java
Apache-2.0
public DateTimeFormatter getFormatter(final String pattern) { return DEFAULT_FORMATTER_MAP.computeIfAbsent(pattern, DateTimeFormatter::ofPattern); }
Get datetime formatter @param pattern datetime pattern @return DateTimeFormatter instance
getFormatter
java
arextest/arex-agent-java
arex-instrumentation-foundation/src/main/java/io/arex/foundation/serializer/util/DateFormatParser.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation-foundation/src/main/java/io/arex/foundation/serializer/util/DateFormatParser.java
Apache-2.0
public static Object restoreRange(String json) { try { Object rangeDeserializer = JacksonSerializerWithType.INSTANCE.deserialize(json, rangeClass); if (StringUtil.containsIgnoreCase(json, GUAVA_BELOW_ALL_CLASS_NAME)) { lowerBoundField.set(rangeDeserializer, belowAllInstance); } if (StringUtil.containsIgnoreCase(json, GUAVA_ABOVE_ALL_CLASS_NAME)) { upperBoundField.set(rangeDeserializer, aboveAllInstance); } return rangeDeserializer; } catch (Throwable e) { LogManager.warn("rang.restore", e); return null; } }
<relocation> <pattern>com.google</pattern> <shadedPattern>shaded.com.google</shadedPattern> </relocation> after packaging, com.google.** will be relocated to shaded.com.google.**. String also will be relocated. so in order to get the Range type at runtime, need to remove the shaded prefix ex: String GUAVA_RANGE_CLASS_NAME = com.google.common.collect.Range -> shaded.com.google.common.collect.Range
restoreRange
java
arextest/arex-agent-java
arex-instrumentation-foundation/src/main/java/io/arex/foundation/serializer/util/GuavaRangeManager.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation-foundation/src/main/java/io/arex/foundation/serializer/util/GuavaRangeManager.java
Apache-2.0
public static boolean isGuavaRange(String typeName) { return GUAVA_RANGE_CLASS_NAME.endsWith(typeName); }
Guava_RANGE will be shaded, so use endswith.
isGuavaRange
java
arextest/arex-agent-java
arex-instrumentation-foundation/src/main/java/io/arex/foundation/serializer/util/GuavaRangeManager.java
https://github.com/arextest/arex-agent-java/blob/master/arex-instrumentation-foundation/src/main/java/io/arex/foundation/serializer/util/GuavaRangeManager.java
Apache-2.0
private static String testDynamic(int num) { return UUID.randomUUID().toString(); }
the value returned by each call is different, but if replayed, the recorded value should be returned normally
testDynamic
java
arextest/arex-agent-java
arex-integration-tests/arex-dynamic-integration-test/src/test/java/io/arex/integrationtest/dynamic/DynamicClassIT.java
https://github.com/arextest/arex-agent-java/blob/master/arex-integration-tests/arex-dynamic-integration-test/src/test/java/io/arex/integrationtest/dynamic/DynamicClassIT.java
Apache-2.0
private void init(final Calendar definingCalendar) { patterns = new ArrayList<>(); final StrategyParser fm = new StrategyParser(definingCalendar); for(;;) { final StrategyAndWidth field = fm.getNextStrategy(); if(field==null) { break; } patterns.add(field); } }
Initialize derived fields from defining fields. This is called from constructor and from readObject (de-serialization) @param definingCalendar the {@link Calendar} instance used to initialize this FastDateParser
init
java
arextest/arex-agent-java
arex-third-party/src/main/java/io/arex/agent/thirdparty/util/time/FastDateParser.java
https://github.com/arextest/arex-agent-java/blob/master/arex-third-party/src/main/java/io/arex/agent/thirdparty/util/time/FastDateParser.java
Apache-2.0
private static Map<String, Integer> appendDisplayNames(final Calendar cal, final Locale locale, final int field, final StringBuilder regex) { final Map<String, Integer> values = new HashMap<>(); final Map<String, Integer> displayNames = cal.getDisplayNames(field, Calendar.ALL_STYLES, locale); final TreeSet<String> sorted = new TreeSet<>(LONGER_FIRST_LOWERCASE); for (final Map.Entry<String, Integer> displayName : displayNames.entrySet()) { final String key = displayName.getKey().toLowerCase(locale); if (sorted.add(key)) { values.put(key, displayName.getValue()); } } for (final String symbol : sorted) { simpleQuote(regex, symbol).append('|'); } return values; }
Get the short and long values displayed for a field @param cal The calendar to obtain the short and long values @param locale The locale of display names @param field The field of interest @param regex The regular expression to build @return The map of string display names to field values
appendDisplayNames
java
arextest/arex-agent-java
arex-third-party/src/main/java/io/arex/agent/thirdparty/util/time/FastDateParser.java
https://github.com/arextest/arex-agent-java/blob/master/arex-third-party/src/main/java/io/arex/agent/thirdparty/util/time/FastDateParser.java
Apache-2.0
private Strategy getStrategy(final char f, final int width, final Calendar definingCalendar) { switch(f) { default: throw new IllegalArgumentException("Format '"+f+"' not supported"); case 'D': return DAY_OF_YEAR_STRATEGY; case 'E': return getLocaleSpecificStrategy(Calendar.DAY_OF_WEEK, definingCalendar); case 'F': return DAY_OF_WEEK_IN_MONTH_STRATEGY; case 'G': return getLocaleSpecificStrategy(Calendar.ERA, definingCalendar); case 'H': // Hour in day (0-23) return HOUR_OF_DAY_STRATEGY; case 'K': // Hour in am/pm (0-11) return HOUR_STRATEGY; case 'M': return width>=3 ?getLocaleSpecificStrategy(Calendar.MONTH, definingCalendar) :NUMBER_MONTH_STRATEGY; case 'S': return MILLISECOND_STRATEGY; case 'W': return WEEK_OF_MONTH_STRATEGY; case 'a': return getLocaleSpecificStrategy(Calendar.AM_PM, definingCalendar); case 'd': return DAY_OF_MONTH_STRATEGY; case 'h': // Hour in am/pm (1-12), i.e. midday/midnight is 12, not 0 return HOUR12_STRATEGY; case 'k': // Hour in day (1-24), i.e. midnight is 24, not 0 return HOUR24_OF_DAY_STRATEGY; case 'm': return MINUTE_STRATEGY; case 's': return SECOND_STRATEGY; case 'u': return DAY_OF_WEEK_STRATEGY; case 'w': return WEEK_OF_YEAR_STRATEGY; case 'y': case 'Y': return width>2 ?LITERAL_YEAR_STRATEGY :ABBREVIATED_YEAR_STRATEGY; case 'X': return ISO8601TimeZoneStrategy.getStrategy(width); case 'Z': if (width==2) { return ISO8601TimeZoneStrategy.ISO_8601_3_STRATEGY; } //$FALL-THROUGH$ case 'z': return getLocaleSpecificStrategy(Calendar.ZONE_OFFSET, definingCalendar); } }
Obtain a Strategy given a field from a SimpleDateFormat pattern @param f A sub-sequence of the SimpleDateFormat pattern @param definingCalendar The calendar to obtain the short and long values @return The Strategy that will handle parsing for the field
getStrategy
java
arextest/arex-agent-java
arex-third-party/src/main/java/io/arex/agent/thirdparty/util/time/FastDateParser.java
https://github.com/arextest/arex-agent-java/blob/master/arex-third-party/src/main/java/io/arex/agent/thirdparty/util/time/FastDateParser.java
Apache-2.0