hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e12568e4cb16484e6eb0e19f743a6a290086342 | 4,394 | java | Java | pousse-cafe-core/src/test/java/poussecafe/processing/MessageBrokerTest.java | pousse-cafe/pousse-cafe | 9dfc2d0b7c2e9a733d26f8179fb3954357f33d44 | [
"Apache-2.0"
] | 6 | 2017-05-10T15:02:57.000Z | 2020-08-07T14:38:02.000Z | pousse-cafe-core/src/test/java/poussecafe/processing/MessageBrokerTest.java | pousse-cafe/pousse-cafe | 9dfc2d0b7c2e9a733d26f8179fb3954357f33d44 | [
"Apache-2.0"
] | 217 | 2018-01-31T07:52:30.000Z | 2021-03-23T20:48:43.000Z | pousse-cafe-core/src/test/java/poussecafe/processing/MessageBrokerTest.java | pousse-cafe/pousse-cafe | 9dfc2d0b7c2e9a733d26f8179fb3954357f33d44 | [
"Apache-2.0"
] | 4 | 2019-05-23T05:49:50.000Z | 2020-04-08T07:47:15.000Z | 36.016393 | 112 | 0.722804 | 7,734 | package poussecafe.processing;
import java.util.List;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.stubbing.Answer;
import poussecafe.apm.ApplicationPerformanceMonitoring;
import poussecafe.environment.MessageListener;
import poussecafe.messaging.Message;
import poussecafe.runtime.MessageConsumptionHandler;
import poussecafe.runtime.OriginalAndMarshaledMessage;
import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class MessageBrokerTest {
@Test
public void receivedMessageDispatchedToOneProcessingThread() {
givenReceivedMessage();
givenRuntime();
givenBroker();
whenSubmittingReceivedMessage();
thenMessageForwardedToOneProcessingThread();
}
private void givenReceivedMessage() {
receivedMessage = mock(ReceivedMessage.class);
payload = mock(OriginalAndMarshaledMessage.class);
Message originalMessage = mock(Message.class);
when(payload.original()).thenReturn(originalMessage);
when(receivedMessage.message()).thenReturn(payload);
}
private ReceivedMessage receivedMessage;
private OriginalAndMarshaledMessage payload;
private void givenRuntime() {
threadPool = mock(MessageProcessingThreadPool.class);
when(threadPool.size()).thenReturn(THREAD_POOL_SIZE);
applicationPerformanceMonitoring = mock(ApplicationPerformanceMonitoring.class);
messageConsumptionHandler = mock(MessageConsumptionHandler.class);
listenersSet = mock(ListenersSet.class);
MessageListener listener = mock(MessageListener.class);
List<MessageListener> listeners = asList(listener);
when(listenersSet.messageListenersOf(any())).thenReturn(listeners);
}
private MessageProcessingThreadPool threadPool;
private static final int THREAD_POOL_SIZE = 42;
private ApplicationPerformanceMonitoring applicationPerformanceMonitoring;
private MessageConsumptionHandler messageConsumptionHandler;
private ListenersSet listenersSet;
private void givenBroker() {
broker = new MessageBroker.Builder()
.messageConsumptionContext(new MessageConsumptionContext.Builder()
.applicationPerformanceMonitoring(applicationPerformanceMonitoring)
.messageConsumptionHandler(messageConsumptionHandler)
.messageConsumptionConfiguration(MessageConsumptionConfiguration.defaultConfiguration())
.build())
.messageProcessingThreadsPool(threadPool)
.listenersSet(listenersSet)
.build();
}
private MessageBroker broker;
private void whenSubmittingReceivedMessage() {
broker.dispatch(receivedMessage);
}
private void thenMessageForwardedToOneProcessingThread() {
ArgumentCaptor<Integer> threadIdCaptor = ArgumentCaptor.forClass(Integer.class);
ArgumentCaptor<MessageToProcess> captor = ArgumentCaptor.forClass(MessageToProcess.class);
verify(threadPool).submit(threadIdCaptor.capture(), captor.capture());
MessageToProcess messageToProcess = captor.getValue();
assertThat(messageToProcess.messageListenerGroup().message(), is(payload));
}
@Test
public void receivedMessageAckedWhenAllProcessed() {
givenAutoAckingThreadPool();
givenBroker();
givenReceivedMessage();
whenSubmittingReceivedMessage();
thenReceivedMessageAcked();
}
private void givenAutoAckingThreadPool() {
givenRuntime();
doAnswer(autoAck()).when(threadPool).submit(any(Integer.class), any(MessageToProcess.class));
}
private Answer<Void> autoAck() {
return invocation -> {
int threadId = invocation.getArgument(0);
MessageToProcess messageToProcess = invocation.getArgument(1);
messageToProcess.signalProcessed(threadId);
return null;
};
}
private void thenReceivedMessageAcked() {
verify(receivedMessage).ack();
}
}
|
3e1256b31fec050af0b03b89ecafee7dcccbf911 | 156 | java | Java | javabase/src/main/java/com/zbase/throwsexcdiff/ChildIfaceOne.java | niteshbisht/alg_dynamix | da6e4a1444b1f2e96da027ed29d0a81b92605548 | [
"MIT"
] | null | null | null | javabase/src/main/java/com/zbase/throwsexcdiff/ChildIfaceOne.java | niteshbisht/alg_dynamix | da6e4a1444b1f2e96da027ed29d0a81b92605548 | [
"MIT"
] | null | null | null | javabase/src/main/java/com/zbase/throwsexcdiff/ChildIfaceOne.java | niteshbisht/alg_dynamix | da6e4a1444b1f2e96da027ed29d0a81b92605548 | [
"MIT"
] | null | null | null | 26 | 64 | 0.794872 | 7,735 | package com.zbase.throwsexcdiff;
public interface ChildIfaceOne extends BaseIface {
public void methdodThr(int[] arY) throws NullPointerException;
}
|
3e12573b05fbd044e7bdce367f183cdf1ffe94b6 | 775 | java | Java | pac4j-oauth/src/main/java/org/pac4j/oauth/profile/wordpress/WordPressLinks.java | aruis/pac4j | 9335962fe601319a18504e9fbab9bb46e1d10b8f | [
"Apache-2.0"
] | 2,073 | 2015-01-06T12:05:25.000Z | 2022-03-30T14:54:38.000Z | pac4j-oauth/src/main/java/org/pac4j/oauth/profile/wordpress/WordPressLinks.java | aruis/pac4j | 9335962fe601319a18504e9fbab9bb46e1d10b8f | [
"Apache-2.0"
] | 1,088 | 2015-01-06T08:31:22.000Z | 2022-03-29T06:59:55.000Z | pac4j-oauth/src/main/java/org/pac4j/oauth/profile/wordpress/WordPressLinks.java | aruis/pac4j | 9335962fe601319a18504e9fbab9bb46e1d10b8f | [
"Apache-2.0"
] | 678 | 2015-01-26T12:23:12.000Z | 2022-03-31T06:30:16.000Z | 17.222222 | 69 | 0.628387 | 7,736 | package org.pac4j.oauth.profile.wordpress;
import java.io.Serializable;
/**
* This class represents the links in WordPress.
*
* @author Jerome Leleu
* @since 1.1.0
*/
public final class WordPressLinks implements Serializable {
private static final long serialVersionUID = 650184033370922722L;
private String self;
private String help;
private String site;
public String getSelf() {
return self;
}
public void setSelf(String self) {
this.self = self;
}
public String getHelp() {
return help;
}
public void setHelp(String help) {
this.help = help;
}
public String getSite() {
return site;
}
public void setSite(String site) {
this.site = site;
}
}
|
3e12575f6672fe89ea83da0ddb25dfbdb2d62b5a | 937 | java | Java | app/src/main/java/pro/oblivioncoding/yonggan/airsofttac/MapUtils/ClusterMarkerItem.java | Y0ngg4n/AirsoftTac | a064a46ef158c403ae8b6df9fa3472fc6796555e | [
"Apache-2.0"
] | null | null | null | app/src/main/java/pro/oblivioncoding/yonggan/airsofttac/MapUtils/ClusterMarkerItem.java | Y0ngg4n/AirsoftTac | a064a46ef158c403ae8b6df9fa3472fc6796555e | [
"Apache-2.0"
] | null | null | null | app/src/main/java/pro/oblivioncoding/yonggan/airsofttac/MapUtils/ClusterMarkerItem.java | Y0ngg4n/AirsoftTac | a064a46ef158c403ae8b6df9fa3472fc6796555e | [
"Apache-2.0"
] | null | null | null | 22.853659 | 108 | 0.679829 | 7,737 | package pro.oblivioncoding.yonggan.airsofttac.MapUtils;
import androidx.annotation.NonNull;
import com.google.android.gms.maps.model.LatLng;
import com.google.maps.android.clustering.ClusterItem;
public class ClusterMarkerItem implements ClusterItem {
@NonNull
private final LatLng mPosition;
private String mTitle;
private String mSnippet;
public ClusterMarkerItem(final double lat, final double lng) {
mPosition = new LatLng(lat, lng);
}
public ClusterMarkerItem(final double lat, final double lng, final String title, final String snippet) {
mPosition = new LatLng(lat, lng);
mTitle = title;
mSnippet = snippet;
}
@NonNull
@Override
public LatLng getPosition() {
return mPosition;
}
@Override
public String getTitle() {
return mTitle;
}
@Override
public String getSnippet() {
return mSnippet;
}
}
|
3e12576e319c01bae3341e4155b716c11c54eb7e | 2,069 | java | Java | core/src/main/java/org/openstack4j/model/storage/object/SwiftObject.java | octetnest/openstack4j | 9bd9f66d61f17662d70fd22deb65ebd03cf4b353 | [
"Apache-2.0"
] | 204 | 2016-05-14T12:06:15.000Z | 2022-03-07T09:45:52.000Z | core/src/main/java/org/openstack4j/model/storage/object/SwiftObject.java | octetnest/openstack4j | 9bd9f66d61f17662d70fd22deb65ebd03cf4b353 | [
"Apache-2.0"
] | 721 | 2016-05-13T06:51:32.000Z | 2022-01-13T17:44:40.000Z | core/src/main/java/org/openstack4j/model/storage/object/SwiftObject.java | octetnest/openstack4j | 9bd9f66d61f17662d70fd22deb65ebd03cf4b353 | [
"Apache-2.0"
] | 291 | 2016-05-13T05:58:13.000Z | 2022-03-07T09:43:36.000Z | 22.247312 | 82 | 0.60609 | 7,738 | package org.openstack4j.model.storage.object;
import java.util.Date;
import java.util.Map;
import org.openstack4j.model.ModelEntity;
import org.openstack4j.model.common.DLPayload;
import org.openstack4j.model.storage.block.options.DownloadOptions;
/**
* Represents an Object which is a File or Directory within a Container
*
* @author Jeremy Unruh
*/
public interface SwiftObject extends ModelEntity {
/**
* The MD5 checksum value of the object content.
*
* @return the MD5 checksum
*/
String getETag();
/**
* The date and time when the object was last modified.
*
* @return the last modified date
*/
Date getLastModified();
/**
* The total number of bytes that are stored in Object Storage for the account
*
* @return total number of bytes
*/
long getSizeInBytes();
/**
* The name of the object
*
* @return the name of the object
*/
String getName();
/**
* The name of the directory
*
* @return the name of the directory
*/
String getDirectoryName();
/**
* The content type of the object
*
* @return the content type
*/
String getMimeType();
/**
* @return the container name this object belongs to
*/
String getContainerName();
/**
* Determines if this object is a pseudo directory
*
* @return true if this is a directory
*/
boolean isDirectory();
/**
* Gets the object metadata (this is a lazy fetch)
*
* @return the metadata for this object
*/
Map<String, String> getMetadata();
/**
* Retrieves the Payload for the data backing the current object
*
* @return the download payload
*/
DLPayload download();
/**
* Retrieves the Payload for the data backing the current object
*
* @param options the download options
* @return the download payload
*/
DLPayload download(DownloadOptions options);
}
|
3e12598f208d8e353089d4a91c7dbe542956d17d | 104 | java | Java | src/main/java/jp/mzw/jsanalyzer/revmutator/tracer/ExecTracer.java | mzw/JSAnalyzer | 9eee065609ee3464951c245cf250d8c7f699df8d | [
"Apache-2.0"
] | null | null | null | src/main/java/jp/mzw/jsanalyzer/revmutator/tracer/ExecTracer.java | mzw/JSAnalyzer | 9eee065609ee3464951c245cf250d8c7f699df8d | [
"Apache-2.0"
] | null | null | null | src/main/java/jp/mzw/jsanalyzer/revmutator/tracer/ExecTracer.java | mzw/JSAnalyzer | 9eee065609ee3464951c245cf250d8c7f699df8d | [
"Apache-2.0"
] | null | null | null | 11.555556 | 44 | 0.721154 | 7,739 | package jp.mzw.jsanalyzer.revmutator.tracer;
public class ExecTracer {
public ExecTracer() {
}
}
|
3e12599e65355f4b7aa82cdda0d4d3c5e375f0bc | 2,440 | java | Java | aws-java-sdk-sqs/src/main/java/com/amazonaws/services/sqs/model/transform/TagQueueRequestMarshaller.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 3,372 | 2015-01-03T00:35:43.000Z | 2022-03-31T15:56:24.000Z | aws-java-sdk-sqs/src/main/java/com/amazonaws/services/sqs/model/transform/TagQueueRequestMarshaller.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 2,391 | 2015-01-01T12:55:24.000Z | 2022-03-31T08:01:50.000Z | aws-java-sdk-sqs/src/main/java/com/amazonaws/services/sqs/model/transform/TagQueueRequestMarshaller.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 2,876 | 2015-01-01T14:38:37.000Z | 2022-03-29T19:53:10.000Z | 38.125 | 119 | 0.691393 | 7,740 | /*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.sqs.model.transform;
import java.util.Map;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.sqs.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;
/**
* TagQueueRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class TagQueueRequestMarshaller implements Marshaller<Request<TagQueueRequest>, TagQueueRequest> {
public Request<TagQueueRequest> marshall(TagQueueRequest tagQueueRequest) {
if (tagQueueRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
Request<TagQueueRequest> request = new DefaultRequest<TagQueueRequest>(tagQueueRequest, "AmazonSQS");
request.addParameter("Action", "TagQueue");
request.addParameter("Version", "2012-11-05");
request.setHttpMethod(HttpMethodName.POST);
if (tagQueueRequest.getQueueUrl() != null) {
request.addParameter("QueueUrl", StringUtils.fromString(tagQueueRequest.getQueueUrl()));
}
java.util.Map<String, String> tags = tagQueueRequest.getTags();
int tagsListIndex = 1;
for (Map.Entry<String, String> entry : tags.entrySet()) {
if (entry != null && entry.getKey() != null) {
request.addParameter("Tags." + tagsListIndex + ".Key", StringUtils.fromString(entry.getKey()));
}
if (entry != null && entry.getValue() != null) {
request.addParameter("Tags." + tagsListIndex + ".Value", StringUtils.fromString(entry.getValue()));
}
tagsListIndex++;
}
return request;
}
}
|
3e1259a1aa39df7ce840dfa6cff8eb27e545fa09 | 1,010 | java | Java | src/main/java/br/com/zup/transacoes/config/SecurityConfig.java | christian-moura/orange-talents-07-template-transacao | a82f44035d565ace5d110fb799d0952cdabf6598 | [
"Apache-2.0"
] | null | null | null | src/main/java/br/com/zup/transacoes/config/SecurityConfig.java | christian-moura/orange-talents-07-template-transacao | a82f44035d565ace5d110fb799d0952cdabf6598 | [
"Apache-2.0"
] | null | null | null | src/main/java/br/com/zup/transacoes/config/SecurityConfig.java | christian-moura/orange-talents-07-template-transacao | a82f44035d565ace5d110fb799d0952cdabf6598 | [
"Apache-2.0"
] | null | null | null | 50.5 | 124 | 0.784158 | 7,741 | package br.com.zup.transacoes.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests(authorizeRequests -> authorizeRequests
.antMatchers(HttpMethod.GET, "/api/transacao/**").hasAuthority("SCOPE_financeiro")
//.antMatchers(HttpMethod.POST, "/api/transacao/**").hasAuthority("SCOPE_financeiro")
.anyRequest().authenticated()
).oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
}
}
|
3e125b51421f4a291daeb727c5e14e41623a81f7 | 711 | java | Java | code/packaging/app-config/src/main/java/io/cattle/platform/app/MetricsConfig.java | wlcumt/cattlewl | d709bde3a0d7cb17b6a8a1bb4685681330bc625a | [
"Apache-2.0"
] | 482 | 2015-07-13T21:32:27.000Z | 2022-01-09T02:06:57.000Z | code/packaging/app-config/src/main/java/io/cattle/platform/app/MetricsConfig.java | wlcumt/cattlewl | d709bde3a0d7cb17b6a8a1bb4685681330bc625a | [
"Apache-2.0"
] | 1,116 | 2015-07-09T17:52:53.000Z | 2022-01-03T18:07:24.000Z | code/packaging/app-config/src/main/java/io/cattle/platform/app/MetricsConfig.java | wlcumt/cattlewl | d709bde3a0d7cb17b6a8a1bb4685681330bc625a | [
"Apache-2.0"
] | 230 | 2015-07-12T04:40:05.000Z | 2022-02-03T02:13:42.000Z | 22.935484 | 60 | 0.755274 | 7,742 | package io.cattle.platform.app;
import io.cattle.platform.metrics.util.MetricsStartup;
import io.cattle.platform.metrics.util.MetricsUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.health.HealthCheckRegistry;
@Configuration
public class MetricsConfig {
@Bean
MetricsStartup MetricsStartup() {
return new MetricsStartup();
}
@Bean
MetricRegistry MetricsRegistry() {
return MetricsUtil.getRegistry();
}
@Bean
HealthCheckRegistry HealthCheckRegistry() {
return MetricsUtil.getHealthCheckRegistry();
}
} |
3e125cc633f5ce5b83c5bcd3e0a06682e02158bf | 505 | java | Java | _src/Chapter05/jeepatterns/model/Professor.java | paullewallencom/java-978-1-7888-3062-1 | 027a1ab280ae74de2454c80491c5f573c0356c08 | [
"Apache-2.0"
] | 19 | 2018-08-13T13:47:39.000Z | 2022-01-11T02:25:20.000Z | _src/Chapter05/jeepatterns/model/Professor.java | paullewallencom/java-978-1-7888-3062-1 | 027a1ab280ae74de2454c80491c5f573c0356c08 | [
"Apache-2.0"
] | 6 | 2021-12-10T01:55:47.000Z | 2021-12-14T21:59:07.000Z | _src/Chapter05/jeepatterns/model/Professor.java | paullewallencom/java-978-1-7888-3062-1 | 027a1ab280ae74de2454c80491c5f573c0356c08 | [
"Apache-2.0"
] | 16 | 2018-09-16T05:58:59.000Z | 2022-01-14T16:59:36.000Z | 16.833333 | 56 | 0.742574 | 7,743 | package book.jeepatterns.model;
import java.time.LocalDate;
public class Professor extends Member {
private LocalDate initTeachDate;
public Professor() {
}
public Professor(String name, LocalDate initDate) {
this.setName(name);
this.setInitDate(initDate);
}
public Professor(String name) {
this.setName(name);
}
public LocalDate getInitTeachDate() {
return initTeachDate;
}
public void setInitTeachDate(LocalDate initTeachDate) {
this.initTeachDate = initTeachDate;
}
}
|
3e125d8ff0b22696b414130cc68353637834b40c | 1,544 | java | Java | src/main/java/org/devzendo/minimiser/wiring/lifecycle/StartupQueueHelperInitialisingLifecycle.java | devzendo/mini-miser | ca5fc0ffd7f9d4f39d378759df9946bd4f0e1c89 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/devzendo/minimiser/wiring/lifecycle/StartupQueueHelperInitialisingLifecycle.java | devzendo/mini-miser | ca5fc0ffd7f9d4f39d378759df9946bd4f0e1c89 | [
"Apache-2.0"
] | 1 | 2022-01-21T23:38:27.000Z | 2022-01-21T23:38:27.000Z | src/main/java/org/devzendo/minimiser/wiring/lifecycle/StartupQueueHelperInitialisingLifecycle.java | devzendo/mini-miser | ca5fc0ffd7f9d4f39d378759df9946bd4f0e1c89 | [
"Apache-2.0"
] | null | null | null | 28.592593 | 81 | 0.705959 | 7,744 | /**
* Copyright (C) 2008-2010 Matt Gumbley, DevZendo.org <http://devzendo.org>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.devzendo.minimiser.wiring.lifecycle;
import org.devzendo.commonapp.lifecycle.Lifecycle;
import org.devzendo.commonapp.spring.springloader.SpringLoader;
import org.devzendo.minimiser.startupqueue.StartupQueueHelper;
/**
* Initialises the Startup Queue Helper toolkit.
*
* @author matt
*
*/
public final class StartupQueueHelperInitialisingLifecycle implements Lifecycle {
private final SpringLoader springLoader;
/**
* Stash the SpringLoader for passing on to the toolkit.
* @param loader the SpringLoader
*/
public StartupQueueHelperInitialisingLifecycle(final SpringLoader loader) {
this.springLoader = loader;
}
/**
* {@inheritDoc}
*/
public void shutdown() {
// nothing
}
/**
* {@inheritDoc}
*/
public void startup() {
StartupQueueHelper.initialise(springLoader);
}
}
|
3e125e0cfbe38059c04e179c4efdc748aa15202d | 8,573 | java | Java | platform/platform-impl/src/com/intellij/openapi/application/ImportOldConfigsPanel.java | dmarcotte/intellij-community | 74ed654c3f9ed99f9cc84fa227846b2c38d683c0 | [
"Apache-2.0"
] | null | null | null | platform/platform-impl/src/com/intellij/openapi/application/ImportOldConfigsPanel.java | dmarcotte/intellij-community | 74ed654c3f9ed99f9cc84fa227846b2c38d683c0 | [
"Apache-2.0"
] | null | null | null | platform/platform-impl/src/com/intellij/openapi/application/ImportOldConfigsPanel.java | dmarcotte/intellij-community | 74ed654c3f9ed99f9cc84fa227846b2c38d683c0 | [
"Apache-2.0"
] | 1 | 2019-03-14T10:35:19.000Z | 2019-03-14T10:35:19.000Z | 34.568548 | 119 | 0.686574 | 7,745 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.application;
import com.intellij.openapi.MnemonicHelper;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.PathUtil;
import com.intellij.util.ThreeState;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
/**
* @author max
*/
public class ImportOldConfigsPanel extends JDialog {
private TextFieldWithBrowseButton myPrevInstallation;
private JRadioButton myRbDoNotImport;
private JRadioButton myRbImport;
private JPanel myRootPanel;
private File myLastSelection = null;
private JButton myOkButton;
private JLabel mySuggestLabel;
private JLabel myHomeLabel;
private JRadioButton myRbImportAuto;
private final File myGuessedOldConfig;
private final ConfigImportSettings mySettings;
public ImportOldConfigsPanel(final File guessedOldConfig, final Frame owner, ConfigImportSettings settings) {
super(owner, true);
myGuessedOldConfig = guessedOldConfig;
mySettings = settings;
init();
}
public ImportOldConfigsPanel(final File guessedOldConfig, ConfigImportSettings settings) {
super((Dialog) null, true);
myGuessedOldConfig = guessedOldConfig;
mySettings = settings;
init();
}
private void init() {
new MnemonicHelper().register(getContentPane());
ButtonGroup group = new ButtonGroup();
group.add(myRbDoNotImport);
group.add(myRbImport);
group.add(myRbImportAuto);
myRbDoNotImport.setSelected(true);
final String productName = mySettings.getProductName(ThreeState.UNSURE);
mySuggestLabel.setText(mySettings.getTitleLabel(productName));
myRbDoNotImport.setText(mySettings.getDoNotImportLabel(productName));
if(myGuessedOldConfig != null) {
myRbImportAuto.setText(mySettings.getAutoImportLabel(myGuessedOldConfig));
myRbImportAuto.setSelected(true);
} else {
myRbImportAuto.setVisible(false);
}
myHomeLabel.setText(mySettings.getHomeLabel(productName));
myRbImport.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
update();
}
});
if (myGuessedOldConfig != null) {
myPrevInstallation.setText(myGuessedOldConfig.getParent());
}
else if (SystemInfo.isMac) {
myPrevInstallation.setText(findPreviousInstallationMac(productName));
}
else if (SystemInfo.isWindows) {
String prevInstall = findPreviousInstallationWindows(productName);
if (prevInstall != null) {
myPrevInstallation.setText(prevInstall);
}
}
myPrevInstallation.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
if (myLastSelection != null){
fc = new JFileChooser(myLastSelection);
}
fc.setFileSelectionMode(SystemInfo.isMac ? JFileChooser.FILES_AND_DIRECTORIES : JFileChooser.DIRECTORIES_ONLY);
fc.setFileHidingEnabled(!SystemInfo.isLinux);
int returnVal = fc.showOpenDialog(ImportOldConfigsPanel.this);
if (returnVal == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
if (file != null){
myLastSelection = file;
myPrevInstallation.setText(file.getAbsolutePath());
}
}
}
});
myOkButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
close();
}
});
getContentPane().setLayout(new BorderLayout());
getContentPane().add(myRootPanel);
getRootPane().setDefaultButton(myOkButton);
setTitle(ApplicationBundle.message("title.complete.installation"));
update();
pack();
Dimension parentSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension ownSize = getPreferredSize();
setLocation((parentSize.width - ownSize.width) / 2, (parentSize.height - ownSize.height) / 2);
}
@Nullable
private static String findPreviousInstallationWindows(String productName) {
String programFiles = System.getenv("ProgramFiles");
if (programFiles != null) {
File jetbrainsHome = new File(programFiles, "JetBrains");
if (jetbrainsHome.isDirectory()) {
final File[] files = jetbrainsHome.listFiles();
String latestVersion = null;
File latestFile = null;
for (File file : files) {
if (file.isDirectory() && file.getName().startsWith(productName)) {
String versionName = file.getName().substring(productName.length()).trim();
if (latestVersion == null || StringUtil.compareVersionNumbers(latestVersion, versionName) > 0) {
latestVersion = versionName;
latestFile = file;
}
}
}
if (latestFile != null) {
return latestFile.getAbsolutePath();
}
}
}
return null;
}
private static String findPreviousInstallationMac(String productName) {
//noinspection HardCodedStringLiteral
final String mostProbable = "/Applications/" + productName;
if (new File(mostProbable).exists()) {
return mostProbable;
}
return "/Applications";
}
private void close() {
if (myRbImport.isSelected()) {
final String productWithVendor = mySettings.getProductName(ThreeState.YES);
String instHome;
if (myPrevInstallation.getText() != null) {
instHome = FileUtil.toSystemDependentName(PathUtil.getCanonicalPath(myPrevInstallation.getText()));
}
else {
instHome = null;
}
if (StringUtil.isEmpty(instHome)) {
JOptionPane.showMessageDialog(this,
mySettings.getEmptyHomeErrorText(productWithVendor),
mySettings.getInstallationHomeRequiredTitle(), JOptionPane.ERROR_MESSAGE);
return;
}
String currentInstanceHomePath = PathManager.getHomePath();
if (SystemInfo.isFileSystemCaseSensitive
? currentInstanceHomePath.equals(instHome)
: currentInstanceHomePath.equalsIgnoreCase(instHome)) {
JOptionPane.showMessageDialog(this,
mySettings.getCurrentHomeErrorText(productWithVendor),
mySettings.getInstallationHomeRequiredTitle(), JOptionPane.ERROR_MESSAGE);
return;
}
assert instHome != null;
if (myRbImport.isSelected() && !ConfigImportHelper.isInstallationHomeOrConfig(instHome, mySettings)) {
JOptionPane.showMessageDialog(this,
mySettings.getInvalidHomeErrorText(productWithVendor, instHome),
mySettings.getInstallationHomeRequiredTitle(), JOptionPane.ERROR_MESSAGE);
return;
}
if (!new File(instHome).canRead()) {
JOptionPane.showMessageDialog(this,
mySettings.getInaccessibleHomeErrorText(instHome),
mySettings.getInstallationHomeRequiredTitle(), JOptionPane.ERROR_MESSAGE);
return;
}
}
dispose();
}
public boolean isImportEnabled() {
return myRbImport.isSelected() || myRbImportAuto.isSelected();
}
public File getSelectedFile() {
return myRbImportAuto.isSelected() ? myGuessedOldConfig : new File(myPrevInstallation.getText());
}
private void update() {
myPrevInstallation.setEnabled(myRbImport.isSelected());
}
public static void main(String[] args) {
ImportOldConfigsPanel dlg = new ImportOldConfigsPanel(null, new ConfigImportSettings());
dlg.setVisible(true);
}
}
|
3e125ecb1b3326dfb1f728ee7fea3893be2e236c | 333 | java | Java | CniaoPlay/app/src/main/java/com/qinlong275/android/cniaoplay/common/imageloader/LoaderListener.java | Qinlong275/MyProject | 9df1347597f8df563215c4e2bae60e6104f24076 | [
"Apache-2.0"
] | 1 | 2018-02-11T15:55:03.000Z | 2018-02-11T15:55:03.000Z | CniaoPlay/app/src/main/java/com/qinlong275/android/cniaoplay/common/imageloader/LoaderListener.java | Qinlong275/MyProject | 9df1347597f8df563215c4e2bae60e6104f24076 | [
"Apache-2.0"
] | null | null | null | CniaoPlay/app/src/main/java/com/qinlong275/android/cniaoplay/common/imageloader/LoaderListener.java | Qinlong275/MyProject | 9df1347597f8df563215c4e2bae60e6104f24076 | [
"Apache-2.0"
] | null | null | null | 17.526316 | 60 | 0.705706 | 7,746 | package com.qinlong275.android.cniaoplay.common.imageloader;
/**
* 菜鸟窝http://www.cniao5.com 一个高端的互联网技能学习平台
*
* @author Ivan
* @version V1.0
* @Package com.cniao5.cniao5market.common.imageloader
* @Description: ${TODO}(用一句话描述该文件做什么)
* @date
*/
public interface LoaderListener {
void onSuccess();
void onError();
}
|
3e125f01ea15d625cc7fb0bc75704204f58eb116 | 1,252 | java | Java | src/test/java/com/divae/firstspirit/or/EntityListMockTest.java | heikobarthel/firstspirit-mocks | e3777d2afd8b767c87db6ebec261f0b884b61f7d | [
"Apache-2.0"
] | 1 | 2017-10-24T11:45:44.000Z | 2017-10-24T11:45:44.000Z | src/test/java/com/divae/firstspirit/or/EntityListMockTest.java | heikobarthel/firstspirit-mocks | e3777d2afd8b767c87db6ebec261f0b884b61f7d | [
"Apache-2.0"
] | 2 | 2018-08-14T08:01:02.000Z | 2018-08-17T07:53:04.000Z | src/test/java/com/divae/firstspirit/or/EntityListMockTest.java | heikobarthel/firstspirit-mocks | e3777d2afd8b767c87db6ebec261f0b884b61f7d | [
"Apache-2.0"
] | 2 | 2018-08-17T06:06:37.000Z | 2022-02-16T10:02:50.000Z | 31.3 | 86 | 0.736422 | 7,747 | package com.divae.firstspirit.or;
import com.divae.firstspirit.MockTest;
import de.espirit.or.EntityList;
import de.espirit.or.schema.Entity;
import org.junit.Test;
import java.util.UUID;
import static com.divae.firstspirit.BuilderMock.build;
import static com.divae.firstspirit.or.EntityListMock.entityListWith;
import static com.divae.firstspirit.or.schema.EntityMock.entityWith;
import static java.lang.Boolean.FALSE;
import static java.util.Collections.singletonList;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class EntityListMockTest extends MockTest {
@Override
protected Class<?> getFactoryClass() {
return EntityListMock.class;
}
@Test
public void testValues() {
Entity entity = build(entityWith(new UUID(0, 0)));
EntityList entityList = build(entityListWith().values(singletonList(entity)));
assertThat(entityList.size(), is(1));
assertThat(entityList.isEmpty(), is(FALSE));
assertThat(entityList.get(0), is(entity));
}
@Test(expected = IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {
EntityList entityList = build(entityListWith());
entityList.get(6);
}
}
|
3e125f3fdd2d29280b95d60a6bb359a67c49d8b3 | 866 | java | Java | src/main/java/org/mnode/ical4j/serializer/schema/SchemaPlaceBuilder.java | ical4j/ical4j-json | 450d1d46ff22ed82267e100923cad92b995547fb | [
"BSD-3-Clause"
] | 1 | 2021-12-19T11:20:28.000Z | 2021-12-19T11:20:28.000Z | src/main/java/org/mnode/ical4j/serializer/schema/SchemaPlaceBuilder.java | ical4j/ical4j-serializer | 459228044b9d1347b34f84bc8637138883def330 | [
"BSD-3-Clause"
] | 2 | 2021-11-19T05:57:40.000Z | 2021-12-17T20:51:13.000Z | src/main/java/org/mnode/ical4j/serializer/schema/SchemaPlaceBuilder.java | ical4j/ical4j-json | 450d1d46ff22ed82267e100923cad92b995547fb | [
"BSD-3-Clause"
] | 1 | 2022-03-24T11:33:07.000Z | 2022-03-24T11:33:07.000Z | 34.64 | 78 | 0.714781 | 7,748 | package org.mnode.ical4j.serializer.schema;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import net.fortuna.ical4j.vcard.Property;
import net.fortuna.ical4j.vcard.VCard;
public class SchemaPlaceBuilder extends AbstractSchemaBuilder<VCard> {
public SchemaPlaceBuilder() {
super("Place");
}
@Override
public JsonNode build() {
ObjectNode node = createObjectNode();
putIfNotNull("@id", node, component.getProperty(Property.Id.UID));
putIfNotNull("name", node, component.getProperty(Property.Id.FN));
putIfNotNull("image", node, component.getProperty(Property.Id.PHOTO));
putIfNotNull("url", node, component.getProperty(Property.Id.URL));
setObject("address", node, component.getProperty(Property.Id.ADR));
return node;
}
}
|
3e125f4d6037a010cde9adbaf701bad680da5635 | 1,359 | java | Java | omf-impl/src/test/java/org/om/core/impl/persistence/interceptor/handler/ReferencePropertyHandlerTest.java | teverett/omf | 30cbac79ecfc6278ba3e1b4bae42561e441d7b50 | [
"Apache-2.0"
] | null | null | null | omf-impl/src/test/java/org/om/core/impl/persistence/interceptor/handler/ReferencePropertyHandlerTest.java | teverett/omf | 30cbac79ecfc6278ba3e1b4bae42561e441d7b50 | [
"Apache-2.0"
] | 7 | 2021-01-15T06:11:32.000Z | 2022-03-03T00:43:30.000Z | omf-impl/src/test/java/org/om/core/impl/persistence/interceptor/handler/ReferencePropertyHandlerTest.java | teverett/omf | 30cbac79ecfc6278ba3e1b4bae42561e441d7b50 | [
"Apache-2.0"
] | null | null | null | 31.604651 | 128 | 0.759382 | 7,749 | package org.om.core.impl.persistence.interceptor.handler;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import org.jmock.*;
import org.jmock.integration.junit4.*;
import org.junit.*;
import org.junit.runner.*;
import org.om.core.api.mapping.*;
import org.om.core.api.persistence.*;
import org.om.core.api.session.*;
import org.om.core.impl.test.*;
@RunWith(JMock.class)
public class ReferencePropertyHandlerTest {
private Session session;
private final Mockery mockery = new JUnit4Mockery();
@Before
public void setUp() {
session = mockery.mock(Session.class);
}
@Test
@Ignore
public void test() {
mockery.checking(new Expectations() {
{
oneOf(session).get(EntityWithPrimitiveProperties.class, "/foo/bar");
}
});
final ReferenceHandler handler = new ReferenceHandler(session);
final PersistenceAdapter delegate = new TestingPassThroughPersistenceAdapter("/foo/bar");
final MappedField mappedField = new MappedFieldBuilder().withName("mappedField").withType(EntityWithPrimitiveProperties.class)
.withReferenceMapping("fieldname", EntityWithPrimitiveProperties.class, "path").create();
final Object retrieve = handler.retrieve(mappedField, delegate);
assertThat(retrieve, notNullValue());
System.out.println("ReferencePropertyHandlerTest.test() " + retrieve);
fail("implement me");
}
}
|
3e125f944198b64f6578a37503a05c178a05153a | 3,022 | java | Java | app/src/main/java/com/google/android/stardroid/source/impl/AstronomicalSourceImpl.java | MLDFRJDN/stardroid | f726e16cc3fd33420a0297224cb013f79574b225 | [
"Apache-2.0"
] | 608 | 2015-06-18T02:08:24.000Z | 2022-03-23T21:45:05.000Z | app/src/main/java/com/google/android/stardroid/source/impl/AstronomicalSourceImpl.java | MLDFRJDN/stardroid | f726e16cc3fd33420a0297224cb013f79574b225 | [
"Apache-2.0"
] | 278 | 2015-06-18T02:25:09.000Z | 2022-02-19T15:33:33.000Z | app/src/main/java/com/google/android/stardroid/source/impl/AstronomicalSourceImpl.java | MLDFRJDN/stardroid | f726e16cc3fd33420a0297224cb013f79574b225 | [
"Apache-2.0"
] | 282 | 2015-06-18T02:09:41.000Z | 2022-01-21T07:24:15.000Z | 25.82906 | 79 | 0.720384 | 7,750 | // Copyright 2009 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.android.stardroid.source.impl;
import java.util.ArrayList;
import com.google.android.stardroid.source.ImageSource;
import com.google.android.stardroid.source.LineSource;
import com.google.android.stardroid.source.PointSource;
import com.google.android.stardroid.source.TextSource;
/**
* Simple class for implementing the AstronomicalSource interface. We may merge
* the two in the future (but for now, this lets us do some parallel
* development).
*
*
* @author Brent Bryan
*/
public class AstronomicalSourceImpl {
private float level;
private ArrayList<String> names;
private ArrayList<ImageSource> imageSources;
private ArrayList<LineSource> lineSources;
private ArrayList<PointSource> pointSources;
private ArrayList<TextSource> textSources;
public ArrayList<String> getNames() {
return names;
}
public void setNames(ArrayList<String> names) {
this.names = names;
}
public float getLevel() {
return level;
}
public void setLevel(float level) {
this.level = level;
}
public ArrayList<ImageSource> getImageSources() {
return imageSources;
}
public void setImageSources(ArrayList<ImageSource> imageSources) {
this.imageSources = imageSources;
}
public ArrayList<LineSource> getLineSources() {
return lineSources;
}
public void setLineSources(ArrayList<LineSource> lineSources) {
this.lineSources = lineSources;
}
public ArrayList<PointSource> getPointSources() {
return pointSources;
}
public void setPointSources(ArrayList<PointSource> pointSources) {
this.pointSources = pointSources;
}
public ArrayList<TextSource> getTextSources() {
return textSources;
}
public void setTextSources(ArrayList<TextSource> textSources) {
this.textSources = textSources;
}
public void addPoint(PointSource point) {
if (point == null) {
pointSources = new ArrayList<PointSource>();
}
pointSources.add(point);
}
public void addLabel(TextSource label) {
if (label == null) {
textSources = new ArrayList<TextSource>();
}
textSources.add(label);
}
public void addImage(ImageSource image) {
if (image == null) {
imageSources = new ArrayList<ImageSource>();
}
imageSources.add(image);
}
public void addLine(LineSource line) {
if (line == null) {
lineSources = new ArrayList<LineSource>();
}
lineSources.add(line);
}
}
|
3e12605bee8e54ab32fb74ad2e38009a314b4713 | 511 | java | Java | Java101_PracticesAndProjects/ReverseTriangle/src/Main.java | GamzeYaman/Patika.devJavaProjects | 8e94de62ca2d490bcb66cd1dd6df13fc5f30b86b | [
"MIT"
] | null | null | null | Java101_PracticesAndProjects/ReverseTriangle/src/Main.java | GamzeYaman/Patika.devJavaProjects | 8e94de62ca2d490bcb66cd1dd6df13fc5f30b86b | [
"MIT"
] | null | null | null | Java101_PracticesAndProjects/ReverseTriangle/src/Main.java | GamzeYaman/Patika.devJavaProjects | 8e94de62ca2d490bcb66cd1dd6df13fc5f30b86b | [
"MIT"
] | null | null | null | 21.291667 | 58 | 0.422701 | 7,751 | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number : ");
int n = scan.nextInt();
for (int x = 0; x <= n; x++) {
for (int y = 0; y <= x; y++) {
System.out.print(" ");
}
for (int z = 1; z < (2 * n) - (2 * x); z++) {
System.out.print("*");
}
System.out.println("");
}
}
}
|
3e1260fa68cdd8d0efde0754c322c3473fbaa2d9 | 5,937 | java | Java | modules/thirdparty/batik/sources/org/apache/flex/forks/batik/bridge/SVGTextPathElementBridge.java | blackjyn/flex-sdk | 61aa3601c8c57f2855e18e11fa16f4180de42e05 | [
"ECL-2.0",
"Apache-2.0"
] | 173 | 2015-01-01T18:57:05.000Z | 2022-03-06T14:36:12.000Z | modules/thirdparty/batik/sources/org/apache/flex/forks/batik/bridge/SVGTextPathElementBridge.java | blackjyn/flex-sdk | 61aa3601c8c57f2855e18e11fa16f4180de42e05 | [
"ECL-2.0",
"Apache-2.0"
] | 12 | 2015-05-31T15:51:24.000Z | 2021-01-27T11:30:42.000Z | modules/thirdparty/batik/sources/org/apache/flex/forks/batik/bridge/SVGTextPathElementBridge.java | blackjyn/flex-sdk | 61aa3601c8c57f2855e18e11fa16f4180de42e05 | [
"ECL-2.0",
"Apache-2.0"
] | 122 | 2015-01-01T13:46:06.000Z | 2022-02-13T20:09:21.000Z | 39.919463 | 107 | 0.623571 | 7,752 | /*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.apache.flex.forks.batik.bridge;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import org.apache.flex.forks.batik.dom.util.XLinkSupport;
import org.apache.flex.forks.batik.gvt.text.TextPath;
import org.apache.flex.forks.batik.parser.AWTPathProducer;
import org.apache.flex.forks.batik.parser.ParseException;
import org.apache.flex.forks.batik.parser.PathParser;
import org.w3c.dom.Element;
/**
* Bridge class for the <textPath> element.
*
* @author <a href="mailto:dycjh@example.com">Bella Robinson</a>
* @version $Id: SVGTextPathElementBridge.java 501922 2007-01-31 17:47:47Z dvholten $
*/
public class SVGTextPathElementBridge extends AnimatableGenericSVGBridge
implements ErrorConstants {
/**
* Constructs a new bridge for the <textPath> element.
*/
public SVGTextPathElementBridge() {}
/**
* Returns 'textPath'.
*/
public String getLocalName() {
return SVG_TEXT_PATH_TAG;
}
public void handleElement(BridgeContext ctx, Element e) {
// We don't want to take over from the text content element.
}
/**
* Creates a TextPath object that represents the path along which the text
* is to be rendered.
*
* @param ctx The bridge context.
* @param textPathElement The <textPath> element.
*
* @return The new TextPath.
*/
public TextPath createTextPath(BridgeContext ctx, Element textPathElement) {
// get the referenced element
String uri = XLinkSupport.getXLinkHref(textPathElement);
Element pathElement = ctx.getReferencedElement(textPathElement, uri);
if ((pathElement == null) ||
(!SVG_NAMESPACE_URI.equals(pathElement.getNamespaceURI())) ||
(!pathElement.getLocalName().equals(SVG_PATH_TAG))) {
// couldn't find the referenced element
// or the referenced element was not a path
throw new BridgeException(ctx, textPathElement, ERR_URI_BAD_TARGET,
new Object[] {uri});
}
// construct a shape for the referenced path element
String s = pathElement.getAttributeNS(null, SVG_D_ATTRIBUTE);
Shape pathShape = null;
if (s.length() != 0) {
AWTPathProducer app = new AWTPathProducer();
app.setWindingRule(CSSUtilities.convertFillRule(pathElement));
try {
PathParser pathParser = new PathParser();
pathParser.setPathHandler(app);
pathParser.parse(s);
} catch (ParseException pEx ) {
throw new BridgeException
(ctx, pathElement, pEx, ERR_ATTRIBUTE_VALUE_MALFORMED,
new Object[] {SVG_D_ATTRIBUTE});
} finally {
pathShape = app.getShape();
}
} else {
throw new BridgeException(ctx, pathElement, ERR_ATTRIBUTE_MISSING,
new Object[] {SVG_D_ATTRIBUTE});
}
// if the reference path element has a transform apply the transform
// to the path shape
s = pathElement.getAttributeNS(null, SVG_TRANSFORM_ATTRIBUTE);
if (s.length() != 0) {
AffineTransform tr =
SVGUtilities.convertTransform(pathElement,
SVG_TRANSFORM_ATTRIBUTE, s, ctx);
pathShape = tr.createTransformedShape(pathShape);
}
// create the TextPath object that we are going to return
TextPath textPath = new TextPath(new GeneralPath(pathShape));
// set the start offset if specified
s = textPathElement.getAttributeNS(null, SVG_START_OFFSET_ATTRIBUTE);
if (s.length() > 0) {
float startOffset = 0;
int percentIndex = s.indexOf('%');
if (percentIndex != -1) {
// its a percentage of the length of the path
float pathLength = textPath.lengthOfPath();
String percentString = s.substring(0,percentIndex);
float startOffsetPercent = 0;
try {
startOffsetPercent = SVGUtilities.convertSVGNumber(percentString);
} catch (NumberFormatException e) {
startOffsetPercent = -1;
}
if (startOffsetPercent < 0) {
throw new BridgeException
(ctx, textPathElement, ERR_ATTRIBUTE_VALUE_MALFORMED,
new Object[] {SVG_START_OFFSET_ATTRIBUTE, s});
}
startOffset = (float)(startOffsetPercent * pathLength/100.0);
} else {
// its an absolute length
UnitProcessor.Context uctx = UnitProcessor.createContext(ctx, textPathElement);
startOffset = UnitProcessor.svgOtherLengthToUserSpace(s, SVG_START_OFFSET_ATTRIBUTE, uctx);
}
textPath.setStartOffset(startOffset);
}
return textPath;
}
}
|
3e12610753d7588cd086ae864913655acb40058d | 1,206 | java | Java | wayn-mall/src/main/java/com/wayn/mall/core/service/impl/GoodsServiceImpl.java | wayn111/waynboot-sso | 1286c8f70357b953d57c438a5ed4bc9b847e720b | [
"Apache-2.0"
] | 34 | 2020-04-27T00:52:37.000Z | 2022-03-27T16:15:20.000Z | wayn-mall/src/main/java/com/wayn/mall/core/service/impl/GoodsServiceImpl.java | zoukunbo/waynboot-sso | 4637281e0fb742d10602e0e6e0539f3114e0ecb9 | [
"Apache-2.0"
] | 2 | 2021-10-19T14:31:28.000Z | 2021-12-22T14:49:11.000Z | wayn-mall/src/main/java/com/wayn/mall/core/service/impl/GoodsServiceImpl.java | zoukunbo/waynboot-sso | 4637281e0fb742d10602e0e6e0539f3114e0ecb9 | [
"Apache-2.0"
] | 16 | 2020-04-14T07:34:10.000Z | 2022-03-27T16:15:23.000Z | 32.594595 | 106 | 0.779436 | 7,753 | package com.wayn.mall.core.service.impl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wayn.mall.core.dao.GoodsDao;
import com.wayn.mall.core.entity.Goods;
import com.wayn.mall.core.entity.vo.SearchObjVO;
import com.wayn.mall.core.entity.vo.SearchPageGoodsVO;
import com.wayn.mall.core.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsDao, Goods> implements GoodsService {
@Autowired
private GoodsDao goodsDao;
@Override
public IPage<Goods> selectPage(Page<Goods> page, Goods goods) {
return goodsDao.selectListPage(page, goods);
}
@Override
public IPage<Goods> findMallGoodsListBySearch(Page<SearchPageGoodsVO> page, SearchObjVO searchObjVO) {
return goodsDao.findMallGoodsListBySearch(page, searchObjVO);
}
@Override
public boolean addStock(Long goodsId, Integer goodsCount) {
return goodsDao.addStock(goodsId, goodsCount);
}
}
|
3e12610fadcea6ae9d01773f438f9d29bfca453b | 5,970 | java | Java | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/ReservationInterval.java | dmgerman/hadoop | 70c015914a8756c5440cd969d70dac04b8b6142b | [
"Apache-2.0"
] | null | null | null | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/ReservationInterval.java | dmgerman/hadoop | 70c015914a8756c5440cd969d70dac04b8b6142b | [
"Apache-2.0"
] | null | null | null | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/ReservationInterval.java | dmgerman/hadoop | 70c015914a8756c5440cd969d70dac04b8b6142b | [
"Apache-2.0"
] | null | null | null | 16.222826 | 814 | 0.776884 | 7,754 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
end_comment
begin_package
DECL|package|org.apache.hadoop.yarn.server.resourcemanager.reservation
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|resourcemanager
operator|.
name|reservation
package|;
end_package
begin_comment
comment|/** * This represents the time duration of the reservation * */
end_comment
begin_class
DECL|class|ReservationInterval
specifier|public
class|class
name|ReservationInterval
implements|implements
name|Comparable
argument_list|<
name|ReservationInterval
argument_list|>
block|{
DECL|field|startTime
specifier|private
specifier|final
name|long
name|startTime
decl_stmt|;
DECL|field|endTime
specifier|private
specifier|final
name|long
name|endTime
decl_stmt|;
DECL|method|ReservationInterval (long startTime, long endTime)
specifier|public
name|ReservationInterval
parameter_list|(
name|long
name|startTime
parameter_list|,
name|long
name|endTime
parameter_list|)
block|{
name|this
operator|.
name|startTime
operator|=
name|startTime
expr_stmt|;
name|this
operator|.
name|endTime
operator|=
name|endTime
expr_stmt|;
block|}
comment|/** * Get the start time of the reservation interval * * @return the startTime */
DECL|method|getStartTime ()
specifier|public
name|long
name|getStartTime
parameter_list|()
block|{
return|return
name|startTime
return|;
block|}
comment|/** * Get the end time of the reservation interval * * @return the endTime */
DECL|method|getEndTime ()
specifier|public
name|long
name|getEndTime
parameter_list|()
block|{
return|return
name|endTime
return|;
block|}
comment|/** * Returns whether the interval is active at the specified instant of time * * @param tick the instance of the time to check * @return true if active, false otherwise */
DECL|method|isOverlap (long tick)
specifier|public
name|boolean
name|isOverlap
parameter_list|(
name|long
name|tick
parameter_list|)
block|{
return|return
operator|(
name|startTime
operator|<=
name|tick
operator|&&
name|tick
operator|<=
name|endTime
operator|)
return|;
block|}
annotation|@
name|Override
DECL|method|compareTo (ReservationInterval anotherInterval)
specifier|public
name|int
name|compareTo
parameter_list|(
name|ReservationInterval
name|anotherInterval
parameter_list|)
block|{
name|long
name|diff
init|=
literal|0
decl_stmt|;
if|if
condition|(
name|startTime
operator|==
name|anotherInterval
operator|.
name|getStartTime
argument_list|()
condition|)
block|{
name|diff
operator|=
name|endTime
operator|-
name|anotherInterval
operator|.
name|getEndTime
argument_list|()
expr_stmt|;
block|}
else|else
block|{
name|diff
operator|=
name|startTime
operator|-
name|anotherInterval
operator|.
name|getStartTime
argument_list|()
expr_stmt|;
block|}
if|if
condition|(
name|diff
operator|<
literal|0
condition|)
block|{
return|return
operator|-
literal|1
return|;
block|}
elseif|else
if|if
condition|(
name|diff
operator|>
literal|0
condition|)
block|{
return|return
literal|1
return|;
block|}
else|else
block|{
return|return
literal|0
return|;
block|}
block|}
annotation|@
name|Override
DECL|method|hashCode ()
specifier|public
name|int
name|hashCode
parameter_list|()
block|{
specifier|final
name|int
name|prime
init|=
literal|31
decl_stmt|;
name|int
name|result
init|=
literal|1
decl_stmt|;
name|result
operator|=
name|prime
operator|*
name|result
operator|+
call|(
name|int
call|)
argument_list|(
name|endTime
operator|^
operator|(
name|endTime
operator|>>>
literal|32
operator|)
argument_list|)
expr_stmt|;
name|result
operator|=
name|prime
operator|*
name|result
operator|+
call|(
name|int
call|)
argument_list|(
name|startTime
operator|^
operator|(
name|startTime
operator|>>>
literal|32
operator|)
argument_list|)
expr_stmt|;
return|return
name|result
return|;
block|}
annotation|@
name|Override
DECL|method|equals (Object obj)
specifier|public
name|boolean
name|equals
parameter_list|(
name|Object
name|obj
parameter_list|)
block|{
if|if
condition|(
name|this
operator|==
name|obj
condition|)
block|{
return|return
literal|true
return|;
block|}
if|if
condition|(
name|obj
operator|==
literal|null
condition|)
block|{
return|return
literal|false
return|;
block|}
if|if
condition|(
operator|!
operator|(
name|obj
operator|instanceof
name|ReservationInterval
operator|)
condition|)
block|{
return|return
literal|false
return|;
block|}
name|ReservationInterval
name|other
init|=
operator|(
name|ReservationInterval
operator|)
name|obj
decl_stmt|;
if|if
condition|(
name|endTime
operator|!=
name|other
operator|.
name|endTime
condition|)
block|{
return|return
literal|false
return|;
block|}
if|if
condition|(
name|startTime
operator|!=
name|other
operator|.
name|startTime
condition|)
block|{
return|return
literal|false
return|;
block|}
return|return
literal|true
return|;
block|}
DECL|method|toString ()
specifier|public
name|String
name|toString
parameter_list|()
block|{
return|return
literal|"["
operator|+
name|startTime
operator|+
literal|", "
operator|+
name|endTime
operator|+
literal|"]"
return|;
block|}
block|}
end_class
end_unit
|
3e1261163b572aef9d7aaf0cfb5fdccecb1f3671 | 2,542 | java | Java | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Robot/DriveTrain.java | andrewy2020/NutCracker | 8e6171068fccfbd740734d33708c4c4823fac0bd | [
"MIT"
] | null | null | null | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Robot/DriveTrain.java | andrewy2020/NutCracker | 8e6171068fccfbd740734d33708c4c4823fac0bd | [
"MIT"
] | null | null | null | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Robot/DriveTrain.java | andrewy2020/NutCracker | 8e6171068fccfbd740734d33708c4c4823fac0bd | [
"MIT"
] | null | null | null | 38.515152 | 71 | 0.722659 | 7,755 | package org.firstinspires.ftc.teamcode.Robot;
import com.qualcomm.hardware.bosch.BNO055IMU;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorSimple;
import com.qualcomm.robotcore.hardware.HardwareMap;
import com.qualcomm.robotcore.util.ElapsedTime;
import com.qualcomm.robotcore.util.Range;
import org.firstinspires.ftc.robotcore.external.navigation.Orientation;
public class DriveTrain {
public DcMotor motorLF;
public DcMotor motorLB;
public DcMotor motorRB;
public DcMotor motorRF;
public DriveTrain(HardwareMap hwMap,Mode mode){
motorLF = hwMap.dcMotor.get("motorLF");
motorLB = hwMap.dcMotor.get("motorLB");
motorRB = hwMap.dcMotor.get("motorRB");
motorRF = hwMap.dcMotor.get("motorRF");
motorLF.setDirection(DcMotor.Direction.FORWARD);
motorLB.setDirection(DcMotor.Direction.FORWARD);
motorRF.setDirection(DcMotor.Direction.FORWARD);
motorRB.setDirection(DcMotor.Direction.FORWARD);
motorLB.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
motorLF.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
motorRF.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
motorRB.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
setMotorRunMode(mode);
}
public void setMotorRunMode(Mode mode){
if(mode == Mode.Auto){
motorLF.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
motorRF.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
motorLB.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
motorRB.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
motorLF.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
motorRF.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
motorLB.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
motorRB.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
}
else{
motorLF.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
motorRF.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
motorLB.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
motorRB.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
motorLF.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
motorRF.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
motorLB.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
motorRB.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
}
}
}
|
3e126189402b873ce9979846f2dc36d3f72a3a5f | 4,532 | java | Java | java/src/com/google/template/soy/soytree/CallParamValueNode.java | jmhodges/closure-templates | 1ed83f0a997ee3989ec951c4d85c6407b1ad4f13 | [
"Apache-2.0"
] | 6 | 2015-12-22T12:49:32.000Z | 2017-11-25T20:22:27.000Z | java/src/com/google/template/soy/soytree/CallParamValueNode.java | jmhodges/closure-templates | 1ed83f0a997ee3989ec951c4d85c6407b1ad4f13 | [
"Apache-2.0"
] | 2 | 2015-10-30T22:22:37.000Z | 2015-11-03T17:59:08.000Z | java/src/com/google/template/soy/soytree/CallParamValueNode.java | jmhodges/closure-templates | 1ed83f0a997ee3989ec951c4d85c6407b1ad4f13 | [
"Apache-2.0"
] | 4 | 2015-11-03T19:15:48.000Z | 2019-10-17T06:09:00.000Z | 31.041096 | 99 | 0.718667 | 7,756 | /*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.template.soy.soytree;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.template.soy.base.SourceLocation;
import com.google.template.soy.basetree.CopyState;
import com.google.template.soy.error.ErrorReporter;
import com.google.template.soy.error.ErrorReporter.Checkpoint;
import com.google.template.soy.error.ExplodingErrorReporter;
import com.google.template.soy.error.SoyError;
import com.google.template.soy.soytree.SoyNode.ExprHolderNode;
import java.util.List;
/**
* Node representing a 'param' with a value expression.
*
* <p> Important: Do not use outside of Soy code (treat as superpackage-private).
*
*/
public final class CallParamValueNode extends CallParamNode implements ExprHolderNode {
private static final SoyError SELF_ENDING_TAG_WITHOUT_VALUE
= SoyError.of("A ''param'' tag should be self-ending (with a trailing ''/'') if and only if "
+ "it also contains a value (invalid tag is '{'param {0} /'}').");
private static final SoyError SELF_ENDING_TAG_WITH_KIND_ATTRIBUTE
= SoyError.of("The ''kind'' attribute is not allowed on self-ending ''param'' tags "
+ "(invalid tag is '{'param {0} /'}').");
/** The param key. */
private final String key;
/** The parsed expression for the param value. */
private final ExprUnion valueExprUnion;
private CallParamValueNode(
int id,
SourceLocation sourceLocation,
String key,
ExprUnion valueExprUnion,
String commandText) {
super(id, sourceLocation, commandText);
this.key = Preconditions.checkNotNull(key);
this.valueExprUnion = Preconditions.checkNotNull(valueExprUnion);
}
/**
* Copy constructor.
* @param orig The node to copy.
*/
private CallParamValueNode(CallParamValueNode orig, CopyState copyState) {
super(orig, copyState);
this.key = orig.key;
this.valueExprUnion = (orig.valueExprUnion != null)
? orig.valueExprUnion.copy(copyState)
: null;
}
@Override public Kind getKind() {
return Kind.CALL_PARAM_VALUE_NODE;
}
@Override public String getKey() {
return key;
}
/** Returns the expression text for the param value. */
public String getValueExprText() {
return valueExprUnion.getExprText();
}
/** Returns the parsed expression for the param value. */
public ExprUnion getValueExprUnion() {
return valueExprUnion;
}
@Override public String getTagString() {
return buildTagStringHelper(true);
}
@Override public List<ExprUnion> getAllExprUnions() {
return ImmutableList.of(valueExprUnion);
}
@Override public CallParamValueNode copy(CopyState copyState) {
return new CallParamValueNode(this, copyState);
}
public static final class Builder extends CallParamNode.Builder {
private static CallParamValueNode error() {
return new Builder(-1, "error: error", SourceLocation.UNKNOWN)
.build(ExplodingErrorReporter.get()); // guaranteed to build
}
public Builder(int id, String commandText, SourceLocation sourceLocation) {
super(id, commandText, sourceLocation);
}
public CallParamValueNode build(ErrorReporter errorReporter) {
Checkpoint checkpoint = errorReporter.checkpoint();
CommandTextParseResult parseResult = parseCommandTextHelper(errorReporter);
if (parseResult.valueExprUnion == null) {
errorReporter.report(sourceLocation, SELF_ENDING_TAG_WITHOUT_VALUE, commandText);
}
if (parseResult.contentKind != null) {
errorReporter.report(sourceLocation, SELF_ENDING_TAG_WITH_KIND_ATTRIBUTE, commandText);
}
if (errorReporter.errorsSince(checkpoint)) {
return error();
}
CallParamValueNode node = new CallParamValueNode(
id, sourceLocation, parseResult.key, parseResult.valueExprUnion, commandText);
return node;
}
}
}
|
3e126205311d055227e77726e80d3933432603ed | 2,830 | java | Java | mil.dod.th.ose.config/src/mil/dod/th/ose/config/loading/impl/AddressTrackerCustomizer.java | sofwerx/OSUS-R | 2be47821355573149842e1dd0d8bbd75326da8a7 | [
"CC0-1.0"
] | 11 | 2017-01-12T14:39:38.000Z | 2021-02-22T01:21:46.000Z | mil.dod.th.ose.config/src/mil/dod/th/ose/config/loading/impl/AddressTrackerCustomizer.java | sofwerx/OSUS-R | 2be47821355573149842e1dd0d8bbd75326da8a7 | [
"CC0-1.0"
] | null | null | null | mil.dod.th.ose.config/src/mil/dod/th/ose/config/loading/impl/AddressTrackerCustomizer.java | sofwerx/OSUS-R | 2be47821355573149842e1dd0d8bbd75326da8a7 | [
"CC0-1.0"
] | 3 | 2017-01-12T15:03:44.000Z | 2018-11-30T20:34:45.000Z | 39.305556 | 120 | 0.675972 | 7,757 | //==============================================================================
// This software is part of the Open Standard for Unattended Sensors (OSUS)
// reference implementation (OSUS-R).
//
// To the extent possible under law, the author(s) have dedicated all copyright
// and related and neighboring rights to this software to the public domain
// worldwide. This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along
// with this software. If not, see
// <http://creativecommons.org/publicdomain/zero/1.0/>.
//==============================================================================
package mil.dod.th.ose.config.loading.impl;
import mil.dod.th.core.ccomm.AddressManagerService;
import mil.dod.th.core.ccomm.CCommException;
import mil.dod.th.core.factory.FactoryDescriptor;
import mil.dod.th.core.factory.FactoryException;
import mil.dod.th.core.log.LoggingService;
import mil.dod.th.model.config.AddressConfig;
import org.osgi.service.event.EventAdmin;
/**
* This service is used to track the configuration of addresses.
*
* @author dlandoll
*/
public class AddressTrackerCustomizer extends FactoryObjectTrackerCustomizer
{
/**
* Reference to the asset directory service.
*/
private final AddressManagerService m_AddressManagerService;
/**
* Creates a new service tracker customizer.
*
* @param addressConfig
* Address configuration
* @param addressManagerService
* Address manager service used to create and manage addresses
* @param loggingService
* Logging service used to record messages in the system log
* @param eventAdmin
* Service for sending OSGi events
*/
public AddressTrackerCustomizer(final AddressConfig addressConfig,
final AddressManagerService addressManagerService, final LoggingService loggingService,
final EventAdmin eventAdmin)
{
super(addressConfig, loggingService, eventAdmin);
m_AddressManagerService = addressManagerService;
}
@Override
public void addingFactoryDescriptor(final FactoryDescriptor factory) throws FactoryException
{
// At this point it is either the first run of the configuration or the create policy is set to IfMissing.
// Therefore, if the address does not exist in either of these cases then it should be created or retrieved.
try
{
m_AddressManagerService.getOrCreateAddress(getAddressConfig().getAddressDescription());
}
catch (final IllegalArgumentException | CCommException ex)
{
throw new FactoryException("Unable to get or create address: " + getAddressConfig().getAddressDescription(),
ex);
}
}
}
|
3e12623691e3bc70b5a5af600e3454b318c7498c | 4,304 | java | Java | src/main/java/gjum/minecraft/forge/civrelay/DiscordWebhook.java | Gjum/CivRelay | eb4e8545ded200fdda31c7bbb152afb3a503d69d | [
"Apache-2.0"
] | 7 | 2018-01-10T01:10:31.000Z | 2021-03-06T07:22:06.000Z | src/main/java/gjum/minecraft/forge/civrelay/DiscordWebhook.java | Gjum/CivRelay | eb4e8545ded200fdda31c7bbb152afb3a503d69d | [
"Apache-2.0"
] | 9 | 2018-01-09T17:02:11.000Z | 2021-04-06T01:03:16.000Z | src/main/java/gjum/minecraft/forge/civrelay/DiscordWebhook.java | Gjum/CivRelay | eb4e8545ded200fdda31c7bbb152afb3a503d69d | [
"Apache-2.0"
] | 3 | 2018-06-15T20:39:50.000Z | 2019-02-07T09:47:26.000Z | 36.786325 | 124 | 0.587593 | 7,758 | package gjum.minecraft.forge.civrelay;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
public class DiscordWebhook extends Thread {
public static final Map<String, DiscordWebhook> runningWebhooks = new HashMap<>();
private final LinkedList<byte[]> jsonQueue = new LinkedList<>();
private final String webhookUrl;
private boolean ending = false;
public DiscordWebhook(String webhookUrl) {
if (webhookUrl == null || webhookUrl.length() <= 0) {
throw new IllegalArgumentException("Invalid webhook URL: " + webhookUrl);
}
this.webhookUrl = webhookUrl;
start();
}
@Override
public void run() {
while (true) {
try {
runLoop();
if (ending) {
return;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public synchronized void pushJson(String json) {
jsonQueue.add(json.getBytes(StandardCharsets.UTF_8));
}
public synchronized void end() {
ending = true;
interrupt();
}
private void runLoop() throws IOException {
byte[] json = jsonQueue.peek();
if (json == null) {
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
return; // jump back up to popJson
}
HttpURLConnection connection = (HttpURLConnection) new URL(webhookUrl).openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.addRequestProperty("User-Agent", "Mozilla/4.76");
connection.setRequestProperty("Content-Length", String.valueOf(json.length));
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
try (OutputStream os = connection.getOutputStream()) {
os.write(json);
os.flush();
if (connection.getResponseCode() == 429) {
final int retryAfter = connection.getHeaderFieldInt("Retry-After", 5000);
CivRelayMod.logger.error("Rate limit reached, retrying after " + retryAfter + "ms.");
try {
Thread.sleep(retryAfter);
} catch (InterruptedException ignored) {
}
} else if (connection.getResponseCode() < 200 || 300 <= connection.getResponseCode()) {
CivRelayMod.logger.error(connection.getResponseCode() + ": " + connection.getResponseMessage());
} else {
jsonQueue.remove();
// if we've hit the rate limit, wait a bit longer
if (connection.getHeaderFieldInt("X-RateLimit-Remaining", 0) <= 0) {
final long defaultWaitTime = 1; // if header is absent, continue after 1s by default
final long currentTimeSec = System.currentTimeMillis() / 1000;
final long reset = connection.getHeaderFieldLong("X-RateLimit-Reset", defaultWaitTime + currentTimeSec);
if (reset > 0) {
try {
Thread.sleep(reset - currentTimeSec);
} catch (InterruptedException ignored) {
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static synchronized DiscordWebhook getOrStartDiscord(String webhookAddress) {
final DiscordWebhook discord = runningWebhooks.get(webhookAddress);
if (discord != null) return discord;
// not running: start
DiscordWebhook newDiscord = new DiscordWebhook(webhookAddress);
runningWebhooks.put(webhookAddress, newDiscord);
return newDiscord;
}
public static synchronized void stopDiscord(String webhookAddress) {
final DiscordWebhook discord = runningWebhooks.get(webhookAddress);
if (discord == null) return;
runningWebhooks.remove(webhookAddress);
discord.end();
}
}
|
3e12636515ffaeb5d6afe832d2f134f21ea848ef | 182 | java | Java | src/test/java/junit/tutorial/ch11/RandomNumberGeneratorFixedResultStub.java | toms74209200/JUnit_practice | a6033992b8c03ac12b2dbb4d944806f387bf35aa | [
"MIT"
] | null | null | null | src/test/java/junit/tutorial/ch11/RandomNumberGeneratorFixedResultStub.java | toms74209200/JUnit_practice | a6033992b8c03ac12b2dbb4d944806f387bf35aa | [
"MIT"
] | null | null | null | src/test/java/junit/tutorial/ch11/RandomNumberGeneratorFixedResultStub.java | toms74209200/JUnit_practice | a6033992b8c03ac12b2dbb4d944806f387bf35aa | [
"MIT"
] | null | null | null | 20.222222 | 84 | 0.730769 | 7,759 | package junit.tutorial.ch11;
public class RandomNumberGeneratorFixedResultStub implements RandomNumberGenerator {
@Override
public int nextInt() {
return 1;
}
}
|
3e1264eb27fffdc7726929a876db29421ac00b33 | 101,397 | java | Java | k9mail/src/main/java/com/fsck/ptl/mailstore/LocalFolder.java | anjren/K9-PTL | 46a1da4960f658a5137a25d3c16877a0e5be8239 | [
"BSD-3-Clause"
] | null | null | null | k9mail/src/main/java/com/fsck/ptl/mailstore/LocalFolder.java | anjren/K9-PTL | 46a1da4960f658a5137a25d3c16877a0e5be8239 | [
"BSD-3-Clause"
] | null | null | null | k9mail/src/main/java/com/fsck/ptl/mailstore/LocalFolder.java | anjren/K9-PTL | 46a1da4960f658a5137a25d3c16877a0e5be8239 | [
"BSD-3-Clause"
] | null | null | null | 45.839512 | 239 | 0.471582 | 7,760 | package com.fsck.ptl.mailstore;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;
import com.fsck.ptl.mail.internet.MimeMessageHelper;
import org.apache.commons.io.IOUtils;
import org.apache.james.mime4j.util.MimeUtil;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;
import com.fsck.ptl.Account;
import com.fsck.ptl.K9;
import com.fsck.ptl.Account.MessageFormat;
import com.fsck.ptl.activity.Search;
import com.fsck.ptl.mail.MessageRetrievalListener;
import com.fsck.ptl.helper.HtmlConverter;
import com.fsck.ptl.helper.Utility;
import com.fsck.ptl.mail.Address;
import com.fsck.ptl.mail.Body;
import com.fsck.ptl.mail.BodyPart;
import com.fsck.ptl.mail.FetchProfile;
import com.fsck.ptl.mail.Flag;
import com.fsck.ptl.mail.Folder;
import com.fsck.ptl.mail.Message;
import com.fsck.ptl.mail.MessagingException;
import com.fsck.ptl.mail.Part;
import com.fsck.ptl.mail.Message.RecipientType;
import com.fsck.ptl.mail.internet.MimeBodyPart;
import com.fsck.ptl.mail.internet.MimeHeader;
import com.fsck.ptl.mail.internet.MimeMessage;
import com.fsck.ptl.mail.internet.MimeMultipart;
import com.fsck.ptl.mail.internet.MimeUtility;
import com.fsck.ptl.mail.internet.TextBody;
import com.fsck.ptl.mailstore.LockableDatabase.DbCallback;
import com.fsck.ptl.mailstore.LockableDatabase.WrappedException;
import com.fsck.ptl.provider.AttachmentProvider;
public class LocalFolder extends Folder<LocalMessage> implements Serializable {
private static final long serialVersionUID = -1973296520918624767L;
private final LocalStore localStore;
private String mName = null;
private long mFolderId = -1;
private int mVisibleLimit = -1;
private String prefId = null;
private FolderClass mDisplayClass = FolderClass.NO_CLASS;
private FolderClass mSyncClass = FolderClass.INHERITED;
private FolderClass mPushClass = FolderClass.SECOND_CLASS;
private FolderClass mNotifyClass = FolderClass.INHERITED;
private boolean mInTopGroup = false;
private String mPushState = null;
private boolean mIntegrate = false;
// mLastUid is used during syncs. It holds the highest UID within the local folder so we
// know whether or not an unread message added to the local folder is actually "new" or not.
private Integer mLastUid = null;
public LocalFolder(LocalStore localStore, String name) {
super();
this.localStore = localStore;
this.mName = name;
if (getAccount().getInboxFolderName().equals(getName())) {
mSyncClass = FolderClass.FIRST_CLASS;
mPushClass = FolderClass.FIRST_CLASS;
mInTopGroup = true;
}
}
public LocalFolder(LocalStore localStore, long id) {
super();
this.localStore = localStore;
this.mFolderId = id;
}
public long getId() {
return mFolderId;
}
public String getAccountUuid()
{
return getAccount().getUuid();
}
public boolean getSignatureUse() {
return getAccount().getSignatureUse();
}
public void setLastSelectedFolderName(String destFolderName) {
getAccount().setLastSelectedFolderName(destFolderName);
}
public boolean syncRemoteDeletions() {
return getAccount().syncRemoteDeletions();
}
@Override
public void open(final int mode) throws MessagingException {
if (isOpen() && (getMode() == mode || mode == OPEN_MODE_RO)) {
return;
} else if (isOpen()) {
//previously opened in READ_ONLY and now requesting READ_WRITE
//so close connection and reopen
close();
}
try {
this.localStore.database.execute(false, new DbCallback<Void>() {
@Override
public Void doDbWork(final SQLiteDatabase db) throws WrappedException {
Cursor cursor = null;
try {
String baseQuery = "SELECT " + LocalStore.GET_FOLDER_COLS + " FROM folders ";
if (mName != null) {
cursor = db.rawQuery(baseQuery + "where folders.name = ?", new String[] { mName });
} else {
cursor = db.rawQuery(baseQuery + "where folders.id = ?", new String[] { Long.toString(mFolderId) });
}
if (cursor.moveToFirst() && !cursor.isNull(LocalStore.FOLDER_ID_INDEX)) {
int folderId = cursor.getInt(LocalStore.FOLDER_ID_INDEX);
if (folderId > 0) {
open(cursor);
}
} else {
Log.w(K9.LOG_TAG, "Creating folder " + getName() + " with existing id " + getId());
create(FolderType.HOLDS_MESSAGES);
open(mode);
}
} catch (MessagingException e) {
throw new WrappedException(e);
} finally {
Utility.closeQuietly(cursor);
}
return null;
}
});
} catch (WrappedException e) {
throw(MessagingException) e.getCause();
}
}
void open(Cursor cursor) throws MessagingException {
mFolderId = cursor.getInt(LocalStore.FOLDER_ID_INDEX);
mName = cursor.getString(LocalStore.FOLDER_NAME_INDEX);
mVisibleLimit = cursor.getInt(LocalStore.FOLDER_VISIBLE_LIMIT_INDEX);
mPushState = cursor.getString(LocalStore.FOLDER_PUSH_STATE_INDEX);
super.setStatus(cursor.getString(LocalStore.FOLDER_STATUS_INDEX));
// Only want to set the local variable stored in the super class. This class
// does a DB update on setLastChecked
super.setLastChecked(cursor.getLong(LocalStore.FOLDER_LAST_CHECKED_INDEX));
super.setLastPush(cursor.getLong(LocalStore.FOLDER_LAST_PUSHED_INDEX));
mInTopGroup = (cursor.getInt(LocalStore.FOLDER_TOP_GROUP_INDEX)) == 1 ? true : false;
mIntegrate = (cursor.getInt(LocalStore.FOLDER_INTEGRATE_INDEX) == 1) ? true : false;
String noClass = FolderClass.NO_CLASS.toString();
String displayClass = cursor.getString(LocalStore.FOLDER_DISPLAY_CLASS_INDEX);
mDisplayClass = Folder.FolderClass.valueOf((displayClass == null) ? noClass : displayClass);
String notifyClass = cursor.getString(LocalStore.FOLDER_NOTIFY_CLASS_INDEX);
mNotifyClass = Folder.FolderClass.valueOf((notifyClass == null) ? noClass : notifyClass);
String pushClass = cursor.getString(LocalStore.FOLDER_PUSH_CLASS_INDEX);
mPushClass = Folder.FolderClass.valueOf((pushClass == null) ? noClass : pushClass);
String syncClass = cursor.getString(LocalStore.FOLDER_SYNC_CLASS_INDEX);
mSyncClass = Folder.FolderClass.valueOf((syncClass == null) ? noClass : syncClass);
}
@Override
public boolean isOpen() {
return (mFolderId != -1 && mName != null);
}
@Override
public int getMode() {
return OPEN_MODE_RW;
}
@Override
public String getName() {
return mName;
}
@Override
public boolean exists() throws MessagingException {
return this.localStore.database.execute(false, new DbCallback<Boolean>() {
@Override
public Boolean doDbWork(final SQLiteDatabase db) throws WrappedException {
Cursor cursor = null;
try {
cursor = db.rawQuery("SELECT id FROM folders "
+ "where folders.name = ?", new String[] { LocalFolder.
this.getName()
});
if (cursor.moveToFirst()) {
int folderId = cursor.getInt(0);
return (folderId > 0);
}
return false;
} finally {
Utility.closeQuietly(cursor);
}
}
});
}
@Override
public boolean create(FolderType type) throws MessagingException {
return create(type, getAccount().getDisplayCount());
}
@Override
public boolean create(FolderType type, final int visibleLimit) throws MessagingException {
if (exists()) {
throw new MessagingException("Folder " + mName + " already exists.");
}
List<LocalFolder> foldersToCreate = new ArrayList<LocalFolder>(1);
foldersToCreate.add(this);
this.localStore.createFolders(foldersToCreate, visibleLimit);
return true;
}
class PreferencesHolder {
FolderClass displayClass = mDisplayClass;
FolderClass syncClass = mSyncClass;
FolderClass notifyClass = mNotifyClass;
FolderClass pushClass = mPushClass;
boolean inTopGroup = mInTopGroup;
boolean integrate = mIntegrate;
}
@Override
public void close() {
mFolderId = -1;
}
@Override
public int getMessageCount() throws MessagingException {
try {
return this.localStore.database.execute(false, new DbCallback<Integer>() {
@Override
public Integer doDbWork(final SQLiteDatabase db) throws WrappedException {
try {
open(OPEN_MODE_RW);
} catch (MessagingException e) {
throw new WrappedException(e);
}
Cursor cursor = null;
try {
cursor = db.rawQuery("SELECT COUNT(id) FROM messages WHERE (empty IS NULL OR empty != 1) AND deleted = 0 and folder_id = ?",
new String[] {
Long.toString(mFolderId)
});
cursor.moveToFirst();
return cursor.getInt(0); //messagecount
} finally {
Utility.closeQuietly(cursor);
}
}
});
} catch (WrappedException e) {
throw(MessagingException) e.getCause();
}
}
@Override
public int getUnreadMessageCount() throws MessagingException {
if (mFolderId == -1) {
open(OPEN_MODE_RW);
}
try {
return this.localStore.database.execute(false, new DbCallback<Integer>() {
@Override
public Integer doDbWork(final SQLiteDatabase db) throws WrappedException {
int unreadMessageCount = 0;
Cursor cursor = db.query("messages", new String[] { "COUNT(id)" },
"folder_id = ? AND (empty IS NULL OR empty != 1) AND deleted = 0 AND read=0",
new String[] { Long.toString(mFolderId) }, null, null, null);
try {
if (cursor.moveToFirst()) {
unreadMessageCount = cursor.getInt(0);
}
} finally {
cursor.close();
}
return unreadMessageCount;
}
});
} catch (WrappedException e) {
throw(MessagingException) e.getCause();
}
}
@Override
public int getFlaggedMessageCount() throws MessagingException {
if (mFolderId == -1) {
open(OPEN_MODE_RW);
}
try {
return this.localStore.database.execute(false, new DbCallback<Integer>() {
@Override
public Integer doDbWork(final SQLiteDatabase db) throws WrappedException {
int flaggedMessageCount = 0;
Cursor cursor = db.query("messages", new String[] { "COUNT(id)" },
"folder_id = ? AND (empty IS NULL OR empty != 1) AND deleted = 0 AND flagged = 1",
new String[] { Long.toString(mFolderId) }, null, null, null);
try {
if (cursor.moveToFirst()) {
flaggedMessageCount = cursor.getInt(0);
}
} finally {
cursor.close();
}
return flaggedMessageCount;
}
});
} catch (WrappedException e) {
throw(MessagingException) e.getCause();
}
}
@Override
public void setLastChecked(final long lastChecked) throws MessagingException {
try {
open(OPEN_MODE_RW);
LocalFolder.super.setLastChecked(lastChecked);
} catch (MessagingException e) {
throw new WrappedException(e);
}
updateFolderColumn("last_updated", lastChecked);
}
@Override
public void setLastPush(final long lastChecked) throws MessagingException {
try {
open(OPEN_MODE_RW);
LocalFolder.super.setLastPush(lastChecked);
} catch (MessagingException e) {
throw new WrappedException(e);
}
updateFolderColumn("last_pushed", lastChecked);
}
public int getVisibleLimit() throws MessagingException {
open(OPEN_MODE_RW);
return mVisibleLimit;
}
public void purgeToVisibleLimit(MessageRemovalListener listener) throws MessagingException {
//don't purge messages while a Search is active since it might throw away search results
if (!Search.isActive()) {
if (mVisibleLimit == 0) {
return ;
}
open(OPEN_MODE_RW);
List<? extends Message> messages = getMessages(null, false);
for (int i = mVisibleLimit; i < messages.size(); i++) {
if (listener != null) {
listener.messageRemoved(messages.get(i));
}
messages.get(i).destroy();
}
}
}
public void setVisibleLimit(final int visibleLimit) throws MessagingException {
mVisibleLimit = visibleLimit;
updateFolderColumn("visible_limit", mVisibleLimit);
}
@Override
public void setStatus(final String status) throws MessagingException {
updateFolderColumn("status", status);
}
public void setPushState(final String pushState) throws MessagingException {
mPushState = pushState;
updateFolderColumn("push_state", pushState);
}
private void updateFolderColumn(final String column, final Object value) throws MessagingException {
try {
this.localStore.database.execute(false, new DbCallback<Void>() {
@Override
public Void doDbWork(final SQLiteDatabase db) throws WrappedException {
try {
open(OPEN_MODE_RW);
} catch (MessagingException e) {
throw new WrappedException(e);
}
db.execSQL("UPDATE folders SET " + column + " = ? WHERE id = ?", new Object[] { value, mFolderId });
return null;
}
});
} catch (WrappedException e) {
throw(MessagingException) e.getCause();
}
}
public String getPushState() {
return mPushState;
}
@Override
public FolderClass getDisplayClass() {
return mDisplayClass;
}
@Override
public FolderClass getSyncClass() {
return (FolderClass.INHERITED == mSyncClass) ? getDisplayClass() : mSyncClass;
}
public FolderClass getRawSyncClass() {
return mSyncClass;
}
public FolderClass getNotifyClass() {
return (FolderClass.INHERITED == mNotifyClass) ? getPushClass() : mNotifyClass;
}
public FolderClass getRawNotifyClass() {
return mNotifyClass;
}
@Override
public FolderClass getPushClass() {
return (FolderClass.INHERITED == mPushClass) ? getSyncClass() : mPushClass;
}
public FolderClass getRawPushClass() {
return mPushClass;
}
public void setDisplayClass(FolderClass displayClass) throws MessagingException {
mDisplayClass = displayClass;
updateFolderColumn("display_class", mDisplayClass.name());
}
public void setSyncClass(FolderClass syncClass) throws MessagingException {
mSyncClass = syncClass;
updateFolderColumn("poll_class", mSyncClass.name());
}
public void setPushClass(FolderClass pushClass) throws MessagingException {
mPushClass = pushClass;
updateFolderColumn("push_class", mPushClass.name());
}
public void setNotifyClass(FolderClass notifyClass) throws MessagingException {
mNotifyClass = notifyClass;
updateFolderColumn("notify_class", mNotifyClass.name());
}
public boolean isIntegrate() {
return mIntegrate;
}
public void setIntegrate(boolean integrate) throws MessagingException {
mIntegrate = integrate;
updateFolderColumn("integrate", mIntegrate ? 1 : 0);
}
private String getPrefId(String name) {
if (prefId == null) {
prefId = this.localStore.uUid + "." + name;
}
return prefId;
}
private String getPrefId() throws MessagingException {
open(OPEN_MODE_RW);
return getPrefId(mName);
}
public void delete() throws MessagingException {
String id = getPrefId();
SharedPreferences.Editor editor = this.localStore.getPreferences().edit();
editor.remove(id + ".displayMode");
editor.remove(id + ".syncMode");
editor.remove(id + ".pushMode");
editor.remove(id + ".inTopGroup");
editor.remove(id + ".integrate");
editor.commit();
}
public void save() throws MessagingException {
SharedPreferences.Editor editor = this.localStore.getPreferences().edit();
save(editor);
editor.commit();
}
public void save(SharedPreferences.Editor editor) throws MessagingException {
String id = getPrefId();
// there can be a lot of folders. For the defaults, let's not save prefs, saving space, except for INBOX
if (mDisplayClass == FolderClass.NO_CLASS && !getAccount().getInboxFolderName().equals(getName())) {
editor.remove(id + ".displayMode");
} else {
editor.putString(id + ".displayMode", mDisplayClass.name());
}
if (mSyncClass == FolderClass.INHERITED && !getAccount().getInboxFolderName().equals(getName())) {
editor.remove(id + ".syncMode");
} else {
editor.putString(id + ".syncMode", mSyncClass.name());
}
if (mNotifyClass == FolderClass.INHERITED && !getAccount().getInboxFolderName().equals(getName())) {
editor.remove(id + ".notifyMode");
} else {
editor.putString(id + ".notifyMode", mNotifyClass.name());
}
if (mPushClass == FolderClass.SECOND_CLASS && !getAccount().getInboxFolderName().equals(getName())) {
editor.remove(id + ".pushMode");
} else {
editor.putString(id + ".pushMode", mPushClass.name());
}
editor.putBoolean(id + ".inTopGroup", mInTopGroup);
editor.putBoolean(id + ".integrate", mIntegrate);
}
public void refresh(String name, PreferencesHolder prefHolder) {
String id = getPrefId(name);
SharedPreferences preferences = this.localStore.getPreferences();
try {
prefHolder.displayClass = FolderClass.valueOf(preferences.getString(id + ".displayMode",
prefHolder.displayClass.name()));
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Unable to load displayMode for " + getName(), e);
}
if (prefHolder.displayClass == FolderClass.NONE) {
prefHolder.displayClass = FolderClass.NO_CLASS;
}
try {
prefHolder.syncClass = FolderClass.valueOf(preferences.getString(id + ".syncMode",
prefHolder.syncClass.name()));
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Unable to load syncMode for " + getName(), e);
}
if (prefHolder.syncClass == FolderClass.NONE) {
prefHolder.syncClass = FolderClass.INHERITED;
}
try {
prefHolder.notifyClass = FolderClass.valueOf(preferences.getString(id + ".notifyMode",
prefHolder.notifyClass.name()));
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Unable to load notifyMode for " + getName(), e);
}
if (prefHolder.notifyClass == FolderClass.NONE) {
prefHolder.notifyClass = FolderClass.INHERITED;
}
try {
prefHolder.pushClass = FolderClass.valueOf(preferences.getString(id + ".pushMode",
prefHolder.pushClass.name()));
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Unable to load pushMode for " + getName(), e);
}
if (prefHolder.pushClass == FolderClass.NONE) {
prefHolder.pushClass = FolderClass.INHERITED;
}
prefHolder.inTopGroup = preferences.getBoolean(id + ".inTopGroup", prefHolder.inTopGroup);
prefHolder.integrate = preferences.getBoolean(id + ".integrate", prefHolder.integrate);
}
@Override
public void fetch(final List<LocalMessage> messages, final FetchProfile fp, final MessageRetrievalListener<LocalMessage> listener)
throws MessagingException {
try {
this.localStore.database.execute(false, new DbCallback<Void>() {
@Override
public Void doDbWork(final SQLiteDatabase db) throws WrappedException {
try {
open(OPEN_MODE_RW);
if (fp.contains(FetchProfile.Item.BODY)) {
for (Message message : messages) {
LocalMessage localMessage = (LocalMessage)message;
Cursor cursor = null;
MimeMultipart mp = new MimeMultipart();
mp.setSubType("mixed");
try {
cursor = db.rawQuery("SELECT html_content, text_content, mime_type FROM messages "
+ "WHERE id = ?",
new String[] { Long.toString(localMessage.getId()) });
cursor.moveToNext();
String htmlContent = cursor.getString(0);
String textContent = cursor.getString(1);
String mimeType = cursor.getString(2);
if (mimeType != null && mimeType.toLowerCase(Locale.US).startsWith("multipart/")) {
// If this is a multipart message, preserve both text
// and html parts, as well as the subtype.
mp.setSubType(mimeType.toLowerCase(Locale.US).replaceFirst("^multipart/", ""));
if (textContent != null) {
LocalTextBody body = new LocalTextBody(textContent, htmlContent);
MimeBodyPart bp = new MimeBodyPart(body, "text/plain");
mp.addBodyPart(bp);
}
if (getAccount().getMessageFormat() != MessageFormat.TEXT) {
if (htmlContent != null) {
TextBody body = new TextBody(htmlContent);
MimeBodyPart bp = new MimeBodyPart(body, "text/html");
mp.addBodyPart(bp);
}
// If we have both text and html content and our MIME type
// isn't multipart/alternative, then corral them into a new
// multipart/alternative part and put that into the parent.
// If it turns out that this is the only part in the parent
// MimeMultipart, it'll get fixed below before we attach to
// the message.
if (textContent != null && htmlContent != null && !mimeType.equalsIgnoreCase("multipart/alternative")) {
MimeMultipart alternativeParts = mp;
alternativeParts.setSubType("alternative");
mp = new MimeMultipart();
mp.addBodyPart(new MimeBodyPart(alternativeParts));
}
}
} else if (mimeType != null && mimeType.equalsIgnoreCase("text/plain")) {
// If it's text, add only the plain part. The MIME
// container will drop away below.
if (textContent != null) {
LocalTextBody body = new LocalTextBody(textContent, htmlContent);
MimeBodyPart bp = new MimeBodyPart(body, "text/plain");
mp.addBodyPart(bp);
}
} else if (mimeType != null && mimeType.equalsIgnoreCase("text/html")) {
// If it's html, add only the html part. The MIME
// container will drop away below.
if (htmlContent != null) {
TextBody body = new TextBody(htmlContent);
MimeBodyPart bp = new MimeBodyPart(body, "text/html");
mp.addBodyPart(bp);
}
} else {
// MIME type not set. Grab whatever part we can get,
// with Text taking precedence. This preserves pre-HTML
// composition behaviour.
if (textContent != null) {
LocalTextBody body = new LocalTextBody(textContent, htmlContent);
MimeBodyPart bp = new MimeBodyPart(body, "text/plain");
mp.addBodyPart(bp);
} else if (htmlContent != null) {
TextBody body = new TextBody(htmlContent);
MimeBodyPart bp = new MimeBodyPart(body, "text/html");
mp.addBodyPart(bp);
}
}
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Exception fetching message:", e);
} finally {
Utility.closeQuietly(cursor);
}
try {
cursor = db.query(
"attachments",
new String[] {
"id",
"size",
"name",
"mime_type",
"store_data",
"content_uri",
"content_id",
"content_disposition"
},
"message_id = ?",
new String[] { Long.toString(localMessage.getId()) },
null,
null,
null);
while (cursor.moveToNext()) {
long id = cursor.getLong(0);
int size = cursor.getInt(1);
String name = cursor.getString(2);
String type = cursor.getString(3);
String storeData = cursor.getString(4);
String contentUri = cursor.getString(5);
String contentId = cursor.getString(6);
String contentDisposition = cursor.getString(7);
String encoding = MimeUtility.getEncodingforType(type);
Body body = null;
if (contentDisposition == null) {
contentDisposition = "attachment";
}
if (contentUri != null) {
if (MimeUtil.isMessage(type)) {
body = new LocalAttachmentMessageBody(
Uri.parse(contentUri),
LocalFolder.this.localStore.context);
} else {
body = new LocalAttachmentBody(
Uri.parse(contentUri),
LocalFolder.this.localStore.context);
}
}
MimeBodyPart bp = new LocalAttachmentBodyPart(body, id);
bp.setEncoding(encoding);
if (name != null) {
bp.setHeader(MimeHeader.HEADER_CONTENT_TYPE,
String.format("%s;\r\n name=\"%s\"",
type,
name));
bp.setHeader(MimeHeader.HEADER_CONTENT_DISPOSITION,
String.format(Locale.US, "%s;\r\n filename=\"%s\";\r\n size=%d",
contentDisposition,
name, // TODO: Should use encoded word defined in RFC 2231.
size));
} else {
bp.setHeader(MimeHeader.HEADER_CONTENT_TYPE, type);
bp.setHeader(MimeHeader.HEADER_CONTENT_DISPOSITION,
String.format(Locale.US, "%s;\r\n size=%d",
contentDisposition,
size));
}
bp.setHeader(MimeHeader.HEADER_CONTENT_ID, contentId);
/*
* HEADER_ANDROID_ATTACHMENT_STORE_DATA is a custom header we add to that
* we can later pull the attachment from the remote store if necessary.
*/
bp.setHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA, storeData);
mp.addBodyPart(bp);
}
} finally {
Utility.closeQuietly(cursor);
}
if (mp.getCount() == 0) {
// If we have no body, remove the container and create a
// dummy plain text body. This check helps prevents us from
// triggering T_MIME_NO_TEXT and T_TVD_MIME_NO_HEADERS
// SpamAssassin rules.
localMessage.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "text/plain");
MimeMessageHelper.setBody(localMessage, new TextBody(""));
} else if (mp.getCount() == 1 &&
!(mp.getBodyPart(0) instanceof LocalAttachmentBodyPart)) {
// If we have only one part, drop the MimeMultipart container.
BodyPart part = mp.getBodyPart(0);
localMessage.setHeader(MimeHeader.HEADER_CONTENT_TYPE, part.getContentType());
MimeMessageHelper.setBody(localMessage, part.getBody());
} else {
// Otherwise, attach the MimeMultipart to the message.
MimeMessageHelper.setBody(localMessage, mp);
}
}
}
} catch (MessagingException e) {
throw new WrappedException(e);
}
return null;
}
});
} catch (WrappedException e) {
throw(MessagingException) e.getCause();
}
}
@Override
public List<LocalMessage> getMessages(int start, int end, Date earliestDate, MessageRetrievalListener<LocalMessage> listener)
throws MessagingException {
open(OPEN_MODE_RW);
throw new MessagingException(
"LocalStore.getMessages(int, int, MessageRetrievalListener) not yet implemented");
}
/**
* Populate the header fields of the given list of messages by reading
* the saved header data from the database.
*
* @param messages
* The messages whose headers should be loaded.
* @throws UnavailableStorageException
*/
void populateHeaders(final List<LocalMessage> messages) throws MessagingException {
this.localStore.database.execute(false, new DbCallback<Void>() {
@Override
public Void doDbWork(final SQLiteDatabase db) throws WrappedException, MessagingException {
Cursor cursor = null;
if (messages.isEmpty()) {
return null;
}
try {
Map<Long, LocalMessage> popMessages = new HashMap<Long, LocalMessage>();
List<String> ids = new ArrayList<String>();
StringBuilder questions = new StringBuilder();
for (int i = 0; i < messages.size(); i++) {
if (i != 0) {
questions.append(", ");
}
questions.append("?");
LocalMessage message = messages.get(i);
Long id = message.getId();
ids.add(Long.toString(id));
popMessages.put(id, message);
}
cursor = db.rawQuery(
"SELECT message_id, name, value FROM headers " + "WHERE message_id in ( " + questions + ") ORDER BY id ASC",
ids.toArray(LocalStore.EMPTY_STRING_ARRAY));
while (cursor.moveToNext()) {
Long id = cursor.getLong(0);
String name = cursor.getString(1);
String value = cursor.getString(2);
//Log.i(K9.LOG_TAG, "Retrieved header name= " + name + ", value = " + value + " for message " + id);
popMessages.get(id).addHeader(name, value);
}
} finally {
Utility.closeQuietly(cursor);
}
return null;
}
});
}
public String getMessageUidById(final long id) throws MessagingException {
try {
return this.localStore.database.execute(false, new DbCallback<String>() {
@Override
public String doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException {
try {
open(OPEN_MODE_RW);
Cursor cursor = null;
try {
cursor = db.rawQuery(
"SELECT uid FROM messages " +
"WHERE id = ? AND folder_id = ?",
new String[] {
Long.toString(id), Long.toString(mFolderId)
});
if (!cursor.moveToNext()) {
return null;
}
return cursor.getString(0);
} finally {
Utility.closeQuietly(cursor);
}
} catch (MessagingException e) {
throw new WrappedException(e);
}
}
});
} catch (WrappedException e) {
throw(MessagingException) e.getCause();
}
}
@Override
public LocalMessage getMessage(final String uid) throws MessagingException {
try {
return this.localStore.database.execute(false, new DbCallback<LocalMessage>() {
@Override
public LocalMessage doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException {
try {
open(OPEN_MODE_RW);
LocalMessage message = new LocalMessage(LocalFolder.this.localStore, uid, LocalFolder.this);
Cursor cursor = null;
try {
cursor = db.rawQuery(
"SELECT " +
LocalStore.GET_MESSAGES_COLS +
"FROM messages " +
"LEFT JOIN threads ON (threads.message_id = messages.id) " +
"WHERE uid = ? AND folder_id = ?",
new String[] {
message.getUid(), Long.toString(mFolderId)
});
if (!cursor.moveToNext()) {
return null;
}
message.populateFromGetMessageCursor(cursor);
} finally {
Utility.closeQuietly(cursor);
}
return message;
} catch (MessagingException e) {
throw new WrappedException(e);
}
}
});
} catch (WrappedException e) {
throw(MessagingException) e.getCause();
}
}
@Override
public List<LocalMessage> getMessages(MessageRetrievalListener listener) throws MessagingException {
return getMessages(listener, true);
}
@Override
public List<LocalMessage> getMessages(final MessageRetrievalListener listener, final boolean includeDeleted) throws MessagingException {
try {
return localStore.database.execute(false, new DbCallback<List<LocalMessage>>() {
@Override
public List<LocalMessage> doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException {
try {
open(OPEN_MODE_RW);
return LocalFolder.this.localStore.getMessages(
listener,
LocalFolder.this,
"SELECT " + LocalStore.GET_MESSAGES_COLS +
"FROM messages " +
"LEFT JOIN threads ON (threads.message_id = messages.id) " +
"WHERE (empty IS NULL OR empty != 1) AND " +
(includeDeleted ? "" : "deleted = 0 AND ") +
"folder_id = ? ORDER BY date DESC",
new String[] { Long.toString(mFolderId) }
);
} catch (MessagingException e) {
throw new WrappedException(e);
}
}
});
} catch (WrappedException e) {
throw(MessagingException) e.getCause();
}
}
@Override
public List<LocalMessage> getMessages(String[] uids, MessageRetrievalListener<LocalMessage> listener)
throws MessagingException {
open(OPEN_MODE_RW);
if (uids == null) {
return getMessages(listener);
}
List<LocalMessage> messages = new ArrayList<LocalMessage>();
for (String uid : uids) {
LocalMessage message = getMessage(uid);
if (message != null) {
messages.add(message);
}
}
return messages;
}
@Override
public Map<String, String> copyMessages(List<? extends Message> msgs, Folder folder) throws MessagingException {
if (!(folder instanceof LocalFolder)) {
throw new MessagingException("copyMessages called with incorrect Folder");
}
return ((LocalFolder) folder).appendMessages(msgs, true);
}
@Override
public Map<String, String> moveMessages(final List<? extends Message> msgs, final Folder destFolder) throws MessagingException {
if (!(destFolder instanceof LocalFolder)) {
throw new MessagingException("moveMessages called with non-LocalFolder");
}
final LocalFolder lDestFolder = (LocalFolder)destFolder;
final Map<String, String> uidMap = new HashMap<String, String>();
try {
this.localStore.database.execute(false, new DbCallback<Void>() {
@Override
public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException {
try {
lDestFolder.open(OPEN_MODE_RW);
for (Message message : msgs) {
LocalMessage lMessage = (LocalMessage)message;
String oldUID = message.getUid();
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "Updating folder_id to " + lDestFolder.getId() + " for message with UID "
+ message.getUid() + ", id " + lMessage.getId() + " currently in folder " + getName());
}
String newUid = K9.LOCAL_UID_PREFIX + UUID.randomUUID().toString();
message.setUid(newUid);
uidMap.put(oldUID, newUid);
// Message threading in the target folder
ThreadInfo threadInfo = lDestFolder.doMessageThreading(db, message);
/*
* "Move" the message into the new folder
*/
long msgId = lMessage.getId();
String[] idArg = new String[] { Long.toString(msgId) };
ContentValues cv = new ContentValues();
cv.put("folder_id", lDestFolder.getId());
cv.put("uid", newUid);
db.update("messages", cv, "id = ?", idArg);
// Create/update entry in 'threads' table for the message in the
// target folder
cv.clear();
cv.put("message_id", msgId);
if (threadInfo.threadId == -1) {
if (threadInfo.rootId != -1) {
cv.put("root", threadInfo.rootId);
}
if (threadInfo.parentId != -1) {
cv.put("parent", threadInfo.parentId);
}
db.insert("threads", null, cv);
} else {
db.update("threads", cv, "id = ?",
new String[] { Long.toString(threadInfo.threadId) });
}
/*
* Add a placeholder message so we won't download the original
* message again if we synchronize before the remote move is
* complete.
*/
// We need to open this folder to get the folder id
open(OPEN_MODE_RW);
cv.clear();
cv.put("uid", oldUID);
cv.putNull("flags");
cv.put("read", 1);
cv.put("deleted", 1);
cv.put("folder_id", mFolderId);
cv.put("empty", 0);
String messageId = message.getMessageId();
if (messageId != null) {
cv.put("message_id", messageId);
}
final long newId;
if (threadInfo.msgId != -1) {
// There already existed an empty message in the target folder.
// Let's use it as placeholder.
newId = threadInfo.msgId;
db.update("messages", cv, "id = ?",
new String[] { Long.toString(newId) });
} else {
newId = db.insert("messages", null, cv);
}
/*
* Update old entry in 'threads' table to point to the newly
* created placeholder.
*/
cv.clear();
cv.put("message_id", newId);
db.update("threads", cv, "id = ?",
new String[] { Long.toString(lMessage.getThreadId()) });
}
} catch (MessagingException e) {
throw new WrappedException(e);
}
return null;
}
});
this.localStore.notifyChange();
return uidMap;
} catch (WrappedException e) {
throw(MessagingException) e.getCause();
}
}
/**
* Convenience transaction wrapper for storing a message and set it as fully downloaded. Implemented mainly to speed up DB transaction commit.
*
* @param message Message to store. Never <code>null</code>.
* @param runnable What to do before setting {@link Flag#X_DOWNLOADED_FULL}. Never <code>null</code>.
* @return The local version of the message. Never <code>null</code>.
* @throws MessagingException
*/
public LocalMessage storeSmallMessage(final Message message, final Runnable runnable) throws MessagingException {
return this.localStore.database.execute(true, new DbCallback<LocalMessage>() {
@Override
public LocalMessage doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException {
try {
appendMessages(Collections.singletonList(message));
final String uid = message.getUid();
final LocalMessage result = getMessage(uid);
runnable.run();
// Set a flag indicating this message has now be fully downloaded
result.setFlag(Flag.X_DOWNLOADED_FULL, true);
return result;
} catch (MessagingException e) {
throw new WrappedException(e);
}
}
});
}
/**
* The method differs slightly from the contract; If an incoming message already has a uid
* assigned and it matches the uid of an existing message then this message will replace the
* old message. It is implemented as a delete/insert. This functionality is used in saving
* of drafts and re-synchronization of updated server messages.
*
* NOTE that although this method is located in the LocalStore class, it is not guaranteed
* that the messages supplied as parameters are actually {@link LocalMessage} instances (in
* fact, in most cases, they are not). Therefore, if you want to make local changes only to a
* message, retrieve the appropriate local message instance first (if it already exists).
*/
@Override
public Map<String, String> appendMessages(List<? extends Message> messages) throws MessagingException {
return appendMessages(messages, false);
}
public void destroyMessages(final List<? extends Message> messages) {
try {
this.localStore.database.execute(true, new DbCallback<Void>() {
@Override
public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException {
for (Message message : messages) {
try {
message.destroy();
} catch (MessagingException e) {
throw new WrappedException(e);
}
}
return null;
}
});
} catch (MessagingException e) {
throw new WrappedException(e);
}
}
private ThreadInfo getThreadInfo(SQLiteDatabase db, String messageId, boolean onlyEmpty) {
String sql = "SELECT t.id, t.message_id, t.root, t.parent " +
"FROM messages m " +
"LEFT JOIN threads t ON (t.message_id = m.id) " +
"WHERE m.folder_id = ? AND m.message_id = ? " +
((onlyEmpty) ? "AND m.empty = 1 " : "") +
"ORDER BY m.id LIMIT 1";
String[] selectionArgs = { Long.toString(mFolderId), messageId };
Cursor cursor = db.rawQuery(sql, selectionArgs);
if (cursor != null) {
try {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
long threadId = cursor.getLong(0);
long msgId = cursor.getLong(1);
long rootId = (cursor.isNull(2)) ? -1 : cursor.getLong(2);
long parentId = (cursor.isNull(3)) ? -1 : cursor.getLong(3);
return new ThreadInfo(threadId, msgId, messageId, rootId, parentId);
}
} finally {
cursor.close();
}
}
return null;
}
/**
* The method differs slightly from the contract; If an incoming message already has a uid
* assigned and it matches the uid of an existing message then this message will replace
* the old message. This functionality is used in saving of drafts and re-synchronization
* of updated server messages.
*
* NOTE that although this method is located in the LocalStore class, it is not guaranteed
* that the messages supplied as parameters are actually {@link LocalMessage} instances (in
* fact, in most cases, they are not). Therefore, if you want to make local changes only to a
* message, retrieve the appropriate local message instance first (if it already exists).
* @param messages
* @param copy
* @return uidMap of srcUids -> destUids
*/
private Map<String, String> appendMessages(final List<? extends Message> messages, final boolean copy) throws MessagingException {
open(OPEN_MODE_RW);
try {
final Map<String, String> uidMap = new HashMap<String, String>();
this.localStore.database.execute(true, new DbCallback<Void>() {
@Override
public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException {
try {
for (Message message : messages) {
long oldMessageId = -1;
String uid = message.getUid();
if (uid == null || copy) {
/*
* Create a new message in the database
*/
String randomLocalUid = K9.LOCAL_UID_PREFIX +
UUID.randomUUID().toString();
if (copy) {
// Save mapping: source UID -> target UID
uidMap.put(uid, randomLocalUid);
} else {
// Modify the Message instance to reference the new UID
message.setUid(randomLocalUid);
}
// The message will be saved with the newly generated UID
uid = randomLocalUid;
} else {
/*
* Replace an existing message in the database
*/
LocalMessage oldMessage = getMessage(uid);
if (oldMessage != null) {
oldMessageId = oldMessage.getId();
}
deleteAttachments(message.getUid());
}
long rootId = -1;
long parentId = -1;
if (oldMessageId == -1) {
// This is a new message. Do the message threading.
ThreadInfo threadInfo = doMessageThreading(db, message);
oldMessageId = threadInfo.msgId;
rootId = threadInfo.rootId;
parentId = threadInfo.parentId;
}
boolean isDraft = (message.getHeader(K9.IDENTITY_HEADER) != null);
List<Part> attachments;
String text;
String html;
if (isDraft) {
// Don't modify the text/plain or text/html part of our own
// draft messages because this will cause the values stored in
// the identity header to be wrong.
ViewableContainer container =
LocalMessageExtractor.extractPartsFromDraft(message);
text = container.text;
html = container.html;
attachments = container.attachments;
} else {
ViewableContainer container =
LocalMessageExtractor.extractTextAndAttachments(LocalFolder.this.localStore.context, message);
attachments = container.attachments;
text = container.text;
html = HtmlConverter.convertEmoji2Img(container.html);
}
String preview = Message.calculateContentPreview(text);
try {
ContentValues cv = new ContentValues();
cv.put("uid", uid);
cv.put("subject", message.getSubject());
cv.put("sender_list", Address.pack(message.getFrom()));
cv.put("date", message.getSentDate() == null
? System.currentTimeMillis() : message.getSentDate().getTime());
cv.put("flags", LocalFolder.this.localStore.serializeFlags(message.getFlags()));
cv.put("deleted", message.isSet(Flag.DELETED) ? 1 : 0);
cv.put("read", message.isSet(Flag.SEEN) ? 1 : 0);
cv.put("flagged", message.isSet(Flag.FLAGGED) ? 1 : 0);
cv.put("answered", message.isSet(Flag.ANSWERED) ? 1 : 0);
cv.put("forwarded", message.isSet(Flag.FORWARDED) ? 1 : 0);
cv.put("folder_id", mFolderId);
cv.put("to_list", Address.pack(message.getRecipients(RecipientType.TO)));
cv.put("cc_list", Address.pack(message.getRecipients(RecipientType.CC)));
cv.put("bcc_list", Address.pack(message.getRecipients(RecipientType.BCC)));
cv.put("html_content", html.length() > 0 ? html : null);
cv.put("text_content", text.length() > 0 ? text : null);
cv.put("preview", preview.length() > 0 ? preview : null);
cv.put("reply_to_list", Address.pack(message.getReplyTo()));
cv.put("attachment_count", attachments.size());
cv.put("internal_date", message.getInternalDate() == null
? System.currentTimeMillis() : message.getInternalDate().getTime());
cv.put("mime_type", message.getMimeType());
cv.put("empty", 0);
String messageId = message.getMessageId();
if (messageId != null) {
cv.put("message_id", messageId);
}
long msgId;
if (oldMessageId == -1) {
msgId = db.insert("messages", "uid", cv);
// Create entry in 'threads' table
cv.clear();
cv.put("message_id", msgId);
if (rootId != -1) {
cv.put("root", rootId);
}
if (parentId != -1) {
cv.put("parent", parentId);
}
db.insert("threads", null, cv);
} else {
db.update("messages", cv, "id = ?", new String[] { Long.toString(oldMessageId) });
msgId = oldMessageId;
}
for (Part attachment : attachments) {
saveAttachment(msgId, attachment, copy);
}
saveHeaders(msgId, (MimeMessage)message);
} catch (Exception e) {
throw new MessagingException("Error appending message", e);
}
}
} catch (MessagingException e) {
throw new WrappedException(e);
}
return null;
}
});
this.localStore.notifyChange();
return uidMap;
} catch (WrappedException e) {
throw(MessagingException) e.getCause();
}
}
/**
* Update the given message in the LocalStore without first deleting the existing
* message (contrast with appendMessages). This method is used to store changes
* to the given message while updating attachments and not removing existing
* attachment data.
* TODO In the future this method should be combined with appendMessages since the Message
* contains enough data to decide what to do.
* @param message
* @throws MessagingException
*/
public void updateMessage(final LocalMessage message) throws MessagingException {
open(OPEN_MODE_RW);
try {
this.localStore.database.execute(false, new DbCallback<Void>() {
@Override
public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException {
try {
message.buildMimeRepresentation();
ViewableContainer container =
LocalMessageExtractor.extractTextAndAttachments(LocalFolder.this.localStore.context, message);
List<Part> attachments = container.attachments;
String text = container.text;
String html = HtmlConverter.convertEmoji2Img(container.html);
String preview = Message.calculateContentPreview(text);
try {
db.execSQL("UPDATE messages SET "
+ "uid = ?, subject = ?, sender_list = ?, date = ?, flags = ?, "
+ "folder_id = ?, to_list = ?, cc_list = ?, bcc_list = ?, "
+ "html_content = ?, text_content = ?, preview = ?, reply_to_list = ?, "
+ "attachment_count = ?, read = ?, flagged = ?, answered = ?, forwarded = ? "
+ "WHERE id = ?",
new Object[] {
message.getUid(),
message.getSubject(),
Address.pack(message.getFrom()),
message.getSentDate() == null ? System
.currentTimeMillis() : message.getSentDate()
.getTime(),
LocalFolder.this.localStore.serializeFlags(message.getFlags()),
mFolderId,
Address.pack(message
.getRecipients(RecipientType.TO)),
Address.pack(message
.getRecipients(RecipientType.CC)),
Address.pack(message
.getRecipients(RecipientType.BCC)),
html.length() > 0 ? html : null,
text.length() > 0 ? text : null,
preview.length() > 0 ? preview : null,
Address.pack(message.getReplyTo()),
attachments.size(),
message.isSet(Flag.SEEN) ? 1 : 0,
message.isSet(Flag.FLAGGED) ? 1 : 0,
message.isSet(Flag.ANSWERED) ? 1 : 0,
message.isSet(Flag.FORWARDED) ? 1 : 0,
message.getId()
});
for (int i = 0, count = attachments.size(); i < count; i++) {
Part attachment = attachments.get(i);
saveAttachment(message.getId(), attachment, false);
}
saveHeaders(message.getId(), message);
} catch (Exception e) {
throw new MessagingException("Error appending message", e);
}
} catch (MessagingException e) {
throw new WrappedException(e);
}
return null;
}
});
} catch (WrappedException e) {
throw(MessagingException) e.getCause();
}
this.localStore.notifyChange();
}
/**
* Save the headers of the given message. Note that the message is not
* necessarily a {@link LocalMessage} instance.
* @param id
* @param message
* @throws com.fsck.ptl.mail.MessagingException
*/
private void saveHeaders(final long id, final MimeMessage message) throws MessagingException {
this.localStore.database.execute(true, new DbCallback<Void>() {
@Override
public Void doDbWork(final SQLiteDatabase db) throws WrappedException, MessagingException {
deleteHeaders(id);
for (String name : message.getHeaderNames()) {
String[] values = message.getHeader(name);
for (String value : values) {
ContentValues cv = new ContentValues();
cv.put("message_id", id);
cv.put("name", name);
cv.put("value", value);
db.insert("headers", "name", cv);
}
}
// Remember that all headers for this message have been saved, so it is
// not necessary to download them again in case the user wants to see all headers.
List<Flag> appendedFlags = new ArrayList<Flag>();
appendedFlags.addAll(message.getFlags());
appendedFlags.add(Flag.X_GOT_ALL_HEADERS);
db.execSQL("UPDATE messages " + "SET flags = ? " + " WHERE id = ?",
new Object[]
{ LocalFolder.this.localStore.serializeFlags(appendedFlags), id });
return null;
}
});
}
void deleteHeaders(final long id) throws MessagingException {
this.localStore.database.execute(false, new DbCallback<Void>() {
@Override
public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException {
db.execSQL("DELETE FROM headers WHERE message_id = ?", new Object[]
{ id });
return null;
}
});
}
/**
* @param messageId
* @param attachment
* @param saveAsNew
* @throws IOException
* @throws MessagingException
*/
private void saveAttachment(final long messageId, final Part attachment, final boolean saveAsNew)
throws IOException, MessagingException {
try {
this.localStore.database.execute(true, new DbCallback<Void>() {
@Override
public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException {
try {
long attachmentId = -1;
Uri contentUri = null;
int size = -1;
File tempAttachmentFile = null;
if ((!saveAsNew) && (attachment instanceof LocalAttachmentBodyPart)) {
attachmentId = ((LocalAttachmentBodyPart) attachment).getAttachmentId();
}
final File attachmentDirectory = StorageManager.getInstance(LocalFolder.this.localStore.context).getAttachmentDirectory(LocalFolder.this.localStore.uUid, LocalFolder.this.localStore.database.getStorageProviderId());
if (attachment.getBody() != null) {
Body body = attachment.getBody();
if (body instanceof LocalAttachmentBody) {
contentUri = ((LocalAttachmentBody) body).getContentUri();
} else if (body instanceof Message) {
// It's a message, so use Message.writeTo() to output the
// message including all children.
Message message = (Message) body;
tempAttachmentFile = File.createTempFile("att", null, attachmentDirectory);
FileOutputStream out = new FileOutputStream(tempAttachmentFile);
try {
message.writeTo(out);
} finally {
out.close();
}
size = (int) (tempAttachmentFile.length() & 0x7FFFFFFFL);
} else {
/*
* If the attachment has a body we're expected to save it into the local store
* so we copy the data into a cached attachment file.
*/
InputStream in = MimeUtility.decodeBody(attachment.getBody());
try {
tempAttachmentFile = File.createTempFile("att", null, attachmentDirectory);
FileOutputStream out = new FileOutputStream(tempAttachmentFile);
try {
size = IOUtils.copy(in, out);
} finally {
out.close();
}
} finally {
try { in.close(); } catch (Throwable ignore) {}
}
}
}
if (size == -1) {
/*
* If the attachment is not yet downloaded see if we can pull a size
* off the Content-Disposition.
*/
String disposition = attachment.getDisposition();
if (disposition != null) {
String sizeParam = MimeUtility.getHeaderParameter(disposition, "size");
if (sizeParam != null) {
try {
size = Integer.parseInt(sizeParam);
} catch (NumberFormatException e) { /* Ignore */ }
}
}
}
if (size == -1) {
size = 0;
}
String storeData =
Utility.combine(attachment.getHeader(
MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA), ',');
String name = MimeUtility.getHeaderParameter(attachment.getContentType(), "name");
String contentId = MimeUtility.getHeaderParameter(attachment.getContentId(), null);
String contentDisposition = MimeUtility.unfoldAndDecode(attachment.getDisposition());
String dispositionType = contentDisposition;
if (dispositionType != null) {
int pos = dispositionType.indexOf(';');
if (pos != -1) {
// extract the disposition-type, "attachment", "inline" or extension-token (see the RFC 2183)
dispositionType = dispositionType.substring(0, pos);
}
}
if (name == null && contentDisposition != null) {
name = MimeUtility.getHeaderParameter(contentDisposition, "filename");
}
if (attachmentId == -1) {
ContentValues cv = new ContentValues();
cv.put("message_id", messageId);
cv.put("content_uri", contentUri != null ? contentUri.toString() : null);
cv.put("store_data", storeData);
cv.put("size", size);
cv.put("name", name);
cv.put("mime_type", attachment.getMimeType());
cv.put("content_id", contentId);
cv.put("content_disposition", dispositionType);
attachmentId = db.insert("attachments", "message_id", cv);
} else {
ContentValues cv = new ContentValues();
cv.put("content_uri", contentUri != null ? contentUri.toString() : null);
cv.put("size", size);
db.update("attachments", cv, "id = ?", new String[]
{ Long.toString(attachmentId) });
}
if (attachmentId != -1 && tempAttachmentFile != null) {
File attachmentFile = new File(attachmentDirectory, Long.toString(attachmentId));
tempAttachmentFile.renameTo(attachmentFile);
contentUri = AttachmentProvider.getAttachmentUri(
getAccount(),
attachmentId);
if (MimeUtil.isMessage(attachment.getMimeType())) {
LocalAttachmentMessageBody body = new LocalAttachmentMessageBody(
contentUri, LocalFolder.this.localStore.context);
MimeMessageHelper.setBody(attachment, body);
} else {
LocalAttachmentBody body = new LocalAttachmentBody(
contentUri, LocalFolder.this.localStore.context);
MimeMessageHelper.setBody(attachment, body);
}
ContentValues cv = new ContentValues();
cv.put("content_uri", contentUri != null ? contentUri.toString() : null);
db.update("attachments", cv, "id = ?", new String[]
{ Long.toString(attachmentId) });
}
/* The message has attachment with Content-ID */
if (contentId != null && contentUri != null) {
Cursor cursor = db.query("messages", new String[]
{ "html_content" }, "id = ?", new String[]
{ Long.toString(messageId) }, null, null, null);
try {
if (cursor.moveToNext()) {
String htmlContent = cursor.getString(0);
if (htmlContent != null) {
String newHtmlContent = htmlContent.replaceAll(
Pattern.quote("cid:" + contentId),
contentUri.toString());
ContentValues cv = new ContentValues();
cv.put("html_content", newHtmlContent);
db.update("messages", cv, "id = ?", new String[]
{ Long.toString(messageId) });
}
}
} finally {
Utility.closeQuietly(cursor);
}
}
if (attachmentId != -1 && attachment instanceof LocalAttachmentBodyPart) {
((LocalAttachmentBodyPart) attachment).setAttachmentId(attachmentId);
}
return null;
} catch (MessagingException e) {
throw new WrappedException(e);
} catch (IOException e) {
throw new WrappedException(e);
}
}
});
} catch (WrappedException e) {
final Throwable cause = e.getCause();
if (cause instanceof IOException) {
throw (IOException) cause;
}
throw (MessagingException) cause;
}
}
/**
* Changes the stored uid of the given message (using it's internal id as a key) to
* the uid in the message.
* @param message
* @throws com.fsck.ptl.mail.MessagingException
*/
public void changeUid(final LocalMessage message) throws MessagingException {
open(OPEN_MODE_RW);
final ContentValues cv = new ContentValues();
cv.put("uid", message.getUid());
this.localStore.database.execute(false, new DbCallback<Void>() {
@Override
public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException {
db.update("messages", cv, "id = ?", new String[]
{ Long.toString(message.getId()) });
return null;
}
});
//TODO: remove this once the UI code exclusively uses the database id
this.localStore.notifyChange();
}
@Override
public void setFlags(final List<? extends Message> messages, final Set<Flag> flags, final boolean value)
throws MessagingException {
open(OPEN_MODE_RW);
// Use one transaction to set all flags
try {
this.localStore.database.execute(true, new DbCallback<Void>() {
@Override
public Void doDbWork(final SQLiteDatabase db) throws WrappedException,
UnavailableStorageException {
for (Message message : messages) {
try {
message.setFlags(flags, value);
} catch (MessagingException e) {
Log.e(K9.LOG_TAG, "Something went wrong while setting flag", e);
}
}
return null;
}
});
} catch (WrappedException e) {
throw(MessagingException) e.getCause();
}
}
@Override
public void setFlags(final Set<Flag> flags, boolean value)
throws MessagingException {
open(OPEN_MODE_RW);
for (Message message : getMessages(null)) {
message.setFlags(flags, value);
}
}
@Override
public String getUidFromMessageId(Message message) throws MessagingException {
throw new MessagingException("Cannot call getUidFromMessageId on LocalFolder");
}
public void clearMessagesOlderThan(long cutoff) throws MessagingException {
open(OPEN_MODE_RO);
List<? extends Message> messages = this.localStore.getMessages(
null,
this,
"SELECT " + LocalStore.GET_MESSAGES_COLS +
"FROM messages " +
"LEFT JOIN threads ON (threads.message_id = messages.id) " +
"WHERE (empty IS NULL OR empty != 1) AND " +
"(folder_id = ? and date < ?)",
new String[] {
Long.toString(mFolderId), Long.toString(cutoff)
});
for (Message message : messages) {
message.destroy();
}
this.localStore.notifyChange();
}
public void clearAllMessages() throws MessagingException {
final String[] folderIdArg = new String[] { Long.toString(mFolderId) };
open(OPEN_MODE_RO);
try {
this.localStore.database.execute(false, new DbCallback<Void>() {
@Override
public Void doDbWork(final SQLiteDatabase db) throws WrappedException {
try {
// Get UIDs for all messages to delete
Cursor cursor = db.query("messages", new String[] { "uid" },
"folder_id = ? AND (empty IS NULL OR empty != 1)",
folderIdArg, null, null, null);
try {
// Delete attachments of these messages
while (cursor.moveToNext()) {
deleteAttachments(cursor.getString(0));
}
} finally {
cursor.close();
}
// Delete entries in 'threads' and 'messages'
db.execSQL("DELETE FROM threads WHERE message_id IN " +
"(SELECT id FROM messages WHERE folder_id = ?)", folderIdArg);
db.execSQL("DELETE FROM messages WHERE folder_id = ?", folderIdArg);
return null;
} catch (MessagingException e) {
throw new WrappedException(e);
}
}
});
} catch (WrappedException e) {
throw(MessagingException) e.getCause();
}
this.localStore.notifyChange();
setPushState(null);
setLastPush(0);
setLastChecked(0);
setVisibleLimit(getAccount().getDisplayCount());
}
@Override
public void delete(final boolean recurse) throws MessagingException {
try {
this.localStore.database.execute(false, new DbCallback<Void>() {
@Override
public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException {
try {
// We need to open the folder first to make sure we've got it's id
open(OPEN_MODE_RO);
List<? extends Message> messages = getMessages(null);
for (Message message : messages) {
deleteAttachments(message.getUid());
}
} catch (MessagingException e) {
throw new WrappedException(e);
}
db.execSQL("DELETE FROM folders WHERE id = ?", new Object[]
{ Long.toString(mFolderId), });
return null;
}
});
} catch (WrappedException e) {
throw(MessagingException) e.getCause();
}
}
@Override
public boolean equals(Object o) {
if (o instanceof LocalFolder) {
return ((LocalFolder)o).mName.equals(mName);
}
return super.equals(o);
}
@Override
public int hashCode() {
return mName.hashCode();
}
void deleteAttachments(final long messageId) throws MessagingException {
open(OPEN_MODE_RW);
this.localStore.database.execute(false, new DbCallback<Void>() {
@Override
public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException {
Cursor attachmentsCursor = null;
try {
String accountUuid = getAccountUuid();
Context context = LocalFolder.this.localStore.context;
// Get attachment IDs
String[] whereArgs = new String[] { Long.toString(messageId) };
attachmentsCursor = db.query("attachments", new String[] { "id" },
"message_id = ?", whereArgs, null, null, null);
final File attachmentDirectory = StorageManager.getInstance(LocalFolder.this.localStore.context)
.getAttachmentDirectory(LocalFolder.this.localStore.uUid, LocalFolder.this.localStore.database.getStorageProviderId());
while (attachmentsCursor.moveToNext()) {
String attachmentId = Long.toString(attachmentsCursor.getLong(0));
try {
// Delete stored attachment
File file = new File(attachmentDirectory, attachmentId);
if (file.exists()) {
file.delete();
}
// Delete thumbnail file
AttachmentProvider.deleteThumbnail(context, accountUuid,
attachmentId);
} catch (Exception e) { /* ignore */ }
}
// Delete attachment metadata from the database
db.delete("attachments", "message_id = ?", whereArgs);
} finally {
Utility.closeQuietly(attachmentsCursor);
}
return null;
}
});
}
private void deleteAttachments(final String uid) throws MessagingException {
open(OPEN_MODE_RW);
try {
this.localStore.database.execute(false, new DbCallback<Void>() {
@Override
public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException {
Cursor messagesCursor = null;
try {
messagesCursor = db.query("messages", new String[]
{ "id" }, "folder_id = ? AND uid = ?", new String[]
{ Long.toString(mFolderId), uid }, null, null, null);
while (messagesCursor.moveToNext()) {
long messageId = messagesCursor.getLong(0);
deleteAttachments(messageId);
}
} catch (MessagingException e) {
throw new WrappedException(e);
} finally {
Utility.closeQuietly(messagesCursor);
}
return null;
}
});
} catch (WrappedException e) {
throw(MessagingException) e.getCause();
}
}
@Override
public boolean isInTopGroup() {
return mInTopGroup;
}
public void setInTopGroup(boolean inTopGroup) throws MessagingException {
mInTopGroup = inTopGroup;
updateFolderColumn("top_group", mInTopGroup ? 1 : 0);
}
public Integer getLastUid() {
return mLastUid;
}
/**
* <p>Fetches the most recent <b>numeric</b> UID value in this folder. This is used by
* {@link com.fsck.ptl.controller.MessagingController#shouldNotifyForMessage} to see if messages being
* fetched are new and unread. Messages are "new" if they have a UID higher than the most recent UID prior
* to synchronization.</p>
*
* <p>This only works for protocols with numeric UIDs (like IMAP). For protocols with
* alphanumeric UIDs (like POP), this method quietly fails and shouldNotifyForMessage() will
* always notify for unread messages.</p>
*
* <p>Once Issue 1072 has been fixed, this method and shouldNotifyForMessage() should be
* updated to use internal dates rather than UIDs to determine new-ness. While this doesn't
* solve things for POP (which doesn't have internal dates), we can likely use this as a
* framework to examine send date in lieu of internal date.</p>
* @throws MessagingException
*/
public void updateLastUid() throws MessagingException {
Integer lastUid = this.localStore.database.execute(false, new DbCallback<Integer>() {
@Override
public Integer doDbWork(final SQLiteDatabase db) {
Cursor cursor = null;
try {
open(OPEN_MODE_RO);
cursor = db.rawQuery("SELECT MAX(uid) FROM messages WHERE folder_id=?", new String[] { Long.toString(mFolderId) });
if (cursor.getCount() > 0) {
cursor.moveToFirst();
return cursor.getInt(0);
}
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Unable to updateLastUid: ", e);
} finally {
Utility.closeQuietly(cursor);
}
return null;
}
});
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Updated last UID for folder " + mName + " to " + lastUid);
mLastUid = lastUid;
}
public Long getOldestMessageDate() throws MessagingException {
return this.localStore.database.execute(false, new DbCallback<Long>() {
@Override
public Long doDbWork(final SQLiteDatabase db) {
Cursor cursor = null;
try {
open(OPEN_MODE_RO);
cursor = db.rawQuery("SELECT MIN(date) FROM messages WHERE folder_id=?", new String[] { Long.toString(mFolderId) });
if (cursor.getCount() > 0) {
cursor.moveToFirst();
return cursor.getLong(0);
}
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Unable to fetch oldest message date: ", e);
} finally {
Utility.closeQuietly(cursor);
}
return null;
}
});
}
private ThreadInfo doMessageThreading(SQLiteDatabase db, Message message)
throws MessagingException {
long rootId = -1;
long parentId = -1;
String messageId = message.getMessageId();
// If there's already an empty message in the database, update that
ThreadInfo msgThreadInfo = getThreadInfo(db, messageId, true);
// Get the message IDs from the "References" header line
String[] referencesArray = message.getHeader("References");
List<String> messageIds = null;
if (referencesArray != null && referencesArray.length > 0) {
messageIds = Utility.extractMessageIds(referencesArray[0]);
}
// Append the first message ID from the "In-Reply-To" header line
String[] inReplyToArray = message.getHeader("In-Reply-To");
String inReplyTo;
if (inReplyToArray != null && inReplyToArray.length > 0) {
inReplyTo = Utility.extractMessageId(inReplyToArray[0]);
if (inReplyTo != null) {
if (messageIds == null) {
messageIds = new ArrayList<String>(1);
messageIds.add(inReplyTo);
} else if (!messageIds.contains(inReplyTo)) {
messageIds.add(inReplyTo);
}
}
}
if (messageIds == null) {
// This is not a reply, nothing to do for us.
return (msgThreadInfo != null) ?
msgThreadInfo : new ThreadInfo(-1, -1, messageId, -1, -1);
}
for (String reference : messageIds) {
ThreadInfo threadInfo = getThreadInfo(db, reference, false);
if (threadInfo == null) {
// Create placeholder message in 'messages' table
ContentValues cv = new ContentValues();
cv.put("message_id", reference);
cv.put("folder_id", mFolderId);
cv.put("empty", 1);
long newMsgId = db.insert("messages", null, cv);
// Create entry in 'threads' table
cv.clear();
cv.put("message_id", newMsgId);
if (rootId != -1) {
cv.put("root", rootId);
}
if (parentId != -1) {
cv.put("parent", parentId);
}
parentId = db.insert("threads", null, cv);
if (rootId == -1) {
rootId = parentId;
}
} else {
if (rootId != -1 && threadInfo.rootId == -1 && rootId != threadInfo.threadId) {
// We found an existing root container that is not
// the root of our current path (References).
// Connect it to the current parent.
// Let all children know who's the new root
ContentValues cv = new ContentValues();
cv.put("root", rootId);
db.update("threads", cv, "root = ?",
new String[] { Long.toString(threadInfo.threadId) });
// Connect the message to the current parent
cv.put("parent", parentId);
db.update("threads", cv, "id = ?",
new String[] { Long.toString(threadInfo.threadId) });
} else {
rootId = (threadInfo.rootId == -1) ?
threadInfo.threadId : threadInfo.rootId;
}
parentId = threadInfo.threadId;
}
}
//TODO: set in-reply-to "link" even if one already exists
long threadId;
long msgId;
if (msgThreadInfo != null) {
threadId = msgThreadInfo.threadId;
msgId = msgThreadInfo.msgId;
} else {
threadId = -1;
msgId = -1;
}
return new ThreadInfo(threadId, msgId, messageId, rootId, parentId);
}
public List<Message> extractNewMessages(final List<Message> messages)
throws MessagingException {
try {
return this.localStore.database.execute(false, new DbCallback<List<Message>>() {
@Override
public List<Message> doDbWork(final SQLiteDatabase db) throws WrappedException {
try {
open(OPEN_MODE_RW);
} catch (MessagingException e) {
throw new WrappedException(e);
}
List<Message> result = new ArrayList<Message>();
List<String> selectionArgs = new ArrayList<String>();
Set<String> existingMessages = new HashSet<String>();
int start = 0;
while (start < messages.size()) {
StringBuilder selection = new StringBuilder();
selection.append("folder_id = ? AND UID IN (");
selectionArgs.add(Long.toString(mFolderId));
int count = Math.min(messages.size() - start, LocalStore.UID_CHECK_BATCH_SIZE);
for (int i = start, end = start + count; i < end; i++) {
if (i > start) {
selection.append(",?");
} else {
selection.append("?");
}
selectionArgs.add(messages.get(i).getUid());
}
selection.append(")");
Cursor cursor = db.query("messages", LocalStore.UID_CHECK_PROJECTION,
selection.toString(), selectionArgs.toArray(LocalStore.EMPTY_STRING_ARRAY),
null, null, null);
try {
while (cursor.moveToNext()) {
String uid = cursor.getString(0);
existingMessages.add(uid);
}
} finally {
Utility.closeQuietly(cursor);
}
for (int i = start, end = start + count; i < end; i++) {
Message message = messages.get(i);
if (!existingMessages.contains(message.getUid())) {
result.add(message);
}
}
existingMessages.clear();
selectionArgs.clear();
start += count;
}
return result;
}
});
} catch (WrappedException e) {
throw(MessagingException) e.getCause();
}
}
private Account getAccount() {
return localStore.getAccount();
}
}
|
3e12666e56c8a661ba97056667d2350967e3ce23 | 5,209 | java | Java | admin-tools-security/admin-tools-security-dbuser/src/main/java/de/chandre/admintool/security/dbuser/contoller/AdminToolSecDBProfileController.java | andrehertwig/admintool | 5763c6a913244a7aab2f7564694fd6d756802116 | [
"MIT"
] | 10 | 2017-02-01T12:53:50.000Z | 2020-05-22T05:21:07.000Z | admin-tools-security/admin-tools-security-dbuser/src/main/java/de/chandre/admintool/security/dbuser/contoller/AdminToolSecDBProfileController.java | andrehertwig/admintool | 5763c6a913244a7aab2f7564694fd6d756802116 | [
"MIT"
] | 46 | 2016-08-05T17:41:30.000Z | 2021-12-18T18:16:36.000Z | admin-tools-security/admin-tools-security-dbuser/src/main/java/de/chandre/admintool/security/dbuser/contoller/AdminToolSecDBProfileController.java | andrehertwig/admintool | 5763c6a913244a7aab2f7564694fd6d756802116 | [
"MIT"
] | 8 | 2016-02-25T19:44:39.000Z | 2021-09-20T10:30:41.000Z | 40.069231 | 147 | 0.780188 | 7,761 | package de.chandre.admintool.security.dbuser.contoller;
import java.io.IOException;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import de.chandre.admintool.core.AdminTool;
import de.chandre.admintool.core.ui.ATError;
import de.chandre.admintool.security.commons.LoginController;
import de.chandre.admintool.security.commons.TemplateUserService;
import de.chandre.admintool.security.commons.auth.UserTO;
import de.chandre.admintool.security.dbuser.AdminToolSecDBProperties;
import de.chandre.admintool.security.dbuser.AdminToolSecDBTemplateUtils;
import de.chandre.admintool.security.dbuser.Constants;
import de.chandre.admintool.security.dbuser.Constants.CommunicationProcess;
import de.chandre.admintool.security.dbuser.auth.PasswordTO;
import de.chandre.admintool.security.dbuser.domain.ATUser;
import de.chandre.admintool.security.dbuser.service.AdminToolSecDBUserDetailsService;
import de.chandre.admintool.security.dbuser.service.validation.AdminToolSecDBUserValidator;
/**
*
* @author André
* @since 1.2.0
*
*/
@Controller
@RequestMapping(AdminTool.ROOTCONTEXT + "/accessmanagement/user/profile")
public class AdminToolSecDBProfileController extends ATSecDBAbctractController {
private final Log LOGGER = LogFactory.getLog(AdminToolSecDBProfileController.class);
@Autowired
private AdminToolSecDBProperties properties;
@Autowired
private TemplateUserService templateUserService;
@Autowired
private AdminToolSecDBUserDetailsService userService;
@Autowired
private AdminToolSecDBUserValidator userValidator;
@Autowired
private AdminToolSecDBTemplateUtils templateUtils;
@RequestMapping(value= {"", "/"})
public String profile(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws IOException {
if (templateUserService.isAnonymous()) {
response.sendRedirect(super.getRootContext(request) + LoginController.LOGIN_PATH);
}
addCommonContextVars(model, request);
ATUser currentUser = templateUserService.getUserPrincipal(ATUser.class);
model.put("currentUser", userService.getUserForId(currentUser.getId()));
return AdminTool.ROOTCONTEXT_NAME + Constants.CONTENT_TPL_PATH + "profile";
}
@RequestMapping(value="/update", method=RequestMethod.POST)
@ResponseBody
public Set<ATError> profileUpdate(@RequestBody UserTO userTO, HttpServletRequest request, HttpServletResponse response) throws IOException {
LOGGER.debug("receiving profile/update request");
if (templateUserService.isAnonymous()) {
return null;
}
try {
userTO.setUsername(templateUserService.getUserName());
Set<ATError> errors = userService.updateProfile(userTO);
return errors;
} catch (Exception e) {
return handleException(e, LOGGER, "error.update.profile",
Constants.MSG_KEY_PREFIX + "profile.update.profile.error", "Could not update profile");
}
}
@RequestMapping(value="/password/update", method=RequestMethod.POST)
@ResponseBody
public Set<ATError> updatePassword(@RequestBody PasswordTO userTO, HttpServletRequest request, HttpServletResponse response) throws IOException {
LOGGER.debug("receiving profile/password/update request");
if (!properties.getUsers().isDirectPasswordChangeInProfileAllowed() || templateUserService.isAnonymous()) {
return null;
}
try {
String userName = templateUserService.getUserName();
Set<ATError> errors = userValidator.validatePasswordChange(userName, userTO.getCurrentPassword(),
userTO.getNewPassword(), userTO.getPasswordConfirm());
if(CollectionUtils.isEmpty(errors)) {
userService.updatePassword(userName, userTO.getNewPassword());
}
return errors;
} catch (Exception e) {
return handleException(e, LOGGER, "error.update.password",
Constants.MSG_KEY_PREFIX + "profile.update.password.error", "Could not update password");
}
}
@RequestMapping(value="/password/reset", method=RequestMethod.POST)
@ResponseBody
public String resetPassword( HttpServletRequest request, HttpServletResponse response) throws IOException {
LOGGER.debug("receiving profile/password/reset request");
if (!templateUtils.isCommunicatorImplemented() || templateUserService.isAnonymous()) {
return Boolean.FALSE.toString();
}
try {
userService.createResetPassword(templateUserService.getUserName(), CommunicationProcess.RESET_PASSWORD_REQUEST_SELF);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
return Boolean.FALSE.toString();
}
return Boolean.TRUE.toString();
}
}
|
3e1267f86bac7427823f49ef8c39f7a7bf9f111e | 1,625 | java | Java | src/main/java/org/identifiers/org/cloud/ws/metadata/channels/Subscriber.java | identifiers-org/cloud-ws-metadata | 1a06d2e332cb3b482827719a0ddf657a24eccc78 | [
"MIT"
] | null | null | null | src/main/java/org/identifiers/org/cloud/ws/metadata/channels/Subscriber.java | identifiers-org/cloud-ws-metadata | 1a06d2e332cb3b482827719a0ddf657a24eccc78 | [
"MIT"
] | 34 | 2018-02-26T11:39:15.000Z | 2020-10-20T09:39:03.000Z | src/main/java/org/identifiers/org/cloud/ws/metadata/channels/Subscriber.java | identifiers-org/cloud-ws-metadata | 1a06d2e332cb3b482827719a0ddf657a24eccc78 | [
"MIT"
] | null | null | null | 35.347826 | 93 | 0.751538 | 7,762 | package org.identifiers.org.cloud.ws.metadata.channels;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import java.util.HashSet;
import java.util.Set;
/**
* Project: metadata
* Package: org.identifiers.org.cloud.ws.metadata.channels
* Timestamp: 2018-09-17 10:54
*
* @author Manuel Bernal Llinares <ychag@example.com>
* ---
*/
public abstract class Subscriber<K, V> implements MessageListener {
private static final Logger logger = LoggerFactory.getLogger(Subscriber.class);
private Set<Listener<V>> listeners = new HashSet<>();
protected abstract RedisMessageListenerContainer getRedisContainer();
protected abstract ChannelTopic getChannelTopic();
protected abstract RedisTemplate<K, V> getRedisTemplate();
protected void doRegisterSubscriber() {
logger.info("[REGISTER] for topic '{}'", getChannelTopic().getTopic());
getRedisContainer().addMessageListener(this, getChannelTopic());
}
public void addListener(Listener<V> listener) {
listeners.add(listener);
}
@Override
public void onMessage(Message message, byte[] bytes) {
V value = (V) getRedisTemplate().getValueSerializer().deserialize(message.getBody());
listeners.parallelStream().forEach(listener -> listener.process(value));
}
}
|
3e126874986ba72a3ab84c4e60b2936b6892f36d | 10,750 | java | Java | java/src/com/vmware/avi/sdk/model/LicenseTransactionDetails.java | yograjshisode/sdk | ad5579229a2821ba6d85f61bff3e7f457e0cce77 | [
"Apache-2.0"
] | 37 | 2016-03-14T22:27:17.000Z | 2022-03-03T05:18:39.000Z | java/src/com/vmware/avi/sdk/model/LicenseTransactionDetails.java | yograjshisode/sdk | ad5579229a2821ba6d85f61bff3e7f457e0cce77 | [
"Apache-2.0"
] | 195 | 2016-03-14T23:47:55.000Z | 2021-05-12T11:28:56.000Z | java/src/com/vmware/avi/sdk/model/LicenseTransactionDetails.java | yograjshisode/sdk | ad5579229a2821ba6d85f61bff3e7f457e0cce77 | [
"Apache-2.0"
] | 50 | 2016-03-14T05:52:14.000Z | 2022-01-06T06:12:00.000Z | 38.808664 | 135 | 0.682605 | 7,763 | package com.vmware.avi.sdk.model;
import java.util.*;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
/**
* The LicenseTransactionDetails is a POJO class extends AviRestResource that used for creating
* LicenseTransactionDetails.
*
* @version 1.0
* @since
*
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class LicenseTransactionDetails {
@JsonProperty("cookie")
private String cookie = null;
@JsonProperty("description")
private String description = null;
@JsonProperty("id")
private String id = null;
@JsonProperty("licensed_service_cores")
private Float licensedServiceCores = null;
@JsonProperty("operation")
private String operation = null;
@JsonProperty("overdraft")
private Boolean overdraft = null;
@JsonProperty("service_cores")
private Float serviceCores = null;
@JsonProperty("tenant_uuid")
private String tenantUuid = null;
@JsonProperty("tier")
private String tier = null;
/**
* This is the getter method this will return the attribute value.
* Placeholder for description of property cookie of obj type licensetransactiondetails field type str type string.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return cookie
*/
public String getCookie() {
return cookie;
}
/**
* This is the setter method to the attribute.
* Placeholder for description of property cookie of obj type licensetransactiondetails field type str type string.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @param cookie set the cookie.
*/
public void setCookie(String cookie) {
this.cookie = cookie;
}
/**
* This is the getter method this will return the attribute value.
* User defined description for the object.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return description
*/
public String getDescription() {
return description;
}
/**
* This is the setter method to the attribute.
* User defined description for the object.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @param description set the description.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* This is the getter method this will return the attribute value.
* Placeholder for description of property id of obj type licensetransactiondetails field type str type string.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return id
*/
public String getId() {
return id;
}
/**
* This is the setter method to the attribute.
* Placeholder for description of property id of obj type licensetransactiondetails field type str type string.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @param id set the id.
*/
public void setId(String id) {
this.id = id;
}
/**
* This is the getter method this will return the attribute value.
* Placeholder for description of property licensed_service_cores of obj type licensetransactiondetails field type str type float.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return licensedServiceCores
*/
public Float getLicensedServiceCores() {
return licensedServiceCores;
}
/**
* This is the setter method to the attribute.
* Placeholder for description of property licensed_service_cores of obj type licensetransactiondetails field type str type float.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @param licensedServiceCores set the licensedServiceCores.
*/
public void setLicensedServiceCores(Float licensedServiceCores) {
this.licensedServiceCores = licensedServiceCores;
}
/**
* This is the getter method this will return the attribute value.
* Placeholder for description of property operation of obj type licensetransactiondetails field type str type string.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return operation
*/
public String getOperation() {
return operation;
}
/**
* This is the setter method to the attribute.
* Placeholder for description of property operation of obj type licensetransactiondetails field type str type string.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @param operation set the operation.
*/
public void setOperation(String operation) {
this.operation = operation;
}
/**
* This is the getter method this will return the attribute value.
* Placeholder for description of property overdraft of obj type licensetransactiondetails field type str type boolean.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return overdraft
*/
public Boolean getOverdraft() {
return overdraft;
}
/**
* This is the setter method to the attribute.
* Placeholder for description of property overdraft of obj type licensetransactiondetails field type str type boolean.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @param overdraft set the overdraft.
*/
public void setOverdraft(Boolean overdraft) {
this.overdraft = overdraft;
}
/**
* This is the getter method this will return the attribute value.
* Placeholder for description of property service_cores of obj type licensetransactiondetails field type str type float.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return serviceCores
*/
public Float getServiceCores() {
return serviceCores;
}
/**
* This is the setter method to the attribute.
* Placeholder for description of property service_cores of obj type licensetransactiondetails field type str type float.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @param serviceCores set the serviceCores.
*/
public void setServiceCores(Float serviceCores) {
this.serviceCores = serviceCores;
}
/**
* This is the getter method this will return the attribute value.
* Unique object identifier of tenant.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return tenantUuid
*/
public String getTenantUuid() {
return tenantUuid;
}
/**
* This is the setter method to the attribute.
* Unique object identifier of tenant.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @param tenantUuid set the tenantUuid.
*/
public void setTenantUuid(String tenantUuid) {
this.tenantUuid = tenantUuid;
}
/**
* This is the getter method this will return the attribute value.
* Placeholder for description of property tier of obj type licensetransactiondetails field type str type string.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return tier
*/
public String getTier() {
return tier;
}
/**
* This is the setter method to the attribute.
* Placeholder for description of property tier of obj type licensetransactiondetails field type str type string.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @param tier set the tier.
*/
public void setTier(String tier) {
this.tier = tier;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LicenseTransactionDetails objLicenseTransactionDetails = (LicenseTransactionDetails) o;
return Objects.equals(this.id, objLicenseTransactionDetails.id)&&
Objects.equals(this.cookie, objLicenseTransactionDetails.cookie)&&
Objects.equals(this.tenantUuid, objLicenseTransactionDetails.tenantUuid)&&
Objects.equals(this.tier, objLicenseTransactionDetails.tier)&&
Objects.equals(this.operation, objLicenseTransactionDetails.operation)&&
Objects.equals(this.serviceCores, objLicenseTransactionDetails.serviceCores)&&
Objects.equals(this.licensedServiceCores, objLicenseTransactionDetails.licensedServiceCores)&&
Objects.equals(this.overdraft, objLicenseTransactionDetails.overdraft)&&
Objects.equals(this.description, objLicenseTransactionDetails.description);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class LicenseTransactionDetails {\n");
sb.append(" cookie: ").append(toIndentedString(cookie)).append("\n");
sb.append(" description: ").append(toIndentedString(description)).append("\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" licensedServiceCores: ").append(toIndentedString(licensedServiceCores)).append("\n");
sb.append(" operation: ").append(toIndentedString(operation)).append("\n");
sb.append(" overdraft: ").append(toIndentedString(overdraft)).append("\n");
sb.append(" serviceCores: ").append(toIndentedString(serviceCores)).append("\n");
sb.append(" tenantUuid: ").append(toIndentedString(tenantUuid)).append("\n");
sb.append(" tier: ").append(toIndentedString(tier)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
3e1268769598a864372982b2e562d3b8b7554714 | 5,571 | java | Java | src/main/java/org/scijava/jupyter/kernel/evaluator/Worker.java | jasminmartin/scijava-jupyter-kernel | e0eb0b7f10c60c1161ea9b31eed3ac25662e2450 | [
"Apache-2.0"
] | 181 | 2017-06-08T19:56:38.000Z | 2021-12-18T17:07:07.000Z | src/main/java/org/scijava/jupyter/kernel/evaluator/Worker.java | jasminmartin/scijava-jupyter-kernel | e0eb0b7f10c60c1161ea9b31eed3ac25662e2450 | [
"Apache-2.0"
] | 43 | 2017-06-02T20:59:44.000Z | 2022-02-03T17:18:31.000Z | src/main/java/org/scijava/jupyter/kernel/evaluator/Worker.java | jasminmartin/scijava-jupyter-kernel | e0eb0b7f10c60c1161ea9b31eed3ac25662e2450 | [
"Apache-2.0"
] | 44 | 2017-06-18T17:04:11.000Z | 2021-11-26T15:25:39.000Z | 31.474576 | 115 | 0.72644 | 7,764 | /*-
* #%L
* SciJava polyglot kernel for Jupyter.
* %%
* Copyright (C) 2017 Hadrien Mary
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.scijava.jupyter.kernel.evaluator;
import com.twosigma.beakerx.jvm.object.SimpleEvaluationObject;
import com.twosigma.beakerx.mimetype.MIMEContainer;
import java.io.Reader;
import java.io.StringReader;
import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import org.scijava.Context;
import org.scijava.convert.ConvertService;
import org.scijava.log.LogService;
import org.scijava.module.ModuleException;
import org.scijava.module.ModuleRunner;
import org.scijava.module.process.PostprocessorPlugin;
import org.scijava.module.process.PreprocessorPlugin;
import org.scijava.notebook.converter.output.NotebookOutput;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.PluginService;
import org.scijava.script.ScriptInfo;
import org.scijava.script.ScriptLanguage;
import org.scijava.script.ScriptModule;
import org.scijava.util.ClassUtils;
public class Worker implements Runnable {
@Parameter
private LogService log;
@Parameter
private Context context;
@Parameter
private PluginService pluginService;
@Parameter
private ConvertService convertService;
private final Map<String, ScriptEngine> scriptEngines;
private final Map<String, ScriptLanguage> scriptLanguages;
private String languageName;
SimpleEvaluationObject seo = null;
String code = null;
Worker(Context context, Map<String, ScriptEngine> scriptEngines, Map<String, ScriptLanguage> scriptLanguages) {
context.inject(this);
this.scriptEngines = scriptEngines;
this.scriptLanguages = scriptLanguages;
}
public void setup(SimpleEvaluationObject seo, String code, String languageName) {
this.seo = seo;
this.code = code;
this.languageName = languageName;
}
@Override
public void run() {
ScriptLanguage scriptLanguage = this.scriptLanguages.get(this.languageName);
ScriptEngine scriptEngine = this.scriptEngines.get(this.languageName);
final Reader input = new StringReader(this.code);
final ScriptInfo info = new ScriptInfo(context, "dummy.py", input);
info.setLanguage(scriptLanguage);
this.seo.setOutputHandler();
try {
// create the ScriptModule instance
final ScriptModule module = info.createModule();
context.inject(module);
// HACK: Inject our cached script engine instance, rather
// than letting the ScriptModule instance create its own.
final Field f = ClassUtils.getField(ScriptModule.class, "scriptEngine");
ClassUtils.setValue(f, module, scriptEngine);
// execute the code
final List<PreprocessorPlugin> pre = pluginService.createInstancesOfType(PreprocessorPlugin.class);
final List<PostprocessorPlugin> post = pluginService.createInstancesOfType(PostprocessorPlugin.class);
final ModuleRunner runner = new ModuleRunner(context, module, pre, post);
runner.run();
// accumulate the outputs into an ordered map
final Map<String, Object> outputTable = new LinkedHashMap<>();
info.outputs().forEach(output -> {
final String name = output.getName();
final Object value = output.getValue(module);
if (value != null) {
outputTable.put(name, value);
}
});
// convert result into a notebook-friendly form
Object output = null;
try {
if (outputTable.size() == 0) {
output = null;
} else if (outputTable.size() == 1) {
output = outputTable.values().toArray()[0];
if (!(output instanceof MIMEContainer)) {
output = convertService.convert(output, NotebookOutput.class);
if (output == null) {
log.warn("[WARNING] No suitable converter found");
output = outputTable.values().toArray()[0];
}
}
} else {
output = convertService.convert(outputTable,
NotebookOutput.class);
if (output == null) {
log.warn("[WARNING] No suitable converter found");
output = outputTable;
}
}
} catch (Exception e) {
e.printStackTrace();
output = "[ERROR]";
} finally {
this.seo.finished(output);
}
this.syncBindings(scriptEngine, scriptLanguage);
} catch (final ThreadDeath ex) {
seo.error("Execution canceled");
log.error(ex);
} catch (final ModuleException t) {
seo.error(t.getMessage());
log.error(t);
}
this.seo.clrOutputHandler();
this.seo.executeCodeCallback();
}
private void syncBindings(ScriptEngine scriptEngine, ScriptLanguage scriptLanguage) {
Bindings currentBindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
this.scriptEngines.forEach((String name, ScriptEngine engine) -> {
Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
currentBindings.keySet().forEach((String key) -> {
bindings.put(key, scriptLanguage.decode(currentBindings.get(key)));
});
});
}
}
|
3e1268991079e440a47d55adf8ccf3672c4e491e | 263 | java | Java | src/main/java/com/atlassian/jira/cloud/jenkins/deploymentinfo/client/model/package-info.java | PatrikSchalin/atlassian-jira-software-cloud-plugin | 67ba8d4f202c08f877e31956fe33e02f16c395f3 | [
"Apache-2.0"
] | 34 | 2019-07-09T04:38:08.000Z | 2022-03-15T11:57:54.000Z | src/main/java/com/atlassian/jira/cloud/jenkins/deploymentinfo/client/model/package-info.java | PatrikSchalin/atlassian-jira-software-cloud-plugin | 67ba8d4f202c08f877e31956fe33e02f16c395f3 | [
"Apache-2.0"
] | 17 | 2019-06-24T02:48:50.000Z | 2022-03-24T04:06:52.000Z | src/main/java/com/atlassian/jira/cloud/jenkins/deploymentinfo/client/model/package-info.java | PatrikSchalin/atlassian-jira-software-cloud-plugin | 67ba8d4f202c08f877e31956fe33e02f16c395f3 | [
"Apache-2.0"
] | 30 | 2019-09-17T13:46:54.000Z | 2022-03-15T11:57:57.000Z | 32.875 | 71 | 0.889734 | 7,765 | @ParametersAreNonnullByDefault
@ReturnValuesAreNonnullByDefault
package com.atlassian.jira.cloud.jenkins.deploymentinfo.client.model;
import edu.umd.cs.findbugs.annotations.ReturnValuesAreNonnullByDefault;
import javax.annotation.ParametersAreNonnullByDefault;
|
3e12689bf26b6b1d0b584801df65276df2cf6a33 | 267 | java | Java | core/group/src/main/java/com/cmpl/web/core/group/GroupRepository.java | lperrod/web | d194be2c58dd7430fd8fd869e15d67808e61d469 | [
"Apache-2.0"
] | null | null | null | core/group/src/main/java/com/cmpl/web/core/group/GroupRepository.java | lperrod/web | d194be2c58dd7430fd8fd869e15d67808e61d469 | [
"Apache-2.0"
] | null | null | null | core/group/src/main/java/com/cmpl/web/core/group/GroupRepository.java | lperrod/web | d194be2c58dd7430fd8fd869e15d67808e61d469 | [
"Apache-2.0"
] | null | null | null | 24.272727 | 66 | 0.827715 | 7,766 | package com.cmpl.web.core.group;
import com.cmpl.web.core.common.repository.BaseRepository;
import com.cmpl.web.core.models.BOGroup;
import org.springframework.stereotype.Repository;
@Repository
public interface GroupRepository extends BaseRepository<BOGroup> {
}
|
3e1268a8cca71e5dc30288fe1dd9ff0bd98f2244 | 368 | java | Java | src/test/java/com/github/andrewapj/todoapi/api/model/ApiTodoListSummaryTest.java | andrewapj/todo-api | ade37da41815d899b84458bbac26021ee52afac8 | [
"MIT"
] | null | null | null | src/test/java/com/github/andrewapj/todoapi/api/model/ApiTodoListSummaryTest.java | andrewapj/todo-api | ade37da41815d899b84458bbac26021ee52afac8 | [
"MIT"
] | null | null | null | src/test/java/com/github/andrewapj/todoapi/api/model/ApiTodoListSummaryTest.java | andrewapj/todo-api | ade37da41815d899b84458bbac26021ee52afac8 | [
"MIT"
] | null | null | null | 23 | 67 | 0.766304 | 7,767 | package com.github.andrewapj.todoapi.api.model;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class ApiTodoListSummaryTest {
@Test
public void equalsContract() {
EqualsVerifier.forClass(ApiTodoListSummary.class).verify();
}
}
|
3e1268bab2570e161fbfd72ed9446562961d8af3 | 10,253 | java | Java | platform/analysis-api/src/com/intellij/lang/documentation/DocumentationProvider.java | 06needhamt/intellij-community | 63d7b8030e4fdefeb4760e511e289f7e6b3a5c5b | [
"Apache-2.0"
] | 2 | 2019-04-28T07:48:50.000Z | 2020-12-11T14:18:08.000Z | platform/analysis-api/src/com/intellij/lang/documentation/DocumentationProvider.java | 06needhamt/intellij-community | 63d7b8030e4fdefeb4760e511e289f7e6b3a5c5b | [
"Apache-2.0"
] | null | null | null | platform/analysis-api/src/com/intellij/lang/documentation/DocumentationProvider.java | 06needhamt/intellij-community | 63d7b8030e4fdefeb4760e511e289f7e6b3a5c5b | [
"Apache-2.0"
] | null | null | null | 49.771845 | 147 | 0.734419 | 7,768 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.lang.documentation;
import com.intellij.codeInsight.documentation.DocumentationManagerProtocol;
import com.intellij.codeInsight.documentation.DocumentationManagerUtil;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.NlsSafe;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiDocCommentBase;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.function.Consumer;
/**
* Contributes content to the following IDE features:
* <ul>
* <li>Quick Documentation (invoked via explicit action or shown on mouse hover)</li>
* <li>Navigation info (shown in editor on Ctrl/Cmd+mouse hover)</li>
* <li>Rendered representation of documentation comments</li>
* </ul>
* <p>
* Extend {@link AbstractDocumentationProvider}.
* <p>
* Language-specific instance should be registered in {@code com.intellij.lang.documentationProvider} extension point; otherwise use
* {@code com.intellij.documentationProvider}.
* </p>
*
* @see com.intellij.lang.LanguageDocumentation
* @see DocumentationProviderEx
* @see ExternalDocumentationProvider
* @see ExternalDocumentationHandler
*/
public interface DocumentationProvider {
/**
* Please use {@code com.intellij.lang.documentationProvider} instead of this for language-specific documentation.
*/
ExtensionPointName<DocumentationProvider> EP_NAME = ExtensionPointName.create("com.intellij.documentationProvider");
/**
* Returns the text to show in the Ctrl-hover popup for the specified element.
*
* @param element the element for which the documentation is requested (for example, if the mouse is over
* a method reference, this will be the method to which the reference is resolved).
* @param originalElement the element under the mouse cursor
* @return the documentation to show, or {@code null} if the provider can't provide any documentation for this element. Documentation can contain
* HTML markup. If HTML special characters need to be shown in popup, they should be properly escaped.
*/
@Nullable
default String getQuickNavigateInfo(PsiElement element, PsiElement originalElement) {
return null;
}
/**
* Returns the list of possible URLs to show as external documentation for the specified element.
*
* @param element the element for which the documentation is requested (for example, if the mouse is over
* a method reference, this will be the method to which the reference is resolved).
* @param originalElement the element under the mouse cursor
* @return the list of URLs to open in the browser or to use for showing documentation internally ({@link ExternalDocumentationProvider}).
* If the list contains a single URL, it will be opened.
* If the list contains multiple URLs, the user will be prompted to choose one of them.
* For {@link ExternalDocumentationProvider}, first URL, yielding non-empty result in
* {@link ExternalDocumentationProvider#fetchExternalDocumentation(Project, PsiElement, List, boolean)} will be used.
*/
@Nullable
default List<String> getUrlFor(PsiElement element, PsiElement originalElement) {
return null;
}
/**
* <p>Callback for asking the doc provider for the complete documentation.
* Underlying implementation may be time-consuming, that's why this method is expected not to be called from EDT.</p>
*
* <p>One can use {@link DocumentationMarkup} to get proper content layout. Typical sample will look like this:
* <pre>
* DEFINITION_START + definition + DEFINITION_END +
* CONTENT_START + main description + CONTENT_END +
* SECTIONS_START +
* SECTION_HEADER_START + section name +
* SECTION_SEPARATOR + "<p>" + section content + SECTION_END +
* ... +
* SECTIONS_END
* </pre>
* </p>
* To show different content on mouse hover in editor, {@link #generateHoverDoc(PsiElement, PsiElement)} should be implemented.
*
* @param element the element for which the documentation is requested (for example, if the mouse is over
* a method reference, this will be the method to which the reference is resolved).
* @param originalElement the element under the mouse cursor
* @return target element's documentation, or {@code null} if provider is unable to generate documentation
* for the given element
*/
@Nullable
default @NlsSafe String generateDoc(PsiElement element, @Nullable PsiElement originalElement) {
return null;
}
/**
* Same as {@link #generateDoc(PsiElement, PsiElement)}, but used for documentation showed on mouse hover in editor.
* <p>
* At the moment it's only invoked to get initial on-hover documentation. If user navigates any link in that documentation,
* {@link #generateDoc(PsiElement, PsiElement)} will be used to fetch corresponding content.
*/
@Nullable
default String generateHoverDoc(@NotNull PsiElement element, @Nullable PsiElement originalElement) {
return generateDoc(element, originalElement);
}
/**
* @deprecated Override {@link #generateRenderedDoc(PsiDocCommentBase)} instead
*/
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2021.2")
default @Nullable @NlsSafe String generateRenderedDoc(@NotNull PsiElement element) {
return null;
}
/**
* This is used to display rendered documentation in editor, in place of corresponding documentation comment's text.
*
* @see #collectDocComments(PsiFile, Consumer)
*/
@ApiStatus.Experimental
default @Nullable @NlsSafe String generateRenderedDoc(@NotNull PsiDocCommentBase comment) {
PsiElement target = comment.getOwner();
return generateRenderedDoc(target == null ? comment : target);
}
/**
* This defines documentation comments in file, which can be rendered in place. HTML content to be displayed will be obtained using
* {@link #generateRenderedDoc(PsiDocCommentBase)} method.
* <p>
* To support cases, when rendered fragment doesn't have representing {@code PsiDocCommentBase} element (e.g. for the sequence of line
* comments in languages not having a block comment concept), fake elements (not existing in the {@code file}) might be returned. In such
* a case, {@link #findDocComment(PsiFile, TextRange)} should also be implemented by the documentation provider, for the rendered
* documentation view to work correctly.
*/
@ApiStatus.Experimental
default void collectDocComments(@NotNull PsiFile file, @NotNull Consumer<? super @NotNull PsiDocCommentBase> sink) {}
/**
* This method is needed to support rendered representation of documentation comments in editor. It should return doc comment located at
* the provided text range in a file. Overriding the default implementation only makes sense for languages which use fake
* {@code PsiDocCommentBase} implementations (e.g. in cases when rendered view is provided for a set of adjacent line comments, and
* there's no real {@code PsiDocCommentBase} element in a file representing the range to render).
*
* @see #collectDocComments(PsiFile, Consumer)
*/
@ApiStatus.Experimental
default @Nullable PsiDocCommentBase findDocComment(@NotNull PsiFile file, @NotNull TextRange range) {
PsiDocCommentBase comment = PsiTreeUtil.getParentOfType(file.findElementAt(range.getStartOffset()), PsiDocCommentBase.class, false);
return comment == null || !range.equals(comment.getTextRange()) ? null : comment;
}
@Nullable
default PsiElement getDocumentationElementForLookupItem(PsiManager psiManager, Object object, PsiElement element) {
return null;
}
/**
* Returns the target element for a link in a documentation comment. The link needs to use the
* {@link DocumentationManagerProtocol#PSI_ELEMENT_PROTOCOL} protocol.
*
* @param psiManager the PSI manager for the project in which the documentation is requested.
* @param link the text of the link, not including the protocol.
* @param context the element from which the navigation is performed.
* @return the navigation target, or {@code null} if the link couldn't be resolved.
* @see DocumentationManagerUtil#createHyperlink(StringBuilder, String, String, boolean)
*/
@Nullable
default PsiElement getDocumentationElementForLink(PsiManager psiManager, String link, PsiElement context) {
return null;
}
/**
* Override this method if standard platform's choice for target PSI element to show documentation for (element either declared or
* referenced at target offset) isn't suitable for your language. For example, it could be a keyword where there's no
* {@link com.intellij.psi.PsiReference}, but for which users might benefit from context help.
*
* @param targetOffset equals to caret offset for 'Quick Documentation' action, and to offset under mouse cursor for documentation shown
* on mouse hover
* @param contextElement the leaf PSI element in {@code file} at target offset
* @return target PSI element to show documentation for, or {@code null} if it should be determined by standard platform's logic (default
* behaviour)
*/
@Nullable
default PsiElement getCustomDocumentationElement(@NotNull final Editor editor,
@NotNull final PsiFile file,
@Nullable PsiElement contextElement,
int targetOffset) {
//noinspection deprecation
return (this instanceof DocumentationProviderEx)
? ((DocumentationProviderEx)this).getCustomDocumentationElement(editor, file, contextElement)
: null;
}
} |
3e126914d2d1e539a70278e16ed30303e41e18fe | 4,691 | java | Java | hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/HoodieWriteCommitCallbackConfig.java | tildehacker-harness/hudi | 371526789d663dee85041eb31c27c52c81ef87ef | [
"Apache-2.0"
] | 3 | 2021-01-20T09:51:33.000Z | 2021-07-14T03:02:48.000Z | hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/HoodieWriteCommitCallbackConfig.java | tildehacker-harness/hudi | 371526789d663dee85041eb31c27c52c81ef87ef | [
"Apache-2.0"
] | null | null | null | hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/HoodieWriteCommitCallbackConfig.java | tildehacker-harness/hudi | 371526789d663dee85041eb31c27c52c81ef87ef | [
"Apache-2.0"
] | null | null | null | 38.138211 | 116 | 0.753784 | 7,769 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hudi.config;
import org.apache.hudi.common.config.ConfigProperty;
import org.apache.hudi.common.config.HoodieConfig;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
/**
* Write callback related config.
*/
public class HoodieWriteCommitCallbackConfig extends HoodieConfig {
public static final String CALLBACK_PREFIX = "hoodie.write.commit.callback.";
public static final ConfigProperty<Boolean> CALLBACK_ON = ConfigProperty
.key(CALLBACK_PREFIX + "on")
.defaultValue(false)
.sinceVersion("0.6.0")
.withDocumentation("Turn callback on/off. off by default.");
public static final ConfigProperty<String> CALLBACK_CLASS_PROP = ConfigProperty
.key(CALLBACK_PREFIX + "class")
.defaultValue("org.apache.hudi.callback.impl.HoodieWriteCommitHttpCallback")
.sinceVersion("0.6.0")
.withDocumentation("Full path of callback class and must be a subclass of HoodieWriteCommitCallback class, "
+ "org.apache.hudi.callback.impl.HoodieWriteCommitHttpCallback by default");
// ***** HTTP callback configs *****
public static final ConfigProperty<String> CALLBACK_HTTP_URL_PROP = ConfigProperty
.key(CALLBACK_PREFIX + "http.url")
.noDefaultValue()
.sinceVersion("0.6.0")
.withDocumentation("Callback host to be sent along with callback messages");
public static final ConfigProperty<String> CALLBACK_HTTP_API_KEY = ConfigProperty
.key(CALLBACK_PREFIX + "http.api.key")
.defaultValue("hudi_write_commit_http_callback")
.sinceVersion("0.6.0")
.withDocumentation("Http callback API key. hudi_write_commit_http_callback by default");
public static final ConfigProperty<Integer> CALLBACK_HTTP_TIMEOUT_SECONDS = ConfigProperty
.key(CALLBACK_PREFIX + "http.timeout.seconds")
.defaultValue(3)
.sinceVersion("0.6.0")
.withDocumentation("Callback timeout in seconds. 3 by default");
private HoodieWriteCommitCallbackConfig() {
super();
}
public static HoodieWriteCommitCallbackConfig.Builder newBuilder() {
return new HoodieWriteCommitCallbackConfig.Builder();
}
public static class Builder {
private final HoodieWriteCommitCallbackConfig writeCommitCallbackConfig = new HoodieWriteCommitCallbackConfig();
public HoodieWriteCommitCallbackConfig.Builder fromFile(File propertiesFile) throws IOException {
try (FileReader reader = new FileReader(propertiesFile)) {
this.writeCommitCallbackConfig.getProps().load(reader);
return this;
}
}
public HoodieWriteCommitCallbackConfig.Builder fromProperties(Properties props) {
this.writeCommitCallbackConfig.getProps().putAll(props);
return this;
}
public HoodieWriteCommitCallbackConfig.Builder writeCommitCallbackOn(String callbackOn) {
writeCommitCallbackConfig.setValue(CALLBACK_ON, callbackOn);
return this;
}
public HoodieWriteCommitCallbackConfig.Builder withCallbackClass(String callbackClass) {
writeCommitCallbackConfig.setValue(CALLBACK_CLASS_PROP, callbackClass);
return this;
}
public HoodieWriteCommitCallbackConfig.Builder withCallbackHttpUrl(String url) {
writeCommitCallbackConfig.setValue(CALLBACK_HTTP_URL_PROP, url);
return this;
}
public Builder withCallbackHttpTimeoutSeconds(String timeoutSeconds) {
writeCommitCallbackConfig.setValue(CALLBACK_HTTP_TIMEOUT_SECONDS, timeoutSeconds);
return this;
}
public Builder withCallbackHttpApiKey(String apiKey) {
writeCommitCallbackConfig.setValue(CALLBACK_HTTP_API_KEY, apiKey);
return this;
}
public HoodieWriteCommitCallbackConfig build() {
writeCommitCallbackConfig.setDefaults(HoodieWriteCommitCallbackConfig.class.getName());
return writeCommitCallbackConfig;
}
}
}
|
3e12697a7975643f62af35144818a820f38213b4 | 4,101 | java | Java | src/test/java/seedu/address/logic/parser/SetMemberAvailabilityCommandParserTest.java | felix-ong/tp | d6125343ecfa7b7b494be307e147ee04f75684b5 | [
"MIT"
] | null | null | null | src/test/java/seedu/address/logic/parser/SetMemberAvailabilityCommandParserTest.java | felix-ong/tp | d6125343ecfa7b7b494be307e147ee04f75684b5 | [
"MIT"
] | 166 | 2021-09-27T14:13:14.000Z | 2021-11-10T12:21:22.000Z | src/test/java/seedu/address/logic/parser/SetMemberAvailabilityCommandParserTest.java | felix-ong/tp | d6125343ecfa7b7b494be307e147ee04f75684b5 | [
"MIT"
] | 4 | 2021-09-13T16:10:51.000Z | 2021-09-26T17:02:37.000Z | 43.168421 | 119 | 0.732504 | 7,770 | package seedu.address.logic.parser;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.address.logic.commands.CommandTestUtil.AVAILABILITY_DESC_BOB;
import static seedu.address.logic.commands.CommandTestUtil.INVALID_AVAILABILITY_DESC;
import static seedu.address.logic.commands.CommandTestUtil.NAME_DESC_BOB;
import static seedu.address.logic.parser.CommandParserTestUtil.assertParseFailure;
import static seedu.address.logic.parser.CommandParserTestUtil.assertParseSuccess;
import java.time.DayOfWeek;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
import seedu.address.commons.core.index.Index;
import seedu.address.logic.commands.SetMemberAvailabilityCommand;
import seedu.address.logic.parser.exceptions.ParseException;
import seedu.address.model.member.Availability;
public class SetMemberAvailabilityCommandParserTest {
private SetMemberAvailabilityCommandParser parser = new SetMemberAvailabilityCommandParser();
@Test
public void parse_emptyArgs_exceptionThrown() {
assertParseFailure(parser, " ",
String.format(MESSAGE_INVALID_COMMAND_FORMAT, SetMemberAvailabilityCommand.MESSAGE_USAGE));
}
@Test
public void parse_emptyIndices_exceptionThrown() {
assertParseFailure(parser, AVAILABILITY_DESC_BOB, ParserUtil.MESSAGE_INVALID_INDEX);
}
@Test
public void parse_multipleIndicesMultipleAvailability_success() throws ParseException {
List<Index> expectedIndices = new ArrayList<>();
String indicesString = "1 2 3";
String[] indicesArray = indicesString.split("\\s+");
for (String s : indicesArray) {
expectedIndices.add(ParserUtil.parseIndex(s));
}
List<DayOfWeek> expectedAvailability = Arrays.asList(DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY);
assertParseSuccess(parser, "1 2 3" + AVAILABILITY_DESC_BOB,
new SetMemberAvailabilityCommand(expectedIndices, new Availability(expectedAvailability)));
}
@Test
public void parse_multipleIndicesWithMultipleWhitespace_success() throws ParseException {
List<Index> expectedIndices = new ArrayList<>();
String indicesString = "1 2 3";
String[] indicesArray = indicesString.split("\\s+");
for (String s : indicesArray) {
expectedIndices.add(ParserUtil.parseIndex(s));
}
List<DayOfWeek> expectedAvailability = Arrays.asList(DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY);
assertParseSuccess(parser, " 1 2 3" + AVAILABILITY_DESC_BOB,
new SetMemberAvailabilityCommand(expectedIndices, new Availability(expectedAvailability)));
}
@Test
public void parse_compulsoryFieldMissing_failure() {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT,
SetMemberAvailabilityCommand.MESSAGE_USAGE);
// missing index/indices
assertParseFailure(parser, AVAILABILITY_DESC_BOB, ParserUtil.MESSAGE_INVALID_INDEX);
// missing availability prefix
assertParseFailure(parser, "1 2 3" + NAME_DESC_BOB, expectedMessage);
}
@Test
public void parse_invalidValue_failure() {
// invalid index/indices
assertParseFailure(parser, "one two three" + AVAILABILITY_DESC_BOB, ParserUtil.MESSAGE_INVALID_INDEX);
// invalid availability
assertParseFailure(parser, "1 2 3" + INVALID_AVAILABILITY_DESC, Availability.MESSAGE_CONSTRAINTS);
}
@Test
public void parse_emptyAvailability_success() throws ParseException {
List<Index> expectedIndices = new ArrayList<>();
String indicesString = "1 2 3";
String[] indicesArray = indicesString.split("\\s+");
for (String s : indicesArray) {
expectedIndices.add(ParserUtil.parseIndex(s));
}
assertParseSuccess(parser, "1 2 3" + " d/",
new SetMemberAvailabilityCommand(expectedIndices, new Availability(new ArrayList<>())));
}
}
|
3e126a056c8bea6daa079837040a32d08b5a645c | 2,812 | java | Java | app/src/main/java/com/jlu/chengjie/zhihu/fragment/WatchFragment.java | Easoncheng0405/ZhiHu | e7e1dc0702a3806b46c8d0c69238ecd30b43a18c | [
"Apache-2.0"
] | 3 | 2021-04-08T11:20:42.000Z | 2022-03-10T13:23:50.000Z | app/src/main/java/com/jlu/chengjie/zhihu/fragment/WatchFragment.java | Easoncheng0405/ZhiHu | e7e1dc0702a3806b46c8d0c69238ecd30b43a18c | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/jlu/chengjie/zhihu/fragment/WatchFragment.java | Easoncheng0405/ZhiHu | e7e1dc0702a3806b46c8d0c69238ecd30b43a18c | [
"Apache-2.0"
] | 4 | 2019-05-09T15:24:55.000Z | 2022-03-19T06:49:00.000Z | 33.105882 | 132 | 0.697584 | 7,771 | /*
* Copyright [2018] [chengjie.jlu@qq.com]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jlu.chengjie.zhihu.fragment;
/*
*@Author chengjie
*@Date 2018-12-15
*@Email kenaa@example.com
*/
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.jlu.chengjie.zhihu.R;
import com.jlu.chengjie.zhihu.adapter.FocusAdapter;
import com.jlu.chengjie.zhihu.model.FocusPeople;
import java.util.ArrayList;
import java.util.List;
public class WatchFragment extends Fragment {
@BindView(R.id.focus_people)
RecyclerView recyclerView;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.watch_fragment, container, false);
ButterKnife.bind(this, view);
FocusPeople people = new FocusPeople();
people.setPeople("知乎刘看山 关注了问题 · 3小时 前");
people.setTitle("你在诉讼\\仲裁案件中,被对方律师下过什么套?");
people.setContent("问题描述:本题已收录至知乎圆桌网络仲裁值多少,更多[仲裁]相关话题欢迎关注讨论。");
people.setInfo("11 回答 · 1083 关注");
List<FocusPeople> list = new ArrayList<FocusPeople>() {
{
add(people);
add(people);
add(people);
add(people);
add(people);
add(people);
}
};
Context context = getContext();
if (context != null) {
FocusAdapter adapter = new FocusAdapter(context, list);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
recyclerView.setAdapter(adapter);
recyclerView.setFocusableInTouchMode(false);
}
return view;
}
}
|
3e126aa30374f41eb75529581d682562d8093cd3 | 7,445 | java | Java | src/main/java/lee/study/down/hanndle/HttpDownInitializer.java | yfyyyfff/proxyee-down | fe71df46cbd9cf7f6fb751a099c4ce05aaf6fd51 | [
"Apache-2.0"
] | 1 | 2018-01-15T11:16:00.000Z | 2018-01-15T11:16:00.000Z | src/main/java/lee/study/down/hanndle/HttpDownInitializer.java | dingdang1990/proxyee-down | fe71df46cbd9cf7f6fb751a099c4ce05aaf6fd51 | [
"Apache-2.0"
] | null | null | null | src/main/java/lee/study/down/hanndle/HttpDownInitializer.java | dingdang1990/proxyee-down | fe71df46cbd9cf7f6fb751a099c4ce05aaf6fd51 | [
"Apache-2.0"
] | null | null | null | 41.592179 | 98 | 0.620416 | 7,772 | package lee.study.down.hanndle;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.util.ReferenceCountUtil;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import lee.study.down.HttpDownServer;
import lee.study.down.dispatch.HttpDownCallback;
import lee.study.down.ext.LargeMappedByteBuffer;
import lee.study.down.model.ChunkInfo;
import lee.study.down.model.TaskInfo;
import lee.study.down.util.HttpDownUtil;
public class HttpDownInitializer extends ChannelInitializer {
private boolean isSsl;
private TaskInfo taskInfo;
private ChunkInfo chunkInfo;
private HttpDownCallback callback;
private long realContentSize;
public HttpDownInitializer(boolean isSsl, TaskInfo taskInfo, ChunkInfo chunkInfo,
HttpDownCallback callback) throws Exception {
this.isSsl = isSsl;
this.taskInfo = taskInfo;
this.chunkInfo = chunkInfo;
this.callback = callback;
}
@Override
protected void initChannel(Channel ch) throws Exception {
this.chunkInfo.setChannel(ch);
if (isSsl) {
ch.pipeline().addLast(HttpDownServer.CLIENT_SSL_CONTEXT.newHandler(ch.alloc()));
}
ch.pipeline().addLast("httpCodec", new HttpClientCodec());
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
if (msg instanceof HttpContent) {
if (chunkInfo.getFileChannel() == null || !chunkInfo.getFileChannel().isOpen()) {
return;
}
HttpContent httpContent = (HttpContent) msg;
ByteBuf byteBuf = httpContent.content();
int readableBytes = byteBuf.readableBytes();
synchronized (chunkInfo) {
Boolean close = ctx.channel().attr(HttpDownUtil.CLOSE_ATTR).get();
if (close != null && close == true) {
return;
}
if (chunkInfo.getStatus() == 1) {
chunkInfo.getMappedBuffer().put(byteBuf.nioBuffer());
//文件已下载大小
chunkInfo.setDownSize(chunkInfo.getDownSize() + readableBytes);
} else {
return;
}
}
synchronized (taskInfo) {
taskInfo.setDownSize(taskInfo.getDownSize() + readableBytes);
}
callback.onProgress(taskInfo, chunkInfo);
//分段下载完成关闭fileChannel
if (chunkInfo.getDownSize() == chunkInfo.getTotalSize()) {
HttpDownUtil.safeClose(ctx.channel(), chunkInfo);
//分段下载完成回调
chunkInfo.setStatus(2);
chunkInfo.setLastTime(System.currentTimeMillis());
callback.onChunkDone(taskInfo, chunkInfo);
synchronized (taskInfo) {
if (taskInfo.getStatus() == 1 && taskInfo.getChunkInfoList().stream()
.allMatch((chunk) -> chunk.getStatus() == 2)) {
//记录完成时间
taskInfo.setLastTime(System.currentTimeMillis());
if (taskInfo.getTotalSize() <= 0) { //chunked编码最后更新文件大小
taskInfo.setTotalSize(taskInfo.getDownSize());
taskInfo.getChunkInfoList().get(0).setTotalSize(taskInfo.getDownSize());
}
//文件下载完成回调
taskInfo.setStatus(2);
callback.onDone(taskInfo);
}
}
} else if (realContentSize
== chunkInfo.getDownSize() + chunkInfo.getOriStartPosition() - chunkInfo
.getNowStartPosition() || (realContentSize - 1)
== chunkInfo.getDownSize() + chunkInfo.getOriStartPosition() - chunkInfo
.getNowStartPosition()) { //百度响应做了手脚,会少一个字节
//真实响应字节小于要下载的字节,在下载完成后要继续下载
HttpDownServer.LOGGER.debug(
"继续下载:" + chunkInfo.getIndex() + "\t" + chunkInfo.getDownSize());
HttpDownUtil.continueDown(taskInfo, chunkInfo);
} else if (chunkInfo.getDownSize() > chunkInfo.getTotalSize()) {
//错误下载从0开始重新下过
HttpDownServer.LOGGER.error("Out of chunk size:" + chunkInfo + "\t" + taskInfo);
synchronized (taskInfo) {
synchronized (chunkInfo) {
taskInfo.setTotalSize(taskInfo.getTotalSize() - chunkInfo.getDownSize());
}
}
HttpDownUtil.retryDown(taskInfo, chunkInfo, 0);
}
} else {
HttpResponse httpResponse = (HttpResponse) msg;
realContentSize = HttpDownUtil.getDownFileSize(httpResponse.headers());
HttpDownServer.LOGGER.debug(
"下载响应:" + chunkInfo.getIndex() + "\t" + chunkInfo.getDownSize() + "\t"
+ httpResponse.headers().get(
HttpHeaderNames.CONTENT_RANGE) + "\t" + realContentSize);
synchronized (chunkInfo) {
Boolean close = ctx.channel().attr(HttpDownUtil.CLOSE_ATTR).get();
if (close == null || close == false) {
FileChannel fileChannel = new RandomAccessFile(taskInfo.buildTaskFilePath(), "rw")
.getChannel();
LargeMappedByteBuffer mappedBuffer = new LargeMappedByteBuffer(fileChannel,
MapMode.READ_WRITE, chunkInfo.getOriStartPosition() + chunkInfo.getDownSize(),
chunkInfo.getTotalSize() - chunkInfo.getDownSize());
chunkInfo.setStatus(1);
chunkInfo.setFileChannel(fileChannel);
chunkInfo.setMappedBuffer(mappedBuffer);
callback.onChunkStart(taskInfo, chunkInfo);
}
}
}
} catch (Exception e) {
throw e;
} finally {
ReferenceCountUtil.release(msg);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
callback.onError(taskInfo, chunkInfo, cause);
if (cause instanceof IOException) {
HttpDownServer.LOGGER.error("down onError:", cause);
}
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
super.channelUnregistered(ctx);
ctx.channel().close();
}
});
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
}
public static void main(String[] args) throws Exception {
String path = "f:/down/test1.txt";
RandomAccessFile randomAccessFile = new RandomAccessFile(path, "rw");
randomAccessFile.setLength(100);
randomAccessFile.close();
FileChannel fileChannel = new RandomAccessFile(path, "rw").getChannel();
MappedByteBuffer mbb = fileChannel.map(MapMode.READ_WRITE, 0, 5);
mbb.put(new byte[]{1, 2, 3, 4, 5});
}
}
|
3e126b10ab4cfec99601d3bc4ac115c216323837 | 415 | java | Java | koks/manager/event/impl/EventSafeWalk.java | Schummel-Software/Koks-v3 | b31bdcf41249c4f94029bf782a1059f23c163a51 | [
"Apache-2.0"
] | 8 | 2022-01-09T17:18:15.000Z | 2022-02-02T04:34:56.000Z | koks/manager/event/impl/EventSafeWalk.java | Schummel-Software/Koks-v3 | b31bdcf41249c4f94029bf782a1059f23c163a51 | [
"Apache-2.0"
] | 2 | 2022-01-13T14:18:52.000Z | 2022-01-15T01:04:08.000Z | koks/manager/event/impl/EventSafeWalk.java | Schummel-Software/Koks-v3 | b31bdcf41249c4f94029bf782a1059f23c163a51 | [
"Apache-2.0"
] | 2 | 2022-01-19T03:12:11.000Z | 2022-02-02T04:27:06.000Z | 17.291667 | 42 | 0.621687 | 7,773 | package koks.manager.event.impl;
import koks.manager.event.Event;
/**
* @author deleteboys | lmao | kroko
* @created on 13.09.2020 : 05:36
*/
public class EventSafeWalk extends Event {
boolean safe;
public boolean isSafe() {
return safe;
}
public void setSafe(boolean safe) {
this.safe = safe;
}
public EventSafeWalk(boolean safe) {
this.safe = safe;
}
}
|
3e126ca957582a5cbcb8442165ff05afca671f63 | 1,617 | java | Java | particlelib/src/main/java/com/eliotlash/particlelib/particles/components/meta/BedrockComponentLocalSpace.java | SimplyCmd/Terrariamod | d0629a589a38cf8eed380a2a2da73152ce815ae9 | [
"CC0-1.0"
] | 6 | 2020-05-13T00:03:50.000Z | 2021-12-04T16:09:50.000Z | particlelib/src/main/java/com/eliotlash/particlelib/particles/components/meta/BedrockComponentLocalSpace.java | SimplyCmd/Terrariamod | d0629a589a38cf8eed380a2a2da73152ce815ae9 | [
"CC0-1.0"
] | 6 | 2020-08-14T14:02:44.000Z | 2021-08-15T05:11:12.000Z | particlelib/src/main/java/com/eliotlash/particlelib/particles/components/meta/BedrockComponentLocalSpace.java | SimplyCmd/Terrariamod | d0629a589a38cf8eed380a2a2da73152ce815ae9 | [
"CC0-1.0"
] | 3 | 2020-10-19T20:03:53.000Z | 2021-09-09T02:38:38.000Z | 29.4 | 108 | 0.7953 | 7,774 | package com.eliotlash.particlelib.particles.components.meta;
import com.eliotlash.particlelib.particles.components.BedrockComponentBase;
import com.eliotlash.particlelib.particles.components.IComponentParticleInitialize;
import com.eliotlash.particlelib.particles.emitter.BedrockEmitter;
import com.eliotlash.particlelib.particles.emitter.BedrockParticle;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.eliotlash.molang.MolangException;
import com.eliotlash.molang.MolangParser;
public class BedrockComponentLocalSpace extends BedrockComponentBase implements IComponentParticleInitialize
{
public boolean position;
public boolean rotation;
public BedrockComponentBase fromJson(JsonElement elem, MolangParser parser) throws MolangException
{
if (!elem.isJsonObject()) return super.fromJson(elem, parser);
JsonObject element = elem.getAsJsonObject();
if (element.has("position")) this.position = element.get("position").getAsBoolean();
if (element.has("rotation")) this.rotation = element.get("rotation").getAsBoolean();
return super.fromJson(element, parser);
}
@Override
public JsonElement toJson()
{
JsonObject object = new JsonObject();
if (this.position) object.addProperty("position", true);
if (this.rotation) object.addProperty("rotation", true);
return object;
}
@Override
public void apply(BedrockEmitter emitter, BedrockParticle particle)
{
particle.relativePosition = this.position;
particle.relativeRotation = this.rotation;
particle.setupMatrix(emitter);
}
@Override
public int getSortingIndex()
{
return 1000;
}
}
|
3e126da8f1572602424446a0806420eb681b1e41 | 8,704 | java | Java | services/kg-core-api/src/main/java/eu/ebrains/kg/core/api/Queries.java | HumanBrainProject/kg-core | 496fc78792bdb10e1783163b0e09a1f0aafceecb | [
"Apache-2.0"
] | 2 | 2020-12-20T16:11:50.000Z | 2021-11-23T11:20:56.000Z | services/kg-core-api/src/main/java/eu/ebrains/kg/core/api/Queries.java | HumanBrainProject/kg-core | 496fc78792bdb10e1783163b0e09a1f0aafceecb | [
"Apache-2.0"
] | 7 | 2020-03-31T20:04:38.000Z | 2021-06-04T07:53:33.000Z | services/kg-core-api/src/main/java/eu/ebrains/kg/core/api/Queries.java | HumanBrainProject/kg-core | 496fc78792bdb10e1783163b0e09a1f0aafceecb | [
"Apache-2.0"
] | null | null | null | 49.737143 | 391 | 0.732652 | 7,775 | /*
* Copyright 2018 - 2021 Swiss Federal Institute of Technology Lausanne (EPFL)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This open source software code was developed in part or in whole in the
* Human Brain Project, funded from the European Union's Horizon 2020
* Framework Programme for Research and Innovation under
* Specific Grant Agreements No. 720270, No. 785907, and No. 945539
* (Human Brain Project SGA1, SGA2 and SGA3).
*/
package eu.ebrains.kg.core.api;
import eu.ebrains.kg.commons.AuthContext;
import eu.ebrains.kg.commons.Version;
import eu.ebrains.kg.commons.api.JsonLd;
import eu.ebrains.kg.commons.config.openApiGroups.Simple;
import eu.ebrains.kg.commons.jsonld.InstanceId;
import eu.ebrains.kg.commons.jsonld.JsonLdDoc;
import eu.ebrains.kg.commons.jsonld.NormalizedJsonLd;
import eu.ebrains.kg.commons.markers.ExposesData;
import eu.ebrains.kg.commons.markers.ExposesInputWithoutEnrichedSensitiveData;
import eu.ebrains.kg.commons.markers.ExposesQuery;
import eu.ebrains.kg.commons.markers.WritesData;
import eu.ebrains.kg.commons.model.*;
import eu.ebrains.kg.commons.query.KgQuery;
import eu.ebrains.kg.commons.semantics.vocabularies.EBRAINSVocabulary;
import eu.ebrains.kg.core.controller.CoreQueryController;
import eu.ebrains.kg.core.controller.IdsController;
import eu.ebrains.kg.core.model.ExposedStage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
/**
* The query API allows to execute and manage queries on top of the EBRAINS KG. This is the main interface for reading clients.
*/
@RestController
@RequestMapping(Version.API+"/queries")
@Simple
public class Queries {
private final CoreQueryController queryController;
private final AuthContext authContext;
private final JsonLd.Client jsonLd;
private final IdsController ids;
public Queries(CoreQueryController queryController, AuthContext authContext, JsonLd.Client jsonLd, IdsController ids) {
this.queryController = queryController;
this.authContext = authContext;
this.jsonLd = jsonLd;
this.ids = ids;
}
@Operation(summary = "List the queries and filter them by root type and/or text in the label, name or description")
@GetMapping
@ExposesQuery
public PaginatedResult<NormalizedJsonLd> listQueriesPerRootType(@ParameterObject PaginationParam paginationParam, @RequestParam(value = "type", required = false) String rootType, @RequestParam(value = "search", required = false) String search) {
if(rootType != null){
return PaginatedResult.ok(queryController.listQueriesPerRootType(search, new Type(rootType), paginationParam));
} else {
return PaginatedResult.ok(queryController.listQueries(search, paginationParam));
}
}
@Operation(summary = "Execute the query in the payload in test mode (e.g. for execution before saving with the KG QueryBuilder)")
@PostMapping
@ExposesData
public PaginatedResult<? extends JsonLdDoc> testQuery(@RequestBody JsonLdDoc query, @ParameterObject PaginationParam paginationParam, @RequestParam("stage") ExposedStage stage, @RequestParam(value = "instanceId", required = false) UUID instanceId, @RequestParam(defaultValue = "{}") Map<String, String> allRequestParams) {
//Remove the non-dynamic parameters from the map
allRequestParams.remove("stage");
allRequestParams.remove("instanceId");
allRequestParams.remove("from");
allRequestParams.remove("size");
NormalizedJsonLd normalizedJsonLd = jsonLd.normalize(query, true);
KgQuery q = new KgQuery(normalizedJsonLd, stage.getStage());
if(instanceId!=null){
q.setIdRestrictions(Collections.singletonList(instanceId));
}
return PaginatedResult.ok(queryController.executeQuery(q, allRequestParams, paginationParam));
}
@Operation(summary = "Get the query specification with the given query id in a specific space")
@GetMapping("/{queryId}")
@ExposesQuery
public ResponseEntity<Result<NormalizedJsonLd>> getQuerySpecification(@PathVariable("queryId") UUID queryId) {
InstanceId instanceId = ids.resolveId(DataStage.IN_PROGRESS, queryId);
NormalizedJsonLd kgQuery = queryController.fetchQueryById(instanceId);
return kgQuery != null ? ResponseEntity.ok(Result.ok(kgQuery)): ResponseEntity.notFound().build();
}
@Operation(summary = "Remove a query specification")
@DeleteMapping("/{queryId}")
@WritesData
public ResponseEntity<Void> removeQuery(@PathVariable("queryId") UUID queryId) {
InstanceId resolveId = ids.resolveId(DataStage.IN_PROGRESS, queryId);
if(resolveId!=null) {
Set<InstanceId> instanceIds = queryController.deleteQuery(resolveId);
if(instanceIds.isEmpty()){
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok().build();
}
else {
return ResponseEntity.notFound().build();
}
}
@Operation(summary = "Create or save a query specification")
@PutMapping("/{queryId}")
@WritesData
@ExposesInputWithoutEnrichedSensitiveData
public ResponseEntity<Result<NormalizedJsonLd>> saveQuery(@RequestBody JsonLdDoc query, @PathVariable(value = "queryId") UUID queryId, @RequestParam(value = "space", required = false) @Parameter(description = "Required only when the instance is created to specify where it should be stored ("+SpaceName.PRIVATE_SPACE+" for your private space) - but not if it's updated.") String space) {
NormalizedJsonLd normalizedJsonLd = jsonLd.normalize(query, true);
normalizedJsonLd.addTypes(EBRAINSVocabulary.META_QUERY_TYPE);
InstanceId resolveId = ids.resolveId(DataStage.IN_PROGRESS, queryId);
SpaceName spaceName = authContext.resolveSpaceName(space);
if(resolveId != null){
if(spaceName!=null && !resolveId.getSpace().equals(spaceName)){
return ResponseEntity.status(HttpStatus.CONFLICT).body(Result.nok(HttpStatus.CONFLICT.value(), "The query with this UUID already exists in a different space"));
}
return queryController.updateQuery(normalizedJsonLd, resolveId);
}
if(spaceName==null){
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Result.nok(HttpStatus.BAD_REQUEST.value(), "The query with this UUID doesn't exist yet. You therefore need to specify the space where it should be stored."));
}
return queryController.createNewQuery(normalizedJsonLd, queryId, spaceName);
}
@Operation(summary = "Execute a stored query to receive the instances")
@GetMapping("/{queryId}/instances")
@ExposesData
public PaginatedResult<? extends JsonLdDoc> executeQueryById(@PathVariable("queryId") UUID queryId, @ParameterObject PaginationParam paginationParam, @RequestParam("stage") ExposedStage stage, @RequestParam(value = "instanceId", required = false) UUID instanceId, @RequestParam(defaultValue = "{}") Map<String, String> allRequestParams) {
//Remove the non-dynamic parameters from the map
allRequestParams.remove("stage");
allRequestParams.remove("instanceId");
allRequestParams.remove("from");
allRequestParams.remove("size");
InstanceId queryInstance = ids.resolveId(DataStage.IN_PROGRESS, queryId);
final NormalizedJsonLd queryPayload = queryController.fetchQueryById(queryInstance);
if(queryPayload==null){
return null;
}
KgQuery query = new KgQuery(queryPayload, stage.getStage());
if(instanceId!=null){
query.setIdRestrictions(Collections.singletonList(instanceId));
}
return PaginatedResult.ok(queryController.executeQuery(query, allRequestParams, paginationParam));
}
}
|
3e127049d5a91022e3d1afd25cd69a8aed5c7536 | 1,623 | java | Java | testes/domain/servicos/CalculoDeValorDoPeriodoServiceTest.java | PBorio/hotel | 208b0c77c381b6bddaace922d2bf50e298b0df07 | [
"Apache-2.0"
] | null | null | null | testes/domain/servicos/CalculoDeValorDoPeriodoServiceTest.java | PBorio/hotel | 208b0c77c381b6bddaace922d2bf50e298b0df07 | [
"Apache-2.0"
] | null | null | null | testes/domain/servicos/CalculoDeValorDoPeriodoServiceTest.java | PBorio/hotel | 208b0c77c381b6bddaace922d2bf50e298b0df07 | [
"Apache-2.0"
] | null | null | null | 40.575 | 99 | 0.821319 | 7,776 | package domain.servicos;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.Assert;
import org.junit.Test;
import domain.exceptions.ValorDiariaNaoInformadoException;
import domain.interfaces.CalculavelPorPeriodo;
import domain.servicos.helpers.ParserDeStringParaData;
public class CalculoDeValorDoPeriodoServiceTest {
@Test
public void umCalculavelPorDiariaTemSeuValorComBaseNaMultplicacaoDosDiasPeloValorUnitario(){
CalculavelPorPeriodo calculavel = mock(CalculavelPorPeriodo.class);
when(calculavel.getInicio()).thenReturn(new ParserDeStringParaData().parseData("09/03/2014"));
when(calculavel.getFim()).thenReturn(new ParserDeStringParaData().parseData("11/03/2014"));
when(calculavel.getValorDiaria()).thenReturn(10.0);
CalculoDeValorPorPeriodoService calculoPorPeriodoService = new CalculoDeValorPorPeriodoService();
Assert.assertEquals((Double)20.0, calculoPorPeriodoService.calcularValor(calculavel));
}
@Test(expected=ValorDiariaNaoInformadoException.class)
public void seOValorDaDiariaNaoFoiInformadoDeveGerarExcecao(){
CalculavelPorPeriodo calculavel = mock(CalculavelPorPeriodo.class);
when(calculavel.getInicio()).thenReturn(new ParserDeStringParaData().parseData("09/03/2014"));
when(calculavel.getFim()).thenReturn(new ParserDeStringParaData().parseData("11/03/2014"));
when(calculavel.getValorDiaria()).thenReturn(null);
CalculoDeValorPorPeriodoService calculoPorPeriodoService = new CalculoDeValorPorPeriodoService();
Assert.assertEquals((Double)20.0, calculoPorPeriodoService.calcularValor(calculavel));
}
}
|
3e12710b94cc5a44295996b4b4a8867721d9561e | 796 | java | Java | sdk/iothub/azure-resourcemanager-iothub/src/samples/java/com/azure/resourcemanager/iothub/generated/IotHubResourceDeleteSamples.java | liukun2634/azure-sdk-for-java | a42ba097eef284333c9befba180eea3cfed41312 | [
"MIT"
] | 1 | 2022-01-08T06:43:30.000Z | 2022-01-08T06:43:30.000Z | sdk/iothub/azure-resourcemanager-iothub/src/samples/java/com/azure/resourcemanager/iothub/generated/IotHubResourceDeleteSamples.java | liukun2634/azure-sdk-for-java | a42ba097eef284333c9befba180eea3cfed41312 | [
"MIT"
] | null | null | null | sdk/iothub/azure-resourcemanager-iothub/src/samples/java/com/azure/resourcemanager/iothub/generated/IotHubResourceDeleteSamples.java | liukun2634/azure-sdk-for-java | a42ba097eef284333c9befba180eea3cfed41312 | [
"MIT"
] | null | null | null | 34.608696 | 128 | 0.733668 | 7,777 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.iothub.generated;
import com.azure.core.util.Context;
/** Samples for IotHubResource Delete. */
public final class IotHubResourceDeleteSamples {
/*
* x-ms-original-file: specification/iothub/resource-manager/Microsoft.Devices/stable/2021-07-02/examples/iothub_delete.json
*/
/**
* Sample code: IotHubResource_Delete.
*
* @param manager Entry point to IotHubManager.
*/
public static void iotHubResourceDelete(com.azure.resourcemanager.iothub.IotHubManager manager) {
manager.iotHubResources().delete("myResourceGroup", "testHub", Context.NONE);
}
}
|
3e12713f5b2f9cc365c768a3fb04c9e143382b12 | 8,184 | java | Java | api/src/test/java/edu/cornell/mannlib/vitro/webapp/auth/policy/PolicyHelper_StatementsTest.java | dsi-ehess/Vitro | 9e21ec0a14d867c9586049064efdc698116bcfc2 | [
"BSD-3-Clause"
] | 74 | 2015-01-19T20:02:51.000Z | 2022-02-20T20:28:54.000Z | api/src/test/java/edu/cornell/mannlib/vitro/webapp/auth/policy/PolicyHelper_StatementsTest.java | dsi-ehess/Vitro | 9e21ec0a14d867c9586049064efdc698116bcfc2 | [
"BSD-3-Clause"
] | 122 | 2015-01-21T17:08:34.000Z | 2022-03-27T19:59:01.000Z | api/src/test/java/edu/cornell/mannlib/vitro/webapp/auth/policy/PolicyHelper_StatementsTest.java | dsi-ehess/Vitro | 9e21ec0a14d867c9586049064efdc698116bcfc2 | [
"BSD-3-Clause"
] | 95 | 2015-01-08T13:08:28.000Z | 2022-02-22T13:15:21.000Z | 33.679012 | 108 | 0.737659 | 7,778 | /* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.auth.policy;
import static org.junit.Assert.assertEquals;
import org.apache.log4j.Level;
import org.junit.Before;
import org.junit.Test;
import stubs.javax.servlet.ServletContextStub;
import stubs.javax.servlet.http.HttpServletRequestStub;
import stubs.javax.servlet.http.HttpSessionStub;
import org.apache.jena.ontology.OntModel;
import org.apache.jena.ontology.OntModelSpec;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.Statement;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.Authorization;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyDecision;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyIface;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.RequestedAction;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.AbstractDataPropertyStatementAction;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.AbstractObjectPropertyStatementAction;
/**
* Test the function of PolicyHelper in authorizing statements and models.
*/
public class PolicyHelper_StatementsTest extends AbstractTestClass {
private static final String APPROVED_SUBJECT_URI = "test://approvedSubjectUri";
private static final String APPROVED_PREDICATE_URI = "test://approvedPredicateUri";
private static final String UNAPPROVED_PREDICATE_URI = "test://bogusPredicateUri";
private static final String APPROVED_OBJECT_URI = "test://approvedObjectUri";
private ServletContextStub ctx;
private HttpSessionStub session;
private HttpServletRequestStub req;
private OntModel ontModel;
@Before
public void setup() {
ctx = new ServletContextStub();
session = new HttpSessionStub();
session.setServletContext(ctx);
req = new HttpServletRequestStub();
req.setSession(session);
ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
setLoggerLevel(ServletPolicyList.class, Level.WARN);
ServletPolicyList.addPolicy(ctx, new MySimplePolicy());
}
// ----------------------------------------------------------------------
// The tests.
// ----------------------------------------------------------------------
@Test
public void addNullStatement() {
assertEquals("null statement", false,
PolicyHelper.isAuthorizedToAdd(req, null, ontModel));
}
@Test
public void addStatementWithNullRequest() {
Statement stmt = dataStatement(APPROVED_SUBJECT_URI,
APPROVED_PREDICATE_URI);
assertEquals("null request", false,
PolicyHelper.isAuthorizedToAdd(null, stmt, ontModel));
}
@Test
public void addStatementToNullModel() {
Statement stmt = dataStatement(APPROVED_SUBJECT_URI,
APPROVED_PREDICATE_URI);
assertEquals("authorized", false,
PolicyHelper.isAuthorizedToAdd(req, stmt, null));
}
@Test
public void addAuthorizedDataStatement() {
Statement stmt = dataStatement(APPROVED_SUBJECT_URI,
APPROVED_PREDICATE_URI);
assertEquals("authorized", true,
PolicyHelper.isAuthorizedToAdd(req, stmt, ontModel));
}
@Test
public void addAuthorizedObjectStatement() {
Statement stmt = objectStatement(APPROVED_SUBJECT_URI,
APPROVED_PREDICATE_URI, APPROVED_OBJECT_URI);
assertEquals("authorized", true,
PolicyHelper.isAuthorizedToAdd(req, stmt, ontModel));
}
@Test
public void addUnauthorizedDataStatement() {
Statement stmt = dataStatement(APPROVED_SUBJECT_URI,
UNAPPROVED_PREDICATE_URI);
assertEquals("not authorized", false,
PolicyHelper.isAuthorizedToAdd(req, stmt, ontModel));
}
@Test
public void addUnauthorizedObjectStatement() {
Statement stmt = objectStatement(APPROVED_SUBJECT_URI,
UNAPPROVED_PREDICATE_URI, APPROVED_OBJECT_URI);
assertEquals("not authorized", false,
PolicyHelper.isAuthorizedToAdd(req, stmt, ontModel));
}
@Test
public void dropNullStatement() {
assertEquals("null statement", false, PolicyHelper.isAuthorizedToDrop(
req, (Statement) null, ontModel));
}
@Test
public void dropStatementWithNullRequest() {
Statement stmt = dataStatement(APPROVED_SUBJECT_URI,
APPROVED_PREDICATE_URI);
assertEquals("null request", false,
PolicyHelper.isAuthorizedToDrop(null, stmt, ontModel));
}
@Test
public void dropStatementFromNullModel() {
Statement stmt = dataStatement(APPROVED_SUBJECT_URI,
APPROVED_PREDICATE_URI);
assertEquals("authorized", false,
PolicyHelper.isAuthorizedToDrop(req, stmt, null));
}
@Test
public void dropAuthorizedDataStatement() {
Statement stmt = dataStatement(APPROVED_SUBJECT_URI,
APPROVED_PREDICATE_URI);
assertEquals("authorized", true,
PolicyHelper.isAuthorizedToDrop(req, stmt, ontModel));
}
@Test
public void dropAuthorizedObjectStatement() {
Statement stmt = objectStatement(APPROVED_SUBJECT_URI,
APPROVED_PREDICATE_URI, APPROVED_OBJECT_URI);
assertEquals("authorized", true,
PolicyHelper.isAuthorizedToDrop(req, stmt, ontModel));
}
@Test
public void dropUnauthorizedDataStatement() {
Statement stmt = dataStatement(APPROVED_SUBJECT_URI,
UNAPPROVED_PREDICATE_URI);
assertEquals("not authorized", false,
PolicyHelper.isAuthorizedToDrop(req, stmt, ontModel));
}
@Test
public void dropUnauthorizedObjectStatement() {
Statement stmt = objectStatement(APPROVED_SUBJECT_URI,
UNAPPROVED_PREDICATE_URI, APPROVED_OBJECT_URI);
assertEquals("not authorized", false,
PolicyHelper.isAuthorizedToDrop(req, stmt, ontModel));
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
/** Build a data statement. */
private Statement dataStatement(String subjectUri, String predicateUri) {
Resource subject = ontModel.createResource(subjectUri);
Property predicate = ontModel.createProperty(predicateUri);
return ontModel.createStatement(subject, predicate, "whoCares?");
}
/** Build a object statement. */
private Statement objectStatement(String subjectUri, String predicateUri,
String objectUri) {
Resource subject = ontModel.createResource(subjectUri);
Resource object = ontModel.createResource(objectUri);
Property predicate = ontModel.createProperty(predicateUri);
return ontModel.createStatement(subject, predicate, object);
}
// ----------------------------------------------------------------------
// Helper classes
// ----------------------------------------------------------------------
private static class MySimplePolicy implements PolicyIface {
@Override
public PolicyDecision isAuthorized(IdentifierBundle whoToAuth,
RequestedAction whatToAuth) {
if (whatToAuth instanceof AbstractDataPropertyStatementAction) {
return isAuthorized((AbstractDataPropertyStatementAction) whatToAuth);
} else if (whatToAuth instanceof AbstractObjectPropertyStatementAction) {
return isAuthorized((AbstractObjectPropertyStatementAction) whatToAuth);
} else {
return inconclusive();
}
}
private PolicyDecision isAuthorized(
AbstractDataPropertyStatementAction whatToAuth) {
if ((APPROVED_SUBJECT_URI.equals(whatToAuth.getSubjectUri()))
&& (APPROVED_PREDICATE_URI.equals(whatToAuth
.getPredicateUri()))) {
return authorized();
} else {
return inconclusive();
}
}
private PolicyDecision isAuthorized(
AbstractObjectPropertyStatementAction whatToAuth) {
if ((APPROVED_SUBJECT_URI.equals(whatToAuth.getSubjectUri()))
&& (APPROVED_PREDICATE_URI.equals(whatToAuth
.getPredicateUri()))
&& (APPROVED_OBJECT_URI.equals(whatToAuth.getObjectUri()))) {
return authorized();
} else {
return inconclusive();
}
}
private PolicyDecision authorized() {
return new BasicPolicyDecision(Authorization.AUTHORIZED, "");
}
private PolicyDecision inconclusive() {
return new BasicPolicyDecision(Authorization.INCONCLUSIVE, "");
}
}
}
|
3e1271af0b941cd68c3f842ea7149675daf2811a | 2,249 | java | Java | net.solarnetwork.common/src/net/solarnetwork/util/StaticOptionalService.java | Tsvetelin98/Solar | 350341d4f6a32d53efd48778ee7a8ba89a591978 | [
"Apache-2.0"
] | null | null | null | net.solarnetwork.common/src/net/solarnetwork/util/StaticOptionalService.java | Tsvetelin98/Solar | 350341d4f6a32d53efd48778ee7a8ba89a591978 | [
"Apache-2.0"
] | null | null | null | net.solarnetwork.common/src/net/solarnetwork/util/StaticOptionalService.java | Tsvetelin98/Solar | 350341d4f6a32d53efd48778ee7a8ba89a591978 | [
"Apache-2.0"
] | null | null | null | 27.765432 | 88 | 0.672299 | 7,779 | /* ==================================================================
* StaticOptionalService.java - Mar 28, 2013 12:45:36 PM
*
* Copyright 2007-2013 SolarNetwork.net Dev Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
* ==================================================================
*/
package net.solarnetwork.util;
import java.util.HashMap;
import java.util.Map;
/**
* Implementation of {@link OptionalService} using a static service instance.
*
* <p>
* This can be useful when the {@link OptionalService} API is required, but the
* service is known and available statically.
* </p>
*
* @author matt
* @version 1.1
*/
public class StaticOptionalService<T> implements OptionalService<T>, FilterableService {
private final T service;
private Map<String, Object> propertyFilters;
public StaticOptionalService(T service) {
super();
this.service = service;
propertyFilters = new HashMap<String, Object>(4);
}
@Override
public T service() {
return service;
}
@Override
public Map<String, ?> getPropertyFilters() {
return propertyFilters;
}
@Override
public void setPropertyFilter(String key, Object value) {
Map<String, Object> filters = propertyFilters;
if ( filters == null ) {
filters = new HashMap<String, Object>(4);
propertyFilters = filters;
}
filters.put(key, value);
}
@Override
public Object removePropertyFilter(String key) {
Map<String, Object> filters = propertyFilters;
Object result = null;
if ( filters != null ) {
result = filters.remove(key);
}
return result;
}
}
|
3e12731ec79133f5e7ca58145380628368711eb7 | 11,669 | java | Java | components/bpmn/org.wso2.carbon.bpmn.rest/src/main/java/org/wso2/carbon/bpmn/rest/model/runtime/TaskQueryRequest.java | AnuradhaSK/carbon-business-process | c70fae8ff1242af3fa3bbfa02a5988629d7904ff | [
"Apache-2.0"
] | 10 | 2015-09-23T14:55:12.000Z | 2022-02-17T14:07:04.000Z | components/bpmn/org.wso2.carbon.bpmn.rest/src/main/java/org/wso2/carbon/bpmn/rest/model/runtime/TaskQueryRequest.java | AnuradhaSK/carbon-business-process | c70fae8ff1242af3fa3bbfa02a5988629d7904ff | [
"Apache-2.0"
] | 55 | 2015-01-13T02:30:51.000Z | 2022-03-31T12:04:21.000Z | components/bpmn/org.wso2.carbon.bpmn.rest/src/main/java/org/wso2/carbon/bpmn/rest/model/runtime/TaskQueryRequest.java | AnuradhaSK/carbon-business-process | c70fae8ff1242af3fa3bbfa02a5988629d7904ff | [
"Apache-2.0"
] | 130 | 2015-01-27T10:57:18.000Z | 2022-03-29T18:21:43.000Z | 26.641553 | 91 | 0.702117 | 7,780 | /**
* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.bpmn.rest.model.runtime;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.wso2.carbon.bpmn.rest.common.PaginateRequest;
import org.wso2.carbon.bpmn.rest.engine.variable.QueryVariable;
import javax.xml.bind.annotation.*;
import java.util.Date;
import java.util.List;
@XmlRootElement(name = "TaskQueryRequest")
@XmlAccessorType(XmlAccessType.FIELD)
public class TaskQueryRequest extends PaginateRequest {
private String name;
private String nameLike;
private String description;
private String descriptionLike;
private Integer priority;
private Integer minimumPriority;
private Integer maximumPriority;
private String assignee;
private String assigneeLike;
private String owner;
private String ownerLike;
private Boolean unassigned;
private String delegationState;
private String candidateUser;
private String candidateGroup;
@XmlElementWrapper(name = "CandidateGroupInCollection")
@XmlElement(name = "CandidateGroupIn")
private List<String> candidateGroupIn;
private String involvedUser;
private String processInstanceId;
private String processInstanceBusinessKey;
private String processInstanceBusinessKeyLike;
private String processDefinitionKey;
private String processDefinitionName;
private String processDefinitionKeyLike;
private String processDefinitionNameLike;
private String executionId;
private Date createdOn;
private Date createdBefore;
private Date createdAfter;
private Boolean excludeSubTasks;
private String taskDefinitionKey;
private String taskDefinitionKeyLike;
private Date dueDate;
private Date dueBefore;
private Date dueAfter;
private Boolean withoutDueDate;
private Boolean active;
private Boolean includeTaskLocalVariables;
private Boolean includeProcessVariables;
private String tenantId;
private String tenantIdLike;
private Boolean withoutTenantId;
private String candidateOrAssigned;
@XmlElementWrapper(name = "QueryTaskVariables")
@XmlElement(name = "QueryVariable")
private List<QueryVariable> taskVariables;
@XmlElementWrapper(name = "QueryProcessVariables")
@XmlElement(name = "QueryVariable")
private List<QueryVariable> processInstanceVariables;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNameLike() {
return nameLike;
}
public void setNameLike(String nameLike) {
this.nameLike = nameLike;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescriptionLike() {
return descriptionLike;
}
public void setDescriptionLike(String descriptionLike) {
this.descriptionLike = descriptionLike;
}
public Integer getPriority() {
return priority;
}
public void setPriority(Integer priority) {
this.priority = priority;
}
public Integer getMinimumPriority() {
return minimumPriority;
}
public void setMinimumPriority(Integer minimumPriority) {
this.minimumPriority = minimumPriority;
}
public Integer getMaximumPriority() {
return maximumPriority;
}
public void setMaximumPriority(Integer maximumPriority) {
this.maximumPriority = maximumPriority;
}
public String getAssignee() {
return assignee;
}
public void setAssignee(String assignee) {
this.assignee = assignee;
}
public String getAssigneeLike() {
return assigneeLike;
}
public void setAssigneeLike(String assigneeLike) {
this.assigneeLike = assigneeLike;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getOwnerLike() {
return ownerLike;
}
public void setOwnerLike(String ownerLike) {
this.ownerLike = ownerLike;
}
public Boolean getUnassigned() {
return unassigned;
}
public void setUnassigned(Boolean unassigned) {
this.unassigned = unassigned;
}
public String getDelegationState() {
return delegationState;
}
public void setDelegationState(String delegationState) {
this.delegationState = delegationState;
}
public String getCandidateUser() {
return candidateUser;
}
public void setCandidateUser(String candidateUser) {
this.candidateUser = candidateUser;
}
public String getCandidateGroup() {
return candidateGroup;
}
public void setCandidateGroup(String candidateGroup) {
this.candidateGroup = candidateGroup;
}
public List<String> getCandidateGroupIn() {
return candidateGroupIn;
}
public void setCandidateGroupIn(List<String> candidateGroupIn) {
this.candidateGroupIn = candidateGroupIn;
}
public String getInvolvedUser() {
return involvedUser;
}
public void setInvolvedUser(String involvedUser) {
this.involvedUser = involvedUser;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getProcessInstanceBusinessKey() {
return processInstanceBusinessKey;
}
public void setProcessInstanceBusinessKey(String processInstanceBusinessKey) {
this.processInstanceBusinessKey = processInstanceBusinessKey;
}
public String getProcessInstanceBusinessKeyLike() {
return processInstanceBusinessKeyLike;
}
public void setProcessInstanceBusinessKeyLike(String processInstanceBusinessKeyLike) {
this.processInstanceBusinessKeyLike = processInstanceBusinessKeyLike;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
public Date getCreatedBefore() {
return createdBefore;
}
public void setCreatedBefore(Date createdBefore) {
this.createdBefore = createdBefore;
}
public Date getCreatedAfter() {
return createdAfter;
}
public void setCreatedAfter(Date createdAfter) {
this.createdAfter = createdAfter;
}
public Boolean getExcludeSubTasks() {
return excludeSubTasks;
}
public void setExcludeSubTasks(Boolean excludeSubTasks) {
this.excludeSubTasks = excludeSubTasks;
}
public String getTaskDefinitionKey() {
return taskDefinitionKey;
}
public void setTaskDefinitionKey(String taskDefinitionKey) {
this.taskDefinitionKey = taskDefinitionKey;
}
public String getTaskDefinitionKeyLike() {
return taskDefinitionKeyLike;
}
public void setTaskDefinitionKeyLike(String taskDefinitionKeyLike) {
this.taskDefinitionKeyLike = taskDefinitionKeyLike;
}
public Date getDueDate() {
return dueDate;
}
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
public Date getDueBefore() {
return dueBefore;
}
public void setDueBefore(Date dueBefore) {
this.dueBefore = dueBefore;
}
public Date getDueAfter() {
return dueAfter;
}
public void setDueAfter(Date dueAfter) {
this.dueAfter = dueAfter;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public Boolean getIncludeTaskLocalVariables() {
return includeTaskLocalVariables;
}
public void setIncludeTaskLocalVariables(Boolean includeTaskLocalVariables) {
this.includeTaskLocalVariables = includeTaskLocalVariables;
}
public Boolean getIncludeProcessVariables() {
return includeProcessVariables;
}
public void setIncludeProcessVariables(Boolean includeProcessVariables) {
this.includeProcessVariables = includeProcessVariables;
}
@JsonTypeInfo(use= JsonTypeInfo.Id.CLASS, defaultImpl=QueryVariable.class)
public List<QueryVariable> getTaskVariables() {
return taskVariables;
}
public void setTaskVariables(List<QueryVariable> taskVariables) {
this.taskVariables = taskVariables;
}
@JsonTypeInfo(use= JsonTypeInfo.Id.CLASS, defaultImpl=QueryVariable.class)
public List<QueryVariable> getProcessInstanceVariables() {
return processInstanceVariables;
}
public void setProcessInstanceVariables(List<QueryVariable> processInstanceVariables) {
this.processInstanceVariables = processInstanceVariables;
}
public void setProcessDefinitionNameLike(String processDefinitionNameLike) {
this.processDefinitionNameLike = processDefinitionNameLike;
}
public String getProcessDefinitionNameLike() {
return processDefinitionNameLike;
}
public String getProcessDefinitionKeyLike() {
return processDefinitionKeyLike;
}
public void setProcessDefinitionKeyLike(String processDefinitionKeyLike) {
this.processDefinitionKeyLike = processDefinitionKeyLike;
}
public void setWithoutDueDate(Boolean withoutDueDate) {
this.withoutDueDate = withoutDueDate;
}
public Boolean getWithoutDueDate() {
return withoutDueDate;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public void setProcessDefinitionKey(String processDefinitionKey) {
this.processDefinitionKey = processDefinitionKey;
}
public String getProcessDefinitionName() {
return processDefinitionName;
}
public void setProcessDefinitionName(String processDefinitionName) {
this.processDefinitionName = processDefinitionName;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantIdLike(String tenantIdLike) {
this.tenantIdLike = tenantIdLike;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public Boolean getWithoutTenantId() {
return withoutTenantId;
}
public String getCandidateOrAssigned() {
return candidateOrAssigned;
}
public void setCandidateOrAssigned(String candidateOrAssigned) {
this.candidateOrAssigned = candidateOrAssigned;
}
}
|
3e1273a8b8696514e54dcbaea3803ee9a35d862d | 1,001 | java | Java | Java_Language_Proficiency/Data Structures/Java Comparator.java | PawelPuszczynski/Hackerrank_Challenge_Solutions | 9373216a1c0c97d9dfefa89cfd0be2e215bae7de | [
"MIT"
] | null | null | null | Java_Language_Proficiency/Data Structures/Java Comparator.java | PawelPuszczynski/Hackerrank_Challenge_Solutions | 9373216a1c0c97d9dfefa89cfd0be2e215bae7de | [
"MIT"
] | null | null | null | Java_Language_Proficiency/Data Structures/Java Comparator.java | PawelPuszczynski/Hackerrank_Challenge_Solutions | 9373216a1c0c97d9dfefa89cfd0be2e215bae7de | [
"MIT"
] | null | null | null | 22.75 | 74 | 0.513487 | 7,781 | import java.util.*;
class Checker implements Comparator <Player> {
@Override
public int compare(Player o1, Player o2) {
if ( o1.score != o2.score) {
return ( o1.score < o2.score ? 1:-1);
} else {
return o1.name.compareTo(o2.name);
}
}
}
class Player{
String name;
int score;
Player(String name, int score){
this.name = name;
this.score = score;
}
}
class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
Player[] player = new Player[n];
Checker checker = new Checker();
for(int i = 0; i < n; i++){
player[i] = new Player(scan.next(), scan.nextInt());
}
scan.close();
Arrays.sort(player, checker);
for(int i = 0; i < player.length; i++){
System.out.printf("%s %s\n", player[i].name, player[i].score);
}
}
} |
3e1273b6d7f695ca1bc9360a35c52f0ed889416e | 2,180 | java | Java | subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/SimpleGroovyExecutableMemberDoc.java | NoraLuna/git-github.com-NoraLuna-tgit | 01309f9d4be34ddf93c4a9943b5a97843bff6181 | [
"Apache-2.0"
] | 860 | 2015-01-01T01:08:04.000Z | 2022-03-29T10:25:57.000Z | subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/SimpleGroovyExecutableMemberDoc.java | NoraLuna/git-github.com-NoraLuna-tgit | 01309f9d4be34ddf93c4a9943b5a97843bff6181 | [
"Apache-2.0"
] | 103 | 2015-01-01T09:35:05.000Z | 2019-03-06T22:22:32.000Z | subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/SimpleGroovyExecutableMemberDoc.java | NoraLuna/git-github.com-NoraLuna-tgit | 01309f9d4be34ddf93c4a9943b5a97843bff6181 | [
"Apache-2.0"
] | 285 | 2015-01-03T11:33:14.000Z | 2022-03-03T12:25:28.000Z | 40.37037 | 113 | 0.718349 | 7,782 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.codehaus.groovy.tools.groovydoc;
import java.util.*;
import org.codehaus.groovy.groovydoc.*;
public class SimpleGroovyExecutableMemberDoc extends SimpleGroovyMemberDoc implements GroovyExecutableMemberDoc {
List parameters;
public SimpleGroovyExecutableMemberDoc(String name, GroovyClassDoc belongsToClass) {
super(name, belongsToClass);
parameters = new ArrayList();
}
public GroovyParameter[] parameters() {
return (GroovyParameter[]) parameters.toArray(new GroovyParameter[parameters.size()]);
}
public void add(GroovyParameter parameter) {
parameters.add(parameter);
}
public String flatSignature() {/*todo*/return null;}
public boolean isNative() {/*todo*/return false;}
public boolean isSynchronized() {/*todo*/return false;}
public boolean isVarArgs() {/*todo*/return false;}
// public GroovyParamTag[] paramTags() {/*todo*/return null;}
public String signature() {/*todo*/return null;}
public GroovyClassDoc[] thrownExceptions() {/*todo*/return null;}
public GroovyType[] thrownExceptionTypes() {/*todo*/return null;}
// public GroovyThrowsTag[] throwsTags() {/*todo*/return null;}
// public GroovyTypeVariable[] typeParameters() {/*todo*/return null;}
// public GroovyParamTag[] typeParamTags() {/*todo*/return null;}
}
|
3e1273fdb6268f3c73ef1be854e0916e81319092 | 944 | java | Java | modules/global/src/com/haulmont/cuba/core/entity/annotation/LocalizedValue.java | cuba-platform/cuba-thesis | 09ae6b584537f89e458a6a70c9344b3f47d9a8c4 | [
"Apache-2.0"
] | 2 | 2020-02-21T08:17:10.000Z | 2020-07-27T08:24:47.000Z | modules/global/src/com/haulmont/cuba/core/entity/annotation/LocalizedValue.java | cuba-platform/cuba-thesis | 09ae6b584537f89e458a6a70c9344b3f47d9a8c4 | [
"Apache-2.0"
] | null | null | null | modules/global/src/com/haulmont/cuba/core/entity/annotation/LocalizedValue.java | cuba-platform/cuba-thesis | 09ae6b584537f89e458a6a70c9344b3f47d9a8c4 | [
"Apache-2.0"
] | 2 | 2020-02-21T08:17:12.000Z | 2020-09-22T20:02:02.000Z | 28.606061 | 108 | 0.693856 | 7,783 | /*
* Copyright (c) 2008-2013 Haulmont. All rights reserved.
* Use is subject to license terms, see http://www.cuba-platform.com/license for details.
*/
package com.haulmont.cuba.core.entity.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Explains how to get localized value of an attribute
*
* @author krivopustov
* @version $Id$
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface LocalizedValue {
/**
* Explicit definition of a messages pack, e.g. "com.haulmont.cuba.core.entity"
*/
String messagePack() default "";
/**
* Expression in terms of traversing object graph, returning messages pack name stored in an attribute,
* e.g. "proc.messagesPack"
*/
String messagePackExpr() default "";
}
|
3e127414ef57fa53d9144a2ea07cadb86ed67145 | 12,000 | java | Java | src/main/java/com/xero/api/JsonConfig.java | icecreamhead/Xero-Java | caba7a5cc27360c5304ee6421a9d5a13976edd5a | [
"MIT"
] | null | null | null | src/main/java/com/xero/api/JsonConfig.java | icecreamhead/Xero-Java | caba7a5cc27360c5304ee6421a9d5a13976edd5a | [
"MIT"
] | null | null | null | src/main/java/com/xero/api/JsonConfig.java | icecreamhead/Xero-Java | caba7a5cc27360c5304ee6421a9d5a13976edd5a | [
"MIT"
] | null | null | null | 28.708134 | 115 | 0.690083 | 7,784 | package com.xero.api;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import static java.lang.String.format;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonConfig implements Config {
private String APP_TYPE = "Public";
private String USER_AGENT = "Xero-Java-SDK";
private String ACCEPT = "application/xml";
private String CONSUMER_KEY;
private String CONSUMER_SECRET;
private String API_BASE_URL = "https://api.xero.com";
private String API_ENDPOINT_URL = "https://api.xero.com/api.xro/2.0/";
private String FILES_ENDPOINT_URL = "https://api.xero.com/files.xro/1.0/";
private String ASSETS_ENDPOINT_URL = "https://api.xero.com/assets.xro/1.0";
private String BANKFEEDS_ENDPOINT_URL = "https://api.xero.com/bankfeeds.xro/1.0";
private String REQUEST_TOKEN_URL = "https://api.xero.com/oauth/RequestToken";
private String AUTHENTICATE_URL = "https://api.xero.com/oauth/Authorize";
private String ACCESS_TOKEN_URL = "https://api.xero.com/oauth/AccessToken";
private String API_ENDPOINT_STEM = "/api.xro/2.0/";
private String FILES_ENDPOINT_STEM = "/files.xro/1.0/";
private String ASSETS_ENDPOINT_STEM = "/assets.xro/1.0/";
private String BANKFEEDS_ENDPOINT_STEM = "/bankfeeds.xro/1.0/";
private String REQUEST_TOKEN_STEM = "/oauth/RequestToken";
private String AUTHENTICATE_STEM = "/oauth/Authorize";
private String ACCESS_TOKEN_STEM = "/oauth/AccessToken";
private String CALLBACK_BASE_URL;
private String AUTH_CALLBACK_URL;
private String PATH_TO_PRIVATE_KEY_CERT;
private String PRIVATE_KEY_PASSWORD;
private String PROXY_HOST;
private long PROXY_PORT = 80;
private boolean PROXY_HTTPS_ENABLED = false;
private int CONNECT_TIMEOUT = 60;
private int READ_TIMEOUT = 60;
private String DECIMAL_PLACES = null;
private boolean USING_APP_FIREWALL = false;
private String APP_FIREWALL_HOSTNAME;
private String APP_FIREWALL_URL_PREFIX;
private String KEY_STORE_PATH;
private String KEY_STORE_PASSWORD;
private String configFile;
private static Config instance = null;
final static Logger logger = LogManager.getLogger(JsonConfig.class);
public JsonConfig(String configFile) {
this.configFile = configFile;
load();
}
/* Static 'instance' method */
public static Config getInstance() {
if (instance == null) {
instance = new JsonConfig("config.json");
}
return instance;
}
@Override
public String getAppType() {
return APP_TYPE;
}
@Override
public String getPrivateKeyPassword() {
return PRIVATE_KEY_PASSWORD;
}
@Override
public String getPathToPrivateKey() {
return PATH_TO_PRIVATE_KEY_CERT;
}
@Override
public String getConsumerKey() {
return CONSUMER_KEY;
}
@Override
public String getConsumerSecret() {
return CONSUMER_SECRET;
}
@Override
public String getApiUrl() {
return API_ENDPOINT_URL;
}
@Override
public String getFilesUrl() {
return FILES_ENDPOINT_URL;
}
@Override
public String getAssetsUrl() {
return ASSETS_ENDPOINT_URL;
}
@Override
public String getBankFeedsUrl() {
return BANKFEEDS_ENDPOINT_URL;
}
@Override
public String getRequestTokenUrl() {
return REQUEST_TOKEN_URL;
}
@Override
public String getAuthorizeUrl() {
return AUTHENTICATE_URL;
}
@Override
public String getAccessTokenUrl() {
return ACCESS_TOKEN_URL;
}
@Override
public String getUserAgent() {
return USER_AGENT + " " + CONSUMER_KEY + " [Xero-Java-2.1.1]";
}
@Override
public String getAccept() {
return ACCEPT;
}
@Override
public String getRedirectUri() {
return AUTH_CALLBACK_URL;
}
@Override
public String getProxyHost() {
return PROXY_HOST;
}
@Override
public long getProxyPort() {
return PROXY_PORT;
}
@Override
public boolean getProxyHttpsEnabled() {
return PROXY_HTTPS_ENABLED;
}
@Override
public int getConnectTimeout() {
// in seconds
return CONNECT_TIMEOUT;
}
@Override
public int getReadTimeout() {
// in seconds
return READ_TIMEOUT;
}
@Override
public String getDecimalPlaces(){
// 2 or 4
return DECIMAL_PLACES;
}
@Override
public boolean isUsingAppFirewall() {
return USING_APP_FIREWALL;
}
@Override
public String getAppFirewallHostname() {
return APP_FIREWALL_HOSTNAME;
}
@Override
public String getAppFirewallUrlPrefix() {
return APP_FIREWALL_URL_PREFIX;
}
@Override
public String getKeyStorePath() {
return KEY_STORE_PATH;
}
@Override
public String getKeyStorePassword() {
return KEY_STORE_PASSWORD;
}
// SETTERS
@Override
public void setConsumerKey(String consumerKey) {
CONSUMER_KEY = consumerKey;
}
@Override
public void setConsumerSecret(String consumerSecret) {
CONSUMER_SECRET = consumerSecret;
}
@Override
public void setAppType(String appType) {
APP_TYPE = appType;
}
@Override
public void setAuthCallBackUrl(String authCallbackUrl) {
AUTH_CALLBACK_URL = authCallbackUrl;
}
@Override
public void setConnectTimeout(int connectTimeout) {
// in seconds
CONNECT_TIMEOUT = connectTimeout;
}
@Override
public void setReadTimeout(int readTimeout) {
// in seconds
READ_TIMEOUT = readTimeout;
}
@Override
public void setDecimalPlaces(String decimalPlaces) {
// 2 or 4
DECIMAL_PLACES = decimalPlaces;
}
@Override
public void setUsingAppFirewall(boolean usingAppFirewall) {
this.USING_APP_FIREWALL = usingAppFirewall;
}
@Override
public void setAppFirewallHostname(String appFirewallHostname) {
this.APP_FIREWALL_HOSTNAME = appFirewallHostname;
}
@Override
public void setAppFirewallUrlPrefix(String appFirewallUrlPrefix) {
this.APP_FIREWALL_URL_PREFIX = appFirewallUrlPrefix;
}
@Override
public void setKeyStorePath(String keyStorePath) {
this.KEY_STORE_PATH = keyStorePath;
}
@Override
public void setKeyStorePassword(String keyStorePassword) {
this.KEY_STORE_PASSWORD = keyStorePassword;
}
private void load() {
InputStream inputStream = JsonConfig.class.getResourceAsStream("/" + configFile);
if (inputStream == null) {
logger.error(format("Config file '%s' could not be found in src/resources folder. Missing file?", configFile));
throw new XeroClientException(format("Config file '%s' could not be opened. Missing file?", configFile));
} else {
InputStreamReader reader = new InputStreamReader(inputStream);
JSONParser parser = new JSONParser();
Object obj = null;
try {
obj = parser.parse(reader);
} catch (FileNotFoundException e) {
logger.error(e);
throw new XeroClientException(format("Config file '%s' not found", configFile), e);
} catch (IOException e) {
logger.error(e);
throw new XeroClientException(format("IO error reading config file '%s' not found", configFile), e);
} catch (ParseException e) {
logger.error(e);
throw new XeroClientException(format("Parse error reading config file '%s' not found", configFile), e);
}
JSONObject jsonObject = (JSONObject) obj;
if (jsonObject.containsKey("AppType")) {
APP_TYPE = (String) jsonObject.get("AppType");
}
if (jsonObject.containsKey("UserAgent")) {
USER_AGENT = (String) jsonObject.get("UserAgent");
}
if (jsonObject.containsKey("Accept")) {
ACCEPT = (String) jsonObject.get("Accept");
}
if (jsonObject.containsKey("ConsumerKey")) {
CONSUMER_KEY = (String) jsonObject.get("ConsumerKey");
}
if (jsonObject.containsKey("ConsumerSecret")) {
CONSUMER_SECRET = (String) jsonObject.get("ConsumerSecret");
}
if (jsonObject.containsKey("ApiBaseUrl")) {
API_BASE_URL = (String) jsonObject.get("ApiBaseUrl");
if (jsonObject.containsKey("ApiEndpointPath")) {
String endpointPath = (String) jsonObject.get("ApiEndpointPath");
API_ENDPOINT_URL = API_BASE_URL + endpointPath;
} else {
API_ENDPOINT_URL = API_BASE_URL + API_ENDPOINT_STEM;
}
if (jsonObject.containsKey("FilesEndpointPath")) {
String filesEndpointPath = (String) jsonObject.get("FilesEndpointPath");
FILES_ENDPOINT_URL = API_BASE_URL + filesEndpointPath;
} else {
FILES_ENDPOINT_URL = API_BASE_URL + FILES_ENDPOINT_STEM;
}
if (jsonObject.containsKey("AssetsEndpointPath")) {
String assetsEndpointPath = (String) jsonObject.get("AssetsEndpointPath");
ASSETS_ENDPOINT_URL = API_BASE_URL + assetsEndpointPath;
} else {
ASSETS_ENDPOINT_URL = API_BASE_URL + ASSETS_ENDPOINT_STEM;
}
if (jsonObject.containsKey("BankFeedsEndpointPath")) {
String BankFeedsEndpointPath = (String) jsonObject.get("BankFeedsEndpointPath");
BANKFEEDS_ENDPOINT_URL = API_BASE_URL + BankFeedsEndpointPath;
} else {
BANKFEEDS_ENDPOINT_URL = API_BASE_URL + BANKFEEDS_ENDPOINT_STEM;
}
if (jsonObject.containsKey("RequestTokenPath")) {
String requestPath = (String) jsonObject.get("RequestTokenPath");
REQUEST_TOKEN_URL = API_BASE_URL + requestPath;
} else {
REQUEST_TOKEN_URL = API_BASE_URL + REQUEST_TOKEN_STEM;
}
if (jsonObject.containsKey("AccessTokenPath")) {
String accessPath = (String) jsonObject.get("AccessTokenPath");
ACCESS_TOKEN_URL = API_BASE_URL + accessPath;
} else {
ACCESS_TOKEN_URL = API_BASE_URL + ACCESS_TOKEN_STEM;
}
if (jsonObject.containsKey("AuthenticateUrl")) {
String authenticatePath = (String) jsonObject.get("AuthenticateUrl");
AUTHENTICATE_URL = API_BASE_URL + authenticatePath;
} else {
AUTHENTICATE_URL = API_BASE_URL + AUTHENTICATE_STEM;
}
}
if (jsonObject.containsKey("CallbackBaseUrl")) {
CALLBACK_BASE_URL = (String) jsonObject.get("CallbackBaseUrl");
if (jsonObject.containsKey("CallbackPath")) {
String callbackPath = (String) jsonObject.get("CallbackPath");
AUTH_CALLBACK_URL = CALLBACK_BASE_URL + callbackPath;
}
}
if (jsonObject.containsKey("PrivateKeyCert")) {
PATH_TO_PRIVATE_KEY_CERT = (String) jsonObject.get("PrivateKeyCert");
PRIVATE_KEY_PASSWORD = (String) jsonObject.get("PrivateKeyPassword");
}
if (jsonObject.containsKey("ProxyHost")) {
PROXY_HOST = (String) jsonObject.get("ProxyHost");
if (jsonObject.containsKey("ProxyPort")) {
PROXY_PORT = (long) jsonObject.get("ProxyPort");
}
if (jsonObject.containsKey("ProxyHttpsEnabled")) {
PROXY_HTTPS_ENABLED = (boolean) jsonObject.get("ProxyHttpsEnabled");
}
}
if (jsonObject.containsKey("DecimalPlaces")) {
DECIMAL_PLACES = (String) jsonObject.get("DecimalPlaces");
}
if (jsonObject.containsKey("KeyStorePath")) {
KEY_STORE_PATH = (String) jsonObject.get("KeyStorePath");
}
if (jsonObject.containsKey("KeyStorePassword")) {
KEY_STORE_PASSWORD = (String) jsonObject.get("KeyStorePassword");
}
if (jsonObject.containsKey("usingAppFirewall")) {
USING_APP_FIREWALL = (boolean) jsonObject.get("usingAppFirewall");
if (jsonObject.containsKey("appFirewallHostname")) {
APP_FIREWALL_HOSTNAME = (String) jsonObject.get("appFirewallHostname");
}
if (jsonObject.containsKey("appFirewallUrlPrefix")) {
APP_FIREWALL_URL_PREFIX = (String) jsonObject.get("appFirewallUrlPrefix");
}
}
}
}
}
|
3e12742f5ecb810600fdaa6ab3c916bf9b14aa74 | 583 | java | Java | bak/access/service/impl/WenDangXiuGaiYeServiceImpl.java | zhanglailong/stcp | 2209f2f7c81a01da948e5c6c050d215d656a77de | [
"MIT"
] | null | null | null | bak/access/service/impl/WenDangXiuGaiYeServiceImpl.java | zhanglailong/stcp | 2209f2f7c81a01da948e5c6c050d215d656a77de | [
"MIT"
] | null | null | null | bak/access/service/impl/WenDangXiuGaiYeServiceImpl.java | zhanglailong/stcp | 2209f2f7c81a01da948e5c6c050d215d656a77de | [
"MIT"
] | null | null | null | 27.761905 | 136 | 0.811321 | 7,785 | package org.jeecg.modules.access.service.impl;
import org.jeecg.modules.access.entity.WenDangXiuGaiYe;
import org.jeecg.modules.access.mapper.WenDangXiuGaiYeMapper;
import org.jeecg.modules.access.service.IWenDangXiuGaiYeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 文档修改页 服务实现类
* </p>
*
* @author GodMeowIceSun
* @since 2021-08-06
*/
@Service
public class WenDangXiuGaiYeServiceImpl extends ServiceImpl<WenDangXiuGaiYeMapper, WenDangXiuGaiYe> implements IWenDangXiuGaiYeService {
}
|
3e12744a05c8852abeb84cc2e8f0be8a720a194a | 2,989 | java | Java | jimsql/jim-sdk/jim-core/src/main/java/io/jimdb/core/Bootstraps.java | jimdb-org/jimdb | 927e4447879189597dbe7f91a7fe0e8865107ef4 | [
"Apache-2.0"
] | 59 | 2020-01-10T06:27:12.000Z | 2021-12-16T06:37:36.000Z | jimsql/jim-sdk/jim-core/src/main/java/io/jimdb/core/Bootstraps.java | jimdb-org/jimdb | 927e4447879189597dbe7f91a7fe0e8865107ef4 | [
"Apache-2.0"
] | null | null | null | jimsql/jim-sdk/jim-core/src/main/java/io/jimdb/core/Bootstraps.java | jimdb-org/jimdb | 927e4447879189597dbe7f91a7fe0e8865107ef4 | [
"Apache-2.0"
] | 3 | 2020-02-13T05:04:20.000Z | 2020-06-29T01:07:48.000Z | 32.846154 | 90 | 0.739043 | 7,786 | /*
* Copyright 2019 The JIMDB Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package io.jimdb.core;
import java.util.Properties;
import io.jimdb.core.config.JimConfig;
import io.jimdb.common.config.SystemProperties;
import io.jimdb.common.exception.DBException;
import io.jimdb.common.exception.ErrorCode;
import io.jimdb.common.exception.ErrorModule;
import io.jimdb.common.exception.BaseException;
import io.jimdb.core.plugin.PluginFactory;
import io.jimdb.core.plugin.SQLEngine;
import io.jimdb.common.utils.lang.IOUtil;
import io.jimdb.common.utils.lang.UncaughtExceptionHandlerImpl;
import io.netty.util.ResourceLeakDetector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import reactor.core.publisher.Hooks;
import reactor.core.scheduler.Schedulers;
/**
* @version V1.0
*/
@SuppressFBWarnings("OCP_OVERLY_CONCRETE_PARAMETER")
public final class Bootstraps {
private static final Logger LOG = LoggerFactory.getLogger(Bootstraps.class);
private Bootstraps() {
}
public static JimConfig init(final String confFile) {
Properties properties = IOUtil.loadResource(confFile);
JimConfig config = new JimConfig(properties);
init(config);
return config;
}
public static void init(final JimConfig config) {
// load plugin
PluginFactory.init(config);
final SQLEngine sqlEngine = PluginFactory.getSqlEngine();
if (sqlEngine != null) {
sqlEngine.setSQLExecutor(PluginFactory.getSqlExecutor());
}
// init global variable
Thread.setDefaultUncaughtExceptionHandler(UncaughtExceptionHandlerImpl.getInstance());
ResourceLeakDetector.setLevel(SystemProperties.getLeakLevel());
// init reactor
if (SystemProperties.getReactorDebug()) {
Hooks.onOperatorDebug();
}
Hooks.onNextDropped(o -> LOG.error("Occur next event dropped : {}.", o));
Hooks.onErrorDropped(e -> LOG.error("Occur error event dropped.", e));
Hooks.onOperatorError((e, o) -> {
LOG.error(String.format("OperatorError : %s", o), e);
if (e instanceof BaseException) {
return e;
}
return DBException.get(ErrorModule.EXECUTOR, ErrorCode.ER_SYSTEM_INTERNAL, e);
});
if (config.getSchedulerFactory() != null) {
Schedulers.setFactory(config.getSchedulerFactory());
}
}
public static void stop(final JimConfig config) throws Exception {
PluginFactory.close();
config.close();
}
}
|
3e1274a1785fd18b3d5cad61d5eef269e42be99e | 7,002 | java | Java | src/dctc/java/com/dataiku/dctc/command/Rm.java | dataiku/dctc | 67e6edfdd93c292ba4dba1863e9a39dad32d92fd | [
"Apache-2.0"
] | 1 | 2016-03-23T15:39:46.000Z | 2016-03-23T15:39:46.000Z | src/dctc/java/com/dataiku/dctc/command/Rm.java | dataiku/dctc | 67e6edfdd93c292ba4dba1863e9a39dad32d92fd | [
"Apache-2.0"
] | null | null | null | src/dctc/java/com/dataiku/dctc/command/Rm.java | dataiku/dctc | 67e6edfdd93c292ba4dba1863e9a39dad32d92fd | [
"Apache-2.0"
] | 1 | 2021-01-21T10:00:57.000Z | 2021-01-21T10:00:57.000Z | 31.399103 | 79 | 0.423736 | 7,787 | package com.dataiku.dctc.command;
import static com.dataiku.dip.utils.PrettyString.scat;
import java.io.IOException;
import java.util.List;
import com.dataiku.dctc.clo.OptionAgregator;
import com.dataiku.dctc.command.abs.Command;
import com.dataiku.dctc.display.Interactive;
import com.dataiku.dctc.file.GFile;
import com.dataiku.dip.utils.IndentedWriter;
public class Rm extends Command {
public String tagline() {
return "Remove files and folders.";
}
public void longDescription(IndentedWriter printer) {
printer.print(scat("Remove files and folders. By default, it will"
, "refuse to remove"
, "folders. Use -r"));
}
// Public
@Override
public void perform(List<GFile> args) {
for (GFile arg: args) {
try {
if (exists(arg) && couldDelDir(arg)) {
rm(arg);
}
} catch (IOException e) {
error(arg, "failed to delete", e, 0);
}
}
}
@Override
public String cmdname() {
return "rm";
}
/// Getters
public boolean interactive() {
if (interactive == null) {
interactive = hasOption('i');
}
return interactive;
}
public boolean verbose() {
if (verbose == null) {
verbose = hasOption('v');
}
return verbose;
}
public boolean recursiveDeletion() {
if (recursiveDeletion == null) {
recursiveDeletion = hasOption('r');
}
return recursiveDeletion;
}
public boolean force() {
if (force == null) {
force = hasOption('f');
}
return force;
}
/// Setters
public Rm interactive(boolean interactive) {
this.interactive = interactive;
return this;
}
public Rm verbose(boolean verbose) {
this.verbose = verbose;
return this;
}
public Rm recursiveDeletion(boolean recursiveDeletion) {
this.recursiveDeletion = recursiveDeletion;
return this;
}
public Rm force(boolean force) {
this.force = force;
return this;
}
// Protected
@Override
protected void setOptions(List<OptionAgregator> opts) {
opts.add(stdOption('v'
, "verbose"
, "Explain what i being done."));
opts.add(stdOption("rR"
, "recursive"
, "Remove directories and their contents"
+ " recursively."));
opts.add(stdOption('f'
, "force"
, "Ignore nonexistent files and arguments,"
+ " never prompt."));
opts.add(stdOption('i'
, "Prompt before every removal."));
}
@Override
protected String proto() {
return "[OPT...] [FILE...]";
}
// Private
private void del(GFile arg) throws IOException {
if (recursiveDeletion() || arg.isFile() || arg.isEmpty()) {
if (!arg.delete()) {
if (!force()) {
error(arg, "Cannot remove", 2);
}
}
}
else {
notEmpty(arg);
}
}
private boolean dirAsk(GFile arg) throws IOException {
if (arg.isEmpty()) {
return Interactive.ask("rm"
, "rm: remove directory `"
+ arg.givenName() + "'? "
, "yY"
, "nN"
, getYell());
}
else {
return Interactive.ask("rm"
, "rm: descend into directory `"
+ arg.givenName() + "'? "
, "yY"
, "nN"
, getYell());
}
}
private boolean fileAsk(GFile arg) {
return Interactive.ask("rm"
, "rm: remove regular file `"
+ arg.givenName() + "'? "
, "yY"
, "nN"
, getYell());
}
private void notEmpty(GFile arg) {
error(arg, "Cannot remove, directory not empty", 1);
}
private void rm(GFile arg) throws IOException {
if (arg.isDirectory()) {
if (!interactive() || dirAsk(arg)) {
if (interactive()) {
// If one file is not delete, we must not delete
// the root.
List<? extends GFile> sons = arg.grecursiveList();
for (int i = sons.size() - 1; i != -1; --i) {
GFile son = sons.get(i);
if (son.isDirectory()) {
if (dirAsk(son)) {
del(son);
}
}
else {
if (fileAsk(son)) {
del(son);
}
}
}
}
else {
if (verbose()) {
@SuppressWarnings("unchecked")
List<GFile> rlist = (List<GFile>) arg.grecursiveList();
for (int i = rlist.size() - 1; i != -1; --i) {
GFile son = rlist.get(i);
verbose(son.givenName());
del(son);
}
}
else {
del(arg);
}
}
}
}
else {
if (!interactive() || fileAsk(arg)) {
del(arg);
}
}
}
private boolean couldDelDir(GFile arg) throws IOException {
if (arg.isDirectory() && !recursiveDeletion()) {
if (!force()) {
error(arg, "Cannot remove, is a directory", 2);
}
return false;
}
return true;
}
private boolean exists(GFile arg) throws IOException {
if (arg.exists() || force()) {
return true;
}
else {
if (!force()) {
error(arg, "Cannot remove, no such file or directory", 2);
}
return false;
}
}
private void verbose(String arg) {
if (verbose()) {
System.out.println("removed `" + arg + "'");
}
}
// Attributes
private Boolean interactive = null;
private Boolean verbose = null;
private Boolean recursiveDeletion = null;
private Boolean force = null;
}
|
3e1274da01c152412876c9123249d6d456b81f15 | 3,282 | java | Java | library/src/test/java/com/bugsnag/android/repackaged/dslplatform/json/generated/types/Map/NullableArrayOfOneMapsDefaultValueTurtle.java | bugsnag/dsl-json | b6962b182f6d44c25682177018b73e003128e761 | [
"BSD-3-Clause"
] | null | null | null | library/src/test/java/com/bugsnag/android/repackaged/dslplatform/json/generated/types/Map/NullableArrayOfOneMapsDefaultValueTurtle.java | bugsnag/dsl-json | b6962b182f6d44c25682177018b73e003128e761 | [
"BSD-3-Clause"
] | null | null | null | library/src/test/java/com/bugsnag/android/repackaged/dslplatform/json/generated/types/Map/NullableArrayOfOneMapsDefaultValueTurtle.java | bugsnag/dsl-json | b6962b182f6d44c25682177018b73e003128e761 | [
"BSD-3-Clause"
] | null | null | null | 64.352941 | 415 | 0.784887 | 7,788 | package com.bugsnag.android.repackaged.dslplatform.json.generated.types.Map;
import com.bugsnag.android.repackaged.dslplatform.json.generated.types.StaticJson;
import com.bugsnag.android.repackaged.dslplatform.json.generated.ocd.javaasserts.MapAsserts;
import java.io.IOException;
@SuppressWarnings({"rawtypes", "unchecked"}) // suppress pre-existing warnings
public class NullableArrayOfOneMapsDefaultValueTurtle {
private static StaticJson.JsonSerialization jsonSerialization;
@org.junit.BeforeClass
public static void initializeJsonSerialization() throws IOException {
jsonSerialization = StaticJson.getSerialization();
}
@org.junit.Test
public void testDefaultValueEquality() throws IOException {
final java.util.Map<String, String>[] defaultValue = null;
final StaticJson.Bytes defaultValueJsonSerialized = jsonSerialization.serialize(defaultValue);
final java.util.Map<String, String>[] defaultValueJsonDeserialized = jsonSerialization.deserialize(java.util.Map[].class, defaultValueJsonSerialized.content, defaultValueJsonSerialized.length);
MapAsserts.assertNullableArrayOfOneEquals(defaultValue, defaultValueJsonDeserialized);
}
@org.junit.Test
public void testBorderValue1Equality() throws IOException {
final java.util.Map<String, String>[] borderValue1 = new java.util.Map[] { new java.util.HashMap<String, String>(0) };
final StaticJson.Bytes borderValue1JsonSerialized = jsonSerialization.serialize(borderValue1);
final java.util.Map<String, String>[] borderValue1JsonDeserialized = jsonSerialization.deserialize(java.util.Map[].class, borderValue1JsonSerialized.content, borderValue1JsonSerialized.length);
MapAsserts.assertNullableArrayOfOneEquals(borderValue1, borderValue1JsonDeserialized);
}
@org.junit.Test
public void testBorderValue2Equality() throws IOException {
final java.util.Map<String, String>[] borderValue2 = new java.util.Map[] { new java.util.HashMap<String, String>() {{ put("", "empty"); put("a", "1"); put("b", "2"); put("c", "3"); }} };
final StaticJson.Bytes borderValue2JsonSerialized = jsonSerialization.serialize(borderValue2);
final java.util.Map<String, String>[] borderValue2JsonDeserialized = jsonSerialization.deserialize(java.util.Map[].class, borderValue2JsonSerialized.content, borderValue2JsonSerialized.length);
MapAsserts.assertNullableArrayOfOneEquals(borderValue2, borderValue2JsonDeserialized);
}
@org.junit.Test
public void testBorderValue3Equality() throws IOException {
final java.util.Map<String, String>[] borderValue3 = new java.util.Map[] { new java.util.HashMap<String, String>(0), new java.util.HashMap<String, String>() {{ put("a", "b"); }}, new java.util.HashMap<String, String>() {{ put("Quote: \", Solidus /", "Backslash: \\, Aphos: ', Brackets: [] () {}"); }}, new java.util.HashMap<String, String>() {{ put("", "empty"); put("a", "1"); put("b", "2"); put("c", "3"); }} };
final StaticJson.Bytes borderValue3JsonSerialized = jsonSerialization.serialize(borderValue3);
final java.util.Map<String, String>[] borderValue3JsonDeserialized = jsonSerialization.deserialize(java.util.Map[].class, borderValue3JsonSerialized.content, borderValue3JsonSerialized.length);
MapAsserts.assertNullableArrayOfOneEquals(borderValue3, borderValue3JsonDeserialized);
}
}
|
3e1274f279cf95510a3d79cda09ef19438183ceb | 966 | java | Java | Lab5/RecyclerViewLab/app/src/main/java/mobiledev/unb/ca/recyclerviewlab/model/Course.java | zikaihuang/cs2063-winter-2021-labs | f674b15cd854dd98c302e7f9dabbbb741e96aac0 | [
"Apache-2.0"
] | 2 | 2021-01-28T04:54:17.000Z | 2021-03-25T00:13:02.000Z | Lab5/RecyclerViewLab/app/src/main/java/mobiledev/unb/ca/recyclerviewlab/model/Course.java | zikaihuang/cs2063-winter-2021-labs | f674b15cd854dd98c302e7f9dabbbb741e96aac0 | [
"Apache-2.0"
] | null | null | null | Lab5/RecyclerViewLab/app/src/main/java/mobiledev/unb/ca/recyclerviewlab/model/Course.java | zikaihuang/cs2063-winter-2021-labs | f674b15cd854dd98c302e7f9dabbbb741e96aac0 | [
"Apache-2.0"
] | 8 | 2021-01-26T18:49:22.000Z | 2021-04-26T01:28:07.000Z | 23 | 95 | 0.604555 | 7,789 | package mobiledev.unb.ca.recyclerviewlab.model;
import androidx.annotation.NonNull;
public class Course {
private final String id;
private final String name;
private final String description;
private Course (Builder builder) {
this.id = builder.id;
this.name = builder.name;
this.description = builder.description;
}
// Only need to include getters
public String getTitle() {
return id + ": " + name;
}
public String getDescription() {
return description;
}
public static class Builder {
private String id;
private String name;
private String description;
public Builder(@NonNull String id, @NonNull String name, @NonNull String description) {
this.id = id;
this.name = name;
this.description = description;
}
public Course build() {
return new Course(this);
}
}
}
|
3e12764802fae1a2cec33fab4b1b16b142275d19 | 2,287 | java | Java | ohara-common/src/main/java/oharastream/ohara/common/setting/KeyImpl.java | wu87988622/ohara | 54ed84693c977e94751ee2afcdd1bd789e236e2c | [
"Apache-2.0"
] | 1 | 2019-03-28T02:33:36.000Z | 2019-03-28T02:33:36.000Z | ohara-common/src/main/java/oharastream/ohara/common/setting/KeyImpl.java | wu87988622/ohara | 54ed84693c977e94751ee2afcdd1bd789e236e2c | [
"Apache-2.0"
] | null | null | null | ohara-common/src/main/java/oharastream/ohara/common/setting/KeyImpl.java | wu87988622/ohara | 54ed84693c977e94751ee2afcdd1bd789e236e2c | [
"Apache-2.0"
] | 1 | 2020-07-03T11:05:45.000Z | 2020-07-03T11:05:45.000Z | 30.493333 | 97 | 0.710538 | 7,790 | /*
* Copyright 2019 is-land
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oharastream.ohara.common.setting;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;
import oharastream.ohara.common.json.JsonObject;
import oharastream.ohara.common.util.CommonUtils;
/**
* this is for marshalling object to json representation. { "group": "g", "name": "n" }
*
* <p>Noted: this impl extends the {@link TopicKey} than {@link ObjectKey} since both interfaces
* have identical impl, and we all hate duplicate code. Noted: this class should be internal than
* public to other packages.
*/
class KeyImpl implements JsonObject, TopicKey, ConnectorKey, Serializable {
private static final long serialVersionUID = 1L;
private static final String GROUP_KEY = "group";
private static final String NAME_KEY = "name";
private final String group;
private final String name;
@JsonCreator
KeyImpl(@JsonProperty(GROUP_KEY) String group, @JsonProperty(NAME_KEY) String name) {
this.group = CommonUtils.requireNonEmpty(group);
this.name = CommonUtils.requireNonEmpty(name);
}
@Override
@JsonProperty(GROUP_KEY)
public String group() {
return group;
}
@Override
@JsonProperty(NAME_KEY)
public String name() {
return name;
}
// ------------------------[object]------------------------//
@Override
public boolean equals(Object obj) {
if (obj instanceof ObjectKey)
return ((ObjectKey) obj).group().equals(group) && ((ObjectKey) obj).name().equals(name);
return false;
}
@Override
public int hashCode() {
return toJsonString().hashCode();
}
@Override
public String toString() {
return toJsonString();
}
}
|
3e1276925b9a1616ee672274e7cfabd7be15baf2 | 2,391 | java | Java | djmall-sale/src/main/java/com/qz/djmall/sale/controller/SmsCouponHistoryController.java | liuboyuan0098/my-djmall | 87a629c7d01058e94ca7113c3dfe14459a4ee4be | [
"Apache-2.0"
] | null | null | null | djmall-sale/src/main/java/com/qz/djmall/sale/controller/SmsCouponHistoryController.java | liuboyuan0098/my-djmall | 87a629c7d01058e94ca7113c3dfe14459a4ee4be | [
"Apache-2.0"
] | null | null | null | djmall-sale/src/main/java/com/qz/djmall/sale/controller/SmsCouponHistoryController.java | liuboyuan0098/my-djmall | 87a629c7d01058e94ca7113c3dfe14459a4ee4be | [
"Apache-2.0"
] | 1 | 2020-11-25T11:50:53.000Z | 2020-11-25T11:50:53.000Z | 26.197802 | 80 | 0.713926 | 7,791 | package com.qz.djmall.sale.controller;
import java.util.Arrays;
import java.util.Map;
//import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.qz.djmall.sale.entity.SmsCouponHistoryEntity;
import com.qz.djmall.sale.service.SmsCouponHistoryService;
import com.qz.common.utils.PageUtils;
import com.qz.common.utils.R;
/**
* 优惠券领取历史记录
*
* @author lby
* @email anpch@example.com
* @date 2020-12-01 17:00:56
*/
@RestController
@RequestMapping("sale/smscouponhistory")
public class SmsCouponHistoryController {
@Autowired
private SmsCouponHistoryService smsCouponHistoryService;
/**
* 列表
*/
@RequestMapping("/list")
//@RequiresPermissions("sale:smscouponhistory:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = smsCouponHistoryService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{id}")
//@RequiresPermissions("sale:smscouponhistory:info")
public R info(@PathVariable("id") Long id){
SmsCouponHistoryEntity smsCouponHistory = smsCouponHistoryService.getById(id);
return R.ok().put("smsCouponHistory", smsCouponHistory);
}
/**
* 保存
*/
@RequestMapping("/save")
//@RequiresPermissions("sale:smscouponhistory:save")
public R save(@RequestBody SmsCouponHistoryEntity smsCouponHistory){
smsCouponHistoryService.save(smsCouponHistory);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
//@RequiresPermissions("sale:smscouponhistory:update")
public R update(@RequestBody SmsCouponHistoryEntity smsCouponHistory){
smsCouponHistoryService.updateById(smsCouponHistory);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
//@RequiresPermissions("sale:smscouponhistory:delete")
public R delete(@RequestBody Long[] ids){
smsCouponHistoryService.removeByIds(Arrays.asList(ids));
return R.ok();
}
}
|
3e12772ad4a0fe20e6d902ad82d5a1f9736aba7b | 2,481 | java | Java | src/de/lorenzwiest/basiccompiler/compiler/library/methods/helper/Method_Substring.java | lwiest/BASICCompiler | fb0678444f42ab1fdc60a83697a4d3b283cea813 | [
"Xerox",
"MIT",
"Unlicense"
] | 15 | 2015-10-15T12:51:26.000Z | 2022-01-04T14:14:35.000Z | src/de/lorenzwiest/basiccompiler/compiler/library/methods/helper/Method_Substring.java | lwiest/BASICCompiler | fb0678444f42ab1fdc60a83697a4d3b283cea813 | [
"Xerox",
"MIT",
"Unlicense"
] | 1 | 2022-03-02T13:56:48.000Z | 2022-03-02T13:56:48.000Z | src/de/lorenzwiest/basiccompiler/compiler/library/methods/helper/Method_Substring.java | lwiest/BASICCompiler | fb0678444f42ab1fdc60a83697a4d3b283cea813 | [
"Xerox",
"MIT",
"Unlicense"
] | 3 | 2015-05-03T06:15:29.000Z | 2019-10-03T06:05:54.000Z | 30.256098 | 78 | 0.73156 | 7,792 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 Lorenz Wiest
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package de.lorenzwiest.basiccompiler.compiler.library.methods.helper;
import java.util.List;
import de.lorenzwiest.basiccompiler.classfile.info.ExceptionTableInfo;
import de.lorenzwiest.basiccompiler.compiler.etc.ByteOutStream;
import de.lorenzwiest.basiccompiler.compiler.library.LibraryManager;
import de.lorenzwiest.basiccompiler.compiler.library.methods.Method;
public class Method_Substring extends Method {
private final static String METHOD_NAME = "Substring";
private final static String DESCRIPTOR = "([CII)[C";
private final static int NUM_LOCALS = 5;
public Method_Substring(LibraryManager libraryManager) {
super(libraryManager, METHOD_NAME, DESCRIPTOR, NUM_LOCALS);
}
@Override
public void addMethodBytecode(ByteOutStream o, List<ExceptionTableInfo> e) {
// local 0: [C source char[]
// local 1: I start index, inclusive
// local 2: I end index, exclusive
// local 3: I temp length substring
// local 4: [C substring char[]
o.iload_2();
o.iload_1();
o.isub();
o.istore_3();
o.iload_3();
o.newarray_char();
o.astore(4);
o.goto_("loopCond");
o.label("loop");
o.iinc(3, -1);
o.iinc(2, -1);
o.aload(4);
o.iload_3();
o.aload_0();
o.iload_2();
o.caload();
o.castore();
o.label("loopCond");
o.iload_3();
o.ifgt("loop");
o.aload(4);
o.areturn();
}
}
|
3e1278a8bdb7b36c0844a5717c5e079322720f50 | 2,645 | java | Java | truevfs-it/src/test/java/net/java/truevfs/kernel/spec/io/ThrowingInputStream.java | XakepSDK/truevfs | 62f9dabc105987d2b25add9b0e9389176ebcee4d | [
"Apache-2.0"
] | 18 | 2017-10-19T04:46:53.000Z | 2021-09-16T04:24:26.000Z | truevfs-it/src/test/java/net/java/truevfs/kernel/spec/io/ThrowingInputStream.java | XakepSDK/truevfs | 62f9dabc105987d2b25add9b0e9389176ebcee4d | [
"Apache-2.0"
] | 13 | 2017-09-26T12:23:48.000Z | 2022-02-03T11:08:12.000Z | truevfs-it/src/test/java/net/java/truevfs/kernel/spec/io/ThrowingInputStream.java | XakepSDK/truevfs | 62f9dabc105987d2b25add9b0e9389176ebcee4d | [
"Apache-2.0"
] | 4 | 2017-10-19T04:46:55.000Z | 2022-03-31T13:22:43.000Z | 26.45 | 77 | 0.668431 | 7,793 | /*
* Copyright © 2005 - 2021 Schlichtherle IT Services.
* All rights reserved. Use is subject to license terms.
*/
package net.java.truevfs.kernel.spec.io;
import net.java.truecommons.io.DecoratingInputStream;
import edu.umd.cs.findbugs.annotations.CreatesObligation;
import java.io.IOException;
import java.io.InputStream;
import javax.annotation.CheckForNull;
import javax.annotation.WillCloseWhenClosed;
import javax.annotation.concurrent.NotThreadSafe;
import net.java.truevfs.kernel.spec.FsTestConfig;
import net.java.truevfs.kernel.spec.FsThrowManager;
/**
* A decorating input stream which supports throwing exceptions according to
* {@link FsTestConfig}.
*
* @see ThrowingOutputStream
* @author Christian Schlichtherle
*/
@NotThreadSafe
public final class ThrowingInputStream extends DecoratingInputStream {
private final FsThrowManager control;
@CreatesObligation
public ThrowingInputStream(@WillCloseWhenClosed InputStream in) {
this(in, null);
}
@CreatesObligation
public ThrowingInputStream( final @WillCloseWhenClosed InputStream in,
final @CheckForNull FsThrowManager control) {
super(in);
this.control = null != control
? control
: FsTestConfig.get().getThrowControl();
}
private void checkAllExceptions() throws IOException {
control.check(this, IOException.class);
checkUndeclaredExceptions();
}
private void checkUndeclaredExceptions() {
control.check(this, RuntimeException.class);
control.check(this, Error.class);
}
@Override
public int read() throws IOException {
checkAllExceptions();
return in.read();
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
checkAllExceptions();
return in.read(b, off, len);
}
@Override
public long skip(long n) throws IOException {
checkAllExceptions();
return in.skip(n);
}
@Override
public int available() throws IOException {
checkAllExceptions();
return in.available();
}
@Override
public void close() throws IOException {
checkAllExceptions();
in.close();
}
@Override
public void mark(int readlimit) {
checkUndeclaredExceptions();
in.mark(readlimit);
}
@Override
public void reset() throws IOException {
checkAllExceptions();
in.reset();
}
@Override
public boolean markSupported() {
checkUndeclaredExceptions();
return in.markSupported();
}
} |
3e12797c5adb2e43624289ae3a25feaf58144d59 | 595 | java | Java | src/main/java/com/github/sandor_balazs/sentiment_analysis/jaxb/corpus/package-info.java | sandor-balazs/sentiment-analysis | f262db387a58fdbeb314c615e6f7dd123c8c32e7 | [
"MIT"
] | 4 | 2016-12-10T14:20:59.000Z | 2016-12-22T23:40:50.000Z | src/main/java/com/github/sandor_balazs/sentiment_analysis/jaxb/corpus/package-info.java | sandor-balazs/sentiment-analysis | f262db387a58fdbeb314c615e6f7dd123c8c32e7 | [
"MIT"
] | null | null | null | src/main/java/com/github/sandor_balazs/sentiment_analysis/jaxb/corpus/package-info.java | sandor-balazs/sentiment-analysis | f262db387a58fdbeb314c615e6f7dd123c8c32e7 | [
"MIT"
] | null | null | null | 59.5 | 182 | 0.769748 | 7,794 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.11.10 at 10:56:43 AM CET
//
@javax.xml.bind.annotation.XmlSchema(namespace = "http://github.com/sandor-balazs/sentiment-analysis/jaxb/corpus", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.github.sandor_balazs.sentiment_analysis.jaxb.corpus;
|
3e127b87017071aa7baac3b35ce89b25d3867083 | 768 | java | Java | container-core/src/main/java/com/yahoo/container/jdisc/state/FileWrapper.java | sagiyaho/vespa | 5865b9bb80b540f6d252312fa6002300b2f1c9ee | [
"Apache-2.0"
] | 4,054 | 2017-08-11T07:58:38.000Z | 2022-03-31T22:32:15.000Z | container-core/src/main/java/com/yahoo/container/jdisc/state/FileWrapper.java | sagiyaho/vespa | 5865b9bb80b540f6d252312fa6002300b2f1c9ee | [
"Apache-2.0"
] | 4,854 | 2017-08-10T20:19:25.000Z | 2022-03-31T19:04:23.000Z | container-core/src/main/java/com/yahoo/container/jdisc/state/FileWrapper.java | sagiyaho/vespa | 5865b9bb80b540f6d252312fa6002300b2f1c9ee | [
"Apache-2.0"
] | 541 | 2017-08-10T18:51:18.000Z | 2022-03-11T03:18:56.000Z | 26.482759 | 112 | 0.71875 | 7,795 | // Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.jdisc.state;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.stream.Stream;
/**
* @author olaa
*/
public class FileWrapper {
long getFileAgeInSeconds(Path path) throws IOException {
Instant lastModifiedTime = Files.getLastModifiedTime(path).toInstant();
return Instant.now().getEpochSecond() - lastModifiedTime.getEpochSecond();
}
Stream<Path> walkTree(Path path) throws IOException {
return Files.walk(path);
}
boolean isRegularFile(Path path) {
return Files.isRegularFile(path);
}
}
|
3e127bd9c8e438a7a46e15fe0236c0e135d336cd | 2,048 | java | Java | src/com/dci/intellij/dbn/generator/DatasetJoinBundle.java | consulo/consulo-sql | d85206f43c39999c836ea19cc944672e6f72414e | [
"Apache-2.0"
] | null | null | null | src/com/dci/intellij/dbn/generator/DatasetJoinBundle.java | consulo/consulo-sql | d85206f43c39999c836ea19cc944672e6f72414e | [
"Apache-2.0"
] | null | null | null | src/com/dci/intellij/dbn/generator/DatasetJoinBundle.java | consulo/consulo-sql | d85206f43c39999c836ea19cc944672e6f72414e | [
"Apache-2.0"
] | null | null | null | 30.567164 | 87 | 0.609863 | 7,796 | /*
* Copyright 2012-2014 Dan Cioca
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dci.intellij.dbn.generator;
import com.dci.intellij.dbn.object.DBDataset;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class DatasetJoinBundle {
private List<DatasetJoin> joins = new ArrayList<DatasetJoin>();
public DatasetJoinBundle(Set<DBDataset> datasets, boolean lenient) {
for (DBDataset dataset1 : datasets) {
for (DBDataset dataset2 : datasets) {
if (!dataset1.equals(dataset2)) {
createJoin(dataset1, dataset2, lenient);
}
}
}
}
private void createJoin(DBDataset dataset1, DBDataset dataset2, boolean lenient) {
if (!contains(dataset1, dataset2)) {
DatasetJoin datasetJoin = new DatasetJoin(dataset1, dataset2, lenient);
if (!datasetJoin.isEmpty()) {
joins.add(datasetJoin);
}
}
}
protected boolean contains(DBDataset... datasets) {
for (DatasetJoin datasetJoin : joins) {
if (datasetJoin.contains(datasets)) return true;
}
return false;
}
public List<DatasetJoin> getJoins() {
return joins;
}
public boolean isEmpty() {
for (DatasetJoin join : joins) {
if (!join.isEmpty()) {
return false;
}
}
return true;
}
}
|
3e127cc3014232bf393b2098d01b720a1e34c533 | 1,618 | java | Java | umd/src/main/java/com/wyy/service/KafkaProducer.java | oakdream/cubeai | 9f819c1b2eb65fc2455c1cc0b88dca65c667aa1c | [
"Apache-2.0"
] | 1 | 2019-07-24T07:28:00.000Z | 2019-07-24T07:28:00.000Z | umu/src/main/java/com/wyy/service/KafkaProducer.java | oakdream/cubeai | 9f819c1b2eb65fc2455c1cc0b88dca65c667aa1c | [
"Apache-2.0"
] | null | null | null | umu/src/main/java/com/wyy/service/KafkaProducer.java | oakdream/cubeai | 9f819c1b2eb65fc2455c1cc0b88dca65c667aa1c | [
"Apache-2.0"
] | null | null | null | 35.955556 | 97 | 0.697157 | 7,797 | package com.wyy.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
@Service
public class KafkaProducer {
private static final Logger log = LoggerFactory.getLogger(KafkaProducer.class);
private KafkaTemplate<String, String> kafkaTemplate;
public KafkaProducer(KafkaTemplate<String, String> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
public void send(String topic, String message) {
// the KafkaTemplate provides asynchronous send methods returning a Future
ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send(topic, message);
// register a callback with the listener to receive the result of the send asynchronously
future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
@Override
public void onSuccess(SendResult<String, String> result) {
log.info("Kafka sent message='{}' with offset={}", message,
result.getRecordMetadata().offset());
}
@Override
public void onFailure(Throwable ex) {
log.error("Kafka unable to send message='{}'", message, ex);
}
});
// or, to block the sending thread to await the result, invoke the future's get() method
}
}
|
3e127cc63304027fdef3fed30b9448a597b4ba48 | 874 | java | Java | com.eixox.jetfuel/src/main/java/com/eixox/restrictions/RequiredRestriction.java | EixoX/Jetfuel-Java | 2b2b1730ff5bf4c5f5d0a6374c126bff9c5d8fbc | [
"Apache-2.0"
] | null | null | null | com.eixox.jetfuel/src/main/java/com/eixox/restrictions/RequiredRestriction.java | EixoX/Jetfuel-Java | 2b2b1730ff5bf4c5f5d0a6374c126bff9c5d8fbc | [
"Apache-2.0"
] | null | null | null | com.eixox.jetfuel/src/main/java/com/eixox/restrictions/RequiredRestriction.java | EixoX/Jetfuel-Java | 2b2b1730ff5bf4c5f5d0a6374c126bff9c5d8fbc | [
"Apache-2.0"
] | 3 | 2019-05-01T02:22:28.000Z | 2021-08-23T16:59:42.000Z | 22.410256 | 68 | 0.721968 | 7,798 | package com.eixox.restrictions;
import java.util.Date;
public class RequiredRestriction implements Restriction {
public RequiredRestriction() {
}
public RequiredRestriction(Required required) {
// just complying to a constructor pattern.
}
public final boolean validate(Object input) {
if (input == null)
return false;
else if (input instanceof String)
return !"".equals(input);
else if (input instanceof Number)
return ((Number) input).intValue() != 0;
else if (input instanceof Date)
return ((Date) input).getTime() > 0;
else
return true;
}
public String getRestrictionMessageFor(Object input) {
return validate(input) ? null : "Obrigatório";
}
public void assertValid(Object input) throws RestrictionException {
String msg = getRestrictionMessageFor(input);
if (msg != null)
throw new RestrictionException(msg);
}
}
|
3e127e6ef55ac706f69567bfee9e1052475f6797 | 4,904 | java | Java | demo/src/main/java/com/mintegral/sdk/demo/FeedsImageActivity.java | MTGSDK/MintegralAndroidSDK_Test | 142763e9a5b761ffe1da0b3a4c75633678ecbb88 | [
"Apache-2.0"
] | null | null | null | demo/src/main/java/com/mintegral/sdk/demo/FeedsImageActivity.java | MTGSDK/MintegralAndroidSDK_Test | 142763e9a5b761ffe1da0b3a4c75633678ecbb88 | [
"Apache-2.0"
] | 16 | 2020-09-23T11:34:04.000Z | 2022-01-12T05:30:05.000Z | demo/src/main/java/com/mintegral/sdk/demo/FeedsImageActivity.java | Hanlion/MintegralAndroidSDK_Test | fa855ef5423866fabd18a1bda2523db674fa34f5 | [
"Apache-2.0"
] | 2 | 2020-09-23T11:20:50.000Z | 2021-02-09T17:11:51.000Z | 29.365269 | 92 | 0.759584 | 7,799 | package com.mintegral.sdk.demo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.mintegral.msdk.MIntegralConstans;
import com.mintegral.msdk.MIntegralSDK;
import com.mintegral.msdk.out.Campaign;
import com.mintegral.msdk.out.Frame;
import com.mintegral.msdk.out.MIntegralSDKFactory;
import com.mintegral.msdk.out.MtgNativeHandler;
import com.mintegral.msdk.out.NativeListener.NativeAdListener;
import com.mintegral.msdk.out.NativeListener.Template;
import com.mintegral.sdk.demo.util.ImageLoadTask;
import com.mintegral.sdk.demo.view.StarLevelLayoutView;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
/**
* native displayfeedsImage
*
*/
public class FeedsImageActivity extends BaseActivity {
private static final String TAG = FeedsImageActivity.class.getName();
private static final String UNIT_ID = "146868";
private LinearLayout mLl_Root;
private ImageView mIvIcon;
private ImageView mIvImage;
private TextView mTvAppName;
private TextView mTvAppDesc;
private TextView mTvCta;
private StarLevelLayoutView mStarLayout;
private MtgNativeHandler nativeHandle;
private ProgressBar mProgressBar;
@Override
public int getResLayoutId() {
return R.layout.mintegral_native_feeds_image;
}
@Override
public void initView() {
mIvIcon = (ImageView) findViewById(R.id.mintegral_feeds_icon);
mIvImage = (ImageView) findViewById(R.id.mintegral_feeds_image);
mTvAppName = (TextView) findViewById(R.id.mintegral_feeds_app_name);
mTvCta = (TextView) findViewById(R.id.mintegral_feeds_tv_cta);
mTvAppDesc = (TextView) findViewById(R.id.mintegral_feeds_app_desc);
mLl_Root = (LinearLayout) findViewById(R.id.mintegral_feeds_ll_root);
mStarLayout = (StarLevelLayoutView) findViewById(R.id.mintegral_feeds_star);
mProgressBar = (ProgressBar) findViewById(R.id.mintegral_feeds_progress);
}
@Override
public void initData() {
showLoadding();
loadNative();
}
@Override
public void setListener() {
}
private void showLoadding() {
mProgressBar.setVisibility(View.VISIBLE);
mLl_Root.setVisibility(View.GONE);
}
private void hideLoadding() {
mProgressBar.setVisibility(View.GONE);
mLl_Root.setVisibility(View.VISIBLE);
}
public void preloadNative() {
MIntegralSDK sdk = MIntegralSDKFactory.getMIntegralSDK();
Map<String, Object> preloadMap = new HashMap<String, Object>();
preloadMap.put(MIntegralConstans.PROPERTIES_LAYOUT_TYPE, MIntegralConstans.LAYOUT_NATIVE);
preloadMap.put(MIntegralConstans.PROPERTIES_UNIT_ID, UNIT_ID);
preloadMap.put(MIntegralConstans.PLACEMENT_ID, "138780");
List<Template> list = new ArrayList<Template>();
list.add(new Template(MIntegralConstans.TEMPLATE_BIG_IMG, 1));
preloadMap.put(MIntegralConstans.NATIVE_INFO, MtgNativeHandler.getTemplateString(list));
sdk.preload(preloadMap);
}
public void loadNative() {
//Map<String, Object> properties = MtgNativeHandler.getNativeProperties(UNIT_ID);
Map<String, Object> properties = MtgNativeHandler.getNativeProperties("138780", UNIT_ID);
nativeHandle = new MtgNativeHandler(properties, this);
nativeHandle.addTemplate(new Template(MIntegralConstans.TEMPLATE_BIG_IMG, 1));
nativeHandle.setAdListener(new NativeAdListener() {
@Override
public void onAdLoaded(List<Campaign> campaigns, int template) {
hideLoadding();
fillFeedsImageLayout(campaigns);
preloadNative();
}
@Override
public void onAdLoadError(String message) {
Log.e(TAG, "onAdLoadError:" + message);
}
@Override
public void onAdFramesLoaded(List<Frame> list) {
}
@Override
public void onLoggingImpression(int adsourceType) {
}
@Override
public void onAdClick(Campaign campaign) {
Log.e(TAG, "onAdClick");
}
});
nativeHandle.load();
}
protected void fillFeedsImageLayout(List<Campaign> campaigns) {
if (campaigns != null && campaigns.size() > 0) {
Campaign campaign = campaigns.get(0);
if (!TextUtils.isEmpty(campaign.getIconUrl())) {
new ImageLoadTask(campaign.getIconUrl()) {
@Override
public void onRecived(Drawable result) {
mIvIcon.setImageDrawable(result);
}
}.execute();
}
if (!TextUtils.isEmpty(campaign.getImageUrl())) {
new ImageLoadTask(campaign.getImageUrl()) {
@Override
public void onRecived(Drawable result) {
mIvImage.setImageDrawable(result);
}
}.execute();
}
mTvAppName.setText(campaign.getAppName() + "");
mTvAppDesc.setText(campaign.getAppDesc() + "");
mTvCta.setText(campaign.getAdCall());
int rating = (int) campaign.getRating();
mStarLayout.setRating(rating);
nativeHandle.registerView(mLl_Root, campaign);
}
}
}
|
3e12809a7523a1868122674e5b5be629ea8eff49 | 644 | java | Java | src/main/java/net/sf/esfinge/metadata/annotation/container/ProcessorPerMethod.java | magaum/metadata | 7d5e4deb205fe22c0e31459d514c786c668ac56d | [
"MIT"
] | 10 | 2015-06-08T22:06:11.000Z | 2022-03-26T21:36:10.000Z | src/main/java/net/sf/esfinge/metadata/annotation/container/ProcessorPerMethod.java | magaum/metadata | 7d5e4deb205fe22c0e31459d514c786c668ac56d | [
"MIT"
] | 34 | 2016-07-14T14:15:45.000Z | 2019-08-02T18:48:40.000Z | src/main/java/net/sf/esfinge/metadata/annotation/container/ProcessorPerMethod.java | magaum/metadata | 7d5e4deb205fe22c0e31459d514c786c668ac56d | [
"MIT"
] | 10 | 2015-09-23T19:02:17.000Z | 2021-05-08T10:26:49.000Z | 33.894737 | 83 | 0.833851 | 7,800 | package net.sf.esfinge.metadata.annotation.container;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import net.sf.esfinge.metadata.annotation.finder.SearchOnEnclosingElements;
import net.sf.esfinge.metadata.container.reading.MethodProcessorsReadingProcessor;
@Retention(RetentionPolicy.RUNTIME)
@AnnotationReadingConfig(MethodProcessorsReadingProcessor.class)
@SearchOnEnclosingElements
public @interface ProcessorPerMethod {
Class<? extends Annotation> configAnnotation();
ProcessorType type() default ProcessorType.READER_ADDS_METADATA;
}
|
3e1280ba8d7115d850313584467ea3daa92d01ae | 698 | java | Java | references/bcb_chosen_clones/selected#666157#752#770.java | cragkhit/elasticsearch | 05567b30c5bde08badcac1bf421454e5d995eb91 | [
"Apache-2.0"
] | 23 | 2018-10-03T15:02:53.000Z | 2021-09-16T11:07:36.000Z | references/bcb_chosen_clones/selected#666157#752#770.java | cragkhit/elasticsearch | 05567b30c5bde08badcac1bf421454e5d995eb91 | [
"Apache-2.0"
] | 18 | 2019-02-10T04:52:54.000Z | 2022-01-25T02:14:40.000Z | references/bcb_chosen_clones/selected#666157#752#770.java | cragkhit/Siamese | 05567b30c5bde08badcac1bf421454e5d995eb91 | [
"Apache-2.0"
] | 19 | 2018-11-16T13:39:05.000Z | 2021-09-05T23:59:30.000Z | 34.9 | 72 | 0.514327 | 7,801 | @SuppressWarnings("unchecked")
private <T> T[] newArray(T[] array) {
int size = size();
if (size > array.length) {
Class<?> clazz = array.getClass().getComponentType();
array = (T[]) Array.newInstance(clazz, size);
}
if (front < rear) {
System.arraycopy(elements, front, array, 0, size);
} else if (size != 0) {
int length = elements.length;
System.arraycopy(elements, front, array, 0, length - front);
System.arraycopy(elements, 0, array, length - front, rear);
}
if (size < array.length) {
array[size] = null;
}
return array;
}
|
3e128124243636b2458e71cbb75c690d9bc19313 | 305 | java | Java | guns-core/src/main/java/com/stylefeng/guns/core/mutidatasource/annotion/DataSource.java | saltedsaury/ida_boss | 83a35e6261d19cc9f90317e19f28702f8d63c2e3 | [
"Apache-2.0"
] | null | null | null | guns-core/src/main/java/com/stylefeng/guns/core/mutidatasource/annotion/DataSource.java | saltedsaury/ida_boss | 83a35e6261d19cc9f90317e19f28702f8d63c2e3 | [
"Apache-2.0"
] | null | null | null | guns-core/src/main/java/com/stylefeng/guns/core/mutidatasource/annotion/DataSource.java | saltedsaury/ida_boss | 83a35e6261d19cc9f90317e19f28702f8d63c2e3 | [
"Apache-2.0"
] | null | null | null | 16.052632 | 56 | 0.718033 | 7,802 | package com.stylefeng.guns.core.mutidatasource.annotion;
import java.lang.annotation.*;
/**
*
* 多数据源标识
*
* @author fengshuonan
* @date 2017年3月5日 上午9:44:24
*/
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE })
public @interface DataSource {
String name() default "";
}
|
3e12822147f080338a60080cb575cb1391b41cfc | 3,210 | java | Java | common/src/main/java/us/myles/ViaVersion/api/minecraft/chunks/NibbleArray.java | 2001zhaozhao/ViaVersion | 68af5c9eb44332ab5c28bbc082758e0b8a889a3a | [
"MIT"
] | 3 | 2020-02-08T14:26:52.000Z | 2020-08-07T17:11:34.000Z | common/src/main/java/us/myles/ViaVersion/api/minecraft/chunks/NibbleArray.java | 2001zhaozhao/ViaVersion | 68af5c9eb44332ab5c28bbc082758e0b8a889a3a | [
"MIT"
] | 1 | 2020-07-09T19:34:28.000Z | 2020-07-09T19:34:30.000Z | common/src/main/java/us/myles/ViaVersion/api/minecraft/chunks/NibbleArray.java | 2001zhaozhao/ViaVersion | 68af5c9eb44332ab5c28bbc082758e0b8a889a3a | [
"MIT"
] | 2 | 2019-02-06T21:50:06.000Z | 2020-07-21T07:28:18.000Z | 24.883721 | 115 | 0.525857 | 7,803 | package us.myles.ViaVersion.api.minecraft.chunks;
import java.util.Arrays;
public class NibbleArray {
private final byte[] handle;
public NibbleArray(int length) {
if (length == 0 || length % 2 != 0) {
throw new IllegalArgumentException("Length of nibble array must be a positive number dividable by 2!");
}
this.handle = new byte[length / 2];
}
public NibbleArray(byte[] handle) {
if (handle.length == 0 || handle.length % 2 != 0) {
throw new IllegalArgumentException("Length of nibble array must be a positive number dividable by 2!");
}
this.handle = handle;
}
/**
* Get the value at a desired X, Y, Z
*
* @param x Block X
* @param y Block Y
* @param z Block Z
* @return The value at the given XYZ
*/
public byte get(int x, int y, int z) {
return get(ChunkSection.index(x, y, z));
}
/**
* Get the value at an index
*
* @param index The index to lookup
* @return The value at that index.
*/
public byte get(int index) {
byte value = handle[index / 2];
if (index % 2 == 0) {
return (byte) (value & 0xF);
} else {
return (byte) ((value >> 4) & 0xF);
}
}
/**
* Set the value based on an x, y, z
*
* @param x Block X
* @param y Block Y
* @param z Block Z
* @param value Desired Value
*/
public void set(int x, int y, int z, int value) {
set(ChunkSection.index(x, y, z), value);
}
/**
* Set a value at an index
*
* @param index The index to set the value at.
* @param value The desired value
*/
public void set(int index, int value) {
if (index % 2 == 0) {
index /= 2;
handle[index] = (byte) ((handle[index] & 0xF0) | (value & 0xF));
} else {
index /= 2;
handle[index] = (byte) ((handle[index] & 0xF) | ((value & 0xF) << 4));
}
}
/**
* The size of this nibble
*
* @return The size as an int of the nibble
*/
public int size() {
return handle.length * 2;
}
/**
* Get the actual number of bytes
*
* @return The number of bytes based on the handle.
*/
public int actualSize() {
return handle.length;
}
/**
* Fill the array with a value
*
* @param value Value to fill with
*/
public void fill(byte value) {
value &= 0xF; // Max nibble size (= 16)
Arrays.fill(handle, (byte) ((value << 4) | value));
}
/**
* Get the byte array behind this nibble
*
* @return The byte array
*/
public byte[] getHandle() {
return handle;
}
/**
* Copy a byte array into this nibble
*
* @param handle The byte array to copy in.
*/
public void setHandle(byte[] handle) {
if (handle.length != this.handle.length) {
throw new IllegalArgumentException("Length of handle must equal to size of nibble array!");
}
System.arraycopy(handle, 0, this.handle, 0, handle.length);
}
}
|
3e128533676196a3553c332de82e6e650de7d081 | 328 | java | Java | pkix/src/main/java/com/distrimind/bouncycastle/cert/CertRuntimeException.java | JasonMahdjoub/BouncyCastle | f4df9513105c2b3f2d65052989cb0ffb2a81d705 | [
"MIT"
] | null | null | null | pkix/src/main/java/com/distrimind/bouncycastle/cert/CertRuntimeException.java | JasonMahdjoub/BouncyCastle | f4df9513105c2b3f2d65052989cb0ffb2a81d705 | [
"MIT"
] | null | null | null | pkix/src/main/java/com/distrimind/bouncycastle/cert/CertRuntimeException.java | JasonMahdjoub/BouncyCastle | f4df9513105c2b3f2d65052989cb0ffb2a81d705 | [
"MIT"
] | 1 | 2020-07-26T09:52:56.000Z | 2020-07-26T09:52:56.000Z | 17.263158 | 60 | 0.658537 | 7,804 | package com.distrimind.bouncycastle.cert;
public class CertRuntimeException
extends RuntimeException
{
private Throwable cause;
public CertRuntimeException(String msg, Throwable cause)
{
super(msg);
this.cause = cause;
}
public Throwable getCause()
{
return cause;
}
} |
3e128551424d65420cf86590da84627167e491c5 | 8,518 | java | Java | src/com/powersurgepub/pspub/Reports.java | hbowie/pspub | 55b19cd18a1f944d3f3b1ca5d62d155185af0627 | [
"Apache-2.0"
] | null | null | null | src/com/powersurgepub/pspub/Reports.java | hbowie/pspub | 55b19cd18a1f944d3f3b1ca5d62d155185af0627 | [
"Apache-2.0"
] | null | null | null | src/com/powersurgepub/pspub/Reports.java | hbowie/pspub | 55b19cd18a1f944d3f3b1ca5d62d155185af0627 | [
"Apache-2.0"
] | null | null | null | 37.034783 | 103 | 0.638295 | 7,805 | /*
* Copyright 2016 - 2016 Herb Bowie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.powersurgepub.pspub;
import com.powersurgepub.psdatalib.textmerge.*;
import com.powersurgepub.pstextmerge.*;
import com.powersurgepub.psutils.*;
import com.powersurgepub.psdatalib.script.*;
import com.powersurgepub.psdatalib.txbio.*;
import com.powersurgepub.psdatalib.txbmodel.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
/**
A collection of reports available within an application. Each report requires
a matching PSTextMerge script file that can be run in order to generate the
report. These script files will retrieved from a folder named 'reports'. If
an application data folder already contains such a folder, then that folder
will be used. If not, then the reports will be loaded from the application's
resources folder. The first time that any report is executed for a particular
data collection, the standard reports folder will be copied to the application
data folder. After this initial copy, the contents of this folder may be
customized as needed.
@author Herb Bowie
*/
public class Reports {
public static final String REPORTS_FOLDER = "reports";
public static final String WEBPREFS_FILE = "webprefs.css";
public static final String CSSHREF_FILE = "csshref.html";
private TextMergeHarness textMerge = null;
private ScriptExecutor scriptExec = null;
private JMenu reportsMenu = null;
private File appReportsFolder = null;
private File dataReportsFolder = null;
private boolean dataReportsFolderPopulated = false;
private SortedMap<String, Report> reports = new TreeMap<String, Report>();
private WebPrefsProvider webPrefs = null;
private MarkupWriter markupWriter;
/**
Construct a new report object.
@param reportsMenu The report menu under which the list of available
reports will be available.
*/
public Reports(JMenu reportsMenu) {
this.reportsMenu = reportsMenu;
textMerge = TextMergeHarness.getShared();
textMerge.initTextMergeModules();
}
/**
Set the Executor that is to receive any callbacks from the script.
@param scriptExec The Executor that is to receive any
callbacks from the script.
*/
public void setScriptExecutor(ScriptExecutor scriptExec) {
this.scriptExec = scriptExec;
textMerge.setExecutor(scriptExec);
}
public void setWebPrefs(WebPrefsProvider webPrefs) {
this.webPrefs = webPrefs;
}
/**
Provide a new folder full of application data, which may contain a
folder named 'reports'. The reports menu will be re-populated with
reports available for this data folder.
@param dataFolder The application data folder.
*/
public void setDataFolder(File dataFolder) {
dataReportsFolder = new File(dataFolder, REPORTS_FOLDER);
appReportsFolder = new File(Home.getShared().getAppFolder(), REPORTS_FOLDER);
reports = new TreeMap<String, Report>();
reportsMenu.removeAll();
dataReportsFolderPopulated = true;
if (dataReportsFolder.exists()) {
loadReports (dataReportsFolder);
Logger.getShared().recordEvent(LogEvent.NORMAL,
"Loading reports from " + dataReportsFolder.toString(), false);
}
if (reports.isEmpty()) {
Logger.getShared().recordEvent(LogEvent.NORMAL,
"Loading reports from " + appReportsFolder.toString(), false);
loadReports (appReportsFolder);
dataReportsFolderPopulated = false;
}
}
/**
Get the location of the reports folder into which reports should be written.
@return The location of the reports folder into which
reports should be written.
*/
public File getReportsFolder() {
return dataReportsFolder;
}
/**
Load the reports from the passed folder.
@param folder The folder to be used.
*/
private void loadReports (File folder) {
if (folder != null && folder.exists() && folder.canRead()) {
String[] fileNames = folder.list();
for (String fileName : fileNames){
File candidate = new File (folder, fileName);
if (Report.isValidFile(candidate)) {
Report report = new Report(candidate);
reports.put(report.getKey(), report);
JMenuItem menuItem = new JMenuItem(report.getName());
menuItem.setActionCommand (report.getKey());
menuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
if (! dataReportsFolderPopulated) {
dataReportsFolderPopulated = FileUtils.copyFolder(appReportsFolder, dataReportsFolder);
}
Report selectedReport = reports.get(evt.getActionCommand());
runReport(selectedReport);
} // end actionPerformed method
}); // end add of action listener
reportsMenu.add(menuItem);
} // end if the right kind of file
} // end for each file in the folder
} // end if good folder
} // end loadReports method
/**
Run the report that has been requested and attempt to open the output
in a web browsers window.
@param report The report to be run.
*/
private void runReport(Report report) {
if (report != null) {
File reportScript
= new File(dataReportsFolder, report.getFileName());
if (reportScript != null
&& reportScript.exists()
&& reportScript.canRead()) {
if (scriptExec != null) {
textMerge.setExecutor(scriptExec);
}
if (webPrefs != null) {
File cssFile = new File(dataReportsFolder, WEBPREFS_FILE);
markupWriter = new MarkupWriter (cssFile, MarkupWriter.HTML_FRAGMENT_FORMAT);
markupWriter.openForOutput();
markupWriter.writeLine (" body, p, h1, li {");
markupWriter.writeLine (" font-family: \"" + webPrefs.getFontFamily()
+ "\"" + ", Verdana, Geneva, sans-serif;");
markupWriter.writeLine (" font-size: " + webPrefs.getFontSize() + ";");
markupWriter.writeLine (" }");
markupWriter.close();
String cssHref = webPrefs.getCSShref();
if (cssHref != null && cssHref.length() > 0) {
File cssHrefFile = new File(dataReportsFolder, CSSHREF_FILE);
markupWriter = new MarkupWriter (cssHrefFile, MarkupWriter.HTML_FRAGMENT_FORMAT);
markupWriter.openForOutput();
StringBuffer textOut = new StringBuffer(" ");
textOut.append ("<" + TextType.LINK);
textOut.append (" "
+ TextType.REL + "=\""
+ TextType.STYLESHEET + "\"");
textOut.append (" "
+ TextType.TYPE + "=\""
+ TextType.TEXT_CSS + "\"");
textOut.append (" "
+ TextType.HREF + "=\""
+ cssHref + "\"");
textOut.append (" />");
markupWriter.writeLine (textOut.toString());
markupWriter.close();
}
}
textMerge.resetOutputFileName();
textMerge.playScript(reportScript);
String reportFileName = textMerge.getOutputFileName().trim();
File reportFile = null;
if (reportFileName == null || reportFileName.length() == 0) {
reportFile = new File(dataReportsFolder, report.getHTMLName());
} else {
reportFile = new File(reportFileName);
}
if (reportFile != null
&& reportFile.exists()
&& reportFile.canRead()) {
Home.getShared().openURL(reportFile);
}
} // end if we have a report script to execute
} // end if we have a selected report
}
}
|
3e128596c3d69d0a15ca2b02dfcc3763fde69460 | 1,226 | java | Java | redis/redis-checker/src/main/java/com/ctrip/xpipe/redis/checker/alert/manager/SenderManager.java | coral-cloud/x-pipe | d4ad1d9039a83f55439b69ae7d6954171002fa39 | [
"Apache-2.0"
] | 1,652 | 2016-04-18T10:34:30.000Z | 2022-03-30T06:15:35.000Z | redis/redis-checker/src/main/java/com/ctrip/xpipe/redis/checker/alert/manager/SenderManager.java | coral-cloud/x-pipe | d4ad1d9039a83f55439b69ae7d6954171002fa39 | [
"Apache-2.0"
] | 342 | 2016-07-27T10:38:01.000Z | 2022-03-31T11:11:46.000Z | redis/redis-checker/src/main/java/com/ctrip/xpipe/redis/checker/alert/manager/SenderManager.java | coral-cloud/x-pipe | d4ad1d9039a83f55439b69ae7d6954171002fa39 | [
"Apache-2.0"
] | 492 | 2016-04-25T05:14:10.000Z | 2022-03-16T01:40:38.000Z | 27.244444 | 116 | 0.679445 | 7,806 | package com.ctrip.xpipe.redis.checker.alert.manager;
import com.ctrip.xpipe.redis.checker.alert.AlertChannel;
import com.ctrip.xpipe.redis.checker.alert.AlertMessageEntity;
import com.ctrip.xpipe.redis.checker.alert.sender.Sender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* @author chen.zhu
* <p>
* Oct 18, 2017
*/
@Component
public class SenderManager {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private Map<String, Sender> senders;
public Sender querySender(String id) {
return senders.get(id);
}
public boolean sendAlert(AlertChannel channel, AlertMessageEntity message) {
String channelId = channel.getId();
Sender sender = senders.get(channelId);
try {
boolean result = sender.send(message);
logger.debug("[sendAlert] Channel: {}, message: {}, send out: {}", channel, message.getTitle(), result);
return result;
} catch (Exception e) {
logger.error("[sendAlert]", e);
return false;
}
}
}
|
3e1287156b38e50bf69c70af8259a4fd8d7984f5 | 4,604 | java | Java | impl/src/main/java/org/ehcache/internal/cachingtier/ClockEvictingHeapCachingTier.java | timeck/ehcache3 | efc5001b261712c900d90c10b49289ffb9321602 | [
"Apache-2.0"
] | null | null | null | impl/src/main/java/org/ehcache/internal/cachingtier/ClockEvictingHeapCachingTier.java | timeck/ehcache3 | efc5001b261712c900d90c10b49289ffb9321602 | [
"Apache-2.0"
] | null | null | null | impl/src/main/java/org/ehcache/internal/cachingtier/ClockEvictingHeapCachingTier.java | timeck/ehcache3 | efc5001b261712c900d90c10b49289ffb9321602 | [
"Apache-2.0"
] | null | null | null | 26.923977 | 116 | 0.689618 | 7,807 | /*
* Copyright Terracotta, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ehcache.internal.cachingtier;
import org.ehcache.internal.concurrent.ConcurrentHashMap;
import org.ehcache.spi.cache.tiering.CachingTier;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
/**
* @author Alex Snaps
*/
public class ClockEvictingHeapCachingTier<K> implements CachingTier<K> {
private static final int MAX_EVICTION = 5;
private final ConcurrentHashMap<K, ClockEvictableEntry> map = new ConcurrentHashMap<K, ClockEvictableEntry>();
private volatile AtomicReference<Iterator<Map.Entry<K, ClockEvictableEntry>>> iterator
= new AtomicReference<Iterator<Map.Entry<K,ClockEvictableEntry>>>(map.entrySet().iterator());
private Map.Entry<K, ClockEvictableEntry> newIterator(final Iterator<Map.Entry<K, ClockEvictableEntry>> old) {
final Iterator<Map.Entry<K, ClockEvictableEntry>> newIt = map.entrySet().iterator();
if(!this.iterator.compareAndSet(old, newIt))
return this.iterator.get().next();
else {
return newIt.next();
}
}
private final long maxOnHeapEntries;
public ClockEvictingHeapCachingTier(final long maxOnHeapEntryCount) {
maxOnHeapEntries = maxOnHeapEntryCount;
}
@Override
public Object get(final K key) {
final ClockEvictableEntry entry = map.get(key);
return entry == null ? null : entry.getValue();
}
@Override
public Object putIfAbsent(final K key, final Object value) {
final ClockEvictableEntry previous = map.putIfAbsent(key, new ClockEvictableEntry(value));
if (previous == null) {
evictIfNecessary();
return null;
} else {
return previous.getValue();
}
}
private void evictIfNecessary() {
int count = 0;
while (count < MAX_EVICTION && map.size() > maxOnHeapEntries) {
Map.Entry<K, ClockEvictableEntry> next;
next = next();
final ClockEvictableEntry value = next.getValue();
if (!value.wasAccessedAndFlip() && map.remove(next.getKey(), value)) {
count++;
}
}
}
private Map.Entry<K, ClockEvictableEntry> next() {
final Iterator<Map.Entry<K, ClockEvictableEntry>> iterator = this.iterator.get();
Map.Entry<K, ClockEvictableEntry> next;
if(!iterator.hasNext()) {
next = newIterator(iterator);
} else {
next = iterator.next();
}
return next;
}
@Override
public void remove(final K key) {
map.remove(key);
}
@Override
public void remove(final K key, final Object value) {
map.remove(key, new ClockEvictableEntry(value));
}
@Override
public boolean replace(final K key, final Object oldValue, final Object newValue) {
return map.replace(key, new ClockEvictableEntry(oldValue), new ClockEvictableEntry(newValue));
}
@Override
public long getMaxCacheSize() {
return maxOnHeapEntries;
}
public long size() {
return map.size();
}
}
final class ClockEvictableEntry {
private final Object value;
private volatile boolean accessed;
ClockEvictableEntry(final Object value) {
this(value, true);
}
ClockEvictableEntry(final Object value, final boolean accessed) {
if (value == null) {
throw new NullPointerException(ClockEvictingHeapCachingTier.class.getName() + " does not accept null values");
}
this.value = value;
this.accessed = accessed;
}
public Object getValue() {
accessed();
return value;
}
public void accessed() {
this.accessed = true;
}
public boolean wasAccessedAndFlip() {
final boolean b = accessed;
accessed = false;
return b;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null) {
return false;
}
if(getClass() == o.getClass()) {
final ClockEvictableEntry that = (ClockEvictableEntry)o;
return value.equals(that.value);
} else {
return value.getClass() == o.getClass() && value.equals(o);
}
}
@Override
public int hashCode() {
return value.hashCode();
}
}
|
3e1287289584889e4673515172db9b88c960fd58 | 833 | java | Java | arukas/app/src/main/java/com/xbw/arukas/View/MyListView.java | xbw12138/ArukasDockerPro | f6e94257353e37f26527e2f8691a11fbfc738c78 | [
"MIT"
] | 1 | 2019-07-25T04:39:56.000Z | 2019-07-25T04:39:56.000Z | arukas/app/src/main/java/com/xbw/arukas/View/MyListView.java | xbw12138/ArukasDockerPro | f6e94257353e37f26527e2f8691a11fbfc738c78 | [
"MIT"
] | null | null | null | arukas/app/src/main/java/com/xbw/arukas/View/MyListView.java | xbw12138/ArukasDockerPro | f6e94257353e37f26527e2f8691a11fbfc738c78 | [
"MIT"
] | 1 | 2021-01-18T17:14:29.000Z | 2021-01-18T17:14:29.000Z | 26.03125 | 98 | 0.719088 | 7,808 | package com.xbw.arukas.View;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ListView;
/**
* Created by xubowen on 2017/3/22.
*/
public class MyListView extends ListView {
public MyListView(Context context) {
super(context);
}
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
|
3e12872b4aa1efe2d6582725c73588ab30827fbc | 17,488 | java | Java | RemoteInputDemo/entry/src/main/java/com/huawei/codelab/slice/MainAbilitySlice.java | wf0304-gme/harmonyos-codelabs | bee1ea9697d8c29b947072fe8b71434007885fc5 | [
"Apache-2.0"
] | 181 | 2021-03-04T09:53:24.000Z | 2022-03-30T10:59:10.000Z | RemoteInputDemo/entry/src/main/java/com/huawei/codelab/slice/MainAbilitySlice.java | wf0304-gme/harmonyos-codelabs | bee1ea9697d8c29b947072fe8b71434007885fc5 | [
"Apache-2.0"
] | 12 | 2021-04-18T04:21:23.000Z | 2021-09-26T03:26:31.000Z | RemoteInputDemo/entry/src/main/java/com/huawei/codelab/slice/MainAbilitySlice.java | wf0304-gme/harmonyos-codelabs | bee1ea9697d8c29b947072fe8b71434007885fc5 | [
"Apache-2.0"
] | 151 | 2021-03-05T09:03:51.000Z | 2022-03-30T11:12:16.000Z | 38.435165 | 132 | 0.665599 | 7,809 | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License,Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.huawei.codelab.slice;
import com.huawei.codelab.ResourceTable;
import com.huawei.codelab.callback.MainCallBack;
import com.huawei.codelab.constants.EventConstants;
import com.huawei.codelab.data.ComponentPointData;
import com.huawei.codelab.data.ComponentPointDataMgr;
import com.huawei.codelab.proxy.ConnectManagerIml;
import com.huawei.codelab.utils.AbilityMgr;
import com.huawei.codelab.utils.LogUtils;
import com.huawei.codelab.utils.MovieSearchUtils;
import com.huawei.codelab.utils.PermissionBridge;
import com.huawei.codelab.utils.WindowManagerUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.continuation.DeviceConnectState;
import ohos.aafwk.ability.continuation.ExtraParams;
import ohos.aafwk.ability.continuation.IContinuationDeviceCallback;
import ohos.aafwk.ability.continuation.IContinuationRegisterManager;
import ohos.aafwk.ability.continuation.RequestCallback;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Image;
import ohos.agp.components.ScrollView;
import ohos.agp.components.TableLayout;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.event.commonevent.CommonEventData;
import ohos.event.commonevent.CommonEventManager;
import ohos.event.commonevent.CommonEventSubscribeInfo;
import ohos.event.commonevent.CommonEventSubscriber;
import ohos.event.commonevent.CommonEventSupport;
import ohos.event.commonevent.MatchingSkills;
import ohos.media.image.common.Size;
import ohos.rpc.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* MainAbilitySlice
*
* @since 2021-02-26
*/
public class MainAbilitySlice extends AbilitySlice implements PermissionBridge.OnPermissionStateListener {
private static final String ABILITY_NAME = "com.huawei.codelab.RemoteInputAbility";
private static final String MOVIE_PLAY_ABILITY = "com.huawei.codelab.MoviePlayAbility";
private static final String MAIN_ABILITY = "com.huawei.codelab.MainAbility";
private static final int FOCUS_PADDING = 8;
private static final int SEARCH_PADDING = 3;
private static final int LIST_INIT_SIZE = 16;
private static final String TAG = MainAbilitySlice.class.getName();
private static final Lock MOVE_LOCK = new ReentrantLock();
private MainAbilitySlice.MyCommonEventSubscriber subscriber;
private TextField tvTextInput;
private ScrollView scrollView;
private DirectionalLayout keyBoardLayout;
private TableLayout movieTableLayout;
private Size size;
private final AbilityMgr abilityMgr = new AbilityMgr(this);
// 搜索的到的影片
private final List<ComponentPointData> movieSearchList = new ArrayList<>(LIST_INIT_SIZE);
// 当前焦点所在位置
private ComponentPointData componentPointDataNow;
// 注册流转任务管理服务后返回的Ability token
private int abilityToken;
// 用户在设备列表中选择设备后返回的设备ID
private String selectDeviceId;
// 获取流转任务管理服务管理类
private IContinuationRegisterManager continuationRegisterManager;
// 设置监听FA流转管理服务设备状态变更的回调
private final IContinuationDeviceCallback callback = new IContinuationDeviceCallback() {
@Override
public void onDeviceConnectDone(String deviceId, String s1) {
selectDeviceId = deviceId;
abilityMgr.openRemoteAbility(selectDeviceId, getBundleName(), ABILITY_NAME);
getUITaskDispatcher().asyncDispatch(() -> continuationRegisterManager.updateConnectStatus(abilityToken, selectDeviceId,
DeviceConnectState.IDLE.getState(), null));
}
@Override
public void onDeviceDisconnectDone(String deviceId) {
}
};
// 设置注册FA流转管理服务服务回调
private final RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResult(int result) {
abilityToken = result;
}
};
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
new PermissionBridge().setOnPermissionStateListener(this);
// 全屏设置
WindowManagerUtils.setWindows();
// 初始化布局
initComponent();
// 初始化按钮组件
initKeyBoardComponent(keyBoardLayout);
// 初始化影片图片组件
initMovieTableComponent(movieTableLayout);
// 事件订阅
subscribe();
}
private void registerTransService() {
continuationRegisterManager = getContinuationRegisterManager();
// 增加过滤条件
ExtraParams params = new ExtraParams();
String[] devTypes = new String[]{ExtraParams.DEVICETYPE_SMART_PAD, ExtraParams.DEVICETYPE_SMART_PHONE};
params.setDevType(devTypes);
// 注册FA流转管理服务
continuationRegisterManager.register(getBundleName(), params, callback, requestCallback);
}
private void initMovieTableComponent(TableLayout tableLayout) {
int index = 0;
while (index < tableLayout.getChildCount()) {
DirectionalLayout childLayout = null;
if (tableLayout.getComponentAt(index) instanceof DirectionalLayout) {
childLayout = (DirectionalLayout) tableLayout.getComponentAt(index);
}
ComponentPointData componentPointData = new ComponentPointData();
Component component = null;
int indexMovie = 0;
while (childLayout != null && indexMovie < childLayout.getChildCount()) {
Component comChild = childLayout.getComponentAt(indexMovie);
indexMovie++;
if (comChild instanceof Text) {
componentPointData = ComponentPointDataMgr
.getConstantMovie(((Text) comChild).getText()).orElse(null);
continue;
}
component = findComponentById(comChild.getId());
}
if (componentPointData != null && component != null) {
componentPointData.setComponentId(component.getId());
}
ComponentPointDataMgr.getComponentPointDataMgrs().add(componentPointData);
index++;
}
}
private void initKeyBoardComponent(DirectionalLayout directionalLayout) {
int index = 0;
while (index < directionalLayout.getChildCount()) {
DirectionalLayout childLayout = null;
if (directionalLayout.getComponentAt(index) instanceof DirectionalLayout) {
childLayout = (DirectionalLayout) directionalLayout.getComponentAt(index);
}
int indexButton = 0;
while (childLayout != null && indexButton < childLayout.getChildCount()) {
if (childLayout.getComponentAt(indexButton) instanceof Button) {
Button button = (Button) childLayout.getComponentAt(indexButton);
buttonInit(button);
indexButton++;
}
}
index++;
}
}
private void initComponent() {
if (findComponentById(ResourceTable.Id_scrollview) instanceof ScrollView) {
scrollView = (ScrollView) findComponentById(ResourceTable.Id_scrollview);
}
if (findComponentById(ResourceTable.Id_TV_input) instanceof TextField) {
tvTextInput = (TextField) findComponentById(ResourceTable.Id_TV_input);
// 初始化默认选中效果
ComponentPointData componentPointData = new ComponentPointData();
componentPointData.setComponentId(tvTextInput.getId());
componentPointData.setPointX(0);
componentPointData.setPointY(1);
tvTextInput.requestFocus();
componentPointDataNow = componentPointData;
ComponentPointDataMgr.getComponentPointDataMgrs().add(componentPointDataNow);
// 点击事件触发设备选取弹框
tvTextInput.setClickedListener(component -> showDevicesDialog());
}
if (findComponentById(ResourceTable.Id_keyBoardComponent) instanceof DirectionalLayout) {
keyBoardLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_keyBoardComponent);
}
if (findComponentById(ResourceTable.Id_tableLayout) instanceof TableLayout) {
movieTableLayout = (TableLayout) findComponentById(ResourceTable.Id_tableLayout);
}
if (findComponentById(ResourceTable.Id_image_ten) instanceof Image) {
Image image = (Image) findComponentById(ResourceTable.Id_image_ten);
size = image.getPixelMap().getImageInfo().size;
}
}
private void showDevicesDialog() {
ExtraParams extraParams = new ExtraParams();
extraParams.setDevType(new String[]{ExtraParams.DEVICETYPE_SMART_TV,
ExtraParams.DEVICETYPE_SMART_PHONE});
extraParams.setDescription("远程遥控器");
continuationRegisterManager.showDeviceList(abilityToken, extraParams, result -> LogUtils.info(TAG, "show devices success"));
}
private void buttonInit(Button button) {
if (button.getId() == ResourceTable.Id_del) {
findComponentById(button.getId()).setClickedListener(component -> {
if (tvTextInput.getText().length() > 0) {
tvTextInput.setText(tvTextInput.getText().substring(0, tvTextInput.getText().length() - 1));
}
});
} else if (button.getId() == ResourceTable.Id_clear) {
findComponentById(button.getId()).setClickedListener(component -> tvTextInput.setText(""));
} else {
findComponentById(button.getId()).setClickedListener(component -> tvTextInput.append(button.getText()));
}
}
@Override
public void onActive() {
super.onActive();
}
@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}
@Override
public void onPermissionGranted() {
registerTransService();
}
@Override
public void onPermissionDenied() {
terminate();
}
/**
* MyCommonEventSubscriber
*
* @since 2020-12-03
*/
class MyCommonEventSubscriber extends CommonEventSubscriber {
MyCommonEventSubscriber(CommonEventSubscribeInfo info) {
super(info);
}
@Override
public void onReceiveEvent(CommonEventData commonEventData) {
Intent intent = commonEventData.getIntent();
int requestType = intent.getIntParam("requestType", 0);
String inputString = intent.getStringParam("inputString");
if (requestType == ConnectManagerIml.REQUEST_SEND_DATA) {
tvTextInput.setText(inputString);
} else if (requestType == ConnectManagerIml.REQUEST_SEND_SEARCH) {
// 如果当前选中的是文本框则搜索影片;如果当前选中的是影片则播放影片;X轴坐标为0当前选中文本框;X轴大于1当前选中影片
if (componentPointDataNow.getPointX() == 0) {
// 调用大屏的搜索方法
searchMovies(tvTextInput.getText());
return;
}
// 播放影片
abilityMgr.playMovie(getBundleName(), MOVIE_PLAY_ABILITY);
} else {
// 移动方向
String moveString = intent.getStringParam("move");
MainCallBack.movePoint(MainAbilitySlice.this, moveString);
}
}
}
/**
* goBack
*/
public void goBack() {
clearLastBackg();
scrollView.scrollTo(0, 0);
componentPointDataNow = ComponentPointDataMgr.getMoviePoint(0, 1).orElse(null);
findComponentById(ResourceTable.Id_TV_input).requestFocus();
abilityMgr.returnMainAbility(getBundleName(), MAIN_ABILITY);
}
/**
* move
*
* @param pointX pointX
* @param pointY pointY
*/
public void move(int pointX, int pointY) {
MOVE_LOCK.lock();
try {
// 设置焦点滚动
if (pointX == 0 && componentPointDataNow.getPointX() > 0) {
scrollView.fluentScrollByY(pointY * size.height);
}
if (componentPointDataNow.getPointX() == 0 && pointX == 1) {
scrollView.scrollTo(0, 0);
}
// 设置背景
if (componentPointDataNow.getPointX() + pointX == 0) {
setBackGround(componentPointDataNow.getPointX() + pointX, 1);
} else {
setBackGround(componentPointDataNow.getPointX() + pointX, componentPointDataNow.getPointY() + pointY);
}
} finally {
MOVE_LOCK.unlock();
}
}
private void setBackGround(int pointX, int pointY) {
ComponentPointData componentPointDataNew = ComponentPointDataMgr.getMoviePoint(pointX, pointY).orElse(null);
if (componentPointDataNew == null) {
return;
}
// 清除上次选中的效果
clearLastBackg();
componentPointDataNow = componentPointDataNew;
if (findComponentById(componentPointDataNow.getComponentId()) instanceof Image) {
Image newImage = (Image) findComponentById(componentPointDataNow.getComponentId());
newImage.setPadding(FOCUS_PADDING, FOCUS_PADDING, FOCUS_PADDING, FOCUS_PADDING);
} else {
Component component = findComponentById(componentPointDataNow.getComponentId());
component.requestFocus();
}
}
private void clearLastBackg() {
Component component = null;
if (findComponentById(componentPointDataNow.getComponentId()) instanceof TextField) {
TextField textField = (TextField) findComponentById(componentPointDataNow.getComponentId());
textField.clearFocus();
} else {
component = findComponentById(componentPointDataNow.getComponentId());
component.setPadding(0, 0, 0, 0);
}
// 如果是搜索出来的还是保持搜索到的背景
for (ComponentPointData componentPointData : movieSearchList) {
if (component != null && componentPointData.getComponentId() == component.getId()) {
component.setPadding(SEARCH_PADDING, SEARCH_PADDING, SEARCH_PADDING, SEARCH_PADDING);
}
}
}
private void searchMovies(String text) {
if (text == null || "".equals(text)) {
return;
}
// 清空上次搜索结果及背景效果
clearHistroyBackGround();
for (ComponentPointData componentPointData : ComponentPointDataMgr.getComponentPointDataMgrs()) {
if (MovieSearchUtils.isContainMovie(componentPointData.getMovieName(), text)
|| MovieSearchUtils.isContainMovie(componentPointData.getMovieFirstName(), text)) {
movieSearchList.add(componentPointData);
Component component = findComponentById(componentPointData.getComponentId());
component.setPadding(SEARCH_PADDING, SEARCH_PADDING, SEARCH_PADDING, SEARCH_PADDING);
}
}
if (movieSearchList.size() > 0) {
componentPointDataNow = movieSearchList.get(0);
Component component = findComponentById(componentPointDataNow.getComponentId());
component.setPadding(FOCUS_PADDING, FOCUS_PADDING, FOCUS_PADDING, FOCUS_PADDING);
} else {
Component component = findComponentById(componentPointDataNow.getComponentId());
component.requestFocus();
}
}
private void clearHistroyBackGround() {
// 清空上次搜索的结果
for (ComponentPointData componentPointData : movieSearchList) {
Component component = findComponentById(componentPointData.getComponentId());
component.setPadding(0, 0, 0, 0);
}
movieSearchList.clear();
// 去掉当前焦点背景
clearLastBackg();
}
private void subscribe() {
MatchingSkills matchingSkills = new MatchingSkills();
matchingSkills.addEvent(EventConstants.SCREEN_REMOTE_CONTROLL_EVENT);
matchingSkills.addEvent(CommonEventSupport.COMMON_EVENT_SCREEN_ON);
CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(matchingSkills);
subscriber = new MainAbilitySlice.MyCommonEventSubscriber(subscribeInfo);
try {
CommonEventManager.subscribeCommonEvent(subscriber);
} catch (RemoteException e) {
LogUtils.error("", "subscribeCommonEvent occur exception.");
}
}
private void unSubscribe() {
try {
CommonEventManager.unsubscribeCommonEvent(subscriber);
} catch (RemoteException e) {
LogUtils.error(TAG, "unSubscribe Exception");
}
}
@Override
protected void onStop() {
super.onStop();
unSubscribe();
}
}
|
3e1287d25ec75ea17b21447b96e932c500f7d8d4 | 6,675 | java | Java | SourceCode/ILIT/AndroidApp/IndicKeyboard/app/src/main/java/org/buildmlearn/indickeyboard/settings/SettingsActivity.java | BuildmLearn/Indic-Language-Input-Tool-ILIT | 4473dff89350ce76f390ad094b27b49605530de0 | [
"BSD-3-Clause"
] | null | null | null | SourceCode/ILIT/AndroidApp/IndicKeyboard/app/src/main/java/org/buildmlearn/indickeyboard/settings/SettingsActivity.java | BuildmLearn/Indic-Language-Input-Tool-ILIT | 4473dff89350ce76f390ad094b27b49605530de0 | [
"BSD-3-Clause"
] | null | null | null | SourceCode/ILIT/AndroidApp/IndicKeyboard/app/src/main/java/org/buildmlearn/indickeyboard/settings/SettingsActivity.java | BuildmLearn/Indic-Language-Input-Tool-ILIT | 4473dff89350ce76f390ad094b27b49605530de0 | [
"BSD-3-Clause"
] | null | null | null | 27.582645 | 146 | 0.75206 | 7,810 | package org.buildmlearn.indickeyboard.settings;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.provider.Settings;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;
import com.crashlytics.android.Crashlytics;
import org.buildmlearn.indickeyboard.R;
import java.util.List;
import io.fabric.sdk.android.Fabric;
public class SettingsActivity extends PreferenceActivity {
public static boolean isTablet;
private boolean isDefault = false;
private boolean isEnabled = false;
private EditText previewEditText;
private TextView instructionTextView;
private RadioGroup radioGroup;
private SharedPreferences prefs;
private SharedPreferences.Editor editor;
private boolean inEnglish = false;
private ScrollView layout;
private Button rateus;
private TextView doYouLikeTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
if (getIntent().getExtras() != null) {
inEnglish = getIntent().getExtras().getBoolean("inEnglish", false);
}
layout = (ScrollView) getLayoutInflater().inflate(
R.layout.settings_layout, null);
previewEditText = (EditText) layout
.findViewById(R.id.preview_edit_text);
instructionTextView = (TextView) layout.findViewById(R.id.instruction);
rateus = (Button) layout.findViewById(R.id.rateus);
doYouLikeTextView = (TextView) layout.findViewById(R.id.likeus);
String instruction = getStringResourceByName("settings_instruction");
instructionTextView.setText(instruction);
String doyoulikeustext=getStringResourceByName("do_you_like");
String rateustext=getStringResourceByName("rate_us");
doYouLikeTextView.setText(doyoulikeustext);
rateus.setText(rateustext);
setContentView(layout);
overridePendingTransition(R.anim.activity_open_translate,
R.anim.activity_close_scale);
checkKeyboardStatus();
prefs = UserSettings.getPrefs();
String key = getString(R.string.tablet_layout_setting_key);
Boolean isBig = prefs.getBoolean(key, false);
rateus.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent rate = new Intent(Intent.ACTION_VIEW);
//Will add the link
rate.setData(Uri.parse("https://play.google.com/store/apps/") );
startActivity(rate);
}
});
if (isDefault && isEnabled) {
isTablet = isTablet(this);
previewEditText.requestFocus();
} else {
startMainActivity();
}
// getActionBar().setTitle(getStringResourceByName("title"));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activity_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_language:
if (!inEnglish) {
inEnglish = true;
String languageName = getResources().getString(
R.string.language_name);
int resId = getResources().getIdentifier(
languageName + "_" + "menu_language", "string",
getPackageName());
String title = getResources().getString(resId);
item.setTitle(title);
} else {
inEnglish = false;
String title = getResources().getString(R.string.menu_language);
item.setTitle(title);
}
setCorrectText();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public String getStringResourceByName(String aString) {
String packageName = getPackageName();
String languageName = getResources().getString(R.string.language_name);
int resId = getResources().getIdentifier("hindi" + "_" + aString,
"string", packageName);
if (inEnglish)
resId = 0;
if (resId == 0) {
resId = getResources()
.getIdentifier(aString, "string", packageName);
}
return getString(resId);
}
@Override
public void onBackPressed() {
moveTaskToBack(true);
}
@Override
public void onResume() {
super.onResume();
checkKeyboardStatus();
if (isDefault && isEnabled) {
} else {
startMainActivity();
}
}
public void startMainActivity() {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("inEnglish", inEnglish);
startActivity(intent);
}
public void setCorrectText() {
String smallRadioText = getStringResourceByName("settings_layout_small");
String bigRadioText = getStringResourceByName("settings_layout_big");
String instruction = getStringResourceByName("settings_instruction");
instructionTextView.setText(instruction);
String doyoulikeustext=getStringResourceByName("do_you_like");
String rateustext=getStringResourceByName("rate_us");
doYouLikeTextView.setText(doyoulikeustext);
rateus.setText(rateustext);
}
@Override
public void onPause() {
super.onPause();
overridePendingTransition(R.anim.activity_open_scale,
R.anim.activity_close_translate);
}
public void checkKeyboardStatus() {
InputMethodManager mgr = (InputMethodManager) this
.getSystemService(Context.INPUT_METHOD_SERVICE);
List<InputMethodInfo> lim = mgr.getEnabledInputMethodList();
isEnabled = false;
isDefault = false;
for (InputMethodInfo im : lim) {
if (im.getPackageName().equals(getPackageName())) {
isEnabled = true;
final String currentImeId = Settings.Secure.getString(
getContentResolver(),
Settings.Secure.DEFAULT_INPUT_METHOD);
if (im != null && im.getId().equals(currentImeId)) {
isDefault = true;
}
}
}
}
public static boolean isTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
private void showPreview() {
previewEditText.requestFocus();
previewEditText.setText(null);
InputMethodManager imm = (InputMethodManager) getApplicationContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(previewEditText, 0);
}
}
|
3e12880e83b87640802cb477c54ab12060a59b40 | 3,168 | java | Java | flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/asm/translate/TranslateGraphIds.java | mathiaspet/pyflink | 62227ccc2d82869cb0037a3db647182b0b381723 | [
"BSD-3-Clause"
] | 6 | 2016-02-04T17:36:12.000Z | 2021-05-22T08:09:39.000Z | flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/asm/translate/TranslateGraphIds.java | mathiaspet/pyflink | 62227ccc2d82869cb0037a3db647182b0b381723 | [
"BSD-3-Clause"
] | 1 | 2021-04-08T08:10:16.000Z | 2021-04-08T08:10:16.000Z | flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/asm/translate/TranslateGraphIds.java | mathiaspet/pyflink | 62227ccc2d82869cb0037a3db647182b0b381723 | [
"BSD-3-Clause"
] | 8 | 2015-02-18T15:57:13.000Z | 2021-12-26T01:03:03.000Z | 35.595506 | 122 | 0.754104 | 7,811 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.graph.asm.translate;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.graph.Edge;
import org.apache.flink.graph.Graph;
import org.apache.flink.graph.GraphAlgorithm;
import org.apache.flink.graph.Vertex;
import org.apache.flink.util.Preconditions;
import static org.apache.flink.api.common.ExecutionConfig.PARALLELISM_DEFAULT;
import static org.apache.flink.api.common.ExecutionConfig.PARALLELISM_UNKNOWN;
import static org.apache.flink.graph.asm.translate.Translate.translateEdgeIds;
import static org.apache.flink.graph.asm.translate.Translate.translateVertexIds;
/**
* Translate {@link Vertex} and {@link Edge} IDs of a {@link Graph} using the given {@link MapFunction}
*
* @param <OLD> old graph ID type
* @param <NEW> new graph ID type
* @param <VV> vertex value type
* @param <EV> edge value type
*/
public class TranslateGraphIds<OLD, NEW, VV, EV>
implements GraphAlgorithm<OLD, VV, EV, Graph<NEW, VV, EV>> {
// Required configuration
private MapFunction<OLD,NEW> translator;
// Optional configuration
private int parallelism = PARALLELISM_UNKNOWN;
/**
* Translate {@link Vertex} and {@link Edge} IDs of a {@link Graph} using the given {@link MapFunction}
*
* @param translator implements conversion from {@code OLD} to {@code NEW}
*/
public TranslateGraphIds(MapFunction<OLD, NEW> translator) {
Preconditions.checkNotNull(translator);
this.translator = translator;
}
/**
* Override the operator parallelism.
*
* @param parallelism operator parallelism
* @return this
*/
public TranslateGraphIds<OLD, NEW, VV, EV> setParallelism(int parallelism) {
Preconditions.checkArgument(parallelism > 0 || parallelism == PARALLELISM_DEFAULT || parallelism == PARALLELISM_UNKNOWN,
"The parallelism must be greater than zero.");
this.parallelism = parallelism;
return this;
}
@Override
public Graph<NEW, VV, EV> run(Graph<OLD, VV, EV> input) throws Exception {
// Vertices
DataSet<Vertex<NEW, VV>> translatedVertices = translateVertexIds(input.getVertices(), translator, parallelism);
// Edges
DataSet<Edge<NEW, EV>> translatedEdges = translateEdgeIds(input.getEdges(), translator, parallelism);
// Graph
return Graph.fromDataSet(translatedVertices, translatedEdges, input.getContext());
}
}
|
3e1288af75d3af1ff99dd55e22db8543fb7e03a6 | 450 | java | Java | src/net/shadersmod/client/ShaderPackNone.java | josesilveiraa/novoline | 9146c4add3aa518d9aa40560158e50be1b076cf0 | [
"Unlicense"
] | 5 | 2022-02-04T12:57:17.000Z | 2022-03-26T16:12:16.000Z | src/net/shadersmod/client/ShaderPackNone.java | josesilveiraa/novoline | 9146c4add3aa518d9aa40560158e50be1b076cf0 | [
"Unlicense"
] | 2 | 2022-02-25T20:10:14.000Z | 2022-03-03T14:25:03.000Z | src/net/shadersmod/client/ShaderPackNone.java | josesilveiraa/novoline | 9146c4add3aa518d9aa40560158e50be1b076cf0 | [
"Unlicense"
] | 1 | 2021-11-28T09:59:55.000Z | 2021-11-28T09:59:55.000Z | 19.565217 | 56 | 0.72 | 7,812 | package net.shadersmod.client;
import java.io.InputStream;
import net.shadersmod.client.IShaderPack;
import net.shadersmod.client.Shaders;
public class ShaderPackNone implements IShaderPack {
public void close() {
}
public InputStream getResourceAsStream(String var1) {
return null;
}
public boolean hasDirectory(String var1) {
return false;
}
public String getName() {
return Shaders.packNameNone;
}
}
|
3e1288e1b5e7073a973430067b5cf035a54c5d9e | 21,278 | java | Java | sdk/core/azure-core/src/main/java/com/azure/core/util/polling/Poller.java | shettyh/azure-sdk-for-java | 46776a1d02a81df6801cae3258298f55537c9a54 | [
"MIT"
] | null | null | null | sdk/core/azure-core/src/main/java/com/azure/core/util/polling/Poller.java | shettyh/azure-sdk-for-java | 46776a1d02a81df6801cae3258298f55537c9a54 | [
"MIT"
] | null | null | null | sdk/core/azure-core/src/main/java/com/azure/core/util/polling/Poller.java | shettyh/azure-sdk-for-java | 46776a1d02a81df6801cae3258298f55537c9a54 | [
"MIT"
] | null | null | null | 47.284444 | 120 | 0.674875 | 7,813 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.core.util.polling;
import com.azure.core.util.logging.ClientLogger;
import com.azure.core.util.polling.PollResponse.OperationStatus;
import reactor.core.Disposable;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.time.Duration;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* This class offers API that simplifies the task of executing long-running operations against an Azure service.
* The {@link Poller} consists of a poll operation, a cancel operation, if it is supported by the Azure service, and a
* polling interval.
*
* <p>
* It provides the following functionality:
* <ul>
* <li>Querying the current state of long-running operations.</li>
* <li>Requesting an asynchronous notification for long-running operation's state.</li>
* <li>Cancelling the long-running operation if cancellation is supported by the service.</li>
* <li>Triggering a poll operation manually.</li>
* <li>Enable/Disable auto-polling.</li>
* </ul>
*
* <p><strong>Auto polling</strong></p>
* Auto-polling is enabled by default. The {@link Poller} starts polling as soon as the instance is created. The
* {@link Poller} will transparently call the poll operation every polling cycle and track the state of the
* long-running operation. Azure services can return {@link PollResponse#getRetryAfter()} to override the
* {@code Poller.pollInterval} defined in the {@link Poller}. {@link #getStatus()} represents the status returned by a
* successful long-running operation at the time the last auto-polling or last manual polling, whichever happened most
* recently.
*
* <p><strong>Disable auto polling</strong></p>
* For those scenarios which require manual control of the polling cycle, disable auto-polling by calling
* {@link #setAutoPollingEnabled(boolean) setAutoPollingEnabled(false)}. Then perform manual polling by invoking
* {@link #poll()} function. It will call poll operation once and update {@link #getStatus()} with the latest status.
*
* <p>When auto-polling is disabled, the {@link Poller} will not update its status or any other information, unless
* manual polling is triggered by calling {@link #poll()} function.
*
* <p>The {@link Poller} will stop polling when the long-running operation is complete or disabled. Polling is
* considered complete based on status defined in {@link OperationStatus}.
*
* <p><strong>Code samples</strong></p>
*
* <p><strong>Instantiating and subscribing to PollResponse</strong></p>
* {@codesnippet com.azure.core.util.polling.poller.instantiationAndSubscribe}
*
* <p><strong>Wait for polling to complete</strong></p>
* {@codesnippet com.azure.core.util.polling.poller.block}
*
* <p><strong>Disable auto polling and poll manually</strong></p>
* {@codesnippet com.azure.core.util.polling.poller.poll-manually}
*
* @param <T> Type of poll response value
* @see PollResponse
* @see OperationStatus
*/
public class Poller<T> {
private final ClientLogger logger = new ClientLogger(Poller.class);
/*
* poll operation is a function that takes the previous PollResponse, and returns a new Mono of PollResponse to
* represent the current state
*/
private final Function<PollResponse<T>, Mono<PollResponse<T>>> pollOperation;
/*
* poll interval before next auto poll. This value will be used if the PollResponse does not include retryAfter
* from the service.
*/
private final Duration pollInterval;
/*
* This will save last poll response.
*/
private PollResponse<T> pollResponse;
/*
* This will be called when cancel operation is triggered.
*/
private final Consumer<Poller<T>> cancelOperation;
/*
* Indicate to poll automatically or not when poller is created.
* default value is false;
*/
private boolean autoPollingEnabled;
/*
* This handle to Flux allow us to perform polling operation in asynchronous manner.
* This could be shared among many subscriber. One of the subscriber will be this poller itself.
* Once subscribed, this Flux will continue to poll for status until poll operation is done/complete.
*/
private final Flux<PollResponse<T>> fluxHandle;
/*
* Since constructor create a subscriber and start auto polling. This handle will be used to dispose the subscriber
* when client disable auto polling.
*/
private Disposable fluxDisposable;
/**
* Creates a {@link Poller} instance with poll interval and poll operation. The polling starts immediately by
* invoking {@code pollOperation}. The next poll cycle will be defined by {@code retryAfter} value in
* {@link PollResponse}. In absence of {@code retryAfter}, the {@link Poller} will use {@code pollInterval}.
*
* <p><strong>Create poller object</strong></p>
* {@codesnippet com.azure.core.util.polling.poller.initialize.interval.polloperation}
*
* @param pollInterval Non null and greater than zero poll interval.
* @param pollOperation The polling operation to be called by the {@link Poller} instance. This must never return
* {@code null} and always have a non-null {@link OperationStatus}. {@link Mono} returned from poll operation
* should never return {@link Mono#error(Throwable)}. If an unexpected scenario happens during the poll
* operation, it should be handled by the client library and return a valid {@link PollResponse}. However if
* the poll operation returns {@link Mono#error(Throwable)}, the {@link Poller} will disregard it and continue
* to poll.
* @throws IllegalArgumentException if {@code pollInterval} is less than or equal to zero and if
* {@code pollInterval} or {@code pollOperation} are {@code null}
*/
public Poller(Duration pollInterval, Function<PollResponse<T>, Mono<PollResponse<T>>> pollOperation) {
this(pollInterval, pollOperation, null, null);
}
/**
* Creates a {@link Poller} instance with poll interval, poll operation, and optional cancel operation. Polling
* starts immediately by invoking {@code pollOperation}. The next poll cycle will be defined by retryAfter value in
* {@link PollResponse}. In absence of {@link PollResponse#getRetryAfter()}, the {@link Poller} will use
* {@code pollInterval}.
*
* @param pollInterval Not-null and greater than zero poll interval.
* @param pollOperation The polling operation to be called by the {@link Poller} instance. This must never return
* {@code null} and always have a non-null {@link OperationStatus}. {@link Mono} returned from poll operation
* should never return {@link Mono#error(Throwable)}. If an unexpected scenario happens during the poll
* operation, it should be handled by the client library and return a valid {@link PollResponse}. However if
* the poll operation returns {@link Mono#error(Throwable)}, the {@link Poller} will disregard it and continue
* to poll.
* @param activationOperation The activation operation to be called by the {@link Poller} instance before
* calling {@code pollOperation}. It can be {@code null} which will indicate to the {@link Poller} that
* {@code pollOperation} can be called straight away.
* @param cancelOperation Cancel operation if cancellation is supported by the service. If it is {@code null}, then
* the cancel operation is not supported.
* @throws IllegalArgumentException if {@code pollInterval} is less than or equal to zero and if
* {@code pollInterval} or {@code pollOperation} are {@code null}
*/
public Poller(Duration pollInterval, Function<PollResponse<T>, Mono<PollResponse<T>>> pollOperation,
Supplier<Mono<T>> activationOperation, Consumer<Poller<T>> cancelOperation) {
if (pollInterval == null || pollInterval.toNanos() <= 0) {
throw logger.logExceptionAsWarning(new IllegalArgumentException(
"Null, negative or zero value for poll interval is not allowed."));
}
if (pollOperation == null) {
throw logger.logExceptionAsWarning(new IllegalArgumentException(
"Null value for poll operation is not allowed."));
}
this.pollInterval = pollInterval;
this.pollOperation = pollOperation;
this.pollResponse = new PollResponse<>(OperationStatus.NOT_STARTED, null);
this.fluxHandle = asyncPollRequestWithDelay()
.flux()
.repeat()
.takeUntil(pollResponse -> hasCompleted())
.share()
.delaySubscription(activationOperation != null ? activationOperation.get() : Mono.empty());
// auto polling start here
this.fluxDisposable = fluxHandle.subscribe();
this.autoPollingEnabled = true;
this.cancelOperation = cancelOperation;
}
/**
* Create a {@link Poller} instance with poll interval, poll operation and cancel operation. The polling starts
* immediately by invoking {@code pollOperation}. The next poll cycle will be defined by retryAfter value
* in {@link PollResponse}. In absence of {@link PollResponse#getRetryAfter()}, the {@link Poller}
* will use {@code pollInterval}.
*
* @param pollInterval Not-null and greater than zero poll interval.
* @param pollOperation The polling operation to be called by the {@link Poller} instance. This is a callback into
* the client library, which must never return {@code null}, and which must always have a non-null
* {@link OperationStatus}. {@link Mono} returned from poll operation should never return
* {@link Mono#error(Throwable)}.If any unexpected scenario happens in poll operation, it should be handled by
* client library and return a valid {@link PollResponse}. However if poll operation returns
* {@link Mono#error(Throwable)}, the {@link Poller} will disregard that and continue to poll.
* @param cancelOperation cancel operation if cancellation is supported by the service. It can be {@code null}
* which will indicate to the {@link Poller} that cancel operation is not supported by Azure service.
* @throws IllegalArgumentException if {@code pollInterval} is less than or equal to zero and if
* {@code pollInterval} or {@code pollOperation} are {@code null}
*/
public Poller(Duration pollInterval, Function<PollResponse<T>, Mono<PollResponse<T>>> pollOperation,
Consumer<Poller<T>> cancelOperation) {
this(pollInterval, pollOperation, null, cancelOperation);
}
/**
* Attempts to cancel the long-running operation that this {@link Poller} represents. This is possible only if the
* service supports it, otherwise an {@code UnsupportedOperationException} will be thrown.
* <p>
* It will call cancelOperation if status is {@link OperationStatus#IN_PROGRESS} otherwise it does nothing.
*
* @throws UnsupportedOperationException when the cancel operation is not supported by the Azure service.
*/
public void cancelOperation() throws UnsupportedOperationException {
if (this.cancelOperation == null) {
throw logger.logExceptionAsError(new UnsupportedOperationException(
"Cancel operation is not supported on this service/resource."));
}
// We can not cancel an operation if it was never started
// It only make sense to call cancel operation if current status IN_PROGRESS.
if (this.pollResponse != null && this.pollResponse.getStatus() != OperationStatus.IN_PROGRESS) {
return;
}
//Time to call cancel
this.cancelOperation.accept(this);
}
/**
* This method returns a {@link Flux} that can be subscribed to, enabling a subscriber to receive notification of
* every {@link PollResponse}, as it is received.
*
* @return A {@link Flux} that can be subscribed to receive poll responses as the long-running operation executes.
*/
public Flux<PollResponse<T>> getObserver() {
return this.fluxHandle;
}
/**
* Enables user to take control of polling and trigger manual poll operation. It will call poll operation once.
* This will not turn off auto polling.
*
* <p><strong>Manual polling</strong></p>
* <p>
* {@codesnippet com.azure.core.util.polling.poller.poll-indepth}
*
* @return A {@link Mono} that returns {@link PollResponse}. This will call poll operation once.
*/
public Mono<PollResponse<T>> poll() {
return this.pollOperation.apply(this.pollResponse)
.doOnEach(pollResponseSignal -> {
if (pollResponseSignal.get() != null) {
this.pollResponse = pollResponseSignal.get();
}
});
}
/**
* Blocks execution and wait for polling to complete. The polling is considered complete based on the status defined
* in {@link OperationStatus}.
*
* <p>It will enable auto-polling if it was disabled by the user.
*
* @return A {@link PollResponse} when polling is complete.
*/
public PollResponse<T> block() {
if (!isAutoPollingEnabled()) {
setAutoPollingEnabled(true);
}
return this.fluxHandle.blockLast();
}
/**
* Blocks execution and wait for polling to complete. The polling is considered complete based on status defined
* in {@link OperationStatus}.
* <p>It will enable auto-polling if it was disable by user.
*
* @param timeout The duration for which execution is blocked and waits for polling to complete.
* @return returns final {@link PollResponse} when polling is complete as defined in {@link OperationStatus}.
*/
public PollResponse<T> block(Duration timeout) {
if (!isAutoPollingEnabled()) {
setAutoPollingEnabled(true);
}
return this.fluxHandle.blockLast(timeout);
}
/**
* Blocks indefinitely until given {@link OperationStatus} is received.
*
* @param statusToBlockFor The desired {@link OperationStatus} to block for.
* @return {@link PollResponse} whose {@link PollResponse#getStatus()} matches {@code statusToBlockFor}.
* @throws IllegalArgumentException If {@code statusToBlockFor} is {@code null}.
*/
public PollResponse<T> blockUntil(OperationStatus statusToBlockFor) {
return blockUntil(statusToBlockFor, null);
}
/**
* Blocks until given {@code statusToBlockFor} is received or the {@code timeout} elapses. If a {@code null}
* {@code timeout} is given, it will block indefinitely.
*
* @param statusToBlockFor The desired {@link OperationStatus} to block for and it can be any valid
* {@link OperationStatus} value.
* @param timeout The time after which it will stop blocking. A {@code null} value will cause to block
* indefinitely. Zero or negative are not valid values.
* @return {@link PollResponse} for matching desired status to block for.
* @throws IllegalArgumentException if {@code timeout} is zero or negative and if {@code statusToBlockFor} is
* {@code null}.
*/
public PollResponse<T> blockUntil(OperationStatus statusToBlockFor, Duration timeout) {
if (statusToBlockFor == null) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("Null value for status is not allowed."));
}
if (timeout != null && timeout.toNanos() <= 0) {
throw logger.logExceptionAsWarning(new IllegalArgumentException(
"Negative or zero value for timeout is not allowed."));
}
if (!isAutoPollingEnabled()) {
setAutoPollingEnabled(true);
}
if (timeout != null) {
return this.fluxHandle
.filter(tPollResponse -> matchStatus(tPollResponse, statusToBlockFor)).blockFirst(timeout);
} else {
return this.fluxHandle
.filter(tPollResponse -> matchStatus(tPollResponse, statusToBlockFor)).blockFirst();
}
}
/*
* Indicate that the {@link PollResponse} matches with the status to block for.
* @param currentPollResponse The poll response which we have received from the flux.
* @param statusToBlockFor The {@link OperationStatus} to block and it can be any valid {@link OperationStatus}
* value.
* @return True if the {@link PollResponse} return status matches the status to block for.
*/
private boolean matchStatus(PollResponse<T> currentPollResponse, OperationStatus statusToBlockFor) {
// perform validation
if (currentPollResponse == null || statusToBlockFor == null) {
return false;
}
if (statusToBlockFor == currentPollResponse.getStatus()) {
return true;
}
return false;
}
/*
* This function will apply delay and call poll operation function async.
* We expect Mono from pollOperation should never return Mono.error(). If any unexpected
* scenario happens in pollOperation, it should catch it and return a valid PollResponse.
* This is because poller does not know what to do in case on Mono.error.
* This function will return empty mono in case of Mono.error() returned by poll operation.
*
* @return mono of poll response
*/
private Mono<PollResponse<T>> asyncPollRequestWithDelay() {
return Mono.defer(() -> this.pollOperation.apply(this.pollResponse)
.delaySubscription(getCurrentDelay())
.onErrorResume(throwable -> {
// We should never get here and since we want to continue polling
//Log the error
return Mono.empty();
})
.doOnEach(pollResponseSignal -> {
if (pollResponseSignal.get() != null) {
this.pollResponse = pollResponseSignal.get();
}
}));
}
/*
* We will use {@link PollResponse#getRetryAfter} if it is greater than zero otherwise use poll interval.
*/
private Duration getCurrentDelay() {
return (this.pollResponse != null
&& this.pollResponse.getRetryAfter() != null
&& this.pollResponse.getRetryAfter().toNanos() > 0) ? this.pollResponse.getRetryAfter() : this.pollInterval;
}
/**
* Controls whether auto-polling is enabled or disabled. Refer to the {@link Poller} class-level JavaDoc for more
* details on auto-polling.
*
* <p><strong>Disable auto polling</strong></p>
* {@codesnippet com.azure.core.util.polling.poller.disableautopolling}
*
* <p><strong>Enable auto polling</strong></p>
* {@codesnippet com.azure.core.util.polling.poller.enableautopolling}
*
* @param autoPollingEnabled If true, auto-polling will occur transparently in the background, otherwise it
* requires manual polling by the user to get the latest state.
*/
public final void setAutoPollingEnabled(boolean autoPollingEnabled) {
this.autoPollingEnabled = autoPollingEnabled;
if (this.autoPollingEnabled) {
if (!activeSubscriber()) {
this.fluxDisposable = this.fluxHandle.subscribe(pr -> this.pollResponse = pr);
}
} else {
if (activeSubscriber()) {
this.fluxDisposable.dispose();
}
}
}
/*
* An operation will be considered complete if it is in one of the following state:
* <ul>
* <li>SUCCESSFULLY_COMPLETED</li>
* <li>USER_CANCELLED</li>
* <li>FAILED</li>
* </ul>
* Also see {@link OperationStatus}
* @return true if operation is done/complete.
*/
private boolean hasCompleted() {
return pollResponse != null && (pollResponse.getStatus() == OperationStatus.SUCCESSFULLY_COMPLETED
|| pollResponse.getStatus() == OperationStatus.FAILED
|| pollResponse.getStatus() == OperationStatus.USER_CANCELLED);
}
/*
* Determine if this poller's internal subscriber exists and active.
*/
private boolean activeSubscriber() {
return (this.fluxDisposable != null && !this.fluxDisposable.isDisposed());
}
/**
* Indicates if auto polling is enabled. Refer to the {@link Poller} class-level JavaDoc for more details on
* auto-polling.
*
* @return {@code true} if auto-polling is enabled and {@code false} otherwise.
*/
public boolean isAutoPollingEnabled() {
return this.autoPollingEnabled;
}
/**
* Current known status as a result of last poll event or last response from a manual polling.
*
* @return Current status or {@code null} if no status is available.
*/
public OperationStatus getStatus() {
return this.pollResponse != null ? this.pollResponse.getStatus() : null;
}
}
|
3e1289e68bb3a0db1d748984578923dd6410b397 | 673 | java | Java | src/main/java/com/pengyifan/leetcode/AddDigits.java | aav789/pengyifan-leetcode | aa0b1062c3e22ce50f6a97edb906338d86e4e9ae | [
"BSD-3-Clause"
] | 26 | 2015-04-21T16:30:17.000Z | 2020-03-18T03:02:19.000Z | src/main/java/com/pengyifan/leetcode/AddDigits.java | aav789/pengyifan-leetcode | aa0b1062c3e22ce50f6a97edb906338d86e4e9ae | [
"BSD-3-Clause"
] | 1 | 2017-06-18T02:14:55.000Z | 2017-06-18T02:14:55.000Z | src/main/java/com/pengyifan/leetcode/AddDigits.java | aav789/pengyifan-leetcode | aa0b1062c3e22ce50f6a97edb906338d86e4e9ae | [
"BSD-3-Clause"
] | 25 | 2015-03-15T04:02:01.000Z | 2020-03-01T01:11:18.000Z | 21.03125 | 97 | 0.597325 | 7,814 | package com.pengyifan.leetcode;
/**
* Given a non-negative integer num, repeatedly add all its digits until the result has only one
* digit.
* <p>
* For example:
* <p>
* Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return
* it.
* <p>
* Follow up:
* Could you do it without any loop/recursion in O(1) runtime?
*/
public class AddDigits {
public int addDigits(int num) {
return addDigitsHelper(num);
}
private int addDigitsHelper(int num) {
if (num < 10) {
return num;
}
int i = 0;
while (num != 0) {
i += num % 10;
num = num / 10;
}
return addDigitsHelper(i);
}
}
|
3e128a39846d6cc872ce9b6ce1b6709daf547c51 | 347 | java | Java | src/main/java/bean/ResponseWrapper.java | matarrese/content-api-the-guardian | cfe615907b5fe4b96ae1af7879fa078574c751d4 | [
"Apache-2.0"
] | 8 | 2018-01-16T11:05:56.000Z | 2021-05-23T00:49:11.000Z | src/main/java/bean/ResponseWrapper.java | matarrese/content-api-the-guardian | cfe615907b5fe4b96ae1af7879fa078574c751d4 | [
"Apache-2.0"
] | null | null | null | src/main/java/bean/ResponseWrapper.java | matarrese/content-api-the-guardian | cfe615907b5fe4b96ae1af7879fa078574c751d4 | [
"Apache-2.0"
] | 7 | 2018-08-19T23:34:18.000Z | 2021-07-15T20:19:34.000Z | 15.772727 | 52 | 0.70317 | 7,815 | package bean;
public class ResponseWrapper {
private Response response;
public Response getResponse() {
return response;
}
public void setResponse(final Response response) {
this.response = response;
}
public ResponseWrapper(final Response response) {
this.response = response;
}
public ResponseWrapper() {
}
}
|
3e128b5fcb988b51a08c7407efba7d91897c8074 | 2,316 | java | Java | core-test/src/main/java/org/openstack4j/api/dns/v2/DesignateRecordsetServiceTest.java | octetnest/openstack4j | 9bd9f66d61f17662d70fd22deb65ebd03cf4b353 | [
"Apache-2.0"
] | 204 | 2016-05-14T12:06:15.000Z | 2022-03-07T09:45:52.000Z | core-test/src/main/java/org/openstack4j/api/dns/v2/DesignateRecordsetServiceTest.java | octetnest/openstack4j | 9bd9f66d61f17662d70fd22deb65ebd03cf4b353 | [
"Apache-2.0"
] | 721 | 2016-05-13T06:51:32.000Z | 2022-01-13T17:44:40.000Z | core-test/src/main/java/org/openstack4j/api/dns/v2/DesignateRecordsetServiceTest.java | octetnest/openstack4j | 9bd9f66d61f17662d70fd22deb65ebd03cf4b353 | [
"Apache-2.0"
] | 291 | 2016-05-13T05:58:13.000Z | 2022-03-07T09:43:36.000Z | 35.630769 | 123 | 0.740933 | 7,816 | package org.openstack4j.api.dns.v2;
import com.google.common.collect.ImmutableList;
import org.openstack4j.api.AbstractTest;
import org.openstack4j.model.dns.v2.Action;
import org.openstack4j.model.dns.v2.Recordset;
import org.openstack4j.model.dns.v2.Status;
import org.testng.annotations.Test;
import java.util.List;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
/**
* Tests the DNS/Designate API version 2 ZoneService
*/
@Test(groups = "dnsV2", suiteName = "DNS/Designate_V2")
public class DesignateRecordsetServiceTest extends AbstractTest {
private static final String JSON_RECORDSET = "/dns/v2/create_recordset.json";
private static final String JSON_RECORDSETLIST = "/dns/v2/list_recordsets.json";
private static final String ZONE_ID = "2150b1bf-dee2-4221-9d85-11f7886fb15f";
private static final String RECORDSET_NAME = "example.org.";
private static final String RECORDSET_TYPE = "A";
private static final ImmutableList<String> RECORDSET_RECORDS = ImmutableList.of("10.1.0.2");
private static final Status RECORDSET_STATUS = Status.PENDING;
private static final Action RECORDSET_ACTION = Action.CREATE;
private static final Integer RECORDSET_VERSION = 1;
@Override
protected Service service() {
return Service.DNS;
}
public void recordsetCreateTest() throws Exception {
respondWith(JSON_RECORDSET);
Recordset recordset = osv3().dns().recordsets().create(ZONE_ID, RECORDSET_NAME, RECORDSET_TYPE, RECORDSET_RECORDS);
assertEquals(recordset.getZoneId(), ZONE_ID);
assertEquals(recordset.getName(), RECORDSET_NAME);
assertEquals(recordset.getType(), RECORDSET_TYPE);
assertEquals(recordset.getRecords(), RECORDSET_RECORDS);
assertEquals(recordset.getStatus(), RECORDSET_STATUS);
assertEquals(recordset.getAction(), RECORDSET_ACTION);
}
public void recordsetListTest() throws Exception {
respondWith(JSON_RECORDSETLIST);
List<? extends Recordset> recordsetList = osv3().dns().recordsets().list(ZONE_ID);
assertFalse(recordsetList.isEmpty());
assertEquals(recordsetList.get(0).getZoneId(), ZONE_ID);
assertEquals(recordsetList.get(0).getVersion(), RECORDSET_VERSION);
}
}
|
3e128c12aec15e03300a1f2468a621d0299626f1 | 3,005 | java | Java | src/main/java/no/fint/p360/handler/noark/KodeverkHandler.java | FINTLabs/fint-ra-arkiv-adapter | 05bede363a86cf496bb69b61c3190e55b87757fe | [
"MIT"
] | null | null | null | src/main/java/no/fint/p360/handler/noark/KodeverkHandler.java | FINTLabs/fint-ra-arkiv-adapter | 05bede363a86cf496bb69b61c3190e55b87757fe | [
"MIT"
] | 8 | 2019-11-12T11:03:22.000Z | 2020-10-18T13:14:23.000Z | src/main/java/no/fint/p360/handler/noark/KodeverkHandler.java | FINTLabs/fint-p360-arkiv-adapter | 05bede363a86cf496bb69b61c3190e55b87757fe | [
"MIT"
] | null | null | null | 40.066667 | 123 | 0.757737 | 7,817 | package no.fint.p360.handler.noark;
import lombok.extern.slf4j.Slf4j;
import no.fint.event.model.Event;
import no.fint.event.model.ResponseStatus;
import no.fint.event.model.Status;
import no.fint.model.administrasjon.arkiv.ArkivActions;
import no.fint.model.resource.FintLinks;
import no.fint.p360.handler.Handler;
import no.fint.p360.repository.KodeverkRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import static no.fint.model.administrasjon.arkiv.ArkivActions.*;
@Service
@Slf4j
public class KodeverkHandler implements Handler {
private final EnumMap<ArkivActions, Supplier<List<? extends FintLinks>>> suppliers = new EnumMap<>(ArkivActions.class);
@PostConstruct
public void init() {
suppliers.put(GET_ALL_DOKUMENTSTATUS, kodeverkRepository::getDokumentStatus);
suppliers.put(GET_ALL_DOKUMENTTYPE, kodeverkRepository::getDokumentType);
suppliers.put(GET_ALL_JOURNALPOSTTYPE, kodeverkRepository::getJournalpostType);
suppliers.put(GET_ALL_JOURNALSTATUS, kodeverkRepository::getJournalStatus);
suppliers.put(GET_ALL_KORRESPONDANSEPARTTYPE, kodeverkRepository::getKorrespondansepartType);
suppliers.put(GET_ALL_MERKNADSTYPE, kodeverkRepository::getMerknadstype);
suppliers.put(GET_ALL_PARTROLLE, kodeverkRepository::getPartRolle);
suppliers.put(GET_ALL_SAKSSTATUS, kodeverkRepository::getSaksstatus);
suppliers.put(GET_ALL_SKJERMINGSHJEMMEL, kodeverkRepository::getSkjermingshjemmel);
suppliers.put(GET_ALL_TILGANGSRESTRIKSJON, kodeverkRepository::getTilgangsrestriksjon);
suppliers.put(GET_ALL_TILKNYTTETREGISTRERINGSOM, kodeverkRepository::getTilknyttetRegistreringSom);
suppliers.put(GET_ALL_VARIANTFORMAT, kodeverkRepository::getVariantformat);
suppliers.put(GET_ALL_KLASSIFIKASJONSSYSTEM, kodeverkRepository::getKlassifikasjonssystem);
suppliers.put(GET_ALL_KLASSE, kodeverkRepository::getKlasse);
}
@Autowired
private KodeverkRepository kodeverkRepository;
@Override
public void accept(Event<FintLinks> response) {
if (!health()) {
response.setStatus(Status.ADAPTER_REJECTED);
response.setMessage("Health test failed");
return;
}
response.setResponseStatus(ResponseStatus.ACCEPTED);
suppliers.getOrDefault(ArkivActions.valueOf(response.getAction()), Collections::emptyList)
.get()
.forEach(response::addData);
}
@Override
public Set<String> actions() {
return suppliers.keySet().stream().map(Enum::name).collect(Collectors.toSet());
}
@Override
public boolean health() {
return kodeverkRepository.health();
}
}
|
3e128c2ae5b22c3cc3c366b8656be67e755b353a | 347 | java | Java | src/main/java/org/toilelibre/libe/soundtransform/model/library/pack/note/NoteAccessor.java | libetl/soundtransform | b46b4dada206dd24e87664d84d2303819c383add | [
"Apache-2.0"
] | 47 | 2015-05-31T21:14:22.000Z | 2021-09-12T05:47:22.000Z | src/main/java/org/toilelibre/libe/soundtransform/model/library/pack/note/NoteAccessor.java | libetl/soundtransform | b46b4dada206dd24e87664d84d2303819c383add | [
"Apache-2.0"
] | 112 | 2015-01-19T11:05:58.000Z | 2022-03-29T04:05:48.000Z | src/main/java/org/toilelibre/libe/soundtransform/model/library/pack/note/NoteAccessor.java | libetl/soundtransform | b46b4dada206dd24e87664d84d2303819c383add | [
"Apache-2.0"
] | 9 | 2016-03-19T12:28:35.000Z | 2021-12-28T02:38:38.000Z | 28.916667 | 87 | 0.763689 | 7,818 | package org.toilelibre.libe.soundtransform.model.library.pack.note;
import org.toilelibre.libe.soundtransform.model.library.pack.PackAccessor;
public abstract class NoteAccessor extends PackAccessor {
public NoteAccessor () {
super ();
this.usedImpls.put (SoundToNoteService.class, DefaultSoundToNoteService.class);
}
}
|
3e12902badc70afee566e68b66ebc43f1df3955c | 1,469 | java | Java | src/main/java/org/ddouglascarr/query/models/Delegation.java | ddouglascarr/liquidcanon-api | 2d4294479449a5e17f7c8bfe018625c00bba6561 | [
"MIT"
] | null | null | null | src/main/java/org/ddouglascarr/query/models/Delegation.java | ddouglascarr/liquidcanon-api | 2d4294479449a5e17f7c8bfe018625c00bba6561 | [
"MIT"
] | null | null | null | src/main/java/org/ddouglascarr/query/models/Delegation.java | ddouglascarr/liquidcanon-api | 2d4294479449a5e17f7c8bfe018625c00bba6561 | [
"MIT"
] | null | null | null | 15.795699 | 47 | 0.59224 | 7,819 | package org.ddouglascarr.query.models;
import org.ddouglascarr.enums.DelegationScope;
import org.springframework.data.annotation.Id;
import java.util.UUID;
public class Delegation
{
@Id
private UUID id;
private UUID trusterId;
private UUID trusteeId;
private DelegationScope scope;
private UUID unitId;
private UUID areaId;
private UUID issueId;
// Getters and Setters
public UUID getId()
{
return id;
}
public void setId(UUID id)
{
this.id = id;
}
public UUID getTrusterId()
{
return trusterId;
}
public void setTrusterId(UUID trusterId)
{
this.trusterId = trusterId;
}
public UUID getTrusteeId()
{
return trusteeId;
}
public void setTrusteeId(UUID trusteeId)
{
this.trusteeId = trusteeId;
}
public DelegationScope getScope()
{
return scope;
}
public void setScope(DelegationScope scope)
{
this.scope = scope;
}
public UUID getUnitId()
{
return unitId;
}
public void setUnitId(UUID unitId)
{
this.unitId = unitId;
}
public UUID getAreaId()
{
return areaId;
}
public void setAreaId(UUID areaId)
{
this.areaId = areaId;
}
public UUID getIssueId()
{
return issueId;
}
public void setIssueId(UUID issueId)
{
this.issueId = issueId;
}
}
|
3e12914866764aac648075c89b6e300c6cbd716c | 550 | java | Java | src/test/java/org/kwok/util/json/Test_Properties.java | KwokRoot/java-json-to-properties | eaa3a6f4e3667e2df47ad8d9f2ab78f65d5886e9 | [
"Apache-2.0"
] | 3 | 2019-01-28T13:24:13.000Z | 2019-02-17T11:07:05.000Z | src/test/java/org/kwok/util/json/Test_Properties.java | KwokRoot/java-json-to-properties | eaa3a6f4e3667e2df47ad8d9f2ab78f65d5886e9 | [
"Apache-2.0"
] | null | null | null | src/test/java/org/kwok/util/json/Test_Properties.java | KwokRoot/java-json-to-properties | eaa3a6f4e3667e2df47ad8d9f2ab78f65d5886e9 | [
"Apache-2.0"
] | null | null | null | 15.277778 | 55 | 0.630909 | 7,820 | package org.kwok.util.json;
import java.util.Properties;
/**
* 由于 Properties 继承自 Hashtable,固 key、value 值均不可为 null。
* @author Kwok
*/
public class Test_Properties {
public static void main(String[] args) {
Properties properties = new Properties();
try{
properties.setProperty(null, "kwok");
}catch (Exception e) {
System.err.println("键不能为 null。");
}
try{
properties.setProperty("kwok", null);
}catch (Exception e) {
System.err.println("值不能为 null。");
}
/*
结果:
键不能为 null。
值不能为 null。
*/
}
}
|
3e12916c89a7b9907aafd945597349e6a5e2d1ef | 2,079 | java | Java | sample/src/androidTest/java/com/litepaltest/test/crud/save/Many2OneUniSaveTest.java | hexingbo/LitePal | 9645b564f66a13517bf4a882886914fe5c389126 | [
"Apache-2.0"
] | 14 | 2015-08-28T01:57:05.000Z | 2017-11-27T06:00:56.000Z | sample/src/androidTest/java/com/litepaltest/test/crud/save/Many2OneUniSaveTest.java | MaddenCat/LitePal | 9645b564f66a13517bf4a882886914fe5c389126 | [
"Apache-2.0"
] | null | null | null | sample/src/androidTest/java/com/litepaltest/test/crud/save/Many2OneUniSaveTest.java | MaddenCat/LitePal | 9645b564f66a13517bf4a882886914fe5c389126 | [
"Apache-2.0"
] | 10 | 2015-11-25T02:05:12.000Z | 2019-03-28T09:27:48.000Z | 22.597826 | 93 | 0.637807 | 7,821 | package com.litepaltest.test.crud.save;
import junit.framework.Assert;
import com.litepaltest.model.Classroom;
import com.litepaltest.model.Teacher;
import com.litepaltest.test.LitePalTestCase;
public class Many2OneUniSaveTest extends LitePalTestCase {
private Classroom c1;
private Teacher t1;
private Teacher t2;
public void init() {
c1 = new Classroom();
c1.setName("Music room");
t1 = new Teacher();
t1.setTeacherName("John");
t1.setAge(25);
t2 = new Teacher();
t2.setTeacherName("Sean");
t2.setAge(35);
}
public void testCase1() {
init();
c1.getTeachers().add(t1);
c1.getTeachers().add(t2);
c1.save();
t1.save();
t2.save();
assertFK(c1, t1, t2);
}
public void testCase2() {
init();
c1.getTeachers().add(t1);
c1.getTeachers().add(t2);
t1.save();
t2.save();
c1.save();
assertFK(c1, t1, t2);
}
public void testCase3() {
init();
c1.getTeachers().add(t1);
c1.getTeachers().add(t2);
t1.save();
c1.save();
t2.save();
assertFK(c1, t1, t2);
}
public void testCase4() {
init();
t1 = null;
t2 = null;
c1.getTeachers().add(t1);
c1.getTeachers().add(t2);
c1.save();
isDataExists(getTableName(c1), c1.get_id());
}
public void testSaveFast() {
init();
c1.getTeachers().add(t1);
c1.getTeachers().add(t2);
c1.saveFast();
t1.saveFast();
t2.saveFast();
isDataExists(getTableName(c1), c1.get_id());
isDataExists(getTableName(t1), t1.getId());
isDataExists(getTableName(t2), t2.getId());
Assert.assertFalse(isFKInsertCorrect(getTableName(c1), getTableName(t1), c1.get_id(),
t1.getId()));
Assert.assertFalse(isFKInsertCorrect(getTableName(c1), getTableName(t2), c1.get_id(),
t2.getId()));
}
private void assertFK(Classroom c1, Teacher t1, Teacher t2) {
Assert.assertTrue(isFKInsertCorrect(getTableName(c1), getTableName(t1), c1.get_id(),
t1.getId()));
Assert.assertTrue(isFKInsertCorrect(getTableName(c1), getTableName(t2), c1.get_id(),
t2.getId()));
}
}
|
3e1291aa9309c6871d70cf54a60cb5925247861f | 1,587 | java | Java | src/main/java/io/renren/modules/sys/service/SysConfigService.java | iikspiral/springbootSigleton | 8892f0cfc1a45025fe24e31c36ea956a5a89b1d8 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/renren/modules/sys/service/SysConfigService.java | iikspiral/springbootSigleton | 8892f0cfc1a45025fe24e31c36ea956a5a89b1d8 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/renren/modules/sys/service/SysConfigService.java | iikspiral/springbootSigleton | 8892f0cfc1a45025fe24e31c36ea956a5a89b1d8 | [
"Apache-2.0"
] | null | null | null | 22.138889 | 80 | 0.696989 | 7,822 | /**
* Copyright 2018 人人开源 http://www.renren.io
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.renren.modules.sys.service;
import com.baomidou.mybatisplus.service.IService;
import io.renren.common.utils.PageUtils;
import io.renren.modules.sys.entity.SysConfigEntity;
import java.util.Map;
/**
* 系统配置信息
*
* @author Yophy.W
* @email envkt@example.com
* @date 2016年12月4日 下午6:49:01
*/
public interface SysConfigService extends IService<SysConfigEntity> {
PageUtils queryPage(Map<String, Object> params);
/**
* 保存配置信息
*/
public void save(SysConfigEntity config);
/**
* 更新配置信息
*/
public void update(SysConfigEntity config);
/**
* 根据key,更新value
*/
public void updateValueByKey(String key, String value);
/**
* 删除配置信息
*/
public void deleteBatch(Long[] ids);
/**
* 根据key,获取配置的value值
*
* @param key key
*/
public String getValue(String key);
/**
* 根据key,获取value的Object对象
* @param key key
* @param clazz Object对象
*/
public <T> T getConfigObject(String key, Class<T> clazz);
}
|
3e1291f4ca28a3e31316a420fd92c109a782dcde | 4,012 | java | Java | src/main/java/inaki/sw/mines/view/swing/utils/Autocomplete.java | isarobeadot/i-sw-mines | e1f017d6290ab381dce3d03b7f2817a90b279fda | [
"MIT"
] | null | null | null | src/main/java/inaki/sw/mines/view/swing/utils/Autocomplete.java | isarobeadot/i-sw-mines | e1f017d6290ab381dce3d03b7f2817a90b279fda | [
"MIT"
] | 9 | 2021-04-26T15:22:35.000Z | 2021-04-26T15:25:38.000Z | src/main/java/inaki/sw/mines/view/swing/utils/Autocomplete.java | isarobeadot/i-sw-mines | e1f017d6290ab381dce3d03b7f2817a90b279fda | [
"MIT"
] | null | null | null | 27.668966 | 84 | 0.577268 | 7,823 | package inaki.sw.mines.view.swing.utils;
import java.awt.event.ActionEvent;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
import static java.util.logging.Logger.getLogger;
import javax.swing.AbstractAction;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
/**
* From https://stackabuse.com/example-adding-autocomplete-to-jtextfield/
*
* @author inaki
* @since 2.2.1
*/
public class Autocomplete implements DocumentListener {
private static final Logger LOGGER = getLogger(Autocomplete.class.getName());
private static enum Mode {
INSERT,
COMPLETION
};
private final JTextField textField;
private final List<String> keywords;
private Mode mode = Mode.INSERT;
/**
*
* @param textField
* @param keywords
*/
public Autocomplete(JTextField textField, List<String> keywords) {
this.textField = textField;
this.keywords = keywords;
Collections.sort(keywords);
}
@Override
public void changedUpdate(DocumentEvent ev) {
}
@Override
public void removeUpdate(DocumentEvent ev) {
}
@Override
public void insertUpdate(DocumentEvent ev) {
if (ev.getLength() != 1) {
return;
}
int pos = ev.getOffset();
String content = "";
try {
content = textField.getText(0, pos + 1);
}
catch (BadLocationException e) {
LOGGER.severe(e.getMessage());
}
// Find where the word starts
int w;
for (w = pos; w >= 0; w--) {
if (!Character.isLetter(content.charAt(w))) {
break;
}
}
// Too few chars
if (pos - w < 2) {
return;
}
String prefix = content.substring(w + 1).toLowerCase();
int n = Collections.binarySearch(keywords, prefix);
if (n < 0 && -n <= keywords.size()) {
String match = keywords.get(-n - 1);
if (match.startsWith(prefix)) {
// A completion is found
String completion = match.substring(pos - w);
// We cannot modify Document from within notification,
// so we submit a task that does the change later
SwingUtilities.invokeLater(new CompletionTask(completion, pos + 1));
}
} else {
// Nothing found
mode = Mode.INSERT;
}
}
/**
*
*/
public class CommitAction extends AbstractAction {
/**
*
*/
private static final long serialVersionUID = 5794543109646743416L;
@Override
public void actionPerformed(ActionEvent ev) {
if (mode == Mode.COMPLETION) {
int pos = textField.getSelectionEnd();
StringBuilder sb = new StringBuilder(textField.getText());
sb.insert(pos, " ");
textField.setText(sb.toString());
textField.setCaretPosition(pos + 1);
mode = Mode.INSERT;
} else {
textField.replaceSelection("\t");
}
}
}
private class CompletionTask implements Runnable {
private final String completion;
private final int position;
CompletionTask(String completion, int position) {
this.completion = completion;
this.position = position;
}
@Override
public void run() {
StringBuilder sb = new StringBuilder(textField.getText());
sb.insert(position, completion);
textField.setText(sb.toString());
textField.setCaretPosition(position + completion.length());
textField.moveCaretPosition(position);
mode = Mode.COMPLETION;
}
}
}
|
3e12923d5d9c5e7c249ea88d0fd287d5c6118bd5 | 1,553 | java | Java | src/main/java/com/wyh2020/fstore/base/util/OrderByUtil.java | wyh2020/fstore-platform | 337d2997aad6071429aaf5b1fcb54158f036ee38 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/wyh2020/fstore/base/util/OrderByUtil.java | wyh2020/fstore-platform | 337d2997aad6071429aaf5b1fcb54158f036ee38 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/wyh2020/fstore/base/util/OrderByUtil.java | wyh2020/fstore-platform | 337d2997aad6071429aaf5b1fcb54158f036ee38 | [
"Apache-2.0"
] | null | null | null | 31.06 | 108 | 0.520927 | 7,824 | package com.wyh2020.fstore.base.util;
import com.wyh2020.fstore.base.form.SortInfo;
import org.apache.commons.lang3.StringUtils;
import java.util.List;
import java.util.Map;
/**
* Created by hzh on 2018/3/31.
*/
public class OrderByUtil {
/**
* 获得排序字段
* @param sortInfoList
* @param orderByField
* @return
*/
public static String getOrderBy(List<SortInfo> sortInfoList , Map<String,String> orderByField) {
StringBuffer orderBy = new StringBuffer();
if (sortInfoList != null && sortInfoList.size() != 0){
for (int i = 0 ; i < sortInfoList.size() ; i++){
SortInfo sortInfo = sortInfoList.get(i);
String feild = orderByField.get(sortInfo.getField());
if (StringUtils.isBlank(feild)){
continue;
}
orderBy.append(feild);
orderBy.append(" ");
String sort;
if (StringUtils.isBlank(sortInfo.getSort())) {
sort = "ASC";
} else if (sortInfo.getSort().equalsIgnoreCase("DESC")) {
sort = "DESC";
} else if (sortInfo.getSort().equalsIgnoreCase("ASC")) {
sort = "ASC";
} else {
sort = "ASC";
}
orderBy.append(sort).append(",");
}
return StringUtils.isBlank(orderBy.toString()) ? null : orderBy.substring(0,orderBy.length()-1);
}
return null;
}
}
|
3e12929ab2c7314068d9e72210715d482e397184 | 1,084 | java | Java | src/main/java/com/exasol/projectkeeper/validators/changesfile/ExasolVersionMatcher.java | exasol/project-keeper-maven-plugin | 0cfb69e272e62044ac1cffa41119aca84ed67e72 | [
"MIT"
] | 1 | 2021-09-10T15:45:46.000Z | 2021-09-10T15:45:46.000Z | src/main/java/com/exasol/projectkeeper/validators/changesfile/ExasolVersionMatcher.java | exasol/project-keeper-maven-plugin | 0cfb69e272e62044ac1cffa41119aca84ed67e72 | [
"MIT"
] | 248 | 2020-09-28T10:31:52.000Z | 2022-03-28T07:27:22.000Z | src/main/java/com/exasol/projectkeeper/validators/changesfile/ExasolVersionMatcher.java | exasol/project-keeper-maven-plugin | 0cfb69e272e62044ac1cffa41119aca84ed67e72 | [
"MIT"
] | 3 | 2021-04-17T09:38:36.000Z | 2021-11-25T09:11:58.000Z | 32.848485 | 107 | 0.682657 | 7,825 | package com.exasol.projectkeeper.validators.changesfile;
import java.util.regex.Pattern;
/**
* This class matches version numbers in the format used for Exasol open-source projects (major.minor.fix).
*/
public class ExasolVersionMatcher {
private static final Pattern EXASOL_VERSION_PATTERN = Pattern.compile("\\d+\\.\\d+\\.\\d+");
/** Suffix for snapshot versions. */
public static final String SNAPSHOT_SUFFIX = "-SNAPSHOT";
/**
* Match version numbers in the format used for Exasol open-source projects (major.minor.fix).
*
* @param tag string to match
* @return {@code true} if string matches the format
*/
public boolean isExasolStyleVersion(final String tag) {
return EXASOL_VERSION_PATTERN.matcher(tag).matches();
}
/**
* Check if a given version string is a snapshot version.
*
* @param version version string
* @return {@code true if it's a snapshot version}
*/
public boolean isSnapshotVersion(final String version) {
return version.endsWith(SNAPSHOT_SUFFIX);
}
}
|
3e1292a53683efec4045f7863e0cf93ca5118408 | 1,873 | java | Java | board/board-service/src/main/java/com/welab/wefe/board/service/api/project/job/StopJobApi.java | rinceyuan/WeFe | 8482cb737cb7ba37b2856d184cd42c1bd35a6318 | [
"Apache-2.0"
] | 39 | 2021-10-12T01:43:27.000Z | 2022-03-28T04:46:35.000Z | board/board-service/src/main/java/com/welab/wefe/board/service/api/project/job/StopJobApi.java | rinceyuan/WeFe | 8482cb737cb7ba37b2856d184cd42c1bd35a6318 | [
"Apache-2.0"
] | 6 | 2021-10-14T02:11:47.000Z | 2022-03-23T02:41:50.000Z | board/board-service/src/main/java/com/welab/wefe/board/service/api/project/job/StopJobApi.java | rinceyuan/WeFe | 8482cb737cb7ba37b2856d184cd42c1bd35a6318 | [
"Apache-2.0"
] | 10 | 2021-10-14T09:36:03.000Z | 2022-02-10T11:05:12.000Z | 32.859649 | 80 | 0.72771 | 7,826 | /**
* Copyright 2021 Tianmian Tech. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.welab.wefe.board.service.api.project.job;
import com.welab.wefe.board.service.service.ProjectFlowJobService;
import com.welab.wefe.common.exception.StatusCodeWithException;
import com.welab.wefe.common.fieldvalidate.annotation.Check;
import com.welab.wefe.common.web.api.base.AbstractNoneOutputApi;
import com.welab.wefe.common.web.api.base.Api;
import com.welab.wefe.common.web.dto.AbstractApiInput;
import com.welab.wefe.common.web.dto.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @author zane.luo
*/
@Api(path = "flow/job/stop", name = "Pause the project process flow task")
public class StopJobApi extends AbstractNoneOutputApi<StopJobApi.Input> {
@Autowired
ProjectFlowJobService projectFlowJobService;
@Override
protected ApiResult<?> handler(Input input) throws StatusCodeWithException {
projectFlowJobService.stopFlowJob(input);
return success();
}
public static class Input extends AbstractApiInput {
@Check(name = "任务id", require = true)
private String jobId;
public String getJobId() {
return jobId;
}
public void setJobId(String jobId) {
this.jobId = jobId;
}
}
}
|
3e129302531f6a7f0a0df89814717512b85c6e42 | 328 | java | Java | android/android/app/src/main/java/jeffreychang/xyz/servicecom_android_challenge/ui/users/UserViewHolder.java | jeffchang5/Service.com-Android | 178391e4472f1fc5f4d0059630203832d2f37183 | [
"Unlicense",
"MIT"
] | null | null | null | android/android/app/src/main/java/jeffreychang/xyz/servicecom_android_challenge/ui/users/UserViewHolder.java | jeffchang5/Service.com-Android | 178391e4472f1fc5f4d0059630203832d2f37183 | [
"Unlicense",
"MIT"
] | null | null | null | android/android/app/src/main/java/jeffreychang/xyz/servicecom_android_challenge/ui/users/UserViewHolder.java | jeffchang5/Service.com-Android | 178391e4472f1fc5f4d0059630203832d2f37183 | [
"Unlicense",
"MIT"
] | null | null | null | 20.5 | 64 | 0.710366 | 7,827 | package jeffreychang.xyz.servicecom_android_challenge.ui.users;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* Created by chang on 6/6/2017.
*/
class UserViewHolder extends RecyclerView.ViewHolder {
public UserViewHolder(View itemView) {
super(itemView);
}
}
|
3e12932674e7a0cac1a5d1286df001ba4cd12828 | 2,808 | java | Java | app/src/androidTest/java/com/macaca/android/testing/server/xmlUtils/UiElement.java | qddegtya/UIAutomatorWD | ed21ca9f886b29b5c2016cde153a2a8e764c0afb | [
"MIT"
] | 54 | 2017-05-03T13:32:50.000Z | 2022-03-18T03:03:23.000Z | app/src/androidTest/java/com/macaca/android/testing/server/xmlUtils/UiElement.java | qddegtya/UIAutomatorWD | ed21ca9f886b29b5c2016cde153a2a8e764c0afb | [
"MIT"
] | 32 | 2017-05-05T17:11:22.000Z | 2020-04-26T03:24:50.000Z | app/src/androidTest/java/com/macaca/android/testing/server/xmlUtils/UiElement.java | qddegtya/UIAutomatorWD | ed21ca9f886b29b5c2016cde153a2a8e764c0afb | [
"MIT"
] | 24 | 2017-05-08T12:42:01.000Z | 2021-04-02T05:44:00.000Z | 24.206897 | 80 | 0.649573 | 7,828 | package com.macaca.android.testing.server.xmlUtils;
/**
* Created by xdf on 09/05/2017.
*/
import android.graphics.Rect;
import android.view.accessibility.AccessibilityNodeInfo;
import java.util.List;
import java.util.Map;
/**
* UiElement that implements the common operations.
*
* @param <R> the type of the raw element this class wraps, for example, View or
* AccessibilityNodeInfo
* @param <E> the type of the concrete subclass of UiElement
*/
public abstract class UiElement<R, E extends UiElement<R, E>> {
public AccessibilityNodeInfo node;
@SuppressWarnings("unchecked")
public <T> T get(Attribute attribute) {
return (T) getAttributes().get(attribute);
}
public String getText() {
return get(Attribute.TEXT);
}
public String getContentDescription() {
return get(Attribute.CONTENT_DESC);
}
public String getClassName() {
return get(Attribute.CLASS);
}
public String getResourceId() {
return get(Attribute.RESOURCE_ID);
}
public String getPackageName() {
return get(Attribute.PACKAGE);
}
public boolean isCheckable() {
return (Boolean) get(Attribute.CHECKABLE);
}
public boolean isChecked() {
return (Boolean) get(Attribute.CHECKED);
}
public boolean isClickable() {
return (Boolean) get(Attribute.CLICKABLE);
}
public boolean isEnabled() {
return (Boolean) get(Attribute.ENABLED);
}
public boolean isFocusable() {
return (Boolean) get(Attribute.FOCUSABLE);
}
public boolean isFocused() {
return (Boolean) get(Attribute.FOCUSED);
}
public boolean isScrollable() {
return (Boolean) get(Attribute.SCROLLABLE);
}
public boolean isLongClickable() {
return (Boolean) get(Attribute.LONG_CLICKABLE);
}
public boolean isPassword() {
return (Boolean) get(Attribute.PASSWORD);
}
public boolean isSelected() {
return (Boolean) get(Attribute.SELECTED);
}
public int getIndex() { return (Integer)get(Attribute.INDEX); }
protected abstract List<E> getChildren();
public Rect getBounds() {
return get(Attribute.BOUNDS);
}
public int getSelectionStart() {
Integer value = get(Attribute.SELECTION_START);
return value == null ? 0 : value;
}
public int getSelectionEnd() {
Integer value = get(Attribute.SELECTION_END);
return value == null ? 0 : value;
}
public boolean hasSelection() {
final int selectionStart = getSelectionStart();
final int selectionEnd = getSelectionEnd();
return selectionStart >= 0 && selectionStart != selectionEnd;
}
protected abstract Map<Attribute, Object> getAttributes();
} |
3e129347a9597a2e93d9260fa30d62aeab91f89f | 2,784 | java | Java | src/main/java/edu/unh/artt/core/error_sample/representation/OffsetGmSample.java | BrandonSmith68/ARTT-Core | 97ce3a794e47f1c3f84408e04e25ba4551f74917 | [
"MIT"
] | null | null | null | src/main/java/edu/unh/artt/core/error_sample/representation/OffsetGmSample.java | BrandonSmith68/ARTT-Core | 97ce3a794e47f1c3f84408e04e25ba4551f74917 | [
"MIT"
] | null | null | null | src/main/java/edu/unh/artt/core/error_sample/representation/OffsetGmSample.java | BrandonSmith68/ARTT-Core | 97ce3a794e47f1c3f84408e04e25ba4551f74917 | [
"MIT"
] | null | null | null | 28.701031 | 136 | 0.660201 | 7,829 | package edu.unh.artt.core.error_sample.representation;
import org.apache.commons.codec.binary.Hex;
import java.util.List;
import java.util.stream.Collectors;
/**
* Represents the offsetFromGm time error measurement. This is the result of a comparison between received Sync messages
* from the grandmaster and link partners being monitored.
*/
public class OffsetGmSample implements TimeErrorSample {
/* The computed offsetFromGm time error metric */
final double offset_from_gm;
/* ID of the node this metric was generated for. Note that this will be 'empty' for re-sampled data since the
* clockId of a sample is not a computed metric. This field is only useful for outliers. */
final byte [] clock_identity;
/* Network representation of this sample */
final long weight;
/* When the offset was recorded in the timebase of the receiver */
final long timestamp;
/**
* @see OffsetGmSample#OffsetGmSample(long, long, double, byte[] empty)
*/
public OffsetGmSample(long timestamp, long weight, double offsetFromGmScaled) {
this(timestamp, weight, offsetFromGmScaled, new byte[8]);
}
/**
* @param weight Network representation of the sample
* @param offsetFromGmScaled Computed offset metric
* @param clockId clock identity that the sample is associated with
*/
public OffsetGmSample(long timestamp, long weight, double offsetFromGmScaled, byte [] clockId) {
offset_from_gm = offsetFromGmScaled;
clock_identity = clockId;
this.timestamp = timestamp;
this.weight = weight;
}
@Override
public List<OffsetGmSample> parseSamples(List<double[]> sampleData) {
return sampleData.stream().map(darr -> new OffsetGmSample(System.currentTimeMillis(), 1, darr[0])).collect(Collectors.toList());
}
/**
* @return Computed offsetFromGm sample
*/
@Override
public double[] getSample() {
return new double[] {offset_from_gm};
}
/**
* @return Network representation of the sample
*/
@Override
public long getWeight() {
return weight;
}
/**
* @see TimeErrorSample#getTimestamp()
*/
@Override
public long getTimestamp() {
return timestamp;
}
/**
* @return Identification for the source of the data
*/
@Override
public String getIdentifier() {
return Hex.encodeHexString(clock_identity) + "; " + offset_from_gm +"ns; " + weight + "nodes;";
}
/**
* @return Clock identity associated with this
*/
public byte [] getClockIdentity() {
return clock_identity;
}
/**
* @return 1 dimension
*/
@Override
public int getNumDimensions() {
return 1;
}
}
|
3e12936144b563a6388c3723b0f8aaf890453c58 | 1,066 | java | Java | src/main/java/de/up/ling/irtg/codec/CodecMetadata.java | dmhowcroft/alto | 9670ce1261b06158854c0b730a49974395397b5f | [
"Apache-2.0"
] | 10 | 2019-07-30T12:16:06.000Z | 2021-09-03T14:34:06.000Z | src/main/java/de/up/ling/irtg/codec/CodecMetadata.java | dmhowcroft/alto | 9670ce1261b06158854c0b730a49974395397b5f | [
"Apache-2.0"
] | 37 | 2019-04-03T14:07:05.000Z | 2021-12-21T15:18:23.000Z | src/main/java/de/up/ling/irtg/codec/CodecMetadata.java | dmhowcroft/alto | 9670ce1261b06158854c0b730a49974395397b5f | [
"Apache-2.0"
] | 2 | 2020-06-26T11:38:38.000Z | 2020-07-10T15:37:37.000Z | 30.457143 | 79 | 0.743902 | 7,830 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package de.up.ling.irtg.codec;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* An annotation type for adding metadata to a codec class.
* Each codec class must be annotated with CodecMetadata in order
* to be registered with the <code>CodecManager</code>. Use this
* annotation to specify a name and extension for the codec.
* You may optionally annotate a codec as "experimental=true" to
* mark it as experimental. (From Utool.)
*
* @author Alexander Koller
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface CodecMetadata {
String name();
String description();
String extension() default "";
Class type();
boolean displayInPopup() default true;
boolean experimental() default false;
}
|
3e1293915e04a14b2356d4529b7a6520326435e3 | 3,798 | java | Java | feilong-core/src/main/java/com/feilong/core/util/closure/BeanPropertyValueChangeClosure.java | venusdrogon/feilong | 6e5809373fb0c53c0cd26e40985ab40cd06e01f7 | [
"Apache-2.0"
] | 47 | 2020-05-25T15:06:16.000Z | 2022-03-25T09:28:37.000Z | feilong-core/src/main/java/com/feilong/core/util/closure/BeanPropertyValueChangeClosure.java | ifeilong/feilong | d59ae9a98924b902e9604b98c3ea24b461bb6b36 | [
"Apache-2.0"
] | 232 | 2020-04-22T14:19:44.000Z | 2021-08-24T11:50:49.000Z | feilong-core/src/main/java/com/feilong/core/util/closure/BeanPropertyValueChangeClosure.java | venusdrogon/feilong | 6e5809373fb0c53c0cd26e40985ab40cd06e01f7 | [
"Apache-2.0"
] | 19 | 2020-05-07T02:57:12.000Z | 2022-03-15T02:26:48.000Z | 31.915966 | 112 | 0.642707 | 7,831 | /*
* Copyright (C) 2008 feilong
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.feilong.core.util.closure;
import org.apache.commons.collections4.Closure;
import com.feilong.core.Validate;
import com.feilong.core.bean.PropertyUtil;
/**
* {@link org.apache.commons.collections4.Closure} 实现,用来更新指定属性的指定值.
* <h3>构造函数:</h3>
*
* <blockquote>
*
* BeanPropertyValueChangeClosure 构造函数提供两个参数, 属性名称和指定的属性值
*
* <pre class="code">
* public BeanPropertyValueChangeClosure(String propertyName, Object propertyValue)
* </pre>
*
* <b>注意:</b> Possibly indexed and/or nested name of the property to be
* modified,参见<a href="../../bean/BeanUtil.html#propertyName">propertyName</a>.
* </blockquote>
*
* <h3>典型的使用示例:</h3>
*
* <blockquote>
*
* <pre class="code">
* // create the closure
* BeanPropertyValueChangeClosure closure = new BeanPropertyValueChangeClosure("activeEmployee", Boolean.TRUE);
*
* // update the Collection
* CollectionUtils.forAllDo(peopleCollection, closure);
* </pre>
*
* 上面的示例将会提取 <code>peopleCollection</code> 的每个 person 对象, 并且更新<code>activeEmployee</code> 属性值为<code>true</code>.
*
* </blockquote>
*
* @author <a href="https://github.com/ifeilong/feilong">feilong</a>
* @param <T>
* the generic type
* @see "org.apache.commons.beanutils.BeanPropertyValueChangeClosure"
* @see "org.apache.commons.collections4.CollectionUtils#forAllDo(Iterable, Closure)"
* @see "org.apache.commons.collections4.IterableUtils#forEach(Iterable, Closure)"
* @since 1.10.2
*/
public class BeanPropertyValueChangeClosure<T> implements Closure<T>{
/**
* 指定bean对象排序属性名字.
*
* <p>
* 泛型T对象指定的属性名称,Possibly indexed and/or nested name of the property to be modified,参见
* <a href="../../bean/BeanUtil.html#propertyName">propertyName</a>
* </p>
*/
private final String propertyName;
/** 指定的属性值. */
private final Object propertyValue;
//---------------------------------------------------------------
/**
* Instantiates a new bean property value change closure.
*
* <p>
* 如果 <code>propertyName</code> 是null,抛出 {@link NullPointerException}<br>
* 如果 <code>propertyName</code> 是blank,抛出 {@link IllegalArgumentException}<br>
* </p>
*
* @param propertyName
* 指定bean对象排序属性名字.
* <p>
* 泛型T对象指定的属性名称,Possibly indexed and/or nested name of the property to be modified,参见
* <a href="../../bean/BeanUtil.html#propertyName">propertyName</a>
* </p>
* @param propertyValue
* the value
*/
public BeanPropertyValueChangeClosure(String propertyName, Object propertyValue){
Validate.notBlank(propertyName, "propertyName can't be blank!");
this.propertyName = propertyName;
this.propertyValue = propertyValue;
}
//---------------------------------------------------------------
/*
* (non-Javadoc)
*
* @see org.apache.commons.collections4.Closure#execute(java.lang.Object)
*/
@Override
public void execute(T input){
if (null == input){//如果 input是null,跳过去
return;
}
PropertyUtil.setProperty(input, propertyName, propertyValue);
}
}
|
3e1293978f85224fc6e99d3c5cb797a144b0cde6 | 5,978 | java | Java | framework/security/src/org/ofbiz/security/SecurityFactory.java | javedabdulkadir/http-svn.apache.org-repos-asf-ofbiz-branches-release16.11- | bc0b461379a864bc5c11301e8c027fe7fb57565f | [
"Apache-2.0"
] | 13 | 2019-01-31T06:32:54.000Z | 2020-07-22T07:44:39.000Z | framework/security/src/org/ofbiz/security/SecurityFactory.java | javedabdulkadir/http-svn.apache.org-repos-asf-ofbiz-branches-release16.11- | bc0b461379a864bc5c11301e8c027fe7fb57565f | [
"Apache-2.0"
] | 1 | 2016-03-20T18:11:42.000Z | 2016-03-20T18:11:42.000Z | framework/security/src/org/ofbiz/security/SecurityFactory.java | javedabdulkadir/http-svn.apache.org-repos-asf-ofbiz-branches-release16.11- | bc0b461379a864bc5c11301e8c027fe7fb57565f | [
"Apache-2.0"
] | 12 | 2019-01-28T01:51:37.000Z | 2021-12-26T10:31:40.000Z | 44.61194 | 193 | 0.67096 | 7,832 | /*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.security;
import org.ofbiz.base.config.GenericConfigException;
import org.ofbiz.base.config.SecurityConfigUtil;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.w3c.dom.Element;
/**
* <code>SecurityFactory</code>
*
* This Factory class returns an instance of a security implementation.
*
* Setting the security implementation className is done in security.xml.
* If no customiz security name is given, the default implementation will be used (OFBizSecurity)
*/
public class SecurityFactory {
public static final String module = SecurityFactory.class.getName();
public static final String DEFAULT_SECURITY = "org.ofbiz.security.OFBizSecurity";
private static String securityName = null;
private static Element rootElement = null;
private static SecurityConfigUtil.SecurityInfo securityInfo = null;
/**
* Returns an instance of a Security implementation as defined in the security.xml by defined name
* in security.properties.
*
* @param delegator the generic delegator
* @return instance of security implementation (default: OFBizSecurity)
*/
public static Security getInstance(Delegator delegator) throws SecurityConfigurationException {
Security security = null;
// Make securityName a singleton
if (securityName == null) {
String _securityName = UtilProperties.getPropertyValue("security.properties", "security.context");
securityName = _securityName;
}
if (Debug.verboseOn()) Debug.logVerbose("[SecurityFactory.getInstance] Security implementation context name from security.properties: " + securityName, module);
synchronized (SecurityFactory.class) {
try {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Class<?> c = loader.loadClass(getSecurityClass(securityName));
security = (Security) c.newInstance();
security.setDelegator(delegator);
} catch (ClassNotFoundException cnf) {
throw new SecurityConfigurationException("Cannot load security implementation class", cnf);
} catch (InstantiationException ie) {
throw new SecurityConfigurationException("Cannot get instance of the security implementation", ie);
} catch (IllegalAccessException iae) {
throw new SecurityConfigurationException(iae.getMessage(), iae);
}
}
if (Debug.verboseOn()) Debug.logVerbose("[SecurityFactory.getInstance] Security implementation successfully loaded!!!", module);
return security;
}
/**
* Returns the class name of a custom Security implementation.
* The default class name (org.ofbiz.security.OFBizSecurity) may be overridden by a customized implementation
* class name in security.xml.
*
* @param securityName the security context name to be looked up
* @return className the class name of the security implementatin
* @throws SecurityConfigurationException
*/
private static String getSecurityClass(String securityName) throws SecurityConfigurationException {
String className = null;
if (Debug.verboseOn())
Debug.logVerbose("[SecurityFactory.getSecurityClass] Security implementation context name: " + securityName, module);
// Only load rootElement again, if not yet loaded (singleton)
if (rootElement == null) {
try {
SecurityConfigUtil.getXmlDocument();
Element _rootElement = SecurityConfigUtil.getXmlRootElement();
rootElement = _rootElement;
} catch (GenericConfigException e) {
Debug.logError(e, "Error getting Security Config XML root element", module);
return null;
}
}
if (securityInfo == null) {
SecurityConfigUtil.SecurityInfo _securityInfo = SecurityConfigUtil.getSecurityInfo(securityName);
// Make sure, that the security conetxt name is defined and present
if (_securityInfo == null) {
throw new SecurityConfigurationException("ERROR: no security definition was found with the name " + securityName + " in security.xml");
}
securityInfo = _securityInfo;
}
// This is the default implementation and uses org.ofbiz.security.OFBizSecurity
if (UtilValidate.isEmpty(securityInfo.className)) {
className = DEFAULT_SECURITY;
} else {
// Use a customized security
className = securityInfo.className;
}
if (Debug.verboseOn()) Debug.logVerbose("[SecurityFactory.getSecurity] Security implementation " + className + " for security name " + securityName + " successfully loaded!!!", module);
return className;
}
}
|
3e12940e55743962261721c064ebc46b6160ba2b | 2,532 | java | Java | src/test/java/org/psidnell/omnifocus/integrationtest/Diff.java | psidnell/ofexport2 | 07cbb0c1b200111547b9d645477c4f9c757a3126 | [
"Apache-2.0"
] | 122 | 2015-01-04T18:12:24.000Z | 2021-12-15T11:50:30.000Z | src/test/java/org/psidnell/omnifocus/integrationtest/Diff.java | psidnell/ofexport2 | 07cbb0c1b200111547b9d645477c4f9c757a3126 | [
"Apache-2.0"
] | 10 | 2015-01-05T06:49:31.000Z | 2017-11-06T19:58:58.000Z | src/test/java/org/psidnell/omnifocus/integrationtest/Diff.java | psidnell/ofexport2 | 07cbb0c1b200111547b9d645477c4f9c757a3126 | [
"Apache-2.0"
] | 16 | 2015-02-18T04:20:21.000Z | 2020-04-24T05:45:52.000Z | 32.461538 | 89 | 0.607425 | 7,833 | /*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.integrationtest;
import static org.junit.Assert.assertEquals;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Diff {
static Logger LOGGER = LoggerFactory.getLogger(Diff.class);
public static void diff(File expectedFile, File actualFile) throws IOException {
try (
BufferedReader expectedIn = new BufferedReader(new FileReader(expectedFile));
BufferedReader actualIn = new BufferedReader(new FileReader(actualFile));) {
int line = 1;
String expected = expectedIn.readLine();
String actual = actualIn.readLine();
while (Diff.diff (expected, actual, line)) {
expected = expectedIn.readLine();
actual = actualIn.readLine();
line++;
}
}
}
public static void diff(String[] expected, String[] actual) {
int i;
for (i = 0; i < expected.length && i < actual.length; i++) {
diff (expected[i], actual[i], i+1);
}
if (expected.length > actual.length) {
diff (expected[i], null, i+1);
}
else if (expected.length < actual.length) {
diff (null, actual[i], i+1);
}
}
public static boolean diff(String expected, String actual, int line) {
if (expected != null && actual != null && !expected.equals(actual)) {
LOGGER.error("Error on line " + line);
LOGGER.error("Expected: " + expected);
LOGGER.error("Actual: " + actual);
}
String message = "Error on line " + line + " " + expected + " != " + actual;
assertEquals (message, expected, actual);
return expected != null;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.