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 Project fetchProjectByName(final String key) throws ProjectManagerException { final Project result = this.projectLoader.fetchProjectByName(key); return result; }
Returns project object for given name using methods of the private projectLoader. @param key @throws ProjectManagerException
fetchProjectByName
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/AbstractProjectCache.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/AbstractProjectCache.java
Apache-2.0
protected Project fetchProjectById(final Integer id) throws ProjectManagerException { final Project result = this.projectLoader.fetchProjectById(id); return result; }
Returns project object for given id using methods of the private projectLoader. @param id @throws ProjectManagerException
fetchProjectById
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/AbstractProjectCache.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/AbstractProjectCache.java
Apache-2.0
public HashMap<String, Props> getJobPropsMap() { return this.jobPropsMap; }
Returns job properties. @return Map of job name to properties.
getJobPropsMap
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/DirectoryFlowLoader.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/DirectoryFlowLoader.java
Apache-2.0
public ArrayList<Props> getPropsList() { return this.propsList; }
Returns list of properties. @return List of Props.
getPropsList
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/DirectoryFlowLoader.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/DirectoryFlowLoader.java
Apache-2.0
public Map<String, List<Edge>> getEdgeMap() { return this.edgeMap; }
Returns the edge map constructed from the loaded flows. @return Map of flow name to all its Edges.
getEdgeMap
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/DirectoryYamlFlowLoader.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/DirectoryYamlFlowLoader.java
Apache-2.0
private static boolean overridePropsInNodeBean(final NodeBean nodeBean, final String[] pathList, final int idx, final Props prop) { if (idx < pathList.length && nodeBean.getName().equals(pathList[idx])) { if (idx == pathList.length - 1) { if (prop.containsKey(Constants.NODE_TYPE)) { nodeBean.setType(prop.get(Constants.NODE_TYPE)); } final Map<String, String> config = prop.getFlattened(); config.remove(Constants.NODE_TYPE); nodeBean.setConfig(config); return true; } for (final NodeBean bean : nodeBean.getNodes()) { if (overridePropsInNodeBean(bean, pathList, idx + 1, prop)) { return true; } } } return false; }
Helper method to recursively find the node to override props. @param nodeBean the node bean @param pathList the path list @param idx the idx @param prop the props to override @return the boolean
overridePropsInNodeBean
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/FlowLoaderUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/FlowLoaderUtils.java
Apache-2.0
public static void addEmailPropsToFlow(final Flow flow, final Props prop) { final List<String> successEmailList = prop.getStringList(CommonJobProperties.SUCCESS_EMAILS, Collections.EMPTY_LIST); final Set<String> successEmail = new HashSet<>(); for (final String email : successEmailList) { successEmail.add(email.toLowerCase()); } final List<String> failureEmailList = prop.getStringList(CommonJobProperties.FAILURE_EMAILS, Collections.EMPTY_LIST); final Set<String> failureEmail = new HashSet<>(); for (final String email : failureEmailList) { failureEmail.add(email.toLowerCase()); } final List<String> overrideEmailList = prop.getStringList(CommonJobProperties.OVERRIDE_EMAILS, Collections.EMPTY_LIST); final Set<String> overrideEmail = new HashSet<>(); for (final String email : overrideEmailList) { overrideEmail.add(email.toLowerCase()); } final List<String> notifyEmailList = prop.getStringList(CommonJobProperties.NOTIFY_EMAILS, Collections.EMPTY_LIST); for (String email : notifyEmailList) { email = email.toLowerCase(); successEmail.add(email); failureEmail.add(email); } flow.addFailureEmails(failureEmail); flow.addSuccessEmails(successEmail); flow.addOverrideEmails(overrideEmail); }
Adds email properties to a flow. @param flow the flow @param prop the prop
addEmailPropsToFlow
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/FlowLoaderUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/FlowLoaderUtils.java
Apache-2.0
public static ValidationReport generateFlowLoaderReport(final Set<String> errors) { final ValidationReport report = new ValidationReport(); report.addErrorMsgs(errors); return report; }
Generate flow loader report validation report. @param errors the errors @return the validation report
generateFlowLoaderReport
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/FlowLoaderUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/FlowLoaderUtils.java
Apache-2.0
public static void checkJobProperties(final int projectId, final Props props, final Map<String, Props> jobPropsMap, final Set<String> errors) { // if project is in the memory check whitelist, then we don't need to check // its memory settings if (ProjectWhitelist.isProjectWhitelisted(projectId, ProjectWhitelist.WhitelistType.MemoryCheck)) { return; } final MemConfValue maxXms = MemConfValue.parseMaxXms(props); final MemConfValue maxXmx = MemConfValue.parseMaxXmx(props); for (final String jobName : jobPropsMap.keySet()) { final Props jobProps = jobPropsMap.get(jobName); final String xms = jobProps.getString(XMS, null); if (xms != null && !PropsUtils.isVariableReplacementPattern(xms) && Utils.parseMemString(xms) > maxXms.getSize()) { errors.add(String.format( "%s: Xms value has exceeded the allowed limit (max Xms = %s)", jobName, maxXms.getString())); } final String xmx = jobProps.getString(XMX, null); if (xmx != null && !PropsUtils.isVariableReplacementPattern(xmx) && Utils.parseMemString(xmx) > maxXmx.getSize()) { errors.add(String.format( "%s: Xmx value has exceeded the allowed limit (max Xmx = %s)", jobName, maxXmx.getString())); } // job callback properties check JobCallbackValidator.validate(jobName, props, jobProps, errors); } }
Check job properties. @param projectId the project id @param props the server props @param jobPropsMap the job props map @param errors the errors
checkJobProperties
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/FlowLoaderUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/FlowLoaderUtils.java
Apache-2.0
public static void cleanUpDir(final File dir) { try { if (dir != null && dir.exists()) { FileUtils.deleteDirectory(dir); } } catch (final IOException e) { logger.error("Failed to delete the directory", e); dir.deleteOnExit(); } }
Clean up the directory. @param dir the directory to be deleted
cleanUpDir
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/FlowLoaderUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/FlowLoaderUtils.java
Apache-2.0
public static boolean isAzkabanFlowVersion20(final double azkabanFlowVersion) { return Double.compare(azkabanFlowVersion, Constants.AZKABAN_FLOW_VERSION_2_0) == 0; }
Check if azkaban flow version is 2.0. @param azkabanFlowVersion the azkaban flow version @return the boolean
isAzkabanFlowVersion20
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/FlowLoaderUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/FlowLoaderUtils.java
Apache-2.0
@Override public boolean accept(final File pathname) { final String name = pathname.getName(); return pathname.isFile() && !pathname.isHidden() && name.length() > this.suffix.length() && name.endsWith(this.suffix); }
Instantiates a new Suffix filter. @param suffix the suffix
accept
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/FlowLoaderUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/FlowLoaderUtils.java
Apache-2.0
private static File getFlowFile(final File tempDir, final ProjectLoader projectLoader, final ExecutableFlow flow) throws Exception { final List<ImmutableFlowProps> immutableFlowPropsList = ImmutableList.copyOf(flow.getFlowProps()); // There should be exact one source (file name) for each flow file. if (immutableFlowPropsList.isEmpty() || immutableFlowPropsList.get(0) == null) { throw new ProjectManagerException( "Failed to get flow file source. Flow props is empty for " + flow.getId()); } final String source = immutableFlowPropsList.get(0).getSource(); final int flowVersion = projectLoader .getLatestFlowVersion(flow.getProjectId(), flow.getVersion(), source); return projectLoader .getUploadedFlowFile(flow.getProjectId(), flow.getVersion(), source, flowVersion, tempDir); }
This function fetches the flow file and puts it in tempDir @param tempDir location where the flow file is put @param projectLoader Used to fetch from DB @param flow the executable flow @return returns the flow file from db. @throws Exception
getFlowFile
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/FlowLoaderUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/FlowLoaderUtils.java
Apache-2.0
private void init() { final List<Project> projects = super.getActiveProjects(); logger.info("Loading active projects."); for (final Project proj : projects) { putProject(proj); } logger.info("Loading flows from active projects."); loadAllFlows(projects); logger.info("Loading flow resource recommendations from active projects."); loadAllFlowResourceRecommendations(projects); logger.info("Active projects has been initialized."); }
load all active projects and their corresponding flows into memory. Queries from database only returns a high level project object. Need to explicitly load flows for the project objects.
init
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/InMemoryProjectCache.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/InMemoryProjectCache.java
Apache-2.0
@Override public void putProject(final Project project) { this.projectsByName.put(project.getName(), project); this.projectsById.put(project.getId(), project); }
Inserts given project into the cache. @param project Project
putProject
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/InMemoryProjectCache.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/InMemoryProjectCache.java
Apache-2.0
@Override public Optional<Project> getProjectByName(final String key) { Project project = this.projectsByName.get(key); if (project == null) { logger.info("No active project with name {} exists in cache, fetching from DB.", key); try { project = fetchProjectByName(key); } catch (final ProjectManagerException e) { logger.error("Could not load project from store.", e); } } return Optional.ofNullable(project); }
Queries an active project by name. Fetches from database if not present in cache. @param key name of the project @return Project
getProjectByName
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/InMemoryProjectCache.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/InMemoryProjectCache.java
Apache-2.0
@Override public Optional<Project> getProjectById(final Integer key) throws ProjectManagerException { Project project = this.projectsById.get(key); if (project == null) { logger.info("Project with ID " + key + " not found in cache, fetching from DB"); project = fetchProjectById(key); } return Optional.ofNullable(project); }
Fetch active/inactive project by project id. If active project not present in cache, fetches from DB. Fetches inactive project from DB. @param key Project id @return Project
getProjectById
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/InMemoryProjectCache.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/InMemoryProjectCache.java
Apache-2.0
@Override public void removeProject(final Project project) { this.projectsByName.remove(project.getName()); this.projectsById.remove(project.getId()); }
Invalidates the given project from cache.
removeProject
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/InMemoryProjectCache.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/InMemoryProjectCache.java
Apache-2.0
@Override public List<Project> getProjectsWithSimilarNames(final Pattern pattern) { final List<Project> matches = new ArrayList<>(); final ArrayList<String> names = new ArrayList<>(this.projectsByName.getKeys()); for (final String projName : names) { if (pattern.matcher(projName).find()) { matches.add(this.projectsByName.get(projName)); } } return matches; }
@param pattern @return List of Projects matching to given pattern.
getProjectsWithSimilarNames
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/InMemoryProjectCache.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/InMemoryProjectCache.java
Apache-2.0
@Override public List<Project> getActiveProjects() { return new ArrayList<>(this.projectsById.values()); }
Returns all the projects from the in-memory cache map.
getActiveProjects
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/InMemoryProjectCache.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/InMemoryProjectCache.java
Apache-2.0
@Override public synchronized Project createNewProject(String name, String description, User creator) throws ProjectManagerException { return createNewProject(name, description, creator, null); }
Creates a Project in the db. <p> It will throw an exception if it finds an active project of the same name, or the SQL fails
createNewProject
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/JdbcProjectImpl.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/JdbcProjectImpl.java
Apache-2.0
@Override public List<Project> fetchProjectById(final List<Integer> ids) throws ProjectManagerException { if (ids.size() == 0) { throw new ProjectManagerException("No input to query"); } final ProjectResultHandler handler = new ProjectResultHandler(); List<Project> projects = Collections.emptyList(); final String name = StringUtils.join(ids, ',').toString(); final String SELECT_PROJECT_BY_IDS = "SELECT " + "prj.id, prj.name, prj.active, prj.modified_time, prj.create_time, prj.version, prj.last_modified_by, prj.description, prj.enc_type, prj.settings_blob, prj.security_tag, " + "prm.name, prm.permissions, prm.isGroup, prjver.uploader " + "FROM projects prj " + "LEFT JOIN project_versions prjver ON prj.id = prjver.project_id " + "LEFT JOIN project_permissions prm ON prj.id = prm.project_id WHERE prj.id in (" + name + ")"; try { projects = this.dbOperator .query(SELECT_PROJECT_BY_IDS, handler); } catch (final SQLException ex) { logger.error(SELECT_PROJECT_BY_IDS + " failed.", ex); throw new ProjectManagerException( SELECT_PROJECT_BY_IDS + " failed.", ex); } return projects; }
Returns list of Projects with ids that match with any id specified in the list of ids passed as a parameter. @param ids List of ids of projects to be queried @throws ProjectManagerException
fetchProjectById
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/JdbcProjectImpl.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/JdbcProjectImpl.java
Apache-2.0
public List<Project> getProjectsByRegex(final String regexPattern) { final Pattern pattern; try { pattern = Pattern.compile(regexPattern, Pattern.CASE_INSENSITIVE); } catch (final PatternSyntaxException e) { logger.error("Bad regex pattern {}", regexPattern); return Collections.emptyList(); } return this.cache.getProjectsWithSimilarNames(pattern); }
This function matches the regex pattern with the names of all active projects, gets corresponding ids and fetches the corresponding projects from the cache( cases : all projects are present in cache / cache queries from DB and is updated).
getProjectsByRegex
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/ProjectManager.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/ProjectManager.java
Apache-2.0
public Boolean isActiveProject(final int id) { Project project = getProject(id); if (project == null) { return false; } project = getProject(project.getName()); return project != null ? true : false; }
Checks if a project is active using project_id. getProject(id) can also fetch he inactive projects from DB. Thus we need to make sure project retrieved is present in the mapping which consists of all the active projects. This map has key as project name in all the project cache implementations.
isActiveProject
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/ProjectManager.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/ProjectManager.java
Apache-2.0
public Project getProject(final String name) { final Project fetchedProject = this.cache.getProjectByName(name).orElse(null); return fetchedProject; }
Fetch active project by project name. Queries the cache first then DB.
getProject
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/ProjectManager.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/ProjectManager.java
Apache-2.0
public static ValidationStatus getInfoMsgLevel(final String msg) { if (msg.startsWith("ERROR")) { return ValidationStatus.ERROR; } if (msg.startsWith("WARN")) { return ValidationStatus.WARN; } return ValidationStatus.PASS; }
Return the severity level this information message is associated with.
getInfoMsgLevel
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/validator/ValidationReport.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/validator/ValidationReport.java
Apache-2.0
public void addWarnLevelInfoMsg(final String msg) { if (msg != null) { this._infoMsgs.add("WARN" + msg); } }
Add an information message associated with warning messages
addWarnLevelInfoMsg
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/validator/ValidationReport.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/validator/ValidationReport.java
Apache-2.0
public void addErrorLevelInfoMsg(final String msg) { if (msg != null) { this._infoMsgs.add("ERROR" + msg); } }
Add an information message associated with error messages
addErrorLevelInfoMsg
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/validator/ValidationReport.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/validator/ValidationReport.java
Apache-2.0
public void addWarningMsgs(final Set<String> msgs) { if (msgs != null) { this._warningMsgs.addAll(msgs); if (!msgs.isEmpty() && this._errorMsgs.isEmpty()) { this._status = ValidationStatus.WARN; } } }
Add a message with status level being {@link ValidationStatus#WARN}
addWarningMsgs
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/validator/ValidationReport.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/validator/ValidationReport.java
Apache-2.0
public void addErrorMsgs(final Set<String> msgs) { if (msgs != null) { this._errorMsgs.addAll(msgs); if (!msgs.isEmpty()) { this._status = ValidationStatus.ERROR; } } }
Add a message with status level being {@link ValidationStatus#ERROR}
addErrorMsgs
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/validator/ValidationReport.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/validator/ValidationReport.java
Apache-2.0
public ValidationStatus getStatus() { return this._status; }
Retrieve the status of the report.
getStatus
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/validator/ValidationReport.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/validator/ValidationReport.java
Apache-2.0
public Set<String> getInfoMsgs() { return this._infoMsgs; }
Retrieve the list of information messages.
getInfoMsgs
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/validator/ValidationReport.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/validator/ValidationReport.java
Apache-2.0
public Set<String> getWarningMsgs() { return this._warningMsgs; }
Retrieve the messages associated with status level {@link ValidationStatus#WARN}
getWarningMsgs
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/validator/ValidationReport.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/validator/ValidationReport.java
Apache-2.0
public Set<String> getErrorMsgs() { return this._errorMsgs; }
Retrieve the messages associated with status level {@link ValidationStatus#ERROR}
getErrorMsgs
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/validator/ValidationReport.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/validator/ValidationReport.java
Apache-2.0
@Override public String toString() { return this._status; }
Status of the ValidationReport. It also represents the severity of each rule. The order of severity for the status is PASS < WARN < ERROR.
toString
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/validator/ValidationStatus.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/validator/ValidationStatus.java
Apache-2.0
@Override public void close() throws ValidatorManagerException { this.setJarFileNames2Close.clear(); closeClassLoader(this); finalizeNativeLibs(this); cleanupJarFileFactory(); }
Workaround for jdk 6 disgrace with open jar files & native libs, which is a reason of unrefreshable classloader.
close
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/validator/ValidatorClassLoader.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/validator/ValidatorClassLoader.java
Apache-2.0
private void initClassLoader() { final File validatorDir = new File(this.validatorDirPath); final List<URL> resources = new ArrayList<>(); try { if (validatorDir.canRead() && validatorDir.isDirectory()) { for (final File f : validatorDir.listFiles()) { if (f.getName().endsWith(".jar")) { resources.add(f.toURI().toURL()); } } } } catch (final MalformedURLException e) { throw new ValidatorManagerException(e); } validatorLoader = new ValidatorClassLoader(resources.toArray(new URL[resources.size()])); }
Load the validator plugins from the validator directory (default being validators/) into the validator ClassLoader. This enables creating instances of these validators in the loadValidators() method.
initClassLoader
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/validator/XmlValidatorManager.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/validator/XmlValidatorManager.java
Apache-2.0
@Override public String getCacheKey(final Project project, final File projectDir, final Props props) { final Props nonNullProps = props == null ? new Props() : props; StringBuilder compoundedKey = new StringBuilder(); for (final Entry<String, ProjectValidator> validator : this.validators.entrySet()) { try { // Attempt to cast to ProjectValidatorCacheable ProjectValidatorCacheable cacheableValidator = (ProjectValidatorCacheable) validator.getValue(); compoundedKey.append(cacheableValidator.getCacheKey(project, projectDir, nonNullProps)); } catch (ClassCastException e) { // Swallow this error - the validator must not have been a cacheable validator } } return HashUtils.SHA1.getHashStr(compoundedKey.toString()); }
Gets a SHA1 hash of the combined cache keys for all loaded validators. @see azkaban.project.validator.ProjectValidatorCacheable#getCacheKey(azkaban.project.Project, java.io.File, azkaban.utils.Props)
getCacheKey
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/validator/XmlValidatorManager.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/project/validator/XmlValidatorManager.java
Apache-2.0
@Override protected boolean isRampTestEnabled(ExecutableFlow flow, ExecutableRamp executableRamp) { return true; }
Full Ramp Policy is a Dummy Ramp Policy which does apply any ramp upon the job flow.
isRampTestEnabled
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/ramppolicy/FullRampPolicy.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/ramppolicy/FullRampPolicy.java
Apache-2.0
public Props getCommonPluginProps() { return this.commonProps; }
Gets common properties for every ramp policy
getCommonPluginProps
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/ramppolicy/RampPolicyPluginSet.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/ramppolicy/RampPolicyPluginSet.java
Apache-2.0
public void setCommonPluginProps(final Props commonProps) { this.commonProps = commonProps; }
Sets the common properties shared in every ramp policy
setCommonPluginProps
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/ramppolicy/RampPolicyPluginSet.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/ramppolicy/RampPolicyPluginSet.java
Apache-2.0
public Props getPluginLoadProps(final String rampPolicyName) { return this.pluginLoadPropsMap.get(rampPolicyName); }
Get the properties for a ramp policy used to setup and load a plugin
getPluginLoadProps
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/ramppolicy/RampPolicyPluginSet.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/ramppolicy/RampPolicyPluginSet.java
Apache-2.0
public Props getPluginCommonProps(final String rampPolicyName) { return this.pluginCommonPropsMap.get(rampPolicyName); }
Get the properties that will be given to the plugin as common properties.
getPluginCommonProps
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/ramppolicy/RampPolicyPluginSet.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/ramppolicy/RampPolicyPluginSet.java
Apache-2.0
public Class<? extends RampPolicy> getPluginClass(final String rampPolicyName) { return this.rampPolicyToClass.get(rampPolicyName); }
Gets the plugin ramp policy class
getPluginClass
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/ramppolicy/RampPolicyPluginSet.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/ramppolicy/RampPolicyPluginSet.java
Apache-2.0
public void addPluginProps(final String rampPolicyName, final Props props) { if (props != null) { this.pluginCommonPropsMap.put(rampPolicyName, props); } }
Adds plugin common properties used as default runtime properties. if props is null, nothing will be added. @param rampPolicyName ramp policy name @param props nullable props
addPluginProps
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/ramppolicy/RampPolicyPluginSet.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/ramppolicy/RampPolicyPluginSet.java
Apache-2.0
public void addPluginLoadProps(final String rampPolicyName, final Props props) { if (props != null) { this.pluginLoadPropsMap.put(rampPolicyName, props); } }
Adds plugin load properties used to load the plugin. if props is null, nothing will be added. @param rampPolicyName ramp policy name @param props nullable props
addPluginLoadProps
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/ramppolicy/RampPolicyPluginSet.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/ramppolicy/RampPolicyPluginSet.java
Apache-2.0
@Override public void shutdown() { }
Shutdowns the scheduler thread. After shutdown, it may not be safe to use it again.
shutdown
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/scheduler/ScheduleManager.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/scheduler/ScheduleManager.java
Apache-2.0
public List<Schedule> getSchedules() throws ScheduleManagerException { final List<Schedule> updates = this.loader.loadUpdatedSchedules(); refreshLocal(updates); return new ArrayList<>(this.scheduleIDMap.values()); }
Retrieves a copy of the list of updated schedules.
getSchedules
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/scheduler/ScheduleManager.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/scheduler/ScheduleManager.java
Apache-2.0
public List<Schedule> getAllSchedules() { try { return this.loader.loadAllSchedules(); } catch (ScheduleManagerException e) { logger.error("Failed to load all schedules", e); return new ArrayList<>(); } }
Retrieves a copy of the list of all schedules regardless the status, active or inactive ones.
getAllSchedules
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/scheduler/ScheduleManager.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/scheduler/ScheduleManager.java
Apache-2.0
public Schedule getSchedule(final int projectId, final String flowId) throws ScheduleManagerException { // for one specific schedule refresh, we only need to update that schedule Schedule s = this.scheduleIdentityPairMap.get(new Pair<>(projectId, flowId)); return s == null ? null : updateSingleSchedule(s); }
Returns the scheduled flow for the flow name
getSchedule
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/scheduler/ScheduleManager.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/scheduler/ScheduleManager.java
Apache-2.0
public Schedule getSchedule(final int scheduleId) throws ScheduleManagerException { Schedule s = this.scheduleIDMap.get(scheduleId); return s == null ? null : updateSingleSchedule(s); }
Returns the scheduled flow for the scheduleId @param scheduleId Schedule ID
getSchedule
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/scheduler/ScheduleManager.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/scheduler/ScheduleManager.java
Apache-2.0
private void internalSchedule(@NotNull final Schedule s) { this.scheduleIDMap.put(s.getScheduleId(), s); this.scheduleIdentityPairMap.put(s.getScheduleIdentityPair(), s); }
Schedules the flow, but doesn't save the schedule afterwards.
internalSchedule
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/scheduler/ScheduleManager.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/scheduler/ScheduleManager.java
Apache-2.0
private Schedule updateSingleSchedule(@NotNull Schedule s) throws ScheduleManagerException { s.lock(); try { Optional<Schedule> updatedSchedule = loader.loadUpdateSchedule(s); if (updatedSchedule.isPresent()) { Schedule schedule = updatedSchedule.get(); if (schedule.getStatus().equals(TriggerStatus.EXPIRED.toString())) { onScheduleExpire(schedule); } else { internalSchedule(schedule); } return schedule; } return s; } finally { s.unlock(); } }
fetch from TriggerManager to see if the desired trigger is being updated or not. if updated, update schedule metadata; if not being updated, return the original schedule. @param s, original schedule @return latest schedule metadata
updateSingleSchedule
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/scheduler/ScheduleManager.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/scheduler/ScheduleManager.java
Apache-2.0
public static void validatePreprocessFlowParameters(ExecutionOptions options, Props azProps) throws ServletException { List<String> errMsg = new ArrayList<>(); Map<String, String> flowParameters = options.getFlowParameters(); if (flowParameters == null || flowParameters.isEmpty()) { return; } // if ALLOW_RESTART_ON_EXECUTION_STOPPED then ALLOW_RESTART_ON_STATUS += "EXECUTION_STOPPED," if (Boolean.parseBoolean( flowParameters.getOrDefault( FlowParameters.FLOW_PARAM_ALLOW_RESTART_ON_EXECUTION_STOPPED, "false")) ){ flowParameters.put( FlowParameters.FLOW_PARAM_ALLOWED_RETRY_STATUS, Status.EXECUTION_STOPPED.name() + "," + flowParameters.getOrDefault(FlowParameters.FLOW_PARAM_ALLOWED_RETRY_STATUS, "") ); flowParameters.remove(FlowParameters.FLOW_PARAM_ALLOW_RESTART_ON_EXECUTION_STOPPED); } if (flowParameters.containsKey(FlowParameters.FLOW_PARAM_ALLOWED_RETRY_STATUS)) { // user defined restart-statuses; remove the empty spaces final Set<String> statuses = Arrays.stream( flowParameters.getOrDefault(FlowParameters.FLOW_PARAM_ALLOWED_RETRY_STATUS, "") .split("\\s*,\\s*") ).map(String::trim).filter(s -> !s.isEmpty()).collect(Collectors.toSet()); for (String str : statuses) { try{ Status status = Status.valueOf(str); if (!RESTARTABLE_TERMINAL_STATUSES.contains(status)) { errMsg.add(String.format("`%s` is not a valid restartable status, " + "permitted status are %s\n", str, RESTARTABLE_TERMINAL_STATUSES)); } } catch (Exception e) { errMsg.add(String.format("`%s` is not a valid Status defined in Azkaban, please " + "correct\n", str)); } } flowParameters.put(FlowParameters.FLOW_PARAM_ALLOWED_RETRY_STATUS, Strings.join(statuses, ",")); } if (flowParameters.containsKey(FlowParameters.FLOW_PARAM_MAX_RETRIES)){ // check restart count limit try { validateIntegerParam(flowParameters, FlowParameters.FLOW_PARAM_MAX_RETRIES); final int flowRestartCountLimit = azProps.getInt( AZKABAN_EXECUTION_RESTART_LIMIT, DEFAULT_FLOW_RETRY_LIMIT); final int flowMaxRetryLimit = Integer.parseInt( flowParameters.getOrDefault(FlowParameters.FLOW_PARAM_MAX_RETRIES, "0")); if (flowMaxRetryLimit > flowRestartCountLimit || flowMaxRetryLimit < 0){ errMsg.add(String.format( "Invalid `" + FlowParameters.FLOW_PARAM_MAX_RETRIES + " = %d`, value should be " + "within [0, %d]\n", flowMaxRetryLimit, flowRestartCountLimit)); } } catch (ExecutorManagerException e) { errMsg.add(e.getMessage()); } } if (flowParameters.containsKey(FlowParameters.FLOW_PARAM_RETRY_STRATEGY)){ String restartStrategy = flowParameters.get(FlowParameters.FLOW_PARAM_RETRY_STRATEGY); try { FlowRetryStrategy restartStrategyEnum = FlowRetryStrategy.valueFromName(restartStrategy); } catch (IllegalArgumentException e){ errMsg.add(String.format("Invalid %s = %s. Valid values are: %s", FlowParameters.FLOW_PARAM_RETRY_STRATEGY, restartStrategy, FlowRetryStrategy.getNames())); } } // throw exception if there's any error message if (!errMsg.isEmpty()) { throw new ServletException(String.format("ExecutionOptions is invalid, error reasons: %s", errMsg)); } }
Validate the ExecutionOption's Flow-Parameters against the application level Properties @throws ServletException if any of the parameter is invalid
validatePreprocessFlowParameters
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/server/HttpRequestUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/server/HttpRequestUtils.java
Apache-2.0
public static boolean validateIntegerParam(final Map<String, String> params, final String paramName) throws ExecutorManagerException { if (params != null && params.containsKey(paramName) && !StringUtils.isNumeric(params.get(paramName))) { throw new ExecutorManagerException(paramName + " should be an integer"); } return true; }
parse a string as number and throws exception if parsed value is not a valid integer @throws ExecutorManagerException if paramName is not a valid integer
validateIntegerParam
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/server/HttpRequestUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/server/HttpRequestUtils.java
Apache-2.0
public static boolean validateBooleanParam(final Map<String, String> params, final String paramName) throws ExecutorManagerException { if (params != null && params.containsKey(paramName) && null == BooleanUtils.toBooleanObject(params.get(paramName))) { throw new ExecutorManagerException(paramName + " should be boolean"); } return true; }
Parse a string as boolean and throws exception if parsed value is not a valid boolean. @param params @param paramName @return @throws ExecutorManagerException
validateBooleanParam
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/server/HttpRequestUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/server/HttpRequestUtils.java
Apache-2.0
public static boolean hasPermission(final UserManager userManager, final User user, final Permission.Type type) { for (final String roleName : user.getRoles()) { final Role role = userManager.getRole(roleName); if (role.getPermission().isPermissionSet(type) || role.getPermission().isPermissionSet(Permission.Type.ADMIN)) { return true; } } return false; }
returns true if user has access of type
hasPermission
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/server/HttpRequestUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/server/HttpRequestUtils.java
Apache-2.0
public static Map<String, String> getParamGroup(final HttpServletRequest request, final String groupName) throws ServletException { final Enumeration<String> enumerate = request.getParameterNames(); final String matchString = groupName + "["; final HashMap<String, String> groupParam = new HashMap<>(); while (enumerate.hasMoreElements()) { final String str = enumerate.nextElement(); if (str.startsWith(matchString)) { try { groupParam.put(str.substring(matchString.length(), str.length() - 1), request.getParameter(str)); } catch (IndexOutOfBoundsException e) { throw new ServletException(String.format("Param group %s is invalid.", groupName), e); } } } return groupParam; }
Read params like groupName[key]: value
getParamGroup
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/server/HttpRequestUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/server/HttpRequestUtils.java
Apache-2.0
public static SslSocketConnector getSslSocketConnector(final int sslPortNumber, final Props props) { final SslSocketConnector secureConnector = new SslSocketConnector(); secureConnector.setPort(sslPortNumber); secureConnector.setKeystore(props.getString(JETTY_KEYSTORE)); secureConnector.setPassword(props.getString(JETTY_PASSWORD)); secureConnector.setKeyPassword(props.getString(JETTY_KEYPASSWORD)); secureConnector.setTruststore(props.getString(JETTY_TRUSTSTORE)); secureConnector.setTrustPassword(props.getString(JETTY_TRUSTPASSWORD)); secureConnector.setHeaderBufferSize(DEFAULT_HEADER_BUFFER_SIZE); // set up vulnerable cipher suites to exclude final List<String> cipherSuitesToExclude = props .getStringList("jetty.excludeCipherSuites"); logger.info("Excluded Cipher Suites: " + String.valueOf(cipherSuitesToExclude)); if (cipherSuitesToExclude != null && !cipherSuitesToExclude.isEmpty()) { secureConnector.setExcludeCipherSuites(cipherSuitesToExclude.toArray(new String[0])); } return secureConnector; }
@param sslPortNumber Port number to bind for the socket @param props Azkaban properties containing configurations for Jetty Server @return SSL enabled SocketConnector {@link SslSocketConnector}, for https connection to the jetty server
getSslSocketConnector
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/server/JettyServerUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/server/JettyServerUtils.java
Apache-2.0
public static SocketConnector getSocketConnector(final int port) { final SocketConnector connector = new SocketConnector(); connector.setPort(port); connector.setHeaderBufferSize(DEFAULT_HEADER_BUFFER_SIZE); return connector; }
@param port Port number to bind for the socket @return A plain {@link SocketConnector} for http connection to the jetty server
getSocketConnector
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/server/JettyServerUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/server/JettyServerUtils.java
Apache-2.0
public void registerMBean(final String name, final Object mbean) { final Class<?> mbeanClass = mbean.getClass(); final ObjectName mbeanName; try { mbeanName = new ObjectName(mbeanClass.getName() + ":name=" + name); getMbeanServer().registerMBean(mbean, mbeanName); logger.info("Bean " + mbeanClass.getCanonicalName() + " registered."); this.registeredMBeans.add(mbeanName); } catch (final Exception e) { logger.error("Error registering mbean " + mbeanClass.getCanonicalName(), e); } }
A class to manager MBean Registration tasks
registerMBean
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/server/MBeanRegistrationManager.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/server/MBeanRegistrationManager.java
Apache-2.0
public MBeanServer getMbeanServer() { return (mbeanServer == null) ? ManagementFactory.getPlatformMBeanServer() : mbeanServer; }
Get Platform MBeanServer Instance @return platform MBeanServer Instance
getMbeanServer
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/server/MBeanRegistrationManager.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/server/MBeanRegistrationManager.java
Apache-2.0
public List<ObjectName> getMBeanNames() { return registeredMBeans; }
Get MBean Names @return list of MBean Names
getMBeanNames
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/server/MBeanRegistrationManager.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/server/MBeanRegistrationManager.java
Apache-2.0
public MBeanInfo getMBeanInfo(final ObjectName name) { try { return getMbeanServer().getMBeanInfo(name); } catch (final Exception e) { logger.error("Load MBean Information Failure", e); return null; } }
Get MBeanInfo @param name mbean Name @return MBeanInfo
getMBeanInfo
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/server/MBeanRegistrationManager.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/server/MBeanRegistrationManager.java
Apache-2.0
public Object getMBeanAttribute(final ObjectName name, final String attribute) { try { return getMbeanServer().getAttribute(name, attribute); } catch (final Exception e) { logger.error( "Retrieve MBeanServer attribute Failure. " + "ObjectName = " + name.toString() + ", " + "attribute = " + attribute, e); return null; } }
Get MBean Attribute @param name mbean name @param attribute attribute name @return object of MBean Attribute
getMBeanAttribute
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/server/MBeanRegistrationManager.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/server/MBeanRegistrationManager.java
Apache-2.0
public Map<String, Object> getMBeanResult(final String mbeanName) { final Map<String, Object> ret = new HashMap<>(); try { final ObjectName name = new ObjectName(mbeanName); final MBeanInfo info = getMBeanInfo(name); final MBeanAttributeInfo[] mbeanAttrs = info.getAttributes(); final Map<String, Object> attributes = new TreeMap<>(); for (final MBeanAttributeInfo attrInfo : mbeanAttrs) { final Object obj = getMBeanAttribute(name, attrInfo.getName()); attributes.put(attrInfo.getName(), obj); } ret.put("attributes", attributes); } catch (final Exception e) { logger.error("Invalid MBean Name. name = " + mbeanName, e); ret.put("error", "'" + mbeanName + "' is not a valid mBean name"); } return ret; }
Get MBean Result @param mbeanName mbeanName @return Map of MBean
getMBeanResult
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/server/MBeanRegistrationManager.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/server/MBeanRegistrationManager.java
Apache-2.0
public Session getSession(final String sessionId) { final Session elem = this.cache.getIfPresent(sessionId); return elem; }
Returns the cached session using the session id.
getSession
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/server/session/SessionCache.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/server/session/SessionCache.java
Apache-2.0
public long getSessionCount() { return this.cache.size(); }
Returns the approximate number of sessions currently be kept.
getSessionCount
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/server/session/SessionCache.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/server/session/SessionCache.java
Apache-2.0
private int getSessionCountByUserByIP(final User user, final String ip) { // first search for duplicate sessions with the given IP final Set<Session> sessionsWithSameIP = this.findSessionsByIP(ip); // then search for duplicate sessions with the given user int duplicateSessionCount = 0; for (final Session sessionByIP : sessionsWithSameIP) { if (sessionByIP.getUser().equals(user)) { duplicateSessionCount++; } } return duplicateSessionCount; }
Return the number of sessions sharing the given user and ip.
getSessionCountByUserByIP
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/server/session/SessionCache.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/server/session/SessionCache.java
Apache-2.0
public boolean addSession(final Session session) { if (isViolatingMaxNumberOfSessionPerIpPerUser(session)) { return false; } this.cache.put(session.getSessionId(), session); return true; }
Adds a session to the cache. @return <code>true</code> Session is successfully added while not violating the duplicate IP and user check; <code>false</code> otherwise.
addSession
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/server/session/SessionCache.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/server/session/SessionCache.java
Apache-2.0
public Set<Session> findSessionsByIP(final String ip) { final Set<Session> ret = new HashSet<>(); final Map<String, Session> cacheSnapshot = this.cache.asMap(); for (final Entry<String, Session> entry : cacheSnapshot.entrySet()) { if (entry.getValue().getIp().equals(ip)) { ret.add(entry.getValue()); } } return ret; }
Returns sessions whose IP equals to the given IP.
findSessionsByIP
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/server/session/SessionCache.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/server/session/SessionCache.java
Apache-2.0
public boolean isComponentType(final SlaType.ComponentType componentType) { return this.type.getComponent() == componentType; }
Check the SlaType's ComponentType of this SlaOption's @param componentType component Type @return true/false
isComponentType
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/sla/SlaOption.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/sla/SlaOption.java
Apache-2.0
public static SlaOption fromObject(Object json) { return new SlaOption(SlaOptionDeprecated.fromObject(json)); }
Convert the original JSON format, used by {@link SlaOptionDeprecated}, to an SLA option. @param json the original JSON format for {@link SlaOptionDeprecated}. @return the SLA option.
fromObject
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/sla/SlaOption.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/sla/SlaOption.java
Apache-2.0
public Object toWebObject() { final HashMap<String, Object> slaObj = new HashMap<>(); if (this.type.getComponent() == SlaType.ComponentType.FLOW) { slaObj.put(WEB_ID, ""); } else { slaObj.put(WEB_ID, this.jobName); } slaObj.put(WEB_DURATION, durationToString(this.duration)); slaObj.put(WEB_STATUS, this.type.getStatus().toString()); final List<String> actionsObj = new ArrayList<>(); if (hasAlert()) { actionsObj.add(WEB_ACTION_EMAIL); } if (hasKill()) { actionsObj.add(WEB_ACTION_KILL); } slaObj.put(WEB_ACTIONS, actionsObj); return slaObj; }
@return the web object representation for the SLA option.
toWebObject
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/sla/SlaOption.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/sla/SlaOption.java
Apache-2.0
public static List<SlaOption> getJobLevelSLAOptions(final List<SlaOption> options, final String jobId) { return filterSLAOptions(options, ComponentType.JOB, jobId); }
@param options a list of SLA options. @return the job level SLA options.
getJobLevelSLAOptions
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/sla/SlaOption.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/sla/SlaOption.java
Apache-2.0
@Override public void authorize() { if (this.isSecurityEnabled) { try { login(this.keytabPrincipal, this.keytabPath); } catch (final IOException e) { log.error(e); throw new AzkabanException(String.format( "Error: Unable to authorize to Hadoop. Principal: %s Keytab: %s", this.keytabPrincipal, this.keytabPath)); } } }
API to authorize HDFS access. This logins in the configured user via the keytab. If the user is already logged in then it renews the TGT.
authorize
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/storage/HdfsAuth.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/storage/HdfsAuth.java
Apache-2.0
private void login(final String keytabPrincipal, final String keytabPath) throws IOException { if (this.loggedInUser == null) { log.info( String.format("Logging in using Principal: %s Keytab: %s", keytabPrincipal, keytabPath)); UserGroupInformation.loginUserFromKeytab(keytabPrincipal, keytabPath); this.loggedInUser = UserGroupInformation.getLoginUser(); log.info(String.format("User %s logged in.", this.loggedInUser)); } else { log.info(String.format("User %s already logged in. Refreshing TGT", this.loggedInUser)); this.loggedInUser.checkTGTAndReloginFromKeytab(); } }
This method is used to login using keytab and set loggedInUser. @param keytabPrincipal @param keytabPath @throws IOException
login
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/storage/HdfsAuth.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/storage/HdfsAuth.java
Apache-2.0
@VisibleForTesting boolean isCleanupPermitted() { return this.maxArtifactsPerProject > 0; }
The query must sort the versions in reverse order for the cleanup operation to work correctly! TODO spyne: Refactor database storage cleanup to use this When using DatabaseStorage, resourceId is always NULL. Hence, those rows will currently be never cleaned up.
isCleanupPermitted
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/storage/StorageCleaner.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/storage/StorageCleaner.java
Apache-2.0
public static boolean hasPermissionforAction(final UserManager userManager, final User user, final Permission.Type type) { for (final String roleName : user.getRoles()) { final Role role = userManager.getRole(roleName); final Permission perm = role.getPermission(); if (perm.isPermissionSet(Permission.Type.ADMIN) || perm.isPermissionSet(type)) { return true; } } return false; }
@return - Returns true if the given user is an ADMIN, or if user has the required permission for the action requested.
hasPermissionforAction
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/user/UserUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/user/UserUtils.java
Apache-2.0
public static void setupWatch(final Map<String, ParseConfigFile> configFileMap, final FileWatcher watcher) { Preconditions.checkNotNull(configFileMap); Preconditions.checkArgument(configFileMap.size() > 0); // Map to store WatchKey to Dir mapping final Map<WatchKey, Path> keys = new HashMap<>(); // A directory to config files multimap final Multimap<Path, String> dirToFilesMap = HashMultimap.create(); // Iterate over each file. for (final Map.Entry<String, ParseConfigFile> entry : configFileMap.entrySet()) { final String fileName = entry.getKey(); final ParseConfigFile parser = entry.getValue(); Preconditions.checkNotNull(fileName); Preconditions.checkNotNull(parser); final File file = new File(fileName); if (!file.exists()) { log.warn("Failed to setup watch service, user provided file " + fileName + " does not " + "exist."); continue; } try { final Path dir = Paths.get(fileName).getParent(); if (!dirToFilesMap.containsKey(dir)) { // There is no entry for this directory, create a watchkey final WatchKey watchKey = watcher.register(dir); keys.put(watchKey, dir); } // Add the config file to dir map dirToFilesMap.put(dir, fileName); } catch (final IOException e) { // Ignore the IOException log.warn("IOException while setting up watch on conf " + fileName + ". ", e); } } // Return if WatchService is not initialized if (keys.size() == 0) { log.warn("Watchservice was not setup for any config file(s)."); try { watcher.close(); } catch (final IOException e) { log.warn("IOException while closing watchService. ", e); } return; } final Runnable runnable = () -> { // Watchservice is established, now listen for the events till eternity! for (; ; ) { final WatchKey watchKey; try { watchKey = watcher.take(); } catch (final InterruptedException ie) { log.warn(ie.toString()); Thread.currentThread().interrupt(); return; } // Get the directory for which watch service event triggered. final Path dir = keys.get(watchKey); for (final WatchEvent<?> event : watcher.pollEvents(watchKey)) { // Make sure the modification happened to user config file @SuppressWarnings("unchecked") final Path name = ((WatchEvent<Path>) event).context(); final String filename = dir.resolve(name).toString(); // Lookup the file in dirToFilesMap if (!dirToFilesMap.containsEntry(dir, filename)) { continue; } // Match! // Reparse the config file log.info("Modification detected, reloading config file " + filename + "."); try { configFileMap.get(filename).parseConfigFile(); } catch (final Exception e) { // If there is any exception while parsing the config file, log it and move on log.warn("Reload failed for config file " + filename + " due to ", e); } } } }; final Thread thread = new Thread(runnable); // allow JVM to terminate without waiting for this thread if the app is shutting down thread.setDaemon(true); log.info("Starting configuration watching thread."); thread.start(); }
Creates a watch thread which listens to specified files' modification and reloads configurations
setupWatch
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/user/UserUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/user/UserUtils.java
Apache-2.0
public static HttpURLConnection loginAuthenticatedURL(final URL url, final String keytabPrincipal, final String keytabPath) throws Exception { logger.info( "Logging in URL: " + url.toString() + " using Principal: " + keytabPrincipal + ", Keytab: " + keytabPath); UserGroupInformation loginUser = UserGroupInformation.getLoginUser(); if (loginUser == null) { UserGroupInformation.loginUserFromKeytab(keytabPrincipal, keytabPath); loginUser = UserGroupInformation.getLoginUser(); logger.info("Logged in with user " + loginUser); } else { logger.info("Login user (" + loginUser + ") already created, refreshing tgt."); loginUser.checkTGTAndReloginFromKeytab(); } final HttpURLConnection connection = loginUser.doAs( (PrivilegedExceptionAction<HttpURLConnection>) () -> { final Token token = new Token(); return new AuthenticatedURL().openConnection(url, token); }); return connection; }
The util class for hadoop authentication.
loginAuthenticatedURL
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/utils/AuthenticationUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/utils/AuthenticationUtils.java
Apache-2.0
private void ensureIsEnabled() { if (!isEnabled()) { throw new UnsupportedOperationException("Thin archive support is not enabled!"); } }
Return if the DependencyTransferManager will be able to download dependencies from the current Storage instance. @return if this class is enabled and can download dependencies.
ensureIsEnabled
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/utils/DependencyTransferManager.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/utils/DependencyTransferManager.java
Apache-2.0
@VisibleForTesting void waitForAllToSucceedOrOneToFail(final CompletableFuture<?>[] futures) throws InterruptedException, ExecutionException, TimeoutException { CompletableFuture<?> failure = new CompletableFuture(); for (CompletableFuture<?> f : futures) { // f = f is redundant, but bug checker throws error if we don't do it because it doesn't like us ignoring a // returned future...but we're still going to ignore it. f = f.exceptionally(ex -> { logger.error("Download failed with an exception: " + ex); failure.completeExceptionally(ex); return null; }); } // Wait for either the failure future to complete, or all of the actual futures to complete. CompletableFuture.anyOf(failure, CompletableFuture.allOf(futures)).get(dependencyDownloadMaxTimeout, TimeUnit.SECONDS); }
Add timeout to the download process. @throws TimeoutException, if the download process takes longer than the timeout.
waitForAllToSucceedOrOneToFail
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/utils/DependencyTransferManager.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/utils/DependencyTransferManager.java
Apache-2.0
public static ClassLoader getClassLoader(List<URL> resources, ClassLoader parent) { return new URLClassLoader(resources.toArray(new URL[resources.size()]), parent); }
Get ClassLoader From Resources @param resources list of resource @param parent parent class loader @return class loader
getClassLoader
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/utils/DIUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/utils/DIUtils.java
Apache-2.0
public static List<URL> loadResources( final File pluginDir, final List<String> globalClassPaths, final List<String> classPaths, final List<String> libDirectories ) throws MalformedURLException { final List<URL> resources = new ArrayList<>(); LOGGER.info("Adding global resources"); loadResources(globalClassPaths, resources); LOGGER.info("Adding type resources"); loadResources(classPaths, resources); LOGGER.info("Adding lib resources"); if (libDirectories != null) { for (final String libDir : libDirectories) { loadResources(new File(libDir), resources); } } LOGGER.info("Adding type override resources"); loadResources(pluginDir, resources); return resources; }
Load Setting to Resources @param pluginDir plugin Directory @param globalClassPaths list of global class path @param classPaths list of local class path @param libDirectories list of lib directories @return
loadResources
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/utils/DIUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/utils/DIUtils.java
Apache-2.0
private static void loadResources(final List<String> classPaths, List<URL> resources) throws MalformedURLException { if (classPaths != null) { for (final String jar : classPaths) { final URL cpItem = new File(jar).toURI().toURL(); if (!resources.contains(cpItem)) { LOGGER.info("adding to classpath " + cpItem); resources.add(cpItem); } } } }
Load Setting from a list of class paths to Resources @param classPaths list of class paths @param resources list of resource @throws MalformedURLException
loadResources
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/utils/DIUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/utils/DIUtils.java
Apache-2.0
private static void loadResources(final File directory, List<URL> resources) throws MalformedURLException { for (final File file : directory.listFiles()) { if (file.getName().endsWith(".jar")) { resources.add(file.toURI().toURL()); LOGGER.info("adding to classpath " + file.toURI().toURL()); } } }
Load Setting from file directory to Resources @param directory file directory for .jar files @param resources list of resource @throws MalformedURLException
loadResources
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/utils/DIUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/utils/DIUtils.java
Apache-2.0
@Override public void alertOnFailedUpdate(final Executor executor, List<ExecutableFlow> flows, final ExecutorManagerException updateException) { flows = flows.stream() .filter(flow -> flow.getExecutionOptions() != null) .filter(flow -> CollectionUtils.isNotEmpty(flow.getExecutionOptions().getFailureEmails())) .collect(Collectors.toList()); // group by mail creator in case some flows use different creators final ImmutableListMultimap<String, ExecutableFlow> creatorsToFlows = Multimaps .index(flows, flow -> flow.getExecutionOptions().getMailCreator()); for (final String mailCreatorName : creatorsToFlows.keySet()) { final ImmutableList<ExecutableFlow> creatorFlows = creatorsToFlows.get(mailCreatorName); final MailCreator mailCreator = getMailCreator(mailCreatorName); // group by recipients in case some flows have different failure email addresses final ImmutableListMultimap<List<String>, ExecutableFlow> emailsToFlows = Multimaps .index(creatorFlows, flow -> flow.getExecutionOptions().getFailureEmails()); for (final List<String> emailList : emailsToFlows.keySet()) { sendFailedUpdateEmail(executor, updateException, mailCreator, emailsToFlows.get(emailList)); } } }
Sends as many emails as there are unique combinations of: <p> [mail creator] x [failure email address list] <p> Executions with the same combo are grouped into a single message.
alertOnFailedUpdate
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/utils/Emailer.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/utils/Emailer.java
Apache-2.0
@Override public void alertOnFailedExecutorHealthCheck(final Executor executor, final List<ExecutableFlow> flows, final ExecutorManagerException failureException, final List<String> emailList) { if (emailList == null || emailList.isEmpty()) { // We should consider throwing an exception here. For now this follows the model of the rest // of the file and simply returns. logger.error("No email list specified for failed health check alert"); return; } final MailCreator mailCreator = DefaultMailCreator.getCreator(DefaultMailCreator.DEFAULT_MAIL_CREATOR); final EmailMessage message = this.messageCreator.createMessage(); final boolean mailCreated = mailCreator .createFailedExecutorHealthCheckMessage(flows, executor, failureException, message, this.azkabanName, this.scheme, this.clientHostname, this.clientPortNumber, emailList); final List<Integer> executionIds = Lists.transform(flows, ExecutableFlow::getExecutionId); sendEmail(message, mailCreated, "failed health check message for executions " + executionIds); }
Use the default mail creator to send a failed executor healthcheck message to the given list of addresses. Message includes a list of flows impacted on the executor.
alertOnFailedExecutorHealthCheck
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/utils/Emailer.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/utils/Emailer.java
Apache-2.0
@Override public void alertOnJobPropertyOverridden(final Project project, final Flow flow, final Map<String, Object> eventData) { final List<String> emailList = flow.getOverrideEmails(); final String emailSubject = "[Project Property Overridden Alert]"; final String modifier = String.valueOf(eventData.get(MODIFIED_BY)); final String jobName = String.valueOf(eventData.get("jobOverridden")); final String diffMessage = String.valueOf(eventData.get("diffMessage")); final String emailBody = "User " + modifier + " has overridden following job properties in project " + project.getName() + " flow " + flow.getId() + " job " + jobName + ": " + "\n" + diffMessage; sendEmail(emailList, emailSubject, emailBody); }
Alert user when a job property is overridden in a project @param project @param flow @param eventData
alertOnJobPropertyOverridden
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/utils/Emailer.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/utils/Emailer.java
Apache-2.0
private void validate() { if (!this.binaryExecutable.canExecute()) { throw new RuntimeException("Unable to execute execute-as-user binary. Invalid Path: " + this.binaryExecutable.getAbsolutePath()); } }
Construct the object @param nativeLibDirectory Absolute path to the native Lib Directory
validate
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/utils/ExecuteAsUser.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/utils/ExecuteAsUser.java
Apache-2.0
public static synchronized void addGroupAndUserForEffectiveUser(final ExecuteAsUser executeAsUser, final String effectiveUser) throws Exception { List<String> commands = Arrays.asList(ADD_GROUP_PATH, effectiveUser); int result = executeAsUser.execute("root", commands); // If group is added successfully, it will return code 0. // If group is already added then it will return code 9. if (result == 0 || result == 9) { logger.info("Group is added successfully."); commands = Arrays .asList(ADD_USER_PATH, "-l", "-m", effectiveUser, "-g", effectiveUser); result = executeAsUser.execute("root", commands); // If user is added successfully, it will return code 0. // If user is already added then it will return code 9. if (result == 0 || result == 9) { logger.info("User is added successfully."); } else { final String errorMessage = "Failed to add user:" + effectiveUser + "Return value was: " + result; logger.error(errorMessage); throw new JobExecutionException(errorMessage); } } else { final String errorMessage = "Failed to add group:" + effectiveUser + "Return value was: " + result; logger.error(errorMessage); throw new JobExecutionException(errorMessage); } }
Add group and user on environment where job will run before job process starts. These commands can only be executed by root user. Keep it synchronized in case of race condition. Otherwise, it is possible that while threadA creates a new user and not yet finish the create user call, threadB finds user is already created and thus continue the processing which ends up with user not found error. @param effectiveUser @throws Exception
addGroupAndUserForEffectiveUser
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/utils/ExecuteAsUserUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/utils/ExecuteAsUserUtils.java
Apache-2.0
private static boolean validExternalLink(final String externalLinkUrl, final int timeout) { final RequestConfig config = RequestConfig.custom() .setConnectTimeout(timeout) .setConnectionRequestTimeout(timeout) .setSocketTimeout(timeout).build(); final CloseableHttpClient client = HttpClients.custom() .setDefaultRequestConfig(config) .setSSLSocketFactory(null).disableRedirectHandling().build(); try { try { final HttpResponse httpResponse = client.execute(new HttpGet(externalLinkUrl)); final int responseCode = httpResponse.getStatusLine().getStatusCode(); if (responseCode >= HttpStatus.SC_BAD_REQUEST) { logger.warn("validExternalLink url " + externalLinkUrl + " not reachable, response code " + responseCode); return false; } logger.debug("validExternalLink url " + externalLinkUrl + " is reachable."); return true; } finally { client.close(); } } catch (Exception e) { logger.error("validExternalLink url " + externalLinkUrl + " CONNECT ERROR " + e); return false; } }
Check if the external link url is reachable by making a http request to it. If the response has 200x or 300x status code, returns true, and the external link is enabled or rendered clickable in the UI, otherwise returns false, and the external link is rendered disabled.
validExternalLink
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/utils/ExternalLinkUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/utils/ExternalLinkUtils.java
Apache-2.0
public static boolean isDirWritable(final File dir) { File testFile = null; try { testFile = new File(dir, "_tmp"); /* * Create and delete a dummy file in order to check file permissions. Maybe * there is a safer way for this check. */ testFile.createNewFile(); } catch (final IOException e) { return false; } finally { if (testFile != null) { testFile.delete(); } } return true; }
Check if a directory is writable @param dir directory file object @return true if it is writable. false, otherwise
isDirWritable
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/utils/FileIOUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/utils/FileIOUtils.java
Apache-2.0
public static boolean isValidDirectory(File directory) { if (!directory.exists()) { LOGGER.warn("Directory [" + directory.toPath() + "] does not exist."); return false; } if (!directory.isDirectory()) { LOGGER.error("Directory [" + directory.toPath() + "] is invalid. No extra plugins will be loaded"); return false; } if (!directory.canRead()) { LOGGER.error("Directory [" + directory.toPath() + "] is not readable. No extra plugins will be loaded"); return false; } return true; }
Check if a directory is a valid directory @param directory directory file object @return true if it exists, valid and readable
isValidDirectory
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/utils/FileIOUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/utils/FileIOUtils.java
Apache-2.0
public static void deleteDirectorySilently(final File dir) { if (dir != null) { try { FileUtils.deleteDirectory(dir); } catch (final IOException e) { LOGGER.error("error when deleting dir {}", dir, e); } } }
Delete a directory, log the error if deletion fails.
deleteDirectorySilently
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/utils/FileIOUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/utils/FileIOUtils.java
Apache-2.0
public static File getDirectory(File parentDirectory, String folderName) { File directory = new File(parentDirectory, folderName); if (!directory.exists()) { directory.mkdir(); } return directory; }
Get Directory or Create a Directory if it does not exist @param parentDirectory parent Directory name @param folderName sub folder name @return handle of File
getDirectory
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/utils/FileIOUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/utils/FileIOUtils.java
Apache-2.0
public static void moveFiles(File sourceDirectory, File destinationDiretory, String fileNamePattern) throws IOException { File[] files = sourceDirectory.listFiles(); for (File file : files) { if (!file.isDirectory()) { if (file.getName().matches(fileNamePattern)) { Files.move( Paths.get(file.getAbsolutePath()), Paths.get(String.format("%s/%s", destinationDiretory.getAbsolutePath(), file.getName()))); } } } }
Move Files from source directory to destinationDirectory if the file name matches the given pattern @param sourceDirectory source directory @param destinationDiretory destination directory @param fileNamePattern regular expression pattern of file name's @throws IOException
moveFiles
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/utils/FileIOUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/utils/FileIOUtils.java
Apache-2.0
public static void dumpNumberToFile(final Path filePath, final long num) throws IOException { try (final BufferedWriter writer = Files .newBufferedWriter(filePath, StandardCharsets.UTF_8)) { writer.write(String.valueOf(num)); } catch (final IOException e) { LOGGER.error("Failed to write the number {} to the file {}", num, filePath, e); throw e; } }
Dumps a number into a new file. @param filePath the target file @param num the number to dump @throws IOException if file already exists
dumpNumberToFile
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/utils/FileIOUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/utils/FileIOUtils.java
Apache-2.0
public static String getCanonicalPath(final File f) { try { return f.getCanonicalPath(); } catch (IOException e) { throw new RuntimeException(e); } }
A thin wrapper for File.getCanonicalPath() that doesn't throw a checked exception @param f input file @return String canonical path of the file
getCanonicalPath
java
azkaban/azkaban
azkaban-common/src/main/java/azkaban/utils/FileIOUtils.java
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/utils/FileIOUtils.java
Apache-2.0