_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q16000
XMLHolidayManager._createConfigurationHierarchy
train
@Nonnull private static CalendarHierarchy _createConfigurationHierarchy (@Nonnull final Configuration aConfig, @Nullable final CalendarHierarchy aParent) { final ECountry eCountry = ECountry.getFromIDOrNull (aConfig.getHierarchy ()); final CalendarHierarchy aHierarchy = new CalendarHierarchy (aParent, aConfig.getHierarchy (), eCountry); for (final Configuration aSubConfig : aConfig.getSubConfigurations ()) { final CalendarHierarchy aSubHierarchy = _createConfigurationHierarchy (aSubConfig, aHierarchy); aHierarchy.addChild (aSubHierarchy); } return aHierarchy; }
java
{ "resource": "" }
q16001
JdbcSupplier.setDbType
train
public static void setDbType(JdbcDialect dialect, String key, String type) { Properties props = getTypesProps(dialect); props.setProperty(key, type); }
java
{ "resource": "" }
q16002
EthiopianOrthodoxHolidayParser._getEthiopianOrthodoxHolidaysInGregorianYear
train
private static ICommonsSet <LocalDate> _getEthiopianOrthodoxHolidaysInGregorianYear (final int nGregorianYear, final int nEOMonth, final int nEODay) { return CalendarHelper.getDatesFromChronologyWithinGregorianYear (nEOMonth, nEODay, nGregorianYear, CopticChronology.INSTANCE); }
java
{ "resource": "" }
q16003
XMLResultsParser.parse
train
@Override public Result parse(Command cmd, InputStream input, ResultType type) { return parseResults(cmd, input, type); }
java
{ "resource": "" }
q16004
XMLResultsParser.parseResults
train
public static Result parseResults(Command cmd, InputStream input, ResultType type) throws SparqlException { try { return createResults(cmd, input, type); } catch (Throwable t) { logger.debug("Error parsing results from stream, cleaning up."); try { input.close(); } catch (IOException e) { logger.warn("Error closing input stream from failed protocol response", e); } throw SparqlException.convert("Error parsing SPARQL protocol results from stream", t); } }
java
{ "resource": "" }
q16005
XMLResultsParser.createResults
train
private static Result createResults(Command cmd, InputStream stream, ResultType type) throws SparqlException { XMLInputFactory xmlStreamFactory = XMLInputFactory.newInstance(); // Tell the factory to combine adjacent character blocks into a single event, so we don't have to do it ourselves. xmlStreamFactory.setProperty(XMLInputFactory.IS_COALESCING, true); // Tell the factory to create a reader that will close the underlying stream when done. xmlStreamFactory.setProperty(XMLInputFactory2.P_AUTO_CLOSE_INPUT, true); XMLStreamReader rdr; try { rdr = xmlStreamFactory.createXMLStreamReader(stream, "UTF-8"); } catch (XMLStreamException e) { throw new SparqlException("Unable to open XML data", e); } List<String> cols = new ArrayList<String>(); List<String> md = new ArrayList<String>(); try { if (rdr.nextTag() != START_ELEMENT || !nameIs(rdr, SPARQL)) { throw new SparqlException("Result is not a SPARQL XML result document"); } // Initialize the base URI to the String base = null; if (cmd != null) { base = ((ProtocolDataSource)cmd.getConnection().getDataSource()).getUrl().toString(); } // read the header information parseHeader(base, rdr, cols, md); // move the cursor into the results, and read in the first row if (rdr.nextTag() != START_ELEMENT) throw new SparqlException("No body to result document"); String typeName = rdr.getLocalName(); if (typeName.equalsIgnoreCase(RESULTS.toString())) { if (type != null && type != ResultType.SELECT) { throw new SparqlException("Unexpected result type; expected " + type + " but found SELECT."); } return new XMLSelectResults(cmd, rdr, cols, md); } if (typeName.equalsIgnoreCase(BOOLEAN.toString())) { if (type != null && type != ResultType.ASK) { throw new SparqlException("Unexpected result type; expected " + type + " but found ASK."); } if (!cols.isEmpty()) { logger.warn("Boolean result contained column definitions in head: {}", cols); } return parseBooleanResult(cmd, rdr, md); } throw new SparqlException("Unknown element type in result document. Expected <results> or <boolean> but got <" + typeName + ">"); } catch (XMLStreamException e) { throw new SparqlException("Error reading the XML stream", e); } }
java
{ "resource": "" }
q16006
XMLResultsParser.parseHeader
train
static private void parseHeader(String base, XMLStreamReader rdr, List<String> cols, List<String> md) throws XMLStreamException, SparqlException { logger.debug("xml:base is initially {}", base); base = getBase(base, rdr); testOpen(rdr, rdr.nextTag(), HEAD, "Missing header from XML results"); base = getBase(base, rdr); boolean endedVars = false; int eventType; while ((eventType = rdr.nextTag()) != END_ELEMENT || !nameIs(rdr, HEAD)) { if (eventType == START_ELEMENT) { if (nameIs(rdr, VARIABLE)) { if (endedVars) throw new SparqlException("Encountered a variable after header metadata"); String var = rdr.getAttributeValue(null, "name"); if (var != null) cols.add(var); else logger.warn("<variable> element without 'name' attribute"); } else if (nameIs(rdr, LINK)) { String b = getBase(base, rdr); // Copy to a new var since we're looping. String href = rdr.getAttributeValue(null, HREF); if (href != null) md.add(resolve(b, href)); else logger.warn("<link> element without 'href' attribute"); endedVars = true; } } } // ending on </head>. next() should be <results> or <boolean> testClose(rdr, eventType, HEAD, "Unexpected element in header: " + rdr.getLocalName()); }
java
{ "resource": "" }
q16007
XMLResultsParser.nameIs
train
static final boolean nameIs(XMLStreamReader rdr, Element elt) { return rdr.getLocalName().equalsIgnoreCase(elt.name()); }
java
{ "resource": "" }
q16008
ThreadUtil.runOnUiThread
train
public static void runOnUiThread(@NonNull final Runnable runnable) { Condition.INSTANCE.ensureNotNull(runnable, "The runnable may not be null"); new Handler(Looper.getMainLooper()).post(runnable); }
java
{ "resource": "" }
q16009
AbstractDataBinder.notifyOnLoad
train
@SafeVarargs private final boolean notifyOnLoad(@NonNull final KeyType key, @NonNull final ParamType... params) { boolean result = true; for (Listener<DataType, KeyType, ViewType, ParamType> listener : listeners) { result &= listener.onLoadData(this, key, params); } return result; }
java
{ "resource": "" }
q16010
AbstractDataBinder.notifyOnFinished
train
@SafeVarargs private final void notifyOnFinished(@NonNull final KeyType key, @Nullable final DataType data, @NonNull final ViewType view, @NonNull final ParamType... params) { for (Listener<DataType, KeyType, ViewType, ParamType> listener : listeners) { listener.onFinished(this, key, data, view, params); } }
java
{ "resource": "" }
q16011
AbstractDataBinder.notifyOnCanceled
train
private void notifyOnCanceled() { for (Listener<DataType, KeyType, ViewType, ParamType> listener : listeners) { listener.onCanceled(this); } }
java
{ "resource": "" }
q16012
AbstractDataBinder.getCachedData
train
@Nullable private DataType getCachedData(@NonNull final KeyType key) { synchronized (cache) { return cache.get(key); } }
java
{ "resource": "" }
q16013
AbstractDataBinder.cacheData
train
private void cacheData(@NonNull final KeyType key, @NonNull final DataType data) { synchronized (cache) { if (useCache) { cache.put(key, data); } } }
java
{ "resource": "" }
q16014
AbstractDataBinder.loadDataAsynchronously
train
private void loadDataAsynchronously( @NonNull final Task<DataType, KeyType, ViewType, ParamType> task) { threadPool.submit(new Runnable() { @Override public void run() { if (!isCanceled()) { while (!notifyOnLoad(task.key, task.params)) { try { Thread.sleep(100); } catch (InterruptedException e) { break; } } task.result = loadData(task); Message message = Message.obtain(); message.obj = task; sendMessage(message); } } }); }
java
{ "resource": "" }
q16015
AbstractDataBinder.loadData
train
@Nullable private DataType loadData(@NonNull final Task<DataType, KeyType, ViewType, ParamType> task) { try { DataType data = doInBackground(task.key, task.params); if (data != null) { cacheData(task.key, data); } logger.logInfo(getClass(), "Loaded data with key " + task.key); return data; } catch (Exception e) { logger.logError(getClass(), "An error occurred while loading data with key " + task.key, e); return null; } }
java
{ "resource": "" }
q16016
AbstractDataBinder.addListener
train
public final void addListener( @NonNull final Listener<DataType, KeyType, ViewType, ParamType> listener) { listeners.add(listener); }
java
{ "resource": "" }
q16017
AbstractDataBinder.removeListener
train
public final void removeListener( @NonNull final Listener<DataType, KeyType, ViewType, ParamType> listener) { listeners.remove(listener); }
java
{ "resource": "" }
q16018
AbstractDataBinder.load
train
@SafeVarargs public final void load(@NonNull final KeyType key, @NonNull final ViewType view, @NonNull final ParamType... params) { load(key, view, true, params); }
java
{ "resource": "" }
q16019
AbstractDataBinder.load
train
@SafeVarargs public final void load(@NonNull final KeyType key, @NonNull final ViewType view, final boolean async, @NonNull final ParamType... params) { Condition.INSTANCE.ensureNotNull(key, "The key may not be null"); Condition.INSTANCE.ensureNotNull(view, "The view may not be null"); Condition.INSTANCE.ensureNotNull(params, "The array may not be null"); setCanceled(false); views.put(view, key); DataType data = getCachedData(key); if (!isCanceled()) { if (data != null) { onPostExecute(view, data, 0, params); notifyOnFinished(key, data, view, params); logger.logInfo(getClass(), "Loaded data with key " + key + " from cache"); } else { onPreExecute(view, params); Task<DataType, KeyType, ViewType, ParamType> task = new Task<>(view, key, params); if (async) { loadDataAsynchronously(task); } else { data = loadData(task); onPostExecute(view, data, 0, params); notifyOnFinished(key, data, view, params); } } } }
java
{ "resource": "" }
q16020
AbstractDataBinder.isCached
train
public final boolean isCached(@NonNull final KeyType key) { Condition.INSTANCE.ensureNotNull(key, "The key may not be null"); synchronized (cache) { return cache.get(key) != null; } }
java
{ "resource": "" }
q16021
AbstractDataBinder.useCache
train
public final void useCache(final boolean useCache) { synchronized (cache) { this.useCache = useCache; logger.logDebug(getClass(), useCache ? "Enabled" : "Disabled" + " caching"); if (!useCache) { clearCache(); } } }
java
{ "resource": "" }
q16022
NameDbUsa.profile
train
private static void profile(Task task, String message, int tries) { for (int i = 0; i < tries; i++) { long start = System.nanoTime(); task.run(); long finish = System.nanoTime(); System.out.println( String.format("[Try %d] %-30s: %-5.2fms", i + 1, message, (finish - start) / 1000000.0) ); } }
java
{ "resource": "" }
q16023
ElevationShadowView.obtainShadowElevation
train
private void obtainShadowElevation(@NonNull final TypedArray typedArray) { int defaultValue = getResources().getDimensionPixelSize( R.dimen.elevation_shadow_view_shadow_elevation_default_value); elevation = pixelsToDp(getContext(), typedArray .getDimensionPixelSize(R.styleable.ElevationShadowView_shadowElevation, defaultValue)); }
java
{ "resource": "" }
q16024
ElevationShadowView.obtainShadowOrientation
train
private void obtainShadowOrientation(@NonNull final TypedArray typedArray) { int defaultValue = getResources() .getInteger(R.integer.elevation_shadow_view_shadow_orientation_default_value); orientation = Orientation.fromValue(typedArray .getInteger(R.styleable.ElevationShadowView_shadowOrientation, defaultValue)); }
java
{ "resource": "" }
q16025
ElevationShadowView.obtainEmulateParallelLight
train
private void obtainEmulateParallelLight(@NonNull final TypedArray typedArray) { boolean defaultValue = getResources() .getBoolean(R.bool.elevation_shadow_view_emulate_parallel_light_default_value); emulateParallelLight = typedArray .getBoolean(R.styleable.ElevationShadowView_emulateParallelLight, defaultValue); }
java
{ "resource": "" }
q16026
ElevationShadowView.adaptElevationShadow
train
private void adaptElevationShadow() { setImageBitmap( createElevationShadow(getContext(), elevation, orientation, emulateParallelLight)); setScaleType(orientation == Orientation.LEFT || orientation == Orientation.TOP || orientation == Orientation.RIGHT || orientation == Orientation.BOTTOM ? ScaleType.FIT_XY : ScaleType.FIT_CENTER); }
java
{ "resource": "" }
q16027
ElevationShadowView.setShadowElevation
train
public final void setShadowElevation(final int elevation) { Condition.INSTANCE.ensureAtLeast(elevation, 0, "The elevation must be at least 0"); Condition.INSTANCE.ensureAtMaximum(elevation, ElevationUtil.MAX_ELEVATION, "The elevation must be at maximum " + ElevationUtil.MAX_ELEVATION); this.elevation = elevation; adaptElevationShadow(); }
java
{ "resource": "" }
q16028
ElevationShadowView.setShadowOrientation
train
public final void setShadowOrientation(@NonNull final Orientation orientation) { Condition.INSTANCE.ensureNotNull(orientation, "The orientation may not be null"); this.orientation = orientation; adaptElevationShadow(); }
java
{ "resource": "" }
q16029
DefaultErrorHandler.hasError
train
@Override public boolean hasError(Response<ByteSource> rs) { StatusType statusType = StatusType.valueOf(rs.getStatus()); return (statusType == StatusType.CLIENT_ERROR || statusType == StatusType.SERVER_ERROR); }
java
{ "resource": "" }
q16030
DefaultErrorHandler.handleError
train
protected void handleError(URI requestUri, HttpMethod requestMethod, int statusCode, String statusMessage, ByteSource errorBody) throws RestEndpointIOException { throw new RestEndpointException(requestUri, requestMethod, statusCode, statusMessage, errorBody); }
java
{ "resource": "" }
q16031
Duzzt.init
train
public void init(APUtils utils) throws DuzztInitializationException { URL url = GenerateEDSLProcessor.class.getResource(ST_RESOURCE_NAME); this.sourceGenGroup = new STGroupFile( url, ST_ENCODING, ST_DELIM_START_CHAR, ST_DELIM_STOP_CHAR); sourceGenGroup.setListener(new ReporterDiagnosticListener(utils.getReporter())); sourceGenGroup.load(); if(!sourceGenGroup.isDefined(ST_MAIN_TEMPLATE_NAME)) { sourceGenGroup = null; throw new DuzztInitializationException("Could not find main template '" + ST_MAIN_TEMPLATE_NAME + "' in template group file " + url.toString()); } this.isJava9OrNewer = isJava9OrNewer(utils.getProcessingEnv().getSourceVersion()); }
java
{ "resource": "" }
q16032
Duzzt.process
train
public void process(Element elem, GenerateEmbeddedDSL annotation, Elements elementUtils, Types typeUtils, Filer filer, Reporter reporter) throws IOException { if(!ElementUtils.checkElementKind(elem, ElementKind.CLASS, ElementKind.INTERFACE)) { throw new IllegalArgumentException("Annotation " + GenerateEmbeddedDSL.class.getSimpleName() + " can only be used on class or interface declarations!"); } TypeElement te = (TypeElement)elem; ReporterDiagnosticListener dl = new ReporterDiagnosticListener(reporter); DSLSettings settings = new DSLSettings(annotation); DSLSpecification spec = DSLSpecification.create(te, settings, elementUtils, typeUtils); BricsCompiler compiler = new BricsCompiler(spec.getImplementation()); DuzztAutomaton automaton = compiler.compile(spec.getDSLSyntax(), spec.getSubExpressions()); // Make sure classes have same name if generated twice from the same spec automaton.reassignStateIds(typeUtils); render(spec, automaton, filer, dl); }
java
{ "resource": "" }
q16033
PermissionUtil.isPermissionGranted
train
public static boolean isPermissionGranted(@NonNull final Context context, @NonNull final String permission) { Condition.INSTANCE.ensureNotNull(context, "The context may not be null"); Condition.INSTANCE.ensureNotNull(permission, "The permission may not be null"); Condition.INSTANCE.ensureNotEmpty(permission, "The permission may not be empty"); return Build.VERSION.SDK_INT < Build.VERSION_CODES.M || ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED; }
java
{ "resource": "" }
q16034
PermissionUtil.areAllPermissionsGranted
train
public static boolean areAllPermissionsGranted(@NonNull final Context context, @NonNull final String... permissions) { Condition.INSTANCE.ensureNotNull(context, "The context may not be null"); Condition.INSTANCE.ensureNotNull(permissions, "The array may not be null"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { for (String permission : permissions) { if (!isPermissionGranted(context, permission)) { return false; } } } return true; }
java
{ "resource": "" }
q16035
PermissionUtil.getNotGrantedPermissions
train
@NonNull public static String[] getNotGrantedPermissions(@NonNull final Context context, @NonNull final String... permissions) { Condition.INSTANCE.ensureNotNull(permissions, "The array may not be null"); Collection<String> notGrantedPermissions = new LinkedList<>(); for (String permission : permissions) { if (!isPermissionGranted(context, permission)) { notGrantedPermissions.add(permission); } } String[] result = new String[notGrantedPermissions.size()]; notGrantedPermissions.toArray(result); return result; }
java
{ "resource": "" }
q16036
ObjectDAO.findByDate
train
private List<O> findByDate(String dateField, Date start, Date end, int numObjects, boolean asc) { if (start == null) start = new Date(0); if (end == null) end = new Date(); return getDatastore().find(clazz).filter(dateField + " >", start).filter(dateField + " <", end).order(asc ? dateField : '-' + dateField).limit(numObjects).asList(); }
java
{ "resource": "" }
q16037
ObjectDAO.createdInPeriod
train
public List<O> createdInPeriod(Date start, Date end, int numObjects) { return findByDate("creationDate", start, end, numObjects, true); }
java
{ "resource": "" }
q16038
ObjectDAO.similar
train
public List<Similarity> similar(Image object, double threshold) { //return getDatastore().find(Similarity.class).field("firstObject").equal(object).order("similarityScore").asList(); Query<Similarity> q = getDatastore().createQuery(Similarity.class); q.or( q.criteria("firstObject").equal(object), q.criteria("secondObject").equal(object) ); return q.order("-similarityScore").filter("similarityScore >", threshold).asList(); }
java
{ "resource": "" }
q16039
WorkerDao.createZookeeperBase
train
public void createZookeeperBase() throws WorkerDaoException { createPersistentEmptyNodeIfNotExist(BASE_ZK); createPersistentEmptyNodeIfNotExist(WORKERS_ZK); createPersistentEmptyNodeIfNotExist(PLANS_ZK); createPersistentEmptyNodeIfNotExist(SAVED_ZK); createPersistentEmptyNodeIfNotExist(LOCKS_ZK); createPersistentEmptyNodeIfNotExist(PLAN_WORKERS_ZK); }
java
{ "resource": "" }
q16040
WorkerDao.findWorkersWorkingOnPlan
train
public List<String> findWorkersWorkingOnPlan(Plan plan) throws WorkerDaoException{ try { Stat exists = framework.getCuratorFramework().checkExists().forPath(PLAN_WORKERS_ZK + "/" + plan.getName()); if (exists == null ){ return new ArrayList<String>(); } return framework.getCuratorFramework().getChildren().forPath(PLAN_WORKERS_ZK + "/" + plan.getName()); } catch (Exception e) { throw new WorkerDaoException(e); } }
java
{ "resource": "" }
q16041
WorkerDao.findPlanByName
train
public Plan findPlanByName(String name) throws WorkerDaoException { Stat planStat; byte[] planBytes; try { planStat = framework.getCuratorFramework().checkExists().forPath(PLANS_ZK + "/" + name); if (planStat == null) { return null; } planBytes = framework.getCuratorFramework().getData().forPath(PLANS_ZK + "/" + name); } catch (Exception e) { LOGGER.warn(e); throw new WorkerDaoException(e); } Plan p = null; try { p = deserializePlan(planBytes); } catch (JsonParseException | JsonMappingException e) { LOGGER.warn("while parsing plan " + name, e); } catch (IOException e) { LOGGER.warn("while parsing plan " + name, e); } return p; }
java
{ "resource": "" }
q16042
WorkerDao.createOrUpdatePlan
train
public void createOrUpdatePlan(Plan plan) throws WorkerDaoException { try { createZookeeperBase(); Stat s = this.framework.getCuratorFramework().checkExists().forPath(PLANS_ZK + "/" + plan.getName()); if (s != null) { framework.getCuratorFramework().setData().withVersion(s.getVersion()) .forPath(PLANS_ZK + "/" + plan.getName(), serializePlan(plan)); } else { framework.getCuratorFramework().create().withMode(CreateMode.PERSISTENT) .withACL(Ids.OPEN_ACL_UNSAFE) .forPath(PLANS_ZK + "/" + plan.getName(), serializePlan(plan)); } } catch (Exception e) { LOGGER.warn(e); throw new WorkerDaoException(e); } }
java
{ "resource": "" }
q16043
WorkerDao.createEphemeralNodeForDaemon
train
public void createEphemeralNodeForDaemon(TeknekDaemon d) throws WorkerDaoException { try { byte [] hostbytes = d.getHostname().getBytes(ENCODING); framework.getCuratorFramework().create() .withMode(CreateMode.EPHEMERAL).withACL(Ids.OPEN_ACL_UNSAFE).forPath(WORKERS_ZK + "/" + d.getMyId(), hostbytes); } catch (Exception e) { LOGGER.warn(e); throw new WorkerDaoException(e); } }
java
{ "resource": "" }
q16044
WorkerDao.findAllWorkerStatusForPlan
train
public List<WorkerStatus> findAllWorkerStatusForPlan(Plan plan, List<String> otherWorkers) throws WorkerDaoException{ List<WorkerStatus> results = new ArrayList<WorkerStatus>(); try { Stat preCheck = framework.getCuratorFramework().checkExists().forPath(PLAN_WORKERS_ZK + "/" + plan.getName()); if (preCheck == null){ return results; } } catch (Exception e1) { LOGGER.warn(e1); throw new WorkerDaoException(e1); } for (String worker : otherWorkers) { String lookAtPath = PLAN_WORKERS_ZK + "/" + plan.getName() + "/" + worker; try { Stat stat = framework.getCuratorFramework().checkExists().forPath(lookAtPath); byte[] data = framework.getCuratorFramework().getData().storingStatIn(stat).forPath(lookAtPath); results.add(MAPPER.readValue(data, WorkerStatus.class)); } catch (Exception e) { LOGGER.warn(e); throw new WorkerDaoException(e); } } return results; }
java
{ "resource": "" }
q16045
WorkerDao.registerWorkerStatus
train
public void registerWorkerStatus(ZooKeeper zk, Plan plan, WorkerStatus s) throws WorkerDaoException{ String writeToPath = PLAN_WORKERS_ZK + "/" + plan.getName() + "/" + s.getWorkerUuid(); try { Stat planBase = zk.exists(PLAN_WORKERS_ZK + "/" + plan.getName(), false); if (planBase == null){ try { zk.create(PLAN_WORKERS_ZK + "/" + plan.getName(), new byte [0] , Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } catch (Exception ignore){} } zk.create(writeToPath, MAPPER.writeValueAsBytes(s), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); LOGGER.debug("Registered as ephemeral " + writeToPath); zk.exists(PLANS_ZK + "/" + plan.getName(), true); //watch job for events } catch (KeeperException | InterruptedException | IOException e) { LOGGER.warn(e); throw new WorkerDaoException(e); } }
java
{ "resource": "" }
q16046
WorkerDao.deletePlan
train
public void deletePlan(Plan p) throws WorkerDaoException { String planNode = PLANS_ZK + "/" + p.getName(); try { Stat s = framework.getCuratorFramework().checkExists().forPath(planNode); framework.getCuratorFramework().delete().withVersion(s.getVersion()).forPath(planNode); } catch (Exception e) { throw new WorkerDaoException(e); } }
java
{ "resource": "" }
q16047
ArrayUtil.indexOf
train
public static int indexOf(@NonNull final boolean[] array, final boolean value) { Condition.INSTANCE.ensureNotNull(array, "The array may not be null"); for (int i = 0; i < array.length; i++) { if (array[i] == value) { return i; } } return -1; }
java
{ "resource": "" }
q16048
AbstractViewRecycler.addUnusedView
train
protected final void addUnusedView(@NonNull final View view, final int viewType) { if (useCache) { if (unusedViews == null) { unusedViews = new SparseArray<>(adapter.getViewTypeCount()); } Queue<View> queue = unusedViews.get(viewType); if (queue == null) { queue = new LinkedList<>(); unusedViews.put(viewType, queue); } queue.add(view); } }
java
{ "resource": "" }
q16049
AbstractViewRecycler.pollUnusedView
train
@Nullable protected final View pollUnusedView(final int viewType) { if (useCache && unusedViews != null) { Queue<View> queue = unusedViews.get(viewType); if (queue != null) { return queue.poll(); } } return null; }
java
{ "resource": "" }
q16050
AbstractViewRecycler.getView
train
@Nullable public final View getView(@NonNull final ItemType item) { Condition.INSTANCE.ensureNotNull(item, "The item may not be null"); return activeViews.get(item); }
java
{ "resource": "" }
q16051
AbstractViewRecycler.clearCache
train
public final void clearCache() { if (unusedViews != null) { unusedViews.clear(); unusedViews = null; } logger.logDebug(getClass(), "Removed all unused views from cache"); }
java
{ "resource": "" }
q16052
AbstractViewRecycler.clearCache
train
public final void clearCache(final int viewType) { if (unusedViews != null) { unusedViews.remove(viewType); } logger.logDebug(getClass(), "Removed all unused views of view type " + viewType + " from cache"); }
java
{ "resource": "" }
q16053
Worker.init
train
public void init(){ try { zk = new ZooKeeper(parent.getProperties().get(TeknekDaemon.ZK_SERVER_LIST).toString(), 30000, this); } catch (IOException e1) { throw new RuntimeException(e1); } Feed feed = DriverFactory.buildFeed(plan.getFeedDesc()); List<WorkerStatus> workerStatus; try { workerStatus = parent.getWorkerDao().findAllWorkerStatusForPlan(plan, otherWorkers); } catch (WorkerDaoException e1) { throw new RuntimeException(e1); } if (workerStatus.size() >= feed.getFeedPartitions().size()){ throw new RuntimeException("Number of running workers " + workerStatus.size()+" >= feed partitions " + feed.getFeedPartitions().size() +" plan should be fixed " +plan.getName()); } FeedPartition toProcess = findPartitionToProcess(workerStatus, feed.getFeedPartitions()); if (toProcess != null){ driver = DriverFactory.createDriver(toProcess, plan, parent.getMetricRegistry()); driver.initialize(); WorkerStatus iGotThis = new WorkerStatus(myId.toString(), toProcess.getPartitionId() , parent.getMyId()); try { parent.getWorkerDao().registerWorkerStatus(zk, plan, iGotThis); } catch (WorkerDaoException e) { throw new RuntimeException(e); } } else { throw new RuntimeException("Could not start plan "+plan.getName()); } }
java
{ "resource": "" }
q16054
Worker.shutdown
train
private void shutdown(){ parent.workerThreads.get(plan).remove(this); if (zk != null) { try { logger.debug("closing " + zk.getSessionId()); zk.close(); zk = null; } catch (InterruptedException e1) { logger.debug(e1); } logger.debug("shutdown complete"); } }
java
{ "resource": "" }
q16055
CalendarHierarchy.getDescription
train
@Nonnull public String getDescription (final Locale aContentLocale) { final String ret = m_eCountry == null ? null : m_eCountry.getDisplayText (aContentLocale); return ret != null ? ret : "undefined"; }
java
{ "resource": "" }
q16056
SHPSolutions.toNode
train
private static RDFNode toNode(Object value) { if (value == null) { return null; } else if (value instanceof RDFNode) { return (RDFNode) value; } else if (value instanceof IRI) { return new NamedNodeImpl(URI.create(((IRI)value).iri.toString())); } else if (value instanceof PlainLiteral) { PlainLiteral pl = (PlainLiteral)value; String lang = pl.language != null ? pl.language.toString() : null; return new PlainLiteralImpl(pl.lexical.toString(), lang); } else if (value instanceof TypedLiteral) { TypedLiteral tl = (TypedLiteral)value; return new TypedLiteralImpl(tl.lexical.toString(), URI.create(tl.datatype.toString())); } else if (value instanceof BNode) { return new BlankNodeImpl(((BNode)value).label.toString()); } else { // Sherpa passes strings as something other than java.lang.String, so convert. if (value instanceof CharSequence) { value = value.toString(); } // What's left is a primitive Java type, convert it to an XSD-typed literal. // Falls back to xsd:anySimpleType for unrecognized classes return Conversions.toLiteral(value); } }
java
{ "resource": "" }
q16057
MediaDAO.findNear
train
public List<M> findNear(double latitude, double longitude, int numImages) { return getDatastore().find(clazz).field("location.coordinates").near(latitude, longitude).limit(numImages).asList(); }
java
{ "resource": "" }
q16058
MediaDAO.search
train
public List<M> search(String datefield, Date date, int width, int height, int count, int offset, UserAccount account, String query, List<String> sources) { List<Criteria> l = new ArrayList<>(); Query<M> q = getDatastore().createQuery(clazz); if (query != null) { Pattern p = Pattern.compile("(.*)" + query + "(.*)", Pattern.CASE_INSENSITIVE); l.add(q.or( q.criteria("title").equal(p), q.criteria("description").equal(p) )); } if (account != null) { l.add(q.criteria("contributor").equal(account)); } if (width > 0) l.add(q.criteria("width").greaterThanOrEq(width)); if (height > 0) l.add(q.criteria("height").greaterThanOrEq(height)); if (date != null) l.add(q.criteria(datefield).greaterThanOrEq(date)); if (sources != null) l.add(q.criteria("source").in(sources)); q.and(l.toArray(new Criteria[l.size()])); return q.order("crawlDate").offset(offset).limit(count).asList(); }
java
{ "resource": "" }
q16059
ViewUtil.setBackground
train
@SuppressWarnings("deprecation") public static void setBackground(@NonNull final View view, @Nullable final Drawable background) { Condition.INSTANCE.ensureNotNull(view, "The view may not be null"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { view.setBackground(background); } else { view.setBackgroundDrawable(background); } }
java
{ "resource": "" }
q16060
ViewUtil.removeOnGlobalLayoutListener
train
@SuppressWarnings("deprecation") public static void removeOnGlobalLayoutListener(@NonNull final ViewTreeObserver observer, @Nullable final OnGlobalLayoutListener listener) { Condition.INSTANCE.ensureNotNull(observer, "The view tree observer may not be null"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { observer.removeOnGlobalLayoutListener(listener); } else { observer.removeGlobalOnLayoutListener(listener); } }
java
{ "resource": "" }
q16061
ViewUtil.removeFromParent
train
public static void removeFromParent(@NonNull final View view) { Condition.INSTANCE.ensureNotNull(view, "The view may not be null"); ViewParent parent = view.getParent(); if (parent instanceof ViewGroup) { ((ViewGroup) parent).removeView(view); } }
java
{ "resource": "" }
q16062
SquareImageView.obtainScaledEdge
train
private void obtainScaledEdge(@NonNull final TypedArray typedArray) { int defaultValue = Edge.VERTICAL.getValue(); Edge scaledEdge = Edge.fromValue( typedArray.getInt(R.styleable.SquareImageView_scaledEdge, defaultValue)); setScaledEdge(scaledEdge); }
java
{ "resource": "" }
q16063
AbstractHolidayParser._isValidForCycle
train
private static boolean _isValidForCycle (@Nonnull final Holiday aHoliday, final int nYear) { final String sEvery = aHoliday.getEvery (); if (sEvery != null && !"EVERY_YEAR".equals (sEvery)) { if ("ODD_YEARS".equals (sEvery)) return nYear % 2 != 0; if ("EVEN_YEARS".equals (sEvery)) return nYear % 2 == 0; if (aHoliday.getValidFrom () != null) { int nCycleYears = 0; if ("2_YEARS".equalsIgnoreCase (sEvery)) nCycleYears = 2; else if ("3_YEARS".equalsIgnoreCase (sEvery)) nCycleYears = 3; else if ("4_YEARS".equalsIgnoreCase (sEvery)) nCycleYears = 4; else if ("5_YEARS".equalsIgnoreCase (sEvery)) nCycleYears = 5; else if ("6_YEARS".equalsIgnoreCase (sEvery)) nCycleYears = 6; else throw new IllegalArgumentException ("Cannot handle unknown cycle type '" + sEvery + "'."); return (nYear - aHoliday.getValidFrom ().intValue ()) % nCycleYears == 0; } } return true; }
java
{ "resource": "" }
q16064
AbstractHolidayParser._isValidInYear
train
private static boolean _isValidInYear (@Nonnull final Holiday aHoliday, final int nYear) { return (aHoliday.getValidFrom () == null || aHoliday.getValidFrom ().intValue () <= nYear) && (aHoliday.getValidTo () == null || aHoliday.getValidTo ().intValue () >= nYear); }
java
{ "resource": "" }
q16065
AbstractHolidayParser.shallBeMoved
train
protected static final boolean shallBeMoved (@Nonnull final LocalDate aFixed, @Nonnull final MovingCondition aMoveCond) { return aFixed.getDayOfWeek () == XMLHolidayHelper.getWeekday (aMoveCond.getSubstitute ()); }
java
{ "resource": "" }
q16066
AbstractHolidayParser._moveDate
train
private static LocalDate _moveDate (final MovingCondition aMoveCond, final LocalDate aDate) { final DayOfWeek nWeekday = XMLHolidayHelper.getWeekday (aMoveCond.getWeekday ()); final int nDirection = aMoveCond.getWith () == With.NEXT ? 1 : -1; LocalDate aMovedDate = aDate; while (aMovedDate.getDayOfWeek () != nWeekday) { aMovedDate = aMovedDate.plusDays (nDirection); } return aMovedDate; }
java
{ "resource": "" }
q16067
AbstractHolidayParser.moveDate
train
protected static final LocalDate moveDate (final MoveableHoliday aMoveableHoliday, final LocalDate aFixed) { for (final MovingCondition aMoveCond : aMoveableHoliday.getMovingCondition ()) if (shallBeMoved (aFixed, aMoveCond)) return _moveDate (aMoveCond, aFixed); return aFixed; }
java
{ "resource": "" }
q16068
AbstractViewHolderAdapter.setCurrentParentView
train
protected final void setCurrentParentView(@NonNull final View currentParentView) { Condition.INSTANCE.ensureNotNull(currentParentView, "The parent view may not be null"); this.currentParentView = currentParentView; }
java
{ "resource": "" }
q16069
AbstractViewHolderAdapter.findViewById
train
@SuppressWarnings("unchecked") protected final <ViewType extends View> ViewType findViewById(@IdRes final int viewId) { Condition.INSTANCE.ensureNotNull(currentParentView, "No parent view set", IllegalStateException.class); ViewHolder viewHolder = (ViewHolder) currentParentView.getTag(); if (viewHolder == null) { viewHolder = new ViewHolder(currentParentView); currentParentView.setTag(viewHolder); } return (ViewType) viewHolder.findViewById(viewId); }
java
{ "resource": "" }
q16070
SignalSlot.writeSlot
train
private void writeSlot(T data, Throwable error) { dataLock.lock(); try { this.error = error; this.data = data; availableCondition.signalAll(); } finally { dataLock.unlock(); } }
java
{ "resource": "" }
q16071
SignalSlot.getAndClearUnderLock
train
private T getAndClearUnderLock() throws Throwable { if(error != null) { throw error; } else { // Return and clear current T retValue = data; data = null; return retValue; } }
java
{ "resource": "" }
q16072
SignalSlot.take
train
public T take() throws Throwable { dataLock.lock(); try { while(data == null && error == null) { try { availableCondition.await(); } catch(InterruptedException e) { // ignore and re-loop in case of spurious wake-ups } } // should only get to here if data or error is non-null return getAndClearUnderLock(); } finally { dataLock.unlock(); } }
java
{ "resource": "" }
q16073
DefaultYAMLParser.yyparse
train
public Object yyparse (yyInput yyLex, Object yydebug) throws java.io.IOException { //t this.yydebug = (jay.yydebug.yyDebug)yydebug; return yyparse(yyLex); }
java
{ "resource": "" }
q16074
ProtocolDataSource.createPooledClient
train
private HttpClient createPooledClient() { HttpParams connMgrParams = new BasicHttpParams(); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme(HTTP_SCHEME, PlainSocketFactory.getSocketFactory(), HTTP_PORT)); schemeRegistry.register(new Scheme(HTTPS_SCHEME, SSLSocketFactory.getSocketFactory(), HTTPS_PORT)); // All connections will be to the same endpoint, so no need for per-route configuration. // TODO See how this does in the presence of redirects. ConnManagerParams.setMaxTotalConnections(connMgrParams, poolSize); ConnManagerParams.setMaxConnectionsPerRoute(connMgrParams, new ConnPerRouteBean(poolSize)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(connMgrParams, schemeRegistry); HttpParams httpParams = new BasicHttpParams(); HttpProtocolParams.setUseExpectContinue(httpParams, false); ConnManagerParams.setTimeout(httpParams, acquireTimeout * 1000); return new DefaultHttpClient(ccm, httpParams); }
java
{ "resource": "" }
q16075
DuzztState.addTransition
train
public void addTransition(DuzztAction action, DuzztState succ) { transitions.put(action, new DuzztTransition(action, succ)); }
java
{ "resource": "" }
q16076
Transformations.getObj
train
public static ObjectNode getObj(ObjectNode obj, String fieldName) { return obj != null ? obj(obj.get(fieldName)) : null; }
java
{ "resource": "" }
q16077
Transformations.getObjAndRemove
train
public static ObjectNode getObjAndRemove(ObjectNode obj, String fieldName) { ObjectNode result = null; if (obj != null) { result = obj(remove(obj, fieldName)); } return result; }
java
{ "resource": "" }
q16078
Transformations.createArray
train
public static ArrayNode createArray(boolean fallbackToEmptyArray, JsonNode... nodes) { ArrayNode array = null; for (JsonNode element: nodes) { if (element != null) { if (array == null) { array = new ArrayNode(JsonNodeFactory.instance); } array.add(element); } } if ((array == null) && fallbackToEmptyArray) { array = new ArrayNode(JsonNodeFactory.instance); } return array; }
java
{ "resource": "" }
q16079
Transformations.getArray
train
public static ArrayNode getArray(ObjectNode obj, String fieldName) { return obj == null ? null : array(obj.get(fieldName)); }
java
{ "resource": "" }
q16080
Transformations.getArrayAndRemove
train
public static ArrayNode getArrayAndRemove(ObjectNode obj, String fieldName) { ArrayNode result = null; if (obj != null) { result = array(remove(obj, fieldName)); } return result; }
java
{ "resource": "" }
q16081
Transformations.remove
train
public static JsonNode remove(ObjectNode obj, String fieldName) { JsonNode result = null; if (obj != null) { result = obj.remove(fieldName); } return result; }
java
{ "resource": "" }
q16082
Transformations.rename
train
public static void rename(ObjectNode obj, String oldFieldName, String newFieldName) { if (obj != null && isNotBlank(oldFieldName) && isNotBlank(newFieldName)) { JsonNode node = remove(obj, oldFieldName); if (node != null) { obj.set(newFieldName, node); } } }
java
{ "resource": "" }
q16083
ResultFactory.stripParams
train
private static final String stripParams(String mediaType) { int sc = mediaType.indexOf(';'); if (sc >= 0) mediaType = mediaType.substring(0, sc); return mediaType; }
java
{ "resource": "" }
q16084
ResultFactory.getDefaultMediaType
train
public static String getDefaultMediaType(ResultType expectedType) { ResponseFormat format = (expectedType != null) ? defaultTypeFormats.get(expectedType) : null; // If the expected type is unknown, we should let the server decide, otherwise we could // wind up requesting a response type that doesn't match the actual resuts (e.g. xml with CONSTRUCT). // TODO: We could include multiple media types in the Accept: field, but that assumes that the // server has proper support for content negotiation. Many servers only look at the first value. return (format != null) ? format.mimeText : null; }
java
{ "resource": "" }
q16085
ResultFactory.findParser
train
private static final ResultParser findParser(String mediaType, ResultType expectedType) { ResponseFormat format = null; // Prefer MIME type when choosing result format. if (mediaType != null) { mediaType = stripParams(mediaType); format = mimeFormats.get(mediaType); if (format == null) { logger.warn("Unrecognized media type ({}) in SPARQL server response", mediaType); } else { logger.debug("Using result format {} for media type {}", format, mediaType); } } // If MIME type was absent or unrecognized, choose default based on expected result type. if (format == null) { logger.debug("Unable to determine result format from media type"); if (expectedType != null) { format = defaultTypeFormats.get(expectedType); logger.debug("Using default format {} for expected result type {}", format, expectedType); } else { format = DEFAULT_FORMAT; logger.debug("No expected type provided; using default format {}", format); } } assert format != null:"Could not determine result format"; // Validate that the chosen format can produce the expected result type. if (expectedType != null && !format.resultTypes.contains(expectedType)) { throw new SparqlException("Result format " + format + " does not support expected result type " + expectedType); } return format.parser; }
java
{ "resource": "" }
q16086
Filter.equalsFilter
train
public static Filter equalsFilter(String column, Object operand) { return new Filter(column, FilterOperator.EQUALS, operand); }
java
{ "resource": "" }
q16087
Filter.inFilter
train
public static Filter inFilter(String column, Object operand) { return new Filter(column, FilterOperator.IN, operand); }
java
{ "resource": "" }
q16088
HeaderAndFooterGridView.inflatePlaceholderView
train
@NonNull protected final View inflatePlaceholderView(@Nullable final View convertView, final int height) { View view = convertView; if (!(view instanceof PlaceholderView)) { view = new PlaceholderView(getContext()); } view.setMinimumHeight(height); return view; }
java
{ "resource": "" }
q16089
HeaderAndFooterGridView.getViewHeight
train
protected final int getViewHeight(@NonNull final ListAdapter adapter, final int position) { View view = adapter.getView(position, null, this); LayoutParams layoutParams = (LayoutParams) view.getLayoutParams(); if (layoutParams == null) { layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); view.setLayoutParams(layoutParams); } int widthMeasureSpec = getChildMeasureSpec( MeasureSpec.makeMeasureSpec(getColumnWidthCompatible(), MeasureSpec.EXACTLY), 0, layoutParams.width); int heightMeasureSpec = getChildMeasureSpec(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 0, layoutParams.height); view.measure(widthMeasureSpec, heightMeasureSpec); return view.getMeasuredHeight(); }
java
{ "resource": "" }
q16090
HeaderAndFooterGridView.createItemClickListener
train
private OnItemClickListener createItemClickListener( @NonNull final OnItemClickListener encapsulatedListener) { return new OnItemClickListener() { @Override public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) { encapsulatedListener.onItemClick(parent, view, getItemPosition(position), id); } }; }
java
{ "resource": "" }
q16091
HeaderAndFooterGridView.createItemLongClickListener
train
private OnItemLongClickListener createItemLongClickListener( @NonNull final OnItemLongClickListener encapsulatedListener) { return new OnItemLongClickListener() { @Override public boolean onItemLongClick(final AdapterView<?> parent, final View view, final int position, final long id) { return encapsulatedListener .onItemLongClick(parent, view, getItemPosition(position), id); } }; }
java
{ "resource": "" }
q16092
HeaderAndFooterGridView.getItemPosition
train
private int getItemPosition(final int position) { int numColumns = getNumColumnsCompatible(); int headerItemCount = getHeaderViewsCount() * numColumns; int adapterCount = adapter.getEncapsulatedAdapter().getCount(); if (position < headerItemCount) { return position / numColumns; } else if (position < headerItemCount + adapterCount + getNumberOfPlaceholderViews()) { return position - headerItemCount + getHeaderViewsCount(); } else { return getHeaderViewsCount() + adapterCount + (position - headerItemCount - adapterCount - getNumberOfPlaceholderViews()) / numColumns; } }
java
{ "resource": "" }
q16093
HeaderAndFooterGridView.getNumberOfPlaceholderViews
train
private int getNumberOfPlaceholderViews() { int numColumns = getNumColumnsCompatible(); int adapterCount = adapter.getEncapsulatedAdapter().getCount(); int lastLineCount = adapterCount % numColumns; return lastLineCount > 0 ? numColumns - lastLineCount : 0; }
java
{ "resource": "" }
q16094
HeaderAndFooterGridView.addHeaderView
train
public final void addHeaderView(@NonNull final View view, @Nullable final Object data, final boolean selectable) { Condition.INSTANCE.ensureNotNull(view, "The view may not be null"); headers.add(new FullWidthItem(view, data, selectable)); notifyDataSetChanged(); }
java
{ "resource": "" }
q16095
HeaderAndFooterGridView.addFooterView
train
public final void addFooterView(@NonNull final View view, @Nullable final Object data, final boolean selectable) { Condition.INSTANCE.ensureNotNull(view, "The view may not be null"); footers.add(new FullWidthItem(view, data, selectable)); notifyDataSetChanged(); }
java
{ "resource": "" }
q16096
QueryExecution.asyncMoreRequest
train
private void asyncMoreRequest(int startRow) { try { DataRequest moreRequest = new DataRequest(); moreRequest.queryId = queryId; moreRequest.startRow = startRow; moreRequest.maxSize = maxBatchSize; logger.debug("Client requesting {} .. {}", startRow, (startRow + maxBatchSize - 1)); DataResponse response = server.data(moreRequest); logger.debug("Client got response {} .. {}, more={}", new Object[] { response.startRow, (response.startRow + response.data.size() - 1), response.more }); nextData.add(new Window(response.data, response.more)); } catch (AvroRemoteException e) { this.nextData.addError(toSparqlException(e)); } catch (Throwable t) { this.nextData.addError(t); } }
java
{ "resource": "" }
q16097
SparqlCall.encode
train
private static final String encode(String s) { try { return URLEncoder.encode(s, UTF_8); } catch (UnsupportedEncodingException e) { throw new Error("JVM unable to handle UTF-8"); } }
java
{ "resource": "" }
q16098
SparqlCall.dump
train
@SuppressWarnings("unused") private static final void dump(HttpClient client, HttpUriRequest req) { if (logger.isTraceEnabled()) { StringBuilder sb = new StringBuilder("\n=== Request ==="); sb.append("\n").append(req.getRequestLine()); for (Header h : req.getAllHeaders()) { sb.append("\n").append(h.getName()).append(": ").append(h.getValue()); } logger.trace(sb.toString()); HttpResponse resp = null; try { resp = client.execute(req); } catch (Exception e) { logger.trace("Error executing request", e); return; } sb = new StringBuilder("\n=== Response ==="); sb.append("\n").append(resp.getStatusLine()); for (Header h : resp.getAllHeaders()) { sb.append("\n").append(h.getName()).append(": ").append(h.getValue()); } logger.trace(sb.toString()); HttpEntity entity = resp.getEntity(); if (entity != null) { sb = new StringBuilder("\n=== Content ==="); try { int len = (int) entity.getContentLength(); if (len < 0) len = 100; ByteArrayOutputStream baos = new ByteArrayOutputStream(len); entity.writeTo(baos); sb.append("\n").append(baos.toString("UTF-8")); logger.trace(sb.toString()); } catch (IOException e) { logger.trace("Error reading content", e); } } } }
java
{ "resource": "" }
q16099
SparqlCall.executeRequest
train
static HttpResponse executeRequest(ProtocolCommand command, String mimeType) { HttpClient client = ((ProtocolConnection)command.getConnection()).getHttpClient(); URL url = ((ProtocolDataSource)command.getConnection().getDataSource()).getUrl(); HttpUriRequest req; try { String params = "query=" + encode(command.getCommand()); String u = url.toString() + "?" + params; if (u.length() > QUERY_LIMIT) { // POST connection try { req = new HttpPost(url.toURI()); } catch (URISyntaxException e) { throw new SparqlException("Endpoint <" + url + "> not in an acceptable format", e); } ((HttpPost) req).setEntity((HttpEntity) new StringEntity(params)); } else { // GET connection req = new HttpGet(u); } if (command.getTimeout() != Command.NO_TIMEOUT) { HttpParams reqParams = new BasicHttpParams(); HttpConnectionParams.setSoTimeout(reqParams, (int) (command.getTimeout() * 1000)); req.setParams(reqParams); } // Add Accept and Content-Type (for POST'ed queries) headers to the request. addHeaders(req, mimeType); // There's a small chance the request could be aborted before it's even executed, we'll have to live with that. command.setRequest(req); //dump(client, req); HttpResponse response = client.execute(req); StatusLine status = response.getStatusLine(); int code = status.getStatusCode(); // TODO the client doesn't handle redirects for posts; should we do that here? if (code >= SUCCESS_MIN && code <= SUCCESS_MAX) { return response; } else { throw new SparqlException("Unexpected status code in server response: " + status.getReasonPhrase() + "(" + code + ")"); } } catch (UnsupportedEncodingException e) { throw new SparqlException("Unabled to encode data", e); } catch (ClientProtocolException cpe) { throw new SparqlException("Error in protocol", cpe); } catch (IOException e) { throw new SparqlException(e); } }
java
{ "resource": "" }