code
stringlengths
73
34.1k
label
stringclasses
1 value
public static <T> Observable<T> delayedEmitAsync(T event, int milliseconds) { return delayProvider.delayedEmitAsync(event, milliseconds); }
java
@Beta public MSICredentials withObjectId(String objectId) { this.objectId = objectId; this.clientId = null; this.identityId = null; return this; }
java
@Beta public MSICredentials withIdentityId(String identityId) { this.identityId = identityId; this.clientId = null; this.objectId = null; return this; }
java
protected String addPostRunDependent(TaskGroup.HasTaskGroup dependent) { Objects.requireNonNull(dependent); this.taskGroup.addPostRunDependentTaskGroup(dependent.taskGroup()); return dependent.taskGroup().key(); }
java
public static <T> PollingState<T> create(Response<ResponseBody> response, LongRunningOperationOptions lroOptions, int defaultRetryTimeout, Type resourceType, SerializerAdapter<?> serializerAdapter) throws IOException { PollingState<T> pollingState = new PollingState<>(); pollingState.initialHttpMethod = response.raw().request().method(); pollingState.defaultRetryTimeout = defaultRetryTimeout; pollingState.withResponse(response); pollingState.resourceType = resourceType; pollingState.serializerAdapter = serializerAdapter; pollingState.loggingContext = response.raw().request().header(LOGGING_HEADER); pollingState.finalStateVia = lroOptions.finalStateVia(); String responseContent = null; PollingResource resource = null; if (response.body() != null) { responseContent = response.body().string(); response.body().close(); } if (responseContent != null && !responseContent.isEmpty()) { pollingState.resource = serializerAdapter.deserialize(responseContent, resourceType); resource = serializerAdapter.deserialize(responseContent, PollingResource.class); } final int statusCode = pollingState.response.code(); if (resource != null && resource.properties != null && resource.properties.provisioningState != null) { pollingState.withStatus(resource.properties.provisioningState, statusCode); } else { switch (statusCode) { case 202: pollingState.withStatus(AzureAsyncOperation.IN_PROGRESS_STATUS, statusCode); break; case 204: case 201: case 200: pollingState.withStatus(AzureAsyncOperation.SUCCESS_STATUS, statusCode); break; default: pollingState.withStatus(AzureAsyncOperation.FAILED_STATUS, statusCode); } } return pollingState; }
java
public static <ResultT> PollingState<ResultT> createFromJSONString(String serializedPollingState) { ObjectMapper mapper = initMapper(new ObjectMapper()); PollingState<ResultT> pollingState; try { pollingState = mapper.readValue(serializedPollingState, PollingState.class); } catch (IOException exception) { throw new RuntimeException(exception); } return pollingState; }
java
public static <ResultT> PollingState<ResultT> createFromPollingState(PollingState<?> other, ResultT result) { PollingState<ResultT> pollingState = new PollingState<>(); pollingState.resource = result; pollingState.initialHttpMethod = other.initialHttpMethod(); pollingState.status = other.status(); pollingState.statusCode = other.statusCode(); pollingState.azureAsyncOperationHeaderLink = other.azureAsyncOperationHeaderLink(); pollingState.locationHeaderLink = other.locationHeaderLink(); pollingState.putOrPatchResourceUri = other.putOrPatchResourceUri(); pollingState.defaultRetryTimeout = other.defaultRetryTimeout; pollingState.retryTimeout = other.retryTimeout; pollingState.loggingContext = other.loggingContext; pollingState.finalStateVia = other.finalStateVia; return pollingState; }
java
void updateFromResponseOnPutPatch(Response<ResponseBody> response) throws CloudException, IOException { String responseContent = null; if (response.body() != null) { responseContent = response.body().string(); response.body().close(); } if (responseContent == null || responseContent.isEmpty()) { throw new CloudException("polling response does not contain a valid body", response); } PollingResource resource = serializerAdapter.deserialize(responseContent, PollingResource.class); final int statusCode = response.code(); if (resource != null && resource.properties != null && resource.properties.provisioningState != null) { this.withStatus(resource.properties.provisioningState, statusCode); } else { this.withStatus(AzureAsyncOperation.SUCCESS_STATUS, statusCode); } CloudError error = new CloudError(); this.withErrorBody(error); error.withCode(this.status()); error.withMessage("Long running operation failed"); this.withResponse(response); this.withResource(serializerAdapter.<T>deserialize(responseContent, resourceType)); }
java
void updateFromResponseOnDeletePost(Response<ResponseBody> response) throws IOException { this.withResponse(response); String responseContent = null; if (response.body() != null) { responseContent = response.body().string(); response.body().close(); } this.withResource(serializerAdapter.<T>deserialize(responseContent, resourceType)); withStatus(AzureAsyncOperation.SUCCESS_STATUS, response.code()); }
java
PollingState<T> withStatus(String status, int statusCode) throws IllegalArgumentException { if (status == null) { throw new IllegalArgumentException("Status is null."); } this.status = status; this.statusCode = statusCode; return this; }
java
PollingState<T> withResponse(Response<ResponseBody> response) { this.response = response; withPollingUrlFromResponse(response); withPollingRetryTimeoutFromResponse(response); return this; }
java
void throwCloudExceptionIfInFailedState() { if (this.isStatusFailed()) { if (this.errorBody() != null) { throw new CloudException("Async operation failed with provisioning state: " + this.status(), this.response(), this.errorBody()); } else { throw new CloudException("Async operation failed with provisioning state: " + this.status(), this.response()); } } }
java
static AzureAsyncOperation fromResponse(SerializerAdapter<?> serializerAdapter, Response<ResponseBody> response) throws CloudException { AzureAsyncOperation asyncOperation = null; String rawString = null; if (response.body() != null) { try { rawString = response.body().string(); asyncOperation = serializerAdapter.deserialize(rawString, AzureAsyncOperation.class); } catch (IOException exception) { // Exception will be handled below } finally { response.body().close(); } } if (asyncOperation == null || asyncOperation.status() == null) { throw new CloudException("polling response does not contain a valid body: " + rawString, response); } else { asyncOperation.rawString = rawString; } return asyncOperation; }
java
public void setOwner(Graph<DataT, NodeT> ownerGraph) { if (this.ownerGraph != null) { throw new RuntimeException("Changing owner graph is not allowed"); } this.ownerGraph = ownerGraph; }
java
protected void onFaultedResolution(String dependencyKey, Throwable throwable) { if (toBeResolved == 0) { throw new RuntimeException("invalid state - " + this.key() + ": The dependency '" + dependencyKey + "' is already reported or there is no such dependencyKey"); } toBeResolved--; }
java
public String userAgent() { return String.format("Azure-SDK-For-Java/%s OS:%s MacAddressHash:%s Java:%s", getClass().getPackage().getImplementationVersion(), OS, MAC_ADDRESS_HASH, JAVA_VERSION); }
java
public static String groupFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null; }
java
public static String subscriptionFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).subscriptionId() : null; }
java
public static String resourceProviderFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).providerNamespace() : null; }
java
public static String resourceTypeFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).resourceType() : null; }
java
public static String extractFromResourceId(String id, String identifier) { if (id == null || identifier == null) { return id; } Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+"); Matcher matcher = pattern.matcher(id); if (matcher.find()) { return matcher.group().split("/")[1]; } else { return null; } }
java
public static String nameFromResourceId(String id) { return (id != null) ? ResourceId.fromString(id).name() : null; }
java
public static String constructResourceId( final String subscriptionId, final String resourceGroupName, final String resourceProviderNamespace, final String resourceType, final String resourceName, final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } return String.format( "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); }
java
private <T> ServiceResponse<T> getPutOrPatchResult(Observable<Response<ResponseBody>> observable, Type resourceType) throws CloudException, InterruptedException, IOException { Observable<ServiceResponse<T>> asyncObservable = getPutOrPatchResultAsync(observable, resourceType); return asyncObservable.toBlocking().last(); }
java
public <T> Observable<ServiceResponse<T>> getPutOrPatchResultAsync(Observable<Response<ResponseBody>> observable, final Type resourceType) { return this.<T>beginPutOrPatchAsync(observable, resourceType) .toObservable() .flatMap(new Func1<PollingState<T>, Observable<PollingState<T>>>() { @Override public Observable<PollingState<T>> call(PollingState<T> pollingState) { return pollPutOrPatchAsync(pollingState, resourceType); } }) .last() .map(new Func1<PollingState<T>, ServiceResponse<T>>() { @Override public ServiceResponse<T> call(PollingState<T> pollingState) { return new ServiceResponse<>(pollingState.resource(), pollingState.response()); } }); }
java
private <T> Observable<PollingState<T>> updateStateFromLocationHeaderOnPutAsync(final PollingState<T> pollingState) { return pollAsync(pollingState.locationHeaderLink(), pollingState.loggingContext()) .flatMap(new Func1<Response<ResponseBody>, Observable<PollingState<T>>>() { @Override public Observable<PollingState<T>> call(Response<ResponseBody> response) { int statusCode = response.code(); if (statusCode == 202) { pollingState.withResponse(response); pollingState.withStatus(AzureAsyncOperation.IN_PROGRESS_STATUS, statusCode); } else if (statusCode == 200 || statusCode == 201) { try { pollingState.updateFromResponseOnPutPatch(response); } catch (CloudException | IOException e) { return Observable.error(e); } } return Observable.just(pollingState); } }); }
java
private <T> Observable<PollingState<T>> updateStateFromGetResourceOperationAsync(final PollingState<T> pollingState, String url) { return pollAsync(url, pollingState.loggingContext()) .flatMap(new Func1<Response<ResponseBody>, Observable<PollingState<T>>>() { @Override public Observable<PollingState<T>> call(Response<ResponseBody> response) { try { pollingState.updateFromResponseOnPutPatch(response); return Observable.just(pollingState); } catch (CloudException | IOException e) { return Observable.error(e); } } }); }
java
private Observable<Response<ResponseBody>> pollAsync(String url, String loggingContext) { URL endpoint; try { endpoint = new URL(url); } catch (MalformedURLException e) { return Observable.error(e); } AsyncService service = restClient().retrofit().create(AsyncService.class); if (loggingContext != null && !loggingContext.endsWith(" (poll)")) { loggingContext += " (poll)"; } return service.get(endpoint.getFile(), serviceClientUserAgent, loggingContext) .flatMap(new Func1<Response<ResponseBody>, Observable<Response<ResponseBody>>>() { @Override public Observable<Response<ResponseBody>> call(Response<ResponseBody> response) { RuntimeException exception = createExceptionFromResponse(response, 200, 201, 202, 204); if (exception != null) { return Observable.error(exception); } else { return Observable.just(response); } } }); }
java
public Indexable taskResult(String taskId) { TaskGroupEntry<TaskItem> taskGroupEntry = super.getNode(taskId); if (taskGroupEntry != null) { return taskGroupEntry.taskResult(); } if (!this.proxyTaskGroupWrapper.isActive()) { throw new IllegalArgumentException("A dependency task with id '" + taskId + "' is not found"); } taskGroupEntry = this.proxyTaskGroupWrapper.proxyTaskGroup.getNode(taskId); if (taskGroupEntry != null) { return taskGroupEntry.taskResult(); } throw new IllegalArgumentException("A dependency task or 'post-run' dependent task with with id '" + taskId + "' not found"); }
java
public String addDependency(FunctionalTaskItem dependencyTaskItem) { IndexableTaskItem dependency = IndexableTaskItem.create(dependencyTaskItem); this.addDependency(dependency); return dependency.key(); }
java
public void addDependencyTaskGroup(TaskGroup dependencyTaskGroup) { if (dependencyTaskGroup.proxyTaskGroupWrapper.isActive()) { dependencyTaskGroup.proxyTaskGroupWrapper.addDependentTaskGroup(this); } else { DAGraph<TaskItem, TaskGroupEntry<TaskItem>> dependencyGraph = dependencyTaskGroup; super.addDependencyGraph(dependencyGraph); } }
java
public String addPostRunDependent(FunctionalTaskItem dependentTaskItem) { IndexableTaskItem taskItem = IndexableTaskItem.create(dependentTaskItem); this.addPostRunDependent(taskItem); return taskItem.key(); }
java
private Observable<Indexable> invokeReadyTasksAsync(final InvocationContext context) { TaskGroupEntry<TaskItem> readyTaskEntry = super.getNext(); final List<Observable<Indexable>> observables = new ArrayList<>(); // Enumerate the ready tasks (those with dependencies resolved) and kickoff them concurrently // while (readyTaskEntry != null) { final TaskGroupEntry<TaskItem> currentEntry = readyTaskEntry; final TaskItem currentTaskItem = currentEntry.data(); if (currentTaskItem instanceof ProxyTaskItem) { observables.add(invokeAfterPostRunAsync(currentEntry, context)); } else { observables.add(invokeTaskAsync(currentEntry, context)); } readyTaskEntry = super.getNext(); } return Observable.mergeDelayError(observables); }
java
private Observable<Indexable> processFaultedTaskAsync(final TaskGroupEntry<TaskItem> faultedEntry, final Throwable throwable, final InvocationContext context) { markGroupAsCancelledIfTerminationStrategyIsIPTC(); reportError(faultedEntry, throwable); if (isRootEntry(faultedEntry)) { if (shouldPropagateException(throwable)) { return toErrorObservable(throwable); } return Observable.empty(); } else if (shouldPropagateException(throwable)) { return Observable.concatDelayError(invokeReadyTasksAsync(context), toErrorObservable(throwable)); } else { return invokeReadyTasksAsync(context); } }
java
@Override public boolean shouldRetry(int retryCount, Response response) { int code = response.code(); //CHECKSTYLE IGNORE MagicNumber FOR NEXT 2 LINES return retryCount < this.retryCount && (code == 408 || (code >= 500 && code != 501 && code != 505)); }
java
@Beta(SinceVersion.V1_1_0) public void close() { httpClient.dispatcher().executorService().shutdown(); httpClient.connectionPool().evictAll(); synchronized (httpClient.connectionPool()) { httpClient.connectionPool().notifyAll(); } synchronized (AsyncTimeout.class) { AsyncTimeout.class.notifyAll(); } }
java
public static <InnerT> PagedList<InnerT> convertToPagedList(List<InnerT> list) { PageImpl<InnerT> page = new PageImpl<>(); page.setItems(list); page.setNextPageLink(null); return new PagedList<InnerT>(page) { @Override public Page<InnerT> nextPage(String nextPageLink) { return null; } }; }
java
public static <InnerT> Observable<InnerT> convertListToInnerAsync(Observable<List<InnerT>> innerList) { return innerList.flatMap(new Func1<List<InnerT>, Observable<InnerT>>() { @Override public Observable<InnerT> call(List<InnerT> inners) { return Observable.from(inners); } }); }
java
public static <InnerT> Observable<InnerT> convertPageToInnerAsync(Observable<Page<InnerT>> innerPage) { return innerPage.flatMap(new Func1<Page<InnerT>, Observable<InnerT>>() { @Override public Observable<InnerT> call(Page<InnerT> pageInner) { return Observable.from(pageInner.items()); } }); }
java
public void add(final IndexableTaskItem taskItem) { this.dependsOnTaskGroup.addPostRunDependentTaskGroup(taskItem.taskGroup()); this.collection.add(taskItem); }
java
public Eval<UploadResult> putAsync(String key, Object value) { return Eval.later(() -> put(key, value)) .map(t -> t.orElse(null)) .map(FluentFunctions.ofChecked(up -> up.waitForUploadResult())); }
java
public Future<PutObjectResult> putAsync(String key, String value) { return Future.of(() -> put(key, value), this.uploadService) .flatMap(t->t.fold(p->Future.ofResult(p),e->Future.ofError(e))); }
java
public static <T> void finish(T query, long correlationId, EventBus bus, String... labels) { for (String type : labels) { RemoveLabelledQuery<T> next = finish(query, correlationId, type); bus.post(next); } }
java
public static <T> AddQuery<T> start(T query, long correlationId) { return start(query, correlationId, "default", null); }
java
public static <T> void finish(T query, long correlationId, EventBus bus, String... types) { for (String type : types) { RemoveQuery<T> next = finish(query, correlationId, type); bus.post(next); } }
java
public Try<R,Throwable> execute(T input){ return Try.withCatch( ()->transactionTemplate.execute(status-> transaction.apply(input))); }
java
public <Ex extends Throwable> Try<R,Ex> execute(T input,Class<Ex> classes){ return Try.withCatch( ()->transactionTemplate.execute(status-> transaction.apply(input)),classes); }
java
public Column getColumn(String columnName) { if (columnName == null) { return null; } for (Column column : columns) { if (columnName.equals(column.getData())) { return column; } } return null; }
java
public void addColumn(String columnName, boolean searchable, boolean orderable, String searchValue) { this.columns.add(new Column(columnName, "", searchable, orderable, new Search(searchValue, false))); }
java
public void addOrder(String columnName, boolean ascending) { if (columnName == null) { return; } for (int i = 0; i < columns.size(); i++) { if (!columnName.equals(columns.get(i).getData())) { continue; } order.add(new Order(i, ascending ? "asc" : "desc")); } }
java
public Model interpolateModel(Model model, File projectDir, ModelBuildingRequest config, ModelProblemCollector problems) { interpolateObject(model, model, projectDir, config, problems); return model; }
java
public String interpolate( String input, RecursionInterceptor recursionInterceptor ) throws InterpolationException { try { return interpolate( input, recursionInterceptor, new HashSet<String>() ); } finally { if ( !cacheAnswers ) { existingAnswers.clear(); } } }
java
public List getFeedback() { List<?> messages = new ArrayList(); for ( ValueSource vs : valueSources ) { List feedback = vs.getFeedback(); if ( feedback != null && !feedback.isEmpty() ) { messages.addAll( feedback ); } } return messages; }
java
public ModelSource resolveModel( Parent parent ) throws UnresolvableModelException { Dependency parentDependency = new Dependency(); parentDependency.setGroupId(parent.getGroupId()); parentDependency.setArtifactId(parent.getArtifactId()); parentDependency.setVersion(parent.getVersion()); parentDependency.setClassifier(""); parentDependency.setType("pom"); Artifact parentArtifact = null; try { Iterable<ArtifactResult> artifactResults = depencencyResolver.resolveDependencies( projectBuildingRequest, singleton(parentDependency), null, null ); Iterator<ArtifactResult> iterator = artifactResults.iterator(); if (iterator.hasNext()) { parentArtifact = iterator.next().getArtifact(); } } catch (DependencyResolverException e) { throw new UnresolvableModelException( e.getMessage(), parent.getGroupId(), parent.getArtifactId(), parent.getVersion(), e ); } return resolveModel( parentArtifact.getGroupId(), parentArtifact.getArtifactId(), parentArtifact.getVersion() ); }
java
protected String extractHeaderComment( File xmlFile ) throws MojoExecutionException { try { SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); SaxHeaderCommentHandler handler = new SaxHeaderCommentHandler(); parser.setProperty( "http://xml.org/sax/properties/lexical-handler", handler ); parser.parse( xmlFile, handler ); return handler.getHeaderComment(); } catch ( Exception e ) { throw new MojoExecutionException( "Failed to parse XML from " + xmlFile, e ); } }
java
protected Model createFlattenedPom( File pomFile ) throws MojoExecutionException, MojoFailureException { ModelBuildingRequest buildingRequest = createModelBuildingRequest( pomFile ); Model effectivePom = createEffectivePom( buildingRequest, isEmbedBuildProfileDependencies(), this.flattenMode ); Model flattenedPom = new Model(); // keep original encoding (we could also normalize to UTF-8 here) String modelEncoding = effectivePom.getModelEncoding(); if ( StringUtils.isEmpty( modelEncoding ) ) { modelEncoding = "UTF-8"; } flattenedPom.setModelEncoding( modelEncoding ); Model cleanPom = createCleanPom( effectivePom ); FlattenDescriptor descriptor = getFlattenDescriptor(); Model originalPom = this.project.getOriginalModel(); Model resolvedPom = this.project.getModel(); Model interpolatedPom = createResolvedPom( buildingRequest ); // copy the configured additional POM elements... for ( PomProperty<?> property : PomProperty.getPomProperties() ) { if ( property.isElement() ) { Model sourceModel = getSourceModel( descriptor, property, effectivePom, originalPom, resolvedPom, interpolatedPom, cleanPom ); if ( sourceModel == null ) { if ( property.isRequired() ) { throw new MojoFailureException( "Property " + property.getName() + " is required and can not be removed!" ); } } else { property.copy( sourceModel, flattenedPom ); } } } return flattenedPom; }
java
public final int toCodePoints(char[] src, int srcOff, int srcLen, int[] dest, int destOff) { if (srcLen < 0) { throw new IllegalArgumentException("srcLen must be >= 0"); } int codePointCount = 0; for (int i = 0; i < srcLen; ) { final int cp = codePointAt(src, srcOff + i, srcOff + srcLen); final int charCount = Character.charCount(cp); dest[destOff + codePointCount++] = cp; i += charCount; } return codePointCount; }
java
public final int toChars(int[] src, int srcOff, int srcLen, char[] dest, int destOff) { if (srcLen < 0) { throw new IllegalArgumentException("srcLen must be >= 0"); } int written = 0; for (int i = 0; i < srcLen; ++i) { written += Character.toChars(src[srcOff + i], dest, destOff + written); } return written; }
java
public static List<Sentence> splitSentences(CharSequence text) { return JavaConversions.seqAsJavaList( TwitterKoreanProcessor.splitSentences(text) ); }
java
public static List<KoreanPhraseExtractor.KoreanPhrase> extractPhrases(Seq<KoreanToken> tokens, boolean filterSpam, boolean includeHashtags) { return JavaConversions.seqAsJavaList( TwitterKoreanProcessor.extractPhrases(tokens, filterSpam, includeHashtags) ); }
java
public static String detokenize(List<String> tokens) { return TwitterKoreanProcessor.detokenize(JavaConversions.iterableAsScalaIterable(tokens)); }
java
public ConverterServerBuilder baseUri(String baseUri) { checkNotNull(baseUri); this.baseUri = URI.create(baseUri); return this; }
java
public ConverterServerBuilder workerPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit) { assertNumericArgument(corePoolSize, true); assertNumericArgument(maximumPoolSize, true); assertNumericArgument(corePoolSize + maximumPoolSize, false); assertNumericArgument(keepAliveTime, true); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.keepAliveTime = unit.toMillis(keepAliveTime); return this; }
java
public ConverterServerBuilder requestTimeout(long timeout, TimeUnit unit) { assertNumericArgument(timeout, true); this.requestTimeout = unit.toMillis(timeout); return this; }
java
public ConverterServerBuilder processTimeout(long processTimeout, TimeUnit timeUnit) { assertNumericArgument(processTimeout, false); this.processTimeout = timeUnit.toMillis(processTimeout); return this; }
java
public HttpServer build() { checkNotNull(baseUri); StandaloneWebConverterConfiguration configuration = makeConfiguration(); // The configuration has to be configured both by a binder to make it injectable // and directly in order to trigger life cycle methods on the deployment container. ResourceConfig resourceConfig = ResourceConfig .forApplication(new WebConverterApplication(configuration)) .register(configuration); if (sslContext == null) { return GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig); } else { return GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig, true, new SSLEngineConfigurator(sslContext)); } }
java
@UiThread public int getParentAdapterPosition() { int flatPosition = getAdapterPosition(); if (flatPosition == RecyclerView.NO_POSITION) { return flatPosition; } return mExpandableAdapter.getNearestParentPosition(flatPosition); }
java
@UiThread protected void expandView() { setExpanded(true); onExpansionToggled(false); if (mParentViewHolderExpandCollapseListener != null) { mParentViewHolderExpandCollapseListener.onParentExpanded(getAdapterPosition()); } }
java
@UiThread protected void collapseView() { setExpanded(false); onExpansionToggled(true); if (mParentViewHolderExpandCollapseListener != null) { mParentViewHolderExpandCollapseListener.onParentCollapsed(getAdapterPosition()); } }
java
@UiThread protected void parentExpandedFromViewHolder(int flatParentPosition) { ExpandableWrapper<P, C> parentWrapper = mFlatItemList.get(flatParentPosition); updateExpandedParent(parentWrapper, flatParentPosition, true); }
java
@UiThread protected void parentCollapsedFromViewHolder(int flatParentPosition) { ExpandableWrapper<P, C> parentWrapper = mFlatItemList.get(flatParentPosition); updateCollapsedParent(parentWrapper, flatParentPosition, true); }
java
@UiThread public void expandParentRange(int startParentPosition, int parentCount) { int endParentPosition = startParentPosition + parentCount; for (int i = startParentPosition; i < endParentPosition; i++) { expandParent(i); } }
java
@UiThread public void collapseParentRange(int startParentPosition, int parentCount) { int endParentPosition = startParentPosition + parentCount; for (int i = startParentPosition; i < endParentPosition; i++) { collapseParent(i); } }
java
private List<ExpandableWrapper<P, C>> generateFlattenedParentChildList(List<P> parentList) { List<ExpandableWrapper<P, C>> flatItemList = new ArrayList<>(); int parentCount = parentList.size(); for (int i = 0; i < parentCount; i++) { P parent = parentList.get(i); generateParentWrapper(flatItemList, parent, parent.isInitiallyExpanded()); } return flatItemList; }
java
private List<ExpandableWrapper<P, C>> generateFlattenedParentChildList(List<P> parentList, Map<P, Boolean> savedLastExpansionState) { List<ExpandableWrapper<P, C>> flatItemList = new ArrayList<>(); int parentCount = parentList.size(); for (int i = 0; i < parentCount; i++) { P parent = parentList.get(i); Boolean lastExpandedState = savedLastExpansionState.get(parent); boolean shouldExpand = lastExpandedState == null ? parent.isInitiallyExpanded() : lastExpandedState; generateParentWrapper(flatItemList, parent, shouldExpand); } return flatItemList; }
java
@NonNull @UiThread private HashMap<Integer, Boolean> generateExpandedStateMap() { HashMap<Integer, Boolean> parentHashMap = new HashMap<>(); int childCount = 0; int listItemCount = mFlatItemList.size(); for (int i = 0; i < listItemCount; i++) { if (mFlatItemList.get(i) != null) { ExpandableWrapper<P, C> listItem = mFlatItemList.get(i); if (listItem.isParent()) { parentHashMap.put(i - childCount, listItem.isExpanded()); } else { childCount++; } } } return parentHashMap; }
java
@UiThread private int getFlatParentPosition(int parentPosition) { int parentCount = 0; int listItemCount = mFlatItemList.size(); for (int i = 0; i < listItemCount; i++) { if (mFlatItemList.get(i).isParent()) { parentCount++; if (parentCount > parentPosition) { return i; } } } return INVALID_FLAT_POSITION; }
java
@UiThread public int getParentAdapterPosition() { int flatPosition = getAdapterPosition(); if (mExpandableAdapter == null || flatPosition == RecyclerView.NO_POSITION) { return RecyclerView.NO_POSITION; } return mExpandableAdapter.getNearestParentPosition(flatPosition); }
java
@UiThread public int getChildAdapterPosition() { int flatPosition = getAdapterPosition(); if (mExpandableAdapter == null || flatPosition == RecyclerView.NO_POSITION) { return RecyclerView.NO_POSITION; } return mExpandableAdapter.getChildPosition(flatPosition); }
java
public static String fillLogParams(String sql, Map<Object, Object> logParams) { StringBuilder result = new StringBuilder(); Map<Object, Object> tmpLogParam = (logParams == null ? new HashMap<Object, Object>() : logParams); Iterator<Object> it = tmpLogParam.values().iterator(); boolean inQuote = false; boolean inQuote2 = false; char[] sqlChar = sql != null ? sql.toCharArray() : new char[]{}; for (int i=0; i < sqlChar.length; i++){ if (sqlChar[i] == '\''){ inQuote = !inQuote; } if (sqlChar[i] == '"'){ inQuote2 = !inQuote2; } if (sqlChar[i] == '?' && !(inQuote || inQuote2)){ if (it.hasNext()){ result.append(prettyPrint(it.next())); } else { result.append('?'); } } else { result.append(sqlChar[i]); } } return result.toString(); }
java
protected static void sendInitSQL(Connection connection, String initSQL) throws SQLException{ // fetch any configured setup sql. if (initSQL != null){ Statement stmt = null; try{ stmt = connection.createStatement(); stmt.execute(initSQL); if (testSupport){ // only to aid code coverage, normally set to false stmt = null; } } finally{ if (stmt != null){ stmt.close(); } } } }
java
public void close() throws SQLException { try { if (this.resetConnectionOnClose /*FIXME: && !getAutoCommit() && !isTxResolved() */){ /*if (this.autoCommitStackTrace != null){ logger.debug(this.autoCommitStackTrace); this.autoCommitStackTrace = null; } else { logger.debug(DISABLED_AUTO_COMMIT_WARNING); }*/ rollback(); if (!getAutoCommit()){ setAutoCommit(true); } } if (this.logicallyClosed.compareAndSet(false, true)) { if (this.threadWatch != null){ this.threadWatch.interrupt(); // if we returned the connection to the pool, terminate thread watch thread if it's // running even if thread is still alive (eg thread has been recycled for use in some // container). this.threadWatch = null; } if (this.closeOpenStatements){ for (Entry<Statement, String> statementEntry: this.trackedStatement.entrySet()){ statementEntry.getKey().close(); if (this.detectUnclosedStatements){ logger.warn(String.format(UNCLOSED_LOG_ERROR_MESSAGE, statementEntry.getValue())); } } this.trackedStatement.clear(); } if (!this.connectionTrackingDisabled){ pool.getFinalizableRefs().remove(this.connection); } ConnectionHandle handle = null; //recreate can throw a SQLException in constructor on recreation try { handle = this.recreateConnectionHandle(); this.pool.connectionStrategy.cleanupConnection(this, handle); this.pool.releaseConnection(handle); } catch(SQLException e) { //check if the connection was already closed by the recreation if (!isClosed()) { this.pool.connectionStrategy.cleanupConnection(this, handle); this.pool.releaseConnection(this); } throw e; } if (this.doubleCloseCheck){ this.doubleCloseException = this.pool.captureStackTrace(CLOSED_TWICE_EXCEPTION_MESSAGE); } } else { if (this.doubleCloseCheck && this.doubleCloseException != null){ String currentLocation = this.pool.captureStackTrace("Last closed trace from thread ["+Thread.currentThread().getName()+"]:\n"); logger.error(String.format(LOG_ERROR_MESSAGE, this.doubleCloseException, currentLocation)); } } } catch (SQLException e) { throw markPossiblyBroken(e); } }
java
protected void internalClose() throws SQLException { try { clearStatementCaches(true); if (this.connection != null){ // safety! this.connection.close(); if (!this.connectionTrackingDisabled && this.finalizableRefs != null){ this.finalizableRefs.remove(this.connection); } } this.logicallyClosed.set(true); } catch (SQLException e) { throw markPossiblyBroken(e); } }
java
protected void clearStatementCaches(boolean internalClose) { if (this.statementCachingEnabled){ // safety if (internalClose){ this.callableStatementCache.clear(); this.preparedStatementCache.clear(); } else { if (this.pool.closeConnectionWatch){ // debugging enabled? this.callableStatementCache.checkForProperClosure(); this.preparedStatementCache.checkForProperClosure(); } } } }
java
public Object getProxyTarget(){ try { return Proxy.getInvocationHandler(this.connection).invoke(null, this.getClass().getMethod("getProxyTarget"), null); } catch (Throwable t) { throw new RuntimeException("BoneCP: Internal error - transaction replay log is not turned on?", t); } }
java
public void refreshConnection() throws SQLException{ this.connection.close(); // if it's still in use, close it. try{ this.connection = this.pool.obtainRawInternalConnection(); } catch(SQLException e){ throw markPossiblyBroken(e); } }
java
public void switchDataSource(BoneCPConfig newConfig) throws SQLException { logger.info("Switch to new datasource requested. New Config: "+newConfig); DataSource oldDS = getTargetDataSource(); if (!(oldDS instanceof BoneCPDataSource)){ throw new SQLException("Unknown datasource type! Was expecting BoneCPDataSource but received "+oldDS.getClass()+". Not switching datasource!"); } BoneCPDataSource newDS = new BoneCPDataSource(newConfig); newDS.getConnection().close(); // initialize a connection (+ throw it away) to force the datasource to initialize the pool // force application to start using the new one setTargetDataSource(newDS); logger.info("Shutting down old datasource slowly. Old Config: "+oldDS); // tell the old datasource to terminate. This terminates the pool lazily so existing checked out connections can still be used. ((BoneCPDataSource)oldDS).close(); }
java
protected static Connection memorize(final Connection target, final ConnectionHandle connectionHandle) { return (Connection) Proxy.newProxyInstance( ConnectionProxy.class.getClassLoader(), new Class[] {ConnectionProxy.class}, new MemorizeTransactionProxy(target, connectionHandle)); }
java
protected static Statement memorize(final Statement target, final ConnectionHandle connectionHandle) { return (Statement) Proxy.newProxyInstance( StatementProxy.class.getClassLoader(), new Class[] {StatementProxy.class}, new MemorizeTransactionProxy(target, connectionHandle)); }
java
protected static PreparedStatement memorize(final PreparedStatement target, final ConnectionHandle connectionHandle) { return (PreparedStatement) Proxy.newProxyInstance( PreparedStatementProxy.class.getClassLoader(), new Class[] {PreparedStatementProxy.class}, new MemorizeTransactionProxy(target, connectionHandle)); }
java
protected static CallableStatement memorize(final CallableStatement target, final ConnectionHandle connectionHandle) { return (CallableStatement) Proxy.newProxyInstance( CallableStatementProxy.class.getClassLoader(), new Class[] {CallableStatementProxy.class}, new MemorizeTransactionProxy(target, connectionHandle)); }
java
private Object runWithPossibleProxySwap(Method method, Object target, Object[] args) throws IllegalAccessException, InvocationTargetException { Object result; // swap with proxies to these too. if (method.getName().equals("createStatement")){ result = memorize((Statement)method.invoke(target, args), this.connectionHandle.get()); } else if (method.getName().equals("prepareStatement")){ result = memorize((PreparedStatement)method.invoke(target, args), this.connectionHandle.get()); } else if (method.getName().equals("prepareCall")){ result = memorize((CallableStatement)method.invoke(target, args), this.connectionHandle.get()); } else result = method.invoke(target, args); return result; }
java
private void fillConnections(int connectionsToCreate) throws InterruptedException { try { for (int i=0; i < connectionsToCreate; i++){ // boolean dbDown = this.pool.getDbIsDown().get(); if (this.pool.poolShuttingDown){ break; } this.partition.addFreeConnection(new ConnectionHandle(null, this.partition, this.pool, false)); } } catch (Exception e) { logger.error("Error in trying to obtain a connection. Retrying in "+this.acquireRetryDelayInMs+"ms", e); Thread.sleep(this.acquireRetryDelayInMs); } }
java
public String calculateCacheKey(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability){ StringBuilder tmp = calculateCacheKeyInternal(sql, resultSetType, resultSetConcurrency); tmp.append(", H:"); tmp.append(resultSetHoldability); return tmp.toString(); }
java
private StringBuilder calculateCacheKeyInternal(String sql, int resultSetType, int resultSetConcurrency) { StringBuilder tmp = new StringBuilder(sql.length()+20); tmp.append(sql); tmp.append(", T"); tmp.append(resultSetType); tmp.append(", C"); tmp.append(resultSetConcurrency); return tmp; }
java
public String calculateCacheKey(String sql, int autoGeneratedKeys) { StringBuilder tmp = new StringBuilder(sql.length()+4); tmp.append(sql); tmp.append(autoGeneratedKeys); return tmp.toString(); }
java
public String calculateCacheKey(String sql, int[] columnIndexes) { StringBuilder tmp = new StringBuilder(sql.length()+4); tmp.append(sql); for (int i=0; i < columnIndexes.length; i++){ tmp.append(columnIndexes[i]); tmp.append("CI,"); } return tmp.toString(); }
java
public void run() { ConnectionHandle connection = null; long tmp; long nextCheckInMs = this.maxAgeInMs; int partitionSize= this.partition.getAvailableConnections(); long currentTime = System.currentTimeMillis(); for (int i=0; i < partitionSize; i++){ try { connection = this.partition.getFreeConnections().poll(); if (connection != null){ connection.setOriginatingPartition(this.partition); tmp = this.maxAgeInMs - (currentTime - connection.getConnectionCreationTimeInMs()); if (tmp < nextCheckInMs){ nextCheckInMs = tmp; } if (connection.isExpired(currentTime)){ // kill off this connection closeConnection(connection); continue; } if (this.lifoMode){ // we can't put it back normally or it will end up in front again. if (!(connection.getOriginatingPartition().getFreeConnections().offer(connection))){ connection.internalClose(); } } else { this.pool.putConnectionBackInPartition(connection); } Thread.sleep(20L); // test slowly, this is not an operation that we're in a hurry to deal with (avoid CPU spikes)... } } catch (Throwable e) { logger.error("Connection max age thread exception.", e); } } // throw it back on the queue }
java
protected void closeConnection(ConnectionHandle connection) { if (connection != null) { try { connection.internalClose(); } catch (Throwable t) { logger.error("Destroy connection exception", t); } finally { this.pool.postDestroyConnection(connection); } } }
java
public void setIdleMaxAge(long idleMaxAge, TimeUnit timeUnit) { this.idleMaxAgeInSeconds = TimeUnit.SECONDS.convert(idleMaxAge, checkNotNull(timeUnit)); }
java