_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q170000 | MinDeps.setOptions | validation | public boolean setOptions(String[] options) throws Exception {
ArgumentParser parser;
Namespace ns;
parser = ArgumentParsers.newArgumentParser(MinDeps.class.getName());
parser.addArgument("--java-home")
.type(Arguments.fileType().verifyExists().verifyIsDirectory())
.dest("javahome")
.required(true)
.help("The java home directory of the JDK that includes the jdeps binary, default is taken from JAVA_HOME environment variable.");
parser.addArgument("--class-path")
.dest("classpath")
.required(true)
.help("The CLASSPATH to use for jdeps.");
parser.addArgument("--classes")
.type(Arguments.fileType().verifyExists().verifyIsFile().verifyCanRead())
.dest("classes")
.required(true)
.help("The file containing the classes to determine the dependencies for. Empty lines and lines starting with # get ignored.");
parser.addArgument("--additional")
.type(Arguments.fileType())
.setDefault(new File("."))
.required(false)
.dest("additional")
.help("The file with additional class names to just include.");
parser.addArgument("--output")
.type(Arguments.fileType())
.setDefault(new File("."))
.required(false)
.dest("output")
.help("The file for storing the determined class names in.");
parser.addArgument("package")
.dest("packages")
.required(true)
.nargs("+")
.help("The packages to keep, eg 'weka'.");
try {
ns = parser.parseArgs(options);
}
catch (ArgumentParserException e) {
parser.handleError(e);
return false;
}
setJavaHome(ns.get("javahome"));
setClassPath(ns.getString("classpath"));
setClassesFile(ns.get("classes"));
setAdditionalFile(ns.get("additional"));
setPackages(ns.getList("packages"));
setOutputFile(ns.get("output"));
return true;
} | java | {
"resource": ""
} |
q170001 | MinDeps.check | validation | protected String check() {
String error;
if (!m_JavaHome.exists())
return "Java home directory does not exist: " + m_JavaHome;
if (!m_JavaHome.isDirectory())
return "Java home does not point to a directory: " + m_JavaHome;
if (System.getProperty("os.name").toLowerCase().contains("windows"))
m_Jdeps = new File(m_JavaHome.getAbsolutePath() + File.separator + "bin" + File.separator + "jdeps.exe");
else
m_Jdeps = new File(m_JavaHome.getAbsolutePath() + File.separator + "bin" + File.separator + "jdeps");
if (!m_Jdeps.exists())
return "jdeps binary does not exist: " + m_Jdeps;
if (!m_ClassesFile.exists())
return "File with class names does not exist: " + m_ClassesFile;
if (m_ClassesFile.isDirectory())
return "File with class names points to directory: " + m_ClassesFile;
// read classes
error = readFile(m_ClassesFile, m_Classes);
if (error != null)
return error;
// read resources
if ((m_AdditionalFile != null) && m_AdditionalFile.exists() && (!m_AdditionalFile.isDirectory())) {
error = readFile(m_AdditionalFile, m_Resources);
if (error != null)
return error;
}
return null;
} | java | {
"resource": ""
} |
q170002 | MinDeps.filter | validation | protected List<String> filter(List<String> lines, String regexp, boolean invert) {
List<String> result;
Pattern pattern;
result = new ArrayList<>();
pattern = Pattern.compile(regexp);
for (String line: lines) {
if (invert) {
if (!pattern.matcher(line).matches())
result.add(line);
}
else {
if (pattern.matcher(line).matches())
result.add(line);
}
}
return result;
} | java | {
"resource": ""
} |
q170003 | MinDeps.packagesRegExp | validation | protected String packagesRegExp() {
StringBuilder result;
int i;
String pkg;
result = new StringBuilder();
result.append(".* (");
for (i = 0; i < m_Packages.size(); i++) {
if (i > 0)
result.append("|");
pkg = m_Packages.get(i);
if (!pkg.endsWith("."))
pkg = pkg + ".";
pkg = pkg.replace(".", "\\.");
result.append(pkg);
}
result.append(").*$");
return result.toString();
} | java | {
"resource": ""
} |
q170004 | MinDeps.output | validation | public void output() {
if ((m_OutputFile == null || m_OutputFile.isDirectory())) {
for (String dep : m_Dependencies)
System.out.println(dep);
}
else {
try {
Files.write(m_OutputFile.toPath(), m_Dependencies, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
}
catch (Exception e) {
System.err.println("Failed to write dependencies to: " + m_OutputFile);
e.printStackTrace();
}
}
} | java | {
"resource": ""
} |
q170005 | InstanceProvider.compareTo | validation | @Override
public int compareTo(InstanceProvider instanceProvider) {
if (this.getPriority().equals(instanceProvider.getPriority())) {
return this.getName().compareTo(instanceProvider.getName());
} else {
return this.getPriority().compareTo(instanceProvider.getPriority());
}
} | java | {
"resource": ""
} |
q170006 | UtilsFactory.getIOUtils | validation | public static IOUtils getIOUtils() {
if (ioUtils == null) {
try {
Class clazz = Class.forName(IO_UTILS);
ioUtils = (IOUtils) clazz.newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
LOGGER.warn("Cannot instanciate util: {}", e.getMessage());
throw new IllegalStateException(e);
}
}
return ioUtils;
} | java | {
"resource": ""
} |
q170007 | UtilsFactory.getImageUtils | validation | public static ImageUtils getImageUtils() {
if (imageUtils == null) {
try {
Class clazz = Class.forName(IMAGE_UTILS);
imageUtils = (ImageUtils) clazz.newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
LOGGER.warn("Cannot instanciate util: {}", e.getMessage());
throw new IllegalStateException(e);
}
}
return imageUtils;
} | java | {
"resource": ""
} |
q170008 | UtilsFactory.getPriceUtils | validation | public static PriceUtils getPriceUtils() {
if (priceUtils == null) {
try {
Class clazz = Class.forName(PRICE_UTILS);
priceUtils = (PriceUtils) clazz.newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
LOGGER.warn("Cannot instanciate util: {}", e.getMessage());
throw new IllegalStateException(e);
}
}
return priceUtils;
} | java | {
"resource": ""
} |
q170009 | UtilsFactory.getResourceUtils | validation | public static ResourceUtils getResourceUtils() {
if (resourceUtils == null) {
try {
Class clazz = Class.forName(RESOURCE_UTILS);
resourceUtils = (ResourceUtils) clazz.newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
LOGGER.warn("Cannot instanciate util: {}", e.getMessage());
throw new IllegalStateException(e);
}
}
return resourceUtils;
} | java | {
"resource": ""
} |
q170010 | UtilsFactory.getZipUtils | validation | public static ZipUtils getZipUtils() {
if (zipUtils == null) {
try {
Class clazz = Class.forName(ZIP_UTILS);
zipUtils = (ZipUtils) clazz.newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
LOGGER.warn("Cannot instanciate util: {}",e.getMessage());
throw new IllegalStateException(e);
}
}
return zipUtils;
} | java | {
"resource": ""
} |
q170011 | UtilsFactory.getDigestUtils | validation | public static DigestUtils getDigestUtils() {
if (digestUtils == null) {
try {
Class clazz = Class.forName(DIGEST_UTILS);
digestUtils = (DigestUtils) clazz.newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
LOGGER.warn("Cannot instanciate util: {}", e.getMessage());
throw new IllegalStateException(e);
}
}
return digestUtils;
} | java | {
"resource": ""
} |
q170012 | UtilsFactory.getStringUtils | validation | public static StringUtils getStringUtils() {
if (stringUtils == null) {
try {
Class clazz = Class.forName(STRING_UTILS);
stringUtils = (StringUtils) clazz.newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
LOGGER.warn("Cannot instanciate util: {}", e.getMessage());
throw new IllegalStateException(e);
}
}
return stringUtils;
} | java | {
"resource": ""
} |
q170013 | UtilsFactory.getResourceService | validation | public static ResourceService getResourceService() {
if (resourceService == null) {
try {
Class clazz = Class.forName(RESOURCE_SERVICE);
resourceService = (ResourceService) clazz.newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
LOGGER.warn("Cannot instanciate util: {}", e.getMessage());
throw new IllegalStateException(e);
}
}
return resourceService;
} | java | {
"resource": ""
} |
q170014 | UtilsFactory.getPricingService | validation | public static PricingService getPricingService() {
if (pricingService == null) {
try {
Class clazz = Class.forName(PRICING_SERVICE);
pricingService = (PricingService) clazz.newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
LOGGER.warn("Cannot instanciate util: {}", e.getMessage());
throw new IllegalStateException(e);
}
}
return pricingService;
} | java | {
"resource": ""
} |
q170015 | UtilsFactory.getInstanceService | validation | public static InstanceService getInstanceService() {
if (instanceService == null) {
try {
Class clazz = Class.forName(INSTANCE_SERVICE);
instanceService = (InstanceService) clazz.newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
LOGGER.warn("Cannot instanciate util: {}", e.getMessage());
throw new IllegalStateException(e);
}
}
return instanceService;
} | java | {
"resource": ""
} |
q170016 | WorkflowHarvester.getObjectId | validation | @Override
public Set<String> getObjectId(File uploadedFile) throws HarvesterException {
Set<String> objectIds = new HashSet<String>();
try {
objectIds.add(createDigitalObject(uploadedFile));
} catch (StorageException se) {
throw new HarvesterException(se);
}
return objectIds;
} | java | {
"resource": ""
} |
q170017 | WorkflowHarvester.createDigitalObject | validation | private String createDigitalObject(File file) throws HarvesterException,
StorageException {
String objectId;
DigitalObject object;
if (forceUpdate) {
object = StorageUtils.storeFile(getStorage(), file,
!forceLocalStorage);
} else {
String oid = StorageUtils.generateOid(file);
String pid = StorageUtils.generatePid(file);
object = getStorage().createObject(oid);
if (forceLocalStorage) {
try {
object.createStoredPayload(pid, new FileInputStream(file));
} catch (FileNotFoundException ex) {
throw new HarvesterException(ex);
}
} else {
object.createLinkedPayload(pid, file.getAbsolutePath());
}
}
// update object metadata
Properties props = object.getMetadata();
props.setProperty("render-pending", "true");
props.setProperty("file.path",
FilenameUtils.separatorsToUnix(file.getAbsolutePath()));
objectId = object.getId();
// Store rendition information if we have it
String ext = FilenameUtils.getExtension(file.getName());
for (String chain : renderChains.keySet()) {
Map<String, List<String>> details = renderChains.get(chain);
if (details.get("fileTypes").contains(ext)) {
storeList(props, details, "harvestQueue");
storeList(props, details, "indexOnHarvest");
storeList(props, details, "renderQueue");
}
}
object.close();
return objectId;
} | java | {
"resource": ""
} |
q170018 | WorkflowHarvester.storeList | validation | private void storeList(Properties props, Map<String, List<String>> details,
String field) {
Set<String> valueSet = new LinkedHashSet<String>();
// merge with original property value if exists
String currentValue = props.getProperty(field, "");
if (!"".equals(currentValue)) {
String[] currentList = currentValue.split(",");
valueSet.addAll(Arrays.asList(currentList));
}
valueSet.addAll(details.get(field));
String joinedList = StringUtils.join(valueSet, ",");
props.setProperty(field, joinedList);
} | java | {
"resource": ""
} |
q170019 | MetadataManager.ensureMetadata | validation | public List<MetadataInfo> ensureMetadata(final MigratoryOption [] options)
throws MigratoryException
{
if (migratoryContext.getDbSupport().tableExists(migratoryConfig.getMetadataTableName()))
{
return null;
}
if (migratoryConfig.isReadOnly()) {
throw new MigratoryException(Reason.IS_READONLY);
}
// Table does not exist. The way we get one, is that we run a special migration for the internal metadata schema
final MigrationPlanner migrationPlanner = new MigrationPlanner(new MigrationManager(migratoryContext, METADATA_MIGRATION_NAME), 0, Integer.MAX_VALUE);
migrationPlanner.plan();
if (migrationPlanner.getDirection() != MigrationDirection.FORWARD) {
throw new MigratoryException(Reason.INTERNAL, "Migration planner could not plan a migration for the metadata table!");
}
final DbMigrator migrator = new DbMigrator(migratoryContext, migrationPlanner);
try {
lock(METADATA_MIGRATION_NAME);
final List<MigrationResult> results = migrator.migrate(options);
return commit(results);
} catch (MigratoryException e) {
rollback();
throw e;
} catch (RuntimeException e) {
rollback();
throw e;
}
} | java | {
"resource": ""
} |
q170020 | DryDetailBuilder.createDrySourceDetail | validation | private Object createDrySourceDetail(final AbstractBuild<?, ?> owner,
final AnnotationContainer container, final String defaultEncoding,
final String fromString, final String toString) {
long from = Long.parseLong(fromString);
long to = Long.parseLong(toString);
FileAnnotation fromAnnotation = container.getAnnotation(from);
if (fromAnnotation instanceof DuplicateCode) {
return new SourceDetail(owner, ((DuplicateCode)fromAnnotation).getLink(to), defaultEncoding);
}
return null;
} | java | {
"resource": ""
} |
q170021 | ThresholdValidation.validate | validation | private FormValidation validate(final String highThreshold, final String normalThreshold, final String message) {
try {
int high = Integer.parseInt(highThreshold);
int normal = Integer.parseInt(normalThreshold);
if (isValid(normal, high)) {
return FormValidation.ok();
}
}
catch (NumberFormatException exception) {
// ignore and return failure
}
return FormValidation.error(message);
} | java | {
"resource": ""
} |
q170022 | Utils.validateArgs | validation | static void validateArgs(List<Object> args, Object instance, Method m, Command cmd) {
if (!onClasspath(JSR303_1_1_CLASSNAME)) {
return;
}
try {
Object validator = getValidator();
Method validate = validator.getClass().getMethod("validateArgs", List.class,
Object.class, Method.class, Command.class);
validate.invoke(validator, args, instance, m, cmd);
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof RuntimeException) {
throw (RuntimeException) e.getCause();
}
throw new RuntimeException(e.getCause());
} catch (Exception e) {
throw new RuntimeException(e);
}
} | java | {
"resource": ""
} |
q170023 | Utils.validateOpts | validation | static void validateOpts(Object instance) {
if (!onClasspath(JSR303_1_0_CLASSNAME)) {
return;
}
try {
Object validator = getValidator();
Method validate = validator.getClass().getMethod("validateOpts", Object.class);
validate.invoke(validator, instance);
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof RuntimeException) {
throw (RuntimeException) e.getTargetException();
}
throw new RuntimeException(e.getTargetException());
} catch (RuntimeException e) {
throw e;
} catch (Throwable e) {
throw new RuntimeException(e);
}
} | java | {
"resource": ""
} |
q170024 | Utils.onClasspath | validation | static boolean onClasspath(String className) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
cl.loadClass(className);
} catch (ClassNotFoundException e) {
return false;
}
return true;
} | java | {
"resource": ""
} |
q170025 | LoaderManager.accept | validation | public boolean accept(final URI uri)
{
for (final MigrationLoader loader : loaders) {
if (loader.accept(uri)) {
return true;
}
}
return false;
} | java | {
"resource": ""
} |
q170026 | LoaderManager.loadFile | validation | public String loadFile(final URI fileUri)
{
try {
for (final MigrationLoader loader : loaders) {
if (loader.accept(fileUri)) {
return loader.loadFile(fileUri);
}
}
return null;
}
catch (IOException ioe) {
throw new MigratoryException(Reason.INTERNAL, ioe);
}
} | java | {
"resource": ""
} |
q170027 | CliMain.run | validation | public void run() throws RuntimeException {
if (terminalArgs == null) {
terminalArgs = new String[0];
}
p = GNUishParser.parse(terminalArgs);
readCommands();
if (p.getCommand() == null || "".equals(p.getCommand())) {
Utils.printAvailableCommandsHelp(commands);
return;
}
final Command cmd = commands.get(p.getCommand());
if (cmd == null) {
throw CliException.COMMAND_NOT_FOUND(p.getCommand());
}
if (p.help()) {
Utils.printCommandHelp(cmd);
return;
}
try {
cmd.execute(p);
} catch (Exception e) {
if (p.debug()) {
e.printStackTrace();
}
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
}
} | java | {
"resource": ""
} |
q170028 | CliMain.readCommands | validation | private void readCommands() {
try {
final Enumeration<URL> urls = Thread.currentThread().getContextClassLoader()
.getResources(XmlCommands.FILEPATH);
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
InputStream in = url.openStream();
for (Command command : XmlCommands.fromXml(in)) {
commands.put(command.getCommand(), command);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
} | java | {
"resource": ""
} |
q170029 | AsyncHttpHandlerSupport.postProcess | validation | protected void postProcess(final String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response)
throws IOException, ServletException {
// NOOP
} | java | {
"resource": ""
} |
q170030 | AsyncHttpHandlerSupport.preProcess | validation | protected Map<String, Object> preProcess(final String target, final Request baseRequest, final HttpServletRequest request,
final HttpServletResponse response) throws IOException, ServletException {
return Collections.emptyMap();
} | java | {
"resource": ""
} |
q170031 | Migratory.dbMigrate | validation | public Map<String, List<MetadataInfo>> dbMigrate(final MigrationPlan migrationPlan, final MigratoryOption ... options) throws MigratoryException
{
init();
final InternalMigrator migrator = new InternalMigrator(this);
return migrator.migrate(migrationPlan, options);
} | java | {
"resource": ""
} |
q170032 | Migratory.dbValidate | validation | public Map<String, ValidationResult> dbValidate(final Collection<String> personalities, final MigratoryOption ... options) throws MigratoryException
{
init();
final InternalValidator validator = new InternalValidator(this);
return validator.validate(personalities, options);
} | java | {
"resource": ""
} |
q170033 | Migratory.dbHistory | validation | public Map<String, List<MetadataInfo>> dbHistory(final Collection<String> personalities, final MigratoryOption ... options)
throws MigratoryException
{
init();
final InternalHistory internalHistory = new InternalHistory(this);
return internalHistory.history(personalities, options);
} | java | {
"resource": ""
} |
q170034 | Migratory.dbInit | validation | public List<MetadataInfo> dbInit(final MigratoryOption ... options) throws MigratoryException
{
init();
final InternalInit internalInit = new InternalInit(this);
return internalInit.init(options);
} | java | {
"resource": ""
} |
q170035 | SqlScript.linesToStatements | validation | List<SqlStatement> linesToStatements(List<String> lines)
{
final List<SqlStatement> statements = Lists.newArrayList();
final StringBuilder statementSql = new StringBuilder();
int count = 0;
String delimiter = DEFAULT_STATEMENT_DELIMITER;
for (final String line : lines)
{
if (StringUtils.isBlank(line)) {
continue;
}
if (statementSql.length() > 0) {
statementSql.append(" ");
}
statementSql.append(line);
final String oldDelimiter = delimiter;
delimiter = changeDelimiterIfNecessary(statementSql.toString(), line, delimiter);
if (!StringUtils.equals(delimiter, oldDelimiter) && isDelimiterChangeExplicit()) {
statementSql.setLength(0);
continue; // for
}
if (StringUtils.endsWith(line, delimiter)) {
// Trim off the delimiter at the end.
statementSql.setLength(statementSql.length() - delimiter.length());
statements.add(new SqlStatement(count++, StringUtils.trimToEmpty(statementSql.toString())));
LOG.debug("Found statement: {}", statementSql);
if (!isDelimiterChangeExplicit()) {
delimiter = DEFAULT_STATEMENT_DELIMITER;
}
statementSql.setLength(0);
}
}
// Catch any statements not followed by delimiter.
if (statementSql.length() > 0) {
statements.add(new SqlStatement(count++, StringUtils.trimToEmpty(statementSql.toString())));
}
return statements;
} | java | {
"resource": ""
} |
q170036 | NotableLinkRepository.findByNotableAndCalendarName | validation | @Programmatic
public NotableLink findByNotableAndCalendarName(
final Object notable,
final String calendarName) {
if(notable == null) {
return null;
}
if(calendarName == null) {
return null;
}
final Bookmark bookmark = bookmarkService.bookmarkFor(notable);
if(bookmark == null) {
return null;
}
final String notableStr = bookmark.toString();
return repositoryService.firstMatch(
new QueryDefault<>(NotableLink.class,
"findByNotableAndCalendarName",
"notableStr", notableStr,
"calendarName", calendarName));
} | java | {
"resource": ""
} |
q170037 | NotableLinkRepository.updateLink | validation | @Programmatic
public void updateLink(final Note note) {
final NotableLink link = findByNote(note);
sync(note, link);
} | java | {
"resource": ""
} |
q170038 | GNUishParser.parseOpts | validation | private String[] parseOpts(String[] args) {
if (args == null || args.length == 0) {
return new String[0];
}
final List<String> remainingArgs = new ArrayList<String>();
final List<String> argsList = Arrays.asList(args);
final ListIterator<String> argsIt = argsList.listIterator();
while (argsIt.hasNext()) {
String word = argsIt.next();
if (word.startsWith("--")) {
// long option --foo
final String option = stripLeadingHyphens(word);
if (VERBOSE_LONG_OPT.equals(option)) {
longOpts.put(option, "true");
} else if (DEBUG_LONG_OPT.equals(option)) {
longOpts.put(option, "true");
} else if (HELP_LONG_OPT.equals(option)) {
longOpts.put(option, "true");
} else {
final String arg = parseOptionArg(option, argsIt);
longOpts.put(option, arg);
}
} else if (word.startsWith("-")) {
String options = stripLeadingHyphens(word);
// single short option -f
if (options.length() == 1) {
// only slurp argument if option is argumented
final String arg = parseOptionArg(options, argsIt);
shortOpts.put(options, arg);
continue;
}
// multiple short options -fxy,
// treat as non-argumented java.lang.Boolean variables, no slurp
for (int i = 0; i < options.length(); i++) {
final String option = Character.toString(options.charAt(i));
shortOpts.put(option, "true");
}
} else {
remainingArgs.add(word);
}
}
return remainingArgs.toArray(new String[0]);
} | java | {
"resource": ""
} |
q170039 | IntraVMClient.transmit | validation | public void transmit( Command c, Map h, String b ) {
_server.receive( c, h, b, this );
} | java | {
"resource": ""
} |
q170040 | DuplicateCode.getFormattedSourceCode | validation | public String getFormattedSourceCode() {
try {
JavaSource source = new JavaSourceParser().parse(new StringReader(sourceCode));
JavaSource2HTMLConverter converter = new JavaSource2HTMLConverter();
StringWriter writer = new StringWriter();
JavaSourceConversionOptions options = JavaSourceConversionOptions.getDefault();
options.setShowLineNumbers(false);
options.setAddLineAnchors(false);
converter.convert(source, options, writer);
return writer.toString();
}
catch (IllegalConfigurationException exception) {
return sourceCode;
}
catch (IOException exception) {
return sourceCode;
}
} | java | {
"resource": ""
} |
q170041 | DuplicateCode.getLink | validation | public FileAnnotation getLink(final long linkHashCode) {
for (FileAnnotation link : links) {
if (link.getKey() == linkHashCode) {
return link;
}
}
throw new NoSuchElementException("Linked annotation not found: key=" + linkHashCode);
} | java | {
"resource": ""
} |
q170042 | Client.transmit | validation | public void transmit( Command c, Map h, String b ) {
try {
Transmitter.transmit( c, h, b, _output );
} catch (Exception e) {
receive( Command.ERROR, null, e.getMessage() );
}
} | java | {
"resource": ""
} |
q170043 | JAXBContextCache.get | validation | public static JAXBContext get(final String contextPath) {
Assert.hasText(contextPath, "contextPath is required");
JAXBContext ctx = jaxbContexts.get(contextPath);
if (ctx == null) {
try {
ctx = JAXBContext.newInstance(contextPath);
} catch (final JAXBException e) {
throw new IllegalArgumentException("Failed to create JAXBContext - invalid JAXB context path: " + contextPath, e);
}
jaxbContexts.put(contextPath, ctx);
LoggerFactory.getLogger(JAXBContextCache.class).info("cached : {}", contextPath);
}
return ctx;
} | java | {
"resource": ""
} |
q170044 | CSSBoxTreeBuilder.createBoxList | validation | private void createBoxList(Box root, Vector<BoxNode> list)
{
if (root.isDisplayed())
{
if (!(root instanceof Viewport) && root.isVisible())
{
BoxNode newnode = new BoxNode(root, page, zoom);
newnode.setOrder(order_counter++);
list.add(newnode);
}
if (root instanceof ElementBox)
{
ElementBox elem = (ElementBox) root;
for (int i = elem.getStartChild(); i < elem.getEndChild(); i++)
createBoxList(elem.getSubBox(i), list);
}
}
} | java | {
"resource": ""
} |
q170045 | CSSBoxTreeBuilder.createBoxTree | validation | private BoxNode createBoxTree(ElementBox rootbox, Vector<BoxNode> boxlist, boolean useBounds, boolean useVisualBounds, boolean preserveAux)
{
//a working copy of the box list
Vector<BoxNode> list = new Vector<BoxNode>(boxlist);
//an artificial root node
BoxNode root = new BoxNode(rootbox, page, zoom);
root.setOrder(0);
//detach the nodes from any old trees
for (BoxNode node : list)
node.removeFromTree();
//when working with visual bounds, remove the boxes that are not visually separated
if (!preserveAux)
{
for (Iterator<BoxNode> it = list.iterator(); it.hasNext(); )
{
BoxNode node = it.next();
if (!node.isVisuallySeparated() || !node.isVisible())
it.remove();
}
}
//let each node choose it's children - find the roots and parents
for (BoxNode node : list)
{
if (useBounds)
node.markNodesInside(list, useVisualBounds);
else
node.markChildNodes(list);
}
//choose the roots
for (Iterator<BoxNode> it = list.iterator(); it.hasNext();)
{
BoxNode node = it.next();
/*if (!full) //DEBUG
{
if (node.toString().contains("mediawiki") || node.toString().contains("globalWrapper"))
System.out.println(node + " => " + node.nearestParent);
}*/
if (node.isRootNode())
{
root.appendChild(node);
it.remove();
}
}
//recursively choose the children
for (int i = 0; i < root.getChildCount(); i++)
((BoxNode) root.getChildAt(i)).takeChildren(list);
return root;
} | java | {
"resource": ""
} |
q170046 | CSSBoxTreeBuilder.computeBackgrounds | validation | private void computeBackgrounds(BoxNode root, Color currentbg)
{
Color newbg = root.getBackgroundColor();
if (newbg == null)
newbg = currentbg;
root.setEfficientBackground(newbg);
root.setBackgroundSeparated(!newbg.equals(currentbg));
for (int i = 0; i < root.getChildCount(); i++)
computeBackgrounds((BoxNode) root.getChildAt(i), newbg);
} | java | {
"resource": ""
} |
q170047 | ComponentURLStreamHandlerFactory.setMappingFile | validation | public void setMappingFile(URL url, String realFile){
if (componentFiles == null) initFastIndexes("app", "lib", "repository");
File file = new File(realFile);
componentFiles.put(url.getFile(), file);
} | java | {
"resource": ""
} |
q170048 | ComponentURLStreamHandlerFactory.getMappingFile | validation | public File getMappingFile(URL url) throws IOException {
if (componentFiles == null) initFastIndexes("app", "lib", "repository");
String fileName = FilenameUtils.normalize(url.getFile(), true);
if( !fileName.endsWith(".jar") ) fileName = fileName + ".jar";
if( fileName.startsWith("boot/") || fileName.startsWith("boot\\") ){
fileName = "net.happyonroad/" + FilenameUtils.getName(fileName);
}else if(fileName.startsWith("lib/") || fileName.startsWith("lib\\")){/* Only 3rd lib file will be put into jar classpath*/
//正常的组件component url里面肯定不是lib开头;
// 但是 spring-component-framework的Class-Path指定的那些url被normalize之后却会如此
fileName = ComponentUtils.relativePath(fileName);
}
File componentFile = componentFiles.get(fileName);
if( componentFile == null )
{
// 当第一次建立的快速索引中没有相应文件时
// 尝试看lib下后来有没有相应的文件
componentFile = guessFile(url, "app", "lib", "repository");
if( componentFile == null )
throw new IOException("there is no component named as " + fileName);
}
return componentFile;
} | java | {
"resource": ""
} |
q170049 | VersionRange.createFromVersionSpec | validation | public static VersionRange createFromVersionSpec( String spec )
throws InvalidVersionSpecificationException
{
if ( spec == null )
{
return null;
}
List<Restriction> restrictions = new ArrayList<Restriction>();
String process = spec;
ComponentVersion version = null;
ComponentVersion upperBound = null;
ComponentVersion lowerBound = null;
while ( process.startsWith( "[" ) || process.startsWith( "(" ) )
{
int index1 = process.indexOf( ")" );
int index2 = process.indexOf( "]" );
int index = index2;
if ( index2 < 0 || index1 < index2 )
{
if ( index1 >= 0 )
{
index = index1;
}
}
if ( index < 0 )
{
throw new InvalidVersionSpecificationException( "Unbounded range: " + spec );
}
Restriction restriction = parseRestriction( process.substring( 0, index + 1 ) );
if ( lowerBound == null )
{
lowerBound = restriction.getLowerBound();
}
if ( upperBound != null )
{
if ( restriction.getLowerBound() == null || restriction.getLowerBound().compareTo( upperBound ) < 0 )
{
throw new InvalidVersionSpecificationException( "Ranges overlap: " + spec );
}
}
restrictions.add( restriction );
upperBound = restriction.getUpperBound();
process = process.substring( index + 1 ).trim();
if ( process.length() > 0 && process.startsWith( "," ) )
{
process = process.substring( 1 ).trim();
}
}
if ( process.length() > 0 )
{
if ( restrictions.size() > 0 )
{
throw new InvalidVersionSpecificationException(
"Only fully-qualified sets allowed in multiple set scenario: " + spec );
}
else
{
version = new ComponentVersion( process );
restrictions.add( Restriction.EVERYTHING );
}
}
return new VersionRange( version, restrictions );
} | java | {
"resource": ""
} |
q170050 | BoxTransform.concatenate | validation | public BoxTransform concatenate(BoxTransform src)
{
if (src.isEmpty())
return this;
else if (this.isEmpty())
return src;
else
{
BoxTransform ret = new BoxTransform(this);
ret.transform = new AffineTransform(transform);
ret.transform.concatenate(src.transform);
return ret;
}
} | java | {
"resource": ""
} |
q170051 | BoxTransform.transformRect | validation | public Rectangular transformRect(Rectangular rect)
{
if (transform != null)
{
Rectangle src = new Rectangle(rect.getX1(), rect.getY1(), rect.getWidth(), rect.getHeight());
Shape dest = transform.createTransformedShape(src);
Rectangle destr;
if (dest instanceof Rectangle)
destr = (Rectangle) dest;
else
destr = dest.getBounds();
return new Rectangular(destr);
}
else
return rect;
} | java | {
"resource": ""
} |
q170052 | BoxNode.getMinimalVisualBounds | validation | private Rectangular getMinimalVisualBounds()
{
final Box box = getBox();
if (box instanceof TextBox)
return new RectangularZ(box.getAbsoluteBounds().intersection(box.getClipBlock().getClippedContentBounds()), zoom);
else if (box != null && box.isReplaced())
return new RectangularZ(box.getMinimalAbsoluteBounds().intersection(box.getClipBlock().getClippedContentBounds()), zoom);
else
{
Rectangular ret = null;
for (int i = 0; i < getChildCount(); i++)
{
BoxNode subnode = (BoxNode) getChildAt(i);
Box sub = subnode.getBox();
Rectangular sb = subnode.getVisualBounds();
if (sub.isDisplayed() && subnode.isVisible() && sb.getWidth() > 0 && sb.getHeight() > 0)
{
if (ret == null)
ret = new Rectangular(sb);
else
ret.expandToEnclose(sb);
}
}
//if nothing has been found return an empty rectangle at the top left corner
if (ret == null)
{
Rectangle b = box.getAbsoluteBounds().intersection(box.getClipBlock().getClippedContentBounds());
return new RectangularZ(b.x, b.y, zoom);
}
else
return ret;
}
} | java | {
"resource": ""
} |
q170053 | BoxNode.recomputeVisualBounds | validation | public void recomputeVisualBounds()
{
for (int i = 0; i < getChildCount(); i++)
((BoxNode) getChildAt(i)).recomputeVisualBounds();
visual = computeVisualBounds();
} | java | {
"resource": ""
} |
q170054 | BoxNode.recomputeBounds | validation | public void recomputeBounds()
{
bounds = new Rectangular(visual);
for (int i = 0; i < getChildCount(); i++)
{
BoxNode child = (BoxNode) getChildAt(i);
child.recomputeBounds();
expandToEnclose(child);
}
} | java | {
"resource": ""
} |
q170055 | BoxNode.computeContentBounds | validation | private Rectangular computeContentBounds()
{
Box box = getBox();
Rectangular ret = null;
if (box instanceof Viewport)
{
ret = new RectangularZ(((Viewport) box).getClippedBounds(), zoom);
}
else if (box instanceof ElementBox)
{
ElementBox elem = (ElementBox) box;
//at least one border - take the border bounds
//TODO: when only one border is present, we shouldn't take the whole border box?
if (elem.getBorder().top > 0 || elem.getBorder().left > 0 ||
elem.getBorder().bottom > 0 || elem.getBorder().right > 0)
{
ret = new RectangularZ(elem.getAbsoluteBorderBounds(), zoom);
}
//no border
else
{
ret = new RectangularZ(elem.getAbsoluteBackgroundBounds(), zoom);
}
}
else //not an element - return the whole box
ret = new RectangularZ(box.getAbsoluteBounds(), zoom);
//clip with the clipping bounds
if (box.getClipBlock() != null)
{
Rectangular clip = new RectangularZ(box.getClipBlock().getClippedContentBounds(), zoom);
ret = ret.intersection(clip);
}
return ret;
} | java | {
"resource": ""
} |
q170056 | BoxNode.getTopBorder | validation | @Override
public int getTopBorder()
{
Box box = getBox();
if (box instanceof ElementBox)
return ((ElementBox) box).getBorder().top;
else
return 0;
} | java | {
"resource": ""
} |
q170057 | BoxNode.getBottomBorder | validation | @Override
public int getBottomBorder()
{
Box box = getBox();
if (box instanceof ElementBox)
return ((ElementBox) box).getBorder().bottom;
else
return 0;
} | java | {
"resource": ""
} |
q170058 | BoxNode.getLeftBorder | validation | @Override
public int getLeftBorder()
{
Box box = getBox();
if (box instanceof ElementBox)
return ((ElementBox) box).getBorder().left;
else
return 0;
} | java | {
"resource": ""
} |
q170059 | BoxNode.getRightBorder | validation | @Override
public int getRightBorder()
{
Box box = getBox();
if (box instanceof ElementBox)
return ((ElementBox) box).getBorder().right;
else
return 0;
} | java | {
"resource": ""
} |
q170060 | BoxNode.getEfficientColor | validation | public String getEfficientColor()
{
Box box = getBox();
do
{
if (box instanceof ElementBox)
{
String color = ((ElementBox) box).getStylePropertyValue("color");
if (!color.equals(""))
return color;
}
box = box.getParent();
} while (box != null);
return "";
} | java | {
"resource": ""
} |
q170061 | BoxNode.visuallyEncloses1 | validation | public boolean visuallyEncloses1(BoxNode childNode)
{
int cx1 = childNode.getVisualBounds().getX1();
int cy1 = childNode.getVisualBounds().getY1();
int cx2 = childNode.getVisualBounds().getX2();
int cy2 = childNode.getVisualBounds().getY2();
int px1 = getVisualBounds().getX1();
int py1 = getVisualBounds().getY1();
int px2 = getVisualBounds().getX2();
int py2 = getVisualBounds().getY2();
//check how many corners of the child are inside the parent exactly
int xcnt = 0;
if (cx1 >= px1 && cx1 <= px2 &&
cy1 >= py1 && cy1 <= py2) xcnt++; //top left
if (cx2 >= px1 && cx2 <= px2 &&
cy1 >= py1 && cy1 <= py2) xcnt++; //top right
if (cx1 >= px1 && cx1 <= px2 &&
cy2 >= py1 && cy2 <= py2) xcnt++; //bottom left
if (cx2 >= px1 && cx2 <= px2 &&
cy2 >= py1 && cy2 <= py2) xcnt++; //bottom right
/*if (childNode.toString().contains("globalWrapper") && this.toString().contains("mediawiki"))
System.out.println("jo!");*/
if ((cx1 == px1 && cy1 == py1 && cx2 == px2 && cy2 == py2)) //exact overlap
return this.getOrder() < childNode.getOrder();
else
return xcnt == 4;
} | java | {
"resource": ""
} |
q170062 | BoxNode.takeChildren | validation | public void takeChildren(Vector<BoxNode> list)
{
for (Iterator<BoxNode> it = list.iterator(); it.hasNext();)
{
BoxNode node = it.next();
if (node.nearestParent.equals(this))
{
appendChild(node);
it.remove();
}
}
//let the children take their children
for (int i = 0; i < getChildCount(); i++)
((BoxNode) getChildAt(i)).takeChildren(list);
} | java | {
"resource": ""
} |
q170063 | AppLauncher.process | validation | protected void process(String command) {
try {
Method method = this.getClass().getMethod(command);
logger.info("Try to delegate '{}' to launcher directly.", command);
method.invoke(this);
logger.info("Invoke '{}' to launcher directly successfully. \r\n", command);
} catch (NoSuchMethodException e) {
logger.warn("unrecognized command: '{}'", command);
} catch (Exception e) {
logger.warn("Failed to execute: '{}'", command);
}
} | java | {
"resource": ""
} |
q170064 | Application.dataSource | validation | @Bean
public DataSource dataSource() {
// Replace this with your own datasource.
return new EmbeddedDatabaseBuilder()
.setName("test")
.setType(EmbeddedDatabaseType.HSQL)
.addScript("classpath:hsql-schema.sql")
.build();
} | java | {
"resource": ""
} |
q170065 | Application.dataSource_plain | validation | @Bean
public DataSource dataSource_plain() {
SimpleDriverDataSource ds =
new SimpleDriverDataSource();
ds.setDriverClass(null);
ds.setUrl("jdbc:oracle:thin:@<server>[:<1521>]:<database_name>");
ds.setUsername("");
ds.setPassword("");
return ds;
} | java | {
"resource": ""
} |
q170066 | DropwizardModule.setup | validation | public void setup(PlatformConfiguration config, Environment env) {
this.configuration = Preconditions.checkNotNull(config, "Configuration cannot be null.");
this.environment = Preconditions.checkNotNull(env, "Environment cannot be null.");
} | java | {
"resource": ""
} |
q170067 | OpenStates.query | validation | public <T> T query(MethodMap methodMap, ArgMap argMap, Class<T> responseType ) throws OpenStatesException {
BufferedReader reader = null;
HttpURLConnection conn = null;
String charSet = "utf-8";
try {
if ( isCaching(methodMap, argMap) ) {
File file = getCacheFile(methodMap, argMap);
long fileLength = file.length();
logger.fine("Length of File in cache:" + fileLength + ": " + file.getName());
if ( fileLength == 0L ) {
OpenStates.cacheFileFromAPI(methodMap, argMap, file, responseType);
}
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charSet));
} else {
conn = OpenStates.getConnectionFromAPI(methodMap, argMap);
charSet = getCharset(conn);
// better check it first
int rcode = conn.getResponseCode();
if ( rcode / 100 != 2) {
String msg = conn.getResponseMessage();
conn.disconnect();
throw new OpenStatesException(rcode, msg, methodMap, argMap, responseType);
}
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), charSet));
}
return mapper.readValue( reader, responseType );
} catch (JsonParseException e) {
throw new OpenStatesException(e, methodMap, argMap, responseType);
} catch (JsonMappingException e) {
throw new OpenStatesException(e, methodMap, argMap, responseType);
} catch (URISyntaxException e) {
throw new OpenStatesException(e, methodMap, argMap, responseType);
} catch (IOException e) {
throw new OpenStatesException(e, methodMap, argMap, responseType);
} finally {
suspendCache = false;
if ( conn != null ) conn.disconnect();
if ( reader != null ) {
try {
reader.close();
} catch (IOException e) {
throw new OpenStatesException(e, methodMap, argMap, responseType);
}
}
}
} | java | {
"resource": ""
} |
q170068 | Shell.register | validation | public void register(Command command) {
Preconditions.checkArgument(command != null, "Parameter 'command' must not be [" + command + "]");
register(command.name(), command);
} | java | {
"resource": ""
} |
q170069 | Shell.register | validation | public void register(String name, Command command) {
Preconditions.checkArgument(name != null && !name.isEmpty(), "Parameter 'name' must not be [" + name + "]");
Preconditions.checkArgument(command != null, "Parameter 'command' must not be [" + command + "]");
commands.put(name, command);
} | java | {
"resource": ""
} |
q170070 | Shell.unregister | validation | public void unregister(String name) {
Preconditions.checkArgument(name != null && !name.isEmpty(), "Parameter 'name' must not be [" + name + "]");
commands.remove(name);
} | java | {
"resource": ""
} |
q170071 | Shell.exec | validation | @SuppressWarnings("unchecked")
public void exec(String line) {
String[] strings = line.split("\\s");
if (strings.length == 0) {
return;
}
String cmd = strings[0];
if (strings[0] == null || strings[0].isEmpty()) {
return;
}
String[] args = {};
if (strings.length > 1) {
args = new String[strings.length - 1];
System.arraycopy(strings, 1, args, 0, args.length);
}
Command command = commands.get(cmd);
if (command == null) {
//$NON-NLS-N$
console.println(cmd + ": command not found");
return;
}
Usage usage = command.usage();
Options opts = options.get(command.name());
if (opts == null) {
opts = new Options();
for (Usage.Option option : usage.options()) {
Option opt = new Option(option.opt(), option.longOpt(), false, option.description());
opt.setRequired(option.required());
String arg = option.arg();
if (arg == null || arg.isEmpty()) {
opt.setArgs(1);
opt.setArgName(arg);
}
opts.addOption(opt);
}
options.put(command.name(), opts);
}
CommandLineParser parser = new GnuParser();
CommandLine commandLine = null;
try {
commandLine = parser.parse(opts, args);
} catch (ParseException e) {
console().println(usage.toString());
return;
}
Map<String, String> options = new HashMap<>();
for (Option option : commandLine.getOptions()) {
String opt = option.getOpt();
if (opt != null && !opt.isEmpty()) {
options.put(opt, option.getValue());
}
String longOpt = option.getLongOpt();
if (longOpt != null && !longOpt.isEmpty()) {
options.put(longOpt, option.getValue());
}
}
Line l = new Line(cmd, options, commandLine.getArgList());
try {
command.run(l);
} catch (Exception e) {
e.printStackTrace(new PrintWriter(console.reader().getOutput()));
}
} | java | {
"resource": ""
} |
q170072 | Shell.start | validation | public void start() {
repl.set(true);
String line = null;
while (repl.get() && ((line = console.readLine()) != null)) {
exec(line);
}
} | java | {
"resource": ""
} |
q170073 | CommitteeClass.searchByStateChamber | validation | public Committees searchByStateChamber(String state, String chamber) throws OpenStatesException {
return api.query(
new MethodMap("committees"),
new ArgMap("state", state, "chamber", chamber),
Committees.class
);
} | java | {
"resource": ""
} |
q170074 | CommitteeClass.detail | validation | public Committee detail(String id) throws OpenStatesException {
return api.query(new MethodMap("committees", id), null, Committee.class);
} | java | {
"resource": ""
} |
q170075 | RemoteMBeanInvocationHandler.connect | validation | private static JMXConnector connect(String host, String port, String login, String password) throws IOException {
// Set the service URL.
JMXServiceURL serviceUrl = new JMXServiceURL(
new StringBuffer()
.append("service:jmx:rmi://")
.append(host)
.append(":")
.append(port)
.append("/jndi/rmi://")
.append(host)
.append(":")
.append(port)
.append("/jmxrmi")
.toString());
// Set the service environment.
Map<String,Object> serviceEnv = new HashMap<String,Object>();
serviceEnv.put("jmx.remote.credentials", new String[]{login, password});
// Connect to the JMX service.
return JMXConnectorFactory.connect(serviceUrl, serviceEnv);
} | java | {
"resource": ""
} |
q170076 | RemoteMBeanInvocationHandler.getProperty | validation | private static String getProperty(Properties properties, String key) {
// Check if the properties do not exist.
if (properties == null || properties.getProperty(key) == null) {
throw new IllegalArgumentException("The property " + key + " does not exist.");
}
return properties.getProperty(key);
} | java | {
"resource": ""
} |
q170077 | RemoteMBeanInvocationHandler.invoke | validation | @Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result;
JMXConnector connector = null;
try {
// Connect to the JMX service.
connector = connect(this.host, this.port, this.login, this.password);
// Create the MBean.
T object = JMX.newMXBeanProxy(connector.getMBeanServerConnection(), this.objectName, this.interfaceClass);
// Invoke a method on the MBean.
result = method.invoke(object, args);
}
finally {
// Close the JMX service.
close(connector);
}
return result;
} | java | {
"resource": ""
} |
q170078 | DistrictClass.searchByState | validation | public Districts searchByState(String state) throws OpenStatesException {
return api.query(new MethodMap("districts", state), null, Districts.class);
} | java | {
"resource": ""
} |
q170079 | DistrictClass.search | validation | public Districts search(String state, String chamber) throws OpenStatesException {
return api.query(new MethodMap("districts", state, chamber), null, Districts.class);
} | java | {
"resource": ""
} |
q170080 | DistrictClass.boundaryLookup | validation | public District boundaryLookup(String boundary_id) throws OpenStatesException {
return api.query(new MethodMap("districts", "boundary", boundary_id ), null, District.class);
} | java | {
"resource": ""
} |
q170081 | MetadataClass.state | validation | public Metadata state(String state) throws OpenStatesException {
return api.query(new MethodMap("metadata", state), null, Metadata.class);
} | java | {
"resource": ""
} |
q170082 | MBeanUtility.createObject | validation | private static <T> T createObject(Class<T> interfaceClass) {
ServiceLoader<T> loader = ServiceLoader.load(interfaceClass);
T object = null;
// Loop through the services.
for (T loadedObject : loader) {
// Check if a factory has not been found.
if (object == null) {
// Set the factory.
object = loadedObject;
} else {
throw new IllegalArgumentException("More than one MBean object found.");
}
}
// Check if a object has not been found.
if (object == null) {
throw new IllegalArgumentException("No MBean object found.");
}
return object;
} | java | {
"resource": ""
} |
q170083 | MBeanUtility.register | validation | public static <T> ObjectName register(Class<T> interfaceClass, ObjectName objectName) throws MBeanException {
// Check if the interface class is valid.
if (interfaceClass == null) {
throw new IllegalArgumentException("The interface class is invalid.");
}
try {
// Get the MBean server.
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
// Check if the MBean is not registered with the MBean server.
if (!mBeanServer.isRegistered(objectName)) {
// Register the MBean with the MBean server.
ObjectInstance objectInstance = mBeanServer.registerMBean(createObject(interfaceClass), objectName);
// Get the object name for the registered MBean.
objectName = objectInstance.getObjectName();
}
} catch (Exception e) {
throw new MBeanException(e, "Unable to register the MBean.");
}
return objectName;
} | java | {
"resource": ""
} |
q170084 | MBeanUtility.unregister | validation | public static void unregister(ObjectName objectName) throws MBeanException {
try {
// Get the MBean server.
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
// Check if the MBean is registered with the MBean server.
if (mBeanServer.isRegistered(objectName)) {
// Unregister the MBean with the MBean server.
mBeanServer.unregisterMBean(objectName);
}
} catch (Exception e) {
throw new MBeanException(e,
"Unable to unregister the MBean " +
objectName.getCanonicalName() + ".");
}
} | java | {
"resource": ""
} |
q170085 | MBeanUtility.validateMBean | validation | protected static void validateMBean(Class interfaceClass, ObjectName objectName, MBeanServerConnection mBeanServerConnection) throws MBeanException {
try {
// Check if the interface class is null.
if (interfaceClass == null) {
throw new IllegalArgumentException(
"The interface class is null.");
}
// Check if the interface class is not a MXBean interface.
if (!JMX.isMXBeanInterface(interfaceClass)) {
throw new IllegalArgumentException(
"The interface class " + interfaceClass.getName() +
" is not a MXBean interface.");
}
// Check if the object name is not registered.
if (!mBeanServerConnection.isRegistered(objectName)) {
throw new IllegalArgumentException(
"The object name " + objectName.getCanonicalName() +
" is not registered.");
}
// Check if the object name is not an instance of the interface class.
if (!mBeanServerConnection.isInstanceOf(objectName, interfaceClass.getName())) {
throw new IllegalArgumentException(
"The object name " + objectName.getCanonicalName() +
" is not an instance of the interface class " +
interfaceClass.getName() + ".");
}
} catch (InstanceNotFoundException e) {
throw new IllegalArgumentException(
"The object name " + objectName.getCanonicalName() +
" is not found.");
} catch (IOException e) {
throw new MBeanException(e,
"Unable to validate the MBean represented by the interface class " +
interfaceClass.getName() + " and object name " +
objectName.getCanonicalName() + ".");
}
} | java | {
"resource": ""
} |
q170086 | UUIDPathMinter.get | validation | @Override
public String get() {
try (final Timer.Context context = timer.time()) {
final String s = randomUUID().toString();
if (length == 0 || count == 0) {
return s;
}
final StringJoiner joiner = new StringJoiner("/", "", "/" + s);
IntStream.rangeClosed(0, count - 1)
.forEach(x -> joiner.add(s.substring(x * length, (x + 1) * length)));
return joiner.toString();
}
} | java | {
"resource": ""
} |
q170087 | ParameterDescription.addValue | validation | public void addValue(String value, boolean isDefault) {
p("Adding " + (isDefault ? "default " : "") + "value:" + value + " to parameter:" + m_field.getName());
String name = m_wrappedParameter.names()[0];
if (m_assigned && !isMultiOption()) {
throw new ParameterException("Can only specify option " + name + " once.");
}
validateParameter(name, value);
Class<?> type = m_field.getType();
Object convertedValue = m_jCommander.convertValue(this, value);
boolean isCollection = Collection.class.isAssignableFrom(type);
try {
if (isCollection) {
@SuppressWarnings("unchecked") Collection<Object> l = (Collection<Object>) m_field.get(m_object);
if (l == null || fieldIsSetForTheFirstTime(isDefault)) {
l = newCollection(type);
m_field.set(m_object, l);
}
if (convertedValue instanceof Collection) {
l.addAll((Collection) convertedValue);
} else { // if (isMainParameter || m_parameterAnnotation.arity() > 1) {
l.add(convertedValue);
// } else {
// l.
}
} else {
m_wrappedParameter.addValue(m_field, m_object, convertedValue);
}
if (!isDefault) m_assigned = true;
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}
} | java | {
"resource": ""
} |
q170088 | LegislatorClass.searchByState | validation | public Legislators searchByState(
String state
) throws OpenStatesException {
return api.query(
new MethodMap("legislators"),
new ArgMap( "state", state ),
Legislators.class
);
} | java | {
"resource": ""
} |
q170089 | LegislatorClass.searchByStateActive | validation | public Legislators searchByStateActive(
String state,
Boolean active
) throws OpenStatesException {
return api.query(
new MethodMap("legislators"),
new ArgMap(
"state", state,
"active", active.toString()
),
Legislators.class
);
} | java | {
"resource": ""
} |
q170090 | LegislatorClass.searchByStateTerm | validation | public Legislators searchByStateTerm(
String state,
String term
) throws OpenStatesException {
return api.query(
new MethodMap("legislators"),
new ArgMap(
"state", state,
"term", term
),
Legislators.class
);
} | java | {
"resource": ""
} |
q170091 | LegislatorClass.search | validation | public Legislators search(
String state,
Boolean active,
String term,
String chamber,
String district,
String party,
String first_name,
String last_name
) throws OpenStatesException {
return api.query(
new MethodMap("legislators"),
new ArgMap(
"state", state,
"first_name", first_name,
"last_name", last_name,
"chamber", chamber,
"active", active==null?null:active.toString(),
"term", term,
"party", party,
"district", district
),
Legislators.class
);
} | java | {
"resource": ""
} |
q170092 | LegislatorClass.detail | validation | public Legislator detail(String id) throws OpenStatesException {
return api.query(new MethodMap("legislators", id), null, Legislator.class);
} | java | {
"resource": ""
} |
q170093 | TypesafeEnum.compareTo | validation | public int compareTo(E o) {
if (o.getClass() != getClass()) {
throw new ClassCastException();
}
return ordinal - TypesafeEnum.class.cast(o).ordinal;
} | java | {
"resource": ""
} |
q170094 | DtoRowMapper.setMappedClass | validation | public void setMappedClass(Class<T> mappedClass) {
if (this.mappedClass == null) {
initialize(mappedClass);
}
else {
if (!this.mappedClass.equals(mappedClass)) {
throw new InvalidDataAccessApiUsageException("The mapped class can not be reassigned to map to " +
mappedClass + " since it is already providing mapping for " + this.mappedClass);
}
}
} | java | {
"resource": ""
} |
q170095 | MethodInvocation.proceed | validation | @SuppressWarnings("unchecked")
public R proceed() throws Throwable {
try {
return (R) method().invoke(target, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
} | java | {
"resource": ""
} |
q170096 | Stopwatch.stop | validation | public long stop() {
if (isRunning()) {
stop = System.nanoTime();
total += stop - start;
running = false;
}
return Math.round(total * getPrecision().value);
} | java | {
"resource": ""
} |
q170097 | HttpPidMinter.buildClient | validation | protected HttpClient buildClient() {
HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties().setConnectionManager(connManager);
if (!isBlank(username) && !isBlank(password)) {
final URI uri = URI.create(url);
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
new UsernamePasswordCredentials(username, password));
builder = builder.setDefaultCredentialsProvider(credsProvider);
}
return builder.build();
} | java | {
"resource": ""
} |
q170098 | HttpPidMinter.minterRequest | validation | private HttpUriRequest minterRequest() {
switch (method.toUpperCase()) {
case "GET":
return new HttpGet(url);
case "PUT":
return new HttpPut(url);
default:
return new HttpPost(url);
}
} | java | {
"resource": ""
} |
q170099 | HttpPidMinter.responseToPid | validation | protected String responseToPid( final String responseText ) throws IOException {
LOGGER.debug("responseToPid({})", responseText);
if ( !isBlank(regex) ) {
return responseText.replaceFirst(regex,"");
} else if ( xpath != null ) {
try {
return xpath( responseText, xpath );
} catch (ParserConfigurationException | SAXException | XPathExpressionException e) {
throw new IOException(e);
}
} else {
return responseText;
}
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.