index int64 | repo_id string | file_path string | content string |
|---|---|---|---|
0 | java-sources/am/ik/categolj3/categolj3-api/1.0.0.M6/am/ik/categolj3/api | java-sources/am/ik/categolj3/categolj3-api/1.0.0.M6/am/ik/categolj3/api/jest/JestSearchEntryOperations.java | /*
* Copyright (C) 2015 Toshiaki Maki <makingx@gmail.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 am.ik.categolj3.api.jest;
import am.ik.categolj3.api.entry.Entry;
import am.ik.categolj3.api.entry.SearchEntryOperations;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.Count;
import io.searchbox.core.Search;
import io.searchbox.indices.CreateIndex;
import io.searchbox.indices.IndicesExists;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.List;
@Component
@Slf4j
public class JestSearchEntryOperations implements SearchEntryOperations {
@Autowired
JestClient jestClient;
final String[] fieldsExcludeContent = new String[]{
"entryId",
"created.name",
"created.date",
"updated.name",
"updated.date",
"frontMatter.title",
"frontMatter.tags",
"frontMatter.categories"};
@Override
public Page<Entry> findAll(Pageable pageable, SearchOptions options) {
QueryBuilder query = QueryBuilders.matchAllQuery();
return search(query, pageable, options);
}
@Override
public Page<Entry> findByTag(String tag, Pageable pageable, SearchOptions options) {
QueryBuilder query = QueryBuilders.matchQuery("frontMatter.tags", tag)
.operator(MatchQueryBuilder.Operator.AND);
return search(query, pageable, options);
}
@Override
public Page<Entry> findByCategories(List<String> categories, Pageable pageable, SearchOptions options) {
QueryBuilder query = QueryBuilders.matchQuery("frontMatter.categories", categories)
.operator(MatchQueryBuilder.Operator.AND);
return search(query, pageable, options);
}
@Override
public Page<Entry> findByCreatedBy(String user, Pageable pageable, SearchOptions options) {
QueryBuilder query = QueryBuilders.matchQuery("created.name", user)
.operator(MatchQueryBuilder.Operator.AND);
return search(query, pageable, options);
}
@Override
public Page<Entry> findByUpdatedBy(String user, Pageable pageable, SearchOptions options) {
QueryBuilder query = QueryBuilders.matchQuery("updated.name", user)
.operator(MatchQueryBuilder.Operator.AND);
return search(query, pageable, options);
}
@Override
public Page<Entry> findByQuery(String q, Pageable pageable, SearchOptions options) {
QueryBuilder query = QueryBuilders.simpleQueryStringQuery(q);
return search(query, pageable, options);
}
Page<Entry> search(QueryBuilder query, Pageable pageable, SearchOptions options) {
try {
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder()
.query(query)
.sort("updated.date", SortOrder.DESC)
.sort("entryId", SortOrder.DESC)
.from(pageable.getOffset())
.size(pageable.getPageSize());
if (options.isExcludeContent()) {
sourceBuilder = sourceBuilder.fetchSource(fieldsExcludeContent, new String[]{"content"});
}
long count = jestClient.execute(
new Count.Builder()
.query(new SearchSourceBuilder()
.query(query).toString())
.addIndex(Entry.INDEX_NAME)
.addType(Entry.DOC_TYPE)
.build())
.getCount().longValue();
List<Entry> content = null;
if (count > 0) {
content = ((JestResult) jestClient.execute(
new Search.Builder(sourceBuilder.toString())
.addIndex(Entry.INDEX_NAME)
.addType(Entry.DOC_TYPE)
.build()))
.getSourceAsObjectList(Entry.class);
} else {
content = Collections.emptyList();
}
return new PageImpl<>(content, pageable, count);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
@PostConstruct
void init() throws Exception {
IndicesExists indicesExists = new IndicesExists.Builder(Entry.INDEX_NAME)
.build();
JestResult result = jestClient.execute(indicesExists);
if (!result.isSucceeded()) {
log.info("Create index {} ...", Entry.INDEX_NAME);
// Create articles index
CreateIndex createIndex = new CreateIndex.Builder(Entry.INDEX_NAME)
.build();
String json = jestClient.execute(createIndex).getJsonString();
log.info("Created index {}", json);
}
}
}
|
0 | java-sources/am/ik/categolj3/categolj3-api/1.0.0.M6/am/ik/categolj3/api | java-sources/am/ik/categolj3/categolj3-api/1.0.0.M6/am/ik/categolj3/api/jest/JestSync.java | /*
* Copyright (C) 2015 Toshiaki Maki <makingx@gmail.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 am.ik.categolj3.api.jest;
import am.ik.categolj3.api.event.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import java.util.stream.Collectors;
@Component
@Slf4j
public class JestSync {
@Autowired
JestIndexer indexer;
@Autowired
JestProperties jestProperties;
@Autowired
EventManager eventManager;
@EventListener
public void handleBulkDelete(EntryEvictEvent.Bulk e) {
AppState state = eventManager.getState();
if (state == AppState.INITIALIZED || jestProperties.isInit()) {
if (log.isInfoEnabled()) {
log.info("Bulk delete ({})", e.getEvents().size());
}
try {
indexer.bulkDelete(e.getEvents().stream().map(EntryEvictEvent::getEntryId).collect(Collectors.toList()));
} catch (Exception ex) {
log.warn("Failed to bulk delete", ex);
e.getEvents().forEach(eventManager::registerEntryEvictEvent);
}
} else {
if (log.isInfoEnabled()) {
log.info("Skip to bulk delete (status={},jest.init={})", state, jestProperties.isInit());
}
}
}
@EventListener
public void handleBulkUpdate(EntryPutEvent.Bulk e) {
AppState state = eventManager.getState();
if (state == AppState.INITIALIZED || jestProperties.isInit()) {
if (log.isInfoEnabled()) {
log.info("Bulk update ({})", e.getEvents().size());
}
try {
indexer.bulkUpdate(e.getEvents().stream().map(EntryPutEvent::getEntry).collect(Collectors.toList()));
} catch (Exception ex) {
log.warn("Failed to bulk update", ex);
e.getEvents().forEach(eventManager::registerEntryPutEvent);
}
} else {
if (log.isInfoEnabled()) {
log.info("Skip to bulk update (status={},jest.init={})", state, jestProperties.isInit());
}
}
}
@EventListener
public void handleReindex(EntryReIndexEvent e) {
indexer.reindex();
}
}
|
0 | java-sources/am/ik/categolj3/categolj3-api/1.0.0.M6/am/ik/categolj3/api | java-sources/am/ik/categolj3/categolj3-api/1.0.0.M6/am/ik/categolj3/api/tag/InMemoryTagService.java | /*
* Copyright (C) 2015 Toshiaki Maki <makingx@gmail.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 am.ik.categolj3.api.tag;
import am.ik.categolj3.api.entry.Entry;
import am.ik.categolj3.api.event.EntryEvictEvent;
import am.ik.categolj3.api.event.EntryPutEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.util.CollectionUtils;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;
@Slf4j
public class InMemoryTagService implements TagService {
private final ConcurrentMap<Long, List<String>> tags = new ConcurrentHashMap<>();
@EventListener
public void handlePutEntry(EntryPutEvent.Bulk event) {
if (log.isInfoEnabled()) {
log.info("bulk put ({})", event.getEvents().size());
}
tags.putAll(event.getEvents().stream()
.map(EntryPutEvent::getEntry)
.filter(e -> !CollectionUtils.isEmpty(e.getFrontMatter().getTags()))
.collect(Collectors.toMap(Entry::getEntryId, e -> e.getFrontMatter().getTags())));
}
@EventListener
public void handleEvictEntry(EntryEvictEvent.Bulk event) {
if (log.isInfoEnabled()) {
log.info("bulk evict ({})", event.getEvents().size());
}
event.getEvents().forEach(e -> tags.remove(e.getEntryId()));
}
@Override
public List<String> findAllOrderByNameAsc() {
return this.tags.values().stream()
.flatMap(Collection::stream)
.distinct()
.sorted()
.collect(Collectors.toList());
}
}
|
0 | java-sources/am/ik/categolj3/categolj3-api/1.0.0.M6/am/ik/categolj3/api | java-sources/am/ik/categolj3/categolj3-api/1.0.0.M6/am/ik/categolj3/api/tag/TagRestController.java | /*
* Copyright (C) 2015 Toshiaki Maki <makingx@gmail.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 am.ik.categolj3.api.tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping(path = "api")
public class TagRestController {
@Autowired
TagService tagService;
@RequestMapping(path = "tags", method = RequestMethod.GET)
List<String> list() {
return tagService.findAllOrderByNameAsc();
}
}
|
0 | java-sources/am/ik/categolj3/categolj3-api/1.0.0.M6/am/ik/categolj3/api | java-sources/am/ik/categolj3/categolj3-api/1.0.0.M6/am/ik/categolj3/api/tag/TagService.java | /*
* Copyright (C) 2015 Toshiaki Maki <makingx@gmail.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 am.ik.categolj3.api.tag;
import java.util.List;
public interface TagService {
List<String> findAllOrderByNameAsc();
}
|
0 | java-sources/am/ik/certificate/certificate-importer/0.0.1/am/ik | java-sources/am/ik/certificate/certificate-importer/0.0.1/am/ik/certificate/CertificateImporter.java | package am.ik.certificate;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
public class CertificateImporter {
private AtomicBoolean imported = new AtomicBoolean(false);
private static final Logger log = Logger.getLogger(CertificateImporter.class.getName());
public void doImport(String... pemFiles) throws GeneralSecurityException, IOException {
CertificateFactory fact = CertificateFactory.getInstance("X.509");
List<Certificate> certificates = new ArrayList<>();
for (String pemFile : pemFiles) {
Certificate certificate = fact.generateCertificate(new ByteArrayInputStream(pemFile.getBytes()));
certificates.add(certificate);
}
this.doImport(certificates);
}
public void doImport(List<Certificate> certificates) throws GeneralSecurityException, IOException {
if (imported.get()) {
log.log(Level.WARNING, "Certificates have already been imported!");
return;
}
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null); // init empty keystore
int count = 0;
for (Certificate certificate : certificates) {
String alias = "import" + (count++);
log.log(Level.INFO, "Importing " + alias + "/" + certificate.getType());
trustStore.setCertificateEntry(alias, certificate);
}
String password = UUID.randomUUID().toString();
File trustStoreOutputFile = File.createTempFile("truststore", null);
trustStoreOutputFile.deleteOnExit();
trustStore.store(new FileOutputStream(trustStoreOutputFile), password.toCharArray());
System.setProperty("javax.net.ssl.trustStore", trustStoreOutputFile.getAbsolutePath());
System.setProperty("javax.net.ssl.trustStorePassword", password);
imported.set(true);
}
}
|
0 | java-sources/am/ik/certificate/certificate-importer/0.0.1/am/ik/certificate | java-sources/am/ik/certificate/certificate-importer/0.0.1/am/ik/certificate/spring/CertificateImporterApplicationContextInitializer.java | package am.ik.certificate.spring;
import am.ik.certificate.CertificateImporter;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import java.util.logging.Level;
import java.util.logging.Logger;
public class CertificateImporterApplicationContextInitializer
implements ApplicationContextInitializer<ConfigurableApplicationContext> {
private static final Logger log = Logger.getLogger(CertificateImporterApplicationContextInitializer.class.getName());
@Override
public void initialize(ConfigurableApplicationContext context) {
CertificateImporter certificateImporter = new CertificateImporter();
String[] caCerts = context.getEnvironment().getProperty("ca.certs", String[].class);
if (caCerts != null && caCerts.length > 0) {
try {
certificateImporter.doImport(caCerts);
} catch (Exception e) {
log.log(Level.WARNING, e, () -> "Failed to import certificate.");
}
}
}
}
|
0 | java-sources/am/ik/csng/csng/0.4.0/am/ik | java-sources/am/ik/csng/csng/0.4.0/am/ik/csng/CompileSafeName.java | /*
* Copyright (C) 2020 Toshiaki Maki <makingx@gmail.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 am.ik.csng;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.SOURCE)
public @interface CompileSafeName {
}
|
0 | java-sources/am/ik/csng/csng/0.4.0/am/ik | java-sources/am/ik/csng/csng/0.4.0/am/ik/csng/CompileSafeParameters.java | /*
* Copyright (C) 2020 Toshiaki Maki <makingx@gmail.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 am.ik.csng;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ ElementType.CONSTRUCTOR, ElementType.METHOD })
@Retention(RetentionPolicy.SOURCE)
public @interface CompileSafeParameters {
}
|
0 | java-sources/am/ik/csng/csng/0.4.0/am/ik | java-sources/am/ik/csng/csng/0.4.0/am/ik/csng/package-info.java | /*
* Copyright (C) 2020 Toshiaki Maki <makingx@gmail.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 am.ik.csng;
|
0 | java-sources/am/ik/csng/csng/0.4.0/am/ik/csng | java-sources/am/ik/csng/csng/0.4.0/am/ik/csng/processor/CompileSafeNameProcessor.java | /*
* Copyright (C) 2020 Toshiaki Maki <makingx@gmail.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 am.ik.csng.processor;
import am.ik.csng.CompileSafeName;
import am.ik.csng.CompileSafeParameters;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.*;
import javax.tools.JavaFileObject;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UncheckedIOException;
import java.time.OffsetDateTime;
import java.util.*;
import java.util.function.BiConsumer;
import static am.ik.csng.processor.CompileSafeNameTemplate.*;
import static java.util.stream.Collectors.*;
import static javax.lang.model.element.ElementKind.CLASS;
import static javax.lang.model.element.ElementKind.METHOD;
@SupportedAnnotationTypes({ "am.ik.csng.CompileSafeName",
"am.ik.csng.CompileSafeParameters" })
public class CompileSafeNameProcessor extends AbstractProcessor {
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latest();
}
@Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
for (TypeElement typeElement : annotations) {
final Name qualifiedName = typeElement.getQualifiedName();
if (qualifiedName.contentEquals(CompileSafeName.class.getName())) {
this.processTypeSafeName(typeElement, roundEnv);
}
if (qualifiedName.contentEquals(CompileSafeParameters.class.getName())) {
this.processTypeSafeParameters(typeElement, roundEnv);
}
}
return true;
}
private void processTypeSafeName(TypeElement typeElement, RoundEnvironment roundEnv) {
final Set<? extends Element> elementsAnnotatedWith = roundEnv
.getElementsAnnotatedWith(typeElement);
final Map<String, List<Pair<Element, Integer>>> elementsMap = elementsAnnotatedWith
.stream()
.filter(x -> !(x instanceof ExecutableElement)
|| ((ExecutableElement) x).getTypeParameters().isEmpty())
.map(x -> new Pair<Element, Integer>(x, -1)).collect(groupingBy(k -> {
final Element element = k.first();
return element.getEnclosingElement().toString();
}, toList()));
if (elementsMap.isEmpty()) {
return;
}
elementsMap.forEach(this::writeTypeSafeNameFile);
}
private void processTypeSafeParameters(TypeElement typeElement,
RoundEnvironment roundEnv) {
final Set<? extends Element> elementsAnnotatedWith = roundEnv
.getElementsAnnotatedWith(typeElement);
for (Element element : elementsAnnotatedWith) {
final List<Element> parameters = new ArrayList<>(
((ExecutableElement) element).getParameters());
String className = element.getEnclosingElement().toString();
if (element.getKind() == METHOD) {
parameters.add(0, element.getEnclosingElement());
className = className + upperCamel(element.getSimpleName().toString());
}
final List<Pair<Element, Integer>> pairs = parameters.stream()
.map(x -> new Pair<>(x, parameters.indexOf(x))).collect(toList());
this.writeTypeSafeParametersFile(className, pairs);
}
}
private void writeTypeSafeNameFile(String className,
List<Pair<Element, Integer>> elements) {
this.writeFile(className, "Name", elements, (pair, metas) -> {
final Element element = pair.first();
final CompileSafeName typeSafeName = element
.getAnnotation(CompileSafeName.class);
final String name = element.getSimpleName().toString();
metas.put(name, templateTarget(name));
});
}
private void writeTypeSafeParametersFile(String className,
List<Pair<Element, Integer>> elements) {
this.writeFile(className, "Parameters", elements, (pair, metas) -> {
final Element element = pair.first();
final String name = element.getSimpleName().toString();
metas.put(name,
templateTarget(element.getKind() == CLASS ? lowerCamel(name) : name));
});
}
private void writeFile(String className, String metaClassNameSuffix,
List<Pair<Element, Integer>> elements,
BiConsumer<Pair<Element, Integer>, Map<String, String>> processElement) {
final Pair<String, String> pair = splitClassName(className);
final String packageName = pair.first();
final String simpleClassName = pair.second();
final String metaSimpleClassName = "_" + simpleClassName.replace('.', '_')
+ metaClassNameSuffix;
final String metaClassName = packageName + "." + metaSimpleClassName;
try {
final JavaFileObject builderFile = super.processingEnv.getFiler()
.createSourceFile(metaClassName);
// try (final PrintWriter out = new PrintWriter(System.out)) {
try (final PrintWriter out = new PrintWriter(builderFile.openWriter())) {
if (!packageName.isEmpty()) {
out.print("package ");
out.print(packageName);
out.println(";");
out.println();
}
out.println("// Generated at " + OffsetDateTime.now());
out.print("public final class ");
out.print(metaSimpleClassName);
out.println(" {");
out.println(templateClass(simpleClassName));
final Map<String, String> metas = new LinkedHashMap<>();
for (Pair<Element, Integer> element : elements) {
processElement.accept(element, metas);
}
metas.forEach((k, v) -> out.println(" " + v));
out.println("}");
}
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
}
static Pair<String, String> splitClassName(String className) {
String packageName = "";
final int p = firstUpperPosition(className);
if (p > 0) {
packageName = className.substring(0, p - 1);
}
final String simpleClassName = className.substring(p);
return new Pair<>(packageName, simpleClassName);
}
static int firstUpperPosition(String s) {
final String lower = s.toLowerCase();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != lower.charAt(i)) {
return i;
}
}
return -1;
}
}
|
0 | java-sources/am/ik/csng/csng/0.4.0/am/ik/csng | java-sources/am/ik/csng/csng/0.4.0/am/ik/csng/processor/CompileSafeNameTemplate.java | /*
* Copyright (C) 2020 Toshiaki Maki <makingx@gmail.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 am.ik.csng.processor;
import java.nio.CharBuffer;
final class CompileSafeNameTemplate {
static String templateClass(String simpleClassName) {
final String[] split = simpleClassName.split("\\.");
if (split.length >= 2) {
simpleClassName = split[1];
}
final String lowerCamel = lowerCamel(simpleClassName);
final String upperCamel = upperCamel(simpleClassName);
final String lowerUnderscore = lowerUnderscore(lowerCamel);
final String upperUnderscore = lowerUnderscore.toUpperCase();
return String.format("\tpublic static final String LOWER_CAMEL = \"%s\";\n" + //
"\tpublic static final String UPPER_CAMEL = \"%s\";\n" + //
"\tpublic static final String LOWER_UNDERSCORE = \"%s\";\n" + //
"\tpublic static final String UPPER_UNDERSCORE = \"%s\";\n", lowerCamel,
upperCamel, lowerUnderscore, upperUnderscore);
}
static String templateTarget(String target) {
final String lowerCamel = lowerCamel(target);
final String upperCamel = upperCamel(target);
final String lowerUnderscore = lowerUnderscore(lowerCamel);
final String upperUnderscore = lowerUnderscore.toUpperCase();
return String.format("\tpublic static final class %s {\n" + //
"\t\tpublic static final String LOWER_CAMEL = \"%s\";\n" + //
"\t\tpublic static final String UPPER_CAMEL = \"%s\";\n" + //
"\t\tpublic static final String LOWER_UNDERSCORE = \"%s\";\n" + //
"\t\tpublic static final String UPPER_UNDERSCORE = \"%s\";\n" + //
"\t}\n", upperCamel, lowerCamel, upperCamel, lowerUnderscore,
upperUnderscore);
}
static String lowerCamel(String s) {
if (s.length() >= 2) {
final String firstTwo = s.substring(0, 2);
if (firstTwo.equals(firstTwo.toUpperCase())) {
return s;
}
}
return s.substring(0, 1).toLowerCase() + s.substring(1);
}
static String upperCamel(String s) {
if (s.length() >= 2) {
final String firstTwo = s.substring(0, 2);
if (firstTwo.equals(firstTwo.toUpperCase())) {
return s;
}
}
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
static String lowerUnderscore(String text) {
if (text == null || text.isEmpty()) {
return text;
}
final StringBuilder s = new StringBuilder();
final CharBuffer buffer = CharBuffer.wrap(text);
while (buffer.hasRemaining()) {
final char c = buffer.get();
s.append(Character.toLowerCase(c));
buffer.mark();
if (buffer.hasRemaining()) {
final char c2 = buffer.get();
if (Character.isLowerCase(c) && Character.isUpperCase(c2)) {
s.append("_");
}
buffer.reset();
}
}
return s.toString();
}
}
|
0 | java-sources/am/ik/csng/csng/0.4.0/am/ik/csng | java-sources/am/ik/csng/csng/0.4.0/am/ik/csng/processor/Pair.java | /*
* Copyright (C) 2020 Toshiaki Maki <makingx@gmail.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 am.ik.csng.processor;
import java.util.Objects;
final class Pair<F, S> {
private final F first;
private final S second;
public Pair(F first, S second) {
this.first = first;
this.second = second;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
return Objects.equals(first, pair.first) && Objects.equals(second, pair.second);
}
public F first() {
return this.first;
}
@Override
public int hashCode() {
return Objects.hash(first, second);
}
public S second() {
return this.second;
}
@Override
public String toString() {
return "Pair{" + "first=" + first + ", second=" + second + '}';
}
}
|
0 | java-sources/am/ik/csng/csng/0.4.0/am/ik/csng | java-sources/am/ik/csng/csng/0.4.0/am/ik/csng/processor/package-info.java | /*
* Copyright (C) 2020 Toshiaki Maki <makingx@gmail.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 am.ik.csng.processor;
|
0 | java-sources/am/ik/eureka/simple-eureka-client/0.1.0/am/ik | java-sources/am/ik/eureka/simple-eureka-client/0.1.0/am/ik/eureka/EurekaClientConfigImpl.java | package am.ik.eureka;
import static java.lang.System.getenv;
import static java.util.Optional.ofNullable;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netflix.discovery.DefaultEurekaClientConfig;
public class EurekaClientConfigImpl extends DefaultEurekaClientConfig {
private static final Logger log = LoggerFactory
.getLogger(EurekaClientConfigImpl.class);
@Override
public List<String> getEurekaServerServiceUrls(String myZone) {
String envKey = "EUREKA_CLIENT_SERVICE_URL_" + myZone.toUpperCase();
List<String> eurekaServerServiceUrls = Optional.ofNullable(System.getenv(envKey))
.map(s -> Arrays.asList(s.split(",")))
.orElseGet(() -> super.getEurekaServerServiceUrls(myZone));
log.debug("getEurekaServerServiceUrls({})={}", myZone, eurekaServerServiceUrls);
return eurekaServerServiceUrls;
}
@Override
public int getRegistryFetchIntervalSeconds() {
int seconds = ofNullable(getenv("EUREKA_CLIENT_REGISTRY_FETCH_INTERVAL_SECONDS"))
.map(Integer::parseInt).orElseGet(super::getRegistryFetchIntervalSeconds);
log.debug("getRegistryFetchIntervalSeconds()={}", seconds);
return seconds;
}
@Override
public int getInstanceInfoReplicationIntervalSeconds() {
int seconds = ofNullable(
getenv("EUREKA_CLIENT_INSTANCE_INFO_REPLICATION_INTERVAL_SECONDS"))
.map(Integer::parseInt)
.orElseGet(super::getInstanceInfoReplicationIntervalSeconds);
log.debug("getInstanceInfoReplicationIntervalSeconds()={}", seconds);
return seconds;
}
}
|
0 | java-sources/am/ik/eureka/simple-eureka-client/0.1.0/am/ik | java-sources/am/ik/eureka/simple-eureka-client/0.1.0/am/ik/eureka/EurekaInstanceConfigImpl.java | package am.ik.eureka;
import static java.lang.System.getenv;
import static java.util.Optional.ofNullable;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netflix.appinfo.PropertiesInstanceConfig;
public class EurekaInstanceConfigImpl extends PropertiesInstanceConfig {
private static final Logger log = LoggerFactory
.getLogger(EurekaInstanceConfigImpl.class);
@Override
public String getAppname() {
String appname = super.getAppname();
log.debug("getAppname()={}", appname);
return appname;
}
@Override
public int getNonSecurePort() {
int nonSecurePort = getPort()
.orElseGet(() -> ofNullable(getenv("EUREKA_INSTANCE_NON_SECURE_PORT"))
.map(Integer::parseInt).orElseGet(super::getNonSecurePort));
log.debug("getNonSecurePort()={}", nonSecurePort);
return nonSecurePort;
}
private Optional<Integer> getPort() {
return ofNullable(getenv("PORT")).map(Integer::valueOf);
}
@Override
public String getInstanceId() {
String instanceId = ofNullable(getenv("INSTANCE_GUID"))
.orElseGet(this::getInstanceId);
log.debug("getInstanceId()={}", instanceId);
return instanceId;
}
@Override
public String getHostName(boolean refresh) {
String cfInstanceInternalIp = System.getenv("CF_INSTANCE_INTERNAL_IP");
String hostname = ofNullable(getenv("EUREKA_INSTANCE_HOSTNAME"))
.orElseGet(() -> cfInstanceInternalIp == null ? super.getHostName(refresh)
: cfInstanceInternalIp);
log.debug("getHostName({})={}", refresh, hostname);
return hostname;
}
@Override
public String getVirtualHostName() {
String virtualHostName = ofNullable(getenv("EUREKA_INSTANCE_VIRTUAL_HOST_NAME"))
.orElseGet(this::getAppname);
log.debug("getVirtualHostName()={}", virtualHostName);
return virtualHostName;
}
@Override
public int getLeaseRenewalIntervalInSeconds() {
int seconds = ofNullable(
getenv("EUREKA_INSTANCE_LEASE_RENEWAL_INTERVAL_IN_SECONDS"))
.map(Integer::parseInt)
.orElseGet(super::getLeaseRenewalIntervalInSeconds);
log.debug("getLeaseRenewalIntervalInSeconds()={}", seconds);
return seconds;
}
@Override
public int getLeaseExpirationDurationInSeconds() {
int seconds = ofNullable(
getenv("EUREKA_INSTANCE_LEASE_EXPIRATION_DURATION_IN_SECONDS"))
.map(Integer::parseInt)
.orElseGet(super::getLeaseExpirationDurationInSeconds);
log.debug("getLeaseExpirationDurationInSeconds()={}", seconds);
return seconds;
}
@Override
public boolean isInstanceEnabledOnit() {
return true;
}
}
|
0 | java-sources/am/ik/eureka/simple-eureka-client/0.1.0/am/ik | java-sources/am/ik/eureka/simple-eureka-client/0.1.0/am/ik/eureka/EurekaModule.java | package am.ik.eureka;
import com.google.inject.AbstractModule;
import com.google.inject.Scopes;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.EurekaInstanceConfig;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider;
import com.netflix.discovery.AbstractDiscoveryClientOptionalArgs;
import com.netflix.discovery.DiscoveryClient;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.shared.transport.jersey.Jersey1DiscoveryClientOptionalArgs;
public class EurekaModule extends AbstractModule {
@Override
protected void configure() {
// need to eagerly initialize
bind(ApplicationInfoManager.class).asEagerSingleton();
bind(EurekaInstanceConfig.class).to(EurekaInstanceConfigImpl.class)
.in(Scopes.SINGLETON);
bind(EurekaClientConfig.class).to(EurekaClientConfigImpl.class)
.in(Scopes.SINGLETON);
// this is the self instanceInfo used for registration purposes
bind(InstanceInfo.class).toProvider(EurekaConfigBasedInstanceInfoProvider.class)
.in(Scopes.SINGLETON);
bind(EurekaClient.class).to(DiscoveryClient.class).in(Scopes.SINGLETON);
// Default to the jersey1 discovery client optional args
bind(AbstractDiscoveryClientOptionalArgs.class)
.to(Jersey1DiscoveryClientOptionalArgs.class).in(Scopes.SINGLETON);
bind(EurekaRegistrar.class).asEagerSingleton();
}
}
|
0 | java-sources/am/ik/eureka/simple-eureka-client/0.1.0/am/ik | java-sources/am/ik/eureka/simple-eureka-client/0.1.0/am/ik/eureka/EurekaRegistrar.java | package am.ik.eureka;
import static com.netflix.appinfo.InstanceInfo.InstanceStatus.UP;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Singleton;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
@Singleton
public class EurekaRegistrar {
private static final Logger log = LoggerFactory.getLogger(EurekaRegistrar.class);
@Inject
public EurekaRegistrar(ApplicationInfoManager applicationInfoManager,
EurekaClient eurekaClient, InstanceInfo instanceInfo) {
log.info("Registering to Eureka Server");
// applicationInfoManager.setInstanceStatus(STARTING);
log.info("Application Name = {}", instanceInfo.getAppName());
log.info("Port = {}", instanceInfo.getPort());
log.info("VIP = {}", instanceInfo.getVIPAddress());
log.info("Metadata = {}", instanceInfo.getMetadata());
log.info("Set instance status to UP");
applicationInfoManager.setInstanceStatus(UP);
log.info("Registered");
}
}
|
0 | java-sources/am/ik/fh4j/fh4j/1.0.1 | java-sources/am/ik/fh4j/fh4j/1.0.1/fh4j/DefaultFullHalf.java | /*
* Copyright (C) 2015 Toshiaki Maki <makingx@gmail.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 fh4j;
public class DefaultFullHalf {
public static final FullHalfConverter INSTANCE = new FullHalfConverter(
new FullHalfPairsBuilder()
.pair("!", "!")
.pair("”", "\"")
.pair("#", "#")
.pair("$", "$")
.pair("%", "%")
.pair("&", "&")
.pair("’", "'")
.pair("(", "(")
.pair(")", ")")
.pair("*", "*")
.pair("+", "+")
.pair(",", ",")
.pair("-", "-")
.pair(".", ".")
.pair("/", "/")
.pair("0", "0")
.pair("1", "1")
.pair("2", "2")
.pair("3", "3")
.pair("4", "4")
.pair("5", "5")
.pair("6", "6")
.pair("7", "7")
.pair("8", "8")
.pair("9", "9")
.pair(":", ":")
.pair(";", ";")
.pair("<", "<")
.pair("=", "=")
.pair(">", ">")
.pair("?", "?")
.pair("@", "@")
.pair("A", "A")
.pair("B", "B")
.pair("C", "C")
.pair("D", "D")
.pair("E", "E")
.pair("F", "F")
.pair("G", "G")
.pair("H", "H")
.pair("I", "I")
.pair("J", "J")
.pair("K", "K")
.pair("L", "L")
.pair("M", "M")
.pair("N", "N")
.pair("O", "O")
.pair("P", "P")
.pair("Q", "Q")
.pair("R", "R")
.pair("S", "S")
.pair("T", "T")
.pair("U", "U")
.pair("V", "V")
.pair("W", "W")
.pair("X", "X")
.pair("Y", "Y")
.pair("Z", "Z")
.pair("[", "[")
.pair("¥", "\\")
.pair("]", "]")
.pair("^", "^")
.pair("_", "_")
.pair("`", "`")
.pair("a", "a")
.pair("b", "b")
.pair("c", "c")
.pair("d", "d")
.pair("e", "e")
.pair("f", "f")
.pair("g", "g")
.pair("h", "h")
.pair("i", "i")
.pair("j", "j")
.pair("k", "k")
.pair("l", "l")
.pair("m", "m")
.pair("n", "n")
.pair("o", "o")
.pair("p", "p")
.pair("q", "q")
.pair("r", "r")
.pair("s", "s")
.pair("t", "t")
.pair("u", "u")
.pair("v", "v")
.pair("w", "w")
.pair("x", "x")
.pair("y", "y")
.pair("z", "z")
.pair("{", "{")
.pair("|", "|")
.pair("}", "}")
.pair(String.valueOf('\uff5e'), "~")
.pair("。", "。")
.pair("「", "「")
.pair("」", "」")
.pair("、", "、")
.pair("・", "・")
.pair("ァ", "ァ")
.pair("ィ", "ィ")
.pair("ゥ", "ゥ")
.pair("ェ", "ェ")
.pair("ォ", "ォ")
.pair("ャ", "ャ")
.pair("ュ", "ュ")
.pair("ョ", "ョ")
.pair("ッ", "ッ")
.pair("ー", "ー")
.pair("ア", "ア")
.pair("イ", "イ")
.pair("ウ", "ウ")
.pair("エ", "エ")
.pair("オ", "オ")
.pair("カ", "カ")
.pair("キ", "キ")
.pair("ク", "ク")
.pair("ケ", "ケ")
.pair("コ", "コ")
.pair("サ", "サ")
.pair("シ", "シ")
.pair("ス", "ス")
.pair("セ", "セ")
.pair("ソ", "ソ")
.pair("タ", "タ")
.pair("チ", "チ")
.pair("ツ", "ツ")
.pair("テ", "テ")
.pair("ト", "ト")
.pair("ナ", "ナ")
.pair("ニ", "ニ")
.pair("ヌ", "ヌ")
.pair("ネ", "ネ")
.pair("ノ", "ノ")
.pair("ハ", "ハ")
.pair("ヒ", "ヒ")
.pair("フ", "フ")
.pair("ヘ", "ヘ")
.pair("ホ", "ホ")
.pair("マ", "マ")
.pair("ミ", "ミ")
.pair("ム", "ム")
.pair("メ", "メ")
.pair("モ", "モ")
.pair("ヤ", "ヤ")
.pair("ユ", "ユ")
.pair("ヨ", "ヨ")
.pair("ラ", "ラ")
.pair("リ", "リ")
.pair("ル", "ル")
.pair("レ", "レ")
.pair("ロ", "ロ")
.pair("ワ", "ワ")
.pair("ヲ", "ヲ")
.pair("ン", "ン")
.pair("ガ", "ガ")
.pair("ギ", "ギ")
.pair("グ", "グ")
.pair("ゲ", "ゲ")
.pair("ゴ", "ゴ")
.pair("ザ", "ザ")
.pair("ジ", "ジ")
.pair("ズ", "ズ")
.pair("ゼ", "ゼ")
.pair("ゾ", "ゾ")
.pair("ダ", "ダ")
.pair("ヂ", "ヂ")
.pair("ヅ", "ヅ")
.pair("デ", "デ")
.pair("ド", "ド")
.pair("バ", "バ")
.pair("ビ", "ビ")
.pair("ブ", "ブ")
.pair("べ", "ベ")
.pair("ボ", "ボ")
.pair("パ", "パ")
.pair("ピ", "ピ")
.pair("プ", "プ")
.pair("ペ", "ペ")
.pair("ポ", "ポ")
.pair("ヴ", "ヴ")
.pair(String.valueOf('\u30f7'), "ヷ")
.pair(String.valueOf('\u30fa'), "ヺ")
.pair("゛", "゙")
.pair("゜", "゚")
.pair(" ", " ")
.build());
}
|
0 | java-sources/am/ik/fh4j/fh4j/1.0.1 | java-sources/am/ik/fh4j/fh4j/1.0.1/fh4j/FullHalfConverter.java | /*
* Copyright (C) 2015 Toshiaki Maki <makingx@gmail.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 fh4j;
import java.util.*;
public class FullHalfConverter {
private final Map<String, FullHalfPair> fullwidthMap;
private final Map<String, FullHalfPair> halfwidthMap;
private final FullHalfPairs.AppendablePredicate predicate;
public FullHalfConverter(FullHalfPairs pairs) {
Set<FullHalfPair> pairSet = pairs.pairs();
Map<String, FullHalfPair> f = new HashMap<String, FullHalfPair>();
Map<String, FullHalfPair> h = new HashMap<String, FullHalfPair>();
for (FullHalfPair pair : pairSet) {
f.put(pair.fullwidth(), pair);
h.put(pair.halfwidth(), pair);
}
this.fullwidthMap = Collections.unmodifiableMap(f);
this.halfwidthMap = Collections.unmodifiableMap(h);
this.predicate = pairs.predicate();
}
public String toHalfwidth(String fullwidth) {
if (fullwidth == null || fullwidth.isEmpty()) {
return fullwidth;
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < fullwidth.length(); i++) {
String s = String.valueOf(fullwidth.charAt(i));
builder.append(halfwidth(s));
}
return builder.toString();
}
public String toFullwidth(String halfwidth) {
if (halfwidth == null || halfwidth.isEmpty()) {
return halfwidth;
}
StringBuilder builder = new StringBuilder();
Queue<String> buffer = new LinkedList<String>(); // サイズ1のバッファとしてキューを使う
for (int i = 0; i < halfwidth.length(); i++) {
char c = halfwidth.charAt(i);
String s = String.valueOf(c);
// バッファが空の場合は次のループへ
if (buffer.isEmpty()) {
buffer.add(s);
continue;
}
// バッファから文字を取り出す
String prev = buffer.poll();
if (predicate.isAppendable(c)) {
// バッファの文字と結合した文字が変換可能か
FullHalfPair pair = this.halfwidthMap.get(prev + s);
if (pair != null) {
// 結合文字をStringBuilderに追加
builder.append(pair.fullwidth());
}
else {
// バッファの文字と次の文字をStringBuilderに追加
builder.append(fullwidth(prev));
builder.append(fullwidth(s));
}
}
else {
// バッファの文字をStringBuilderに追加して、次の文字をバッファに追加
builder.append(fullwidth(prev));
buffer.add(s);
}
}
// バッファが残っている場合はStringBuilderに追加
if (!buffer.isEmpty()) {
builder.append(fullwidth(buffer.poll()));
}
return builder.toString();
}
private String fullwidth(String s) {
FullHalfPair pair = this.halfwidthMap.get(s);
if (pair != null) {
return pair.fullwidth();
}
else {
return s;
}
}
private String halfwidth(String s) {
FullHalfPair pair = this.fullwidthMap.get(s);
if (pair != null) {
return pair.halfwidth();
}
else {
return s;
}
}
}
|
0 | java-sources/am/ik/fh4j/fh4j/1.0.1 | java-sources/am/ik/fh4j/fh4j/1.0.1/fh4j/FullHalfPair.java | /*
* Copyright (C) 2015 Toshiaki Maki <makingx@gmail.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 fh4j;
import java.io.Serializable;
public final class FullHalfPair implements Serializable {
private final String fullwidth;
private final String halfwidth;
public FullHalfPair(String fullwidth, String halfwidth) {
if (fullwidth == null || fullwidth.length() != 1) {
throw new IllegalArgumentException("fullwidth must be 1 length string");
}
if (halfwidth == null || (halfwidth.length() != 1 && halfwidth.length() != 2)) {
throw new IllegalArgumentException("halfwidth must be 1 or 2 length string");
}
this.fullwidth = fullwidth;
this.halfwidth = halfwidth;
}
public String fullwidth() {
return this.fullwidth;
}
public String halfwidth() {
return this.halfwidth;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
FullHalfPair that = (FullHalfPair) o;
if (!fullwidth.equals(that.fullwidth))
return false;
return halfwidth.equals(that.halfwidth);
}
@Override
public int hashCode() {
int result = fullwidth.hashCode();
result = 31 * result + halfwidth.hashCode();
return result;
}
}
|
0 | java-sources/am/ik/fh4j/fh4j/1.0.1 | java-sources/am/ik/fh4j/fh4j/1.0.1/fh4j/FullHalfPairs.java | /*
* Copyright (C) 2015 Toshiaki Maki <makingx@gmail.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 fh4j;
import java.util.Set;
public class FullHalfPairs {
private final Set<FullHalfPair> pairs;
private final AppendablePredicate predicate;
public FullHalfPairs(Set<FullHalfPair> pairs, AppendablePredicate predicate) {
this.pairs = pairs;
this.predicate = predicate != null ? predicate : new AppendablePredicate() {
@Override
public boolean isAppendable(char c) {
return c == '゙' || c == '゚';
}
};
}
public Set<FullHalfPair> pairs() {
return this.pairs;
}
public AppendablePredicate predicate() {
return this.predicate;
}
public interface AppendablePredicate {
boolean isAppendable(char c);
}
}
|
0 | java-sources/am/ik/fh4j/fh4j/1.0.1 | java-sources/am/ik/fh4j/fh4j/1.0.1/fh4j/FullHalfPairsBuilder.java | /*
* Copyright (C) 2015 Toshiaki Maki <makingx@gmail.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 fh4j;
import java.util.LinkedHashSet;
import java.util.Set;
public class FullHalfPairsBuilder {
private final Set<FullHalfPair> pairs = new LinkedHashSet<FullHalfPair>();
private FullHalfPairs.AppendablePredicate predicate;
public FullHalfPairsBuilder pair(String fullwidth, String halfwidth) {
this.pairs.add(new FullHalfPair(fullwidth, halfwidth));
return this;
}
public FullHalfPairsBuilder appendablePredicate(
FullHalfPairs.AppendablePredicate predicate) {
this.predicate = predicate;
return this;
}
public FullHalfPairs build() {
return new FullHalfPairs(this.pairs, this.predicate);
}
}
|
0 | java-sources/am/ik/functions/fizz-buzz/1.0.0/am/ik | java-sources/am/ik/functions/fizz-buzz/1.0.0/am/ik/functions/FizzBuzz.java | package am.ik.functions;
import java.util.function.Function;
public class FizzBuzz implements Function<Long, String> {
@Override
public String apply(Long x) {
if (x == null) {
return "";
}
if (x % 3 == 0 && x % 5 == 0) {
return "FizzBuzz";
}
if (x % 3 == 0) {
return "Fizz";
}
if (x % 5 == 0) {
return "Buzz";
}
return x.toString();
}
}
|
0 | java-sources/am/ik/github/reactive-github-client/0.0.4/am/ik | java-sources/am/ik/github/reactive-github-client/0.0.4/am/ik/github/AccessToken.java | package am.ik.github;
import org.springframework.http.HttpHeaders;
import java.util.Optional;
import java.util.function.Consumer;
public class AccessToken {
private final String accessToken;
public AccessToken(String accessToken) {
this.accessToken = accessToken;
}
public AccessToken() {
this(Optional.ofNullable(System.getenv("GITHUB_ACCESS_TOKEN"))
.orElseGet(() -> System.getProperty("github.access.token", "")));
}
public String getAccessToken() {
return accessToken;
}
public Consumer<HttpHeaders> toAuthorization() {
return httpHeaders -> httpHeaders.add(HttpHeaders.AUTHORIZATION, "token " + accessToken);
}
}
|
0 | java-sources/am/ik/github/reactive-github-client/0.0.4/am/ik | java-sources/am/ik/github/reactive-github-client/0.0.4/am/ik/github/GitHubClient.java | package am.ik.github;
import am.ik.github.repositories.commits.CommitsApi;
import am.ik.github.repositories.contents.ContentsApi;
import org.springframework.web.reactive.function.client.WebClient;
public class GitHubClient {
private final WebClient webClient;
public GitHubClient(String apiUrl, WebClient.Builder builder, AccessToken accessToken) {
this.webClient = builder //
.baseUrl(apiUrl) //
.defaultHeaders(accessToken.toAuthorization())
.build();
}
public GitHubClient(WebClient.Builder builder, AccessToken accessToken) {
this("https://api.github.com", builder, accessToken);
}
public ContentsApi.Readme readme(String owner, String repo) {
return new ContentsApi.Readme(webClient, owner, repo);
}
public ContentsApi.File file(String owner, String repo, String path) {
return new ContentsApi.File(webClient, owner, repo, path);
}
public ContentsApi.Contents contents(String owner, String repo, String path) {
return new ContentsApi.Contents(webClient, owner, repo, path);
}
public ContentsApi.Contents contents(String owner, String repo) {
return this.contents(owner, repo, "");
}
public CommitsApi.Commits commits(String owner, String repo) {
return new CommitsApi.Commits(webClient, owner, repo);
}
}
|
0 | java-sources/am/ik/github/reactive-github-client/0.0.4/am/ik/github | java-sources/am/ik/github/reactive-github-client/0.0.4/am/ik/github/core/Commit.java | package am.ik.github.core;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
public class Commit extends Parent {
private final Committer author;
private final Committer committer;
private final Tree tree;
private final String message;
private final List<Parent> parents;
@JsonCreator
public Commit(
@JsonProperty("sha") String sha,
@JsonProperty("url") String url,
@JsonProperty("html_url") String htmlUrl,
@JsonProperty("author") Committer author,
@JsonProperty("committer") Committer committer,
@JsonProperty("tree") Tree tree,
@JsonProperty("message") String message,
@JsonProperty("parents") List<Parent> parents) {
super(sha, url, htmlUrl);
this.author = author;
this.committer = committer;
this.tree = tree;
this.message = message;
this.parents = parents;
}
public Committer getAuthor() {
return author;
}
public Committer getCommitter() {
return committer;
}
public Tree getTree() {
return tree;
}
public String getMessage() {
return message;
}
public List<Parent> getParents() {
return parents;
}
@Override
public String toString() {
return "Commit{" +
"author=" + author +
", committer=" + committer +
", tree=" + tree +
", message='" + message + '\'' +
", parents=" + parents +
'}';
}
}
|
0 | java-sources/am/ik/github/reactive-github-client/0.0.4/am/ik/github | java-sources/am/ik/github/reactive-github-client/0.0.4/am/ik/github/core/Committer.java | package am.ik.github.core;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.OffsetDateTime;
import java.util.Objects;
public class Committer {
private final String name;
private final String email;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private final OffsetDateTime date;
public Committer(String name,
String email) {
this(name, email, null);
}
@JsonCreator
public Committer(@JsonProperty("name") String name,
@JsonProperty("email") String email,
@JsonProperty("date") OffsetDateTime date) {
this.name = Objects.requireNonNull(name);
this.email = Objects.requireNonNull(email);
this.date = date;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public OffsetDateTime getDate() {
return date;
}
@Override
public String toString() {
return "Committer{" +
"name='" + name + '\'' +
", email='" + email + '\'' +
", date=" + date +
'}';
}
}
|
0 | java-sources/am/ik/github/reactive-github-client/0.0.4/am/ik/github | java-sources/am/ik/github/reactive-github-client/0.0.4/am/ik/github/core/Content.java | package am.ik.github.core;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Content {
private final String name;
private final String path;
private final String sha;
private final String url;
private final String gitUrl;
private final String htmlUrl;
private final String downloadUrl;
private final ContentType type;
@JsonCreator
public Content(@JsonProperty("name") String name,
@JsonProperty("path") String path,
@JsonProperty("sha") String sha,
@JsonProperty("url") String url,
@JsonProperty("git_url") String gitUrl,
@JsonProperty("html_url") String htmlUrl,
@JsonProperty("download_url") String downloadUrl,
@JsonProperty("type") ContentType type) {
this.name = name;
this.path = path;
this.sha = sha;
this.url = url;
this.gitUrl = gitUrl;
this.htmlUrl = htmlUrl;
this.downloadUrl = downloadUrl;
this.type = type;
}
public String getName() {
return name;
}
public String getPath() {
return path;
}
public String getSha() {
return sha;
}
public String getUrl() {
return url;
}
public String getGitUrl() {
return gitUrl;
}
public String getHtmlUrl() {
return htmlUrl;
}
public String getDownloadUrl() {
return downloadUrl;
}
public ContentType getType() {
return type;
}
@Override
public String toString() {
return "Content{" +
"name='" + name + '\'' +
", path='" + path + '\'' +
", sha='" + sha + '\'' +
", url='" + url + '\'' +
", gitUrl='" + gitUrl + '\'' +
", htmlUrl='" + htmlUrl + '\'' +
", downloadUrl='" + downloadUrl + '\'' +
", type='" + type + '\'' +
'}';
}
}
|
0 | java-sources/am/ik/github/reactive-github-client/0.0.4/am/ik/github | java-sources/am/ik/github/reactive-github-client/0.0.4/am/ik/github/core/ContentType.java | package am.ik.github.core;
import com.fasterxml.jackson.annotation.JsonCreator;
public enum ContentType {
FILE, DIR;
@JsonCreator
public static ContentType from(String s) {
if (s == null) {
return null;
}
return ContentType.valueOf(s.toUpperCase());
}
}
|
0 | java-sources/am/ik/github/reactive-github-client/0.0.4/am/ik/github | java-sources/am/ik/github/reactive-github-client/0.0.4/am/ik/github/core/Parent.java | package am.ik.github.core;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Parent {
private final String sha;
private final String url;
private final String htmlUrl;
@JsonCreator
public Parent(@JsonProperty("sha") String sha,
@JsonProperty("url") String url,
@JsonProperty("html_url") String htmlUrl) {
this.sha = sha;
this.url = url;
this.htmlUrl = htmlUrl;
}
@Override
public String toString() {
return "Parent{" +
"sha='" + sha + '\'' +
", url='" + url + '\'' +
", htmlUrl='" + htmlUrl + '\'' +
'}';
}
public String getSha() {
return sha;
}
public String getUrl() {
return url;
}
public String getHtmlUrl() {
return htmlUrl;
}
}
|
0 | java-sources/am/ik/github/reactive-github-client/0.0.4/am/ik/github | java-sources/am/ik/github/reactive-github-client/0.0.4/am/ik/github/core/Tree.java | package am.ik.github.core;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Tree {
private final String sha;
private final String url;
@JsonCreator
public Tree(@JsonProperty("sha") String sha,
@JsonProperty("url") String url) {
this.sha = sha;
this.url = url;
}
public String getSha() {
return sha;
}
public String getUrl() {
return url;
}
@Override
public String toString() {
return "Tree{" +
"sha='" + sha + '\'' +
", url='" + url + '\'' +
'}';
}
}
|
0 | java-sources/am/ik/github/reactive-github-client/0.0.4/am/ik/github/repositories | java-sources/am/ik/github/reactive-github-client/0.0.4/am/ik/github/repositories/commits/CommitsApi.java | package am.ik.github.repositories.commits;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.function.Consumer;
public class CommitsApi {
public static class Commits {
private final WebClient webClient;
private final String owner;
private final String repo;
public Commits(WebClient webClient, String owner, String repo) {
this.webClient = webClient;
this.owner = owner;
this.repo = repo;
}
public static class CommitParameter {
private String sha;
private String path;
private String author;
private ZonedDateTime since;
private ZonedDateTime until;
private CommitParameter() {
}
public CommitParameter sha(String sha) {
this.sha = sha;
return this;
}
public CommitParameter path(String path) {
this.path = path;
return this;
}
public CommitParameter author(String author) {
this.author = author;
return this;
}
public CommitParameter since(ZonedDateTime since) {
this.since = since;
return this;
}
public CommitParameter until(ZonedDateTime until) {
this.until = until;
return this;
}
MultiValueMap<String, String> queryParams() {
MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>();
if (sha != null) {
queryParams.add("sha", sha);
}
if (path != null) {
queryParams.add("path", path);
}
if (author != null) {
queryParams.add("author", author);
}
if (since != null) {
queryParams.add("since", since.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
}
if (until != null) {
queryParams.add("until", until.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
}
return queryParams;
}
}
public Flux<CommitsResponse.Commit> get() {
return this.get(x -> {
});
}
public Flux<CommitsResponse.Commit> get(Consumer<CommitParameter> parameterConsumer) {
CommitParameter parameter = new CommitParameter();
parameterConsumer.accept(parameter);
return this.webClient.get() //
.uri(b -> b.path("/repos/{owner}/{repo}/commits")
.queryParams(parameter.queryParams())
.build(owner, repo)) //
.retrieve()
.bodyToFlux(CommitsResponse.Commit.class);
}
}
}
|
0 | java-sources/am/ik/github/reactive-github-client/0.0.4/am/ik/github/repositories | java-sources/am/ik/github/reactive-github-client/0.0.4/am/ik/github/repositories/commits/CommitsResponse.java | package am.ik.github.repositories.commits;
import am.ik.github.core.Parent;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
public abstract class CommitsResponse {
public static final class Commit extends Parent {
private final String commentsUrl;
private final am.ik.github.core.Commit commit;
private final Committer author;
private final Committer committer;
private final List<Parent> parents;
@JsonCreator
public Commit(@JsonProperty("sha") String sha,
@JsonProperty("url") String url,
@JsonProperty("html_url") String htmlUrl,
@JsonProperty("comments_url") String commentsUrl,
@JsonProperty("commit") am.ik.github.core.Commit commit,
@JsonProperty("author") Committer author,
@JsonProperty("committer") Committer committer,
@JsonProperty("parents") List<Parent> parents) {
super(sha, url, htmlUrl);
this.commentsUrl = commentsUrl;
this.commit = commit;
this.author = author;
this.committer = committer;
this.parents = parents;
}
public String getCommentsUrl() {
return commentsUrl;
}
public am.ik.github.core.Commit getCommit() {
return commit;
}
public Committer getAuthor() {
return author;
}
public Committer getCommitter() {
return committer;
}
public List<Parent> getParents() {
return parents;
}
@Override
public String toString() {
return "Commit{" +
"commentsUrl='" + commentsUrl + '\'' +
", commit=" + commit +
", author=" + author +
", committer=" + committer +
", parents=" + parents +
'}';
}
}
public static final class Committer {
private final String login;
private final String id;
private final String avatarUrl;
private final String gravaterId;
private final String url;
private final String htmlUrl;
private final String followersUrl;
private final String followingUrl;
private final String gistsUrl;
private final String starredUrl;
private final String subscriptionsUrl;
private final String organizationsUrl;
private final String reposUrl;
private final String eventsUrl;
private final String receivedEventsUrl;
private final String type;
private final boolean siteAdmin;
public Committer(@JsonProperty("login") String login,
@JsonProperty("id") String id,
@JsonProperty("avatar_url") String avatarUrl,
@JsonProperty("gravater_id") String gravaterId,
@JsonProperty("url") String url,
@JsonProperty("html_url") String htmlUrl,
@JsonProperty("followers_url") String followersUrl,
@JsonProperty("following_url") String followingUrl,
@JsonProperty("gists_url") String gistsUrl,
@JsonProperty("starred_url") String starredUrl,
@JsonProperty("subscriptions_url") String subscriptionsUrl,
@JsonProperty("organizations_url") String organizationsUrl,
@JsonProperty("repos_url") String reposUrl,
@JsonProperty("events_url") String eventsUrl,
@JsonProperty("received_events_url") String receivedEventsUrl,
@JsonProperty("type") String type,
@JsonProperty("site_admin") boolean siteAdmin) {
this.login = login;
this.id = id;
this.avatarUrl = avatarUrl;
this.gravaterId = gravaterId;
this.url = url;
this.htmlUrl = htmlUrl;
this.followersUrl = followersUrl;
this.followingUrl = followingUrl;
this.gistsUrl = gistsUrl;
this.starredUrl = starredUrl;
this.subscriptionsUrl = subscriptionsUrl;
this.organizationsUrl = organizationsUrl;
this.reposUrl = reposUrl;
this.eventsUrl = eventsUrl;
this.receivedEventsUrl = receivedEventsUrl;
this.type = type;
this.siteAdmin = siteAdmin;
}
public String getLogin() {
return login;
}
public String getId() {
return id;
}
public String getAvatarUrl() {
return avatarUrl;
}
public String getGravaterId() {
return gravaterId;
}
public String getUrl() {
return url;
}
public String getHtmlUrl() {
return htmlUrl;
}
public String getFollowersUrl() {
return followersUrl;
}
public String getFollowingUrl() {
return followingUrl;
}
public String getGistsUrl() {
return gistsUrl;
}
public String getStarredUrl() {
return starredUrl;
}
public String getSubscriptionsUrl() {
return subscriptionsUrl;
}
public String getOrganizationsUrl() {
return organizationsUrl;
}
public String getReposUrl() {
return reposUrl;
}
public String getEventsUrl() {
return eventsUrl;
}
public String getReceivedEventsUrl() {
return receivedEventsUrl;
}
public String getType() {
return type;
}
public boolean isSiteAdmin() {
return siteAdmin;
}
@Override
public String toString() {
return "Committer{" +
"login='" + login + '\'' +
", id='" + id + '\'' +
", avatarUrl='" + avatarUrl + '\'' +
", gravaterId='" + gravaterId + '\'' +
", url='" + url + '\'' +
", htmlUrl='" + htmlUrl + '\'' +
", followersUrl='" + followersUrl + '\'' +
", followingUrl='" + followingUrl + '\'' +
", gistsUrl='" + gistsUrl + '\'' +
", starredUrl='" + starredUrl + '\'' +
", subscriptionsUrl='" + subscriptionsUrl + '\'' +
", organizationsUrl='" + organizationsUrl + '\'' +
", reposUrl='" + reposUrl + '\'' +
", eventsUrl='" + eventsUrl + '\'' +
", receivedEventsUrl='" + receivedEventsUrl + '\'' +
", type='" + type + '\'' +
", siteAdmin=" + siteAdmin +
'}';
}
}
} |
0 | java-sources/am/ik/github/reactive-github-client/0.0.4/am/ik/github/repositories | java-sources/am/ik/github/reactive-github-client/0.0.4/am/ik/github/repositories/contents/ContentsApi.java | package am.ik.github.repositories.contents;
import am.ik.github.core.Content;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class ContentsApi {
public static class Contents {
private final WebClient webClient;
private final String owner;
private final String repo;
private final String path;
public Contents(WebClient webClient, String owner, String repo, String path) {
this.webClient = webClient;
this.owner = owner;
this.repo = repo;
this.path = path;
}
public Flux<Content> get() {
return this.webClient.get() //
.uri("/repos/{owner}/{repo}/contents/{path}", owner, repo, path) //
.retrieve()
.bodyToFlux(Content.class);
}
}
public static class File {
private final WebClient webClient;
private final String owner;
private final String repo;
private final String path;
public File(WebClient webClient, String owner, String repo, String path) {
this.webClient = webClient;
this.owner = owner;
this.repo = repo;
this.path = path;
}
public Mono<ContentsResponse.File> get() {
return this.webClient.get() //
.uri("/repos/{owner}/{repo}/contents/{path}", owner, repo, path) //
.retrieve()
.bodyToMono(ContentsResponse.File.class);
}
public Mono<ContentsResponse.Put> create(ContentsRequest.Create create) {
return this.webClient.put() //
.uri("/repos/{owner}/{repo}/contents/{path}", owner, repo, path) //
.syncBody(create) //
.retrieve() //
.bodyToMono(ContentsResponse.Put.class);
}
public Mono<ContentsResponse.Put> update(ContentsRequest.Update update) {
return this.webClient.put() //
.uri("/repos/{owner}/{repo}/contents/{path}", owner, repo, path) //
.syncBody(update) //
.retrieve() //
.bodyToMono(ContentsResponse.Put.class);
}
public Mono<ContentsResponse.Delete> delete(ContentsRequest.Delete delete) {
return this.webClient.delete() //
.uri(b -> delete.buildingUri(b.path("/repos/{owner}/{repo}/contents/{path}")).build(owner, repo, path))
.retrieve() //
.bodyToMono(ContentsResponse.Delete.class);
}
}
public static class Readme {
private final WebClient webClient;
private final String owner;
private final String repo;
public Readme(WebClient webClient, String owner, String repo) {
this.webClient = webClient;
this.owner = owner;
this.repo = repo;
}
public Mono<ContentsResponse.File> get() {
return this.webClient.get() //
.uri("/repos/{owner}/{repo}/readme", owner, repo) //
.retrieve()
.bodyToMono(ContentsResponse.File.class);
}
}
}
|
0 | java-sources/am/ik/github/reactive-github-client/0.0.4/am/ik/github/repositories | java-sources/am/ik/github/reactive-github-client/0.0.4/am/ik/github/repositories/contents/ContentsRequest.java | package am.ik.github.repositories.contents;
import am.ik.github.core.Committer;
import com.fasterxml.jackson.annotation.JsonInclude;
import org.springframework.util.Base64Utils;
import org.springframework.web.util.UriBuilder;
import java.util.Objects;
import static java.nio.charset.StandardCharsets.UTF_8;
public abstract class ContentsRequest {
private static final String DEFAULT_BRANCH = "master";
protected final String message;
protected final String branch;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
protected Committer committer;
public ContentsRequest(String message, String branch, Committer committer) {
this.message = Objects.requireNonNull(message);
this.branch = Objects.requireNonNull(branch);
this.committer = committer;
}
public String getMessage() {
return message;
}
public String getBranch() {
return branch;
}
public Committer getCommitter() {
return committer;
}
public void setCommitter(Committer committer) {
this.committer = committer;
}
public static final class Create extends ContentsRequest {
private final String content;
public Create(String message, String content, String branch, Committer committer) {
super(message, branch, committer);
this.content = Objects.requireNonNull(content);
}
public String getContent() {
return content;
}
}
public static final class Update extends ContentsRequest {
private final String content;
private final String sha;
public Update(String message, String content, String branch, Committer committer, String sha) {
super(message, branch, committer);
this.sha = Objects.requireNonNull(sha);
this.content = Objects.requireNonNull(content);
}
public String getContent() {
return content;
}
public String getSha() {
return sha;
}
}
public static final class Delete extends ContentsRequest {
private final String sha;
public Delete(String message, String branch, Committer committer, String sha) {
super(message, branch, committer);
this.sha = Objects.requireNonNull(sha);
}
public String getSha() {
return sha;
}
public UriBuilder buildingUri(UriBuilder b) {
b.queryParam("message", message)
.queryParam("sha", sha) //
.queryParam("branch", branch);
if (committer != null) {
b.queryParam("committer.name", committer.getName());
b.queryParam("committer.email", committer.getEmail());
}
return b;
}
}
public static final class Builder {
private final String content;
private Committer committer;
private String branch = DEFAULT_BRANCH;
private Builder(String content) {
this.content = content;
}
public Builder committer(Committer committer) {
this.committer = committer;
return this;
}
public Builder committer(String name, String email) {
return committer(new Committer(name, email));
}
public Builder branch(String branch) {
this.branch = branch;
return this;
}
public Create toCreate(String message) {
return new Create(message, content, branch, committer);
}
public Update toUpdate(String message, String sha) {
return new Update(message, content, branch, committer, sha);
}
public Delete toDelete(String message, String sha) {
return new Delete(message, branch, committer, sha);
}
public static Builder fromPlainText(String content) {
byte[] bytes = Objects.requireNonNull(content).getBytes(UTF_8);
String encoded = Base64Utils.encodeToString(bytes);
return new Builder(encoded);
}
public static Builder noContent() {
return new Builder(null);
}
public static Builder fromBase64Encoded(String content) {
return new Builder(content);
}
}
}
|
0 | java-sources/am/ik/github/reactive-github-client/0.0.4/am/ik/github/repositories | java-sources/am/ik/github/reactive-github-client/0.0.4/am/ik/github/repositories/contents/ContentsResponse.java | package am.ik.github.repositories.contents;
import am.ik.github.core.Commit;
import am.ik.github.core.Content;
import am.ik.github.core.ContentType;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Base64;
public abstract class ContentsResponse {
public static final class Put {
private final Content content;
private final Commit commit;
@JsonCreator
public Put(@JsonProperty("content") Content content,
@JsonProperty("commit") Commit commit) {
this.content = content;
this.commit = commit;
}
public Content getContent() {
return content;
}
public Commit getCommit() {
return commit;
}
@Override
public String toString() {
return "Create{" +
"content=" + content +
", commit=" + commit +
'}';
}
}
public static final class Delete {
private final Commit commit;
@JsonCreator
public Delete(@JsonProperty("commit") Commit commit) {
this.commit = commit;
}
public Commit getCommit() {
return commit;
}
@Override
public String toString() {
return "Delete{" +
"commit=" + commit +
'}';
}
}
public static final class File extends Content {
private final String content;
@JsonCreator
public File(@JsonProperty("name") String name,
@JsonProperty("path") String path,
@JsonProperty("sha") String sha,
@JsonProperty("url") String url,
@JsonProperty("git_url") String gitUrl,
@JsonProperty("html_url") String htmlUrl,
@JsonProperty("download_url") String downloadUrl,
@JsonProperty("content") String content,
@JsonProperty("type") ContentType type) {
super(name, path, sha, url, gitUrl, htmlUrl, downloadUrl, (type == null ? ContentType.FILE : type));
this.content = content;
}
public String decode() {
return new String(Base64.getMimeDecoder().decode(this.content));
}
public String getContent() {
return content;
}
@Override
public String toString() {
return "File{" +
"name='" + getName() + '\'' +
", path='" + getPath() + '\'' +
", sha='" + getSha() + '\'' +
", url='" + getUrl() + '\'' +
", gitUrl='" + getGitUrl() + '\'' +
", htmlUrl='" + getHtmlUrl() + '\'' +
", downloadUrl='" + getDownloadUrl() + '\'' +
", type='" + getType() + '\'' +
", content='" + getContent() + '\'' +
'}';
}
}
} |
0 | java-sources/am/ik/hazelcast/hazelcast-dns-service-discovery/1.0.0/am/ik/hazelcast | java-sources/am/ik/hazelcast/hazelcast-dns-service-discovery/1.0.0/am/ik/hazelcast/dns/DnsRestServiceProperties.java | /*
* Copyright (C) 2018 Toshiaki Maki <makingx@gmail.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 am.ik.hazelcast.dns;
import com.hazelcast.config.properties.PropertyDefinition;
import com.hazelcast.config.properties.SimplePropertyDefinition;
import static com.hazelcast.config.properties.PropertyTypeConverter.INTEGER;
import static com.hazelcast.config.properties.PropertyTypeConverter.STRING;
public final class DnsRestServiceProperties {
public static final PropertyDefinition HOSTNAME =
new SimplePropertyDefinition("hostname", false, STRING);
public static final PropertyDefinition PORT =
new SimplePropertyDefinition("port", true, INTEGER);
} |
0 | java-sources/am/ik/hazelcast/hazelcast-dns-service-discovery/1.0.0/am/ik/hazelcast | java-sources/am/ik/hazelcast/hazelcast-dns-service-discovery/1.0.0/am/ik/hazelcast/dns/DnsServiceDiscoveryStrategy.java | /*
* Copyright (C) 2018 Toshiaki Maki <makingx@gmail.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 am.ik.hazelcast.dns;
import com.hazelcast.config.NetworkConfig;
import com.hazelcast.logging.ILogger;
import com.hazelcast.nio.Address;
import com.hazelcast.spi.discovery.AbstractDiscoveryStrategy;
import com.hazelcast.spi.discovery.DiscoveryNode;
import com.hazelcast.spi.discovery.SimpleDiscoveryNode;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static am.ik.hazelcast.dns.DnsRestServiceProperties.HOSTNAME;
import static am.ik.hazelcast.dns.DnsRestServiceProperties.PORT;
public class DnsServiceDiscoveryStrategy extends AbstractDiscoveryStrategy {
private final String hostname;
private final int port;
private final ILogger logger;
public DnsServiceDiscoveryStrategy(ILogger logger,
Map<String, Comparable> properties) {
super(logger, properties);
this.hostname = getOrNull(HOSTNAME);
this.port = getOrDefault(PORT, NetworkConfig.DEFAULT_PORT);
this.logger = logger;
logger.info("DnsServiceDiscoveryStrategy: created {hostname="
+ this.hostname + "}");
}
@Override
public Iterable<DiscoveryNode> discoverNodes() {
List<DiscoveryNode> discoveryNodes = new ArrayList<>();
try {
InetAddress[] addresses = InetAddress.getAllByName(hostname);
for (InetAddress address : addresses) {
discoveryNodes.add(new SimpleDiscoveryNode(new Address(address.getHostAddress(), this.port)));
}
} catch (UnknownHostException e) {
this.logger.warning(this.hostname + " can not be resolved", e);
}
return discoveryNodes;
}
@Override
public void start() {
logger.info("DnsServiceDiscoveryStrategy: started ");
}
@Override
public void destroy() {
logger.info("DnsServiceDiscoveryStrategy: destroyed");
}
} |
0 | java-sources/am/ik/hazelcast/hazelcast-dns-service-discovery/1.0.0/am/ik/hazelcast | java-sources/am/ik/hazelcast/hazelcast-dns-service-discovery/1.0.0/am/ik/hazelcast/dns/DnsServiceDiscoveryStrategyFactory.java | /*
* Copyright (C) 2018 Toshiaki Maki <makingx@gmail.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 am.ik.hazelcast.dns;
import com.hazelcast.config.properties.PropertyDefinition;
import com.hazelcast.logging.ILogger;
import com.hazelcast.spi.discovery.DiscoveryNode;
import com.hazelcast.spi.discovery.DiscoveryStrategy;
import com.hazelcast.spi.discovery.DiscoveryStrategyFactory;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import static am.ik.hazelcast.dns.DnsRestServiceProperties.HOSTNAME;
import static am.ik.hazelcast.dns.DnsRestServiceProperties.PORT;
public class DnsServiceDiscoveryStrategyFactory implements DiscoveryStrategyFactory {
private static final Collection<PropertyDefinition> PROPERTY_DEFINITIONS =
Collections.unmodifiableCollection(
Arrays.asList(HOSTNAME, PORT));
@Override
public Class<? extends DiscoveryStrategy> getDiscoveryStrategyType() {
return DnsServiceDiscoveryStrategy.class;
}
@Override
public DiscoveryStrategy newDiscoveryStrategy(DiscoveryNode discoveryNode,
ILogger logger, Map<String, Comparable> properties) {
logger.info("DnsServiceDiscoveryStrategyFactory.newDiscoveryStrategy(properties=" + properties + ")");
return new DnsServiceDiscoveryStrategy(logger, properties);
}
@Override
public Collection<PropertyDefinition> getConfigurationProperties() {
return PROPERTY_DEFINITIONS;
}
} |
0 | java-sources/am/ik/home/uaa-client/1.9.0/am/ik/home/client | java-sources/am/ik/home/uaa-client/1.9.0/am/ik/home/client/member/AsyncMemberClientImpl.java | package am.ik.home.client.member;
import static am.ik.home.client.member.TypeReferences.memberResourceType;
import static am.ik.home.client.member.TypeReferences.memberResourcesType;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import org.springframework.data.domain.Pageable;
import org.springframework.hateoas.PagedResources;
import org.springframework.hateoas.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureAdapter;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.client.AsyncRestTemplate;
public class AsyncMemberClientImpl implements MemberClient.Async {
private final String apiBase;
private final AsyncRestTemplate asyncRestTemplate;
public AsyncMemberClientImpl(String apiBase, AsyncRestTemplate asyncRestTemplate) {
this.apiBase = apiBase;
this.asyncRestTemplate = asyncRestTemplate;
}
private static <T> CompletableFuture<T> toCompletableFuture(
ListenableFuture<T> listenableFuture) {
CompletableFuture<T> completableFuture = new CompletableFuture<T>() {
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
// propagate cancel to the listenable future
boolean result = listenableFuture.cancel(mayInterruptIfRunning);
super.cancel(mayInterruptIfRunning);
return result;
}
};
listenableFuture.addCallback(new ListenableFutureCallback<T>() {
@Override
public void onSuccess(T result) {
completableFuture.complete(result);
}
@Override
public void onFailure(Throwable t) {
completableFuture.completeExceptionally(t);
}
});
return completableFuture;
}
@Override
public CompletableFuture<PagedResources<Member>> findAll(Pageable pageable) {
RequestEntity<Void> requestEntity = RequestEntities.findAll(apiBase, pageable);
return toCompletableFuture(
new ListenableFutureAdapter<PagedResources<Member>, ResponseEntity<PagedResources<Member>>>(
asyncRestTemplate.exchange(requestEntity.getUrl(),
requestEntity.getMethod(), requestEntity,
memberResourcesType)) {
@Override
protected PagedResources<Member> adapt(
ResponseEntity<PagedResources<Member>> adapteeResult)
throws ExecutionException {
return adapteeResult.getBody();
}
});
}
@Override
public CompletableFuture<Resource<Member>> findOne(String memberId) {
RequestEntity<Void> requestEntity = RequestEntities.findOne(apiBase, memberId);
return toCompletableFuture(
new ListenableFutureAdapter<Resource<Member>, ResponseEntity<Resource<Member>>>(
asyncRestTemplate.exchange(requestEntity.getUrl(),
requestEntity.getMethod(), requestEntity,
memberResourceType)) {
@Override
protected Resource<Member> adapt(
ResponseEntity<Resource<Member>> adapteeResult)
throws ExecutionException {
return adapteeResult.getBody();
}
});
}
@Override
public CompletableFuture<PagedResources<Member>> findByIds(String... ids) {
RequestEntity<Void> requestEntity = RequestEntities.findByIds(apiBase, ids);
return toCompletableFuture(
new ListenableFutureAdapter<PagedResources<Member>, ResponseEntity<PagedResources<Member>>>(
asyncRestTemplate.exchange(requestEntity.getUrl(),
requestEntity.getMethod(), requestEntity,
memberResourcesType)) {
@Override
protected PagedResources<Member> adapt(
ResponseEntity<PagedResources<Member>> adapteeResult)
throws ExecutionException {
return adapteeResult.getBody();
}
});
}
@Override
public CompletableFuture<Resource<Member>> findByEmail(String email) {
RequestEntity<Void> requestEntity = RequestEntities.findByEmail(apiBase, email);
return toCompletableFuture(
new ListenableFutureAdapter<Resource<Member>, ResponseEntity<Resource<Member>>>(
asyncRestTemplate.exchange(requestEntity.getUrl(),
requestEntity.getMethod(), requestEntity,
memberResourceType)) {
@Override
protected Resource<Member> adapt(
ResponseEntity<Resource<Member>> adapteeResult)
throws ExecutionException {
return adapteeResult.getBody();
}
});
}
}
|
0 | java-sources/am/ik/home/uaa-client/1.9.0/am/ik/home/client | java-sources/am/ik/home/uaa-client/1.9.0/am/ik/home/client/member/Member.java | package am.ik.home.client.member;
import java.io.Serializable;
import java.util.List;
public class Member implements Serializable {
private String memberId;
private String givenName;
private String familyName;
private String email;
private List<MemberRole> roles;
public String getMemberId() {
return memberId;
}
public void setMemberId(String memberId) {
this.memberId = memberId;
}
public String getGivenName() {
return givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getFamilyName() {
return familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<MemberRole> getRoles() {
return roles;
}
public void setRoles(List<MemberRole> roles) {
this.roles = roles;
}
@Override
public String toString() {
return "Member{" + "memberId='" + memberId + '\'' + ", givenName='" + givenName
+ '\'' + ", familyName='" + familyName + '\'' + ", email='" + email + '\''
+ ", roles=" + roles + '}';
}
}
|
0 | java-sources/am/ik/home/uaa-client/1.9.0/am/ik/home/client | java-sources/am/ik/home/uaa-client/1.9.0/am/ik/home/client/member/MemberClient.java | package am.ik.home.client.member;
import java.util.concurrent.CompletableFuture;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.hateoas.PagedResources;
import org.springframework.hateoas.Resource;
public interface MemberClient {
PagedResources<Member> findAll(Pageable pageable);
default PagedResources<Member> findAll() {
return findAll(new PageRequest(0, 20));
}
Resource<Member> findOne(String memberId);
PagedResources<Member> findByIds(String... ids);
Resource<Member> findByEmail(String email);
interface Async {
CompletableFuture<PagedResources<Member>> findAll(Pageable pageable);
default CompletableFuture<PagedResources<Member>> findAll() {
return findAll(new PageRequest(0, 20));
}
CompletableFuture<Resource<Member>> findOne(String memberId);
CompletableFuture<PagedResources<Member>> findByIds(String... ids);
CompletableFuture<Resource<Member>> findByEmail(String email);
}
}
|
0 | java-sources/am/ik/home/uaa-client/1.9.0/am/ik/home/client | java-sources/am/ik/home/uaa-client/1.9.0/am/ik/home/client/member/MemberClientImpl.java | package am.ik.home.client.member;
import static am.ik.home.client.member.TypeReferences.memberResourceType;
import static am.ik.home.client.member.TypeReferences.memberResourcesType;
import org.springframework.data.domain.Pageable;
import org.springframework.hateoas.PagedResources;
import org.springframework.hateoas.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.web.client.RestTemplate;
public class MemberClientImpl implements MemberClient {
private final String apiBase;
private final RestTemplate restTemplate;
public MemberClientImpl(String apiBase, RestTemplate restTemplate) {
this.apiBase = apiBase;
this.restTemplate = restTemplate;
}
@Override
public PagedResources<Member> findAll(Pageable pageable) {
RequestEntity<Void> requestEntity = RequestEntities.findAll(apiBase, pageable);
return restTemplate.exchange(requestEntity, memberResourcesType).getBody();
}
@Override
public Resource<Member> findOne(String memberId) {
RequestEntity<Void> requestEntity = RequestEntities.findOne(apiBase, memberId);
return restTemplate.exchange(requestEntity, memberResourceType).getBody();
}
@Override
public PagedResources<Member> findByIds(String... ids) {
RequestEntity<Void> requestEntity = RequestEntities.findByIds(apiBase, ids);
return restTemplate.exchange(requestEntity, memberResourcesType).getBody();
}
@Override
public Resource<Member> findByEmail(String email) {
RequestEntity<Void> requestEntity = RequestEntities.findByEmail(apiBase, email);
return restTemplate.exchange(requestEntity, memberResourceType).getBody();
}
}
|
0 | java-sources/am/ik/home/uaa-client/1.9.0/am/ik/home/client | java-sources/am/ik/home/uaa-client/1.9.0/am/ik/home/client/member/MemberRole.java | package am.ik.home.client.member;
public enum MemberRole {
USER, ADMIN, ACTUATOR
}
|
0 | java-sources/am/ik/home/uaa-client/1.9.0/am/ik/home/client | java-sources/am/ik/home/uaa-client/1.9.0/am/ik/home/client/member/PageableUtils.java | package am.ik.home.client.member;
import org.springframework.data.domain.Pageable;
import org.springframework.web.util.UriComponentsBuilder;
class PageableUtils {
static UriComponentsBuilder withPageable(UriComponentsBuilder builder,
Pageable pageable) {
builder.queryParam("page", pageable.getPageNumber()).queryParam("size",
pageable.getPageSize());
if (pageable.getSort() != null) {
StringBuilder sb = new StringBuilder();
pageable.getSort().forEach(order -> {
sb.append(order.getProperty()).append(",").append(order.getDirection());
});
builder.queryParam("sort", sb.toString());
}
return builder;
}
}
|
0 | java-sources/am/ik/home/uaa-client/1.9.0/am/ik/home/client | java-sources/am/ik/home/uaa-client/1.9.0/am/ik/home/client/member/RequestEntities.java | package am.ik.home.client.member;
import static am.ik.home.client.member.PageableUtils.withPageable;
import static org.springframework.http.RequestEntity.get;
import static org.springframework.web.util.UriComponentsBuilder.fromHttpUrl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.RequestEntity;
import org.springframework.web.util.UriComponentsBuilder;
class RequestEntities {
static RequestEntity<Void> findAll(String apiBase, Pageable pageable) {
UriComponentsBuilder builder = fromHttpUrl(apiBase).pathSegment("v1", "members");
return get(withPageable(builder, pageable).build().encode().toUri()).build();
}
static RequestEntity<Void> findOne(String apiBase, String memberId) {
return get(fromHttpUrl(apiBase).pathSegment("v1", "members", memberId).build()
.encode().toUri()).build();
}
static RequestEntity<Void> findByIds(String apiBase, String... ids) {
return get(
fromHttpUrl(apiBase).pathSegment("v1", "members", "search", "findByIds")
.queryParam("ids", (Object[]) ids).build().encode().toUri())
.build();
}
static RequestEntity<Void> findByEmail(String apiBase, String email) {
return get(
fromHttpUrl(apiBase).pathSegment("v1", "members", "search", "findByEmail")
.queryParam("email", email).build().encode().toUri()).build();
}
}
|
0 | java-sources/am/ik/home/uaa-client/1.9.0/am/ik/home/client | java-sources/am/ik/home/uaa-client/1.9.0/am/ik/home/client/member/TypeReferences.java | package am.ik.home.client.member;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.hateoas.PagedResources;
import org.springframework.hateoas.Resource;
class TypeReferences {
final static ParameterizedTypeReference<Resource<Member>> memberResourceType = new ParameterizedTypeReference<Resource<Member>>() {
};
final static ParameterizedTypeReference<PagedResources<Member>> memberResourcesType = new ParameterizedTypeReference<PagedResources<Member>>() {
};
}
|
0 | java-sources/am/ik/home/uaa-client/1.9.0/am/ik/home/client | java-sources/am/ik/home/uaa-client/1.9.0/am/ik/home/client/user/UaaUser.java | package am.ik.home.client.user;
import java.io.IOException;
import java.io.Serializable;
import java.io.UncheckedIOException;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.util.Base64Utils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class UaaUser implements Serializable {
public static final String ACCESS_TOKEN_MESSAGE_HEADER = "accessToken";
private static final Logger log = LoggerFactory.getLogger(UaaUser.class);
private final String userId;
private final String email;
private final String displayName;
private final Set<String> scope;
private final Set<String> authorities;
public UaaUser(ObjectMapper objectMapper) {
this(objectMapper, getTokenValueFromSecurityContext());
}
public UaaUser(ObjectMapper objectMapper, String jwtAccessToken) {
String payload = jwtAccessToken.split("\\.")[1];
try {
JsonNode json = objectMapper.readValue(
Base64Utils.decodeFromUrlSafeString(payload), JsonNode.class);
log.debug("Payload of accessToken = {}", json);
this.userId = json.get("user_id").asText();
this.email = json.get("email").asText();
this.displayName = json.get("display_name").asText();
Set<String> scope = new LinkedHashSet<>();
if (json.has("scope")) {
for (JsonNode node : json.get("scope")) {
scope.add(node.asText());
}
}
this.scope = Collections.unmodifiableSet(scope);
Set<String> authorities = new LinkedHashSet<>();
if (json.has("authorities")) {
for (JsonNode node : json.get("authorities")) {
authorities.add(node.asText());
}
}
this.authorities = Collections.unmodifiableSet(authorities);
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static String getTokenValueFromSecurityContext() {
Authentication authentication = SecurityContextHolder.getContext()
.getAuthentication();
OAuth2Authentication auth = OAuth2Authentication.class.cast(authentication);
OAuth2AuthenticationDetails details = OAuth2AuthenticationDetails.class
.cast(auth.getDetails());
return details.getTokenValue();
}
public String getUserId() {
return userId;
}
public String getEmail() {
return email;
}
public String getDisplayName() {
return displayName;
}
public Set<String> getScope() {
return scope;
}
public Set<String> getAuthorities() {
return authorities;
}
@Override
public String toString() {
return "UaaUser{" + "userId='" + userId + '\'' + ", email='" + email + '\''
+ ", displayName='" + displayName + '\'' + ", scope=" + scope
+ ", authorities=" + authorities + '}';
}
}
|
0 | java-sources/am/ik/home/uaa-server/1.9.0/am/ik | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home/JwtConfigProps.java | package am.ik.home;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import lombok.Data;
@ConfigurationProperties(prefix = "jwt")
@Validated
@Data
@Component
public class JwtConfigProps {
private String issuer;
private String verifierKey;
private String signingKey;
}
|
0 | java-sources/am/ik/home/uaa-server/1.9.0/am/ik | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home/UaaApplication.java | package am.ik.home;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import javax.sql.DataSource;
import org.apache.catalina.filters.RequestDumperFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.oauth2.authserver.AuthorizationServerProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import am.ik.home.app.AppClientDetails;
import am.ik.home.app.AppRepository;
import am.ik.home.member.Member;
@SpringBootApplication
public class UaaApplication {
public static void main(String[] args) {
SpringApplication.run(UaaApplication.class, args);
}
@Bean
PasswordEncoder passwordEncoder() {
return new Pbkdf2PasswordEncoder();
}
@Profile("!cloud")
@Bean
RequestDumperFilter requestDumperFilter() {
return new RequestDumperFilter();
}
@Configuration
static class RestMvcConfig extends RepositoryRestConfigurerAdapter {
@Override
public void configureRepositoryRestConfiguration(
RepositoryRestConfiguration config) {
config.exposeIdsFor(Member.class);
}
}
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(-20)
static class LoginConfig extends WebSecurityConfigurerAdapter {
@Autowired
DataSource dataSource;
@Autowired
UserDetailsService userDetailsService;
@Bean
PersistentTokenRepository persistentTokenRepository() {
JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
tokenRepository.setDataSource(dataSource);
return tokenRepository;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin().loginPage("/login").permitAll().and().requestMatchers()
.antMatchers("/", "/apps", "/login", "/logout", "/oauth/authorize",
"/oauth/confirm_access", "/admin/**")
.and().authorizeRequests().antMatchers("/login**").permitAll()
.antMatchers("/apps**").access("hasRole('ADMIN')").anyRequest()
.authenticated().and().rememberMe()
.tokenRepository(persistentTokenRepository())
.userDetailsService(userDetailsService)
.tokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(7)).and().logout()
.deleteCookies("JSESSIONID", "remember-me").permitAll().and().csrf()
.ignoringAntMatchers("/oauth/**");
}
}
@Configuration
@EnableAuthorizationServer
@EnableConfigurationProperties(AuthorizationServerProperties.class)
static class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
AuthenticationManager authenticationManager;
@Autowired
AppRepository appRepository;
@Autowired
TokenEnhancer tokenEnhancer;
@Autowired
AuthorizationServerProperties props;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.withClientDetails(clientId -> appRepository.findByAppId(clientId)
.map(AppClientDetails::new)
.orElseThrow(() -> new ClientRegistrationException(
"The given client is invalid")));
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(
Arrays.asList(tokenEnhancer, jwtAccessTokenConverter()));
endpoints.authenticationManager(authenticationManager)
.tokenEnhancer(tokenEnhancerChain)
.pathMapping("/oauth/token_key", "/token_key")
.pathMapping("/oauth/check_token", "/check_token");
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security)
throws Exception {
security.tokenKeyAccess(props.getTokenKeyAccess());
security.checkTokenAccess(props.getCheckTokenAccess());
}
@Bean
@ConfigurationProperties("jwt")
JwtAccessTokenConverter jwtAccessTokenConverter() {
return new JwtAccessTokenConverter();
}
}
@Configuration
@EnableResourceServer
static class OAuth2ResourceConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests().mvcMatchers("/userinfo")
.access("#oauth2.hasScope('openid')")
.antMatchers(HttpMethod.GET, "/v1/members/**")
.access("#oauth2.clientHasRole('ROLE_TRUSTED_CLIENT') and (#oauth2.hasScope('member.read') or #oauth2.hasScope('admin.read'))")
.antMatchers(HttpMethod.POST, "/v1/members/**")
.access("#oauth2.clientHasRole('ROLE_TRUSTED_CLIENT') and (#oauth2.hasScope('member.write') or #oauth2.hasScope('admin.write'))");
}
}
}
|
0 | java-sources/am/ik/home/uaa-server/1.9.0/am/ik | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home/UaaController.java | package am.ik.home;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import am.ik.home.member.Member;
import lombok.RequiredArgsConstructor;
@Controller
@RequiredArgsConstructor
public class UaaController {
@GetMapping("/login")
String login() {
return "login";
}
@ResponseBody
@GetMapping(path = "/userinfo")
Object user(@AuthenticationPrincipal(expression = "member") Member member) {
Map<String, Object> user = new LinkedHashMap<>();
user.put("id", member.getMemberId());
user.put("email", member.getEmail());
Map<String, Object> name = new LinkedHashMap<>();
name.put("givenName", member.getGivenName());
name.put("familyName", member.getFamilyName());
user.put("name", name);
return user;
}
}
|
0 | java-sources/am/ik/home/uaa-server/1.9.0/am/ik | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home/UaaTokenEnhancer.java | package am.ik.home;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;
import am.ik.home.app.AppRepository;
import am.ik.home.member.Member;
import am.ik.home.member.MemberUserDetails;
@Component
public class UaaTokenEnhancer implements TokenEnhancer {
private final String issuer;
private final AppRepository appRepository;
public UaaTokenEnhancer(
@Value("${jwt.issuer:${spring.application.name}}") String issuer,
AppRepository appRepository) {
this.issuer = issuer;
this.appRepository = appRepository;
}
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken,
OAuth2Authentication authentication) {
if (authentication.getPrincipal() instanceof MemberUserDetails) {
MemberUserDetails userDetails = (MemberUserDetails) authentication
.getPrincipal();
Member member = userDetails.getMember();
Instant expiration = accessToken.getExpiration().toInstant();
Map<String, Object> additionalInfo = new LinkedHashMap<>();
additionalInfo.put("user_id", member.getMemberId());
additionalInfo.put("email", member.getEmail());
additionalInfo.put("family_name", member.getFamilyName());
additionalInfo.put("given_name", member.getGivenName());
additionalInfo.put("display_name",
member.getFamilyName() + " " + member.getGivenName());
additionalInfo.put("iss", issuer);
additionalInfo.put("exp", expiration.getEpochSecond());
// Retrieves client information
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String appId = auth.getName();
appRepository.findByAppId(appId).ifPresent(app -> {
Integer validitySeconds = app.getAccessTokenValiditySeconds();
Instant iat = expiration.minusSeconds(validitySeconds);
additionalInfo.put("iat", iat.getEpochSecond());
});
((DefaultOAuth2AccessToken) accessToken)
.setAdditionalInformation(additionalInfo);
}
return accessToken;
}
}
|
0 | java-sources/am/ik/home/uaa-server/1.9.0/am/ik | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home/WhitelabelConfigProps.java | package am.ik.home;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import lombok.Data;
@ConfigurationProperties(prefix = "whitelabel")
@Data
@Component
public class WhitelabelConfigProps {
private String applicationName = "Maki UAA";
}
|
0 | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home/app/App.java | package am.ik.home.app;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.persistence.*;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.URL;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class App implements Serializable {
public static final String DEFAULT_RESOURCE_ID = "oauth2-resource";
@Id
@Column(columnDefinition = "varchar(36)")
@Size(min = 36, max = 36)
private String appId;
@NotEmpty
@Size(max = 255)
private String appName;
@URL
@NotEmpty
@Size(max = 255)
private String appUrl;
@Size(max = 255)
private String appSecret;
@ElementCollection(fetch = FetchType.EAGER)
@Enumerated(EnumType.STRING)
@NotNull
private Set<AppRole> roles;
@ElementCollection(fetch = FetchType.EAGER)
@Enumerated(EnumType.STRING)
@NotEmpty
private Set<AppGrantType> grantTypes;
@ElementCollection(fetch = FetchType.EAGER)
private Set<String> resourceIds = new HashSet<String>() {
{
add(DEFAULT_RESOURCE_ID);
}
};
@ElementCollection(fetch = FetchType.EAGER)
private Set<String> scopes;
@ElementCollection(fetch = FetchType.EAGER)
@NotNull
private Set<String> redirectUrls;
@Max(600000)
@Min(0)
@NotNull
private Integer accessTokenValiditySeconds = (int) TimeUnit.HOURS.toSeconds(3);
@Max(600000)
@Min(0)
@NotNull
private Integer refreshTokenValiditySeconds = (int) TimeUnit.HOURS.toSeconds(12);
@ElementCollection(fetch = FetchType.EAGER)
private Set<String> autoApproveScopes;
}
|
0 | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home/app/AppClientDetails.java | package am.ik.home.app;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toSet;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.util.CollectionUtils;
public class AppClientDetails extends BaseClientDetails {
private final App app;
public AppClientDetails(App app) {
super(app.getAppId(),
CollectionUtils.isEmpty(app.getResourceIds()) ? App.DEFAULT_RESOURCE_ID
: app.getResourceIds().stream().collect(joining(",")),
app.getScopes().stream().distinct().map(String::toLowerCase)
.collect(joining(",")),
app.getGrantTypes().stream().map(Enum::name).distinct()
.map(String::toLowerCase).collect(joining(",")),
app.getRoles().stream().map(Enum::name).map(String::toUpperCase)
.map(s -> "ROLE_" + s).distinct().collect(joining(",")),
app.getRedirectUrls().stream().distinct().map(String::toLowerCase)
.collect(joining(",")));
setClientSecret(app.getAppSecret());
setAccessTokenValiditySeconds(app.getAccessTokenValiditySeconds());
setRefreshTokenValiditySeconds(app.getRefreshTokenValiditySeconds());
setAutoApproveScopes(app.getAutoApproveScopes().stream().map(String::toLowerCase)
.collect(toSet()));
this.app = app;
}
public String getAppName() {
return app.getAppName();
}
public String getAppUrl() {
return app.getAppUrl();
}
}
|
0 | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home/app/AppController.java | package am.ik.home.app;
import java.util.UUID;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import lombok.RequiredArgsConstructor;
@Controller
@RequestMapping(path = "apps")
@RequiredArgsConstructor
public class AppController {
private final AppRepository appRepository;
@GetMapping(params = "new")
String newApp(Model model) {
model.addAttribute("app", new App());
return "apps/new";
}
@PostMapping(params = "new")
String newApp(@Validated App app, BindingResult result) {
if (result.hasErrors()) {
return "apps/new";
}
app.setAppId(UUID.randomUUID().toString());
app.setAppSecret(UUID.randomUUID().toString());
appRepository.save(app);
return "redirect:/";
}
@GetMapping(params = "edit")
String edit(@RequestParam("appId") String appId, Model model) {
App app = appRepository.findOne(appId);
model.addAttribute("app", app);
return "apps/edit";
}
@PostMapping(params = "edit")
String edit(@RequestParam("appId") String appId,
@RequestParam(name = "regenerateSecret", defaultValue = "false") boolean regenerateSecret,
@Validated App app, BindingResult result, RedirectAttributes attributes) {
if (result.hasErrors()) {
return "apps/edit";
}
app.setAppId(appId);
if (regenerateSecret) {
app.setAppSecret(UUID.randomUUID().toString());
}
appRepository.save(app);
attributes.addAttribute("appId", appId);
return "redirect:/apps?edit";
}
@DeleteMapping
String delete(@RequestParam("appId") String appId) {
appRepository.delete(appId);
return "redirect:/";
}
}
|
0 | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home/app/AppGrantType.java | package am.ik.home.app;
public enum AppGrantType {
PASSWORD, AUTHORIZATION_CODE, REFRESH_TOKEN, IMPLICIT, CLIENT_CREDENTIALS
}
|
0 | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home/app/AppRepository.java | package am.ik.home.app;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(exported = false)
public interface AppRepository extends JpaRepository<App, String> {
Optional<App> findByAppId(String appId);
Optional<App> findByAppName(String appName);
Optional<App> findByAppUrl(String appUrl);
}
|
0 | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home/app/AppRole.java | package am.ik.home.app;
public enum AppRole {
CLIENT, TRUSTED_CLIENT
}
|
0 | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home/cloudfoundry/CloudConfig.java | package am.ik.home.cloudfoundry;
import javax.sql.DataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.config.java.AbstractCloudConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Profile("cloud")
@Configuration
public class CloudConfig extends AbstractCloudConfig {
@ConfigurationProperties(prefix = "spring.datasource.tomcat")
@Bean
DataSource dataSource() {
return connectionFactory().dataSource();
}
}
|
0 | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home/cloudfoundry | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home/cloudfoundry/broker/ServiceBrokerSecurityConfig.java | package am.ik.home.cloudfoundry.broker;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import lombok.RequiredArgsConstructor;
@EnableWebSecurity
@RequiredArgsConstructor
@Order(-15)
public class ServiceBrokerSecurityConfig extends WebSecurityConfigurerAdapter {
private final SecurityProperties security;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/v2/**").authorizeRequests()
.antMatchers("/v2/catalog", "/v2/service_instances/**").authenticated()
.and().httpBasic().and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().csrf()
.disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser(security.getUser().getName())
.password(security.getUser().getPassword())
.roles(security.getUser().getRole().toArray(new String[0]));
}
}
|
0 | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home/cloudfoundry | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home/cloudfoundry/broker/UaaCatalogFactoryBean.java | package am.ik.home.cloudfoundry.broker;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.servicebroker.model.Catalog;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
@Component
public class UaaCatalogFactoryBean implements FactoryBean<Catalog> {
@Value("${servicebroker.catalog-json:classpath:catalog.json}")
Resource catalog;
@Autowired
ObjectMapper objectMapper;
@Override
public Catalog getObject() throws Exception {
Catalog catalog = objectMapper.readValue(this.catalog.getInputStream(),
Catalog.class);
return catalog;
}
@Override
public Class<?> getObjectType() {
return Catalog.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
|
0 | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home/cloudfoundry | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home/cloudfoundry/broker/UaaServiceInstanceBindingService.java | package am.ik.home.cloudfoundry.broker;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.servicebroker.model.CreateServiceInstanceAppBindingResponse;
import org.springframework.cloud.servicebroker.model.CreateServiceInstanceBindingRequest;
import org.springframework.cloud.servicebroker.model.CreateServiceInstanceBindingResponse;
import org.springframework.cloud.servicebroker.model.DeleteServiceInstanceBindingRequest;
import org.springframework.cloud.servicebroker.service.ServiceInstanceBindingService;
import org.springframework.stereotype.Component;
import am.ik.home.app.App;
import am.ik.home.app.AppRepository;
@Component
public class UaaServiceInstanceBindingService implements ServiceInstanceBindingService {
private final AppRepository appRepository;
private final String appDomain;
public UaaServiceInstanceBindingService(AppRepository appRepository,
@Value("${vcap.application.uris[0]:example.com}") String appUrl,
@Value("${server.context-path:}") String contextPath) {
this.appRepository = appRepository;
this.appDomain = appUrl + contextPath;
}
@Override
public CreateServiceInstanceBindingResponse createServiceInstanceBinding(
CreateServiceInstanceBindingRequest request) {
String serviceInstanceId = request.getServiceInstanceId();
App app = appRepository.findByAppId(serviceInstanceId)
.orElseThrow(() -> new IllegalStateException(
"the requested app is not found! (appId=" + serviceInstanceId
+ ")"));
Map<String, Object> credentials = new HashMap<>();
credentials.put("client_id", app.getAppId());
credentials.put("client_secret", app.getAppSecret());
credentials.put("auth_domain", "https://" + appDomain);
return new CreateServiceInstanceAppBindingResponse().withCredentials(credentials);
}
@Override
public void deleteServiceInstanceBinding(
DeleteServiceInstanceBindingRequest request) {
}
}
|
0 | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home/cloudfoundry | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home/cloudfoundry/broker/UaaServiceInstanceService.java | package am.ik.home.cloudfoundry.broker;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.springframework.cloud.servicebroker.model.*;
import org.springframework.cloud.servicebroker.service.ServiceInstanceService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import am.ik.home.app.App;
import am.ik.home.app.AppGrantType;
import am.ik.home.app.AppRepository;
import am.ik.home.app.AppRole;
import lombok.RequiredArgsConstructor;
@Component
@RequiredArgsConstructor
public class UaaServiceInstanceService implements ServiceInstanceService {
private final AppRepository appRepository;
@Override
public CreateServiceInstanceResponse createServiceInstance(
CreateServiceInstanceRequest request) {
ArbitraryParameters parameters = new ArbitraryParameters(request.getParameters());
String serviceInstanceId = request.getServiceInstanceId();
App app = App.builder().appId(serviceInstanceId)
.appSecret(UUID.randomUUID().toString())
.roles(Collections.singleton(AppRole.CLIENT))
.scopes(Collections.singleton("openid"))
.autoApproveScopes(Collections.singleton("openid"))
.grantTypes(new HashSet<AppGrantType>() {
{
add(AppGrantType.AUTHORIZATION_CODE);
add(AppGrantType.PASSWORD);
}
}).accessTokenValiditySeconds((int) TimeUnit.HOURS.toSeconds(3))
.refreshTokenValiditySeconds(0).build();
app.setAppUrl(parameters.appUrl()
.orElseGet(() -> "http://" + app.getAppId() + ".example.com"));
app.setAppName(parameters.appName().orElseGet(app::getAppId));
app.setRedirectUrls(parameters.redirectUrls()
.map(urls -> urls.stream().collect(Collectors.toSet()))
.orElseGet(Collections::emptySet));
appRepository.save(app);
return new CreateServiceInstanceResponse();
}
@Override
public GetLastServiceOperationResponse getLastOperation(
GetLastServiceOperationRequest request) {
return new GetLastServiceOperationResponse();
}
@Override
public DeleteServiceInstanceResponse deleteServiceInstance(
DeleteServiceInstanceRequest request) {
String serviceInstanceId = request.getServiceInstanceId();
appRepository.delete(serviceInstanceId);
return new DeleteServiceInstanceResponse();
}
@Override
@Transactional
public UpdateServiceInstanceResponse updateServiceInstance(
UpdateServiceInstanceRequest request) {
appRepository.findByAppId(request.getServiceInstanceId()).ifPresent(app -> {
ArbitraryParameters parameters = new ArbitraryParameters(
request.getParameters());
parameters.appUrl().ifPresent(app::setAppUrl);
parameters.appName().ifPresent(app::setAppName);
parameters.redirectUrls().ifPresent(urls -> app
.setRedirectUrls(urls.stream().collect(Collectors.toSet())));
});
return new UpdateServiceInstanceResponse();
}
private static class ArbitraryParameters {
final Map<String, Object> parameters;
ArbitraryParameters(Map<String, Object> parameters) {
this.parameters = parameters == null ? Collections.emptyMap() : parameters;
}
Optional<String> appUrl() {
return Optional.ofNullable(parameters.get("appUrl")).map(Object::toString);
}
Optional<String> appName() {
return Optional.ofNullable(parameters.get("appName")).map(Object::toString);
}
@SuppressWarnings("unchecked")
Optional<Collection<String>> redirectUrls() {
return Optional.ofNullable(parameters.get("redirectUrls"))
.map(Collection.class::cast);
}
}
}
|
0 | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home/member/Member.java | package am.ik.home.member;
import java.io.Serializable;
import java.util.List;
import javax.persistence.*;
import org.hibernate.annotations.GenericGenerator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Member implements Serializable {
@Id
@GenericGenerator(name = "uuid", strategy = "uuid2")
@GeneratedValue(generator = "uuid")
@Column(columnDefinition = "varchar(36)")
private String memberId;
private String givenName;
private String familyName;
@JsonIgnore
private String password;
@Column(unique = true)
private String email;
@ElementCollection(fetch = FetchType.EAGER)
@Enumerated(EnumType.STRING)
private List<MemberRole> roles;
}
|
0 | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home/member/MemberController.java | package am.ik.home.member;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import am.ik.home.app.App;
import am.ik.home.app.AppRepository;
import lombok.RequiredArgsConstructor;
@Controller
@RequiredArgsConstructor
public class MemberController {
private final MemberService memberService;
private final MemberRepository memberRepository;
private final AppRepository appRepository;
@GetMapping("/")
String home(Model model) {
List<App> apps = appRepository.findAll();
List<Member> members = memberRepository.findAll();
model.addAttribute("apps", apps);
model.addAttribute("members", members);
return "home";
}
@GetMapping(path = "/", params = "new")
String newMember(Model model) {
model.addAttribute("memberForm", new MemberForm());
return "members/new";
}
@PostMapping(path = "/", params = "new")
String newMember(@Validated MemberForm form, BindingResult result) {
if (result.hasErrors()) {
return "members/new";
}
Member member = new Member();
BeanUtils.copyProperties(form, member);
memberService.save(member, form.getRawPassword());
return "redirect:/";
}
@GetMapping(path = "/", params = "edit")
String editLogin(
@AuthenticationPrincipal(expression = "member.memberId") String memberId,
Model model) {
MemberForm form = new MemberForm();
memberRepository.findOne(memberId).ifPresent(member -> {
model.addAttribute("member", member);
BeanUtils.copyProperties(member, form);
});
model.addAttribute("memberForm", form);
return "members/edit";
}
@GetMapping(path = "/", params = { "edit", "memberId" })
String edit(@RequestParam("memberId") String memberId, Model model) {
return editLogin(memberId, model);
}
@PostMapping(path = "/", params = "edit")
String edit(@RequestParam("memberId") String memberId, @Validated MemberForm form,
BindingResult result, Model model, RedirectAttributes attributes) {
Member member = memberRepository.findOne(memberId).get();
if (result.hasErrors()) {
model.addAttribute("member", member);
return "members/edit";
}
Member updated = new Member();
BeanUtils.copyProperties(form, updated);
updated.setMemberId(memberId);
memberService.save(updated, form.getRawPassword());
attributes.addFlashAttribute("updated", true);
attributes.addAttribute("memberId", memberId);
return "redirect:/?edit";
}
@DeleteMapping(path = "/")
String delete(@RequestParam("memberId") String memberId) {
memberService.delete(memberId);
return "redirect:/";
}
}
|
0 | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home/member/MemberForm.java | package am.ik.home.member;
import java.io.Serializable;
import java.util.List;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.terasoluna.gfw.common.validator.constraints.Compare;
import lombok.Data;
@Data
@Compare(left = "rawPassword", right = "passwordConfirm", operator = Compare.Operator.EQUAL, message = "'rawPassword' and 'passwordConfirm' must be same")
public class MemberForm implements Serializable {
@NotEmpty
@Size(max = 255)
private String givenName;
@NotEmpty
@Size(max = 255)
private String familyName;
@NotEmpty
@Size(min = 6, max = 50)
private String rawPassword;
@NotEmpty
@Size(min = 6, max = 50)
private String passwordConfirm;
@NotEmpty
@Size(max = 255)
@Email
private String email;
private List<MemberRole> roles;
}
|
0 | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home/member/MemberRepository.java | package am.ik.home.member;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RestResource;
public interface MemberRepository extends Repository<Member, String> {
Optional<Member> findOne(String memberId);
Optional<Member> findByEmail(@Param("email") String email);
@Query("SELECT x FROM Member x WHERE x.memberId IN (:ids) ORDER BY x.familyName, x.givenName")
List<Member> findByIds(@Param("ids") List<String> ids);
List<Member> findAll();
@RestResource(exported = false)
Member save(Member member);
long countByRoles(MemberRole role);
@RestResource(exported = false)
void delete(String memberId);
}
|
0 | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home/member/MemberRole.java | package am.ik.home.member;
public enum MemberRole {
ADMIN, USER, ACTUATOR
}
|
0 | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home/member/MemberService.java | package am.ik.home.member;
import org.springframework.security.access.method.P;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.RequiredArgsConstructor;
@Service
@Transactional
@RequiredArgsConstructor
public class MemberService {
private final MemberRepository memberRepository;
private final PasswordEncoder passwordEncoder;
@PreAuthorize("hasRole('ADMIN') or #member.memberId == principal.member.memberId")
public Member save(@P("member") Member member, String rawPassword) {
member.setPassword(passwordEncoder.encode(rawPassword));
memberRepository.save(member);
if (memberRepository.countByRoles(MemberRole.ADMIN) == 0) {
throw new IllegalStateException("At least one ADMIN required!");
}
return member;
}
@PreAuthorize("hasRole('ADMIN') or #memberId == principal.member.memberId")
public void delete(@P("memberId") String memberId) {
memberRepository.delete(memberId);
if (memberRepository.countByRoles(MemberRole.ADMIN) == 0) {
throw new IllegalStateException("At least one ADMIN required!");
}
}
}
|
0 | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home/member/MemberUserDetails.java | package am.ik.home.member;
import java.util.stream.Collectors;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
public class MemberUserDetails extends User {
private final Member member;
public MemberUserDetails(Member member) {
super(member.getMemberId(), member.getPassword(),
member.getRoles().stream().map(r -> "ROLE_" + r.name().toUpperCase())
.map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
this.member = member;
}
public Member getMember() {
return member;
}
}
|
0 | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home | java-sources/am/ik/home/uaa-server/1.9.0/am/ik/home/member/MemberUserDetailsService.java | package am.ik.home.member;
import java.util.Optional;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
@Component
public class MemberUserDetailsService implements UserDetailsService {
private final MemberRepository memberRepository;
public MemberUserDetailsService(MemberRepository memberRepository) {
this.memberRepository = memberRepository;
}
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
Optional<Member> member = username.contains("@")
? memberRepository.findByEmail(username)
: memberRepository.findOne(username);
return member.map(MemberUserDetails::new)
.orElseThrow(() -> new UsernameNotFoundException("not found"));
}
}
|
0 | java-sources/am/ik/home/uaa-server/1.9.0/db | java-sources/am/ik/home/uaa-server/1.9.0/db/migration/V6__add_actuator_role.java | package db.migration;
import org.flywaydb.core.api.migration.spring.SpringJdbcMigration;
import org.springframework.jdbc.core.JdbcTemplate;
public class V6__add_actuator_role implements SpringJdbcMigration {
@Override
public void migrate(JdbcTemplate jdbcTemplate) throws Exception {
Long count = jdbcTemplate.queryForObject(
"SELECT count(*) FROM member WHERE member_id='00000000-0000-0000-0000-000000000000'",
Long.class);
if (count == 1) {
jdbcTemplate.update(
"INSERT INTO member_roles (member_member_id, roles) VALUES ('00000000-0000-0000-0000-000000000000', 'ACTUATOR');");
}
}
} |
0 | java-sources/am/ik/home/uaa-server/1.9.0/db | java-sources/am/ik/home/uaa-server/1.9.0/db/migration/V8__add_credhub_app.java | package db.migration;
import org.flywaydb.core.api.migration.spring.SpringJdbcMigration;
import org.springframework.jdbc.core.JdbcTemplate;
public class V8__add_credhub_app implements SpringJdbcMigration {
@Override
public void migrate(JdbcTemplate jdbcTemplate) throws Exception {
Long count = jdbcTemplate.queryForObject(
"SELECT count(*) FROM app WHERE app_name='CredHub' or app_url='http://localhost:9000'",
Long.class);
if (count == 0) {
jdbcTemplate.update(
"INSERT INTO app (access_token_validity_seconds, app_name, app_secret, app_url, refresh_token_validity_seconds, app_id) VALUES (1800, 'CredHub', '00000000-0000-0000-0000-00000000000a', 'http://localhost:9000', 259200, '00000000-0000-0000-0000-00000000000a')");
jdbcTemplate.update(
"INSERT INTO app_grant_types (app_app_id, grant_types) VALUES ('00000000-0000-0000-0000-00000000000a', 'PASSWORD')");
jdbcTemplate.update(
"INSERT INTO app_grant_types (app_app_id, grant_types) VALUES ('00000000-0000-0000-0000-00000000000a', 'AUTHORIZATION_CODE')");
jdbcTemplate.update(
"INSERT INTO app_grant_types (app_app_id, grant_types) VALUES ('00000000-0000-0000-0000-00000000000a', 'REFRESH_TOKEN')");
jdbcTemplate.update(
"INSERT INTO app_redirect_urls (app_app_id, redirect_urls) VALUES ('00000000-0000-0000-0000-00000000000a', 'http://localhost:9000/login')");
jdbcTemplate.update(
"INSERT INTO app_roles (app_app_id, roles) VALUES ('00000000-0000-0000-0000-00000000000a', 'CLIENT')");
jdbcTemplate.update(
"INSERT INTO app_scopes (app_app_id, scopes) VALUES ('00000000-0000-0000-0000-00000000000a', 'credhub.write');");
jdbcTemplate.update(
"INSERT INTO app_scopes (app_app_id, scopes) VALUES ('00000000-0000-0000-0000-00000000000a', 'credhub.read');");
jdbcTemplate.update(
"INSERT INTO app_grant_types (app_app_id, grant_types) VALUES ('00000000-0000-0000-0000-00000000000a', 'REFRESH_TOKEN')");
jdbcTemplate.update(
"INSERT INTO app_resource_ids (app_app_id, resource_ids) VALUES ('00000000-0000-0000-0000-00000000000a', 'credhub');");
}
}
} |
0 | java-sources/am/ik/jqiita/jqiita/0.8.1 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/ConfiguredAccessToken.java | package jqiita;
import lombok.Getter;
class ConfiguredAccessToken {
private static final String ACCESS_TOKEN_PROPERTY_NAME = "jqiita.accessToken";
private static final String ACCESS_TOKEN_ENV_NAME = "JQIITA_ACCESS_TOKEN";
@Getter
private String token;
public ConfiguredAccessToken() {
// PROPERTY > ENV
String token = "";
if (System.getProperty(ACCESS_TOKEN_PROPERTY_NAME) != null) {
token = System.getProperty(ACCESS_TOKEN_PROPERTY_NAME);
} else if (System.getenv(ACCESS_TOKEN_ENV_NAME) != null) {
token = System.getenv(ACCESS_TOKEN_ENV_NAME);
}
this.token = token;
}
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/Qiita.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.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 jqiita;
import java.util.concurrent.ConcurrentHashMap;
public class Qiita {
private static final String DEFAULT_HOST = "https://qiita.com";
private static final String DEFAULT_LOG_LEVEL = "NONE";
private static final ConcurrentHashMap<String, QiitaClient> clientCache = new ConcurrentHashMap<>();
private static final ConfiguredAccessToken configuredAccessToken = new ConfiguredAccessToken();
public static QiitaClient client() {
String accessToken = configuredAccessToken.getToken();
return clientCache.computeIfAbsent(accessToken, key -> new QiitaClient(DEFAULT_HOST, accessToken, DEFAULT_LOG_LEVEL));
}
public static QiitaClientBuilder given() {
return new QiitaClientBuilder();
}
public static class QiitaClientBuilder {
private String accessToken = configuredAccessToken.getToken();
private String host = DEFAULT_HOST;
private String logLevel = DEFAULT_LOG_LEVEL;
public QiitaClient client() {
return clientCache.computeIfAbsent(accessToken, key -> new QiitaClient(host, accessToken, logLevel));
}
public QiitaClientBuilder accessToken(String accessToken) {
this.accessToken = accessToken;
return this;
}
public QiitaClientBuilder host(String host) {
this.host = host;
return this;
}
public LogLevelBuilder log() {
return new LogLevelBuilder(this);
}
}
public static class LogLevelBuilder {
private final QiitaClientBuilder clientBuilder;
LogLevelBuilder(QiitaClientBuilder clientBuilder) {
this.clientBuilder = clientBuilder;
}
public QiitaClientBuilder none() {
clientBuilder.logLevel = "NONE";
return clientBuilder;
}
public QiitaClientBuilder basic() {
clientBuilder.logLevel = "BASIC";
return clientBuilder;
}
public QiitaClientBuilder all() {
clientBuilder.logLevel = "FULL";
return clientBuilder;
}
}
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/QiitaClient.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.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 jqiita;
import com.google.gson.*;
import jqiita.comment.Comments;
import jqiita.comment.Thank;
import jqiita.exception.QiitaErrorHandler;
import jqiita.item.Items;
import jqiita.item.Lgtm;
import jqiita.item.Stocks;
import jqiita.project.Projects;
import jqiita.tag.FollowingTags;
import jqiita.tag.Tags;
import jqiita.template.ExpandedTemplates;
import jqiita.template.Templates;
import jqiita.user.AuthenticatedUser;
import jqiita.user.Followees;
import jqiita.user.Followers;
import jqiita.user.Users;
import lombok.Data;
import retrofit.RestAdapter;
import retrofit.converter.GsonConverter;
import java.lang.reflect.Type;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ConcurrentHashMap;
@Data
public class QiitaClient {
public static final String API_VERSION = "v2";
private static final ConcurrentHashMap<String, Object> objectCache = new ConcurrentHashMap<>();
private final String host;
private final String accessToken;
private final String logLevel;
String getKey(Class<?> clazz, String accessToken) {
return clazz + "$" + accessToken;
}
@SuppressWarnings("unchecked")
public <T> T resource(Class<T> clazz) {
RestAdapter builder = (RestAdapter) objectCache.computeIfAbsent(getKey(RestAdapter.class, accessToken),
(key) -> {
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssX")
.registerTypeAdapter(OffsetDateTime.class, new OffsetDateTimeConverter())
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create();
return new RestAdapter.Builder()
.setEndpoint(host + "/api/" + API_VERSION)
.setConverter(new GsonConverter(gson))
.setLogLevel(RestAdapter.LogLevel.valueOf(logLevel))
.setErrorHandler(new QiitaErrorHandler())
.setRequestInterceptor((request) -> {
if (accessToken != null && !accessToken.isEmpty()) {
request.addHeader("Authorization", "Bearer " + accessToken);
}
})
.build();
});
return (T) objectCache.computeIfAbsent(getKey(clazz, accessToken), (key) -> builder.create(clazz));
}
public QiitaClient clearCache() {
objectCache.clear();
return this;
}
public Comments comments() {
return resource(Comments.class);
}
public Thank thank() {
return resource(Thank.class);
}
public Items items() {
return resource(Items.class);
}
public Lgtm lgtm() {
return resource(Lgtm.class);
}
public Stocks stocks() {
return resource(Stocks.class);
}
public Projects projects() {
return resource(Projects.class);
}
public FollowingTags followingTags() {
return resource(FollowingTags.class);
}
public Tags tags() {
return resource(Tags.class);
}
public ExpandedTemplates expandedTemplates() {
return resource(ExpandedTemplates.class);
}
public Templates templates() {
return resource(Templates.class);
}
public AuthenticatedUser authenticatedUser() {
return resource(AuthenticatedUser.class);
}
public Followees followees() {
return resource(Followees.class);
}
public Followers followers() {
return resource(Followers.class);
}
public Users users() {
return resource(Users.class);
}
static class OffsetDateTimeConverter implements JsonSerializer<OffsetDateTime>, JsonDeserializer<OffsetDateTime> {
@Override
public OffsetDateTime deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
return DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(jsonElement.getAsString(), OffsetDateTime::from);
}
@Override
public JsonElement serialize(OffsetDateTime offsetDateTime, Type type, JsonSerializationContext jsonSerializationContext) {
return new JsonPrimitive(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(offsetDateTime));
}
}
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/comment/Comment.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.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 jqiita.comment;
import jqiita.user.User;
import lombok.Data;
import java.io.Serializable;
@Data
public class Comment implements Serializable {
private String body;
private String id;
private User user;
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/comment/CommentRequest.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.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 jqiita.comment;
import lombok.Data;
import java.io.Serializable;
@Data
public class CommentRequest implements Serializable {
private final String body;
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/comment/Comments.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.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 jqiita.comment;
import jqiita.user.User;
import retrofit.http.*;
import java.util.List;
public interface Comments {
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/comments/:id">API SPEC</a>
*/
@GET("/comments/{id}")
Comment get(@Path("id") String id);
/**
* @see <a href="http://qiita.com/api/v2/docs#delete-/api/v2/comments/:id">API SPEC</a>
*/
@DELETE("/comments/{id}")
Void delete(@Path("id") String id);
/**
* @see <a href="http://qiita.com/api/v2/docs#patch-/api/v2/comments/:id">API SPEC</a>
*/
@POST("/comments/{id}")
@Headers("X-Http-Method-Override: PATCH")
Comment update(@Path("id") String id, @Body CommentRequest request);
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/items/:item_id/comments">API SPEC</a>
*/
@GET("/items/{item_id}/comments")
List<User> listByItemId(@Path("item_id") String itemId);
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/items/:item_id/comments">API SPEC</a>
*/
@GET("/items/{item_id}/comments")
List<User> listByItemId(@Path("item_id") String itemId, @Query("page") int page, @Query("per_page") int perPage);
/**
* @see <a href="http://qiita.com/api/v2/docs#post-/api/v2/items/:item_id/comments">API SPEC</a>
*/
@POST("/items/{item_id}/comments")
Comment create(@Path("item_id") String itemId, @Body CommentRequest request);
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/comment/Thank.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.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 jqiita.comment;
import retrofit.http.DELETE;
import retrofit.http.PUT;
import retrofit.http.Path;
public interface Thank {
/**
* @see <a href="http://qiita.com/api/v2/docs#put-/api/v2/comments/:comment_id/thank">API SPEC</a>
*/
@PUT("/comments/{comment_id}/thank")
Void put(@Path("comment_id") String commentId);
/**
* @see <a href="http://qiita.com/api/v2/docs#delete-/api/v2/comments/:comment_id/thank">API SPEC</a>
*/
@DELETE("/comments/{comment_id}/thank")
Void delete(@Path("comment_id") String commentId);
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/exception/QiitaBadRequestException.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.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 jqiita.exception;
public class QiitaBadRequestException extends QiitaException {
public QiitaBadRequestException(String message, String type, Throwable cause) {
super(message, type, cause);
}
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/exception/QiitaErrorHandler.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.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 jqiita.exception;
import lombok.Data;
import retrofit.ErrorHandler;
import retrofit.RetrofitError;
public class QiitaErrorHandler implements ErrorHandler {
@Override
public Throwable handleError(RetrofitError retrofitError) {
ErrorResponse error = (ErrorResponse) retrofitError.getBodyAs(ErrorResponse.class);
if (error == null) {
return new IllegalStateException(retrofitError);
}
String message = error.getMessage();
String type = error.getType();
try {
return ErrorType.valueOf(type.toUpperCase()).exception(message, type, retrofitError);
} catch (IllegalArgumentException ok) {
return new QiitaException(message, type, retrofitError);
}
}
static enum ErrorType {
BAD_REQUEST {
@Override
QiitaException exception(String message, String type, Throwable cause) {
return new QiitaBadRequestException(message, type, cause);
}
},
UNAUTHORIZED {
@Override
QiitaException exception(String message, String type, Throwable cause) {
return new QiitaUnauthorizedException(message, type, cause);
}
},
FORBIDDEN {
@Override
QiitaException exception(String message, String type, Throwable cause) {
return new QiitaForbiddenException(message, type, cause);
}
},
NOT_FOUND {
@Override
QiitaException exception(String message, String type, Throwable cause) {
return new QiitaNotFoundException(message, type, cause);
}
};
abstract QiitaException exception(String message, String type, Throwable cause);
}
@Data
static class ErrorResponse {
private String message;
private String type;
}
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/exception/QiitaException.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.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 jqiita.exception;
public class QiitaException extends RuntimeException {
private final String message;
private final String type;
public QiitaException(String message, String type, Throwable cause) {
super(message, cause);
this.message = message;
this.type = type;
}
public String getType() {
return type;
}
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/exception/QiitaForbiddenException.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.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 jqiita.exception;
public class QiitaForbiddenException extends QiitaException {
public QiitaForbiddenException(String message, String type, Throwable cause) {
super(message, type, cause);
}
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/exception/QiitaNotFoundException.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.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 jqiita.exception;
public class QiitaNotFoundException extends QiitaException {
public QiitaNotFoundException(String message, String type, Throwable cause) {
super(message, type, cause);
}
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/exception/QiitaUnauthorizedException.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.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 jqiita.exception;
public class QiitaUnauthorizedException extends QiitaException {
public QiitaUnauthorizedException(String message, String type, Throwable cause) {
super(message, type, cause);
}
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/item/Item.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.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 jqiita.item;
import com.google.gson.annotations.SerializedName;
import jqiita.tag.Tag;
import jqiita.user.User;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.time.OffsetDateTime;
import java.util.List;
@Data
public class Item implements Serializable {
private String body;
private boolean coediting;
private OffsetDateTime createdAt;
private String id;
@SerializedName("private")
@Accessors(prefix = "_")
private boolean _private;
private List<Tag> tags;
private String title;
private OffsetDateTime updatedAt;
private User user;
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/item/ItemRequest.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.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 jqiita.item;
import com.google.gson.annotations.SerializedName;
import jqiita.tag.TagRequest;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.List;
@Data
@AllArgsConstructor
@RequiredArgsConstructor
public class ItemRequest implements Serializable {
private final String title;
private final String body;
private final List<TagRequest> tags;
private boolean coediting;
private boolean gist;
@SerializedName("private")
@Accessors(prefix = "_")
private boolean _private;
private boolean tweet;
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/item/Items.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.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 jqiita.item;
import retrofit.http.*;
import java.util.List;
public interface Items {
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/items">API SPEC</a>
*/
@GET("/items")
List<Item> list();
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/items">API SPEC</a>
*/
@GET("/items")
List<Item> list(@Query("page") int page, @Query("per_page") int perPage);
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/users/:user_id/items">API SPEC</a>
*/
@GET("/users/{user_id}/items")
List<Item> listByUserId(@Path("user_id") String userId);
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/users/:user_id/items">API SPEC</a>
*/
@GET("/users/{user_id}/items")
List<Item> listByUserId(@Path("user_id") String userId, @Query("page") int page, @Query("per_page") int perPage);
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/tags/:id/items">API SPEC</a>
*/
@GET("/tags/{id}/items")
List<Item> listByTagId(@Path("id") String id);
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/tags/:id/items">API SPEC</a>
*/
@GET("/tags/{id}/items")
List<Item> listByTagId(@Path("id") String id, @Query("page") int page, @Query("per_page") int perPage);
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/items/:id">API SPEC</a>
*/
@GET("/items/{id}")
Item get(@Path("id") String id);
@POST("/items")
Item create(@Body ItemRequest request);
/**
* @see <a href="http://qiita.com/api/v2/docs#patch-/api/v2/items/:id">API SPEC</a>
*/
@POST("/items/{id}")
@Headers("X-Http-Method-Override: PATCH")
Item update(@Path("id") String id, @Body ItemRequest request);
/**
* @see <a href="http://qiita.com/api/v2/docs#delete-/api/v2/items/:id">API SPEC</a>
*/
@DELETE("/items/{id}")
Void delete(@Path("id") String id);
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/item/Lgtm.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.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 jqiita.item;
import retrofit.http.DELETE;
import retrofit.http.PUT;
import retrofit.http.Path;
public interface Lgtm {
/**
* @see <a href="http://qiita.com/api/v2/docs#put-/api/v2/items/:item_id/lgtm">API SPEC</a>
*/
@PUT("/items/{item_id}/lgtm")
Void put(@Path("item_id") String itemId);
/**
* @see <a href="http://qiita.com/api/v2/docs#delete-/api/v2/items/:item_id/lgtm">API SPEC</a>
*/
@DELETE("/items/{item_id}/lgtm")
Void delete(@Path("item_id") String itemId);
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/item/Stocks.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.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 jqiita.item;
import retrofit.http.*;
import java.util.List;
public interface Stocks {
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/users/:user_id/stocks">API SPEC</a>
*/
@GET("/users/{user_id}/stocks")
List<Item> listByUserId(@Path("user_id") String userId);
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/users/:user_id/stocks">API SPEC</a>
*/
@GET("/users/{user_id}/stocks")
List<Item> listByUserId(@Path("user_id") String userId, @Query("page") int page, @Query("per_page") int perPage);
/**
* @see <a href="http://qiita.com/api/v2/docs#put-/api/v2/items/:item_id/stock">API SPEC</a>
*/
@PUT("/items/{item_id}/stock")
Void put(@Path("item_id") String itemId);
/**
* @see <a href="http://qiita.com/api/v2/docs#delete-/api/v2/items/:item_id/stock">API SPEC</a>
*/
@DELETE("/items/{item_id}/stock")
Void delete(@Path("item_id") String itemId);
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/project/Project.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.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 jqiita.project;
import lombok.Data;
import java.io.Serializable;
import java.time.OffsetDateTime;
@Data
public class Project implements Serializable {
private boolean achived;
private String body;
private OffsetDateTime createdAt;
private String id;
private String name;
private OffsetDateTime updatedAt;
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/project/ProjectRequest.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.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 jqiita.project;
import jqiita.tag.Tag;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
@Data
public class ProjectRequest implements Serializable {
private final boolean achived;
private final String body;
private final List<Tag> tags;
private final String name;
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/project/Projects.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.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 jqiita.project;
import retrofit.http.*;
import java.util.List;
public interface Projects {
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/projects">API SPEC</a>
*/
@GET("/projects")
List<Project> list();
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/projects">API SPEC</a>
*/
@GET("/projects")
List<Project> list(@Query("page") int page, @Query("per_page") int perPage);
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/projects/:id">API SPEC</a>
*/
@GET("/projects/{id}")
Project get(@Path("id") String id);
/**
* @see <a href="http://qiita.com/api/v2/docs#post-/api/v2/projects">API SPEC</a>
*/
@POST("/templates")
Project create(@Body ProjectRequest request);
/**
* @see <a href="http://qiita.com/api/v2/docs#delete-/api/v2/projects/:id">API SPEC</a>
*/
@DELETE("/projects/{id}")
Void delete(@Path("id") String id);
/**
* @see <a href="http://qiita.com/api/v2/docs#patch-/api/v2/projects/:id">API SPEC</a>
*/
@POST("/projects/{id}")
@Headers("X-Http-Method-Override: PATCH")
Project update(@Path("id") String id, @Body ProjectRequest request);
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/tag/FollowingTags.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.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 jqiita.tag;
import retrofit.http.GET;
import retrofit.http.Path;
import retrofit.http.Query;
import java.util.List;
public interface FollowingTags {
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/users/:user_id/following_tags">API SPEC</a>
*/
@GET("/users/{user_id}/following_tags")
List<Tag> listByUserId(@Path("user_id") String userId);
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/users/:user_id/following_tags">API SPEC</a>
*/
@GET("/users/{user_id}/following_tags")
List<Tag> listByUserId(@Path("user_id") String userId, @Query("page") int page, @Query("per_page") int perPage);
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/tag/Tag.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.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 jqiita.tag;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
@Data
public class Tag implements Serializable {
private int followersCount;
private String iconUrl;
private String id;
private int itemsCount;
private String name;
private List<String> versions;
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/tag/TagRequest.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.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 jqiita.tag;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import java.io.Serializable;
import java.util.List;
@Data
@AllArgsConstructor
@RequiredArgsConstructor
public class TagRequest implements Serializable {
private final String name;
private List<String> versions;
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/tag/Tags.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.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 jqiita.tag;
import retrofit.http.GET;
import retrofit.http.Path;
import retrofit.http.Query;
import java.util.List;
public interface Tags {
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/tags">API SPEC</a>
*/
@GET("/tags")
List<Tag> list();
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/tags">API SPEC</a>
*/
@GET("/tags")
List<Tag> list(@Query("page") int page, @Query("per_page") int perPage);
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/tags/:id">API SPEC</a>
*/
@GET("/tags/{id}")
Tag get(@Path("id") String id);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.