text
stringlengths 7
1.01M
|
|---|
package com.virmana.stickers_app.adapter;
import android.app.Activity;
import androidx.recyclerview.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.virmana.stickers_app.R;
import com.virmana.stickers_app.entity.CategoryApi;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Vimal-CVS on 04/11/2020.
*/
public class CategorySelectAdapter extends RecyclerView.Adapter implements SelectableCategoryViewHolder.OnItemSelectedListener {
private final List<CategoryApi> mValues;
private boolean isMultiSelectionEnabled = false;
SelectableCategoryViewHolder.OnItemSelectedListener listener;
Activity activity;
public CategorySelectAdapter( SelectableCategoryViewHolder.OnItemSelectedListener listener,
List<CategoryApi> items,boolean isMultiSelectionEnabled,Activity activity) {
this.listener = listener;
this.isMultiSelectionEnabled = isMultiSelectionEnabled;
this.activity=activity;
mValues = new ArrayList<>();
for (CategoryApi item : items) {
mValues.add(item);
}
}
@Override
public SelectableCategoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_category_select, parent, false);
return new SelectableCategoryViewHolder(itemView, this);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
SelectableCategoryViewHolder holder = (SelectableCategoryViewHolder) viewHolder;
CategoryApi selectableItem = mValues.get(position);
String name = selectableItem.getTitle();
holder.text_view_item_category_item_select.setText(name);
//Picasso.with(activity.getApplicationContext()).load(selectableItem.getImage()).error(R.drawable.flag_placeholder).placeholder(R.drawable.flag_placeholder).into(holder.image_view_iten_language);
if (isMultiSelectionEnabled) {
TypedValue value = new TypedValue();
holder.textView.getContext().getTheme().resolveAttribute(android.R.attr.listChoiceIndicatorMultiple, value, true);
int checkMarkDrawableResId = value.resourceId;
holder.textView.setCheckMarkDrawable(checkMarkDrawableResId);
} else {
TypedValue value = new TypedValue();
holder.textView.getContext().getTheme().resolveAttribute(android.R.attr.listChoiceIndicatorSingle, value, true);
int checkMarkDrawableResId = value.resourceId;
holder.textView.setCheckMarkDrawable(checkMarkDrawableResId);
}
holder.mItem = selectableItem;
holder.setChecked(holder.mItem.isSelected());
}
@Override
public int getItemCount() {
return mValues.size();
}
public List<CategoryApi> getSelectedItems() {
List<CategoryApi> selectedItems = new ArrayList<>();
for (CategoryApi item : mValues) {
if (item.isSelected()) {
selectedItems.add(item);
}
}
return selectedItems;
}
@Override
public int getItemViewType(int position) {
if(isMultiSelectionEnabled){
return SelectableCategoryViewHolder.MULTI_SELECTION;
}
else{
return SelectableCategoryViewHolder.SINGLE_SELECTION;
}
}
@Override
public void onItemSelected(CategoryApi item) {
if (!isMultiSelectionEnabled) {
for (CategoryApi selectableItem : mValues) {
if (!selectableItem.equals(item)
&& selectableItem.isSelected()) {
selectableItem.setSelected(false);
} else if (selectableItem.equals(item)
&& item.isSelected()) {
selectableItem.setSelected(true);
}
}
notifyDataSetChanged();
}
listener.onItemSelected(item);
}
}
|
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.glitchtechscience.ui.colorpicker;
import android.graphics.Color;
import java.util.Comparator;
/**
* A color comparator which compares based on hue, saturation, and value.
*/
public class HsvColorComparator implements Comparator<Integer> {
@Override
public int compare( Integer lhs, Integer rhs ) {
float[] hsv = new float[3];
Color.colorToHSV( lhs, hsv );
float hue1 = hsv[0];
float sat1 = hsv[1];
float val1 = hsv[2];
float[] hsv2 = new float[3];
Color.colorToHSV( rhs, hsv2 );
float hue2 = hsv2[0];
float sat2 = hsv2[1];
float val2 = hsv2[2];
if( hue1 < hue2 ) {
return 1;
} else if( hue1 > hue2 ) {
return -1;
} else {
if( sat1 < sat2 ) {
return 1;
} else if( sat1 > sat2 ) {
return -1;
} else {
if( val1 < val2 ) {
return 1;
} else if( val1 > val2 ) {
return -1;
}
}
}
return 0;
}
}
|
/*
* Copyright (C) 2012 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.util.function;
import com.facebook.util.ExtRunnable;
import java.util.function.ObjLongConsumer;
public interface ExtObjLongConsumer<T, E extends Throwable> {
void accept(T t, long value) throws E;
static <T> ObjLongConsumer<T> quiet(ExtObjLongConsumer<T, ?> objLongConsumer) {
return (t, value) -> ExtRunnable.quiet(() -> objLongConsumer.accept(t, value)).run();
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.core.query;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Value;
import javax.jcr.query.QueryResult;
import javax.jcr.query.Row;
import javax.jcr.query.RowIterator;
/**
* <code>ExcerptTest</code> checks if HTML excerpts are created correctly. The
* test cases assume the following implementation details:
* <ul>
* <li>An excerpt is enclosed with a <div> element</li>
* <li>A fragment is enclosed with a <span> element</li>
* <li>Terms are highlighted with a <strong> element</li>
* <li>The maximum number of fragment created is three</li>
* <li>The maximum excerpt length is 150 characters</li>
* <li>A fragment contains at most 75 characters (excluding '... ') before the first term is highlighted</li>
* <li>At least the following sentence separators are recognized: '.', '!' and '?'</li>
* <li>If there is additial text after the fragment end ' ...' is appended to the fragment</li>
* <li>If the fragment starts within a sentence, then the fragment is prefixed with '... '</li>
* </ul>
*/
public class ExcerptTest extends AbstractQueryTest {
private static final String EXCERPT_START = "<div><span>";
private static final String EXCERPT_END = "</span></div>";
public void testHightlightFirstWord() throws RepositoryException {
checkExcerpt("jackrabbit bla bla bla",
"<strong>jackrabbit</strong> bla bla bla",
"jackrabbit");
}
public void testHightlightLastWord() throws RepositoryException {
checkExcerpt("bla bla bla jackrabbit",
"bla bla bla <strong>jackrabbit</strong>",
"jackrabbit");
}
public void testHightlightWordBetween() throws RepositoryException {
checkExcerpt("bla bla jackrabbit bla bla",
"bla bla <strong>jackrabbit</strong> bla bla",
"jackrabbit");
}
public void testMoreTextDotsAtEnd() throws RepositoryException {
checkExcerpt("bla bla jackrabbit bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla",
"bla bla <strong>jackrabbit</strong> bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla ...",
"jackrabbit");
}
public void testMoreTextDotsAtStart() throws RepositoryException {
checkExcerpt("bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla jackrabbit bla bla bla bla",
"... bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla <strong>jackrabbit</strong> bla bla bla bla",
"jackrabbit");
}
public void testMoreTextDotsAtStartAndEnd() throws RepositoryException {
checkExcerpt("bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla jackrabbit bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla",
"... bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla <strong>jackrabbit</strong> bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla ...",
"jackrabbit");
}
public void testPunctuationStartsFragment() throws RepositoryException {
checkExcerpt("bla bla bla bla bla bla bla bla. bla bla bla bla bla bla bla bla bla bla bla bla jackrabbit bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla",
"bla bla bla bla bla bla bla bla bla bla bla bla <strong>jackrabbit</strong> bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla",
"jackrabbit");
}
public void testPunctuationStartsFragmentEndsWithDots() throws RepositoryException {
checkExcerpt("bla bla bla bla bla bla bla bla. bla bla bla bla bla bla bla bla bla bla bla bla jackrabbit bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla",
"bla bla bla bla bla bla bla bla bla bla bla bla <strong>jackrabbit</strong> bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla ...",
"jackrabbit");
}
public void testHighlightMultipleTerms() throws RepositoryException {
checkExcerpt("bla bla bla apache jackrabbit bla bla bla",
"bla bla bla <strong>apache</strong> <strong>jackrabbit</strong> bla bla bla",
"apache jackrabbit");
}
public void testPreferPhrase() throws RepositoryException {
checkExcerpt("bla apache bla jackrabbit bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla apache jackrabbit bla bla bla",
"... bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla <strong>apache</strong> <strong>jackrabbit</strong> bla bla bla</span><span>bla <strong>apache</strong> bla <strong>jackrabbit</strong> bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla ...",
"apache jackrabbit");
}
/**
* Verifies character encoding on a node property that does not contain any
* excerpt info
*/
public void testEncodeIllegalCharsNoHighlights() throws RepositoryException {
String text = "bla <strong>bla</strong> bla";
String excerpt = createExcerpt("bla <strong>bla</strong> bla");
Node n = testRootNode.addNode(nodeName1);
n.setProperty("text", text);
n.setProperty("other", "foo");
superuser.save();
String stmt = getStatement("foo");
QueryResult result = executeQuery(stmt);
RowIterator rows = result.getRows();
assertEquals(1, rows.getSize());
String ex = rows.nextRow().getValue("rep:excerpt(text)").getString();
assertEquals("Expected " + excerpt + ", but got ", excerpt, ex);
}
/**
* Verifies character encoding on a node property that contains excerpt info
*/
public void testEncodeIllegalCharsHighlights() throws RepositoryException {
checkExcerpt("bla <strong>bla</strong> foo",
"bla <strong>bla</strong> <strong>foo</strong>",
"foo");
}
/**
* test for https://issues.apache.org/jira/browse/JCR-3077
*
* when given a quoted phrase, the excerpt should evaluate it whole as a
* token (not break is down)
*
*/
public void testQuotedPhrase() throws RepositoryException {
checkExcerpt("one two three four",
"one <strong>two three</strong> four", "\"two three\"");
}
/**
* Verifies excerpt generation on a node property that does not contain any
* excerpt info for a quoted phrase
*/
public void testQuotedPhraseNoMatch() throws RepositoryException {
String text = "one two three four";
String excerpt = createExcerpt("one two three four");
String terms = "\"five six\"";
Node n = testRootNode.addNode(nodeName1);
n.setProperty("text", text);
n.setProperty("other", terms);
superuser.save();
String stmt = getStatement(terms);
QueryResult result = executeQuery(stmt);
RowIterator rows = result.getRows();
assertEquals(1, rows.getSize());
String ex = rows.nextRow().getValue("rep:excerpt(text)").getString();
assertEquals("Expected " + excerpt + ", but got ", excerpt, ex);
}
/**
*
* Verifies excerpt generation on a node property that contains the exact
* quoted phrase but with scrambled words.
*
* More clearly it actually checks that the order of tokens is respected for
* a quoted phrase.
*/
public void testQuotedPhraseNoMatchScrambled() throws RepositoryException {
String text = "one two three four";
String excerpt = createExcerpt("one two three four");
String terms = "\"three two\"";
Node n = testRootNode.addNode(nodeName1);
n.setProperty("text", text);
n.setProperty("other", terms);
superuser.save();
String stmt = getStatement(terms);
QueryResult result = executeQuery(stmt);
RowIterator rows = result.getRows();
assertEquals(1, rows.getSize());
String ex = rows.nextRow().getValue("rep:excerpt(text)").getString();
assertEquals("Expected " + excerpt + ", but got ", excerpt, ex);
}
/**
* Verifies excerpt generation on a node property that does not contain the
* exact quoted phrase, but contains fragments of it.
*
*/
public void testQuotedPhraseNoMatchGap() throws RepositoryException {
String text = "one two three four";
String excerpt = createExcerpt("one two three four");
String terms = "\"two four\"";
Node n = testRootNode.addNode(nodeName1);
n.setProperty("text", text);
n.setProperty("other", terms);
superuser.save();
String stmt = getStatement(terms);
QueryResult result = executeQuery(stmt);
RowIterator rows = result.getRows();
assertEquals(1, rows.getSize());
String ex = rows.nextRow().getValue("rep:excerpt(text)").getString();
assertEquals("Expected " + excerpt + ", but got ", excerpt, ex);
}
/**
* test for https://issues.apache.org/jira/browse/JCR-3077
*
* JA search acts as a PhraseQuery, thanks to LUCENE-2458. so it should be
* covered by the QuotedTest search.
*
*/
public void testHighlightJa() throws RepositoryException {
// http://translate.google.com/#auto|en|%E3%82%B3%E3%83%B3%E3%83%86%E3%83%B3%E3%83%88
String jContent = "\u30b3\u30fe\u30c6\u30f3\u30c8";
// http://translate.google.com/#auto|en|%E3%83%86%E3%82%B9%E3%83%88
String jTest = "\u30c6\u30b9\u30c8";
String content = "some text with japanese: " + jContent + " (content)"
+ " and " + jTest + " (test).";
// expected excerpt; note this may change if excerpt providers change
String expectedExcerpt = "some text with japanese: " + jContent
+ " (content) and <strong>" + jTest + "</strong> (test).";
checkExcerpt(content, expectedExcerpt, jTest);
}
/**
* test for https://issues.apache.org/jira/browse/JCR-3428
*
* when given an incomplete fulltext search token, the excerpt should
* highlight the entire matching token
*
*/
public void testEagerMatch() throws RepositoryException {
checkExcerpt("lorem ipsum dolor sit amet",
"lorem <strong>ipsum</strong> dolor sit amet", "ipsu*");
}
/**
* @see #testEagerMatch()
*/
public void testEagerMatch2() throws RepositoryException {
checkExcerpt("lorem ipsum dolor sit amet",
"<strong>lorem</strong> <strong>ipsum</strong> dolor sit amet",
"lorem ipsu*");
}
/**
* @see #testEagerMatch()
*/
public void testEagerMatch3() throws RepositoryException {
checkExcerpt("lorem ipsum dolor sit amet",
"lorem <strong>ipsum</strong> <strong>dolor</strong> sit amet", "ipsu* dolor");
}
private void checkExcerpt(String text, String fragmentText, String terms)
throws RepositoryException {
String excerpt = createExcerpt(fragmentText);
createTestData(text);
String stmt = getStatement(terms);
QueryResult result = executeQuery(stmt);
RowIterator rows = result.getRows();
assertEquals(1, rows.getSize());
assertEquals(excerpt, getExcerpt(rows.nextRow()));
}
private String getStatement(String terms) {
return testPath + "/*[jcr:contains(., '"+ terms + "')]/rep:excerpt(.)";
}
private void createTestData(String text) throws RepositoryException {
Node n = testRootNode.addNode(nodeName1);
n.setProperty("text", text);
superuser.save();
}
private String getExcerpt(Row row) throws RepositoryException {
Value v = row.getValue("rep:excerpt(.)");
if (v != null) {
return v.getString();
} else {
return null;
}
}
private String createExcerpt(String fragments) {
return EXCERPT_START + fragments + EXCERPT_END;
}
/**
* <p>
* Test when there are multiple tokens that match the fulltext search (which
* will generate multiple lucene terms for the highlighter to use) in the
* repository but not all of them are present in the current property.
* </p>
*
*/
public void testMatchMultipleNonMatchingTokens() throws RepositoryException {
String text = "lorem ipsum";
String fragmentText = "lorem <strong>ipsum</strong>";
String terms = "ipsu*";
String excerpt = createExcerpt(fragmentText);
// here we'll add more matching garbage data so we have more tokens
// passed to the highlighter
Node parent = testRootNode.addNode(nodeName1);
Node n = parent.addNode("test");
n.setProperty("text", text);
testRootNode.addNode(nodeName2).setProperty("foo", "ipsuFoo");
testRootNode.addNode(nodeName3).setProperty("bar", "ipsuBar");
superuser.save();
// --
String stmt = testPath + "/" + nodeName1 + "//*[jcr:contains(., '"
+ terms + "')]/rep:excerpt(.)";
QueryResult result = executeQuery(stmt);
RowIterator rows = result.getRows();
assertEquals(1, rows.getSize());
assertEquals(excerpt, getExcerpt(rows.nextRow()));
}
}
|
/*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.pmml.pmml_4_2.model.mining;
import java.util.List;
public interface PredicateRuleProducer {
public String getPredicateRule();
public List<String> getPredicateFieldNames();
public List<String> getFieldMissingFieldNames();
}
|
package com.project.convertedCode.servlets.vendor.phpunit.phpunit.src.Framework.Constraint;
import com.runtimeconverter.runtime.includes.RuntimeIncludable;
import com.runtimeconverter.runtime.includes.RuntimeConverterServlet;
import com.runtimeconverter.runtime.RuntimeEnv;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;
@WebServlet("/vendor/phpunit/phpunit/src/Framework/Constraint/LogicalXor.php")
public class servlet_LogicalXor_php extends RuntimeConverterServlet {
protected final RuntimeIncludable getInclude() {
return com.project
.convertedCode
.includes
.vendor
.phpunit
.phpunit
.src
.Framework
.Constraint
.file_LogicalXor_php
.instance;
}
protected final RuntimeEnv getRuntimeEnv(
String httpRequestType, HttpServletRequest req, HttpServletResponse resp) {
return new com.project.convertedCode.main.ConvertedProjectRuntimeEnv(
req, resp, this.getInclude());
}
}
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.stream.Collector;
import java.util.stream.Collectors;
// package 32-double-map-reduce;
public class THIRTYTWO {
public static class Partition implements Iterator {
private static final BlockingQueue<String> data = new LinkedBlockingDeque<>();
int nlines;
public Partition(String dataStr, int nlines) {
this.nlines = nlines;
String[] lines = dataStr.split("\n");
for (String l : lines) {
data.add(l);
}
}
@Override
public boolean hasNext() {
return !data.isEmpty();
}
@Override
public Object next() {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < nlines; i++) {
String chunk = data.poll();
if (chunk == null)
break;
builder.append(chunk + " "); // line1 line2 line3...
}
return builder.toString();
}
}
public static class SplitWords {
String[] scan(String strData) {
return strData.toLowerCase().split("[^a-zA-Z0-9]+");
}
List<String> removeStopWords(String[] wordList) throws IOException {
Set<String> stopwords = new HashSet<>();
stopwords.addAll(Arrays.asList(new String(Files.readAllBytes(Path.of("../stop_words.txt"))).split(",")));
return Arrays.asList(wordList).stream().filter(w -> !stopwords.contains(w) && w.length() > 1).collect(Collectors.toList());
}
List<Map.Entry<String, Integer>> main(String dataStr) throws IOException {
List<Map.Entry<String, Integer>> result = new ArrayList<>();
removeStopWords(scan(dataStr)).stream().forEach(w -> result.add(new AbstractMap.SimpleEntry<>(w, 1)));
return result;
}
}
public static Map<String, List<Map.Entry<String, Integer>>> regrouop(List<Map.Entry<String, Integer>> pairsList){
Map<String, List<Map.Entry<String, Integer>>> mapping = new HashMap<>();
pairsList.stream().forEach(entry -> {
if(mapping.containsKey(entry.getKey())){
mapping.get(entry.getKey()).add(entry);
}else{
mapping.put(entry.getKey(),new ArrayList<>());
mapping.get(entry.getKey()).add(entry);
}
});
return mapping;
}
public static Entry<String, Integer> countWords(Map<String, List<Map.Entry<String, Integer>>> mapping){
int sum = 0;
String word = "";
for(Entry<String, List<Entry<String, Integer>>> e : mapping.entrySet()) {
word = e.getKey();
for(Entry<String, Integer> k: e.getValue()) {
sum += k.getValue();
}
}
return new AbstractMap.SimpleEntry<>(word, sum);
}
public static Map<String, Integer> sort(Map<String, Integer> wordFreq){
return wordFreq
.entrySet()
.stream()
.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));
}
public static void main(String[] args) throws Exception {
StringBuilder sb = new StringBuilder();
String str;
BufferedReader reader = new BufferedReader(new FileReader(new File(args[0])));
try{
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append(" ");
}
reader.close();
}catch(Exception e){
e.printStackTrace();
}
str = sb.toString();
Iterator iterator = new Partition(str,200);
ArrayList<Map.Entry<String, Integer>> data = new ArrayList<>();
while(iterator.hasNext()) {
SplitWords spl = new SplitWords();
ArrayList<Map.Entry<String, Integer>> temp = (ArrayList<Entry<String, Integer>>) spl
.main((String) iterator.next());
for(Map.Entry<String, Integer> e: temp) {
data.add(e);
}
}
Map<String, List<Entry<String, Integer>>> group = regrouop(data);
HashMap<String, Integer> freq = new HashMap<>();
for(Entry<String, List<Entry<String, Integer>>> g : group.entrySet()) {
Map<String, List<Entry<String, Integer>>> temp = new HashMap<>();
temp.put(g.getKey(), g.getValue());
Map.Entry<String, Integer> output = countWords(temp);
freq.put(output.getKey(), output.getValue());
}
Set<Entry<String, Integer>> freqE = freq.entrySet();
freqE
.stream()
.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
.limit(25)
.forEach(e -> System.out.println(e.getKey()+" - "+e.getValue()));
}
}
|
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. */
package unittest;
import org.junit.jupiter.api.Test;
import com.runtimeverification.rvmonitor.java.rt.annotation.MonitorOn;
public class FunctionTest {
@Test
@MonitorOn("unittest")
void test() {
Instrumented i = new Instrumented();
i.event1();
}
}
|
/*
* Copyright 2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.compute.v1.stub;
import com.google.api.core.BetaApi;
import com.google.api.gax.httpjson.HttpJsonCallSettings;
import com.google.api.gax.httpjson.HttpJsonCallableFactory;
import com.google.api.gax.httpjson.HttpJsonOperationSnapshotCallable;
import com.google.api.gax.httpjson.HttpJsonStubCallableFactory;
import com.google.api.gax.rpc.BatchingCallSettings;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.OperationCallSettings;
import com.google.api.gax.rpc.OperationCallable;
import com.google.api.gax.rpc.PagedCallSettings;
import com.google.api.gax.rpc.UnaryCallSettings;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.compute.v1.Operation;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* REST callable factory implementation for the InstanceGroupManagers service API.
*
* <p>This class is for advanced usage.
*/
@Generated("by gapic-generator-java")
@BetaApi
public class HttpJsonInstanceGroupManagersCallableFactory
implements HttpJsonStubCallableFactory<Operation, ZoneOperationsStub> {
@Override
public <RequestT, ResponseT> UnaryCallable<RequestT, ResponseT> createUnaryCallable(
HttpJsonCallSettings<RequestT, ResponseT> httpJsonCallSettings,
UnaryCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return HttpJsonCallableFactory.createUnaryCallable(
httpJsonCallSettings, callSettings, clientContext);
}
@Override
public <RequestT, ResponseT, PagedListResponseT>
UnaryCallable<RequestT, PagedListResponseT> createPagedCallable(
HttpJsonCallSettings<RequestT, ResponseT> httpJsonCallSettings,
PagedCallSettings<RequestT, ResponseT, PagedListResponseT> callSettings,
ClientContext clientContext) {
return HttpJsonCallableFactory.createPagedCallable(
httpJsonCallSettings, callSettings, clientContext);
}
@Override
public <RequestT, ResponseT> UnaryCallable<RequestT, ResponseT> createBatchingCallable(
HttpJsonCallSettings<RequestT, ResponseT> httpJsonCallSettings,
BatchingCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return HttpJsonCallableFactory.createBatchingCallable(
httpJsonCallSettings, callSettings, clientContext);
}
@BetaApi(
"The surface for long-running operations is not stable yet and may change in the future.")
@Override
public <RequestT, ResponseT, MetadataT>
OperationCallable<RequestT, ResponseT, MetadataT> createOperationCallable(
HttpJsonCallSettings<RequestT, Operation> httpJsonCallSettings,
OperationCallSettings<RequestT, ResponseT, MetadataT> callSettings,
ClientContext clientContext,
ZoneOperationsStub operationsStub) {
UnaryCallable<RequestT, Operation> innerCallable =
HttpJsonCallableFactory.createBaseUnaryCallable(
httpJsonCallSettings, callSettings.getInitialCallSettings(), clientContext);
HttpJsonOperationSnapshotCallable<RequestT, Operation> initialCallable =
new HttpJsonOperationSnapshotCallable<RequestT, Operation>(
innerCallable,
httpJsonCallSettings.getMethodDescriptor().getOperationSnapshotFactory());
return HttpJsonCallableFactory.createOperationCallable(
callSettings, clientContext, operationsStub.longRunningClient(), initialCallable);
}
}
|
package com.leammin.leetcode.easy;
/**
* 35. 搜索插入位置
*
* <p>给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。</p>
*
* <p>你可以假设数组中无重复元素。</p>
*
* <p><strong>示例 1:</strong></p>
*
* <pre><strong>输入:</strong> [1,3,5,6], 5
* <strong>输出:</strong> 2
* </pre>
*
* <p><strong>示例 2:</strong></p>
*
* <pre><strong>输入:</strong> [1,3,5,6], 2
* <strong>输出:</strong> 1
* </pre>
*
* <p><strong>示例 3:</strong></p>
*
* <pre><strong>输入:</strong> [1,3,5,6], 7
* <strong>输出:</strong> 4
* </pre>
*
* <p><strong>示例 4:</strong></p>
*
* <pre><strong>输入:</strong> [1,3,5,6], 0
* <strong>输出:</strong> 0
* </pre>
*
*
* @author Leammin
* @date 2020-06-12
*/
public interface SearchInsertPosition {
int searchInsert(int[] nums, int target);
class Solution implements SearchInsertPosition {
@Override
public int searchInsert(int[] nums, int target) {
int lo = 0;
int hi = nums.length;
while (lo < hi) {
int mid = (lo + hi) >> 1;
if (nums[mid] > target) {
hi = mid;
} else if (nums[mid] < target) {
lo = mid + 1;
} else {
return mid;
}
}
return lo;
}
}
}
|
package io.opensphere.wfs.envoy;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import javax.xml.bind.JAXBElement;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.avro.file.DataFileStream;
import org.apache.avro.generic.GenericRecord;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.simplify.TopologyPreservingSimplifier;
import io.opensphere.core.Toolbox;
import io.opensphere.core.data.DataRegistry;
import io.opensphere.core.datafilter.DataFilter;
import io.opensphere.core.dialog.alertviewer.event.UserMessageEvent;
import io.opensphere.core.event.EventListener;
import io.opensphere.core.event.EventManager;
import io.opensphere.core.model.time.TimeSpan;
import io.opensphere.core.preferences.Preferences;
import io.opensphere.core.util.XMLUtilities;
import io.opensphere.core.util.collections.New;
import io.opensphere.core.util.collections.StreamUtilities;
import io.opensphere.core.util.io.CancellableInputStream;
import io.opensphere.core.util.lang.StringUtilities;
import io.opensphere.core.util.lang.ThreadControl;
import io.opensphere.core.util.taskactivity.TaskActivity;
import io.opensphere.mantle.data.element.MapDataElement;
import io.opensphere.mantle.data.element.factory.AvroTimeHelper;
import io.opensphere.mantle.data.element.mdfilter.OGCFilterParameters;
import io.opensphere.server.control.DefaultServerDataGroupInfo;
import io.opensphere.server.services.ServerConnectionParams;
import io.opensphere.server.source.OGCServerSource;
import io.opensphere.server.util.OGCOutputFormat;
import io.opensphere.server.util.OGCServerConnector;
import io.opensphere.server.util.OGCServerException;
import io.opensphere.wfs.config.WFSServerConfig;
import io.opensphere.wfs.config.WFSServerConfig.WFSServerState;
import io.opensphere.wfs.consumer.FeatureConsumer;
import io.opensphere.wfs.filter.WFSTimeFieldGetter;
import io.opensphere.wfs.gml311.GmlSaxFeatureResponseHandler;
import io.opensphere.wfs.layer.WFSDataType;
import io.opensphere.wfs.placenames.PlaceNameLayerManager;
import io.opensphere.wfs.placenames.PlaceNameTile;
import io.opensphere.wfs.placenames.PlaceNamesRequestEvent;
import io.opensphere.wfs.util.WFSPreferenceUtilities;
import net.opengis.ows._100.DomainType;
import net.opengis.ows._100.Operation;
import net.opengis.ows._100.OperationsMetadata;
import net.opengis.ows._100.RequestMethodType;
import net.opengis.wfs._110.WFSCapabilitiesType;
/**
* Envoy that queries and retrieves data from a WFS server.
*/
@SuppressWarnings("PMD.GodClass")
public class WFSEnvoy extends AbstractWFSEnvoy
{
/** Logger reference. */
private static final Logger LOGGER = Logger.getLogger(WFSEnvoy.class);
/**
* Each point takes ~50 chars so set max points to maximum URL size, minus
* enough for a large URL without the points, divided by 50 chars.
*/
private static final int MAX_POINTS = (8000 - 500) / 50;
/**
* The preferred output format at the server level. This is used by any
* layer that does not specify its own list of output formats.
*/
private OGCOutputFormat myDefaultOutputFormat = OGCOutputFormat.GML_311;
/** A flag indicating whether this server supports HTTP Post. */
private boolean myIsGetFeaturePostEnabled;
/** Listener for events which contain place names to publish. */
private final EventListener<PlaceNamesRequestEvent> myPlaceNamesEventListener;
/** The Place names manager. */
private final PlaceNameLayerManager myPlaceNamesManager;
/** Task activity that tracks placenames requests. */
private final PlacenamesTaskActivity myPlacenamesTaskActivity;
/** The WFS preferences. */
private final Preferences myPreferences;
/** The WFS GetCapabilities object. */
private WFSCapabilitiesType myWfsCapabilities;
/**
* The helper class used by the envoy to perform additional processing.
*/
private final WFSEnvoyHelper myEnvoyHelper;
/**
* Construct the envoy.
*
* @param toolbox The tool box used by plugins to interact with the rest of
* the system.
* @param preferences The WFS preferences.
* @param wfsConn The parameters used to connect to an OGC server URL.
* @param tools Collection of WFS tools.
*/
public WFSEnvoy(Toolbox toolbox, Preferences preferences, ServerConnectionParams wfsConn, WFSTools tools)
{
super(toolbox, wfsConn, tools);
LOGGER.debug("Creating new WFS Envoy.");
myPreferences = preferences;
myPlaceNamesManager = tools.getPlaceNamesManager();
myPlacenamesTaskActivity = new PlacenamesTaskActivity();
EventManager eventManager = getToolbox().getEventManager();
if (eventManager != null)
{
myPlaceNamesEventListener = event -> retrievePlacenameData(event.getTile());
eventManager.subscribe(PlaceNamesRequestEvent.class, myPlaceNamesEventListener);
}
else
{
myPlaceNamesEventListener = null;
}
myEnvoyHelper = toolbox.getPluginToolboxRegistry().getPluginToolbox(WFSToolbox.class).getEnvoyHelper();
}
@Override
public synchronized void close()
{
EventManager eventManager = getToolbox().getEventManager();
if (eventManager != null && myPlaceNamesEventListener != null)
{
eventManager.unsubscribe(PlaceNamesRequestEvent.class, myPlaceNamesEventListener);
}
super.close();
myPlaceNamesManager.removeServer(getServerConfig().getServerTitle());
myWfsCapabilities = null;
}
@Override
public synchronized void open()
{
super.open();
/* If a server has a layer with the place names keyword, consider it a
* place names provider and add it to the corresponding set of
* providers. */
for (WFSDataType type : getDataTypes())
{
for (String tag : type.getTags())
{
if (tag.equalsIgnoreCase(PlaceNameLayerManager.SOURCE))
{
myPlaceNamesManager.addServer(getServerConfig().getServerTitle());
break;
}
}
}
getToolbox().getUIRegistry().getMenuBarRegistry().addTaskActivity(myPlacenamesTaskActivity);
}
@SuppressWarnings("PMD.SimplifiedTernary")
@Override
protected boolean activateLayers(Collection<WFSDataType> typesToActivate) throws InterruptedException
{
boolean addedDescribeFeatureData = true;
try
{
describeFeatures(typesToActivate);
/* Since the data type has been altered by the describe features,
* set the type sync (whatever that is). */
for (WFSDataType dataType : typesToActivate)
{
if (dataType.getParent() instanceof DefaultServerDataGroupInfo)
{
DefaultServerDataGroupInfo serverGroup = (DefaultServerDataGroupInfo)dataType.getParent();
dataType.setTimeExtents(null, false);
dataType.setTypeSync(serverGroup.getTypeSync());
}
}
}
catch (OGCServerException e)
{
String error = "Failed to parse layer information from server [" + getServerConfig().getWfsUrl() + "]: "
+ e.getMessage();
UserMessageEvent.error(getToolbox().getEventManager(), error);
addedDescribeFeatureData = false;
}
return addedDescribeFeatureData ? super.activateLayers(typesToActivate) : false;
}
@Override
protected int getFeatures(WFSDataType wfsType, TimeSpan timeSpan, Geometry geometry, DataFilter userFilter)
throws OGCServerException
{
OGCOutputFormat format = getOutputFormat(wfsType);
OGCFilterParameters filterParams = new OGCFilterParameters();
filterParams.setLatBeforeLon(wfsType.isLatBeforeLon());
filterParams.setRegion(geometry.buffer(0));
filterParams.setTimeSpan(timeSpan);
filterParams.setUserFilter(userFilter == null ? null
: userFilter.applyFieldNameTransform(WFSTimeFieldGetter.getTimeFieldTransform(wfsType)));
filterParams.setSrs(getServerConfig().getServerCustomization().getSrsName());
filterParams.setOutputFormat(format.getFormatString());
int maxFeatures = WFSPreferenceUtilities.getMaxFeaturesFromPreferences(myPreferences);
filterParams.setMaxFeatures(BigInteger.valueOf(maxFeatures));
filterParams.setGeometryTagName(wfsType.getMetaDataInfo().getGeometryColumn());
filterParams.setTimeFieldNames(WFSTimeFieldGetter.getTimeFieldNames(wfsType));
URL url;
InputStream postRequest = null;
try
{
if (myIsGetFeaturePostEnabled)
{
String urlString = getServerConfig().getWfsUrl();
if (format.isStreaming())
{
urlString = StringUtilities.concat(urlString, "?STREAMING=", Boolean.toString(true));
}
url = new URL(urlString);
postRequest = myEnvoyHelper.buildPostQuery(filterParams, wfsType);
}
else
{
/* Format query as an HTTP GET request Simplify the geometry to
* avoid exceeding the HTTP GET character limit. */
filterParams.setRegion(simplifyGeometry(geometry.buffer(0)));
url = myEnvoyHelper.buildGetFeatureURL(filterParams, wfsType, getServerConfig(), myPreferences);
}
}
catch (MalformedURLException e)
{
LOGGER.warn("Failed to build URL for feature request to server: " + e, e);
return -1;
}
catch (UnsupportedEncodingException e)
{
LOGGER.warn("Failed to properly encode URL for feature request to server: " + e, e);
return -1;
}
if (LOGGER.isDebugEnabled())
{
LOGGER.debug("Requesting features from server using URL: " + url);
}
OGCServerConnector connector = getConnector(url, postRequest, getToolbox().getServerProviderRegistry());
return getFeatures(wfsType, connector, format);
}
/**
* Gets the output format for the data type.
*
* @param wfsType the data type
* @return the output format
*/
protected OGCOutputFormat getOutputFormat(WFSDataType wfsType)
{
OGCOutputFormat format = OGCOutputFormat.getDefaultFormat();
// Serialized objects are not supported in OpenSphere
if (wfsType.getOutputFormat() != null && wfsType.getOutputFormat() != OGCOutputFormat.JAVA_OBJECT
&& wfsType.getOutputFormat() != OGCOutputFormat.STREAMING_FEATURE_JAVA_OBJECT)
{
format = wfsType.getOutputFormat();
}
return format;
}
/**
* Gets features.
*
* @param wfsType the {@link WFSDataType} for the layer
* @param connector a configured connection to the server
* @param format the output format string for the request
* @return a count of {@link MapDataElement}s returned from the server
* @throws OGCServerException the server exception
*/
protected int getFeatures(WFSDataType wfsType, OGCServerConnector connector, OGCOutputFormat format) throws OGCServerException
{
switch (format)
{
case AVRO_DEFLATE:
case AVRO:
return getAvroStreaming(wfsType, connector);
case AVRO_B_DEFLATE:
case AVRO_B:
return getAvroFeatures(wfsType, connector);
case GML_311:
return getFeaturesGml(wfsType, connector, format.getFormatString());
default:
return getFeaturesGml(wfsType, connector, format.getFormatString());
}
}
@Override
protected void populateWFSServerConfig(WFSServerConfig wfsServer) throws OGCServerException
{
myWfsCapabilities = getCapabilitiesDoc(getServerConfig());
OperationsMetadata operationsMetadata = myWfsCapabilities.getOperationsMetadata();
List<Operation> opsList = operationsMetadata == null ? Collections.<Operation>emptyList()
: operationsMetadata.getOperation();
Operation getFeatureOperation = StreamUtilities.filterOne(opsList, op -> op.getName().equals("GetFeature"));
if (getFeatureOperation != null)
{
for (DomainType dt : getFeatureOperation.getParameter())
{
if (dt.getName().equals("OutputFormat"))
{
myDefaultOutputFormat = OGCOutputFormat.getPreferredFormat(dt.getValue());
}
}
for (JAXBElement<RequestMethodType> getOrPost : getFeatureOperation.getDCP().get(0).getHTTP().getGetOrPost())
{
if (getOrPost.getName().getLocalPart().equals("Post"))
{
myIsGetFeaturePostEnabled = true;
}
}
}
wfsServer.setServerId(getServerConfig().getServerId(OGCServerSource.WFS_SERVICE));
wfsServer.setServerTitle(getServerTitle());
wfsServer.setLayers(myEnvoyHelper.buildWFSTypes(myWfsCapabilities, getToolbox(), getServerConfig(), getColumnManager(),
myDefaultOutputFormat));
wfsServer.setServerState(WFSServerState.ACTIVE);
}
/**
* Request the describe features service of the server for the given
* {@link WFSDataType}s and update the data types with the data returned.
*
* @param dataTypes The set of WFS types.
* @throws OGCServerException If communication with the server fails.
* @throws InterruptedException If the thread is interrupted.
*/
protected void describeFeatures(Collection<WFSDataType> dataTypes) throws OGCServerException, InterruptedException
{
long parseStart = 0L;
if (LOGGER.isDebugEnabled())
{
parseStart = System.nanoTime();
}
for (WFSDataType dataType : dataTypes)
{
ThreadControl.check();
try
{
URL url = myEnvoyHelper.buildDescribeFeatureTypeURL(getServerConfig(), dataType);
Set<Document> describeDocs = getDescribeFeatureDocs(url, dataType);
myEnvoyHelper.addDescribeFeatureDataToType(dataType, describeDocs);
}
catch (MalformedURLException e)
{
throw new OGCServerException(e.getMessage(), e);
}
}
if (LOGGER.isDebugEnabled())
{
long parseEnd = System.nanoTime();
LOGGER.debug(StringUtilities.formatTimingMessage("Time to request " + dataTypes.size() + " describeFeatures: ",
parseEnd - parseStart));
}
}
/**
* Gets the capabilities doc.
*
* @param serverCfg the server cfg
* @return the capabilities doc
* @throws OGCServerException the server exception
*/
protected WFSCapabilitiesType getCapabilitiesDoc(ServerConnectionParams serverCfg) throws OGCServerException
{
URL url;
try
{
url = myEnvoyHelper.buildGetCapabilitiesURL(serverCfg);
}
catch (MalformedURLException e)
{
throw new OGCServerException("Invalid URL: " + getServerConfig().getWfsUrl(), e);
}
OGCServerConnector connector = getConnector(url, getToolbox().getServerProviderRegistry());
WFSCapabilitiesType wfsCapabilities = connector.requestObject(WFSCapabilitiesType.class);
if (wfsCapabilities == null)
{
throw new OGCServerException("Failed to retrieve WFS Capabilities for ["
+ getServerConfig().getServerId(OGCServerSource.WFS_SERVICE) + "]", null);
}
return wfsCapabilities;
}
/**
* Gets the describe feature docs.
*
* @param serverUrl the server url
* @param dataType the data type
* @return the describe feature docs
* @throws OGCServerException the server exception
* @throws MalformedURLException the malformed url exception
*/
protected Set<Document> getDescribeFeatureDocs(URL serverUrl, WFSDataType dataType)
throws OGCServerException, MalformedURLException
{
Set<Document> docSet = New.set();
OGCServerConnector connector = getConnector(serverUrl, getToolbox().getServerProviderRegistry());
Document doc = connector.requestDocument();
if (LOGGER.isTraceEnabled())
{
StringBuilder sb = new StringBuilder();
sb.append("describeFeatures response from server [").append(serverUrl).append("]: [");
sb.append(XMLUtilities.format(doc));
sb.append(']');
LOGGER.trace(sb.toString());
}
// If there was an exception, try requesting each layer individually
NodeList exceptions = doc.getElementsByTagNameNS("*", "Exception");
if (exceptions != null && exceptions.getLength() > 0)
{
throw new OGCServerException("Describe feature failed for " + dataType.getDisplayName(), new IOException());
}
else
{
docSet.add(doc);
// Check for nested DescribeFeatureType docs
NodeList imports = doc.getElementsByTagNameNS("*", "import");
for (int i = 0; i < imports.getLength(); i++)
{
String schemaLocation = imports.item(i).getAttributes().getNamedItem("schemaLocation").getNodeValue();
if (schemaLocation.toLowerCase().contains("request=describefeaturetype"))
{
docSet.addAll(getDescribeFeatureDocs(new URL(schemaLocation), dataType));
}
}
}
return docSet;
}
/**
* Request features via the GML 3.1.1 interface.
*
* @param wfsType the {@link WFSDataType} for the layer
* @param connector a configured connection to the server
* @param format the output format string for the request
* @return a count of {@link MapDataElement}s returned from the server
* @throws OGCServerException the server exception
*/
private int getFeaturesGml(WFSDataType wfsType, OGCServerConnector connector, String format) throws OGCServerException
{
InputStream is = connector.requestStream();
long t0 = System.nanoTime();
int count = -1;
try
{
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
SAXParser saxParser = factory.newSAXParser();
// parse the WFS response
FeatureConsumer consumer = getConsumerManager().requestConsumer(wfsType, true);
GmlSaxFeatureResponseHandler handler = new GmlSaxFeatureResponseHandler(wfsType, consumer);
saxParser.parse(is, handler);
// consumer.flush();
count = handler.getProcessedCount();
}
catch (ParserConfigurationException e)
{
LOGGER.warn("Failed to create GML parser for feature type [" + format + "]: " + e, e);
}
catch (SAXException e)
{
LOGGER.warn("Failed to parse features from server for layer [" + wfsType.getTypeName() + "], server format [" + format
+ "]: " + e, e);
}
catch (IOException e)
{
LOGGER.warn("Failure while reading features from server connection for layer [" + wfsType.getTypeName()
+ "], server format [" + format + "]: " + e, e);
}
if (LOGGER.isInfoEnabled())
{
long t1 = System.nanoTime();
LOGGER.info(StringUtilities.formatTimingMessage(
"Retrieved " + count + " objects of type [" + wfsType.getDisplayName() + "] from server in ", t1 - t0));
}
return count;
}
/**
* Get a batch of Avro records and stuff them into the layer.
*
* @param type the layer
* @param connector a connector
* @return the number of records inserted
*/
private int getAvroFeatures(WFSDataType type, OGCServerConnector connector)
{
try
{
DataFileStream<GenericRecord> dataFileStream = connector.requestAvro();
if (dataFileStream == null)
{
return -1;
}
AvroTimeHelper help = new AvroTimeHelper(type);
try
{
List<MapDataElement> elements = new LinkedList<>();
while (dataFileStream.hasNext())
{
elements.add(myEnvoyHelper.createDataElement(dataFileStream.next(), help));
}
FeatureConsumer featureConsumer = getConsumerManager().requestConsumer(type, true);
featureConsumer.addFeatures(elements);
featureConsumer.flush();
return elements.size();
}
finally
{
dataFileStream.close();
}
}
catch (IOException | OGCServerException e)
{
LOGGER.error(e);
return -1;
}
}
/**
* Parse a stream of Avro records for inclusion in the WFSDataType.
*
* @param type the layer
* @param conn connector
* @return the number of data elements inserted
* @throws OGCServerException if cancelled or any kind of error occurs
*/
private int getAvroStreaming(WFSDataType type, OGCServerConnector conn) throws OGCServerException
{
CancellableInputStream in = conn.requestStream();
if (in == null)
{
return -1;
}
int count = 0;
boolean cancelled = false;
FeatureConsumer featureConsumer = getConsumerManager().requestConsumer(type, true);
AvroTimeHelper help = new AvroTimeHelper(type);
try
{
DataFileStream<GenericRecord> data = OGCServerConnector.avroDataStream(in);
ThreadControl.check();
while (data.hasNext())
{
MapDataElement element = myEnvoyHelper.createDataElement(data.next(), help);
element.getMapGeometrySupport().setFollowTerrain(true, type);
featureConsumer.addFeature(element);
count++;
ThreadControl.check();
}
}
catch (InterruptedException eek)
{
cancelled = true;
throw new OGCServerException("Cancelled streaming " + type.getDisplayName(), eek);
}
catch (IOException eek)
{
if (in.isCancelled())
{
throw new OGCServerException("Cancelled streaming " + type.getDisplayName(), eek);
}
throw new OGCServerException("Failed streaming " + type.getDisplayName() + " - " + eek.getMessage(), eek);
}
catch (RuntimeException eek)
{
throw new OGCServerException("Anomaly occurred while streaming " + type.getDisplayName(), eek);
}
finally
{
if (!cancelled && !in.isCancelled())
{
featureConsumer.flush();
}
try
{
in.close();
}
catch (IOException e)
{
// quietly ignore
}
}
return count;
}
/**
* Gets the server title from the saved off WFS capabilities.
*
* @return the server title
*/
private String getServerTitle()
{
return myWfsCapabilities.getServiceIdentification() != null ? myWfsCapabilities.getServiceIdentification().getTitle()
: null;
}
/**
* Retrieve the place name data for this tile. This method will cache the
* data once retrieved and provide the data back to the PlaceNameTile.
*
* @param placeNameTile Tile for which to retrieve data.
*/
protected void retrievePlacenameData(final PlaceNameTile placeNameTile)
{
if (placeNameTile.getServerName().equals(getServerConfig().getServerTitle()))
{
getExecutor().execute(new Runnable()
{
@Override
public void run()
{
DataRegistry dataRegistry = getToolbox().getDataRegistry();
if (dataRegistry == null)
{
return;
}
try
{
myPlacenamesTaskActivity.increment();
WFSEnvoyPlaceNameHelper.retrievePlaceNameData(getServerURL(), toString(), placeNameTile, dataRegistry,
getToolbox());
}
finally
{
myPlacenamesTaskActivity.decrement();
}
}
});
}
}
/**
* Simplify a geometry (polygon) to have a maximum number of vertices. This
* is only required for HTTP "Get" requests, "Post" requests do not have a
* length limitation.
*
* @param inputGeometry the geometry to simplify
* @return the new, simplified geometry
*/
private Geometry simplifyGeometry(Geometry inputGeometry)
{
Geometry finalGeom = inputGeometry;
while (finalGeom.getNumPoints() > MAX_POINTS)
{
final double simplificationFactor = 0.001;
finalGeom = TopologyPreservingSimplifier.simplify(finalGeom, simplificationFactor);
LOGGER.warn("Simplified request geometry from " + inputGeometry.getNumPoints() + " to " + finalGeom.getNumPoints()
+ " points.");
}
return finalGeom;
}
/**
* Extension of {@link TaskActivity} that counts concurrent placenames
* requests.
*/
private static class PlacenamesTaskActivity extends TaskActivity
{
/** The number of concurrent requests. */
private int myCount;
/** Decrement the number of requests. */
public synchronized void decrement()
{
if (--myCount == 0)
{
setActive(false);
}
setLabelValue();
}
/** Increment the number of requests. */
public synchronized void increment()
{
if (myCount++ == 0)
{
setActive(true);
}
setLabelValue();
}
/** Set the label value based on the current count. */
private void setLabelValue()
{
setLabelValue(new StringBuilder(32).append("Place Name Downloads: ").append(myCount).toString());
}
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.php.smarty.editor.coloring;
import org.netbeans.spi.editor.highlighting.HighlightsLayer;
import org.netbeans.spi.editor.highlighting.HighlightsLayerFactory;
import org.netbeans.spi.editor.highlighting.ZOrder;
/**
* Inspired by HTML EmbeddingHighlightsLayerFactory.
*
* @author Martin Fousek <marfous@netbeans.org>
*/
public class EmbeddingHighlightsLayerFactory implements HighlightsLayerFactory {
@Override
public HighlightsLayer[] createLayers(Context context) {
return new HighlightsLayer[]{HighlightsLayer.create("tpl-embedding-highlight-layer", //NOI18N
ZOrder.BOTTOM_RACK.forPosition(100), // we need to have lower priority than the default syntax from options - 0
true,
new EmbeddingHighlightsContainer(context.getDocument()))}; //NOI18N
}
}
|
package com.ming.blog.config;
import org.springframework.context.annotation.Configuration;
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;
@Configuration
@EnableWebSecurity()
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// super.configure(http);
http.authorizeRequests()
// .antMatchers("/hello/*", "/", "/home", "/login", "**").permitAll()
.anyRequest().permitAll();
// .anyRequest().authenticated()
/*.and()
.formLogin()
.permitAll();*/
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// super.configure(auth);
auth
.inMemoryAuthentication()
.withUser("user")
.password("123456").roles("USER");
}
}
|
/**
* Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
* This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
*/
package com.oracle.bmc.jms.responses;
import com.oracle.bmc.jms.model.*;
@javax.annotation.Generated(value = "OracleSDKGenerator", comments = "API Version: 20210610")
@lombok.Builder(builderClassName = "Builder")
@lombok.ToString(callSuper = true)
@lombok.EqualsAndHashCode
@lombok.Getter
public class RequestSummarizedManagedInstanceUsageResponse {
/**
* HTTP status code returned by the operation.
*/
private final int __httpStatusCode__;
/**
* Unique Oracle-assigned identifier for the request. If you need to contact
* Oracle about a particular request, please provide the request ID.
*
*/
private String opcRequestId;
/**
* For list pagination. When this header appears in the response, additional pages of results remain.
* Include this value as the `page` parameter for the subsequent GET request to get the next batch of items.
* For important details about how pagination works, see [List Pagination](https://docs.cloud.oracle.com/iaas/Content/API/Concepts/usingapi.htm#nine).
*
*/
private String opcNextPage;
/**
* The returned ManagedInstanceUsageCollection instance.
*/
private ManagedInstanceUsageCollection managedInstanceUsageCollection;
public static class Builder {
/**
* Copy method to populate the builder with values from the given instance.
* @return this builder instance
*/
public Builder copy(RequestSummarizedManagedInstanceUsageResponse o) {
__httpStatusCode__(o.get__httpStatusCode__());
opcRequestId(o.getOpcRequestId());
opcNextPage(o.getOpcNextPage());
managedInstanceUsageCollection(o.getManagedInstanceUsageCollection());
return this;
}
}
}
|
package com.conveyal.data.census;
import com.conveyal.data.geobuf.GeobufDecoder;
import com.conveyal.data.geobuf.GeobufFeature;
import com.vividsolutions.jts.geom.*;
import com.vividsolutions.jts.geom.prep.PreparedPolygon;
import com.vividsolutions.jts.util.GeometricShapeFactory;
import org.mapdb.DBMaker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import static com.conveyal.data.census.ShapeDataStore.lat2tile;
import static com.conveyal.data.census.ShapeDataStore.lon2tile;
/**
* A tile source for seamless Census extracts
*/
public abstract class SeamlessSource {
// convenience
private static final int ZOOM_LEVEL = ShapeDataStore.ZOOM_LEVEL;
protected static final Logger LOG = LoggerFactory.getLogger(SeamlessSource.class);
private static final GeometryFactory geometryFactory = new GeometryFactory();
/** Extract features by bounding box */
public Map<Long, GeobufFeature> extract(double north, double east, double south, double west, boolean onDisk) throws
IOException {
GeometricShapeFactory factory = new GeometricShapeFactory(geometryFactory);
factory.setCentre(new Coordinate((east + west) / 2, (north + south) / 2));
factory.setWidth(east - west);
factory.setHeight(north - south);
Polygon rect = factory.createRectangle();
return extract(rect, onDisk);
}
/** Extract features by arbitrary polygons */
public Map<Long, GeobufFeature> extract(Geometry bounds, boolean onDisk) throws IOException {
Map<Long, GeobufFeature> ret;
if (onDisk)
ret = DBMaker.tempTreeMap();
else
ret = new HashMap<>();
Envelope env = bounds.getEnvelopeInternal();
double west = env.getMinX(), east = env.getMaxX(), north = env.getMaxY(), south = env.getMinY();
// TODO: use prepared polygons
// figure out how many tiles we're requesting
int minX = lon2tile(west, ZOOM_LEVEL), maxX = lon2tile(east, ZOOM_LEVEL),
minY = lat2tile(north, ZOOM_LEVEL), maxY = lat2tile(south, ZOOM_LEVEL);
int tcount = (maxX - minX + 1) * (maxY - minY + 1);
LOG.info("Requesting {} tiles", tcount);
int fcount = 0;
// read all the relevant tiles
for (int x = minX; x <= maxX; x++) {
for (int y = minY; y <= maxY; y++) {
InputStream is = getInputStream(x, y);
if (is == null)
// no data in this tile
continue;
// decoder closes input stream as soon as it has read the tile
GeobufDecoder decoder = new GeobufDecoder(new GZIPInputStream(new BufferedInputStream(is)));
while (decoder.hasNext()) {
GeobufFeature f = decoder.next();
// blocks are duplicated at the edges of tiles, no need to import twice
if (ret.containsKey(f.numericId))
continue;
if (!bounds.disjoint(f.geometry)) {
ret.put(f.numericId, f);
fcount++;
if (fcount % 1000 == 0)
LOG.info("Read {} features", fcount);
}
}
}
}
return ret;
}
/** get an input stream for the given tile */
protected abstract InputStream getInputStream(int x, int y) throws IOException;
}
|
/*
* Gitea API.
* This documentation describes the Gitea API.
*
* OpenAPI spec version: 1.15.0+dev-206-gae6d7860b
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.gitea.api;
import io.gitea.ApiCallback;
import io.gitea.ApiClient;
import io.gitea.ApiException;
import io.gitea.ApiResponse;
import io.gitea.Configuration;
import io.gitea.Pair;
import io.gitea.ProgressRequestBody;
import io.gitea.ProgressResponseBody;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import io.gitea.model.AccessToken;
import io.gitea.model.CreateEmailOption;
import io.gitea.model.CreateGPGKeyOption;
import io.gitea.model.CreateKeyOption;
import io.gitea.model.CreateOAuth2ApplicationOptions;
import io.gitea.model.CreateRepoOption;
import io.gitea.model.DeleteEmailOption;
import io.gitea.model.Email;
import io.gitea.model.GPGKey;
import io.gitea.model.InlineResponse2001;
import io.gitea.model.OAuth2Application;
import org.threeten.bp.OffsetDateTime;
import io.gitea.model.PublicKey;
import io.gitea.model.Repository;
import io.gitea.model.StopWatch;
import io.gitea.model.Team;
import io.gitea.model.TrackedTime;
import io.gitea.model.User;
import io.gitea.model.UserHeatmapData;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class UserApi {
private ApiClient apiClient;
public UserApi() {
this(Configuration.getDefaultApiClient());
}
public UserApi(ApiClient apiClient) {
this.apiClient = apiClient;
}
public ApiClient getApiClient() {
return apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient;
}
/**
* Build call for createCurrentUserRepo
* @param body (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call createCurrentUserRepoCall(CreateRepoOption body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = body;
// create path and map variables
String localVarPath = "/user/repos";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call createCurrentUserRepoValidateBeforeCall(CreateRepoOption body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
com.squareup.okhttp.Call call = createCurrentUserRepoCall(body, progressListener, progressRequestListener);
return call;
}
/**
* Create a repository
*
* @param body (optional)
* @return Repository
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public Repository createCurrentUserRepo(CreateRepoOption body) throws ApiException {
ApiResponse<Repository> resp = createCurrentUserRepoWithHttpInfo(body);
return resp.getData();
}
/**
* Create a repository
*
* @param body (optional)
* @return ApiResponse<Repository>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<Repository> createCurrentUserRepoWithHttpInfo(CreateRepoOption body) throws ApiException {
com.squareup.okhttp.Call call = createCurrentUserRepoValidateBeforeCall(body, null, null);
Type localVarReturnType = new TypeToken<Repository>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* Create a repository (asynchronously)
*
* @param body (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call createCurrentUserRepoAsync(CreateRepoOption body, final ApiCallback<Repository> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = createCurrentUserRepoValidateBeforeCall(body, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<Repository>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userAddEmail
* @param body (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userAddEmailCall(CreateEmailOption body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = body;
// create path and map variables
String localVarPath = "/user/emails";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userAddEmailValidateBeforeCall(CreateEmailOption body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
com.squareup.okhttp.Call call = userAddEmailCall(body, progressListener, progressRequestListener);
return call;
}
/**
* Add email addresses
*
* @param body (optional)
* @return List<Email>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public List<Email> userAddEmail(CreateEmailOption body) throws ApiException {
ApiResponse<List<Email>> resp = userAddEmailWithHttpInfo(body);
return resp.getData();
}
/**
* Add email addresses
*
* @param body (optional)
* @return ApiResponse<List<Email>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<List<Email>> userAddEmailWithHttpInfo(CreateEmailOption body) throws ApiException {
com.squareup.okhttp.Call call = userAddEmailValidateBeforeCall(body, null, null);
Type localVarReturnType = new TypeToken<List<Email>>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* Add email addresses (asynchronously)
*
* @param body (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userAddEmailAsync(CreateEmailOption body, final ApiCallback<List<Email>> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userAddEmailValidateBeforeCall(body, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<List<Email>>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userCheckFollowing
* @param follower username of following user (required)
* @param followee username of followed user (required)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userCheckFollowingCall(String follower, String followee, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/users/{follower}/following/{followee}"
.replaceAll("\\{" + "follower" + "\\}", apiClient.escapeString(follower.toString()))
.replaceAll("\\{" + "followee" + "\\}", apiClient.escapeString(followee.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json", "text/html"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userCheckFollowingValidateBeforeCall(String follower, String followee, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'follower' is set
if (follower == null) {
throw new ApiException("Missing the required parameter 'follower' when calling userCheckFollowing(Async)");
}
// verify the required parameter 'followee' is set
if (followee == null) {
throw new ApiException("Missing the required parameter 'followee' when calling userCheckFollowing(Async)");
}
com.squareup.okhttp.Call call = userCheckFollowingCall(follower, followee, progressListener, progressRequestListener);
return call;
}
/**
* Check if one user is following another user
*
* @param follower username of following user (required)
* @param followee username of followed user (required)
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public void userCheckFollowing(String follower, String followee) throws ApiException {
userCheckFollowingWithHttpInfo(follower, followee);
}
/**
* Check if one user is following another user
*
* @param follower username of following user (required)
* @param followee username of followed user (required)
* @return ApiResponse<Void>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<Void> userCheckFollowingWithHttpInfo(String follower, String followee) throws ApiException {
com.squareup.okhttp.Call call = userCheckFollowingValidateBeforeCall(follower, followee, null, null);
return apiClient.execute(call);
}
/**
* Check if one user is following another user (asynchronously)
*
* @param follower username of following user (required)
* @param followee username of followed user (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userCheckFollowingAsync(String follower, String followee, final ApiCallback<Void> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userCheckFollowingValidateBeforeCall(follower, followee, progressListener, progressRequestListener);
apiClient.executeAsync(call, callback);
return call;
}
/**
* Build call for userCreateOAuth2Application
* @param body (required)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userCreateOAuth2ApplicationCall(CreateOAuth2ApplicationOptions body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = body;
// create path and map variables
String localVarPath = "/user/applications/oauth2";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userCreateOAuth2ApplicationValidateBeforeCall(CreateOAuth2ApplicationOptions body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'body' is set
if (body == null) {
throw new ApiException("Missing the required parameter 'body' when calling userCreateOAuth2Application(Async)");
}
com.squareup.okhttp.Call call = userCreateOAuth2ApplicationCall(body, progressListener, progressRequestListener);
return call;
}
/**
* creates a new OAuth2 application
*
* @param body (required)
* @return OAuth2Application
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public OAuth2Application userCreateOAuth2Application(CreateOAuth2ApplicationOptions body) throws ApiException {
ApiResponse<OAuth2Application> resp = userCreateOAuth2ApplicationWithHttpInfo(body);
return resp.getData();
}
/**
* creates a new OAuth2 application
*
* @param body (required)
* @return ApiResponse<OAuth2Application>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<OAuth2Application> userCreateOAuth2ApplicationWithHttpInfo(CreateOAuth2ApplicationOptions body) throws ApiException {
com.squareup.okhttp.Call call = userCreateOAuth2ApplicationValidateBeforeCall(body, null, null);
Type localVarReturnType = new TypeToken<OAuth2Application>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* creates a new OAuth2 application (asynchronously)
*
* @param body (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userCreateOAuth2ApplicationAsync(CreateOAuth2ApplicationOptions body, final ApiCallback<OAuth2Application> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userCreateOAuth2ApplicationValidateBeforeCall(body, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<OAuth2Application>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userCreateToken
* @param username username of user (required)
* @param accessToken (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userCreateTokenCall(String username, AccessToken accessToken, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = accessToken;
// create path and map variables
String localVarPath = "/users/{username}/tokens"
.replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userCreateTokenValidateBeforeCall(String username, AccessToken accessToken, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'username' is set
if (username == null) {
throw new ApiException("Missing the required parameter 'username' when calling userCreateToken(Async)");
}
com.squareup.okhttp.Call call = userCreateTokenCall(username, accessToken, progressListener, progressRequestListener);
return call;
}
/**
* Create an access token
*
* @param username username of user (required)
* @param accessToken (optional)
* @return AccessToken
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public AccessToken userCreateToken(String username, AccessToken accessToken) throws ApiException {
ApiResponse<AccessToken> resp = userCreateTokenWithHttpInfo(username, accessToken);
return resp.getData();
}
/**
* Create an access token
*
* @param username username of user (required)
* @param accessToken (optional)
* @return ApiResponse<AccessToken>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<AccessToken> userCreateTokenWithHttpInfo(String username, AccessToken accessToken) throws ApiException {
com.squareup.okhttp.Call call = userCreateTokenValidateBeforeCall(username, accessToken, null, null);
Type localVarReturnType = new TypeToken<AccessToken>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* Create an access token (asynchronously)
*
* @param username username of user (required)
* @param accessToken (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userCreateTokenAsync(String username, AccessToken accessToken, final ApiCallback<AccessToken> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userCreateTokenValidateBeforeCall(username, accessToken, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<AccessToken>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userCurrentCheckFollowing
* @param username username of followed user (required)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userCurrentCheckFollowingCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/user/following/{username}"
.replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json", "text/html"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userCurrentCheckFollowingValidateBeforeCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'username' is set
if (username == null) {
throw new ApiException("Missing the required parameter 'username' when calling userCurrentCheckFollowing(Async)");
}
com.squareup.okhttp.Call call = userCurrentCheckFollowingCall(username, progressListener, progressRequestListener);
return call;
}
/**
* Check whether a user is followed by the authenticated user
*
* @param username username of followed user (required)
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public void userCurrentCheckFollowing(String username) throws ApiException {
userCurrentCheckFollowingWithHttpInfo(username);
}
/**
* Check whether a user is followed by the authenticated user
*
* @param username username of followed user (required)
* @return ApiResponse<Void>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<Void> userCurrentCheckFollowingWithHttpInfo(String username) throws ApiException {
com.squareup.okhttp.Call call = userCurrentCheckFollowingValidateBeforeCall(username, null, null);
return apiClient.execute(call);
}
/**
* Check whether a user is followed by the authenticated user (asynchronously)
*
* @param username username of followed user (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userCurrentCheckFollowingAsync(String username, final ApiCallback<Void> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userCurrentCheckFollowingValidateBeforeCall(username, progressListener, progressRequestListener);
apiClient.executeAsync(call, callback);
return call;
}
/**
* Build call for userCurrentCheckStarring
* @param owner owner of the repo (required)
* @param repo name of the repo (required)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userCurrentCheckStarringCall(String owner, String repo, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/user/starred/{owner}/{repo}"
.replaceAll("\\{" + "owner" + "\\}", apiClient.escapeString(owner.toString()))
.replaceAll("\\{" + "repo" + "\\}", apiClient.escapeString(repo.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json", "text/html"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userCurrentCheckStarringValidateBeforeCall(String owner, String repo, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'owner' is set
if (owner == null) {
throw new ApiException("Missing the required parameter 'owner' when calling userCurrentCheckStarring(Async)");
}
// verify the required parameter 'repo' is set
if (repo == null) {
throw new ApiException("Missing the required parameter 'repo' when calling userCurrentCheckStarring(Async)");
}
com.squareup.okhttp.Call call = userCurrentCheckStarringCall(owner, repo, progressListener, progressRequestListener);
return call;
}
/**
* Whether the authenticated is starring the repo
*
* @param owner owner of the repo (required)
* @param repo name of the repo (required)
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public void userCurrentCheckStarring(String owner, String repo) throws ApiException {
userCurrentCheckStarringWithHttpInfo(owner, repo);
}
/**
* Whether the authenticated is starring the repo
*
* @param owner owner of the repo (required)
* @param repo name of the repo (required)
* @return ApiResponse<Void>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<Void> userCurrentCheckStarringWithHttpInfo(String owner, String repo) throws ApiException {
com.squareup.okhttp.Call call = userCurrentCheckStarringValidateBeforeCall(owner, repo, null, null);
return apiClient.execute(call);
}
/**
* Whether the authenticated is starring the repo (asynchronously)
*
* @param owner owner of the repo (required)
* @param repo name of the repo (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userCurrentCheckStarringAsync(String owner, String repo, final ApiCallback<Void> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userCurrentCheckStarringValidateBeforeCall(owner, repo, progressListener, progressRequestListener);
apiClient.executeAsync(call, callback);
return call;
}
/**
* Build call for userCurrentDeleteFollow
* @param username username of user to unfollow (required)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userCurrentDeleteFollowCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/user/following/{username}"
.replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json", "text/html"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userCurrentDeleteFollowValidateBeforeCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'username' is set
if (username == null) {
throw new ApiException("Missing the required parameter 'username' when calling userCurrentDeleteFollow(Async)");
}
com.squareup.okhttp.Call call = userCurrentDeleteFollowCall(username, progressListener, progressRequestListener);
return call;
}
/**
* Unfollow a user
*
* @param username username of user to unfollow (required)
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public void userCurrentDeleteFollow(String username) throws ApiException {
userCurrentDeleteFollowWithHttpInfo(username);
}
/**
* Unfollow a user
*
* @param username username of user to unfollow (required)
* @return ApiResponse<Void>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<Void> userCurrentDeleteFollowWithHttpInfo(String username) throws ApiException {
com.squareup.okhttp.Call call = userCurrentDeleteFollowValidateBeforeCall(username, null, null);
return apiClient.execute(call);
}
/**
* Unfollow a user (asynchronously)
*
* @param username username of user to unfollow (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userCurrentDeleteFollowAsync(String username, final ApiCallback<Void> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userCurrentDeleteFollowValidateBeforeCall(username, progressListener, progressRequestListener);
apiClient.executeAsync(call, callback);
return call;
}
/**
* Build call for userCurrentDeleteGPGKey
* @param id id of key to delete (required)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userCurrentDeleteGPGKeyCall(Long id, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/user/gpg_keys/{id}"
.replaceAll("\\{" + "id" + "\\}", apiClient.escapeString(id.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userCurrentDeleteGPGKeyValidateBeforeCall(Long id, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException("Missing the required parameter 'id' when calling userCurrentDeleteGPGKey(Async)");
}
com.squareup.okhttp.Call call = userCurrentDeleteGPGKeyCall(id, progressListener, progressRequestListener);
return call;
}
/**
* Remove a GPG key
*
* @param id id of key to delete (required)
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public void userCurrentDeleteGPGKey(Long id) throws ApiException {
userCurrentDeleteGPGKeyWithHttpInfo(id);
}
/**
* Remove a GPG key
*
* @param id id of key to delete (required)
* @return ApiResponse<Void>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<Void> userCurrentDeleteGPGKeyWithHttpInfo(Long id) throws ApiException {
com.squareup.okhttp.Call call = userCurrentDeleteGPGKeyValidateBeforeCall(id, null, null);
return apiClient.execute(call);
}
/**
* Remove a GPG key (asynchronously)
*
* @param id id of key to delete (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userCurrentDeleteGPGKeyAsync(Long id, final ApiCallback<Void> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userCurrentDeleteGPGKeyValidateBeforeCall(id, progressListener, progressRequestListener);
apiClient.executeAsync(call, callback);
return call;
}
/**
* Build call for userCurrentDeleteKey
* @param id id of key to delete (required)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userCurrentDeleteKeyCall(Long id, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/user/keys/{id}"
.replaceAll("\\{" + "id" + "\\}", apiClient.escapeString(id.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userCurrentDeleteKeyValidateBeforeCall(Long id, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException("Missing the required parameter 'id' when calling userCurrentDeleteKey(Async)");
}
com.squareup.okhttp.Call call = userCurrentDeleteKeyCall(id, progressListener, progressRequestListener);
return call;
}
/**
* Delete a public key
*
* @param id id of key to delete (required)
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public void userCurrentDeleteKey(Long id) throws ApiException {
userCurrentDeleteKeyWithHttpInfo(id);
}
/**
* Delete a public key
*
* @param id id of key to delete (required)
* @return ApiResponse<Void>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<Void> userCurrentDeleteKeyWithHttpInfo(Long id) throws ApiException {
com.squareup.okhttp.Call call = userCurrentDeleteKeyValidateBeforeCall(id, null, null);
return apiClient.execute(call);
}
/**
* Delete a public key (asynchronously)
*
* @param id id of key to delete (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userCurrentDeleteKeyAsync(Long id, final ApiCallback<Void> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userCurrentDeleteKeyValidateBeforeCall(id, progressListener, progressRequestListener);
apiClient.executeAsync(call, callback);
return call;
}
/**
* Build call for userCurrentDeleteStar
* @param owner owner of the repo to unstar (required)
* @param repo name of the repo to unstar (required)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userCurrentDeleteStarCall(String owner, String repo, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/user/starred/{owner}/{repo}"
.replaceAll("\\{" + "owner" + "\\}", apiClient.escapeString(owner.toString()))
.replaceAll("\\{" + "repo" + "\\}", apiClient.escapeString(repo.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json", "text/html"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userCurrentDeleteStarValidateBeforeCall(String owner, String repo, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'owner' is set
if (owner == null) {
throw new ApiException("Missing the required parameter 'owner' when calling userCurrentDeleteStar(Async)");
}
// verify the required parameter 'repo' is set
if (repo == null) {
throw new ApiException("Missing the required parameter 'repo' when calling userCurrentDeleteStar(Async)");
}
com.squareup.okhttp.Call call = userCurrentDeleteStarCall(owner, repo, progressListener, progressRequestListener);
return call;
}
/**
* Unstar the given repo
*
* @param owner owner of the repo to unstar (required)
* @param repo name of the repo to unstar (required)
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public void userCurrentDeleteStar(String owner, String repo) throws ApiException {
userCurrentDeleteStarWithHttpInfo(owner, repo);
}
/**
* Unstar the given repo
*
* @param owner owner of the repo to unstar (required)
* @param repo name of the repo to unstar (required)
* @return ApiResponse<Void>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<Void> userCurrentDeleteStarWithHttpInfo(String owner, String repo) throws ApiException {
com.squareup.okhttp.Call call = userCurrentDeleteStarValidateBeforeCall(owner, repo, null, null);
return apiClient.execute(call);
}
/**
* Unstar the given repo (asynchronously)
*
* @param owner owner of the repo to unstar (required)
* @param repo name of the repo to unstar (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userCurrentDeleteStarAsync(String owner, String repo, final ApiCallback<Void> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userCurrentDeleteStarValidateBeforeCall(owner, repo, progressListener, progressRequestListener);
apiClient.executeAsync(call, callback);
return call;
}
/**
* Build call for userCurrentGetGPGKey
* @param id id of key to get (required)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userCurrentGetGPGKeyCall(Long id, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/user/gpg_keys/{id}"
.replaceAll("\\{" + "id" + "\\}", apiClient.escapeString(id.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userCurrentGetGPGKeyValidateBeforeCall(Long id, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException("Missing the required parameter 'id' when calling userCurrentGetGPGKey(Async)");
}
com.squareup.okhttp.Call call = userCurrentGetGPGKeyCall(id, progressListener, progressRequestListener);
return call;
}
/**
* Get a GPG key
*
* @param id id of key to get (required)
* @return GPGKey
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public GPGKey userCurrentGetGPGKey(Long id) throws ApiException {
ApiResponse<GPGKey> resp = userCurrentGetGPGKeyWithHttpInfo(id);
return resp.getData();
}
/**
* Get a GPG key
*
* @param id id of key to get (required)
* @return ApiResponse<GPGKey>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<GPGKey> userCurrentGetGPGKeyWithHttpInfo(Long id) throws ApiException {
com.squareup.okhttp.Call call = userCurrentGetGPGKeyValidateBeforeCall(id, null, null);
Type localVarReturnType = new TypeToken<GPGKey>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* Get a GPG key (asynchronously)
*
* @param id id of key to get (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userCurrentGetGPGKeyAsync(Long id, final ApiCallback<GPGKey> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userCurrentGetGPGKeyValidateBeforeCall(id, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<GPGKey>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userCurrentGetKey
* @param id id of key to get (required)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userCurrentGetKeyCall(Long id, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/user/keys/{id}"
.replaceAll("\\{" + "id" + "\\}", apiClient.escapeString(id.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userCurrentGetKeyValidateBeforeCall(Long id, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException("Missing the required parameter 'id' when calling userCurrentGetKey(Async)");
}
com.squareup.okhttp.Call call = userCurrentGetKeyCall(id, progressListener, progressRequestListener);
return call;
}
/**
* Get a public key
*
* @param id id of key to get (required)
* @return PublicKey
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public PublicKey userCurrentGetKey(Long id) throws ApiException {
ApiResponse<PublicKey> resp = userCurrentGetKeyWithHttpInfo(id);
return resp.getData();
}
/**
* Get a public key
*
* @param id id of key to get (required)
* @return ApiResponse<PublicKey>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<PublicKey> userCurrentGetKeyWithHttpInfo(Long id) throws ApiException {
com.squareup.okhttp.Call call = userCurrentGetKeyValidateBeforeCall(id, null, null);
Type localVarReturnType = new TypeToken<PublicKey>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* Get a public key (asynchronously)
*
* @param id id of key to get (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userCurrentGetKeyAsync(Long id, final ApiCallback<PublicKey> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userCurrentGetKeyValidateBeforeCall(id, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<PublicKey>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userCurrentListFollowers
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userCurrentListFollowersCall(Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/user/followers";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
if (page != null)
localVarQueryParams.addAll(apiClient.parameterToPair("page", page));
if (limit != null)
localVarQueryParams.addAll(apiClient.parameterToPair("limit", limit));
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userCurrentListFollowersValidateBeforeCall(Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
com.squareup.okhttp.Call call = userCurrentListFollowersCall(page, limit, progressListener, progressRequestListener);
return call;
}
/**
* List the authenticated user's followers
*
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return List<User>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public List<User> userCurrentListFollowers(Integer page, Integer limit) throws ApiException {
ApiResponse<List<User>> resp = userCurrentListFollowersWithHttpInfo(page, limit);
return resp.getData();
}
/**
* List the authenticated user's followers
*
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return ApiResponse<List<User>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<List<User>> userCurrentListFollowersWithHttpInfo(Integer page, Integer limit) throws ApiException {
com.squareup.okhttp.Call call = userCurrentListFollowersValidateBeforeCall(page, limit, null, null);
Type localVarReturnType = new TypeToken<List<User>>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* List the authenticated user's followers (asynchronously)
*
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userCurrentListFollowersAsync(Integer page, Integer limit, final ApiCallback<List<User>> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userCurrentListFollowersValidateBeforeCall(page, limit, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<List<User>>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userCurrentListFollowing
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userCurrentListFollowingCall(Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/user/following";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
if (page != null)
localVarQueryParams.addAll(apiClient.parameterToPair("page", page));
if (limit != null)
localVarQueryParams.addAll(apiClient.parameterToPair("limit", limit));
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userCurrentListFollowingValidateBeforeCall(Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
com.squareup.okhttp.Call call = userCurrentListFollowingCall(page, limit, progressListener, progressRequestListener);
return call;
}
/**
* List the users that the authenticated user is following
*
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return List<User>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public List<User> userCurrentListFollowing(Integer page, Integer limit) throws ApiException {
ApiResponse<List<User>> resp = userCurrentListFollowingWithHttpInfo(page, limit);
return resp.getData();
}
/**
* List the users that the authenticated user is following
*
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return ApiResponse<List<User>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<List<User>> userCurrentListFollowingWithHttpInfo(Integer page, Integer limit) throws ApiException {
com.squareup.okhttp.Call call = userCurrentListFollowingValidateBeforeCall(page, limit, null, null);
Type localVarReturnType = new TypeToken<List<User>>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* List the users that the authenticated user is following (asynchronously)
*
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userCurrentListFollowingAsync(Integer page, Integer limit, final ApiCallback<List<User>> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userCurrentListFollowingValidateBeforeCall(page, limit, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<List<User>>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userCurrentListGPGKeys
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userCurrentListGPGKeysCall(Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/user/gpg_keys";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
if (page != null)
localVarQueryParams.addAll(apiClient.parameterToPair("page", page));
if (limit != null)
localVarQueryParams.addAll(apiClient.parameterToPair("limit", limit));
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userCurrentListGPGKeysValidateBeforeCall(Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
com.squareup.okhttp.Call call = userCurrentListGPGKeysCall(page, limit, progressListener, progressRequestListener);
return call;
}
/**
* List the authenticated user's GPG keys
*
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return List<GPGKey>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public List<GPGKey> userCurrentListGPGKeys(Integer page, Integer limit) throws ApiException {
ApiResponse<List<GPGKey>> resp = userCurrentListGPGKeysWithHttpInfo(page, limit);
return resp.getData();
}
/**
* List the authenticated user's GPG keys
*
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return ApiResponse<List<GPGKey>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<List<GPGKey>> userCurrentListGPGKeysWithHttpInfo(Integer page, Integer limit) throws ApiException {
com.squareup.okhttp.Call call = userCurrentListGPGKeysValidateBeforeCall(page, limit, null, null);
Type localVarReturnType = new TypeToken<List<GPGKey>>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* List the authenticated user's GPG keys (asynchronously)
*
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userCurrentListGPGKeysAsync(Integer page, Integer limit, final ApiCallback<List<GPGKey>> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userCurrentListGPGKeysValidateBeforeCall(page, limit, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<List<GPGKey>>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userCurrentListKeys
* @param fingerprint fingerprint of the key (optional)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userCurrentListKeysCall(String fingerprint, Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/user/keys";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
if (fingerprint != null)
localVarQueryParams.addAll(apiClient.parameterToPair("fingerprint", fingerprint));
if (page != null)
localVarQueryParams.addAll(apiClient.parameterToPair("page", page));
if (limit != null)
localVarQueryParams.addAll(apiClient.parameterToPair("limit", limit));
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userCurrentListKeysValidateBeforeCall(String fingerprint, Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
com.squareup.okhttp.Call call = userCurrentListKeysCall(fingerprint, page, limit, progressListener, progressRequestListener);
return call;
}
/**
* List the authenticated user's public keys
*
* @param fingerprint fingerprint of the key (optional)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return List<PublicKey>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public List<PublicKey> userCurrentListKeys(String fingerprint, Integer page, Integer limit) throws ApiException {
ApiResponse<List<PublicKey>> resp = userCurrentListKeysWithHttpInfo(fingerprint, page, limit);
return resp.getData();
}
/**
* List the authenticated user's public keys
*
* @param fingerprint fingerprint of the key (optional)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return ApiResponse<List<PublicKey>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<List<PublicKey>> userCurrentListKeysWithHttpInfo(String fingerprint, Integer page, Integer limit) throws ApiException {
com.squareup.okhttp.Call call = userCurrentListKeysValidateBeforeCall(fingerprint, page, limit, null, null);
Type localVarReturnType = new TypeToken<List<PublicKey>>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* List the authenticated user's public keys (asynchronously)
*
* @param fingerprint fingerprint of the key (optional)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userCurrentListKeysAsync(String fingerprint, Integer page, Integer limit, final ApiCallback<List<PublicKey>> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userCurrentListKeysValidateBeforeCall(fingerprint, page, limit, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<List<PublicKey>>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userCurrentListRepos
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userCurrentListReposCall(Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/user/repos";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
if (page != null)
localVarQueryParams.addAll(apiClient.parameterToPair("page", page));
if (limit != null)
localVarQueryParams.addAll(apiClient.parameterToPair("limit", limit));
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userCurrentListReposValidateBeforeCall(Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
com.squareup.okhttp.Call call = userCurrentListReposCall(page, limit, progressListener, progressRequestListener);
return call;
}
/**
* List the repos that the authenticated user owns or has access to
*
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return List<Repository>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public List<Repository> userCurrentListRepos(Integer page, Integer limit) throws ApiException {
ApiResponse<List<Repository>> resp = userCurrentListReposWithHttpInfo(page, limit);
return resp.getData();
}
/**
* List the repos that the authenticated user owns or has access to
*
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return ApiResponse<List<Repository>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<List<Repository>> userCurrentListReposWithHttpInfo(Integer page, Integer limit) throws ApiException {
com.squareup.okhttp.Call call = userCurrentListReposValidateBeforeCall(page, limit, null, null);
Type localVarReturnType = new TypeToken<List<Repository>>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* List the repos that the authenticated user owns or has access to (asynchronously)
*
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userCurrentListReposAsync(Integer page, Integer limit, final ApiCallback<List<Repository>> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userCurrentListReposValidateBeforeCall(page, limit, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<List<Repository>>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userCurrentListStarred
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userCurrentListStarredCall(Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/user/starred";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
if (page != null)
localVarQueryParams.addAll(apiClient.parameterToPair("page", page));
if (limit != null)
localVarQueryParams.addAll(apiClient.parameterToPair("limit", limit));
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userCurrentListStarredValidateBeforeCall(Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
com.squareup.okhttp.Call call = userCurrentListStarredCall(page, limit, progressListener, progressRequestListener);
return call;
}
/**
* The repos that the authenticated user has starred
*
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return List<Repository>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public List<Repository> userCurrentListStarred(Integer page, Integer limit) throws ApiException {
ApiResponse<List<Repository>> resp = userCurrentListStarredWithHttpInfo(page, limit);
return resp.getData();
}
/**
* The repos that the authenticated user has starred
*
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return ApiResponse<List<Repository>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<List<Repository>> userCurrentListStarredWithHttpInfo(Integer page, Integer limit) throws ApiException {
com.squareup.okhttp.Call call = userCurrentListStarredValidateBeforeCall(page, limit, null, null);
Type localVarReturnType = new TypeToken<List<Repository>>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* The repos that the authenticated user has starred (asynchronously)
*
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userCurrentListStarredAsync(Integer page, Integer limit, final ApiCallback<List<Repository>> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userCurrentListStarredValidateBeforeCall(page, limit, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<List<Repository>>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userCurrentListSubscriptions
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userCurrentListSubscriptionsCall(Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/user/subscriptions";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
if (page != null)
localVarQueryParams.addAll(apiClient.parameterToPair("page", page));
if (limit != null)
localVarQueryParams.addAll(apiClient.parameterToPair("limit", limit));
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userCurrentListSubscriptionsValidateBeforeCall(Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
com.squareup.okhttp.Call call = userCurrentListSubscriptionsCall(page, limit, progressListener, progressRequestListener);
return call;
}
/**
* List repositories watched by the authenticated user
*
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return List<Repository>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public List<Repository> userCurrentListSubscriptions(Integer page, Integer limit) throws ApiException {
ApiResponse<List<Repository>> resp = userCurrentListSubscriptionsWithHttpInfo(page, limit);
return resp.getData();
}
/**
* List repositories watched by the authenticated user
*
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return ApiResponse<List<Repository>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<List<Repository>> userCurrentListSubscriptionsWithHttpInfo(Integer page, Integer limit) throws ApiException {
com.squareup.okhttp.Call call = userCurrentListSubscriptionsValidateBeforeCall(page, limit, null, null);
Type localVarReturnType = new TypeToken<List<Repository>>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* List repositories watched by the authenticated user (asynchronously)
*
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userCurrentListSubscriptionsAsync(Integer page, Integer limit, final ApiCallback<List<Repository>> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userCurrentListSubscriptionsValidateBeforeCall(page, limit, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<List<Repository>>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userCurrentPostGPGKey
* @param form (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userCurrentPostGPGKeyCall(CreateGPGKeyOption form, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = form;
// create path and map variables
String localVarPath = "/user/gpg_keys";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userCurrentPostGPGKeyValidateBeforeCall(CreateGPGKeyOption form, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
com.squareup.okhttp.Call call = userCurrentPostGPGKeyCall(form, progressListener, progressRequestListener);
return call;
}
/**
* Create a GPG key
*
* @param form (optional)
* @return GPGKey
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public GPGKey userCurrentPostGPGKey(CreateGPGKeyOption form) throws ApiException {
ApiResponse<GPGKey> resp = userCurrentPostGPGKeyWithHttpInfo(form);
return resp.getData();
}
/**
* Create a GPG key
*
* @param form (optional)
* @return ApiResponse<GPGKey>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<GPGKey> userCurrentPostGPGKeyWithHttpInfo(CreateGPGKeyOption form) throws ApiException {
com.squareup.okhttp.Call call = userCurrentPostGPGKeyValidateBeforeCall(form, null, null);
Type localVarReturnType = new TypeToken<GPGKey>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* Create a GPG key (asynchronously)
*
* @param form (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userCurrentPostGPGKeyAsync(CreateGPGKeyOption form, final ApiCallback<GPGKey> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userCurrentPostGPGKeyValidateBeforeCall(form, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<GPGKey>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userCurrentPostKey
* @param body (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userCurrentPostKeyCall(CreateKeyOption body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = body;
// create path and map variables
String localVarPath = "/user/keys";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userCurrentPostKeyValidateBeforeCall(CreateKeyOption body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
com.squareup.okhttp.Call call = userCurrentPostKeyCall(body, progressListener, progressRequestListener);
return call;
}
/**
* Create a public key
*
* @param body (optional)
* @return PublicKey
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public PublicKey userCurrentPostKey(CreateKeyOption body) throws ApiException {
ApiResponse<PublicKey> resp = userCurrentPostKeyWithHttpInfo(body);
return resp.getData();
}
/**
* Create a public key
*
* @param body (optional)
* @return ApiResponse<PublicKey>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<PublicKey> userCurrentPostKeyWithHttpInfo(CreateKeyOption body) throws ApiException {
com.squareup.okhttp.Call call = userCurrentPostKeyValidateBeforeCall(body, null, null);
Type localVarReturnType = new TypeToken<PublicKey>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* Create a public key (asynchronously)
*
* @param body (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userCurrentPostKeyAsync(CreateKeyOption body, final ApiCallback<PublicKey> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userCurrentPostKeyValidateBeforeCall(body, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<PublicKey>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userCurrentPutFollow
* @param username username of user to follow (required)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userCurrentPutFollowCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/user/following/{username}"
.replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json", "text/html"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userCurrentPutFollowValidateBeforeCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'username' is set
if (username == null) {
throw new ApiException("Missing the required parameter 'username' when calling userCurrentPutFollow(Async)");
}
com.squareup.okhttp.Call call = userCurrentPutFollowCall(username, progressListener, progressRequestListener);
return call;
}
/**
* Follow a user
*
* @param username username of user to follow (required)
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public void userCurrentPutFollow(String username) throws ApiException {
userCurrentPutFollowWithHttpInfo(username);
}
/**
* Follow a user
*
* @param username username of user to follow (required)
* @return ApiResponse<Void>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<Void> userCurrentPutFollowWithHttpInfo(String username) throws ApiException {
com.squareup.okhttp.Call call = userCurrentPutFollowValidateBeforeCall(username, null, null);
return apiClient.execute(call);
}
/**
* Follow a user (asynchronously)
*
* @param username username of user to follow (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userCurrentPutFollowAsync(String username, final ApiCallback<Void> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userCurrentPutFollowValidateBeforeCall(username, progressListener, progressRequestListener);
apiClient.executeAsync(call, callback);
return call;
}
/**
* Build call for userCurrentPutStar
* @param owner owner of the repo to star (required)
* @param repo name of the repo to star (required)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userCurrentPutStarCall(String owner, String repo, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/user/starred/{owner}/{repo}"
.replaceAll("\\{" + "owner" + "\\}", apiClient.escapeString(owner.toString()))
.replaceAll("\\{" + "repo" + "\\}", apiClient.escapeString(repo.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json", "text/html"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userCurrentPutStarValidateBeforeCall(String owner, String repo, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'owner' is set
if (owner == null) {
throw new ApiException("Missing the required parameter 'owner' when calling userCurrentPutStar(Async)");
}
// verify the required parameter 'repo' is set
if (repo == null) {
throw new ApiException("Missing the required parameter 'repo' when calling userCurrentPutStar(Async)");
}
com.squareup.okhttp.Call call = userCurrentPutStarCall(owner, repo, progressListener, progressRequestListener);
return call;
}
/**
* Star the given repo
*
* @param owner owner of the repo to star (required)
* @param repo name of the repo to star (required)
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public void userCurrentPutStar(String owner, String repo) throws ApiException {
userCurrentPutStarWithHttpInfo(owner, repo);
}
/**
* Star the given repo
*
* @param owner owner of the repo to star (required)
* @param repo name of the repo to star (required)
* @return ApiResponse<Void>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<Void> userCurrentPutStarWithHttpInfo(String owner, String repo) throws ApiException {
com.squareup.okhttp.Call call = userCurrentPutStarValidateBeforeCall(owner, repo, null, null);
return apiClient.execute(call);
}
/**
* Star the given repo (asynchronously)
*
* @param owner owner of the repo to star (required)
* @param repo name of the repo to star (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userCurrentPutStarAsync(String owner, String repo, final ApiCallback<Void> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userCurrentPutStarValidateBeforeCall(owner, repo, progressListener, progressRequestListener);
apiClient.executeAsync(call, callback);
return call;
}
/**
* Build call for userCurrentTrackedTimes
* @param since Only show times updated after the given time. This is a timestamp in RFC 3339 format (optional)
* @param before Only show times updated before the given time. This is a timestamp in RFC 3339 format (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userCurrentTrackedTimesCall(OffsetDateTime since, OffsetDateTime before, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/user/times";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
if (since != null)
localVarQueryParams.addAll(apiClient.parameterToPair("since", since));
if (before != null)
localVarQueryParams.addAll(apiClient.parameterToPair("before", before));
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userCurrentTrackedTimesValidateBeforeCall(OffsetDateTime since, OffsetDateTime before, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
com.squareup.okhttp.Call call = userCurrentTrackedTimesCall(since, before, progressListener, progressRequestListener);
return call;
}
/**
* List the current user's tracked times
*
* @param since Only show times updated after the given time. This is a timestamp in RFC 3339 format (optional)
* @param before Only show times updated before the given time. This is a timestamp in RFC 3339 format (optional)
* @return List<TrackedTime>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public List<TrackedTime> userCurrentTrackedTimes(OffsetDateTime since, OffsetDateTime before) throws ApiException {
ApiResponse<List<TrackedTime>> resp = userCurrentTrackedTimesWithHttpInfo(since, before);
return resp.getData();
}
/**
* List the current user's tracked times
*
* @param since Only show times updated after the given time. This is a timestamp in RFC 3339 format (optional)
* @param before Only show times updated before the given time. This is a timestamp in RFC 3339 format (optional)
* @return ApiResponse<List<TrackedTime>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<List<TrackedTime>> userCurrentTrackedTimesWithHttpInfo(OffsetDateTime since, OffsetDateTime before) throws ApiException {
com.squareup.okhttp.Call call = userCurrentTrackedTimesValidateBeforeCall(since, before, null, null);
Type localVarReturnType = new TypeToken<List<TrackedTime>>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* List the current user's tracked times (asynchronously)
*
* @param since Only show times updated after the given time. This is a timestamp in RFC 3339 format (optional)
* @param before Only show times updated before the given time. This is a timestamp in RFC 3339 format (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userCurrentTrackedTimesAsync(OffsetDateTime since, OffsetDateTime before, final ApiCallback<List<TrackedTime>> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userCurrentTrackedTimesValidateBeforeCall(since, before, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<List<TrackedTime>>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userDeleteAccessToken
* @param username username of user (required)
* @param token token to be deleted, identified by ID and if not available by name (required)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userDeleteAccessTokenCall(String username, String token, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/users/{username}/tokens/{token}"
.replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString()))
.replaceAll("\\{" + "token" + "\\}", apiClient.escapeString(token.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userDeleteAccessTokenValidateBeforeCall(String username, String token, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'username' is set
if (username == null) {
throw new ApiException("Missing the required parameter 'username' when calling userDeleteAccessToken(Async)");
}
// verify the required parameter 'token' is set
if (token == null) {
throw new ApiException("Missing the required parameter 'token' when calling userDeleteAccessToken(Async)");
}
com.squareup.okhttp.Call call = userDeleteAccessTokenCall(username, token, progressListener, progressRequestListener);
return call;
}
/**
* delete an access token
*
* @param username username of user (required)
* @param token token to be deleted, identified by ID and if not available by name (required)
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public void userDeleteAccessToken(String username, String token) throws ApiException {
userDeleteAccessTokenWithHttpInfo(username, token);
}
/**
* delete an access token
*
* @param username username of user (required)
* @param token token to be deleted, identified by ID and if not available by name (required)
* @return ApiResponse<Void>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<Void> userDeleteAccessTokenWithHttpInfo(String username, String token) throws ApiException {
com.squareup.okhttp.Call call = userDeleteAccessTokenValidateBeforeCall(username, token, null, null);
return apiClient.execute(call);
}
/**
* delete an access token (asynchronously)
*
* @param username username of user (required)
* @param token token to be deleted, identified by ID and if not available by name (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userDeleteAccessTokenAsync(String username, String token, final ApiCallback<Void> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userDeleteAccessTokenValidateBeforeCall(username, token, progressListener, progressRequestListener);
apiClient.executeAsync(call, callback);
return call;
}
/**
* Build call for userDeleteEmail
* @param body (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userDeleteEmailCall(DeleteEmailOption body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = body;
// create path and map variables
String localVarPath = "/user/emails";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userDeleteEmailValidateBeforeCall(DeleteEmailOption body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
com.squareup.okhttp.Call call = userDeleteEmailCall(body, progressListener, progressRequestListener);
return call;
}
/**
* Delete email addresses
*
* @param body (optional)
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public void userDeleteEmail(DeleteEmailOption body) throws ApiException {
userDeleteEmailWithHttpInfo(body);
}
/**
* Delete email addresses
*
* @param body (optional)
* @return ApiResponse<Void>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<Void> userDeleteEmailWithHttpInfo(DeleteEmailOption body) throws ApiException {
com.squareup.okhttp.Call call = userDeleteEmailValidateBeforeCall(body, null, null);
return apiClient.execute(call);
}
/**
* Delete email addresses (asynchronously)
*
* @param body (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userDeleteEmailAsync(DeleteEmailOption body, final ApiCallback<Void> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userDeleteEmailValidateBeforeCall(body, progressListener, progressRequestListener);
apiClient.executeAsync(call, callback);
return call;
}
/**
* Build call for userDeleteOAuth2Application
* @param id token to be deleted (required)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userDeleteOAuth2ApplicationCall(Long id, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/user/applications/oauth2/{id}"
.replaceAll("\\{" + "id" + "\\}", apiClient.escapeString(id.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userDeleteOAuth2ApplicationValidateBeforeCall(Long id, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException("Missing the required parameter 'id' when calling userDeleteOAuth2Application(Async)");
}
com.squareup.okhttp.Call call = userDeleteOAuth2ApplicationCall(id, progressListener, progressRequestListener);
return call;
}
/**
* delete an OAuth2 Application
*
* @param id token to be deleted (required)
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public void userDeleteOAuth2Application(Long id) throws ApiException {
userDeleteOAuth2ApplicationWithHttpInfo(id);
}
/**
* delete an OAuth2 Application
*
* @param id token to be deleted (required)
* @return ApiResponse<Void>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<Void> userDeleteOAuth2ApplicationWithHttpInfo(Long id) throws ApiException {
com.squareup.okhttp.Call call = userDeleteOAuth2ApplicationValidateBeforeCall(id, null, null);
return apiClient.execute(call);
}
/**
* delete an OAuth2 Application (asynchronously)
*
* @param id token to be deleted (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userDeleteOAuth2ApplicationAsync(Long id, final ApiCallback<Void> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userDeleteOAuth2ApplicationValidateBeforeCall(id, progressListener, progressRequestListener);
apiClient.executeAsync(call, callback);
return call;
}
/**
* Build call for userGet
* @param username username of user to get (required)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userGetCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/users/{username}"
.replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userGetValidateBeforeCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'username' is set
if (username == null) {
throw new ApiException("Missing the required parameter 'username' when calling userGet(Async)");
}
com.squareup.okhttp.Call call = userGetCall(username, progressListener, progressRequestListener);
return call;
}
/**
* Get a user
*
* @param username username of user to get (required)
* @return User
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public User userGet(String username) throws ApiException {
ApiResponse<User> resp = userGetWithHttpInfo(username);
return resp.getData();
}
/**
* Get a user
*
* @param username username of user to get (required)
* @return ApiResponse<User>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<User> userGetWithHttpInfo(String username) throws ApiException {
com.squareup.okhttp.Call call = userGetValidateBeforeCall(username, null, null);
Type localVarReturnType = new TypeToken<User>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* Get a user (asynchronously)
*
* @param username username of user to get (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userGetAsync(String username, final ApiCallback<User> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userGetValidateBeforeCall(username, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<User>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userGetCurrent
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userGetCurrentCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/user";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userGetCurrentValidateBeforeCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
com.squareup.okhttp.Call call = userGetCurrentCall(progressListener, progressRequestListener);
return call;
}
/**
* Get the authenticated user
*
* @return User
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public User userGetCurrent() throws ApiException {
ApiResponse<User> resp = userGetCurrentWithHttpInfo();
return resp.getData();
}
/**
* Get the authenticated user
*
* @return ApiResponse<User>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<User> userGetCurrentWithHttpInfo() throws ApiException {
com.squareup.okhttp.Call call = userGetCurrentValidateBeforeCall(null, null);
Type localVarReturnType = new TypeToken<User>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* Get the authenticated user (asynchronously)
*
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userGetCurrentAsync(final ApiCallback<User> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userGetCurrentValidateBeforeCall(progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<User>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userGetHeatmapData
* @param username username of user to get (required)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userGetHeatmapDataCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/users/{username}/heatmap"
.replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userGetHeatmapDataValidateBeforeCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'username' is set
if (username == null) {
throw new ApiException("Missing the required parameter 'username' when calling userGetHeatmapData(Async)");
}
com.squareup.okhttp.Call call = userGetHeatmapDataCall(username, progressListener, progressRequestListener);
return call;
}
/**
* Get a user's heatmap
*
* @param username username of user to get (required)
* @return List<UserHeatmapData>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public List<UserHeatmapData> userGetHeatmapData(String username) throws ApiException {
ApiResponse<List<UserHeatmapData>> resp = userGetHeatmapDataWithHttpInfo(username);
return resp.getData();
}
/**
* Get a user's heatmap
*
* @param username username of user to get (required)
* @return ApiResponse<List<UserHeatmapData>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<List<UserHeatmapData>> userGetHeatmapDataWithHttpInfo(String username) throws ApiException {
com.squareup.okhttp.Call call = userGetHeatmapDataValidateBeforeCall(username, null, null);
Type localVarReturnType = new TypeToken<List<UserHeatmapData>>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* Get a user's heatmap (asynchronously)
*
* @param username username of user to get (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userGetHeatmapDataAsync(String username, final ApiCallback<List<UserHeatmapData>> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userGetHeatmapDataValidateBeforeCall(username, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<List<UserHeatmapData>>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userGetOAuth2Application
* @param id Application ID to be found (required)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userGetOAuth2ApplicationCall(Long id, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/user/applications/oauth2/{id}"
.replaceAll("\\{" + "id" + "\\}", apiClient.escapeString(id.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userGetOAuth2ApplicationValidateBeforeCall(Long id, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException("Missing the required parameter 'id' when calling userGetOAuth2Application(Async)");
}
com.squareup.okhttp.Call call = userGetOAuth2ApplicationCall(id, progressListener, progressRequestListener);
return call;
}
/**
* get an OAuth2 Application
*
* @param id Application ID to be found (required)
* @return OAuth2Application
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public OAuth2Application userGetOAuth2Application(Long id) throws ApiException {
ApiResponse<OAuth2Application> resp = userGetOAuth2ApplicationWithHttpInfo(id);
return resp.getData();
}
/**
* get an OAuth2 Application
*
* @param id Application ID to be found (required)
* @return ApiResponse<OAuth2Application>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<OAuth2Application> userGetOAuth2ApplicationWithHttpInfo(Long id) throws ApiException {
com.squareup.okhttp.Call call = userGetOAuth2ApplicationValidateBeforeCall(id, null, null);
Type localVarReturnType = new TypeToken<OAuth2Application>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* get an OAuth2 Application (asynchronously)
*
* @param id Application ID to be found (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userGetOAuth2ApplicationAsync(Long id, final ApiCallback<OAuth2Application> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userGetOAuth2ApplicationValidateBeforeCall(id, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<OAuth2Application>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userGetOauth2Application
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userGetOauth2ApplicationCall(Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/user/applications/oauth2";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
if (page != null)
localVarQueryParams.addAll(apiClient.parameterToPair("page", page));
if (limit != null)
localVarQueryParams.addAll(apiClient.parameterToPair("limit", limit));
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userGetOauth2ApplicationValidateBeforeCall(Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
com.squareup.okhttp.Call call = userGetOauth2ApplicationCall(page, limit, progressListener, progressRequestListener);
return call;
}
/**
* List the authenticated user's oauth2 applications
*
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return List<OAuth2Application>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public List<OAuth2Application> userGetOauth2Application(Integer page, Integer limit) throws ApiException {
ApiResponse<List<OAuth2Application>> resp = userGetOauth2ApplicationWithHttpInfo(page, limit);
return resp.getData();
}
/**
* List the authenticated user's oauth2 applications
*
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return ApiResponse<List<OAuth2Application>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<List<OAuth2Application>> userGetOauth2ApplicationWithHttpInfo(Integer page, Integer limit) throws ApiException {
com.squareup.okhttp.Call call = userGetOauth2ApplicationValidateBeforeCall(page, limit, null, null);
Type localVarReturnType = new TypeToken<List<OAuth2Application>>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* List the authenticated user's oauth2 applications (asynchronously)
*
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userGetOauth2ApplicationAsync(Integer page, Integer limit, final ApiCallback<List<OAuth2Application>> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userGetOauth2ApplicationValidateBeforeCall(page, limit, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<List<OAuth2Application>>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userGetStopWatches
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userGetStopWatchesCall(Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/user/stopwatches";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
if (page != null)
localVarQueryParams.addAll(apiClient.parameterToPair("page", page));
if (limit != null)
localVarQueryParams.addAll(apiClient.parameterToPair("limit", limit));
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userGetStopWatchesValidateBeforeCall(Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
com.squareup.okhttp.Call call = userGetStopWatchesCall(page, limit, progressListener, progressRequestListener);
return call;
}
/**
* Get list of all existing stopwatches
*
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return List<StopWatch>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public List<StopWatch> userGetStopWatches(Integer page, Integer limit) throws ApiException {
ApiResponse<List<StopWatch>> resp = userGetStopWatchesWithHttpInfo(page, limit);
return resp.getData();
}
/**
* Get list of all existing stopwatches
*
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return ApiResponse<List<StopWatch>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<List<StopWatch>> userGetStopWatchesWithHttpInfo(Integer page, Integer limit) throws ApiException {
com.squareup.okhttp.Call call = userGetStopWatchesValidateBeforeCall(page, limit, null, null);
Type localVarReturnType = new TypeToken<List<StopWatch>>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* Get list of all existing stopwatches (asynchronously)
*
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userGetStopWatchesAsync(Integer page, Integer limit, final ApiCallback<List<StopWatch>> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userGetStopWatchesValidateBeforeCall(page, limit, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<List<StopWatch>>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userGetTokens
* @param username username of user (required)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userGetTokensCall(String username, Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/users/{username}/tokens"
.replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
if (page != null)
localVarQueryParams.addAll(apiClient.parameterToPair("page", page));
if (limit != null)
localVarQueryParams.addAll(apiClient.parameterToPair("limit", limit));
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userGetTokensValidateBeforeCall(String username, Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'username' is set
if (username == null) {
throw new ApiException("Missing the required parameter 'username' when calling userGetTokens(Async)");
}
com.squareup.okhttp.Call call = userGetTokensCall(username, page, limit, progressListener, progressRequestListener);
return call;
}
/**
* List the authenticated user's access tokens
*
* @param username username of user (required)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return List<AccessToken>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public List<AccessToken> userGetTokens(String username, Integer page, Integer limit) throws ApiException {
ApiResponse<List<AccessToken>> resp = userGetTokensWithHttpInfo(username, page, limit);
return resp.getData();
}
/**
* List the authenticated user's access tokens
*
* @param username username of user (required)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return ApiResponse<List<AccessToken>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<List<AccessToken>> userGetTokensWithHttpInfo(String username, Integer page, Integer limit) throws ApiException {
com.squareup.okhttp.Call call = userGetTokensValidateBeforeCall(username, page, limit, null, null);
Type localVarReturnType = new TypeToken<List<AccessToken>>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* List the authenticated user's access tokens (asynchronously)
*
* @param username username of user (required)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userGetTokensAsync(String username, Integer page, Integer limit, final ApiCallback<List<AccessToken>> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userGetTokensValidateBeforeCall(username, page, limit, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<List<AccessToken>>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userListEmails
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userListEmailsCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/user/emails";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userListEmailsValidateBeforeCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
com.squareup.okhttp.Call call = userListEmailsCall(progressListener, progressRequestListener);
return call;
}
/**
* List the authenticated user's email addresses
*
* @return List<Email>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public List<Email> userListEmails() throws ApiException {
ApiResponse<List<Email>> resp = userListEmailsWithHttpInfo();
return resp.getData();
}
/**
* List the authenticated user's email addresses
*
* @return ApiResponse<List<Email>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<List<Email>> userListEmailsWithHttpInfo() throws ApiException {
com.squareup.okhttp.Call call = userListEmailsValidateBeforeCall(null, null);
Type localVarReturnType = new TypeToken<List<Email>>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* List the authenticated user's email addresses (asynchronously)
*
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userListEmailsAsync(final ApiCallback<List<Email>> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userListEmailsValidateBeforeCall(progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<List<Email>>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userListFollowers
* @param username username of user (required)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userListFollowersCall(String username, Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/users/{username}/followers"
.replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
if (page != null)
localVarQueryParams.addAll(apiClient.parameterToPair("page", page));
if (limit != null)
localVarQueryParams.addAll(apiClient.parameterToPair("limit", limit));
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userListFollowersValidateBeforeCall(String username, Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'username' is set
if (username == null) {
throw new ApiException("Missing the required parameter 'username' when calling userListFollowers(Async)");
}
com.squareup.okhttp.Call call = userListFollowersCall(username, page, limit, progressListener, progressRequestListener);
return call;
}
/**
* List the given user's followers
*
* @param username username of user (required)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return List<User>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public List<User> userListFollowers(String username, Integer page, Integer limit) throws ApiException {
ApiResponse<List<User>> resp = userListFollowersWithHttpInfo(username, page, limit);
return resp.getData();
}
/**
* List the given user's followers
*
* @param username username of user (required)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return ApiResponse<List<User>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<List<User>> userListFollowersWithHttpInfo(String username, Integer page, Integer limit) throws ApiException {
com.squareup.okhttp.Call call = userListFollowersValidateBeforeCall(username, page, limit, null, null);
Type localVarReturnType = new TypeToken<List<User>>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* List the given user's followers (asynchronously)
*
* @param username username of user (required)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userListFollowersAsync(String username, Integer page, Integer limit, final ApiCallback<List<User>> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userListFollowersValidateBeforeCall(username, page, limit, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<List<User>>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userListFollowing
* @param username username of user (required)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userListFollowingCall(String username, Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/users/{username}/following"
.replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
if (page != null)
localVarQueryParams.addAll(apiClient.parameterToPair("page", page));
if (limit != null)
localVarQueryParams.addAll(apiClient.parameterToPair("limit", limit));
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userListFollowingValidateBeforeCall(String username, Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'username' is set
if (username == null) {
throw new ApiException("Missing the required parameter 'username' when calling userListFollowing(Async)");
}
com.squareup.okhttp.Call call = userListFollowingCall(username, page, limit, progressListener, progressRequestListener);
return call;
}
/**
* List the users that the given user is following
*
* @param username username of user (required)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return List<User>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public List<User> userListFollowing(String username, Integer page, Integer limit) throws ApiException {
ApiResponse<List<User>> resp = userListFollowingWithHttpInfo(username, page, limit);
return resp.getData();
}
/**
* List the users that the given user is following
*
* @param username username of user (required)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return ApiResponse<List<User>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<List<User>> userListFollowingWithHttpInfo(String username, Integer page, Integer limit) throws ApiException {
com.squareup.okhttp.Call call = userListFollowingValidateBeforeCall(username, page, limit, null, null);
Type localVarReturnType = new TypeToken<List<User>>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* List the users that the given user is following (asynchronously)
*
* @param username username of user (required)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userListFollowingAsync(String username, Integer page, Integer limit, final ApiCallback<List<User>> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userListFollowingValidateBeforeCall(username, page, limit, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<List<User>>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userListGPGKeys
* @param username username of user (required)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userListGPGKeysCall(String username, Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/users/{username}/gpg_keys"
.replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
if (page != null)
localVarQueryParams.addAll(apiClient.parameterToPair("page", page));
if (limit != null)
localVarQueryParams.addAll(apiClient.parameterToPair("limit", limit));
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userListGPGKeysValidateBeforeCall(String username, Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'username' is set
if (username == null) {
throw new ApiException("Missing the required parameter 'username' when calling userListGPGKeys(Async)");
}
com.squareup.okhttp.Call call = userListGPGKeysCall(username, page, limit, progressListener, progressRequestListener);
return call;
}
/**
* List the given user's GPG keys
*
* @param username username of user (required)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return List<GPGKey>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public List<GPGKey> userListGPGKeys(String username, Integer page, Integer limit) throws ApiException {
ApiResponse<List<GPGKey>> resp = userListGPGKeysWithHttpInfo(username, page, limit);
return resp.getData();
}
/**
* List the given user's GPG keys
*
* @param username username of user (required)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return ApiResponse<List<GPGKey>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<List<GPGKey>> userListGPGKeysWithHttpInfo(String username, Integer page, Integer limit) throws ApiException {
com.squareup.okhttp.Call call = userListGPGKeysValidateBeforeCall(username, page, limit, null, null);
Type localVarReturnType = new TypeToken<List<GPGKey>>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* List the given user's GPG keys (asynchronously)
*
* @param username username of user (required)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userListGPGKeysAsync(String username, Integer page, Integer limit, final ApiCallback<List<GPGKey>> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userListGPGKeysValidateBeforeCall(username, page, limit, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<List<GPGKey>>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userListKeys
* @param username username of user (required)
* @param fingerprint fingerprint of the key (optional)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userListKeysCall(String username, String fingerprint, Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/users/{username}/keys"
.replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
if (fingerprint != null)
localVarQueryParams.addAll(apiClient.parameterToPair("fingerprint", fingerprint));
if (page != null)
localVarQueryParams.addAll(apiClient.parameterToPair("page", page));
if (limit != null)
localVarQueryParams.addAll(apiClient.parameterToPair("limit", limit));
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userListKeysValidateBeforeCall(String username, String fingerprint, Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'username' is set
if (username == null) {
throw new ApiException("Missing the required parameter 'username' when calling userListKeys(Async)");
}
com.squareup.okhttp.Call call = userListKeysCall(username, fingerprint, page, limit, progressListener, progressRequestListener);
return call;
}
/**
* List the given user's public keys
*
* @param username username of user (required)
* @param fingerprint fingerprint of the key (optional)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return List<PublicKey>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public List<PublicKey> userListKeys(String username, String fingerprint, Integer page, Integer limit) throws ApiException {
ApiResponse<List<PublicKey>> resp = userListKeysWithHttpInfo(username, fingerprint, page, limit);
return resp.getData();
}
/**
* List the given user's public keys
*
* @param username username of user (required)
* @param fingerprint fingerprint of the key (optional)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return ApiResponse<List<PublicKey>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<List<PublicKey>> userListKeysWithHttpInfo(String username, String fingerprint, Integer page, Integer limit) throws ApiException {
com.squareup.okhttp.Call call = userListKeysValidateBeforeCall(username, fingerprint, page, limit, null, null);
Type localVarReturnType = new TypeToken<List<PublicKey>>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* List the given user's public keys (asynchronously)
*
* @param username username of user (required)
* @param fingerprint fingerprint of the key (optional)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userListKeysAsync(String username, String fingerprint, Integer page, Integer limit, final ApiCallback<List<PublicKey>> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userListKeysValidateBeforeCall(username, fingerprint, page, limit, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<List<PublicKey>>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userListRepos
* @param username username of user (required)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userListReposCall(String username, Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/users/{username}/repos"
.replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
if (page != null)
localVarQueryParams.addAll(apiClient.parameterToPair("page", page));
if (limit != null)
localVarQueryParams.addAll(apiClient.parameterToPair("limit", limit));
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userListReposValidateBeforeCall(String username, Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'username' is set
if (username == null) {
throw new ApiException("Missing the required parameter 'username' when calling userListRepos(Async)");
}
com.squareup.okhttp.Call call = userListReposCall(username, page, limit, progressListener, progressRequestListener);
return call;
}
/**
* List the repos owned by the given user
*
* @param username username of user (required)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return List<Repository>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public List<Repository> userListRepos(String username, Integer page, Integer limit) throws ApiException {
ApiResponse<List<Repository>> resp = userListReposWithHttpInfo(username, page, limit);
return resp.getData();
}
/**
* List the repos owned by the given user
*
* @param username username of user (required)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return ApiResponse<List<Repository>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<List<Repository>> userListReposWithHttpInfo(String username, Integer page, Integer limit) throws ApiException {
com.squareup.okhttp.Call call = userListReposValidateBeforeCall(username, page, limit, null, null);
Type localVarReturnType = new TypeToken<List<Repository>>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* List the repos owned by the given user (asynchronously)
*
* @param username username of user (required)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userListReposAsync(String username, Integer page, Integer limit, final ApiCallback<List<Repository>> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userListReposValidateBeforeCall(username, page, limit, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<List<Repository>>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userListStarred
* @param username username of user (required)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userListStarredCall(String username, Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/users/{username}/starred"
.replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
if (page != null)
localVarQueryParams.addAll(apiClient.parameterToPair("page", page));
if (limit != null)
localVarQueryParams.addAll(apiClient.parameterToPair("limit", limit));
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userListStarredValidateBeforeCall(String username, Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'username' is set
if (username == null) {
throw new ApiException("Missing the required parameter 'username' when calling userListStarred(Async)");
}
com.squareup.okhttp.Call call = userListStarredCall(username, page, limit, progressListener, progressRequestListener);
return call;
}
/**
* The repos that the given user has starred
*
* @param username username of user (required)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return List<Repository>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public List<Repository> userListStarred(String username, Integer page, Integer limit) throws ApiException {
ApiResponse<List<Repository>> resp = userListStarredWithHttpInfo(username, page, limit);
return resp.getData();
}
/**
* The repos that the given user has starred
*
* @param username username of user (required)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return ApiResponse<List<Repository>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<List<Repository>> userListStarredWithHttpInfo(String username, Integer page, Integer limit) throws ApiException {
com.squareup.okhttp.Call call = userListStarredValidateBeforeCall(username, page, limit, null, null);
Type localVarReturnType = new TypeToken<List<Repository>>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* The repos that the given user has starred (asynchronously)
*
* @param username username of user (required)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userListStarredAsync(String username, Integer page, Integer limit, final ApiCallback<List<Repository>> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userListStarredValidateBeforeCall(username, page, limit, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<List<Repository>>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userListSubscriptions
* @param username username of the user (required)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userListSubscriptionsCall(String username, Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/users/{username}/subscriptions"
.replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
if (page != null)
localVarQueryParams.addAll(apiClient.parameterToPair("page", page));
if (limit != null)
localVarQueryParams.addAll(apiClient.parameterToPair("limit", limit));
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userListSubscriptionsValidateBeforeCall(String username, Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'username' is set
if (username == null) {
throw new ApiException("Missing the required parameter 'username' when calling userListSubscriptions(Async)");
}
com.squareup.okhttp.Call call = userListSubscriptionsCall(username, page, limit, progressListener, progressRequestListener);
return call;
}
/**
* List the repositories watched by a user
*
* @param username username of the user (required)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return List<Repository>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public List<Repository> userListSubscriptions(String username, Integer page, Integer limit) throws ApiException {
ApiResponse<List<Repository>> resp = userListSubscriptionsWithHttpInfo(username, page, limit);
return resp.getData();
}
/**
* List the repositories watched by a user
*
* @param username username of the user (required)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return ApiResponse<List<Repository>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<List<Repository>> userListSubscriptionsWithHttpInfo(String username, Integer page, Integer limit) throws ApiException {
com.squareup.okhttp.Call call = userListSubscriptionsValidateBeforeCall(username, page, limit, null, null);
Type localVarReturnType = new TypeToken<List<Repository>>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* List the repositories watched by a user (asynchronously)
*
* @param username username of the user (required)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userListSubscriptionsAsync(String username, Integer page, Integer limit, final ApiCallback<List<Repository>> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userListSubscriptionsValidateBeforeCall(username, page, limit, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<List<Repository>>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userListTeams
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userListTeamsCall(Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/user/teams";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
if (page != null)
localVarQueryParams.addAll(apiClient.parameterToPair("page", page));
if (limit != null)
localVarQueryParams.addAll(apiClient.parameterToPair("limit", limit));
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userListTeamsValidateBeforeCall(Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
com.squareup.okhttp.Call call = userListTeamsCall(page, limit, progressListener, progressRequestListener);
return call;
}
/**
* List all the teams a user belongs to
*
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return List<Team>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public List<Team> userListTeams(Integer page, Integer limit) throws ApiException {
ApiResponse<List<Team>> resp = userListTeamsWithHttpInfo(page, limit);
return resp.getData();
}
/**
* List all the teams a user belongs to
*
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return ApiResponse<List<Team>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<List<Team>> userListTeamsWithHttpInfo(Integer page, Integer limit) throws ApiException {
com.squareup.okhttp.Call call = userListTeamsValidateBeforeCall(page, limit, null, null);
Type localVarReturnType = new TypeToken<List<Team>>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* List all the teams a user belongs to (asynchronously)
*
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userListTeamsAsync(Integer page, Integer limit, final ApiCallback<List<Team>> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userListTeamsValidateBeforeCall(page, limit, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<List<Team>>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userSearch
* @param q keyword (optional)
* @param uid ID of the user to search for (optional)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userSearchCall(String q, Long uid, Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/users/search";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
if (q != null)
localVarQueryParams.addAll(apiClient.parameterToPair("q", q));
if (uid != null)
localVarQueryParams.addAll(apiClient.parameterToPair("uid", uid));
if (page != null)
localVarQueryParams.addAll(apiClient.parameterToPair("page", page));
if (limit != null)
localVarQueryParams.addAll(apiClient.parameterToPair("limit", limit));
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userSearchValidateBeforeCall(String q, Long uid, Integer page, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
com.squareup.okhttp.Call call = userSearchCall(q, uid, page, limit, progressListener, progressRequestListener);
return call;
}
/**
* Search for users
*
* @param q keyword (optional)
* @param uid ID of the user to search for (optional)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return InlineResponse2001
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public InlineResponse2001 userSearch(String q, Long uid, Integer page, Integer limit) throws ApiException {
ApiResponse<InlineResponse2001> resp = userSearchWithHttpInfo(q, uid, page, limit);
return resp.getData();
}
/**
* Search for users
*
* @param q keyword (optional)
* @param uid ID of the user to search for (optional)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @return ApiResponse<InlineResponse2001>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<InlineResponse2001> userSearchWithHttpInfo(String q, Long uid, Integer page, Integer limit) throws ApiException {
com.squareup.okhttp.Call call = userSearchValidateBeforeCall(q, uid, page, limit, null, null);
Type localVarReturnType = new TypeToken<InlineResponse2001>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* Search for users (asynchronously)
*
* @param q keyword (optional)
* @param uid ID of the user to search for (optional)
* @param page page number of results to return (1-based) (optional)
* @param limit page size of results (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userSearchAsync(String q, Long uid, Integer page, Integer limit, final ApiCallback<InlineResponse2001> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userSearchValidateBeforeCall(q, uid, page, limit, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<InlineResponse2001>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for userUpdateOAuth2Application
* @param id application to be updated (required)
* @param body (required)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call userUpdateOAuth2ApplicationCall(Long id, CreateOAuth2ApplicationOptions body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = body;
// create path and map variables
String localVarPath = "/user/applications/oauth2/{id}"
.replaceAll("\\{" + "id" + "\\}", apiClient.escapeString(id.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json", "text/plain"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "AccessToken", "AuthorizationHeaderToken", "BasicAuth", "SudoHeader", "SudoParam", "TOTPHeader", "Token" };
return apiClient.buildCall(localVarPath, "PATCH", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call userUpdateOAuth2ApplicationValidateBeforeCall(Long id, CreateOAuth2ApplicationOptions body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException("Missing the required parameter 'id' when calling userUpdateOAuth2Application(Async)");
}
// verify the required parameter 'body' is set
if (body == null) {
throw new ApiException("Missing the required parameter 'body' when calling userUpdateOAuth2Application(Async)");
}
com.squareup.okhttp.Call call = userUpdateOAuth2ApplicationCall(id, body, progressListener, progressRequestListener);
return call;
}
/**
* update an OAuth2 Application, this includes regenerating the client secret
*
* @param id application to be updated (required)
* @param body (required)
* @return OAuth2Application
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public OAuth2Application userUpdateOAuth2Application(Long id, CreateOAuth2ApplicationOptions body) throws ApiException {
ApiResponse<OAuth2Application> resp = userUpdateOAuth2ApplicationWithHttpInfo(id, body);
return resp.getData();
}
/**
* update an OAuth2 Application, this includes regenerating the client secret
*
* @param id application to be updated (required)
* @param body (required)
* @return ApiResponse<OAuth2Application>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<OAuth2Application> userUpdateOAuth2ApplicationWithHttpInfo(Long id, CreateOAuth2ApplicationOptions body) throws ApiException {
com.squareup.okhttp.Call call = userUpdateOAuth2ApplicationValidateBeforeCall(id, body, null, null);
Type localVarReturnType = new TypeToken<OAuth2Application>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* update an OAuth2 Application, this includes regenerating the client secret (asynchronously)
*
* @param id application to be updated (required)
* @param body (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call userUpdateOAuth2ApplicationAsync(Long id, CreateOAuth2ApplicationOptions body, final ApiCallback<OAuth2Application> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = userUpdateOAuth2ApplicationValidateBeforeCall(id, body, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<OAuth2Application>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
}
|
package io.percy.examplepercyjavaselenium;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.HttpServer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import io.percy.selenium.Percy;
/**
* Unit test for example App.
*/
public class AppTest {
private static final String TEST_URL = "http://localhost:8000";
private static ExecutorService serverExecutor;
private static HttpServer server;
private static WebDriver driver;
private static Percy percy;
@BeforeEach
public void startAppAndOpenBrowser() throws IOException {
// Disable browser logs from being logged to stdout
System.setProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE,"/dev/null");
// Create a threadpool with 1 thread and run our server on it.
serverExecutor = Executors.newFixedThreadPool(1);
server = App.startServer(serverExecutor);
FirefoxOptions options = new FirefoxOptions();
options.setHeadless(true);
driver = new FirefoxDriver(options);
percy = new Percy(driver);
}
@AfterEach
public void closeBrowser() {
// Close our test browser.
driver.quit();
// Shutdown our server and make sure the threadpool also terminates.
server.stop(1);
serverExecutor.shutdownNow();
}
@Test
public void loadsHomePage() {
driver.get(TEST_URL);
WebElement element = driver.findElement(By.className("todoapp"));
assertNotNull(element);
// Take a Percy snapshot.
percy.snapshot("Home Page");
}
@Test
public void acceptsANewTodo() {
driver.get(TEST_URL);
// We start with zero todos.
List<WebElement> todoEls = driver.findElements(By.cssSelector(".todo-list li"));
assertEquals(0, todoEls.size());
// Add a todo in the browser.
WebElement newTodoEl = driver.findElement(By.className("new-todo"));
newTodoEl.sendKeys("A new fancy todo!");
newTodoEl.sendKeys(Keys.RETURN);
// Now we should have 1 todo.
todoEls = driver.findElements(By.cssSelector(".todo-list li"));
assertEquals(1, todoEls.size());
// Take a Percy snapshot specifying browser widths.
percy.snapshot("One todo", Arrays.asList(768, 992, 1200));
}
@Test
public void letsYouCheckOffATodo() {
driver.get(TEST_URL);
WebElement newTodoEl = driver.findElement(By.className("new-todo"));
newTodoEl.sendKeys("A new todo to check off");
newTodoEl.sendKeys(Keys.RETURN);
WebElement todoCountEl = driver.findElement(By.className("todo-count"));
assertEquals("1 item left", todoCountEl.getText());
driver.findElement(By.cssSelector("input.toggle")).click();
todoCountEl = driver.findElement(By.className("todo-count"));
assertEquals("0 items left", todoCountEl.getText());
// Take a Percy snapshot specifying a minimum height.
percy.snapshot("Checked off todo", null, 2000);
}
}
|
package de.adorsys.ledgers.oba.rest.api.resource;
import de.adorsys.ledgers.middleware.api.domain.account.AccountDetailsTO;
import de.adorsys.ledgers.middleware.api.domain.um.AisConsentTO;
import de.adorsys.ledgers.oba.rest.api.domain.AuthorizeResponse;
import de.adorsys.ledgers.oba.rest.api.domain.ConsentAuthorizeResponse;
import de.adorsys.ledgers.oba.rest.api.domain.CreatePiisConsentRequestTO;
import de.adorsys.ledgers.oba.rest.api.domain.PIISConsentCreateResponse;
import de.adorsys.ledgers.oba.rest.api.exception.ConsentAuthorizeException;
import io.swagger.annotations.*;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Api(value = AISApi.BASE_PATH, tags = "PSU AIS", description = "Provides access to online banking AIS functionality")
public interface AISApi {
String BASE_PATH = "/ais";
@GetMapping(path = "/auth", params = {"redirectId", "encryptedConsentId"})
@ApiOperation(value = "Entry point for authenticating ais consent requests.")
ResponseEntity<AuthorizeResponse> aisAuth(
@RequestParam(name = "redirectId") String redirectId,
@RequestParam(name = "encryptedConsentId") String encryptedConsentId);
/**
* Identifies the user by login an pin.
* <p>
* The returned object contains:
* <ul>
* <li>A list of accounts
* <p>This is supposed to be used to display the list of accounts to the psu</p>
* </li>
* <li>An AisConsent object
* <p>This consent is initialized, but might not contain any more information</p>
* </li>
* </ul>
*
* @param encryptedConsentId the encryptedConsentId
* @param authorisationId the auth id
* @param login the login
* @param pin the password
* @param consentCookieString the cosent cookie
* @return ConsentAuthorizeResponse
*/
@PostMapping(path = "/{encryptedConsentId}/authorisation/{authorisationId}/login")
@ApiOperation(value = "Identifies the user by login an pin. Return sca methods information")
ResponseEntity<ConsentAuthorizeResponse> login(
@PathVariable("encryptedConsentId") String encryptedConsentId,
@PathVariable("authorisationId") String authorisationId,
@RequestParam("login") String login,
@RequestParam("pin") String pin,
@RequestHeader(name = "Cookie", required = false) String consentCookieString);
/**
* Start the consent process. By sending the customer request consent to the core banking.
*
* @param encryptedConsentId the encrypted consent id
* @param authorisationId the authorization id
* @param consentAndaccessTokenCookieString the consent cookie
* @param aisConsent the consent request object
* @return ConsentAuthorizeResponse
*/
@PostMapping("/{encryptedConsentId}/authorisation/{authorisationId}/start")
@ApiOperation(value = "Starts the cosent authaurization process after user selects which account to grant access to",
authorizations = @Authorization(value = "apiKey"))
ResponseEntity<ConsentAuthorizeResponse> startConsentAuth(
@PathVariable("encryptedConsentId") String encryptedConsentId,
@PathVariable("authorisationId") String authorisationId,
@RequestHeader(name = "Cookie", required = false) String consentAndaccessTokenCookieString,
@RequestBody AisConsentTO aisConsent);
/**
* Selects the SCA Method for use.
*
* @param encryptedConsentId the sca id
* @param authorisationId the auth id
* @param scaMethodId sca
* @param consentAndaccessTokenCookieString the cosent cookie
* @return ConsentAuthorizeResponse
*/
@PostMapping("/{encryptedConsentId}/authorisation/{authorisationId}/methods/{scaMethodId}")
@ApiOperation(value = "Selects the SCA Method for use.", authorizations = @Authorization(value = "apiKey"))
ResponseEntity<ConsentAuthorizeResponse> selectMethod(
@PathVariable("encryptedConsentId") String encryptedConsentId,
@PathVariable("authorisationId") String authorisationId,
@PathVariable("scaMethodId") String scaMethodId,
@RequestHeader(name = "Cookie", required = false) String consentAndaccessTokenCookieString);
/**
* Provides a TAN for the validation of an authorization
*
* @param encryptedConsentId the sca id
* @param authorisationId the auth id
* @param consentAndaccessTokenCookieString the cosent cookie
* @param authCode the auth code
* @return ConsentAuthorizeResponse
*/
@PostMapping(path = "/{encryptedConsentId}/authorisation/{authorisationId}/authCode", params = {"authCode"})
@ApiOperation(value = "Provides a TAN for the validation of an authorization", authorizations = @Authorization(value = "apiKey"))
ResponseEntity<ConsentAuthorizeResponse> authrizedConsent(
@PathVariable("encryptedConsentId") String encryptedConsentId,
@PathVariable("authorisationId") String authorisationId,
@RequestHeader(name = "Cookie", required = false) String consentAndaccessTokenCookieString,
@RequestParam("authCode") String authCode);
@PostMapping(path = "/piis")
@ApiOperation(value = "Grant a piis consent", authorizations = @Authorization(value = "apiKey"))
ResponseEntity<PIISConsentCreateResponse> grantPiisConsent(
@RequestHeader(name = "Cookie", required = false) String consentAndaccessTokenCookieString, @RequestBody CreatePiisConsentRequestTO piisConsentTO);
/**
* Return the list of accounts linked with the current customer.
*
* @return : the list of accounts linked with the current customer.
*/
@GetMapping(path = "/accounts")
@ApiOperation(value = "List fo Accessible Accounts", authorizations = @Authorization(value = "apiKey"),
notes = "Returns the list of all accounts linked to the connected user. "
+ "Call only available to role CUSTOMER.")
@ApiResponses(value = {
@ApiResponse(code = 200, response = AccountDetailsTO[].class, message = "List of accounts accessible to the user.")
})
ResponseEntity<List<AccountDetailsTO>> getListOfAccounts(@RequestHeader(name = "Cookie", required = false) String accessTokenCookieString);
/**
* This call provides the server with the opportunity to close this session and
* redirect the PSU to the TPP or close the application window.
* <p>
* In any case, the session of the user will be closed and cookies will be deleted.
*
* @param encryptedConsentId
* @param authorisationId
* @return
*/
@GetMapping(path = "/{encryptedConsentId}/authorisation/{authorisationId}/done", params = {"forgetConsent", "backToTpp"})
@ApiOperation(value = "Close consent session", authorizations = @Authorization(value = "apiKey"),
notes = "This call provides the server with the opportunity to close this session and "
+ "redirect the PSU to the TPP or close the application window.")
ResponseEntity<ConsentAuthorizeResponse> aisDone(
@PathVariable("encryptedConsentId") String encryptedConsentId,
@PathVariable("authorisationId") String authorisationId,
@RequestHeader(name = "Cookie", required = false) String consentAndaccessTokenCookieString,
@RequestParam(name = "forgetConsent", required = false) Boolean forgetConsent,
@RequestParam(name = "backToTpp", required = false) Boolean backToTpp) throws ConsentAuthorizeException;
/**
* Fails AIS Consent authorisation object by its ID.
*
* @param encryptedConsentId ID of Consent
* @return <code>true</code> if consent authorisation was found and failed. <code>false</code> otherwise.
*/
@DeleteMapping(path = "/{encryptedConsentId}/{authorisationId}")
@ApiOperation(value = "Revoke consent", authorizations = @Authorization(value = "apiKey"),
notes = "This call provides the server with the opportunity to close this session and "
+ "revoke consent.")
ResponseEntity<ConsentAuthorizeResponse> revokeConsent(@PathVariable("encryptedConsentId") String encryptedConsentId,
@PathVariable("authorisationId") String authorisationId,
@RequestHeader(name = "Cookie", required = false) String cookieString);
}
|
package com.netto.core.context;
public class ServerAddress {
private String ip;
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
private int port;
private int weight;
}
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.undertow.util;
import io.undertow.UndertowMessages;
import org.xnio.Pooled;
import java.nio.ByteBuffer;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
/**
* A reference counted pooled implementation, that basically consists of a main buffer, that can be sliced off into smaller buffers,
* and the underlying buffer will not be freed until all the slices and the main buffer itself have also been freed.
*
* This also supports the notion of un-freeing the main buffer. Basically this allows the buffer be re-used, so if only a small slice of the
* buffer was used for read operations the main buffer can potentially be re-used. This prevents buffer exhaustion attacks where content
* is sent in many small packets, and you end up allocating a large number of buffers to hold a small amount of data.
*
* @author Stuart Douglas
*/
public class ReferenceCountedPooled implements Pooled<ByteBuffer> {
private final Pooled<ByteBuffer> underlying;
@SuppressWarnings("unused")
private volatile int referenceCount;
private volatile boolean discard = false;
boolean mainFreed = false;
private ByteBuffer slice = null;
private static final AtomicIntegerFieldUpdater<ReferenceCountedPooled> referenceCountUpdater = AtomicIntegerFieldUpdater.newUpdater(ReferenceCountedPooled.class, "referenceCount");
public ReferenceCountedPooled(Pooled<ByteBuffer> underlying, int referenceCount) {
this.underlying = underlying;
this.referenceCount = referenceCount;
}
@Override
public void discard() {
this.discard = true;
if(referenceCountUpdater.decrementAndGet(this) == 0) {
underlying.free(); //we never discard, as discard is basically a big memory leak
}
}
@Override
public void free() {
if(mainFreed) {
return;
}
mainFreed = true;
freeInternal();
}
public boolean isFreed() {
return mainFreed;
}
public boolean tryUnfree() {
int refs;
do {
refs = referenceCountUpdater.get(this);
if(refs <= 0) {
return false;
}
} while (!referenceCountUpdater.compareAndSet(this, refs, refs + 1));
ByteBuffer resource = slice != null ? slice : underlying.getResource();
resource.position(resource.limit());
resource.limit(resource.capacity());
slice = resource.slice();
mainFreed = false;
return true;
}
private void freeInternal() {
if(referenceCountUpdater.decrementAndGet(this) == 0) {
underlying.free();
}
}
@Override
public ByteBuffer getResource() throws IllegalStateException {
if(mainFreed) {
throw UndertowMessages.MESSAGES.bufferAlreadyFreed();
}
if(slice != null) {
return slice;
}
return underlying.getResource();
}
@Override
public void close() {
free();
}
public Pooled<ByteBuffer> createView(final ByteBuffer newValue) {
increaseReferenceCount();
return new Pooled<ByteBuffer>() {
boolean free = false;
@Override
public void discard() {
if(!free) {
free = true;
ReferenceCountedPooled.this.freeInternal();
}
}
@Override
public void free() {
//make sure that a given view can only be freed once
if(!free) {
free = true;
ReferenceCountedPooled.this.freeInternal();
}
}
@Override
public ByteBuffer getResource() throws IllegalStateException {
if(free) {
throw UndertowMessages.MESSAGES.bufferAlreadyFreed();
}
return newValue;
}
@Override
public void close() {
free();
}
};
}
public void increaseReferenceCount() {
int val;
do {
val = referenceCountUpdater.get(this);
if(val == 0) {
//should never happen, as this should only be called from
//code that already has a reference
throw UndertowMessages.MESSAGES.objectWasFreed();
}
} while (!referenceCountUpdater.compareAndSet(this, val, val + 1));
}
}
|
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
// O(n^2) Solution
class Solution {
public boolean isSubtree(TreeNode s, TreeNode t) {
if (s == null && t == null) return true;
if (s == null && t != null || s != null && t == null) return false;
if (isSame(s, t)) return true;
return isSubtree(s.left, t) || isSubtree(s.right, t);
}
private boolean isSame(TreeNode s, TreeNode t) {
if (s == null && t == null) return true;
if (s == null && t != null || s != null && t == null) return false;
return s.val == t.val && isSame(s.left, t.left) && isSame(s.right, t.right);
}
}
// O(n) Solution
class Solution {
public boolean isSubtree(TreeNode s, TreeNode t) {
StringBuilder sb1 = new StringBuilder(200);
serialize(s, sb1);
StringBuilder sb2 = new StringBuilder(200);
serialize(t, sb2);
return sb1.toString().contains(sb2.toString());
}
private void serialize(TreeNode root, StringBuilder sb) {
if (root == null) {
sb.append(",#"); return;
}
sb.append(",").append(root.val);
serialize(root.left, sb);
serialize(root.right, sb);
}
}
|
/*
* Copyright 2018 tweerlei Wruck + Buchmeier GbR - http://www.tweerlei.de/
*
* 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 de.tweerlei.dbgrazer.web.controller.jdbc;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import de.tweerlei.common.util.StringUtils;
import de.tweerlei.common5.jdbc.model.QualifiedName;
import de.tweerlei.dbgrazer.extension.jdbc.MetadataService;
import de.tweerlei.dbgrazer.extension.jdbc.MetadataService.ColumnMode;
import de.tweerlei.dbgrazer.link.service.LinkService;
import de.tweerlei.dbgrazer.query.exception.CancelledByUserException;
import de.tweerlei.dbgrazer.query.exception.PerformQueryException;
import de.tweerlei.dbgrazer.query.model.QueryType;
import de.tweerlei.dbgrazer.query.model.Result;
import de.tweerlei.dbgrazer.query.model.StatementProducer;
import de.tweerlei.dbgrazer.query.service.QueryService;
import de.tweerlei.dbgrazer.web.exception.AccessDeniedException;
import de.tweerlei.dbgrazer.web.model.TaskCompareProgressMonitor;
import de.tweerlei.dbgrazer.web.model.TaskDMLProgressMonitor;
import de.tweerlei.dbgrazer.web.model.TaskProgress;
import de.tweerlei.dbgrazer.web.service.DataFormatterFactory;
import de.tweerlei.dbgrazer.web.service.QueryPerformerService;
import de.tweerlei.dbgrazer.web.service.SchemaTransformerService;
import de.tweerlei.dbgrazer.web.service.ScriptWriterService;
import de.tweerlei.dbgrazer.web.service.TaskProgressService;
import de.tweerlei.dbgrazer.web.service.UserSettingsManager;
import de.tweerlei.dbgrazer.web.service.jdbc.DesignManagerService;
import de.tweerlei.dbgrazer.web.service.jdbc.impl.TableSet;
import de.tweerlei.dbgrazer.web.session.ConnectionSettings;
import de.tweerlei.dbgrazer.web.session.UserSettings;
import de.tweerlei.ermtools.dialect.SQLDialect;
import de.tweerlei.ermtools.dialect.impl.SQLDialectFactory;
import de.tweerlei.ermtools.model.SQLSchema;
/**
* Compare structure of DB objects in the current design
*
* @author Robert Wruck
*/
@Controller
public class DesignDiffController
{
/**
* Helper class used as form backing object
*/
public static final class FormBackingObject
{
private String connection2;
private String mode;
/**
* Constructor
*/
public FormBackingObject()
{
}
/**
* Get the connection2
* @return the connection2
*/
public String getConnection2()
{
return connection2;
}
/**
* Set the connection2
* @param connection2 the connection2 to set
*/
public void setConnection2(String connection2)
{
this.connection2 = connection2;
}
/**
* Get the mode
* @return the mode
*/
public String getMode()
{
return mode;
}
/**
* Set the mode
* @param mode the mode to set
*/
public void setMode(String mode)
{
this.mode = mode;
}
}
private final MetadataService metadataService;
private final LinkService linkService;
private final QueryService queryService;
private final QueryPerformerService runner;
private final SchemaTransformerService schemaTransformer;
private final ScriptWriterService resultBuilder;
private final DataFormatterFactory dataFormatterFactory;
private final UserSettingsManager userSettingsManager;
private final TaskProgressService taskProgressService;
private final DesignManagerService designManagerService;
private final UserSettings userSettings;
private final ConnectionSettings connectionSettings;
private final Logger logger;
/**
* Constructor
* @param metadataService MetadataService
* @param linkService LinkService
* @param queryService QueryService
* @param runner QueryPerformerService
* @param userSettingsManager UserSettingsManager
* @param schemaTransformer SchemaTransformerService
* @param resultBuilder ScriptWriterService
* @param dataFormatterFactory DataFormatterFactory
* @param taskProgressService TaskProgressService
* @param designManagerService DesignManagerService
* @param userSettings UserSettings
* @param connectionSettings ConnectionSettings
*/
@Autowired
public DesignDiffController(MetadataService metadataService, LinkService linkService,
QueryService queryService, QueryPerformerService runner, SchemaTransformerService schemaTransformer,
UserSettingsManager userSettingsManager, ScriptWriterService resultBuilder,
DataFormatterFactory dataFormatterFactory, TaskProgressService taskProgressService,
DesignManagerService designManagerService,
UserSettings userSettings, ConnectionSettings connectionSettings)
{
this.metadataService = metadataService;
this.linkService = linkService;
this.queryService = queryService;
this.runner = runner;
this.schemaTransformer = schemaTransformer;
this.resultBuilder = resultBuilder;
this.dataFormatterFactory = dataFormatterFactory;
this.userSettingsManager = userSettingsManager;
this.taskProgressService = taskProgressService;
this.designManagerService = designManagerService;
this.userSettings = userSettings;
this.connectionSettings = connectionSettings;
this.logger = Logger.getLogger(getClass().getCanonicalName());
}
/**
* Get the FormBackingObject
* @return FormBackingObject
*/
@ModelAttribute("model")
public FormBackingObject getFormBackingObject()
{
final FormBackingObject ret = new FormBackingObject();
return (ret);
}
/**
* Show the schema selection dialog
* @param fbo FormBackingObject
* @return Model
*/
@RequestMapping(value = "/db/*/dbdesigner-compare.html", method = RequestMethod.GET)
public Map<String, Object> showDesignDialog(
@ModelAttribute("model") FormBackingObject fbo
)
{
if (!connectionSettings.isDesignerEnabled())
throw new AccessDeniedException();
final Map<String, Object> model = new HashMap<String, Object>();
if (fbo.getConnection2() != null)
{
connectionSettings.getParameterHistory().put("connection2", fbo.getConnection2());
}
else
{
fbo.setConnection2(connectionSettings.getParameterHistory().get("connection2"));
}
fbo.setMode(connectionSettings.getParameterHistory().get("mode"));
final Map<String, String> all = linkService.findAllLinkNames(userSettingsManager.getEffectiveUserGroups(userSettings.getPrincipal()), null, null);
model.put("allConnections", all);
final Set<QueryType> resultTypes = queryService.findScriptQueryTypes(connectionSettings.getType());
model.put("resultTypes", resultTypes);
model.put("extensionJS", JdbcMessageKeys.EXTENSION_JS);
return (model);
}
/**
* Show catalogs
* @param fbo FormBackingObject
* @return Model
*/
@RequestMapping(value = "/db/*/ajax/design-compare.html", method = RequestMethod.POST)
public Map<String, Object> compareDesigns(
@ModelAttribute("model") FormBackingObject fbo
)
{
if (!connectionSettings.isDesignerEnabled())
throw new AccessDeniedException();
final Map<String, Object> model = new HashMap<String, Object>();
final TaskDMLProgressMonitor pr = taskProgressService.createDMLProgressMonitor();
if (pr == null)
{
model.put("alreadyRunning", Boolean.TRUE);
model.put("progress", taskProgressService.getProgress());
return (model);
}
final TableSet design = designManagerService.getCurrentDesign();
model.put("currentDesign", design);
final TaskCompareProgressMonitor c = taskProgressService.createCompareProgressMonitor();
try {
final Set<QualifiedName> missing = new HashSet<QualifiedName>();
final SQLSchema left = readSchema(connectionSettings.getLinkName(), design.getTableNames(), missing, c.getSourceRows());
final SQLSchema right = readSchema(fbo.getConnection2(), design.getTableNames(), missing, c.getDestinationRows());
final boolean crossDialect = !StringUtils.equals(connectionSettings.getDialectName(),
linkService.getLink(fbo.getConnection2(), null).getDialectName());
final SQLDialect dialect = getSQLDialect();
final StatementProducer p = schemaTransformer.compareSchemas(left, right, false, dialect, crossDialect);
if (!StringUtils.empty(fbo.getMode()) && connectionSettings.isWritable())
{
try {
final Result r = runner.performCustomQueries(connectionSettings.getLinkName(), p, fbo.getMode(), pr);
model.put("result", r.getFirstRowSet().getFirstValue());
}
catch (PerformQueryException e)
{
model.put("exception", e.getCause());
}
catch (CancelledByUserException e)
{
model.put("cancelled", Boolean.TRUE);
}
catch (RuntimeException e)
{
logger.log(Level.WARNING, "runCompareIDs", e);
model.put("exception", e);
}
}
else
{
final String header = getHeader(connectionSettings.getLinkName(), fbo.getConnection2());
model.put("result", resultBuilder.writeScript(p, header, dialect.getScriptStatementWrapper()));
}
connectionSettings.getParameterHistory().put("connection2", fbo.getConnection2());
connectionSettings.getParameterHistory().put("mode", fbo.getMode());
}
finally
{
taskProgressService.removeCompareProgressMonitor();
taskProgressService.removeDMLProgressMonitor();
}
return (model);
}
private SQLSchema readSchema(String conn, Set<QualifiedName> tables, Set<QualifiedName> missing, TaskProgress p)
{
p.setTodo(tables.size());
return (new SQLSchema(null, null, metadataService.getTableInfos(conn, tables, missing, ColumnMode.ALL, p)));
}
private String getHeader(String c1, String c2)
{
return (dataFormatterFactory.getMessage(JdbcMessageKeys.DDL_COMPARE_HEADER, c1, c2));
}
private SQLDialect getSQLDialect()
{
return (SQLDialectFactory.getSQLDialect(connectionSettings.getDialectName()));
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.master.cleaner;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseTestingUtil;
import org.apache.hadoop.hbase.Stoppable;
import org.apache.hadoop.hbase.master.snapshot.SnapshotManager;
import org.apache.hadoop.hbase.testclassification.MasterTests;
import org.apache.hadoop.hbase.testclassification.SmallTests;
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.hbase.shaded.protobuf.generated.SnapshotProtos;
/**
* Tests for SnapshotsCleanerChore
*/
@Category({ MasterTests.class, SmallTests.class })
public class TestSnapshotCleanerChore {
@ClassRule
public static final HBaseClassTestRule CLASS_RULE =
HBaseClassTestRule.forClass(TestSnapshotCleanerChore.class);
private static final Logger LOG = LoggerFactory.getLogger(TestSnapshotCleanerChore.class);
private static final HBaseTestingUtil HBASE_TESTING_UTILITY = new HBaseTestingUtil();
private SnapshotManager snapshotManager;
private Configuration getSnapshotCleanerConf() {
Configuration conf = HBASE_TESTING_UTILITY.getConfiguration();
conf.setInt("hbase.master.cleaner.snapshot.interval", 100);
return conf;
}
@Test
public void testSnapshotCleanerWithoutAnyCompletedSnapshot() throws IOException {
snapshotManager = Mockito.mock(SnapshotManager.class);
Stoppable stopper = new StoppableImplementation();
Configuration conf = getSnapshotCleanerConf();
SnapshotCleanerChore snapshotCleanerChore =
new SnapshotCleanerChore(stopper, conf, snapshotManager);
try {
snapshotCleanerChore.chore();
} finally {
stopper.stop("Stopping Test Stopper");
}
Mockito.verify(snapshotManager, Mockito.times(0)).deleteSnapshot(Mockito.any());
}
@Test
public void testSnapshotCleanerWithNoTtlExpired() throws IOException {
snapshotManager = Mockito.mock(SnapshotManager.class);
Stoppable stopper = new StoppableImplementation();
Configuration conf = getSnapshotCleanerConf();
SnapshotCleanerChore snapshotCleanerChore =
new SnapshotCleanerChore(stopper, conf, snapshotManager);
List<SnapshotProtos.SnapshotDescription> snapshotDescriptionList = new ArrayList<>();
snapshotDescriptionList.add(getSnapshotDescription(-2, "snapshot01", "table01",
EnvironmentEdgeManager.currentTime() - 100000));
snapshotDescriptionList.add(
getSnapshotDescription(10, "snapshot02", "table02", EnvironmentEdgeManager.currentTime()));
Mockito.when(snapshotManager.getCompletedSnapshots()).thenReturn(snapshotDescriptionList);
try {
LOG.info("2 Snapshots are completed but TTL is not expired for any of them");
snapshotCleanerChore.chore();
} finally {
stopper.stop("Stopping Test Stopper");
}
Mockito.verify(snapshotManager, Mockito.times(0)).deleteSnapshot(Mockito.any());
}
@Test
public void testSnapshotCleanerWithSomeTtlExpired() throws IOException {
snapshotManager = Mockito.mock(SnapshotManager.class);
Stoppable stopper = new StoppableImplementation();
Configuration conf = getSnapshotCleanerConf();
SnapshotCleanerChore snapshotCleanerChore =
new SnapshotCleanerChore(stopper, conf, snapshotManager);
List<SnapshotProtos.SnapshotDescription> snapshotDescriptionList = new ArrayList<>();
snapshotDescriptionList.add(getSnapshotDescription(10, "snapshot01", "table01", 1));
snapshotDescriptionList.add(getSnapshotDescription(5, "snapshot02", "table02", 2));
snapshotDescriptionList.add(
getSnapshotDescription(30, "snapshot01", "table01", EnvironmentEdgeManager.currentTime()));
snapshotDescriptionList.add(
getSnapshotDescription(0, "snapshot02", "table02", EnvironmentEdgeManager.currentTime()));
snapshotDescriptionList.add(
getSnapshotDescription(40, "snapshot03", "table03", EnvironmentEdgeManager.currentTime()));
Mockito.when(snapshotManager.getCompletedSnapshots()).thenReturn(snapshotDescriptionList);
try {
LOG.info("5 Snapshots are completed. TTL is expired for 2 them. Going to delete them");
snapshotCleanerChore.chore();
} finally {
stopper.stop("Stopping Test Stopper");
}
Mockito.verify(snapshotManager, Mockito.times(2)).deleteSnapshot(Mockito.any());
}
@Test
public void testSnapshotCleanerWithReadIOE() throws IOException {
snapshotManager = Mockito.mock(SnapshotManager.class);
Stoppable stopper = new StoppableImplementation();
Configuration conf = new HBaseTestingUtil().getConfiguration();
SnapshotCleanerChore snapshotCleanerChore =
new SnapshotCleanerChore(stopper, conf, snapshotManager);
Mockito.when(snapshotManager.getCompletedSnapshots()).thenThrow(IOException.class);
try {
LOG.info("While getting completed Snapshots, IOException would occur. Hence, No Snapshot"
+ " should be deleted");
snapshotCleanerChore.chore();
} finally {
stopper.stop("Stopping Test Stopper");
}
Mockito.verify(snapshotManager, Mockito.times(0)).deleteSnapshot(Mockito.any());
}
@Test
public void testSnapshotChoreWithTtlOutOfRange() throws IOException {
snapshotManager = Mockito.mock(SnapshotManager.class);
Stoppable stopper = new StoppableImplementation();
Configuration conf = getSnapshotCleanerConf();
List<SnapshotProtos.SnapshotDescription> snapshotDescriptionList = new ArrayList<>();
snapshotDescriptionList.add(getSnapshotDescription(Long.MAX_VALUE, "snapshot01", "table01", 1));
snapshotDescriptionList.add(getSnapshotDescription(5, "snapshot02", "table02", 2));
Mockito.when(snapshotManager.getCompletedSnapshots()).thenReturn(snapshotDescriptionList);
SnapshotCleanerChore snapshotCleanerChore =
new SnapshotCleanerChore(stopper, conf, snapshotManager);
try {
LOG.info("Snapshot Chore is disabled. No cleanup performed for Expired Snapshots");
snapshotCleanerChore.chore();
} finally {
stopper.stop("Stopping Test Stopper");
}
Mockito.verify(snapshotManager, Mockito.times(1)).getCompletedSnapshots();
}
private SnapshotProtos.SnapshotDescription getSnapshotDescription(final long ttl,
final String snapshotName, final String tableName, final long snapshotCreationTime) {
SnapshotProtos.SnapshotDescription.Builder snapshotDescriptionBuilder =
SnapshotProtos.SnapshotDescription.newBuilder();
snapshotDescriptionBuilder.setTtl(ttl);
snapshotDescriptionBuilder.setName(snapshotName);
snapshotDescriptionBuilder.setTable(tableName);
snapshotDescriptionBuilder.setType(SnapshotProtos.SnapshotDescription.Type.FLUSH);
snapshotDescriptionBuilder.setCreationTime(snapshotCreationTime);
return snapshotDescriptionBuilder.build();
}
/**
* Simple helper class that just keeps track of whether or not its stopped.
*/
private static class StoppableImplementation implements Stoppable {
private volatile boolean stop = false;
@Override
public void stop(String why) {
this.stop = true;
}
@Override
public boolean isStopped() {
return this.stop;
}
}
}
|
package caldera.common.init;
import caldera.Caldera;
import caldera.common.brew.generic.component.action.ActionType;
import caldera.common.brew.generic.component.action.actions.*;
import caldera.common.brew.generic.component.action.actions.conversion.ConvertEntitiesActionType;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.RegistryObject;
public class ModActions {
public static final DeferredRegister<ActionType<?>> REGISTRY = DeferredRegister.create(CalderaRegistries.ACTION_TYPES, Caldera.MODID);
public static final RegistryObject<ExplodeActionType> EXPLODE = REGISTRY.register("explode", ExplodeActionType::new);
public static final RegistryObject<DestroyCauldronActionType> DESTROY_CAULDRON = REGISTRY.register("destroy_cauldron", DestroyCauldronActionType::new);
public static final RegistryObject<PlaySoundActionType> PLAY_SOUND = REGISTRY.register("play_sound", PlaySoundActionType::new);
public static final RegistryObject<ChangeColorActionType> CHANGE_COLOR = REGISTRY.register("change_color", ChangeColorActionType::new);
public static final RegistryObject<SpawnParticlesActionType> SPAWN_PARTICLES = REGISTRY.register("spawn_particles", SpawnParticlesActionType::new);
public static final RegistryObject<ConvertEntitiesActionType> CONVERT_ENTITIES = REGISTRY.register("convert_entities", ConvertEntitiesActionType::new);
public static final RegistryObject<SpawnItemsAction> SPAWN_ITEMS = REGISTRY.register("spawn_items", SpawnItemsAction::new);
}
|
package io.crnk.home;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.crnk.core.boot.CrnkBoot;
import io.crnk.core.engine.document.Document;
import io.crnk.core.engine.http.HttpHeaders;
import io.crnk.core.engine.http.HttpRequestContextBase;
import io.crnk.core.engine.http.HttpRequestProcessor;
import io.crnk.core.engine.http.HttpResponse;
import io.crnk.core.engine.http.HttpStatus;
import io.crnk.core.engine.internal.http.HttpRequestContextBaseAdapter;
import io.crnk.core.engine.internal.http.HttpRequestDispatcherImpl;
import io.crnk.core.engine.url.ConstantServiceUrlProvider;
import io.crnk.core.exception.BadRequestException;
import io.crnk.test.mock.ClassTestUtils;
import io.crnk.test.mock.TestModule;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
public class HomeModuleTest {
private CrnkBoot boot;
private HomeModule module;
@Before
public void setup() {
this.module = Mockito.spy(HomeModule.create(HomeFormat.JSON_HOME));
boot = new CrnkBoot();
boot.addModule(module);
boot.addModule(new TestModule());
boot.setServiceUrlProvider(new ConstantServiceUrlProvider("http://localhost"));
boot.boot();
}
@Test
public void checkAccepts() {
HttpRequestContextBase context = Mockito.mock(HttpRequestContextBase.class);
Mockito.when(context.getMethod()).thenReturn("GET");
Mockito.when(context.getRequestHeader(Mockito.eq(HttpHeaders.HTTP_HEADER_ACCEPT))).thenReturn(HttpHeaders.JSON_CONTENT_TYPE);
HttpRequestProcessor requestProcessor = module.getRequestProcessor();
HttpRequestContextBaseAdapter contextAdapter = new HttpRequestContextBaseAdapter(context);
Mockito.when(context.getPath()).thenReturn("/");
Assert.assertTrue(requestProcessor.accepts(contextAdapter));
Mockito.when(context.getPath()).thenReturn("/doesNotExists");
Assert.assertFalse(requestProcessor.accepts(contextAdapter));
Mockito.when(context.getPath()).thenReturn("/tasks");
Assert.assertFalse(requestProcessor.accepts(contextAdapter));
}
@Test
public void checkErrorHandling() {
HttpRequestContextBase context = Mockito.mock(HttpRequestContextBase.class);
Mockito.when(context.getMethod()).thenReturn("GET");
Mockito.when(context.getRequestHeader(Mockito.eq(HttpHeaders.HTTP_HEADER_ACCEPT))).thenReturn(HttpHeaders.JSON_CONTENT_TYPE);
HttpRequestProcessor requestProcessor = module.getRequestProcessor();
HomeModuleExtension extension = new HomeModuleExtension() {
protected List<String> getPaths() {
throw new BadRequestException("test error");
}
};
module.setExtensions(Arrays.asList(extension));
HttpRequestContextBaseAdapter contextAdapter = new HttpRequestContextBaseAdapter(context);
HttpResponse response = requestProcessor.processAsync(contextAdapter).get();
Assert.assertEquals(HttpStatus.BAD_REQUEST_400, response.getStatusCode());
}
@Test
public void checkListingOfChildRepositories() throws IOException {
// e.g. /api/tasks/history/
HttpRequestContextBase context = Mockito.mock(HttpRequestContextBase.class);
Mockito.when(context.getMethod()).thenReturn("GET");
Mockito.when(context.getPath()).thenReturn("/tasks");
Mockito.when(context.getRequestHeader(Mockito.eq(HttpHeaders.HTTP_HEADER_ACCEPT))).thenReturn(HttpHeaders.JSON_CONTENT_TYPE);
HttpRequestContextBaseAdapter contextAdapter = new HttpRequestContextBaseAdapter(context);
HttpRequestDispatcherImpl requestDispatcher = boot.getRequestDispatcher();
HttpResponse response = requestDispatcher.process(contextAdapter).get().get();
ObjectReader reader = boot.getObjectMapper().readerFor(Document.class);
Document document = reader.readValue(response.getBody());
ObjectNode links = document.getLinks();
Assert.assertNotNull(links);
JsonNode history = links.get("history");
Assert.assertNotNull(history);
Assert.assertEquals("http://localhost/tasks/history", history.asText());
}
@Test
public void checkNotAcceptedDueToPathFilter() {
module.addPathFilter(httpRequestContext -> false);
HttpRequestContextBase context = Mockito.mock(HttpRequestContextBase.class);
Mockito.when(context.getMethod()).thenReturn("GET");
Mockito.when(context.getRequestHeader(Mockito.eq(HttpHeaders.HTTP_HEADER_ACCEPT))).thenReturn(HttpHeaders.JSON_CONTENT_TYPE);
Mockito.when(context.getPath()).thenReturn("/");
HttpRequestContextBaseAdapter contextAdapter = new HttpRequestContextBaseAdapter(context);
HttpRequestProcessor requestProcessor = module.getRequestProcessor();
Assert.assertFalse(requestProcessor.accepts(contextAdapter));
}
@Test
public void hasProtectedConstructor() {
ClassTestUtils.assertProtectedConstructor(HomeModule.class);
}
@Test
public void moduleName() {
HomeModule module = boot.getModuleRegistry().getModule(HomeModule.class).get();
Assert.assertEquals("home", module.getModuleName());
}
@Test
public void testNonRootRequestNotTouchedForDifferentUrl() throws IOException {
HttpRequestContextBase requestContextBase = Mockito.mock(HttpRequestContextBase.class);
// create json api request
Mockito.when(requestContextBase.getMethod()).thenReturn("GET");
Mockito.when(requestContextBase.getPath()).thenReturn("/doesNotExists");
Mockito.when(requestContextBase.getRequestHeader("Accept")).thenReturn("*");
// execute
HttpRequestDispatcherImpl requestDispatcher = boot.getRequestDispatcher();
requestDispatcher.process(requestContextBase);
Mockito.verify(requestContextBase, Mockito.times(0)).setResponse(Mockito.any(HttpResponse.class));
}
@Test
public void testNonRootRequestNotTouchedForDifferentContentType() throws IOException {
HttpRequestContextBase requestContextBase = Mockito.mock(HttpRequestContextBase.class);
Mockito.when(requestContextBase.getMethod()).thenReturn("GET");
Mockito.when(requestContextBase.getPath()).thenReturn("/");
Mockito.when(requestContextBase.getRequestHeader("Accept")).thenReturn("application/doesNotExists");
HttpRequestDispatcherImpl requestDispatcher = boot.getRequestDispatcher();
requestDispatcher.process(requestContextBase);
Mockito.verify(requestContextBase, Mockito.times(0)).setResponse(Mockito.any(HttpResponse.class));
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.arrow.adapter.jdbc.h2;
import static org.apache.arrow.adapter.jdbc.JdbcToArrowTestHelper.assertNullValues;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import org.apache.arrow.adapter.jdbc.AbstractJdbcToArrowTest;
import org.apache.arrow.adapter.jdbc.JdbcToArrow;
import org.apache.arrow.adapter.jdbc.Table;
import org.apache.arrow.memory.RootAllocator;
import org.apache.arrow.vector.BigIntVector;
import org.apache.arrow.vector.BitVector;
import org.apache.arrow.vector.DateMilliVector;
import org.apache.arrow.vector.DecimalVector;
import org.apache.arrow.vector.Float4Vector;
import org.apache.arrow.vector.Float8Vector;
import org.apache.arrow.vector.IntVector;
import org.apache.arrow.vector.SmallIntVector;
import org.apache.arrow.vector.TimeMilliVector;
import org.apache.arrow.vector.TimeStampVector;
import org.apache.arrow.vector.TinyIntVector;
import org.apache.arrow.vector.VarBinaryVector;
import org.apache.arrow.vector.VarCharVector;
import org.apache.arrow.vector.VectorSchemaRoot;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/**
* JUnit Test Class which contains methods to test JDBC to Arrow data conversion functionality with null values for
* H2 database.
*/
@RunWith(Parameterized.class)
public class JdbcToArrowNullTest extends AbstractJdbcToArrowTest {
private static final String NULL = "null";
private static final String SELECTED_NULL_COLUMN = "selected_null_column";
private static final String[] testFiles = {
"h2/test1_all_datatypes_null_h2.yml",
"h2/test1_selected_datatypes_null_h2.yml"
};
/**
* Constructor which populate table object for each test iteration.
*
* @param table Table object
*/
public JdbcToArrowNullTest(Table table) {
this.table = table;
}
/**
* Get the test data as a collection of Table objects for each test iteration.
*
* @return Collection of Table objects
* @throws SQLException on error
* @throws ClassNotFoundException on error
* @throws IOException on error
*/
@Parameters
public static Collection<Object[]> getTestData() throws SQLException, ClassNotFoundException, IOException {
return Arrays.asList(prepareTestData(testFiles, JdbcToArrowNullTest.class));
}
/**
* Test Method to test JdbcToArrow Functionality for various H2 DB based datatypes with null values.
*/
@Test
public void testJdbcToArroValues() throws SQLException, IOException {
testDataSets(JdbcToArrow.sqlToArrow(conn, table.getQuery(), new RootAllocator(Integer.MAX_VALUE),
Calendar.getInstance()));
testDataSets(JdbcToArrow.sqlToArrow(conn, table.getQuery(), new RootAllocator(Integer.MAX_VALUE)));
testDataSets(JdbcToArrow.sqlToArrow(conn.createStatement().executeQuery(table.getQuery()),
new RootAllocator(Integer.MAX_VALUE), Calendar.getInstance()));
testDataSets(JdbcToArrow.sqlToArrow(conn.createStatement().executeQuery(table.getQuery())));
testDataSets(JdbcToArrow.sqlToArrow(conn.createStatement().executeQuery(table.getQuery()),
new RootAllocator(Integer.MAX_VALUE)));
testDataSets(JdbcToArrow.sqlToArrow(conn.createStatement().executeQuery(table.getQuery()), Calendar.getInstance()));
}
/**
* This method calls the assert methods for various DataSets.
*
* @param root VectorSchemaRoot for test
*/
public void testDataSets(VectorSchemaRoot root) {
switch (table.getType()) {
case NULL:
sqlToArrowTestNullValues(table.getVectors(), root, table.getRowCount());
break;
case SELECTED_NULL_COLUMN:
sqlToArrowTestSelectedNullColumnsValues(table.getVectors(), root, table.getRowCount());
break;
default:
// do nothing
break;
}
}
/**
* This method assert tests null values in vectors for all the datatypes.
*
* @param vectors Vectors to test
* @param root VectorSchemaRoot for test
* @param rowCount number of rows
*/
public void sqlToArrowTestNullValues(String[] vectors, VectorSchemaRoot root, int rowCount) {
assertNullValues((IntVector) root.getVector(vectors[0]), rowCount);
assertNullValues((BitVector) root.getVector(vectors[1]), rowCount);
assertNullValues((TinyIntVector) root.getVector(vectors[2]), rowCount);
assertNullValues((SmallIntVector) root.getVector(vectors[3]), rowCount);
assertNullValues((BigIntVector) root.getVector(vectors[4]), rowCount);
assertNullValues((DecimalVector) root.getVector(vectors[5]), rowCount);
assertNullValues((Float8Vector) root.getVector(vectors[6]), rowCount);
assertNullValues((Float4Vector) root.getVector(vectors[7]), rowCount);
assertNullValues((TimeMilliVector) root.getVector(vectors[8]), rowCount);
assertNullValues((DateMilliVector) root.getVector(vectors[9]), rowCount);
assertNullValues((TimeStampVector) root.getVector(vectors[10]), rowCount);
assertNullValues((VarBinaryVector) root.getVector(vectors[11]), rowCount);
assertNullValues((VarCharVector) root.getVector(vectors[12]), rowCount);
assertNullValues((VarBinaryVector) root.getVector(vectors[13]), rowCount);
assertNullValues((VarCharVector) root.getVector(vectors[14]), rowCount);
assertNullValues((VarCharVector) root.getVector(vectors[15]), rowCount);
assertNullValues((BitVector) root.getVector(vectors[16]), rowCount);
}
/**
* This method assert tests null values in vectors for some selected datatypes.
*
* @param vectors Vectors to test
* @param root VectorSchemaRoot for test
* @param rowCount number of rows
*/
public void sqlToArrowTestSelectedNullColumnsValues(String[] vectors, VectorSchemaRoot root, int rowCount) {
assertNullValues((BigIntVector) root.getVector(vectors[0]), rowCount);
assertNullValues((DecimalVector) root.getVector(vectors[1]), rowCount);
assertNullValues((Float8Vector) root.getVector(vectors[2]), rowCount);
assertNullValues((Float4Vector) root.getVector(vectors[3]), rowCount);
assertNullValues((TimeMilliVector) root.getVector(vectors[4]), rowCount);
assertNullValues((DateMilliVector) root.getVector(vectors[5]), rowCount);
assertNullValues((TimeStampVector) root.getVector(vectors[6]), rowCount);
assertNullValues((VarBinaryVector) root.getVector(vectors[7]), rowCount);
assertNullValues((VarCharVector) root.getVector(vectors[8]), rowCount);
assertNullValues((VarBinaryVector) root.getVector(vectors[9]), rowCount);
assertNullValues((VarCharVector) root.getVector(vectors[10]), rowCount);
assertNullValues((VarCharVector) root.getVector(vectors[11]), rowCount);
assertNullValues((BitVector) root.getVector(vectors[12]), rowCount);
}
}
|
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.google.ads.interactivemedia.v3.impl;
import android.util.Log;
import com.google.ads.interactivemedia.v3.a.f;
import java.util.Iterator;
import java.util.List;
// Referenced classes of package com.google.ads.interactivemedia.v3.impl:
// x
class x$a
implements com.google.ads.interactivemedia.v3.a.g$c
{
public void a()
{
// 0 0:return
}
public void a(f f)
{
x.b(a);
// 0 0:aload_0
// 1 1:getfield #14 <Field x a>
// 2 4:invokestatic #22 <Method void x.b(x)>
f = ((f) (String.valueOf(((Object) (f)))));
// 3 7:aload_1
// 4 8:invokestatic #28 <Method String String.valueOf(Object)>
// 5 11:astore_1
StringBuilder stringbuilder = new StringBuilder(String.valueOf(((Object) (f))).length() + 13);
// 6 12:new #30 <Class StringBuilder>
// 7 15:dup
// 8 16:aload_1
// 9 17:invokestatic #28 <Method String String.valueOf(Object)>
// 10 20:invokevirtual #34 <Method int String.length()>
// 11 23:bipush 13
// 12 25:iadd
// 13 26:invokespecial #37 <Method void StringBuilder(int)>
// 14 29:astore_2
stringbuilder.append("Player Error:");
// 15 30:aload_2
// 16 31:ldc1 #39 <String "Player Error:">
// 17 33:invokevirtual #43 <Method StringBuilder StringBuilder.append(String)>
// 18 36:pop
stringbuilder.append(((String) (f)));
// 19 37:aload_2
// 20 38:aload_1
// 21 39:invokevirtual #43 <Method StringBuilder StringBuilder.append(String)>
// 22 42:pop
Log.e("IMA SDK", stringbuilder.toString());
// 23 43:ldc1 #45 <String "IMA SDK">
// 24 45:aload_2
// 25 46:invokevirtual #49 <Method String StringBuilder.toString()>
// 26 49:invokestatic #55 <Method int Log.e(String, String)>
// 27 52:pop
// 28 53:return
}
public void a(boolean flag, int i)
{
if(i == 5)
//* 0 0:iload_2
//* 1 1:iconst_5
//* 2 2:icmpne 44
{
for(Iterator iterator = x.d(a).iterator(); iterator.hasNext(); ((com.google.ads.interactivemedia.v3.api.player.oAdPlayer.VideoAdPlayerCallback)iterator.next()).onEnded());
// 3 5:aload_0
// 4 6:getfield #14 <Field x a>
// 5 9:invokestatic #60 <Method List x.d(x)>
// 6 12:invokeinterface #66 <Method Iterator List.iterator()>
// 7 17:astore_3
// 8 18:aload_3
// 9 19:invokeinterface #72 <Method boolean Iterator.hasNext()>
// 10 24:ifeq 44
// 11 27:aload_3
// 12 28:invokeinterface #76 <Method Object Iterator.next()>
// 13 33:checkcast #78 <Class com.google.ads.interactivemedia.v3.api.player.VideoAdPlayer$VideoAdPlayerCallback>
// 14 36:invokeinterface #81 <Method void com.google.ads.interactivemedia.v3.api.player.VideoAdPlayer$VideoAdPlayerCallback.onEnded()>
}
//* 15 41:goto 18
// 16 44:return
}
final x a;
x$a(x x1)
{
a = x1;
// 0 0:aload_0
// 1 1:aload_1
// 2 2:putfield #14 <Field x a>
super();
// 3 5:aload_0
// 4 6:invokespecial #17 <Method void Object()>
// 5 9:return
}
}
|
package snowGlobe;
// apcs.io
import apcs.Window;
public class SnowGlobe {
public static void main(String[] args) {
// create a new window
Window.size(400, 400);
// Create a list of Ball objects.
Snow[] list = new Snow[10];
for (int i = 0; i < 10; i++) {
list[i] = new Snow(150, 150, 1, 2);
}
while (true) {
// set the background color
Window.out.background("light green");
// draw the outer circle
Window.out.color("blue");
Window.out.circle(200, 300, 100);
// draw a circle inside it to make it only show a rim, and make the
// inside color light blue
Window.out.color("light blue");
Window.out.circle(200, 300, 80);
// cover the bottom so it is only half a circle
Window.out.color("light green");
Window.out.rectangle(200, 360, 250, 80);
// draw the bottom rim of the snow globe
Window.out.color("blue");
Window.out.rectangle(200, 320, 250, 40);
// print out the text on the bottom rim
Window.out.color("white");
Window.out.font("Helvetica", 12);
Window.out.print("Have a great Christmas!", 133, 328);
// Draw and move each ball.
for (Snow snow : list) {
snow.draw();
snow.move();
}
Window.frame();
}
}
}
|
package com.scriptsbundle.opportunities;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
|
package com.planet_ink.coffee_mud.Abilities.Spells;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2004-2015 Bo Zimmerman
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.
*/
@SuppressWarnings("rawtypes")
public class Spell_DisguiseUndead extends Spell
{
@Override public String ID() { return "Spell_DisguiseUndead"; }
private final static String localizedName = CMLib.lang().L("Disguise Undead");
@Override public String name() { return localizedName; }
private final static String localizedStaticDisplay = CMLib.lang().L("(Disguise Undead)");
@Override public String displayText() { return localizedStaticDisplay; }
@Override public int classificationCode(){return Ability.ACODE_SPELL|Ability.DOMAIN_ILLUSION;}
@Override protected int canAffectCode(){return Ability.CAN_MOBS;}
@Override protected int canTargetCode(){return Ability.CAN_MOBS;}
@Override public int abstractQuality(){ return Ability.QUALITY_OK_OTHERS;}
@Override
public void affectCharStats(MOB affected, CharStats affectableStats)
{
super.affectCharStats(affected,affectableStats);
if(affected==null)
return;
affectableStats.setRaceName("Human");
}
@Override
public void affectPhyStats(Physical affected, PhyStats affectableStats)
{
super.affectPhyStats(affected,affectableStats);
if(affected==null)
return;
if(text().length()>0)
affectableStats.setName(text());
else
affectableStats.setName(L("a normal person"));
}
@Override
public boolean okMessage(Environmental myHost, CMMsg msg)
{
if(!super.okMessage(myHost, msg))
return false;
if((msg.source()==affected)&&(msg.sourceMinor()==CMMsg.TYP_AROMA))
return false;
return true;
}
@Override
public void unInvoke()
{
// undo the affects of this spell
if(!(affected instanceof MOB))
return;
final MOB mob=(MOB)affected;
super.unInvoke();
if(canBeUninvoked())
if((mob.location()!=null)&&(!mob.amDead()))
mob.location().show(mob,null,CMMsg.MSG_OK_VISUAL,L("<S-YOUPOSS> disguise fades."));
}
@Override
public int castingQuality(MOB mob, Physical target)
{
if(mob!=null)
{
if(mob.isInCombat())
return Ability.QUALITY_INDIFFERENT;
if(mob.isMonster())
return Ability.QUALITY_INDIFFERENT;
if(target instanceof MOB)
{
if((!((MOB)target).charStats().getMyRace().racialCategory().equalsIgnoreCase("Undead"))
||(((MOB)target).charStats().raceName().equalsIgnoreCase("Human")))
return Ability.QUALITY_INDIFFERENT;
}
}
return super.castingQuality(mob,target);
}
@Override
public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel)
{
final MOB target=this.getTarget(mob,commands,givenTarget);
if(target==null)
return false;
if((!target.charStats().getMyRace().racialCategory().equalsIgnoreCase("Undead"))
||(target.charStats().raceName().equalsIgnoreCase("Human")))
{
mob.tell(L("This spell only works on the undead."));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),L(auto?"<T-NAME> gain(s) a disguise!":"^S<S-NAME> casts a spell for <T-NAMESELF>, causing <T-HIS-HER> appearance to change.^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
Ability A=beneficialAffect(mob,target,asLevel,0);
if(A!=null)
{
String genderName;
String genderFormal;
String genderInformal;
String genderPersonal;
switch(target.charStats().getStat(CharStats.STAT_GENDER))
{
case 'M': genderName="male"; genderFormal="man"; genderInformal="guy"; genderPersonal="joe"; break;
case 'F': genderName="female"; genderFormal="woman"; genderInformal="gal"; genderPersonal="jane"; break;
default: genderName="person"; genderFormal="person"; genderInformal="person"; genderPersonal="joe"; break;
}
String adjective;
switch(CMLib.dice().roll(1, 3, -1))
{
case 0: adjective="normal"; break;
case 1: adjective="regular"; break;
default: adjective="average"; break;
}
String noun;
switch(CMLib.dice().roll(1, 5, -1))
{
case 0: noun=genderName; break;
case 1: noun=genderFormal; break;
case 2: noun=genderInformal; break;
case 3: noun=genderPersonal; break;
default: noun="person"; break;
}
A.setMiscText(L(CMLib.english().startWithAorAn(adjective+" "+noun).toLowerCase()));
}
target.recoverPhyStats();
}
}
else
return beneficialWordsFizzle(mob,target,L("<S-NAME> cast(s) a spell for <T-NAMESELF>, but nothing happens."));
// return whether it worked
return success;
}
}
|
/*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.iotthingsgraph.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* An object that filters a system instance search. Multiple filters function as OR criteria in the search. For example
* a search that includes a GREENGRASS_GROUP_NAME and a STATUS filter searches for system instances in the specified
* Greengrass group that have the specified status.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotthingsgraph-2018-09-06/SystemInstanceFilter"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SystemInstanceFilter implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The name of the search filter field.
* </p>
*/
private String name;
/**
* <p>
* An array of string values for the search filter field. Multiple values function as AND criteria in the search.
* </p>
*/
private java.util.List<String> value;
/**
* <p>
* The name of the search filter field.
* </p>
*
* @param name
* The name of the search filter field.
* @see SystemInstanceFilterName
*/
public void setName(String name) {
this.name = name;
}
/**
* <p>
* The name of the search filter field.
* </p>
*
* @return The name of the search filter field.
* @see SystemInstanceFilterName
*/
public String getName() {
return this.name;
}
/**
* <p>
* The name of the search filter field.
* </p>
*
* @param name
* The name of the search filter field.
* @return Returns a reference to this object so that method calls can be chained together.
* @see SystemInstanceFilterName
*/
public SystemInstanceFilter withName(String name) {
setName(name);
return this;
}
/**
* <p>
* The name of the search filter field.
* </p>
*
* @param name
* The name of the search filter field.
* @return Returns a reference to this object so that method calls can be chained together.
* @see SystemInstanceFilterName
*/
public SystemInstanceFilter withName(SystemInstanceFilterName name) {
this.name = name.toString();
return this;
}
/**
* <p>
* An array of string values for the search filter field. Multiple values function as AND criteria in the search.
* </p>
*
* @return An array of string values for the search filter field. Multiple values function as AND criteria in the
* search.
*/
public java.util.List<String> getValue() {
return value;
}
/**
* <p>
* An array of string values for the search filter field. Multiple values function as AND criteria in the search.
* </p>
*
* @param value
* An array of string values for the search filter field. Multiple values function as AND criteria in the
* search.
*/
public void setValue(java.util.Collection<String> value) {
if (value == null) {
this.value = null;
return;
}
this.value = new java.util.ArrayList<String>(value);
}
/**
* <p>
* An array of string values for the search filter field. Multiple values function as AND criteria in the search.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setValue(java.util.Collection)} or {@link #withValue(java.util.Collection)} if you want to override the
* existing values.
* </p>
*
* @param value
* An array of string values for the search filter field. Multiple values function as AND criteria in the
* search.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SystemInstanceFilter withValue(String... value) {
if (this.value == null) {
setValue(new java.util.ArrayList<String>(value.length));
}
for (String ele : value) {
this.value.add(ele);
}
return this;
}
/**
* <p>
* An array of string values for the search filter field. Multiple values function as AND criteria in the search.
* </p>
*
* @param value
* An array of string values for the search filter field. Multiple values function as AND criteria in the
* search.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SystemInstanceFilter withValue(java.util.Collection<String> value) {
setValue(value);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getName() != null)
sb.append("Name: ").append(getName()).append(",");
if (getValue() != null)
sb.append("Value: ").append(getValue());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof SystemInstanceFilter == false)
return false;
SystemInstanceFilter other = (SystemInstanceFilter) obj;
if (other.getName() == null ^ this.getName() == null)
return false;
if (other.getName() != null && other.getName().equals(this.getName()) == false)
return false;
if (other.getValue() == null ^ this.getValue() == null)
return false;
if (other.getValue() != null && other.getValue().equals(this.getValue()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
hashCode = prime * hashCode + ((getValue() == null) ? 0 : getValue().hashCode());
return hashCode;
}
@Override
public SystemInstanceFilter clone() {
try {
return (SystemInstanceFilter) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.iotthingsgraph.model.transform.SystemInstanceFilterMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
|
/*
* $Header$
* $Revision: 1235 $
* $Date: 2006-11-08 09:02:21 -0800 (Wed, 08 Nov 2006) $
*
* ====================================================================
*
* Copyright 2000-2002 bob mcwhirter & James Strachan.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of the Jaxen Project nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ====================================================================
* This software consists of voluntary contributions made by many
* individuals on behalf of the Jaxen Project and was originally
* created by bob mcwhirter <bob@werken.com> and
* James Strachan <jstrachan@apache.org>. For more information on the
* Jaxen Project, please see <http://www.jaxen.org/>.
*
* $Id: LocationPath.java 1235 2006-11-08 17:02:21Z elharo $
*/
package net.arnx.xmlic.internal.org.jaxen.expr;
import java.util.List;
/**
* Represents an XPath location path such as <code>//foo/bar</code>
* or <code>pre:baz[position()=last()]</code>.
* This is production 1 in the
* <a href="http://www.w3.org/TR/xpath#NT-LocationPath">XPath 1.0 specification</a>:
*
* <pre>[1] LocationPath ::= RelativeLocationPath
* | AbsoluteLocationPath</pre>
*
*/
public interface LocationPath extends Expr
{
/**
* Add the next step to this location path.
*
* @param step
*/
void addStep(Step step);
/**
* Returns the ordered list of steps in this location path.
* This list may be live.
*
* @return the ordered list of steps in this location path
*/
List getSteps();
/**
* Returns true if this is an absolute location path; false if it isn't.
* Absolute location paths all begiune with <code>/</code>
* or <code>//</code>.
*
* @return true if this is an absol;ute location path; false if it isn't
*/
boolean isAbsolute();
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.syncope.core.workflow.activiti.task;
import org.apache.syncope.core.persistence.api.entity.user.User;
import org.apache.syncope.core.workflow.activiti.ActivitiUserWorkflowAdapter;
import org.springframework.stereotype.Component;
@Component
public class Delete extends AbstractActivitiServiceTask {
@Override
protected void doExecute(final String executionId) {
User user = engine.getRuntimeService().
getVariable(executionId, ActivitiUserWorkflowAdapter.USER, User.class);
// Do something with user...
if (user != null) {
user.checkToken("");
}
// remove user variable
engine.getRuntimeService().removeVariable(executionId, ActivitiUserWorkflowAdapter.USER);
}
}
|
/*
* Copyright 2016-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.stream.app.task.launcher.local.sink.configuration;
import org.springframework.cloud.deployer.spi.core.AppDeploymentRequest;
import org.springframework.cloud.deployer.spi.core.RuntimeEnvironmentInfo;
import org.springframework.cloud.deployer.spi.task.LaunchState;
import org.springframework.cloud.deployer.spi.task.TaskLauncher;
import org.springframework.cloud.deployer.spi.task.TaskStatus;
import org.springframework.cloud.deployer.spi.util.RuntimeVersionUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author Glenn Renfro
* @author Ilayaperumal Gopinathan
*/
@Configuration
public class TaskSinkConfiguration {
@Bean
public TaskLauncher taskLauncher() {
return new TestTaskLauncher();
}
public class TestTaskLauncher implements TaskLauncher {
public static final String LAUNCH_ID = "TEST_LAUNCH_ID";
private LaunchState state = LaunchState.unknown;
@Override
public String launch(AppDeploymentRequest request) {
state = LaunchState.complete;
return null;
}
@Override
public void cancel(String id) {
}
@Override
public TaskStatus status(String id) {
String taskLaunchId = LAUNCH_ID;
TaskStatus taskStatus = new TaskStatus(taskLaunchId, state, null);
return taskStatus;
}
@Override
public void cleanup(String s) {
}
@Override
public void destroy(String s) {
}
@Override
public RuntimeEnvironmentInfo environmentInfo() {
return (new RuntimeEnvironmentInfo.Builder())
.spiClass(TaskLauncher.class)
.implementationName(this.getClass().getSimpleName())
.implementationVersion(RuntimeVersionUtils.getVersion(this.getClass())).platformType("Local")
.platformApiVersion(System.getProperty("os.name") + " " + System.getProperty("os.version"))
.platformClientVersion(System.getProperty("os.version"))
.platformHostVersion(System.getProperty("os.version")).build();
}
}
}
|
/*
* MIT License
*
* Copyright (c) 2022 MASES s.r.l.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**************************************************************************************
* <auto-generated>
* This code was generated from a template using JCOReflector
*
* Manual changes to this file may cause unexpected behavior in your application.
* Manual changes to this file will be overwritten if the code is regenerated.
* </auto-generated>
*************************************************************************************/
package system.data.entity.infrastructure;
import org.mases.jcobridge.*;
import org.mases.jcobridge.netreflection.*;
import java.util.ArrayList;
// Import section
import system.data.DataException;
/**
* The base .NET class managing System.Data.Entity.Infrastructure.CommitFailedException, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089.
* <p>
*
* See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.Data.Entity.Infrastructure.CommitFailedException" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.Data.Entity.Infrastructure.CommitFailedException</a>
*/
public class CommitFailedException extends DataException {
/**
* Fully assembly qualified name: EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
*/
public static final String assemblyFullName = "EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
/**
* Assembly name: EntityFramework
*/
public static final String assemblyShortName = "EntityFramework";
/**
* Qualified class name: System.Data.Entity.Infrastructure.CommitFailedException
*/
public static final String className = "System.Data.Entity.Infrastructure.CommitFailedException";
static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName);
/**
* The type managed from JCOBridge. See {@link JCType}
*/
public static JCType classType = createType();
static JCEnum enumInstance = null;
JCObject classInstance = null;
JCNativeException jcNativeException = null;
static JCType createType() {
try {
String classToCreate = className + ", "
+ (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Creating %s", classToCreate);
JCType typeCreated = bridge.GetType(classToCreate);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Created: %s",
(typeCreated != null) ? typeCreated.toString() : "Returned null value");
return typeCreated;
} catch (JCException jce) {
JCOReflector.writeLog(jce);
return null;
}
}
void addReference(String ref) throws Throwable {
try {
bridge.AddReference(ref);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public CommitFailedException() {
super();
}
/**
* Internal constructor. Use with caution
*/
public CommitFailedException(java.lang.Object instance) {
super(instance);
if (instance instanceof JCObject) {
classInstance = (JCObject) instance;
} else if (instance instanceof JCNativeException) {
jcNativeException = (JCNativeException) instance;
classInstance = jcNativeException.getCLRException();
}
}
public CommitFailedException(String message) {
super(message);
}
public CommitFailedException(NetException cause) {
super(cause);
}
public CommitFailedException(String message, NetException cause) {
super(message, cause);
}
public String getJCOAssemblyName() {
return assemblyFullName;
}
public String getJCOClassName() {
return className;
}
public String getJCOObjectName() {
return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
}
public java.lang.Object getJCOInstance() {
return classInstance;
}
public void setJCOInstance(JCObject instance) {
classInstance = instance;
super.setJCOInstance(classInstance);
}
public JCType getJCOType() {
return classType;
}
/**
* Try to cast the {@link IJCOBridgeReflected} instance into {@link CommitFailedException}, a cast assert is made to check if types are compatible.
* @param from {@link IJCOBridgeReflected} instance to be casted
* @return {@link CommitFailedException} instance
* @throws java.lang.Throwable in case of error during cast operation
*/
public static CommitFailedException cast(IJCOBridgeReflected from) throws Throwable {
NetType.AssertCast(classType, from);
return new CommitFailedException(from.getJCOInstance());
}
// Constructors section
// Methods section
// Properties section
}
|
/*
*
* Copyright 2012-2014 Eurocommercial Properties NV
*
*
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.estatio.module.application.dom;
import com.google.common.collect.ImmutableMap;
import org.incode.module.base.dom.with.WithTitleComparable;
import org.incode.module.unittestsupport.dom.with.ComparableByTitleContractTestAbstract_compareTo;
/**
* Automatically tests all domain objects implementing {@link WithTitleComparable}.
*/
public class WithTitleComparableContractForEstatio_compareTo_Test extends
ComparableByTitleContractTestAbstract_compareTo {
public WithTitleComparableContractForEstatio_compareTo_Test() {
super("org.estatio", ImmutableMap.<Class<?>,Class<?>>of());
}
}
|
package com.coffean.sinfonia.ecs;
import com.badlogic.ashley.core.Entity;
import com.badlogic.ashley.core.PooledEngine;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.World;
import com.coffean.sinfonia.Sinfonia;
import com.coffean.sinfonia.b2d.BodyFactory;
import com.coffean.sinfonia.ecs.components.*;
import com.coffean.sinfonia.ecs.systems.*;
import com.coffean.sinfonia.input.InputManager;
import com.coffean.sinfonia.loader.Assets;
import com.coffean.sinfonia.view.GameScreen;
import static com.coffean.sinfonia.utils.Constants.*;
public class ECSEngine extends PooledEngine {
public final RenderingSystem renderingSystem;
private final PlayerMovementSystem playerMovementSystem;
private final BodyFactory bodyFactory;
private final TextureAtlas playerAtlas;
private final TextureAtlas ashAtlas;
public ECSEngine(final World world, final Sinfonia parent, InputManager inputManager, GameScreen gameScreen) {
bodyFactory = BodyFactory.getInstance(world);
final Assets assetManager = parent.getAssetManager();
playerAtlas = assetManager.manager.get("entities/player.atlas");
ashAtlas = assetManager.manager.get("entities/ashley.atlas");
renderingSystem = new RenderingSystem(parent);
playerMovementSystem = new PlayerMovementSystem(inputManager);
this.addSystem(new AnimationSystem());
this.addSystem(renderingSystem);
this.addSystem(new PhysicsSystem(world));
this.addSystem(new PlayerCameraSystem(parent));
if (Sinfonia.DEBUG) {
this.addSystem(new PhysicsDebugSystem(world, parent.getCamera()));
}
this.addSystem(playerMovementSystem);
this.addSystem(new EntityMovementSystem());
this.addSystem(new CollisionSystem());
this.addSystem(new PlayerInteractionSystem(inputManager, gameScreen, this));
}
public PlayerMovementSystem getMovementSystem() {
return playerMovementSystem;
}
public void createPlayer(int posX, int posY, int width, int height, int drawOrder) {
final Entity player = this.createEntity();
// Box2D
final Box2DComponent box2DComponent = this.createComponent(Box2DComponent.class);
box2DComponent.body = bodyFactory.makeBox(posX, posY, width, height, BodyDef.BodyType.DynamicBody, true, BIT_PLAYER, (short) (BIT_ENTITY | BIT_BOUNDARY | BIT_SIGN), false);
box2DComponent.body.setUserData(player);
player.add(box2DComponent);
// Player
final PlayerComponent playerComponent = this.createComponent(PlayerComponent.class);
playerComponent.speed = 5;
player.add(playerComponent);
// Transform
final TransformComponent transformComponent = this.createComponent(TransformComponent.class);
// Z defines draw order (0 is first drawn)
transformComponent.scale.set(1, 1);
transformComponent.position.set(posX, posY, drawOrder);
player.add(transformComponent);
// Type
final TypeComponent typeComponent = this.createComponent(TypeComponent.class);
typeComponent.type = TypeComponent.PLAYER;
player.add(typeComponent);
// Texture
final TextureComponent textureComponent = this.createComponent(TextureComponent.class);
textureComponent.region = playerAtlas.findRegion("player");
player.add(textureComponent);
// State
final StateComponent stateComponent = this.createComponent(StateComponent.class);
// Starting state
stateComponent.state = StateComponent.STATE_UP;
player.add(stateComponent);
// Collision
final CollisionComponent collisionComponent = this.createComponent(CollisionComponent.class);
player.add(collisionComponent);
// Interaction
final InteractionComponent interactionComponent = this.createComponent(InteractionComponent.class);
player.add(interactionComponent);
// Add player to engine
this.addEntity(player);
}
public void createAshley(int posX, int posY, int width, int height, int drawOrder) {
final Entity entity = this.createEntity();
// Box2D
final Box2DComponent box2DComponent = this.createComponent(Box2DComponent.class);
box2DComponent.body = bodyFactory.makeBox(posX, posY, width, height, BodyDef.BodyType.DynamicBody, true, BIT_ENTITY, (short) (BIT_PLAYER | BIT_BOUNDARY), false);
//ToDo Do this a different way :I
box2DComponent.sensorBody = bodyFactory.makeBox(posX / 2f, posY / 2f, width * 2, height * 2, BodyDef.BodyType.DynamicBody, true, BIT_ENTITY, (short) (BIT_PLAYER | BIT_BOUNDARY), true);
box2DComponent.body.setUserData(entity);
box2DComponent.sensorBody.setUserData(entity);
entity.add(box2DComponent);
// Transform
final TransformComponent transformComponent = this.createComponent(TransformComponent.class);
// Z defines draw order (0 is first drawn)
transformComponent.scale.set(1, 1);
transformComponent.position.set(posX, posY, drawOrder);
entity.add(transformComponent);
// Type
final TypeComponent typeComponent = this.createComponent(TypeComponent.class);
typeComponent.type = TypeComponent.OTHER;
entity.add(typeComponent);
// State
final StateComponent stateComponent = this.createComponent(StateComponent.class);
// Starting state
stateComponent.state = StateComponent.STATE_UP;
stateComponent.isLooping = true;
entity.add(stateComponent);
// Texture
final TextureComponent textureComponent = this.createComponent(TextureComponent.class);
entity.add(textureComponent);
// Animation
final AnimationComponent animationComponent = this.createComponent(AnimationComponent.class);
Animation<TextureRegion> forwardAnim = new Animation<>(0.1f, ashAtlas.findRegions("forward"));
Animation<TextureRegion> backAnim = new Animation<>(0.1f, ashAtlas.findRegions("back"));
Animation<TextureRegion> leftAnim = new Animation<>(0.1f, ashAtlas.findRegions("left"));
Animation<TextureRegion> rightAnim = new Animation<>(0.1f, ashAtlas.findRegions("right"));
Animation<TextureRegion> forwardIdleAnim = new Animation<>(0.1f, ashAtlas.findRegions("forwardidle"));
Animation<TextureRegion> backIdleAnim = new Animation<>(0.1f, ashAtlas.findRegions("backidle"));
Animation<TextureRegion> leftIdleAnim = new Animation<>(0.1f, ashAtlas.findRegions("leftidle"));
Animation<TextureRegion> rightIdleAnim = new Animation<>(0.1f, ashAtlas.findRegions("rightidle"));
animationComponent.animations.put(StateComponent.STATE_UP, forwardAnim);
animationComponent.animations.put(StateComponent.STATE_DOWN, backAnim);
animationComponent.animations.put(StateComponent.STATE_LEFT, leftAnim);
animationComponent.animations.put(StateComponent.STATE_RIGHT, rightAnim);
animationComponent.animations.put(StateComponent.STATE_UP_IDLE, forwardIdleAnim);
animationComponent.animations.put(StateComponent.STATE_DOWN_IDLE, backIdleAnim);
animationComponent.animations.put(StateComponent.STATE_LEFT_IDLE, leftIdleAnim);
animationComponent.animations.put(StateComponent.STATE_RIGHT_IDLE, rightIdleAnim);
entity.add(animationComponent);
// Collision
final CollisionComponent collisionComponent = this.createComponent(CollisionComponent.class);
entity.add(collisionComponent);
// Adds test entity to engine
this.addEntity(entity);
}
public void createGameObject(float posX, float posY, float width, float height, int type, TextureRegion textureRegion) {
//ToDo complete game object creation
final Entity gameObject = this.createEntity();
// Type
final TypeComponent typeComponent = this.createComponent(TypeComponent.class);
typeComponent.type = TypeComponent.GAMEOBJECT;
gameObject.add(typeComponent);
// Gameobject
final GameObjectComponent gameObjectComponent = this.createComponent(GameObjectComponent.class);
gameObjectComponent.type = type;
gameObject.add(gameObjectComponent);
//Box2D
final Box2DComponent box2DComponent = this.createComponent(Box2DComponent.class);
switch (type) {
case GameObjectComponent.TYPE_SIGN:
box2DComponent.body = bodyFactory.makeBox((posX + (textureRegion.getRegionWidth() / 2f)) * 2, (posY + (textureRegion.getRegionHeight() / 2f)) * 2, width * 2, height * 2, BodyDef.BodyType.StaticBody, true, BIT_SIGN, BIT_PLAYER, true);
break;
}
box2DComponent.body.setUserData(gameObject);
gameObject.add(box2DComponent);
// Transform
final TransformComponent transformComponent = this.createComponent(TransformComponent.class);
transformComponent.scale.set(1,1);
transformComponent.position.set(posX, posY, 1);
gameObject.add(transformComponent);
//Texture
final TextureComponent textureComponent = this.createComponent(TextureComponent.class);
textureComponent.region = textureRegion;
gameObject.add(textureComponent);
// Collision
final CollisionComponent collisionComponent = this.createComponent(CollisionComponent.class);
gameObject.add(collisionComponent);
// Interaction
//Game object also get interaction since static bodies always initiate contact
final InteractionComponent interactionComponent = this.createComponent(InteractionComponent.class);
gameObject.add(interactionComponent);
this.addEntity(gameObject);
}
}
|
package org.anddev.andengine.entity.util;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.util.Debug;
import org.anddev.andengine.util.constants.TimeConstants;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 19:52:31 - 09.03.2010
*/
public class FrameCountCrasher implements IUpdateHandler, TimeConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private int mFramesLeft;
private final float[] mFrameLengths;
// ===========================================================
// Constructors
// ===========================================================
public FrameCountCrasher(final int pFrameCount) {
this.mFramesLeft = pFrameCount;
this.mFrameLengths = new float[pFrameCount];
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onUpdate(final float pSecondsElapsed) {
this.mFramesLeft--;
final float[] frameLengths = this.mFrameLengths;
if(this.mFramesLeft >= 0) {
frameLengths[this.mFramesLeft] = pSecondsElapsed;
} else {
for(int i = frameLengths.length - 1; i >= 0; i--) {
Debug.d("Elapsed: " + frameLengths[i]);
}
throw new RuntimeException();
}
}
@Override
public void reset() {
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
|
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.core;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
/**
* Implement this interface when parameters need to be customized based
* on the connection. We might need to do this to make use of proprietary
* features, available only with a specific Connection type.
*
* @author Rod Johnson
* @author Thomas Risberg
* @see CallableStatementCreatorFactory#newCallableStatementCreator(ParameterMapper)
* @see org.springframework.jdbc.object.StoredProcedure#execute(ParameterMapper)
*/
@FunctionalInterface
public interface ParameterMapper {
/**
* Create a Map of input parameters, keyed by name.
*
* @param con JDBC connection. This is useful (and the purpose of this interface)
* if we need to do something RDBMS-specific with a proprietary Connection
* implementation class. This class conceals such proprietary details. However,
* it is best to avoid using such proprietary RDBMS features if possible.
* @return Map of input parameters, keyed by name (never {@code null})
* @throws SQLException if a SQLException is encountered setting
* parameter values (that is, there's no need to catch SQLException)
*/
Map<String, ?> createMap(Connection con) throws SQLException;
}
|
// Targeted by JavaCPP version 1.5.4: DO NOT EDIT THIS FILE
package org.bytedeco.opencv.opencv_stitching;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.javacpp.presets.javacpp.*;
import static org.bytedeco.openblas.global.openblas_nolapack.*;
import static org.bytedeco.openblas.global.openblas.*;
import org.bytedeco.opencv.opencv_core.*;
import static org.bytedeco.opencv.global.opencv_core.*;
import org.bytedeco.opencv.opencv_imgproc.*;
import static org.bytedeco.opencv.global.opencv_imgproc.*;
import static org.bytedeco.opencv.global.opencv_imgcodecs.*;
import org.bytedeco.opencv.opencv_videoio.*;
import static org.bytedeco.opencv.global.opencv_videoio.*;
import org.bytedeco.opencv.opencv_highgui.*;
import static org.bytedeco.opencv.global.opencv_highgui.*;
import org.bytedeco.opencv.opencv_flann.*;
import static org.bytedeco.opencv.global.opencv_flann.*;
import org.bytedeco.opencv.opencv_features2d.*;
import static org.bytedeco.opencv.global.opencv_features2d.*;
import org.bytedeco.opencv.opencv_calib3d.*;
import static org.bytedeco.opencv.global.opencv_calib3d.*;
import org.bytedeco.opencv.opencv_objdetect.*;
import static org.bytedeco.opencv.global.opencv_objdetect.*;
import org.bytedeco.opencv.opencv_video.*;
import static org.bytedeco.opencv.global.opencv_video.*;
import org.bytedeco.opencv.opencv_ml.*;
import static org.bytedeco.opencv.global.opencv_ml.*;
import org.bytedeco.opencv.opencv_shape.*;
import static org.bytedeco.opencv.global.opencv_shape.*;
import org.bytedeco.opencv.opencv_xfeatures2d.*;
import static org.bytedeco.opencv.global.opencv_xfeatures2d.*;
import static org.bytedeco.opencv.global.opencv_stitching.*;
/** \brief Bundle adjuster that expects affine transformation
represented in homogeneous coordinates in R for each camera param. Implements
camera parameters refinement algorithm which minimizes sum of the reprojection
error squares
<p>
It estimates all transformation parameters. Refinement mask is ignored.
<p>
@see AffineBasedEstimator AffineBestOf2NearestMatcher BundleAdjusterAffinePartial
*/
@Namespace("cv::detail") @NoOffset @Properties(inherit = org.bytedeco.opencv.presets.opencv_stitching.class)
public class BundleAdjusterAffine extends BundleAdjusterBase {
static { Loader.load(); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public BundleAdjusterAffine(Pointer p) { super(p); }
/** Native array allocator. Access with {@link Pointer#position(long)}. */
public BundleAdjusterAffine(long size) { super((Pointer)null); allocateArray(size); }
private native void allocateArray(long size);
@Override public BundleAdjusterAffine position(long position) {
return (BundleAdjusterAffine)super.position(position);
}
@Override public BundleAdjusterAffine getPointer(long i) {
return new BundleAdjusterAffine(this).position(position + i);
}
public BundleAdjusterAffine() { super((Pointer)null); allocate(); }
private native void allocate();
}
|
//An exception class to model page faults
//Created by James Vanderhyde, 28 March 2011
package edu.sxu.osvis.pagedmem;
public class PageFault extends Exception
{
private int requestedPage;
public PageFault(int requestedPage)
{
this.requestedPage = requestedPage;
}
public int getRequestedPage()
{
return requestedPage;
}
}
|
/**
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
*
* The Apereo Foundation licenses this file to you under the Educational
* Community 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://opensource.org/licenses/ecl2.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
*/
package org.opencastproject.workflow.api;
import static com.entwinemedia.fn.Stream.$;
import static org.opencastproject.workflow.api.WorkflowOperationInstance.OperationState.FAILED;
import static org.opencastproject.workflow.api.WorkflowOperationInstance.OperationState.INSTANTIATED;
import static org.opencastproject.workflow.api.WorkflowOperationInstance.OperationState.RETRY;
import static org.opencastproject.workflow.api.WorkflowOperationInstance.OperationState.SKIPPED;
import static org.opencastproject.workflow.api.WorkflowOperationInstance.OperationState.SUCCEEDED;
import org.opencastproject.mediapackage.MediaPackage;
import org.opencastproject.security.api.JaxbOrganization;
import org.opencastproject.security.api.JaxbUser;
import org.opencastproject.security.api.Organization;
import org.opencastproject.security.api.User;
import org.opencastproject.workflow.api.WorkflowOperationInstance.OperationState;
import com.entwinemedia.fn.Fn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeSet;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlType(name = "workflow", namespace = "http://workflow.opencastproject.org")
@XmlRootElement(name = "workflow", namespace = "http://workflow.opencastproject.org")
@XmlAccessorType(XmlAccessType.NONE)
public class WorkflowInstanceImpl implements WorkflowInstance {
private final Logger logger = LoggerFactory.getLogger(WorkflowInstance.class);
@XmlAttribute()
private long id;
@XmlAttribute()
private WorkflowState state;
@XmlElement(name = "template")
private String template;
@XmlElement(name = "title")
private String title;
@XmlElement(name = "description")
private String description;
@XmlElement(name = "parent", nillable = true)
private Long parentId;
@XmlJavaTypeAdapter(UserAdapter.class)
@XmlElement(name = "creator", namespace = "http://org.opencastproject.security")
private User creator;
@XmlJavaTypeAdapter(OrganizationAdapter.class)
@XmlElement(name = "organization", namespace = "http://org.opencastproject.security")
private JaxbOrganization organization;
@XmlElement(name = "organization-id", namespace = "http://org.opencastproject.security")
private String organizationId;
@XmlElement(name = "mediapackage", namespace = "http://mediapackage.opencastproject.org")
private MediaPackage mediaPackage;
@XmlElement(name = "operation")
@XmlElementWrapper(name = "operations")
protected List<WorkflowOperationInstance> operations;
@XmlElement(name = "configuration")
@XmlElementWrapper(name = "configurations")
protected Set<WorkflowConfiguration> configurations;
@XmlTransient
protected boolean initialized = false;
/**
* Default no-arg constructor needed by JAXB
*/
public WorkflowInstanceImpl() {
}
/**
* Constructs a new workflow instance from the given definition, mediapackage, and optional parent workflow ID and
* properties.
*
* @param def
* the workflow definition
* @param mediaPackage
* the mediapackage
* @param parentWorkflowId
* the parent workflow ID
* @param creator
* the user that created this workflow instance
* @param organization
* the organization
* @param properties
* the properties
*/
public WorkflowInstanceImpl(WorkflowDefinition def, MediaPackage mediaPackage, Long parentWorkflowId, User creator,
Organization organization, Map<String, String> properties) {
this.id = -1; // this should be set by the workflow service once the workflow is persisted
this.title = def.getTitle();
this.template = def.getId();
this.description = def.getDescription();
this.parentId = parentWorkflowId;
this.creator = creator;
if (organization != null)
this.organizationId = organization.getId();
this.state = WorkflowState.INSTANTIATED;
this.mediaPackage = mediaPackage;
this.operations = new ArrayList<WorkflowOperationInstance>();
this.configurations = new TreeSet<WorkflowConfiguration>();
if (properties != null) {
for (Entry<String, String> entry : properties.entrySet()) {
configurations.add(new WorkflowConfigurationImpl(entry.getKey(), entry.getValue()));
}
}
extend(def);
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.workflow.api.WorkflowInstance#getId()
*/
@Override
public long getId() {
return id;
}
/**
* Sets the identifier of this workflow instance
*
* @param id
*/
@Override
public void setId(long id) {
this.id = id;
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.workflow.api.WorkflowInstance#getTitle()
*/
@Override
public String getTitle() {
return title;
}
/**
* Sets the title of this workflow instance
*
* @param title
*/
public void setTitle(String title) {
this.title = title;
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.workflow.api.WorkflowInstance#getCreator()
*/
@Override
public User getCreator() {
return creator;
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.workflow.api.WorkflowInstance#getOrganizationId()
*/
@Override
public String getOrganizationId() {
if (organizationId != null) {
return organizationId;
}
// get id from old jobs which stored the whole organization
if (organization != null) {
return organization.getId();
}
return null;
}
/**
* @param creator
* the creator to set
*/
public void setCreator(User creator) {
this.creator = creator;
}
/**
* Sets the workflow's organization.
*
* @param organizationId
* the organization identifier
*/
public void setOrganizationId(final String organizationId) {
this.organizationId = organizationId;
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.workflow.api.WorkflowInstance#getDescription()
*/
@Override
public String getDescription() {
return description;
}
/**
* Sets the description of this workflow instance
*
* @param description
*/
public void setDescription(String description) {
this.description = description;
}
/**
* @return the parentId
*/
@Override
public Long getParentId() {
return parentId;
}
/**
* @param parentId
* the parentId to set
*/
public void setParentId(Long parentId) {
this.parentId = parentId;
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.workflow.api.WorkflowInstance#getState()
*/
@Override
public WorkflowState getState() {
return state;
}
/**
* Sets the state of this workflow instance
*
* @param state
*/
@Override
public void setState(WorkflowState state) {
this.state = state;
}
@Override
public boolean isActive() {
return WorkflowUtil.isActive(getState());
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.workflow.api.WorkflowInstance#getCurrentOperation()
*/
@Override
public WorkflowOperationInstance getCurrentOperation() throws IllegalStateException {
if (!initialized)
init();
if (operations == null || operations.isEmpty())
throw new IllegalStateException("Workflow " + id + " has no operations");
WorkflowOperationInstance currentOperation = null;
// Handle newly instantiated workflows
if (INSTANTIATED.equals(operations.get(0).getState()) || RETRY.equals(operations.get(0).getState())) {
currentOperation = operations.get(0);
} else {
OperationState previousState = null;
int position = 0;
while (currentOperation == null && position < operations.size()) {
WorkflowOperationInstance operation = operations.get(position);
switch (operation.getState()) {
case FAILED:
break;
case RETRY:
case INSTANTIATED:
if (SUCCEEDED.equals(previousState) || SKIPPED.equals(previousState) || FAILED.equals(previousState))
currentOperation = operation;
break;
case PAUSED:
currentOperation = operation;
break;
case RUNNING:
currentOperation = operation;
break;
case SKIPPED:
break;
case SUCCEEDED:
break;
default:
throw new IllegalStateException("Found operation in unknown state '" + operation.getState() + "'");
}
previousState = operation.getState();
position++;
}
// If we are at the last operation and there is no more work to do, we're done
if (operations.get(operations.size() - 1) == currentOperation) {
switch (currentOperation.getState()) {
case FAILED:
case SKIPPED:
case SUCCEEDED:
currentOperation = null;
break;
case INSTANTIATED:
case PAUSED:
case RUNNING:
case RETRY:
break;
default:
throw new IllegalStateException("Found operation in unknown state '" + currentOperation.getState() + "'");
}
}
}
return currentOperation;
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.workflow.api.WorkflowInstance#getOperations()
*/
@Override
public List<WorkflowOperationInstance> getOperations() {
if (operations == null)
operations = new ArrayList<WorkflowOperationInstance>();
if (!initialized)
init();
return new ArrayList<WorkflowOperationInstance>(operations);
}
/**
* Sets the workflow operations on this workflow instance
*
* @param workflowOperationInstanceList
*/
@Override
public final void setOperations(List<WorkflowOperationInstance> workflowOperationInstanceList) {
this.operations = workflowOperationInstanceList;
init();
}
protected void init() {
if (operations == null || operations.isEmpty())
return;
// Jaxb will lose the workflow operation's position, so we fix it here
for (int i = 0; i < operations.size(); i++) {
((WorkflowOperationInstanceImpl) operations.get(i)).setPosition(i);
}
initialized = true;
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.workflow.api.WorkflowInstance#getMediaPackage()
*/
@Override
public MediaPackage getMediaPackage() {
return mediaPackage;
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.workflow.api.WorkflowInstance#setMediaPackage(org.opencastproject.mediapackage.MediaPackage)
*/
@Override
public void setMediaPackage(MediaPackage mediaPackage) {
this.mediaPackage = mediaPackage;
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.workflow.api.Configurable#getConfiguration(java.lang.String)
*/
@Override
public String getConfiguration(String key) {
if (key == null || configurations == null)
return null;
for (WorkflowConfiguration config : configurations) {
if (config.getKey().equals(key))
return config.getValue();
}
return null;
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.workflow.api.Configurable#getConfigurationKeys()
*/
@Override
public Set<String> getConfigurationKeys() {
Set<String> keys = new TreeSet<String>();
if (configurations != null && !configurations.isEmpty()) {
for (WorkflowConfiguration config : configurations) {
keys.add(config.getKey());
}
}
return keys;
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.workflow.api.Configurable#removeConfiguration(java.lang.String)
*/
@Override
public void removeConfiguration(String key) {
if (key == null || configurations == null)
return;
for (Iterator<WorkflowConfiguration> configIter = configurations.iterator(); configIter.hasNext();) {
WorkflowConfiguration config = configIter.next();
if (config.getKey().equals(key)) {
configIter.remove();
return;
}
}
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.workflow.api.Configurable#setConfiguration(java.lang.String, java.lang.String)
*/
@Override
public void setConfiguration(String key, String value) {
if (key == null)
return;
if (configurations == null)
configurations = new HashSet<WorkflowConfiguration>();
// Adjust already existing values
for (WorkflowConfiguration config : configurations) {
if (config.getKey().equals(key)) {
((WorkflowConfigurationImpl) config).setValue(value);
return;
}
}
// No configurations were found, so add a new one
configurations.add(new WorkflowConfigurationImpl(key, value));
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.workflow.api.WorkflowInstance#next()
*/
@Override
public WorkflowOperationInstance next() {
if (operations == null || operations.size() == 0)
throw new IllegalStateException("Operations list must contain operations");
if (!initialized)
init();
WorkflowOperationInstance currentOperation = getCurrentOperation();
if (currentOperation == null)
throw new IllegalStateException("Can't call next on a finished workflow");
for (Iterator<WorkflowOperationInstance> opIter = operations.iterator(); opIter.hasNext();) {
WorkflowOperationInstance op = opIter.next();
if (op.equals(currentOperation) && opIter.hasNext()) {
currentOperation.setState(OperationState.SKIPPED);
currentOperation = opIter.next();
return currentOperation;
}
}
return null;
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.workflow.api.WorkflowInstance#hasNext()
*/
@Override
public boolean hasNext() {
if (!initialized)
init();
if (WorkflowState.FAILED.equals(state) || WorkflowState.FAILING.equals(state)
|| WorkflowState.STOPPED.equals(state) || WorkflowState.SUCCEEDED.equals(state))
return false;
if (operations == null || operations.size() == 0)
throw new IllegalStateException("operations list must contain operations");
WorkflowOperationInstance currentOperation = getCurrentOperation();
if (currentOperation == null)
return true;
return operations.lastIndexOf(currentOperation) < operations.size() - 1;
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Workflow {" + id + "}";
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return Long.valueOf(id).hashCode();
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (obj instanceof WorkflowInstance) {
WorkflowInstance other = (WorkflowInstance) obj;
return id == other.getId();
}
return false;
}
/**
* Allows JAXB handling of {@link WorkflowInstance} interfaces.
*/
public static class Adapter extends XmlAdapter<WorkflowInstanceImpl, WorkflowInstance> {
@Override
public WorkflowInstanceImpl marshal(WorkflowInstance instance) throws Exception {
return (WorkflowInstanceImpl) instance;
}
@Override
public WorkflowInstance unmarshal(WorkflowInstanceImpl instance) throws Exception {
instance.init();
return instance;
}
}
/**
* Allows JAXB handling of {@link Organization} interfaces.
*/
static class OrganizationAdapter extends XmlAdapter<JaxbOrganization, Organization> {
@Override
public JaxbOrganization marshal(Organization org) {
if (org == null)
return null;
if (org instanceof JaxbOrganization)
return (JaxbOrganization) org;
return JaxbOrganization.fromOrganization(org);
}
@Override
public Organization unmarshal(JaxbOrganization org) {
return org;
}
}
/**
* Allows JAXB handling of {@link Organization} interfaces.
*/
static class UserAdapter extends XmlAdapter<JaxbUser, User> {
@Override
public JaxbUser marshal(User user) throws Exception {
if (user == null)
return null;
if (user instanceof JaxbUser)
return (JaxbUser) user;
return JaxbUser.fromUser(user);
}
@Override
public User unmarshal(JaxbUser user) throws Exception {
return user;
}
}
/**
* @return the template
*/
@Override
public String getTemplate() {
return template;
}
/**
* @param template
* the template to set
*/
public void setTemplate(String template) {
this.template = template;
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.workflow.api.WorkflowInstance#extend(org.opencastproject.workflow.api.WorkflowDefinition)
*/
@Override
public void extend(WorkflowDefinition workflowDefinition) {
if (!workflowDefinition.getOperations().isEmpty()) {
setOperations($(operations).append($(workflowDefinition.getOperations()).map(mkInstanceFn)).toList());
setTemplate(workflowDefinition.getId());
}
}
@Override
public void insert(WorkflowDefinition workflowDefinition, WorkflowOperationInstance after) {
if (!workflowDefinition.getOperations().isEmpty() && after.getPosition() >= 0) {
setOperations($(operations).take(after.getPosition() + 1)
.append($(workflowDefinition.getOperations()).map(mkInstanceFn))
.append($(operations).drop(after.getPosition() + 1)).toList());
}
}
private final Fn<WorkflowOperationDefinition, WorkflowOperationInstance> mkInstanceFn = new Fn<WorkflowOperationDefinition, WorkflowOperationInstance>() {
@Override
public WorkflowOperationInstance apply(WorkflowOperationDefinition wod) {
return new WorkflowOperationInstanceImpl(wod, -1);
}
};
}
|
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.upax.exoplayer2.ui;
import android.graphics.Color;
import android.graphics.Typeface;
import android.view.accessibility.CaptioningManager;
import android.view.accessibility.CaptioningManager.CaptionStyle;
import androidx.annotation.IntDef;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import com.upax.exoplayer2.util.Util;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/** A compatibility wrapper for {@link CaptionStyle}. */
public final class CaptionStyleCompat {
/**
* The type of edge, which may be none. One of {@link #EDGE_TYPE_NONE}, {@link
* #EDGE_TYPE_OUTLINE}, {@link #EDGE_TYPE_DROP_SHADOW}, {@link #EDGE_TYPE_RAISED} or {@link
* #EDGE_TYPE_DEPRESSED}.
*/
@Documented
@Retention(RetentionPolicy.SOURCE)
@IntDef({
EDGE_TYPE_NONE,
EDGE_TYPE_OUTLINE,
EDGE_TYPE_DROP_SHADOW,
EDGE_TYPE_RAISED,
EDGE_TYPE_DEPRESSED
})
public @interface EdgeType {}
/** Edge type value specifying no character edges. */
public static final int EDGE_TYPE_NONE = 0;
/** Edge type value specifying uniformly outlined character edges. */
public static final int EDGE_TYPE_OUTLINE = 1;
/** Edge type value specifying drop-shadowed character edges. */
public static final int EDGE_TYPE_DROP_SHADOW = 2;
/** Edge type value specifying raised bevel character edges. */
public static final int EDGE_TYPE_RAISED = 3;
/** Edge type value specifying depressed bevel character edges. */
public static final int EDGE_TYPE_DEPRESSED = 4;
/** Use color setting specified by the track and fallback to default caption style. */
public static final int USE_TRACK_COLOR_SETTINGS = 1;
/** Default caption style. */
public static final CaptionStyleCompat DEFAULT =
new CaptionStyleCompat(
Color.WHITE,
Color.BLACK,
Color.TRANSPARENT,
EDGE_TYPE_NONE,
Color.WHITE,
/* typeface= */ null);
/** The preferred foreground color. */
public final int foregroundColor;
/** The preferred background color. */
public final int backgroundColor;
/** The preferred window color. */
public final int windowColor;
/**
* The preferred edge type. One of:
*
* <ul>
* <li>{@link #EDGE_TYPE_NONE}
* <li>{@link #EDGE_TYPE_OUTLINE}
* <li>{@link #EDGE_TYPE_DROP_SHADOW}
* <li>{@link #EDGE_TYPE_RAISED}
* <li>{@link #EDGE_TYPE_DEPRESSED}
* </ul>
*/
@EdgeType public final int edgeType;
/** The preferred edge color, if using an edge type other than {@link #EDGE_TYPE_NONE}. */
public final int edgeColor;
/** The preferred typeface, or {@code null} if unspecified. */
@Nullable public final Typeface typeface;
/**
* Creates a {@link CaptionStyleCompat} equivalent to a provided {@link CaptionStyle}.
*
* @param captionStyle A {@link CaptionStyle}.
* @return The equivalent {@link CaptionStyleCompat}.
*/
@RequiresApi(19)
public static CaptionStyleCompat createFromCaptionStyle(
CaptioningManager.CaptionStyle captionStyle) {
if (Util.SDK_INT >= 21) {
return createFromCaptionStyleV21(captionStyle);
} else {
// Note - Any caller must be on at least API level 19 or greater (because CaptionStyle did
// not exist in earlier API levels).
return createFromCaptionStyleV19(captionStyle);
}
}
/**
* @param foregroundColor See {@link #foregroundColor}.
* @param backgroundColor See {@link #backgroundColor}.
* @param windowColor See {@link #windowColor}.
* @param edgeType See {@link #edgeType}.
* @param edgeColor See {@link #edgeColor}.
* @param typeface See {@link #typeface}.
*/
public CaptionStyleCompat(
int foregroundColor,
int backgroundColor,
int windowColor,
@EdgeType int edgeType,
int edgeColor,
@Nullable Typeface typeface) {
this.foregroundColor = foregroundColor;
this.backgroundColor = backgroundColor;
this.windowColor = windowColor;
this.edgeType = edgeType;
this.edgeColor = edgeColor;
this.typeface = typeface;
}
@RequiresApi(19)
@SuppressWarnings("ResourceType")
private static CaptionStyleCompat createFromCaptionStyleV19(
CaptioningManager.CaptionStyle captionStyle) {
return new CaptionStyleCompat(
captionStyle.foregroundColor,
captionStyle.backgroundColor,
Color.TRANSPARENT,
captionStyle.edgeType,
captionStyle.edgeColor,
captionStyle.getTypeface());
}
@RequiresApi(21)
@SuppressWarnings("ResourceType")
private static CaptionStyleCompat createFromCaptionStyleV21(
CaptioningManager.CaptionStyle captionStyle) {
return new CaptionStyleCompat(
captionStyle.hasForegroundColor() ? captionStyle.foregroundColor : DEFAULT.foregroundColor,
captionStyle.hasBackgroundColor() ? captionStyle.backgroundColor : DEFAULT.backgroundColor,
captionStyle.hasWindowColor() ? captionStyle.windowColor : DEFAULT.windowColor,
captionStyle.hasEdgeType() ? captionStyle.edgeType : DEFAULT.edgeType,
captionStyle.hasEdgeColor() ? captionStyle.edgeColor : DEFAULT.edgeColor,
captionStyle.getTypeface());
}
}
|
package Synchronizer.Lamps;
import Yardmaster.Forwarder;
import Compiler.Debugging;
import Compiler.Litigate;
import java.util.ArrayDeque;
public class PapsOrganizer extends Compiler.Debugging {
private java.util.ArrayDeque<Litigate> eagerJunk = null;
static int significance = 1014134621;
public synchronized String programmingRefer() {
String apexRestrictions = "0";
return "FCFS:";
}
public synchronized void nsoTic() {
int curtail = -1421570146;
if (flowProcedures != null) {
flowProcedures.markStreamingHours(flowProcedures.makeFlyingDay() + 1);
if (flowProcedures.makeFlyingDay() == flowProcedures.receiveExecutionThickness()) {
flowProcedures.putDepartureClock(this.haveCirculatingShudder());
this.finalizingSystems.addLast(flowProcedures);
flowProcedures = null;
this.mbeMarker = true;
}
}
if (this.mbeMarker && flowProcedures == null) {
this.unansweredVariNow--;
if (unansweredVariNow == 0) {
this.mbeMarker = false;
this.unansweredVariNow = Forwarder.DispatchedMonth;
}
} else {
if (flowProcedures == null && !eagerJunk.isEmpty()) {
flowProcedures = eagerJunk.removeFirst();
flowProcedures.doRestartAgain(this.haveCirculatingShudder());
cargoAct(flowProcedures);
}
}
}
public PapsOrganizer() {
this.eagerJunk = new java.util.ArrayDeque<>();
}
public synchronized void phaseEntry(Litigate negotiations) {
double full = 0.9648357807175899;
eagerJunk.addLast(negotiations);
}
}
|
/*
* Copyright (c) 2018 Gomint team
*
* This code is licensed under the BSD license found in the
* LICENSE file in the root directory of this source tree.
*/
package io.gomint.world.block;
/**
* @author geNAZt
* @version 1.0
* @stability 1
*/
public interface BlockHeavyWeightedPressurePlate extends Block {
}
|
package seedu.address.logic.commands;
import static java.util.Objects.requireNonNull;
import seedu.address.logic.CommandHistory;
import seedu.address.logic.commands.exceptions.CommandException;
import seedu.address.model.Model;
import seedu.address.model.person.healthworker.HealthWorker;
/**
* Adds a HealthWorker to the address book.
* @author Lookaz
*/
public class AddHealthWorkerCommand extends AddCommand implements HealthWorkerCommand {
public static final String MESSAGE_USAGE = COMMAND_WORD + " " + COMMAND_OPTION
+ ": Add a health worker to the address book. Parameters:" + ADD_COMMAND_PARAMETERS + "\n"
+ "Example: " + COMMAND_WORD + " " + ADD_COMMAND_EXAMPLE;
public static final String MESSAGE_SUCCESS = "New health worker added: %1$s";
private final HealthWorker toAdd;
public AddHealthWorkerCommand(HealthWorker toAdd) {
requireNonNull(toAdd);
this.toAdd = toAdd;
}
@Override
public CommandResult execute(Model model, CommandHistory history) throws CommandException {
requireNonNull(model);
if (model.hasHealthWorker(toAdd)) {
throw new CommandException(DUPLICATE_HEALTH_WORKER);
}
add(model, toAdd);
return new CommandResult(String.format(MESSAGE_SUCCESS, toAdd));
}
@Override
public void add(Model model, Object toAdd) {
model.addHealthWorker((HealthWorker) toAdd);
//model.commitHealthWorkerBook();
commitHealthWorkerBook(model);
}
@Override
public boolean equals(Object other) {
return (other == this) || (other instanceof AddHealthWorkerCommand
&& (this.toAdd.equals(((AddHealthWorkerCommand) other).toAdd)));
}
}
|
package cz.metacentrum.perun.core.impl;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import cz.metacentrum.perun.audit.events.AuditEvent;
import cz.metacentrum.perun.cabinet.model.Author;
import cz.metacentrum.perun.cabinet.model.Category;
import cz.metacentrum.perun.cabinet.model.Publication;
import cz.metacentrum.perun.cabinet.model.PublicationForGUI;
import cz.metacentrum.perun.cabinet.model.PublicationSystem;
import cz.metacentrum.perun.cabinet.model.Thanks;
import cz.metacentrum.perun.cabinet.model.ThanksForGUI;
import cz.metacentrum.perun.core.api.Attribute;
import cz.metacentrum.perun.core.api.AttributeDefinition;
import cz.metacentrum.perun.core.api.AuditMessage;
import cz.metacentrum.perun.core.api.Candidate;
import cz.metacentrum.perun.core.api.Destination;
import cz.metacentrum.perun.core.api.Group;
import cz.metacentrum.perun.core.api.Member;
import cz.metacentrum.perun.core.api.PerunBean;
import cz.metacentrum.perun.core.api.PerunSession;
import cz.metacentrum.perun.core.api.User;
import cz.metacentrum.perun.core.api.UserExtSource;
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.core.api.exceptions.PerunException;
import cz.metacentrum.perun.core.implApi.AuditMessagesManagerImplApi;
import cz.metacentrum.perun.registrar.model.Application;
import cz.metacentrum.perun.registrar.model.ApplicationForm;
import cz.metacentrum.perun.registrar.model.ApplicationFormItem;
import cz.metacentrum.perun.registrar.model.ApplicationFormItemWithPrefilledValue;
import cz.metacentrum.perun.registrar.model.ApplicationMail;
import cz.metacentrum.perun.rpclib.impl.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcPerunTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Implementation of AuditMessagesManagerImplApi with methods used to read stored auditer messages.
*
* @author Pavel Zlámal
*/
public class AuditMessagesManagerImpl implements AuditMessagesManagerImplApi {
private final static Logger log = LoggerFactory.getLogger(AuditMessagesManagerImpl.class);
private final static ObjectMapper mapper = new ObjectMapper();
private static final Map<Class<?>,Class<?>> mixinMap = new HashMap<>();
private final static String auditMessageMappingSelectQuery = "id, msg, actor, created_at, created_by_uid";
private final JdbcPerunTemplate jdbc;
static {
// configure JSON deserializer for auditer log
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.enableDefaultTyping();
mixinMap.put(Attribute.class, JsonDeserializer.AttributeMixIn.class);
mixinMap.put(AttributeDefinition.class, JsonDeserializer.AttributeDefinitionMixIn.class);
mixinMap.put(User.class, JsonDeserializer.UserMixIn.class);
mixinMap.put(Member.class, JsonDeserializer.MemberMixIn.class);
mixinMap.put(PerunBean.class, JsonDeserializer.PerunBeanMixIn.class);
mixinMap.put(Candidate.class, JsonDeserializer.CandidateMixIn.class);
mixinMap.put(PerunException.class, JsonDeserializer.PerunExceptionMixIn.class);
mixinMap.put(Destination.class, JsonDeserializer.DestinationMixIn.class);
mixinMap.put(Group.class, JsonDeserializer.GroupMixIn.class);
mixinMap.put(UserExtSource.class, JsonDeserializer.UserExtSourceMixIn.class);
// we probably do not log these objects to auditer log, but to be sure we could read them later they are included
mixinMap.put(Application.class, JsonDeserializer.PerunBeanMixIn.class);
mixinMap.put(ApplicationForm.class, JsonDeserializer.PerunBeanMixIn.class);
mixinMap.put(ApplicationFormItem.class, JsonDeserializer.PerunBeanMixIn.class);
mixinMap.put(ApplicationFormItemWithPrefilledValue.class, JsonDeserializer.PerunBeanMixIn.class);
mixinMap.put(ApplicationMail.class, JsonDeserializer.PerunBeanMixIn.class);
mixinMap.put(Author.class, JsonDeserializer.PerunBeanMixIn.class);
mixinMap.put(Category.class, JsonDeserializer.PerunBeanMixIn.class);
mixinMap.put(Publication.class, JsonDeserializer.PerunBeanMixIn.class);
mixinMap.put(PublicationForGUI.class, JsonDeserializer.PerunBeanMixIn.class);
mixinMap.put(PublicationSystem.class, JsonDeserializer.PerunBeanMixIn.class);
mixinMap.put(Thanks.class, JsonDeserializer.PerunBeanMixIn.class);
mixinMap.put(ThanksForGUI.class, JsonDeserializer.PerunBeanMixIn.class);
mapper.setMixIns(mixinMap);
}
private static final RowMapper<AuditEvent> AUDIT_EVENT_MAPPER = new RowMapper<AuditEvent>() {
@Override
public AuditEvent mapRow(ResultSet resultSet, int i) throws SQLException {
try {
return mapper.readValue(resultSet.getString("msg"), AuditEvent.class);
} catch (JsonParseException | JsonMappingException ex) {
log.error("Can't parse JSON auditer log!", ex);
throw new SQLException(ex);
} catch (IOException ex) {
throw new SQLException(ex);
}
}
};
private static final RowMapper<AuditMessage> AUDIT_MESSAGE_MAPPER = new RowMapper<AuditMessage>() {
@Override
public AuditMessage mapRow(ResultSet resultSet, int i) throws SQLException {
AuditEvent event = AUDIT_EVENT_MAPPER.mapRow(resultSet, i);
Integer principalUserId = null;
if (resultSet.getInt("created_by_uid") != 0) principalUserId = resultSet.getInt("created_by_uid");
return new AuditMessage(resultSet.getInt("id"), event, resultSet.getString("actor"),
resultSet.getString("created_at"), principalUserId);
}
};
private static final ResultSetExtractor<Map<String, Integer>> AUDITER_CONSUMER_EXTRACTOR = resultSet -> {
Map<String, Integer> auditerConsumers = new HashMap<>();
while (resultSet.next()) {
// fetch from map by ID
String name = resultSet.getString("name");
Integer lastProcessedId = resultSet.getInt("last_processed_id");
auditerConsumers.put(name, lastProcessedId);
}
return auditerConsumers;
};
public AuditMessagesManagerImpl(DataSource perunPool) {
this.jdbc = new JdbcPerunTemplate(perunPool);
}
@Override
public List<AuditMessage> getMessages(PerunSession perunSession, int count) throws InternalErrorException {
try {
return jdbc.query("select " + auditMessageMappingSelectQuery + " from (select " + auditMessageMappingSelectQuery + Compatibility.getRowNumberOver() + " from auditer_log ORDER BY id desc) "+Compatibility.getAsAlias("temp")+" where rownumber <= ?",
AUDIT_MESSAGE_MAPPER, count);
} catch (EmptyResultDataAccessException ex) {
return new ArrayList<>();
} catch (RuntimeException err) {
throw new InternalErrorException(err);
}
}
@Override
public List<AuditMessage> getMessagesByCount(PerunSession perunSession, int count) throws InternalErrorException {
try {
return jdbc.query("select " + auditMessageMappingSelectQuery + " from auditer_log where id > ((select max(id) from auditer_log)-?) order by id desc", AUDIT_MESSAGE_MAPPER, count);
} catch (EmptyResultDataAccessException ex) {
return new ArrayList<>();
} catch (RuntimeException err) {
throw new InternalErrorException(err);
}
}
@Override
public int getLastMessageId(PerunSession perunSession) throws InternalErrorException {
try {
return jdbc.queryForInt("select max(id) from auditer_log");
} catch (RuntimeException ex) {
throw new InternalErrorException(ex);
}
}
@Override
public void setLastProcessedId(PerunSession perunSession, String consumerName, int lastProcessedId) throws InternalErrorException {
try {
jdbc.update("update auditer_consumers set last_processed_id=?, modified_at=" + Compatibility.getSysdate() + " where name=?", lastProcessedId, consumerName);
} catch (Exception ex) {
throw new InternalErrorException(ex);
}
}
@Override
public int getAuditerMessagesCount(PerunSession perunSession) throws InternalErrorException {
try {
return jdbc.queryForInt("select count(id) from auditer_log");
} catch (RuntimeException ex) {
throw new InternalErrorException(ex);
}
}
@Override
public void createAuditerConsumer(PerunSession perunSession, String consumerName) throws InternalErrorException {
try {
int lastProcessedId = getLastMessageId(perunSession);
int consumerId = Utils.getNewId(jdbc, "auditer_consumers_id_seq");
jdbc.update("insert into auditer_consumers (id, name, last_processed_id) values (?,?,?)", consumerId, consumerName, lastProcessedId);
log.debug("New consumer [name: '{}', lastProcessedId: '{}'] created.", consumerName, lastProcessedId);
} catch(Exception e) {
throw new InternalErrorException(e);
}
}
@Override
public List<AuditMessage> pollConsumerMessages(PerunSession perunSession, String consumerName) throws InternalErrorException {
checkAuditerConsumerExists(perunSession, consumerName);
try {
List<AuditMessage> messages = new ArrayList<>();
int lastProcessedId = getLastProcessedId(consumerName);
int maxId = getLastMessageId(perunSession);
if(maxId > lastProcessedId) {
// get messages
messages = jdbc.query("select " + auditMessageMappingSelectQuery + " from auditer_log where id > ? and id <= ? order by id", AUDIT_MESSAGE_MAPPER, lastProcessedId, maxId);
// update counter
setLastProcessedId(perunSession, consumerName, maxId);
}
return messages;
} catch(Exception ex) {
throw new InternalErrorException(ex);
}
}
@Override
public List<AuditEvent> pollConsumerEvents(PerunSession perunSession, String consumerName) throws InternalErrorException {
checkAuditerConsumerExists(perunSession, consumerName);
try {
List<AuditEvent> eventList = new ArrayList<>();
int lastProcessedId = getLastProcessedId(consumerName);
int maxId = getLastMessageId(perunSession);
if (maxId > lastProcessedId) {
// get events
eventList = jdbc.query("select " + auditMessageMappingSelectQuery + " from auditer_log where id > ? and id <= ? order by id", AUDIT_EVENT_MAPPER, lastProcessedId, maxId);
// update counter
setLastProcessedId(perunSession, consumerName, maxId);
}
return eventList;
} catch (Exception ex) {
throw new InternalErrorException(ex);
}
}
@Override
public Map<String, Integer> getAllAuditerConsumers(PerunSession sess) throws InternalErrorException {
try {
return jdbc.query("select name, last_processed_id from auditer_consumers", AUDITER_CONSUMER_EXTRACTOR);
} catch (RuntimeException ex) {
throw new InternalErrorException(ex);
}
}
@Override
public boolean checkAuditerConsumerExists(PerunSession session, String consumerName) throws InternalErrorException {
if (consumerName == null) throw new InternalErrorException("Auditer consumer doesn't exist.");
try {
return jdbc.queryForInt("select count(*) from auditer_consumers where name=?", consumerName) == 1;
} catch (Exception ex) {
throw new InternalErrorException(ex);
}
}
/**
* Return last processed ID of audit message for specified consumer.
*
* @param consumerName Name of consumer
* @return ID of last processed message
* @throws InternalErrorException When implementation failse
*/
private int getLastProcessedId(String consumerName) throws InternalErrorException {
try {
return jdbc.queryForInt("select last_processed_id from auditer_consumers where name=? for update", consumerName);
} catch (Exception ex) {
throw new InternalErrorException(ex);
}
}
}
|
// Copyright 2021 Google LLC
//
// 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.
/**
* AdRuleErrorReason.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.admanager.axis.v202105;
public class AdRuleErrorReason implements java.io.Serializable {
private java.lang.String _value_;
private static java.util.HashMap _table_ = new java.util.HashMap();
// Constructor
protected AdRuleErrorReason(java.lang.String value) {
_value_ = value;
_table_.put(_value_,this);
}
public static final java.lang.String _NAME_CONTAINS_INVALID_CHARACTERS = "NAME_CONTAINS_INVALID_CHARACTERS";
public static final java.lang.String _BREAK_TEMPLATE_MUST_HAVE_EXACTLY_ONE_FLEXIBLE_AD_SPOT = "BREAK_TEMPLATE_MUST_HAVE_EXACTLY_ONE_FLEXIBLE_AD_SPOT";
public static final java.lang.String _UNKNOWN = "UNKNOWN";
public static final AdRuleErrorReason NAME_CONTAINS_INVALID_CHARACTERS = new AdRuleErrorReason(_NAME_CONTAINS_INVALID_CHARACTERS);
public static final AdRuleErrorReason BREAK_TEMPLATE_MUST_HAVE_EXACTLY_ONE_FLEXIBLE_AD_SPOT = new AdRuleErrorReason(_BREAK_TEMPLATE_MUST_HAVE_EXACTLY_ONE_FLEXIBLE_AD_SPOT);
public static final AdRuleErrorReason UNKNOWN = new AdRuleErrorReason(_UNKNOWN);
public java.lang.String getValue() { return _value_;}
public static AdRuleErrorReason fromValue(java.lang.String value)
throws java.lang.IllegalArgumentException {
AdRuleErrorReason enumeration = (AdRuleErrorReason)
_table_.get(value);
if (enumeration==null) throw new java.lang.IllegalArgumentException();
return enumeration;
}
public static AdRuleErrorReason fromString(java.lang.String value)
throws java.lang.IllegalArgumentException {
return fromValue(value);
}
public boolean equals(java.lang.Object obj) {return (obj == this);}
public int hashCode() { return toString().hashCode();}
public java.lang.String toString() { return _value_;}
public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);}
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumSerializer(
_javaType, _xmlType);
}
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumDeserializer(
_javaType, _xmlType);
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(AdRuleErrorReason.class);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202105", "AdRuleError.Reason"));
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
}
|
package com.lovi.quebic.sockm.server;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.lovi.quebic.sockm.config.TcpAddress;
import com.lovi.quebic.sockm.exception.TcpServerException;
import com.lovi.quebic.sockm.launcher.SockMLauncher;
public class TcpServer {
private final Logger logger = LoggerFactory.getLogger(TcpServer.class);
private TcpAddress localTcpAddress;
private SockMLauncher launcher;
private Thread serverThread;
public TcpServer(SockMLauncher launcher) {
this.launcher = launcher;
localTcpAddress = this.launcher.getTcpServerAddress();
}
public void listen() throws TcpServerException {
final ServerSocketChannel serverSocket;
final Selector selector;
try{
if(localTcpAddress == null){
serverSocket = ServerSocketChannel.open();
serverSocket.bind(new InetSocketAddress(0));
serverSocket.configureBlocking(false);
selector = Selector.open();
serverSocket.register(selector, SelectionKey.OP_ACCEPT);
String address = serverSocket.socket().getInetAddress().getHostAddress();
int port = serverSocket.socket().getLocalPort();
localTcpAddress = new TcpAddress(address, port);
}else{
serverSocket = ServerSocketChannel.open();
serverSocket.bind(new InetSocketAddress(localTcpAddress.getAddress(), localTcpAddress.getPort()));
serverSocket.configureBlocking(false);
selector = Selector.open();
serverSocket.register(selector, SelectionKey.OP_ACCEPT);
}
logger.info("TCP Server Running : " + localTcpAddress);
}catch(Exception e){
throw new TcpServerException(e.getMessage());
}
serverThread = new Thread(new Runnable() {
@Override
public void run() {
try{
while (true) {
//check for stop
if(Thread.interrupted())
break;
selector.select();
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
iterator.remove();
if(key.isValid()){
if (key.isAcceptable()) {
SocketChannel clientSocketChannel = serverSocket.accept();
clientSocketChannel.configureBlocking(false);
clientSocketChannel.register(selector, SelectionKey.OP_READ);
} else if (key.isReadable()) {
try{
processTcpMessage(key);
}catch(Exception e){
}
} else if (key.isWritable()) {
SocketChannel clientSocketChannel = null;
try{
clientSocketChannel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
if(!buffer.hasRemaining()){
buffer.compact();
key.interestOps(SelectionKey.OP_READ);
}
clientSocketChannel.close();
}catch(Exception e){
clientSocketChannel.close();
}
}
}
}
}
} catch (Exception e) {
logger.error("tcpListen Process " + e.getMessage());
}
}
});
serverThread.start();
}
private void processTcpMessage(SelectionKey key) throws IOException{
SocketChannel clientSocketChannel = (SocketChannel) key.channel();
ByteBuffer clientBuffer = ByteBuffer.allocateDirect(1024);
StringBuilder requestStringBuilder = new StringBuilder();
int bytesRead = clientSocketChannel.read(clientBuffer); // read into buffer.
if(bytesRead == -1){
clientSocketChannel.close();
}
while (bytesRead > 0) {
clientBuffer.flip();
while (clientBuffer.hasRemaining()) {
requestStringBuilder.append((char) clientBuffer.get());
}
clientBuffer.clear();
bytesRead = clientSocketChannel.read(clientBuffer);
}
System.out.println("Input " + requestStringBuilder.toString());
clientSocketChannel.write(ByteBuffer.wrap("I am server".getBytes()));
key.interestOps(SelectionKey.OP_WRITE);
}
public TcpAddress getLocalTcpAddress() {
return localTcpAddress;
}
public synchronized void stopServer(){
if(serverThread != null){
serverThread.interrupt();
}
}
}
|
// http://codingbat.com/prob/p142539
public int[] fizzArray3(int start, int end) {
int newArrLength = end - start;
int[] newArr = new int[newArrLength];
int numberToAdd = start;
for (int i = 0; i < newArrLength; ++i) {
newArr[i] = numberToAdd;
numberToAdd++;
}
return newArr;
}
// Recursive solution (for fun)
/*
public int[] fizzArray3(int start, int end) {
int[] newArr = new int[end - start];
int numberToAdd = start;
return fizzArray3(newArr, numberToAdd, 0);
}
public int[] fizzArray3(int[] newArr, int numberToAdd, int i) {
if (i == newArr.length) {
return newArr;
}
newArr[i] = numberToAdd;
numberToAdd++;
return fizzArray3(newArr, numberToAdd, i+1);
}
*/
|
/**
* TypeTable.java
*
* This file was auto-generated from WSDL by the Apache Axis2 version: SNAPSHOT Built on : Nov 10,
* 2010 (06:34:21 UTC)
*/
package org.apache.axis2.description.java2wsdl.xsd;
/**
* TypeTable bean class
*/
public class TypeTable implements org.apache.axis2.databinding.ADBBean {
/*
* This type was generated from the piece of schema that had name = TypeTable Namespace URI =
* http://java2wsdl.description.axis2.apache.org/xsd Namespace Prefix = ns20
*/
/**
*
*/
private static final long serialVersionUID = -6198251403749843239L;
/**
* field for ComplexSchemaMap
*/
protected authclient.java.util.xsd.Map localComplexSchemaMap;
/*
* This tracker boolean wil be used to detect whether the user called the set method for this
* attribute. It will be used to determine whether to include this field in the serialized XML
*/
protected boolean localComplexSchemaMapTracker = false;
/**
* Auto generated getter method
*
* @return authclient.java.util.xsd.Map
*/
public authclient.java.util.xsd.Map getComplexSchemaMap() {
return this.localComplexSchemaMap;
}
/**
* Auto generated setter method
*
* @param param ComplexSchemaMap
*/
public void setComplexSchemaMap(final authclient.java.util.xsd.Map param) {
this.localComplexSchemaMapTracker = true;
this.localComplexSchemaMap = param;
}
/**
*
* @param parentQName
* @param factory
* @return org.apache.axiom.om.OMElement
*/
@Override
public org.apache.axiom.om.OMElement getOMElement(final javax.xml.namespace.QName parentQName,
final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException {
final org.apache.axiom.om.OMDataSource dataSource =
new org.apache.axis2.databinding.ADBDataSource(this, parentQName);
return new org.apache.axiom.om.impl.llom.OMSourcedElementImpl(parentQName, factory, dataSource);
}
@Override
public void serialize(final javax.xml.namespace.QName parentQName,
final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException,
org.apache.axis2.databinding.ADBException {
serialize(parentQName, xmlWriter, false);
}
@Override
public void serialize(final javax.xml.namespace.QName parentQName, final javax.xml.stream.XMLStreamWriter xmlWriter,
final boolean serializeType) throws javax.xml.stream.XMLStreamException,
org.apache.axis2.databinding.ADBException {
java.lang.String prefix = null;
java.lang.String namespace = null;
prefix = parentQName.getPrefix();
namespace = parentQName.getNamespaceURI();
writeStartElement(prefix, namespace, parentQName.getLocalPart(), xmlWriter);
if (serializeType) {
final java.lang.String namespacePrefix =
registerPrefix(xmlWriter, "http://java2wsdl.description.axis2.apache.org/xsd");
if (namespacePrefix != null && namespacePrefix.trim().length() > 0) {
writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "type",
namespacePrefix + ":TypeTable", xmlWriter);
} else {
writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", "TypeTable", xmlWriter);
}
}
if (this.localComplexSchemaMapTracker) {
if (this.localComplexSchemaMap == null) {
writeStartElement(null, "http://java2wsdl.description.axis2.apache.org/xsd", "complexSchemaMap",
xmlWriter);
// write the nil attribute
writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "nil", "1", xmlWriter);
xmlWriter.writeEndElement();
} else {
this.localComplexSchemaMap.serialize(new javax.xml.namespace.QName(
"http://java2wsdl.description.axis2.apache.org/xsd", "complexSchemaMap"), xmlWriter);
}
}
xmlWriter.writeEndElement();
}
private static java.lang.String generatePrefix(final java.lang.String namespace) {
if (namespace.equals("http://java2wsdl.description.axis2.apache.org/xsd")) {
return "ns20";
}
return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
/**
* Utility method to write an element start tag.
*/
private void writeStartElement(java.lang.String prefix, final java.lang.String namespace,
final java.lang.String localPart,
final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
final java.lang.String writerPrefix = xmlWriter.getPrefix(namespace);
if (writerPrefix != null) {
xmlWriter.writeStartElement(namespace, localPart);
} else {
if (namespace.length() == 0) {
prefix = "";
} else if (prefix == null) {
prefix = generatePrefix(namespace);
}
xmlWriter.writeStartElement(prefix, localPart, namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
}
/**
* Util method to write an attribute with the ns prefix
*/
private void writeAttribute(final java.lang.String prefix, final java.lang.String namespace,
final java.lang.String attName, final java.lang.String attValue,
final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (xmlWriter.getPrefix(namespace) == null) {
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
xmlWriter.writeAttribute(namespace, attName, attValue);
}
/**
* Util method to write an attribute without the ns prefix
*/
private void writeAttribute(final java.lang.String namespace, final java.lang.String attName,
final java.lang.String attValue,
final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName, attValue);
} else {
registerPrefix(xmlWriter, namespace);
xmlWriter.writeAttribute(namespace, attName, attValue);
}
}
/**
* Util method to write an attribute without the ns prefix
*/
private void writeQNameAttribute(final java.lang.String namespace, final java.lang.String attName,
final javax.xml.namespace.QName qname,
final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
final java.lang.String attributeNamespace = qname.getNamespaceURI();
java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace);
if (attributePrefix == null) {
attributePrefix = registerPrefix(xmlWriter, attributeNamespace);
}
java.lang.String attributeValue;
if (attributePrefix.trim().length() > 0) {
attributeValue = attributePrefix + ":" + qname.getLocalPart();
} else {
attributeValue = qname.getLocalPart();
}
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName, attributeValue);
} else {
registerPrefix(xmlWriter, namespace);
xmlWriter.writeAttribute(namespace, attName, attributeValue);
}
}
/**
* method to handle Qnames
*/
private void writeQName(final javax.xml.namespace.QName qname,
final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
final java.lang.String namespaceURI = qname.getNamespaceURI();
if (namespaceURI != null) {
java.lang.String prefix = xmlWriter.getPrefix(namespaceURI);
if (prefix == null) {
prefix = generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix, namespaceURI);
xmlWriter.setPrefix(prefix, namespaceURI);
}
if (prefix.trim().length() > 0) {
xmlWriter.writeCharacters(prefix + ":"
+ org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
} else {
// i.e this is the default namespace
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
} else {
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
}
private void writeQNames(final javax.xml.namespace.QName[] qnames,
final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (qnames != null) {
// we have to store this data until last moment since it is not possible to write any
// namespace data after writing the charactor data
final java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer();
java.lang.String namespaceURI = null;
java.lang.String prefix = null;
for (int i = 0; i < qnames.length; i++) {
if (i > 0) {
stringToWrite.append(" ");
}
namespaceURI = qnames[i].getNamespaceURI();
if (namespaceURI != null) {
prefix = xmlWriter.getPrefix(namespaceURI);
if (prefix == null || prefix.length() == 0) {
prefix = generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix, namespaceURI);
xmlWriter.setPrefix(prefix, namespaceURI);
}
if (prefix.trim().length() > 0) {
stringToWrite.append(prefix).append(":")
.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
} else {
stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
}
} else {
stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
}
}
xmlWriter.writeCharacters(stringToWrite.toString());
}
}
/**
* Register a namespace prefix
*/
private java.lang.String registerPrefix(final javax.xml.stream.XMLStreamWriter xmlWriter,
final java.lang.String namespace) throws javax.xml.stream.XMLStreamException {
java.lang.String prefix = xmlWriter.getPrefix(namespace);
if (prefix == null) {
prefix = generatePrefix(namespace);
while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null) {
prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
return prefix;
}
/**
* databinding method to get an XML representation of this object
*
*/
@Override
public javax.xml.stream.XMLStreamReader getPullParser(final javax.xml.namespace.QName qName) throws org.apache.axis2.databinding.ADBException {
final java.util.ArrayList elementList = new java.util.ArrayList();
final java.util.ArrayList attribList = new java.util.ArrayList();
if (this.localComplexSchemaMapTracker) {
elementList.add(new javax.xml.namespace.QName("http://java2wsdl.description.axis2.apache.org/xsd",
"complexSchemaMap"));
elementList.add(this.localComplexSchemaMap == null ? null : this.localComplexSchemaMap);
}
return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(),
attribList.toArray());
}
/**
* Factory class that keeps the parse method
*/
public static class Factory {
/**
* static method to create the object Precondition: If this object is an element, the current or
* next start element starts this object and any intervening reader events are ignorable If this
* object is not an element, it is a complex type and the reader is at the event just after the
* outer start element Postcondition: If this object is an element, the reader is positioned at its
* end element If this object is a complex type, the reader is positioned at the end element of its
* outer element
*/
public static TypeTable parse(final javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception {
final TypeTable object = new TypeTable();
final int event;
java.lang.String nillableValue = null;
final java.lang.String prefix = "";
final java.lang.String namespaceuri = "";
try {
while (!reader.isStartElement() && !reader.isEndElement()) {
reader.next();
}
if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type") != null) {
final java.lang.String fullTypeName =
reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type");
if (fullTypeName != null) {
java.lang.String nsPrefix = null;
if (fullTypeName.indexOf(":") > -1) {
nsPrefix = fullTypeName.substring(0, fullTypeName.indexOf(":"));
}
nsPrefix = nsPrefix == null ? "" : nsPrefix;
final java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":") + 1);
if (!"TypeTable".equals(type)) {
// find namespace for the prefix
final java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix);
return (TypeTable) org.apache.axis2.transaction.xsd.ExtensionMapper.getTypeObject(nsUri,
type,
reader);
}
}
}
// Note all attributes that were handled. Used to differ normal attributes
// from anyAttributes.
final java.util.Vector handledAttributes = new java.util.Vector();
reader.next();
while (!reader.isStartElement() && !reader.isEndElement()) {
reader.next();
}
if (reader.isStartElement()
&& new javax.xml.namespace.QName("http://java2wsdl.description.axis2.apache.org/xsd",
"complexSchemaMap").equals(reader.getName())) {
nillableValue = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "nil");
if ("true".equals(nillableValue) || "1".equals(nillableValue)) {
object.setComplexSchemaMap(null);
reader.next();
reader.next();
} else {
object.setComplexSchemaMap(authclient.java.util.xsd.Map.Factory.parse(reader));
reader.next();
}
} // End of if for expected property start element
else {
}
while (!reader.isStartElement() && !reader.isEndElement()) {
reader.next();
}
if (reader.isStartElement()) {
// A start element we are not expecting indicates a trailing invalid
// property
throw new org.apache.axis2.databinding.ADBException(
"Unexpected subelement " + reader.getLocalName());
}
}
catch (final javax.xml.stream.XMLStreamException e) {
throw new java.lang.Exception(e);
}
return object;
}
}// end of factory class
}
|
/*******************************************************************************
* Copyright (c) 2017 RISE SICS AB.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v20.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.html.
*
* Contributors:
* RISE SICS AB - initial API and implementation
*******************************************************************************/
package org.eclipse.leshan.server.registration;
import java.net.Inet4Address;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.leshan.core.request.Identity;
import org.eclipse.leshan.server.queue.PresenceService;
import org.junit.Assert;
import org.junit.Test;
/**
* tests the implementation of {@link PresenceService}
*
*/
public class RegistrationUpdateTest {
@Test
public void testAdditionalAttributesUpdate() throws Exception {
Registration.Builder builder = new Registration.Builder("registrationId", "endpoint",
Identity.unsecure(Inet4Address.getLocalHost(), 1));
Map<String, String> additionalAttributes = new HashMap<String, String>();
additionalAttributes.put("x", "1");
additionalAttributes.put("y", "10");
additionalAttributes.put("z", "100");
builder.additionalRegistrationAttributes(additionalAttributes);
Registration r = builder.build();
Map<String, String> updateAdditionalAttributes = new HashMap<String, String>();
updateAdditionalAttributes.put("x", "2");
updateAdditionalAttributes.put("y", "11");
updateAdditionalAttributes.put("z", "101");
updateAdditionalAttributes.put("h", "hello");
RegistrationUpdate updateReg = new RegistrationUpdate(r.getId(), r.getIdentity(), null, null, null, null,
updateAdditionalAttributes);
r = updateReg.update(r);
Map<String, String> updatedAdditionalAttributes = r.getAdditionalRegistrationAttributes();
Assert.assertEquals("2", updatedAdditionalAttributes.get("x"));
Assert.assertEquals("11", updatedAdditionalAttributes.get("y"));
Assert.assertEquals("101", updatedAdditionalAttributes.get("z"));
Assert.assertTrue(updatedAdditionalAttributes.containsKey("h"));
Assert.assertEquals("hello", updatedAdditionalAttributes.get("h"));
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.nativelibs4java.opencl;
import static com.nativelibs4java.util.NIOUtils.directBuffer;
import static com.nativelibs4java.util.NIOUtils.get;
import static com.nativelibs4java.util.NIOUtils.put;
import static org.junit.Assert.*;
import java.nio.*;
import org.junit.BeforeClass;
import org.junit.Test;
import com.nativelibs4java.util.NIOUtils;
import org.bridj.*;
import java.nio.ByteOrder;
import static org.bridj.Pointer.*;
import java.nio.ByteOrder;
import java.util.List;
import org.junit.runners.Parameterized;
/**
*
* @author ochafik
*/
@SuppressWarnings("unchecked")
public class BufferTest extends AbstractCommon {
public BufferTest(CLDevice device) {
super(device);
}
@Parameterized.Parameters
public static List<Object[]> getDeviceParameters() {
return AbstractCommon.getDeviceParameters();
}
static ByteOrder otherOrder(ByteOrder o) {
return o.equals(ByteOrder.BIG_ENDIAN) ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN;
}
@Test(expected = IllegalArgumentException.class)
public void testMismatchingOrder() {
context.createBuffer(CLMem.Usage.InputOutput, allocateFloats(10).order(otherOrder(context.getByteOrder())));
}
@Test
public void testMismatchingByteOrder() {
context.createBuffer(CLMem.Usage.InputOutput, allocateBytes(10).order(otherOrder(context.getByteOrder())));
}
@Test
public void testReadWrite() {
for (Class<?> bufferClass : bufferClasses)
testReadWrite(bufferClass, 10, 3, 3);
}
public <B> void testReadWrite(Class<B> bufferClass, int n, int zeroOffset, int zeroLength) {
CLBuffer<B> buf = context.createBuffer(CLMem.Usage.InputOutput, bufferClass, n);
assertEquals(n, buf.getElementCount());
Pointer<B> initial = allocateArray(bufferClass, n).order(context.getByteOrder());
Pointer<B> zeroes = allocateArray(bufferClass, n).order(context.getByteOrder());
for (int i = 0; i < n; i++) {
int v = i + 1;
Object value = null;
if (bufferClass == Integer.class)
value = (Object)v;
else if (bufferClass == Long.class)
value = (Object)(long)v;
else if (bufferClass == Short.class)
value = (Object)(short)v;
else if (bufferClass == Byte.class)
value = (Object)(byte)v;
else if (bufferClass == Double.class)
value = (Object)(double)v;
else if (bufferClass == Float.class)
value = (Object)(float)v;
else if (bufferClass == Boolean.class)
value = (Object)(v != 0);
else if (bufferClass == Character.class)
value = (Object)(char)v;
else
throw new RuntimeException();
initial.set(i, (B)value);
}
buf.write(queue, initial, true);
Pointer<B> retrieved = buf.read(queue);
assertEquals(buf.getElementCount(), retrieved.getValidElements());
for (int i = 0; i < n; i++)
assertEquals(bufferClass.getName(), initial.get(i), retrieved.get(i));
buf.write(queue, zeroOffset, zeroLength, zeroes, true);
boolean direct = true;
String type = direct ? "read to direct buffer" : "read to indirect buffer";
Pointer<B> readBuffer;
//if (direct)
readBuffer = retrieved;
//else
// readBuffer = NIOUtils.indirectBuffer(n, bufferClass);
buf.read(queue, readBuffer, true);
for (int i = 0; i < n; i++) {
if (i >= zeroOffset && i < (zeroOffset + zeroLength))
assertEquals(bufferClass.getName(), zeroes.get(i), readBuffer.get(i));
else
assertEquals(bufferClass.getName(), initial.get(i), readBuffer.get(i));
}
}
Class<?>[] bufferClasses = new Class[] {
Integer.class,
Long.class,
Short.class,
Byte.class,
Double.class,
Float.class
};
Class<? extends Buffer>[] primClasses = new Class[] {
Integer.class,
Long.class,
Short.class,
Byte.class,
Double.class,
Character.class,
Float.class
};
@Test
public void testMap() {
for (Class<?> bufferClass : bufferClasses)
testMap(bufferClass);
}
public <T> void testMap(Class<T> bufferClass) {
int size = 10;
Pointer<Byte> data = allocateBytes(size).order(context.getByteOrder());
CLBuffer<T> buf = context.createBuffer(CLMem.Usage.Input, data, false).as(bufferClass);
Pointer<T> mapped = buf.map(queue, CLMem.MapFlags.Read);
assertEquals(data, mapped);
}
@Test
public void testFill() {
Pointer<Integer> pattern = pointerToInts(1, 2, 3, 4);
int n = 12;
CLBuffer<Integer> buf = context.createIntBuffer(CLMem.Usage.InputOutput, n);
CLEvent e = buf.fillBuffer(queue, pattern);
assertNotNull(e);
Pointer<Integer> data = buf.read(queue, e);
for (int i = 0; i < n; i++) {
int expectedValue = (i % 4) + 1;
assertEquals(expectedValue, data.getIntAtIndex(i));
}
try {
buf.fillBuffer(queue, pattern, pattern.getValidElements(), 0, n - 1);
fail("Expected fill length failure");
} catch (Throwable th) {}
try {
buf.fillBuffer(queue, pattern, pattern.getValidElements() + 1, 0, n);
fail("Expected pattern length failure");
} catch (Throwable th) {}
}
@Test
public void testCopyTo_full() {
CLBuffer<Integer> b = context.createIntBuffer(CLMem.Usage.InputOutput, pointerToInts(1, 2, 3, 4, 5, 6));
CLBuffer<Integer> out = context.createIntBuffer(CLMem.Usage.InputOutput, 6);
CLEvent e = b.copyTo(queue, out);
assertArrayEquals(new int[] { 1, 2, 3, 4, 5, 6 }, out.read(queue, e).getInts());
}
@Test
public void testCopyTo_partial() {
CLBuffer<Integer> b = context.createIntBuffer(CLMem.Usage.InputOutput, pointerToInts(1, 2, 3, 4, 5, 6));
CLBuffer<Integer> out = context.createIntBuffer(CLMem.Usage.InputOutput, 6);
CLEvent e = b.copyElementsTo(queue, out, 2, 1, 2);
assertArrayEquals(new int[] { 3, 4 }, out.read(queue, e).next().validElements(2).getInts());
}
}
|
/**
* Copyright 2009-2018 PrimeTek.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.primefaces.mobile.renderkit;
import java.io.IOException;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import org.primefaces.component.link.Link;
import org.primefaces.mobile.util.MobileUtils;
import org.primefaces.util.HTML;
public class LinkRenderer extends org.primefaces.component.link.LinkRenderer {
@Override
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
ResponseWriter writer = context.getResponseWriter();
Link link = (Link) component;
boolean shouldWriteId = shouldWriteId(link);
boolean disabled = link.isDisabled();
String style = link.getStyle();
String defaultStyleClass = disabled ? Link.MOBILE_DISABLED_STYLE_CLASS : Link.MOBILE_STYLE_CLASS;
String styleClass = link.getStyleClass();
styleClass = (styleClass == null) ? defaultStyleClass : defaultStyleClass + " " + styleClass;
if (disabled) {
writer.startElement("span", link);
if (shouldWriteId) {
writer.writeAttribute("id", link.getClientId(context), "id");
}
writer.writeAttribute("class", styleClass, "styleClass");
if (style != null) {
writer.writeAttribute("style", style, "style");
}
renderContent(context, link);
writer.endElement("span");
}
else {
String outcome = link.getOutcome();
writer.startElement("a", link);
if (shouldWriteId) {
writer.writeAttribute("id", link.getClientId(context), "id");
}
writer.writeAttribute("class", styleClass, "styleClass");
if (outcome != null && outcome.startsWith("pm:")) {
String command = MobileUtils.buildNavigation(outcome) + "return false;";
writer.writeAttribute("href", "#", null);
renderPassThruAttributes(context, link, HTML.LINK_ATTRS_WITHOUT_EVENTS);
renderDomEvents(context, link, HTML.OUTPUT_EVENTS_WITHOUT_CLICK);
renderOnclick(context, component, command);
}
else {
String targetURL = getTargetURL(context, link);
if (targetURL == null) {
targetURL = "#";
}
writer.writeAttribute("href", targetURL, null);
renderPassThruAttributes(context, link, HTML.LINK_ATTRS_WITHOUT_EVENTS);
renderDomEvents(context, link, HTML.OUTPUT_EVENTS);
}
renderContent(context, link);
writer.endElement("a");
}
}
}
|
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
package com.twilio.rest.video.v1.room.participant;
import com.twilio.base.Fetcher;
import com.twilio.exception.ApiConnectionException;
import com.twilio.exception.ApiException;
import com.twilio.exception.RestException;
import com.twilio.http.HttpMethod;
import com.twilio.http.Request;
import com.twilio.http.Response;
import com.twilio.http.TwilioRestClient;
import com.twilio.rest.Domains;
public class PublishedTrackFetcher extends Fetcher<PublishedTrack> {
private final String pathRoomSid;
private final String pathParticipantSid;
private final String pathSid;
/**
* Construct a new PublishedTrackFetcher.
*
* @param pathRoomSid Unique Room identifier where this Track is published.
* @param pathParticipantSid Unique Participant identifier that publishes this
* Track.
* @param pathSid A 34 character string that uniquely identifies this resource.
*/
public PublishedTrackFetcher(final String pathRoomSid,
final String pathParticipantSid,
final String pathSid) {
this.pathRoomSid = pathRoomSid;
this.pathParticipantSid = pathParticipantSid;
this.pathSid = pathSid;
}
/**
* Make the request to the Twilio API to perform the fetch.
*
* @param client TwilioRestClient with which to make the request
* @return Fetched PublishedTrack
*/
@Override
@SuppressWarnings("checkstyle:linelength")
public PublishedTrack fetch(final TwilioRestClient client) {
Request request = new Request(
HttpMethod.GET,
Domains.VIDEO.toString(),
"/v1/Rooms/" + this.pathRoomSid + "/Participants/" + this.pathParticipantSid + "/PublishedTracks/" + this.pathSid + "",
client.getRegion()
);
Response response = client.request(request);
if (response == null) {
throw new ApiConnectionException("PublishedTrack fetch failed: Unable to connect to server");
} else if (!TwilioRestClient.SUCCESS.apply(response.getStatusCode())) {
RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper());
if (restException == null) {
throw new ApiException("Server Error, no content");
}
throw new ApiException(
restException.getMessage(),
restException.getCode(),
restException.getMoreInfo(),
restException.getStatus(),
null
);
}
return PublishedTrack.fromJson(response.getStream(), client.getObjectMapper());
}
}
|
/**
* Classes that know how to discover peers in the P2P network using DNS, IRC or DNS via Tor (orchid).
*/
package com.matthewmitchell.peercoinj.net.discovery;
|
/*
* Do not modify this file; it is automatically
* generated and any modifications will be overwritten.
*
* @(#) xdc-F05
*/
import java.util.*;
import org.mozilla.javascript.*;
import xdc.services.intern.xsr.*;
import xdc.services.spec.Session;
public class ti_uia_scripts
{
static final String VERS = "@(#) xdc-F05\n";
static final Proto.Elm $$T_Bool = Proto.Elm.newBool();
static final Proto.Elm $$T_Num = Proto.Elm.newNum();
static final Proto.Elm $$T_Str = Proto.Elm.newStr();
static final Proto.Elm $$T_Obj = Proto.Elm.newObj();
static final Proto.Fxn $$T_Met = new Proto.Fxn(null, null, 0, -1, false);
static final Proto.Map $$T_Map = new Proto.Map($$T_Obj);
static final Proto.Arr $$T_Vec = new Proto.Arr($$T_Obj);
static final XScriptO $$DEFAULT = Value.DEFAULT;
static final Object $$UNDEF = Undefined.instance;
static final Proto.Obj $$Package = (Proto.Obj)Global.get("$$Package");
static final Proto.Obj $$Module = (Proto.Obj)Global.get("$$Module");
static final Proto.Obj $$Instance = (Proto.Obj)Global.get("$$Instance");
static final Proto.Obj $$Params = (Proto.Obj)Global.get("$$Params");
static final Object $$objFldGet = Global.get("$$objFldGet");
static final Object $$objFldSet = Global.get("$$objFldSet");
static final Object $$proxyGet = Global.get("$$proxyGet");
static final Object $$proxySet = Global.get("$$proxySet");
static final Object $$delegGet = Global.get("$$delegGet");
static final Object $$delegSet = Global.get("$$delegSet");
Scriptable xdcO;
Session ses;
Value.Obj om;
boolean isROV;
boolean isCFG;
Proto.Obj pkgP;
Value.Obj pkgV;
ArrayList<Object> imports = new ArrayList<Object>();
ArrayList<Object> loggables = new ArrayList<Object>();
ArrayList<Object> mcfgs = new ArrayList<Object>();
ArrayList<Object> icfgs = new ArrayList<Object>();
ArrayList<String> inherits = new ArrayList<String>();
ArrayList<Object> proxies = new ArrayList<Object>();
ArrayList<Object> sizes = new ArrayList<Object>();
ArrayList<Object> tdefs = new ArrayList<Object>();
void $$IMPORTS()
{
Global.callFxn("loadPackage", xdcO, "xdc.rov");
Global.callFxn("loadPackage", xdcO, "xdc.rta");
Global.callFxn("loadPackage", xdcO, "xdc");
Global.callFxn("loadPackage", xdcO, "xdc.corevers");
}
void $$OBJECTS()
{
pkgP = (Proto.Obj)om.bind("ti.uia.scripts.Package", new Proto.Obj());
pkgV = (Value.Obj)om.bind("ti.uia.scripts", new Value.Obj("ti.uia.scripts", pkgP));
}
void $$SINGLETONS()
{
pkgP.init("ti.uia.scripts.Package", (Proto.Obj)om.findStrict("xdc.IPackage.Module", "ti.uia.scripts"));
pkgP.bind("$capsule", $$UNDEF);
pkgV.init2(pkgP, "ti.uia.scripts", Value.DEFAULT, false);
pkgV.bind("$name", "ti.uia.scripts");
pkgV.bind("$category", "Package");
pkgV.bind("$$qn", "ti.uia.scripts.");
pkgV.bind("$vers", Global.newArray());
Value.Map atmap = (Value.Map)pkgV.getv("$attr");
atmap.seal("length");
imports.clear();
imports.add(Global.newArray("xdc.rov", Global.newArray()));
imports.add(Global.newArray("xdc.rta", Global.newArray()));
pkgV.bind("$imports", imports);
StringBuilder sb = new StringBuilder();
sb.append("var pkg = xdc.om['ti.uia.scripts'];\n");
sb.append("if (pkg.$vers.length >= 3) {\n");
sb.append("pkg.$vers.push(Packages.xdc.services.global.Vers.getDate(xdc.csd() + '/..'));\n");
sb.append("}\n");
sb.append("if ('ti.uia.scripts$$stat$base' in xdc.om) {\n");
sb.append("pkg.packageBase = xdc.om['ti.uia.scripts$$stat$base'];\n");
sb.append("pkg.packageRepository = xdc.om['ti.uia.scripts$$stat$root'];\n");
sb.append("}\n");
sb.append("pkg.build.libraries = [\n");
sb.append("];\n");
sb.append("pkg.build.libDesc = [\n");
sb.append("];\n");
Global.eval(sb.toString());
}
void $$INITIALIZATION()
{
Value.Obj vo;
if (isCFG) {
}//isCFG
Global.callFxn("init", pkgV);
((Value.Arr)om.findStrict("$packages", "ti.uia.scripts")).add(pkgV);
}
public void exec( Scriptable xdcO, Session ses )
{
this.xdcO = xdcO;
this.ses = ses;
om = (Value.Obj)xdcO.get("om", null);
Object o = om.geto("$name");
String s = o instanceof String ? (String)o : null;
isCFG = s != null && s.equals("cfg");
isROV = s != null && s.equals("rov");
$$IMPORTS();
$$OBJECTS();
if (isROV) {
}//isROV
$$SINGLETONS();
$$INITIALIZATION();
}
}
|
/**
* dropwizard-guice-box Copyright 2018-2019 Graham Crockford
*
* <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gruelbox.tools.dropwizard.guice.example.simple.submodule;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.io.IOException;
import javax.inject.Named;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
@Singleton
class SubmoduleFilter implements Filter {
private final String something;
@Inject
SubmoduleFilter(@Named("something") String something) {
this.something = something;
}
@Override
public void init(FilterConfig filterConfig) {
// No-op
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
((HttpServletResponse) response).setHeader("submodule-response", something);
chain.doFilter(request, response);
}
@Override
public void destroy() {
// No-op
}
}
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2017, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.junit5.bean;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.List;
import jakarta.enterprise.context.SessionScoped;
import jakarta.enterprise.inject.spi.Bean;
import jakarta.enterprise.util.TypeLiteral;
import org.jboss.weld.junit.MockBean;
import org.jboss.weld.junit5.WeldInitiator;
import org.jboss.weld.junit5.WeldJunit5Extension;
import org.jboss.weld.junit5.WeldSetup;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
/**
*
* @author Matej Novotny
*/
@ExtendWith(WeldJunit5Extension.class)
public class AddPassivatingBeanTest {
@WeldSetup
public WeldInitiator weld = WeldInitiator.from(List.class).addBeans(createListBean()).activate(SessionScoped.class).build();
@SuppressWarnings("serial")
static Bean<?> createListBean() {
return MockBean.builder()
.types(new TypeLiteral<List<String>>() {
}.getType())
.scope(SessionScoped.class)
.creating(
// Mock object provided by Mockito
when(mock(List.class).get(0)).thenReturn("42").getMock())
.build();
}
@SuppressWarnings("serial")
@Test
public void testPassivatingBeanAdded() {
Assertions.assertEquals("42", weld.select(new TypeLiteral<List<String>>() {
}).get().get(0));
}
}
|
package chap6;
import javassist.gluonj.util.Loader;
public class Runner {
public static void main(String[] args) throws Throwable {
Loader.run(基本解释器类.class, args, 基本求值器类.class);
}
}
|
package ru.otus;
import ru.otus.example.ExampleTest;
import ru.otus.processor.AnnotationProcessor;
import ru.otus.processor.TestClassProcessor;
public class Starter {
public static void main(String[] args) throws Exception {
TestResultInterpreter.showResults(
new TestClassProcessor(
new AnnotationProcessor(ExampleTest.class)
.process()
)
.executeTests()
);
}
}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015, 2019 Patrick Reinhart
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package net.reini.rabbitmq.cdi;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class JsonEncoderTest {
private Encoder<TestEvent> encoder;
@BeforeEach
public void setUp() {
encoder = new JsonEncoder<>();
}
@Test
public void testEncode() throws EncodeException {
TestEvent eventObject = new TestEvent();
eventObject.setId("theId");
eventObject.setBooleanValue(true);
byte[] messageBody = encoder.encode(eventObject);
assertEquals("{\"id\":\"theId\",\"booleanValue\":true}", new String(messageBody));
assertTrue(eventObject.isBooleanValue());
}
@Test
public void testEncode_with_error() {
RuntimeException ex = new RuntimeException("some error");
TestEvent eventObject = new TestEvent() {
@Override
public String getId() {
throw ex;
}
};
assertThrows(EncodeException.class, () -> {
encoder.encode(eventObject);
});
}
@Test
public void testContentType() {
assertEquals("application/json", encoder.contentType());
}
}
|
package com.bugsnag.android;
import static com.bugsnag.android.BugsnagTestUtils.mapToJson;
import static com.bugsnag.android.BugsnagTestUtils.streamableToJson;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import android.support.test.InstrumentationRegistry;
import android.support.test.filters.SmallTest;
import android.support.test.runner.AndroidJUnit4;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.IOException;
import java.util.Map;
@RunWith(AndroidJUnit4.class)
@SmallTest
public class AppDataTest {
private Configuration config;
private Map<String, Object> appData;
private Client client;
/**
* Configures a new AppData for testing accessors + serialisation
*
* @throws Exception if setup failed
*/
@Before
public void setUp() throws Exception {
config = new Configuration("some-api-key");
client = new Client(InstrumentationRegistry.getContext(), config);
appData = new AppData(client).getAppData();
}
@After
public void tearDown() throws Exception {
Async.cancelTasks();
}
@Test
public void testPackageName() {
assertEquals("com.bugsnag.android.test", appData.get("packageName"));
}
@Test
public void testBuildUuid() {
assertNull(appData.get("buildUUID"));
}
@Test
public void testDuration() {
assertTrue(((Long) appData.get("duration")) > 0);
}
@Test
public void testDurationInForeground() {
assertEquals(0L, appData.get("durationInForeground"));
}
@Test
public void testInForeground() {
assertFalse((Boolean) appData.get("inForeground"));
}
@Test
public void testJsonSerialisation() throws JSONException {
appData.put("buildUUID", "fa54de");
JSONObject appDataJson = mapToJson(appData);
assertEquals(1, appDataJson.getInt("versionCode"));
assertEquals("1.0", appDataJson.get("version"));
assertEquals("development", appDataJson.get("releaseStage"));
assertEquals("android", appDataJson.get("type"));
assertEquals("com.bugsnag.android.test", appDataJson.get("id"));
assertNotNull(appDataJson.get("buildUUID"));
assertNotNull(appDataJson.get("duration"));
assertNotNull(appDataJson.get("durationInForeground"));
assertFalse(appDataJson.getBoolean("inForeground"));
}
@Test
public void testAppVersionOverride() throws JSONException {
String appVersion = "1.2.3";
config.setAppVersion(appVersion);
JSONObject appDataJson = mapToJson(client.appData.getAppData());
assertEquals(appVersion, appDataJson.get("version"));
}
@Test
public void testReleaseStageOverride() throws JSONException {
String releaseStage = "test-stage";
config.setReleaseStage(releaseStage);
JSONObject appDataJson = mapToJson(client.appData.getAppData());
assertEquals(releaseStage, appDataJson.get("releaseStage"));
}
}
|
/*
* Copyright (c) 2022 vitasystems GmbH and Hannover Medical School.
*
* This file is part of project openEHR_SDK
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ehrbase.client.classgenerator.olddtoexamples.shareddefinition;
import org.ehrbase.client.classgenerator.EnumValueSet;
public enum MathFunctionDefiningcode implements EnumValueSet {
DECREASE("decrease", "decrease", "openehr", "521"),
TOTAL("total", "total", "openehr", "148"),
MAXIMUM("maximum", "maximum", "openehr", "144"),
MODE("mode", "mode", "openehr", "267"),
INCREASE("increase", "increase", "openehr", "522"),
ACTUAL("actual", "actual", "openehr", "640"),
VARIATION("variation", "variation", "openehr", "149"),
MINIMUM("minimum", "minimum", "openehr", "145"),
CHANGE("change", "change", "openehr", "147"),
MEAN("mean", "mean", "openehr", "146"),
MEDIAN("median", "median", "openehr", "268");
private String value;
private String description;
private String terminologyId;
private String code;
MathFunctionDefiningcode(String value, String description, String terminologyId, String code) {
this.value = value;
this.description = description;
this.terminologyId = terminologyId;
this.code = code;
}
public String getValue() {
return this.value;
}
public String getDescription() {
return this.description;
}
public String getTerminologyId() {
return this.terminologyId;
}
public String getCode() {
return this.code;
}
}
|
package com.imzhiqiang.rxtrans;
import io.reactivex.Observable;
/**
* Created by zech on 2017/3/19.
*/
public interface TransApi {
Observable<String> trans(String query, String from, String to);
}
|
/*
* Copyright (c) 2009-2018, United States Government, as represented by the Secretary of Health and Human Services.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the United States Government nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE UNITED STATES GOVERNMENT BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.hhs.fha.nhinc.callback.purposeuse;
import gov.hhs.fha.nhinc.callback.opensaml.CallbackProperties;
/**
*
* @author rhalfert
*/
public interface PurposeUseProxy {
/**
* Test whether "purposeFor" syntax should be used instead of "purposeOf" based on configuration.
*
* @param callbackProperties used to pull information about the target endpoint.
* @return true if "purposeFor" syntax should be used instead of "purposeOf"
*/
public boolean isPurposeForUseEnabled(CallbackProperties callbackProperties);
}
|
/*
* Copyright (c) 2013 Menny Even-Danan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.anysoftkeyboard.keyboards.views;
import static com.menny.android.anysoftkeyboard.AnyApplication.getKeyboardThemeFactory;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.FontMetrics;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.CallSuper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.support.v4.util.ArrayMap;
import android.support.v4.view.MotionEventCompat;
import android.text.Layout.Alignment;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Toast;
import com.anysoftkeyboard.addons.AddOn;
import com.anysoftkeyboard.addons.DefaultAddOn;
import com.anysoftkeyboard.api.KeyCodes;
import com.anysoftkeyboard.base.utils.CompatUtils;
import com.anysoftkeyboard.base.utils.GCUtils;
import com.anysoftkeyboard.base.utils.GCUtils.MemRelatedOperation;
import com.anysoftkeyboard.base.utils.Logger;
import com.anysoftkeyboard.ime.InputViewBinder;
import com.anysoftkeyboard.keyboards.AnyKeyboard;
import com.anysoftkeyboard.keyboards.AnyKeyboard.AnyKey;
import com.anysoftkeyboard.keyboards.GenericKeyboard;
import com.anysoftkeyboard.keyboards.Keyboard;
import com.anysoftkeyboard.keyboards.Keyboard.Key;
import com.anysoftkeyboard.keyboards.KeyboardDimens;
import com.anysoftkeyboard.keyboards.KeyboardSupport;
import com.anysoftkeyboard.keyboards.views.preview.KeyPreviewsController;
import com.anysoftkeyboard.keyboards.views.preview.PreviewPopupTheme;
import com.anysoftkeyboard.prefs.AnimationsLevel;
import com.anysoftkeyboard.prefs.RxSharedPrefs;
import com.anysoftkeyboard.theme.KeyboardTheme;
import com.anysoftkeyboard.utils.EmojiUtils;
import com.menny.android.anysoftkeyboard.AnyApplication;
import com.menny.android.anysoftkeyboard.BuildConfig;
import com.menny.android.anysoftkeyboard.R;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Map;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.subjects.BehaviorSubject;
import io.reactivex.subjects.Subject;
public class AnyKeyboardViewBase extends View implements
InputViewBinder, PointerTracker.UIProxy {
// Miscellaneous constants
public static final int NOT_A_KEY = -1;
static final String TAG = "ASKKbdViewBase";
private static final int[] ACTION_KEY_TYPES = new int[]{R.attr.action_done, R.attr.action_search, R.attr.action_go};
private static final int[] KEY_TYPES = new int[]{R.attr.key_type_function, R.attr.key_type_action};
private static final long TWO_FINGERS_LINGER_TIME = 30;
protected final DefaultAddOn mDefaultAddOn;
/**
* The canvas for the above mutable keyboard bitmap
*/
// private Canvas mCanvas;
protected final Paint mPaint;
@NonNull
protected final KeyboardDimensFromTheme mKeyboardDimens = new KeyboardDimensFromTheme();
protected final PreviewPopupTheme mPreviewPopupTheme = new PreviewPopupTheme();
protected final KeyPressTimingHandler mKeyPressTimingHandler;
// TODO: Let the PointerTracker class manage this pointer queue
final PointerQueue mPointerQueue = new PointerQueue();
// Timing constants
private final int mKeyRepeatInterval;
/* keys icons */
private final SparseArray<DrawableBuilder> mKeysIconBuilders = new SparseArray<>(64);
private final SparseArray<Drawable> mKeysIcons = new SparseArray<>(64);
@NonNull
protected final PointerTracker.SharedPointerTrackersData mSharedPointerTrackersData = new PointerTracker.SharedPointerTrackersData();
private final SparseArray<PointerTracker> mPointerTrackers = new SparseArray<>();
@NonNull
private final KeyDetector mKeyDetector;
/**
* The dirty region in the keyboard bitmap
*/
private final Rect mDirtyRect = new Rect();
private final Rect mKeyBackgroundPadding;
private final Rect mClipRegion = new Rect(0, 0, 0, 0);
// a single instance is enough, there is no need to recreate every draw
// operation!
private final KeyboardDrawOperation mDrawOperation;
private final Map<TextWidthCacheKey, TextWidthCacheValue> mTextWidthCache = new ArrayMap<>();
protected final CompositeDisposable mDisposables = new CompositeDisposable();
/**
* Listener for {@link OnKeyboardActionListener}.
*/
protected OnKeyboardActionListener mKeyboardActionListener;
/**
* Notes if the keyboard just changed, so that we could possibly reallocate
* the mBuffer.
*/
protected boolean mKeyboardChanged;
protected float mBackgroundDimAmount;
protected float mOriginalVerticalCorrection;
protected CharSequence mNextAlphabetKeyboardName;
protected CharSequence mNextSymbolsKeyboardName;
int mSwipeVelocityThreshold;
int mSwipeXDistanceThreshold;
int mSwipeYDistanceThreshold;
int mSwipeSpaceXDistanceThreshold;
int mKeyboardActionType = EditorInfo.IME_ACTION_UNSPECIFIED;
private final int[] mThisWindowOffset = new int[2];
private KeyDrawableStateProvider mDrawableStatesProvider;
// XML attribute
private float mKeyTextSize;
private FontMetrics mTextFontMetrics;
private ColorStateList mKeyTextColor;
private Typeface mKeyTextStyle = Typeface.DEFAULT;
private float mLabelTextSize;
private FontMetrics mLabelFontMetrics;
private float mKeyboardNameTextSize;
private FontMetrics mKeyboardNameFontMetrics;
private int mKeyboardNameTextColor = Color.WHITE;
private float mHintTextSize;
private ColorStateList mHintTextColor;
private FontMetrics mHintTextFontMetrics;
private int mThemeHintLabelAlign;
private int mThemeHintLabelVAlign;
private int mShadowColor;
private int mShadowRadius;
private int mShadowOffsetX;
private int mShadowOffsetY;
private Drawable mKeyBackground;
private float mKeyHysteresisDistance;
// Main keyboard
private AnyKeyboard mKeyboard;
private CharSequence mKeyboardName;
// Drawing
private Key[] mKeys;
private KeyPreviewsController mKeyPreviewsManager;
private long mLastTimeHadTwoFingers = 0;
private Key mInvalidatedKey;
private boolean mTouchesAreDisabledTillLastFingerIsUp = false;
private int mTextCaseForceOverrideType;
private int mTextCaseType;
protected boolean mAlwaysUseDrawText;
private boolean mShowKeyboardNameOnKeyboard;
private boolean mShowHintsOnKeyboard;
private int mCustomHintGravity;
private float mDisplayDensity;
protected final Subject<AnimationsLevel> mAnimationLevelSubject = BehaviorSubject.createDefault(AnimationsLevel.Some);
private final float mKeysHeightFactor;
public AnyKeyboardViewBase(Context context, AttributeSet attrs) {
this(context, attrs, R.style.PlainLightAnySoftKeyboard);
}
public AnyKeyboardViewBase(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mDisplayDensity = getResources().getDisplayMetrics().density;
mDefaultAddOn = new DefaultAddOn(context, context);
mKeyPreviewsManager = createKeyPreviewManager(context, mPreviewPopupTheme);
mKeyPressTimingHandler = new KeyPressTimingHandler(this);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setTextAlign(Align.CENTER);
mPaint.setAlpha(255);
mDrawOperation = new KeyboardDrawOperation(this);
mKeyBackgroundPadding = new Rect(0, 0, 0, 0);
final Resources res = getResources();
final float slide = res.getDimension(R.dimen.mini_keyboard_slide_allowance);
mKeyDetector = createKeyDetector(slide);
mKeyRepeatInterval = 50;
mNextAlphabetKeyboardName = getResources().getString(R.string.change_lang_regular);
mNextSymbolsKeyboardName = getResources().getString(R.string.change_symbols_regular);
final RxSharedPrefs rxSharedPrefs = AnyApplication.prefs(context);
mDisposables.add(rxSharedPrefs.getBoolean(R.string.settings_key_show_keyboard_name_text_key, R.bool.settings_default_show_keyboard_name_text_value)
.asObservable().subscribe(value -> mShowKeyboardNameOnKeyboard = value));
mDisposables.add(rxSharedPrefs.getBoolean(R.string.settings_key_show_hint_text_key, R.bool.settings_default_show_hint_text_value)
.asObservable().subscribe(value -> mShowHintsOnKeyboard = value));
mDisposables.add(
Observable.combineLatest(
rxSharedPrefs.getBoolean(R.string.settings_key_use_custom_hint_align_key, R.bool.settings_default_use_custom_hint_align_value).asObservable(),
rxSharedPrefs.getString(R.string.settings_key_custom_hint_align_key, R.string.settings_default_custom_hint_align_value)
.asObservable().map(Integer::parseInt),
rxSharedPrefs.getString(R.string.settings_key_custom_hint_valign_key, R.string.settings_default_custom_hint_valign_value)
.asObservable().map(Integer::parseInt),
(enabled, align, verticalAlign) -> {
if (enabled) {
return align | verticalAlign;
} else {
return Gravity.NO_GRAVITY;
}
}).subscribe(calculatedGravity -> mCustomHintGravity = calculatedGravity));
mDisposables.add(rxSharedPrefs.getString(R.string.settings_key_swipe_distance_threshold, R.string.settings_default_swipe_distance_threshold)
.asObservable().map(Integer::parseInt).subscribe(integer -> {
mSwipeXDistanceThreshold = (int) (integer * mDisplayDensity);
calculateSwipeDistances();
}));
mDisposables.add(rxSharedPrefs.getString(R.string.settings_key_swipe_velocity_threshold, R.string.settings_default_swipe_velocity_threshold)
.asObservable().map(Integer::parseInt).subscribe(integer -> mSwipeVelocityThreshold = (int) (integer * mDisplayDensity)));
mDisposables.add(rxSharedPrefs.getString(R.string.settings_key_theme_case_type_override, R.string.settings_default_theme_case_type_override)
.asObservable().subscribe(this::updatePrefSettings));
mDisposables.add(rxSharedPrefs.getBoolean(R.string.settings_key_workaround_disable_rtl_fix, R.bool.settings_default_workaround_disable_rtl_fix)
.asObservable().subscribe(value -> mAlwaysUseDrawText = value));
mKeysHeightFactor = KeyboardSupport.getKeyboardHeightFactor(context);
AnimationsLevel.createPrefsObservable(context).subscribe(mAnimationLevelSubject);
mDisposables.add(rxSharedPrefs.getBoolean(R.string.settings_key_gesture_typing, R.bool.settings_default_gesture_typing)
.asObservable().subscribe(enabled -> mSharedPointerTrackersData.gestureTypingEnabled = BuildConfig.DEBUG && enabled));
mDisposables.add(rxSharedPrefs.getString(R.string.settings_key_long_press_timeout, R.string.settings_default_long_press_timeout)
.asObservable().map(Integer::parseInt).subscribe(value -> mSharedPointerTrackersData.delayBeforeKeyRepeatStart = mSharedPointerTrackersData.longPressKeyTimeout = value));
mDisposables.add(rxSharedPrefs.getString(R.string.settings_key_long_press_timeout, R.string.settings_default_long_press_timeout)
.asObservable().map(Integer::parseInt).subscribe(value -> mSharedPointerTrackersData.delayBeforeKeyRepeatStart = mSharedPointerTrackersData.longPressKeyTimeout = value));
mDisposables.add(rxSharedPrefs.getString(R.string.settings_key_multitap_timeout, R.string.settings_default_multitap_timeout)
.asObservable().map(Integer::parseInt).subscribe(value -> mSharedPointerTrackersData.multiTapKeyTimeout = value));
resetKeyboardTheme(getKeyboardThemeFactory(context).getEnabledAddOn());
}
protected KeyPreviewsController createKeyPreviewManager(Context context, PreviewPopupTheme previewPopupTheme) {
return new NullKeyPreviewsManager();
}
protected static boolean isSpaceKey(final AnyKey key) {
return key.getPrimaryCode() == KeyCodes.SPACE;
}
public boolean areTouchesDisabled(MotionEvent motionEvent) {
if (motionEvent != null && mTouchesAreDisabledTillLastFingerIsUp) {
//calculate new value for mTouchesAreDisabledTillLastFingerIsUp
//when do we reset the mTouchesAreDisabledTillLastFingerIsUp flag:
//Only if we have a single pointer
//and:
// CANCEL - the single pointer has been cancelled. So no pointers
// UP - the single pointer has been lifted. So now we have no pointers down.
// DOWN - this is the first action from the single pointer, so we already were in no-pointers down state.
final int action = MotionEventCompat.getActionMasked(motionEvent);
if (motionEvent.getPointerCount() == 1 &&
(action == MotionEvent.ACTION_CANCEL ||
action == MotionEvent.ACTION_DOWN ||
action == MotionEvent.ACTION_UP)) {
mTouchesAreDisabledTillLastFingerIsUp = false;
//If the action is UP then we will return the previous value (which is TRUE), since the motion events are disabled until AFTER
//the UP event, so if this event resets the flag, this event should still be disregarded.
return action == MotionEvent.ACTION_UP;
}
}
return mTouchesAreDisabledTillLastFingerIsUp;
}
public boolean isAtTwoFingersState() {
//this is a hack, I know.
//I know that this is a swipe ONLY after the second finger is up, so I already lost the
//two-fingers count in the motion event.
return SystemClock.elapsedRealtime() - mLastTimeHadTwoFingers < TWO_FINGERS_LINGER_TIME;
}
@CallSuper
public void disableTouchesTillFingersAreUp() {
mKeyPressTimingHandler.cancelAllMessages();
mKeyPreviewsManager.cancelAllPreviews();
for (int trackerIndex = 0, trackersCount = mPointerTrackers.size(); trackerIndex < trackersCount; trackerIndex++) {
PointerTracker tracker = mPointerTrackers.valueAt(trackerIndex);
sendOnXEvent(MotionEvent.ACTION_CANCEL, 0, 0, 0, tracker);
tracker.setAlreadyProcessed();
}
mTouchesAreDisabledTillLastFingerIsUp = true;
}
protected void resetKeyboardTheme(@NonNull KeyboardTheme theme) {
final int keyboardThemeStyleResId = getKeyboardStyleResId(theme);
final int[] remoteKeyboardThemeStyleable = theme.getResourceMapping().getRemoteStyleableArrayFromLocal(R.styleable.AnyKeyboardViewTheme);
final int[] remoteKeyboardIconsThemeStyleable = theme.getResourceMapping().getRemoteStyleableArrayFromLocal(R.styleable.AnyKeyboardViewIconsTheme);
final int[] padding = new int[]{0, 0, 0, 0};
int keyTypeFunctionAttrId = R.attr.key_type_function;
int keyActionAttrId = R.attr.key_type_action;
int keyActionTypeDoneAttrId = R.attr.action_done;
int keyActionTypeSearchAttrId = R.attr.action_search;
int keyActionTypeGoAttrId = R.attr.action_go;
HashSet<Integer> doneLocalAttributeIds = new HashSet<>();
TypedArray a = theme.getPackageContext().obtainStyledAttributes(keyboardThemeStyleResId, remoteKeyboardThemeStyleable);
final int n = a.getIndexCount();
for (int i = 0; i < n; i++) {
final int remoteIndex = a.getIndex(i);
final int localAttrId = theme.getResourceMapping().getLocalAttrId(remoteKeyboardThemeStyleable[remoteIndex]);
if (setValueFromThemeInternal(a, padding, localAttrId, remoteIndex)) {
doneLocalAttributeIds.add(localAttrId);
if (localAttrId == R.attr.keyBackground) {
//keyTypeFunctionAttrId and keyActionAttrId are remote
final int[] keyStateAttributes = theme.getResourceMapping().getRemoteStyleableArrayFromLocal(KEY_TYPES);
keyTypeFunctionAttrId = keyStateAttributes[0];
keyActionAttrId = keyStateAttributes[1];
}
}
}
a.recycle();
// taking icons
int iconSetStyleRes = getKeyboardIconsStyleResId(theme);
if (iconSetStyleRes != 0) {
a = theme.getPackageContext().obtainStyledAttributes(iconSetStyleRes, remoteKeyboardIconsThemeStyleable);
final int iconsCount = a.getIndexCount();
for (int i = 0; i < iconsCount; i++) {
final int remoteIndex = a.getIndex(i);
final int localAttrId = theme.getResourceMapping().getLocalAttrId(remoteKeyboardIconsThemeStyleable[remoteIndex]);
if (setKeyIconValueFromTheme(theme, a, localAttrId, remoteIndex)) {
doneLocalAttributeIds.add(localAttrId);
if (localAttrId == R.attr.iconKeyAction) {
//keyActionTypeDoneAttrId and keyActionTypeSearchAttrId and keyActionTypeGoAttrId are remote
final int[] keyStateAttributes = theme.getResourceMapping().getRemoteStyleableArrayFromLocal(ACTION_KEY_TYPES);
keyActionTypeDoneAttrId = keyStateAttributes[0];
keyActionTypeSearchAttrId = keyStateAttributes[1];
keyActionTypeGoAttrId = keyStateAttributes[2];
}
}
}
a.recycle();
}
// filling what's missing
KeyboardTheme fallbackTheme = getKeyboardThemeFactory(getContext()).getFallbackTheme();
final int keyboardFallbackThemeStyleResId = getKeyboardStyleResId(fallbackTheme);
a = fallbackTheme.getPackageContext().obtainStyledAttributes(
keyboardFallbackThemeStyleResId,
R.styleable.AnyKeyboardViewTheme);
final int fallbackCount = a.getIndexCount();
for (int i = 0; i < fallbackCount; i++) {
final int index = a.getIndex(i);
final int attrId = R.styleable.AnyKeyboardViewTheme[index];
if (doneLocalAttributeIds.contains(attrId)) {
continue;
}
setValueFromThemeInternal(a, padding, attrId, index);
}
a.recycle();
// taking missing icons
int fallbackIconSetStyleId = fallbackTheme.getIconsThemeResId();
a = fallbackTheme.getPackageContext().obtainStyledAttributes(
fallbackIconSetStyleId,
R.styleable.AnyKeyboardViewIconsTheme);
final int fallbackIconsCount = a.getIndexCount();
for (int i = 0; i < fallbackIconsCount; i++) {
final int index = a.getIndex(i);
final int attrId = R.styleable.AnyKeyboardViewIconsTheme[index];
if (doneLocalAttributeIds.contains(attrId)) {
continue;
}
setKeyIconValueFromTheme(fallbackTheme, a, attrId, index);
}
a.recycle();
//creating the key-drawable state provider, as we suppose to have the entire data now
mDrawableStatesProvider = new KeyDrawableStateProvider(keyTypeFunctionAttrId, keyActionAttrId, keyActionTypeDoneAttrId, keyActionTypeSearchAttrId, keyActionTypeGoAttrId);
// settings.
// don't forget that there are THREE padding,
// the theme's and the
// background image's padding and the
// View
Drawable keyboardBackground = super.getBackground();
if (keyboardBackground != null) {
Rect backgroundPadding = new Rect();
keyboardBackground.getPadding(backgroundPadding);
padding[0] += backgroundPadding.left;
padding[1] += backgroundPadding.top;
padding[2] += backgroundPadding.right;
padding[3] += backgroundPadding.bottom;
}
setPadding(padding[0], padding[1], padding[2], padding[3]);
final Resources res = getResources();
final int viewWidth = (getWidth() > 0) ? getWidth() : res.getDisplayMetrics().widthPixels;
mKeyboardDimens.setKeyboardMaxWidth(viewWidth - padding[0] - padding[2]);
mPaint.setTextSize(mKeyTextSize);
mKeyBackground.getPadding(mKeyBackgroundPadding);
}
protected KeyDetector createKeyDetector(final float slide) {
return new MiniKeyboardKeyDetector(slide);
}
private boolean setValueFromThemeInternal(TypedArray remoteTypedArray, int[] padding, int localAttrId, int remoteTypedArrayIndex) {
try {
return setValueFromTheme(remoteTypedArray, padding, localAttrId, remoteTypedArrayIndex);
} catch (RuntimeException e) {
Logger.w(TAG, e, "Failed to parse resource with local id %s, and remote index %d", localAttrId, remoteTypedArrayIndex);
if (BuildConfig.DEBUG) throw e;
return false;
}
}
protected boolean setValueFromTheme(TypedArray remoteTypedArray, final int[] padding, final int localAttrId, final int remoteTypedArrayIndex) {
//CHECKSTYLE:OFF: missingswitchdefault
switch (localAttrId) {
case android.R.attr.background:
Drawable keyboardBackground = remoteTypedArray.getDrawable(remoteTypedArrayIndex);
if (keyboardBackground == null) return false;
CompatUtils.setViewBackgroundDrawable(this, keyboardBackground);
break;
case android.R.attr.paddingLeft:
padding[0] = remoteTypedArray.getDimensionPixelSize(remoteTypedArrayIndex, -1);
if (padding[0] == -1) return false;
break;
case android.R.attr.paddingTop:
padding[1] = remoteTypedArray.getDimensionPixelSize(remoteTypedArrayIndex, -1);
if (padding[1] == -1) return false;
break;
case android.R.attr.paddingRight:
padding[2] = remoteTypedArray.getDimensionPixelSize(remoteTypedArrayIndex, -1);
if (padding[2] == -1) return false;
break;
case android.R.attr.paddingBottom:
padding[3] = remoteTypedArray.getDimensionPixelSize(remoteTypedArrayIndex, -1);
if (padding[3] == -1) return false;
break;
case R.attr.keyBackground:
mKeyBackground = remoteTypedArray.getDrawable(remoteTypedArrayIndex);
if (mKeyBackground == null) return false;
break;
case R.attr.keyHysteresisDistance:
mKeyHysteresisDistance = remoteTypedArray.getDimensionPixelOffset(remoteTypedArrayIndex, -1);
if (mKeyHysteresisDistance == -1) return false;
break;
case R.attr.verticalCorrection:
mOriginalVerticalCorrection = remoteTypedArray.getDimensionPixelOffset(remoteTypedArrayIndex, -1);
if (mOriginalVerticalCorrection == -1) return false;
break;
case R.attr.keyTextSize:
mKeyTextSize = remoteTypedArray.getDimensionPixelSize(remoteTypedArrayIndex, -1);
if (mKeyTextSize == -1) return false;
mKeyTextSize = mKeyTextSize * mKeysHeightFactor;
Logger.d(TAG, "AnySoftKeyboardTheme_keyTextSize " + mKeyTextSize);
break;
case R.attr.keyTextColor:
mKeyTextColor = remoteTypedArray.getColorStateList(remoteTypedArrayIndex);
if (mKeyTextColor == null) {
mKeyTextColor = new ColorStateList(new int[][]{{0}},
new int[]{remoteTypedArray.getColor(remoteTypedArrayIndex, 0xFF000000)});
}
break;
case R.attr.labelTextSize:
mLabelTextSize = remoteTypedArray.getDimensionPixelSize(remoteTypedArrayIndex, -1);
if (mLabelTextSize == -1) return false;
mLabelTextSize *= mKeysHeightFactor;
break;
case R.attr.keyboardNameTextSize:
mKeyboardNameTextSize = remoteTypedArray.getDimensionPixelSize(remoteTypedArrayIndex, -1);
if (mKeyboardNameTextSize == -1) return false;
mKeyboardNameTextSize *= mKeysHeightFactor;
break;
case R.attr.keyboardNameTextColor:
mKeyboardNameTextColor = remoteTypedArray.getColor(remoteTypedArrayIndex, Color.WHITE);
break;
case R.attr.shadowColor:
mShadowColor = remoteTypedArray.getColor(remoteTypedArrayIndex, 0);
break;
case R.attr.shadowRadius:
mShadowRadius = remoteTypedArray.getDimensionPixelOffset(remoteTypedArrayIndex, 0);
break;
case R.attr.shadowOffsetX:
mShadowOffsetX = remoteTypedArray.getDimensionPixelOffset(remoteTypedArrayIndex, 0);
break;
case R.attr.shadowOffsetY:
mShadowOffsetY = remoteTypedArray.getDimensionPixelOffset(remoteTypedArrayIndex, 0);
break;
case R.attr.backgroundDimAmount:
mBackgroundDimAmount = remoteTypedArray.getFloat(remoteTypedArrayIndex, -1f);
if (mBackgroundDimAmount == -1f) return false;
break;
case R.attr.keyPreviewBackground:
Drawable keyPreviewBackground = remoteTypedArray.getDrawable(remoteTypedArrayIndex);
if (keyPreviewBackground == null) return false;
mPreviewPopupTheme.setPreviewKeyBackground(keyPreviewBackground);
break;
case R.attr.keyPreviewTextColor:
mPreviewPopupTheme.setPreviewKeyTextColor(remoteTypedArray.getColor(remoteTypedArrayIndex, 0xFFF));
break;
case R.attr.keyPreviewTextSize:
int keyPreviewTextSize = remoteTypedArray.getDimensionPixelSize(remoteTypedArrayIndex, -1);
if (keyPreviewTextSize == -1) return false;
keyPreviewTextSize = (int) (keyPreviewTextSize * mKeysHeightFactor);
mPreviewPopupTheme.setPreviewKeyTextSize(keyPreviewTextSize);
break;
case R.attr.keyPreviewLabelTextSize:
int keyPreviewLabelTextSize = remoteTypedArray.getDimensionPixelSize(remoteTypedArrayIndex, -1);
if (keyPreviewLabelTextSize == -1) return false;
keyPreviewLabelTextSize = (int) (keyPreviewLabelTextSize * mKeysHeightFactor);
mPreviewPopupTheme.setPreviewLabelTextSize(keyPreviewLabelTextSize);
break;
case R.attr.keyPreviewOffset:
mPreviewPopupTheme.setVerticalOffset(remoteTypedArray.getDimensionPixelOffset(remoteTypedArrayIndex, 0));
break;
case R.attr.previewAnimationType:
int previewAnimationType = remoteTypedArray.getInteger(remoteTypedArrayIndex, -1);
if (previewAnimationType == -1) return false;
mPreviewPopupTheme.setPreviewAnimationType(previewAnimationType);
break;
case R.attr.keyTextStyle:
int textStyle = remoteTypedArray.getInt(remoteTypedArrayIndex, 0);
switch (textStyle) {
case 0:
mKeyTextStyle = Typeface.DEFAULT;
break;
case 1:
mKeyTextStyle = Typeface.DEFAULT_BOLD;
break;
case 2:
mKeyTextStyle = Typeface.defaultFromStyle(Typeface.ITALIC);
break;
default:
mKeyTextStyle = Typeface.defaultFromStyle(textStyle);
break;
}
mPreviewPopupTheme.setKeyStyle(mKeyTextStyle);
break;
case R.attr.keyHorizontalGap:
float themeHorizontalKeyGap = remoteTypedArray.getDimensionPixelOffset(remoteTypedArrayIndex, -1);
if (themeHorizontalKeyGap == -1) return false;
mKeyboardDimens.setHorizontalKeyGap(themeHorizontalKeyGap);
break;
case R.attr.keyVerticalGap:
float themeVerticalRowGap = remoteTypedArray.getDimensionPixelOffset(remoteTypedArrayIndex, -1);
if (themeVerticalRowGap == -1) return false;
mKeyboardDimens.setVerticalRowGap(themeVerticalRowGap);
break;
case R.attr.keyNormalHeight:
int themeNormalKeyHeight = remoteTypedArray.getDimensionPixelOffset(remoteTypedArrayIndex, -1);
if (themeNormalKeyHeight == -1) return false;
mKeyboardDimens.setNormalKeyHeight(themeNormalKeyHeight);
break;
case R.attr.keyLargeHeight:
int themeLargeKeyHeight = remoteTypedArray.getDimensionPixelOffset(remoteTypedArrayIndex, -1);
if (themeLargeKeyHeight == -1) return false;
mKeyboardDimens.setLargeKeyHeight(themeLargeKeyHeight);
break;
case R.attr.keySmallHeight:
int themeSmallKeyHeight = remoteTypedArray.getDimensionPixelOffset(remoteTypedArrayIndex, -1);
if (themeSmallKeyHeight == -1) return false;
mKeyboardDimens.setSmallKeyHeight(themeSmallKeyHeight);
break;
case R.attr.hintTextSize:
mHintTextSize = remoteTypedArray.getDimensionPixelSize(remoteTypedArrayIndex, -1);
if (mHintTextSize == -1) return false;
mHintTextSize *= mKeysHeightFactor;
break;
case R.attr.hintTextColor:
mHintTextColor = remoteTypedArray.getColorStateList(remoteTypedArrayIndex);
if (mHintTextColor == null) {
mHintTextColor = new ColorStateList(new int[][]{{0}}, new int[]{remoteTypedArray.getColor(remoteTypedArrayIndex, 0xFF000000)});
}
break;
case R.attr.hintLabelVAlign:
mThemeHintLabelVAlign = remoteTypedArray.getInt(remoteTypedArrayIndex, Gravity.BOTTOM);
break;
case R.attr.hintLabelAlign:
mThemeHintLabelAlign = remoteTypedArray.getInt(remoteTypedArrayIndex, Gravity.RIGHT);
break;
case R.attr.keyTextCaseStyle:
mTextCaseType = remoteTypedArray.getInt(remoteTypedArrayIndex, 0);
break;
}
//CHECKSTYLE:ON: missingswitchdefault
return true;
}
private boolean setKeyIconValueFromTheme(KeyboardTheme theme, TypedArray remoteTypeArray,
final int localAttrId, final int remoteTypedArrayIndex) {
final int keyCode;
switch (localAttrId) {
case R.attr.iconKeyShift:
keyCode = KeyCodes.SHIFT;
break;
case R.attr.iconKeyControl:
keyCode = KeyCodes.CTRL;
break;
case R.attr.iconKeyAction:
keyCode = KeyCodes.ENTER;
break;
case R.attr.iconKeyBackspace:
keyCode = KeyCodes.DELETE;
break;
case R.attr.iconKeyCancel:
keyCode = KeyCodes.CANCEL;
break;
case R.attr.iconKeyGlobe:
keyCode = KeyCodes.MODE_ALPHABET;
break;
case R.attr.iconKeySpace:
keyCode = KeyCodes.SPACE;
break;
case R.attr.iconKeyTab:
keyCode = KeyCodes.TAB;
break;
case R.attr.iconKeyArrowDown:
keyCode = KeyCodes.ARROW_DOWN;
break;
case R.attr.iconKeyArrowLeft:
keyCode = KeyCodes.ARROW_LEFT;
break;
case R.attr.iconKeyArrowRight:
keyCode = KeyCodes.ARROW_RIGHT;
break;
case R.attr.iconKeyArrowUp:
keyCode = KeyCodes.ARROW_UP;
break;
case R.attr.iconKeyInputMoveHome:
keyCode = KeyCodes.MOVE_HOME;
break;
case R.attr.iconKeyInputMoveEnd:
keyCode = KeyCodes.MOVE_END;
break;
case R.attr.iconKeyMic:
keyCode = KeyCodes.VOICE_INPUT;
break;
case R.attr.iconKeySettings:
keyCode = KeyCodes.SETTINGS;
break;
case R.attr.iconKeyCondenseNormal:
keyCode = KeyCodes.MERGE_LAYOUT;
break;
case R.attr.iconKeyCondenseSplit:
keyCode = KeyCodes.SPLIT_LAYOUT;
break;
case R.attr.iconKeyCondenseCompactToRight:
keyCode = KeyCodes.COMPACT_LAYOUT_TO_RIGHT;
break;
case R.attr.iconKeyCondenseCompactToLeft:
keyCode = KeyCodes.COMPACT_LAYOUT_TO_LEFT;
break;
case R.attr.iconKeyClipboardCopy:
keyCode = KeyCodes.CLIPBOARD_COPY;
break;
case R.attr.iconKeyClipboardCut:
keyCode = KeyCodes.CLIPBOARD_CUT;
break;
case R.attr.iconKeyClipboardPaste:
keyCode = KeyCodes.CLIPBOARD_PASTE;
break;
case R.attr.iconKeyClipboardSelect:
keyCode = KeyCodes.CLIPBOARD_SELECT_ALL;
break;
case R.attr.iconKeyQuickText:
keyCode = KeyCodes.QUICK_TEXT;
break;
case R.attr.iconKeyUndo:
keyCode = KeyCodes.UNDO;
break;
case R.attr.iconKeyRedo:
keyCode = KeyCodes.REDO;
break;
case R.attr.iconKeyForwardDelete:
keyCode = KeyCodes.FORWARD_DELETE;
break;
default:
keyCode = 0;
}
if (keyCode == 0) {
if (BuildConfig.DEBUG) {
throw new IllegalArgumentException("No valid keycode for attr " + remoteTypeArray.getResourceId(remoteTypedArrayIndex, 0));
}
Logger.w(TAG, "No valid keycode for attr %d", remoteTypeArray.getResourceId(remoteTypedArrayIndex, 0));
return false;
} else {
mKeysIconBuilders.put(keyCode, DrawableBuilder.build(theme, remoteTypeArray, remoteTypedArrayIndex));
Logger.d(TAG, "DrawableBuilders size is %d, newest key code %d for resId %d (at index %d)", mKeysIconBuilders.size(), keyCode, remoteTypeArray.getResourceId(remoteTypedArrayIndex, 0),
remoteTypedArrayIndex);
return true;
}
}
protected int getKeyboardStyleResId(KeyboardTheme theme) {
return theme.getPopupThemeResId();
}
protected int getKeyboardIconsStyleResId(KeyboardTheme theme) {
return theme.getPopupIconsThemeResId();
}
/**
* Returns the {@link OnKeyboardActionListener} object.
*
* @return the listener attached to this keyboard
*/
protected OnKeyboardActionListener getOnKeyboardActionListener() {
return mKeyboardActionListener;
}
@Override
public void setOnKeyboardActionListener(OnKeyboardActionListener listener) {
mKeyboardActionListener = listener;
for (int trackerIndex = 0, trackersCount = mPointerTrackers.size(); trackerIndex < trackersCount; trackerIndex++) {
PointerTracker tracker = mPointerTrackers.valueAt(trackerIndex);
tracker.setOnKeyboardActionListener(listener);
}
}
protected void setKeyboard(@NonNull AnyKeyboard keyboard, float verticalCorrection) {
mKeysIcons.clear();
if (mKeyboard != null) {
dismissAllKeyPreviews();
}
// Remove any pending messages, except dismissing preview
mKeyPressTimingHandler.cancelAllMessages();
mKeyPreviewsManager.cancelAllPreviews();
mKeyboard = keyboard;
mKeyboardName = keyboard.getKeyboardName();
mKeys = mKeyDetector.setKeyboard(keyboard, keyboard.getShiftKey());
mKeyDetector.setCorrection(-getPaddingLeft(), -getPaddingTop() + verticalCorrection);
for (int trackerIndex = 0, trackersCount = mPointerTrackers.size(); trackerIndex < trackersCount; trackerIndex++) {
PointerTracker tracker = mPointerTrackers.valueAt(trackerIndex);
tracker.setKeyboard(mKeys, mKeyHysteresisDistance);
}
// setting the icon/text
setSpecialKeysIconsAndLabels();
//the new keyboard might be of a different size
requestLayout();
// Hint to reallocate the buffer if the size changed
mKeyboardChanged = true;
invalidateAllKeys();
computeProximityThreshold(keyboard);
calculateSwipeDistances();
}
private void calculateSwipeDistances() {
final AnyKeyboard kbd = getKeyboard();
if (kbd == null) {
mSwipeYDistanceThreshold = 0;
} else {
mSwipeYDistanceThreshold = (int) (mSwipeXDistanceThreshold * (((float) kbd.getHeight()) / ((float) kbd.getMinWidth())));
}
mSwipeSpaceXDistanceThreshold = mSwipeXDistanceThreshold / 2;
mSwipeYDistanceThreshold = mSwipeYDistanceThreshold / 2;
}
/**
* Returns the current keyboard being displayed by this view.
*
* @return the currently attached keyboard
*/
public AnyKeyboard getKeyboard() {
return mKeyboard;
}
@Override
public final void setKeyboard(AnyKeyboard currentKeyboard, CharSequence nextAlphabetKeyboard, CharSequence nextSymbolsKeyboard) {
mNextAlphabetKeyboardName = nextAlphabetKeyboard;
if (TextUtils.isEmpty(mNextAlphabetKeyboardName)) {
mNextAlphabetKeyboardName = getResources().getString(R.string.change_lang_regular);
}
mNextSymbolsKeyboardName = nextSymbolsKeyboard;
if (TextUtils.isEmpty(mNextSymbolsKeyboardName)) {
mNextSymbolsKeyboardName = getResources().getString(R.string.change_symbols_regular);
}
setKeyboard(currentKeyboard, mOriginalVerticalCorrection);
}
@Override
public boolean setShifted(boolean shifted) {
if (mKeyboard != null) {
if (mKeyboard.setShifted(shifted)) {
// The whole keyboard probably needs to be redrawn
invalidateAllKeys();
return true;
}
}
return false;
}
@Override
public boolean setShiftLocked(boolean shiftLocked) {
AnyKeyboard keyboard = getKeyboard();
if (keyboard != null) {
if (keyboard.setShiftLocked(shiftLocked)) {
invalidateAllKeys();
return true;
}
}
return false;
}
/**
* Returns the state of the shift key of the UI, if any.
*
* @return true if the shift is in a pressed state, false otherwise. If
* there is no shift key on the keyboard or there is no keyboard
* attached, it returns false.
*/
@Override
public boolean isShifted() {
//if there no keyboard is set, then the shift state is false
return mKeyboard != null && mKeyboard.isShifted();
}
@Override
public boolean setControl(boolean control) {
if (mKeyboard != null) {
if (mKeyboard.setControl(control)) {
// The whole keyboard probably needs to be redrawn
invalidateAllKeys();
return true;
}
}
return false;
}
/**
* When enabled, calls to {@link OnKeyboardActionListener#onKey} will
* include key mCodes for adjacent keys. When disabled, only the primary key
* code will be reported.
*
* @param enabled whether or not the proximity correction is enabled
*/
public void setProximityCorrectionEnabled(boolean enabled) {
mKeyDetector.setProximityCorrectionEnabled(enabled);
}
private boolean isShiftedAccordingToCaseType(boolean keyShiftState) {
switch (mTextCaseForceOverrideType) {
case -1:
switch (mTextCaseType) {
case 0:
return keyShiftState; //auto
case 1:
return false; //lowercase always
case 2:
return true; //uppercase always
default:
return keyShiftState;
}
case 1:
return false; //lowercase always
case 2:
return true; //uppercase always
default:
return keyShiftState;
}
}
@VisibleForTesting
CharSequence adjustLabelToShiftState(AnyKey key) {
CharSequence label = key.label;
if (isShiftedAccordingToCaseType(mKeyboard.isShifted())) {
if (!TextUtils.isEmpty(key.shiftedKeyLabel)) {
return key.shiftedKeyLabel;
} else if (label != null && label.length() == 1) {
label = Character.toString((char) key.getCodeAtIndex(0, isShiftedAccordingToCaseType(mKeyDetector.isKeyShifted(key))));
}
//remembering for next time
if (key.isShiftCodesAlways()) key.shiftedKeyLabel = label;
}
return label;
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// Round up a little
if (mKeyboard == null) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
} else {
int width = mKeyboard.getMinWidth() + getPaddingLeft() + getPaddingRight();
if (MeasureSpec.getSize(widthMeasureSpec) < width + 10) {
width = MeasureSpec.getSize(widthMeasureSpec);
}
int height = mKeyboard.getHeight() + getPaddingTop() + getPaddingBottom();
setMeasuredDimension(width, height);
}
}
/**
* Compute the average distance between adjacent keys (horizontally and
* vertically) and square it to get the proximity threshold. We use a square
* here and in computing the touch distance from a key's center to avoid
* taking a square root.
*/
private void computeProximityThreshold(Keyboard keyboard) {
if (keyboard == null) {
return;
}
final Key[] keys = mKeys;
if (keys == null) {
return;
}
int length = keys.length;
int dimensionSum = 0;
for (Key key : keys) {
dimensionSum += Math.min(key.width, key.height) + key.gap;
}
if (dimensionSum < 0 || length == 0) {
return;
}
mKeyDetector.setProximityThreshold((int) (dimensionSum * 1.4f / length));
}
@Override
@CallSuper
public void onDraw(final Canvas canvas) {
super.onDraw(canvas);
mDrawOperation.setCanvas(canvas);
GCUtils.getInstance().performOperationWithMemRetry(TAG, mDrawOperation);
}
@CallSuper
protected void onBufferDraw(Canvas canvas, final Paint paint) {
if (mKeyboardChanged) {
invalidateAllKeys();
mKeyboardChanged = false;
}
canvas.getClipBounds(mDirtyRect);
if (mKeyboard == null) {
return;
}
final boolean drawKeyboardNameText = mShowKeyboardNameOnKeyboard && (mKeyboardNameTextSize > 1f);
final boolean drawHintText = (mHintTextSize > 1) && mShowHintsOnKeyboard;
final boolean useCustomKeyTextColor = false;
final ColorStateList keyTextColor = useCustomKeyTextColor ?
new ColorStateList(new int[][]{{0}}, new int[]{0xFF6666FF})
: mKeyTextColor;
// allow preferences to override theme settings for hint text position
final int hintAlign = mCustomHintGravity == Gravity.NO_GRAVITY ? mThemeHintLabelAlign : mCustomHintGravity & Gravity.HORIZONTAL_GRAVITY_MASK;
final int hintVAlign = mCustomHintGravity == Gravity.NO_GRAVITY ? mThemeHintLabelVAlign : mCustomHintGravity & Gravity.VERTICAL_GRAVITY_MASK;
final Drawable keyBackground = mKeyBackground;
final Rect clipRegion = mClipRegion;
final int kbdPaddingLeft = getPaddingLeft();
final int kbdPaddingTop = getPaddingTop();
final Key[] keys = mKeys;
final Key invalidKey = mInvalidatedKey;
boolean drawSingleKey = false;
if (invalidKey != null && canvas.getClipBounds(clipRegion)) {
// TODO we should use Rect.inset and Rect.contains here.
// Is clipRegion completely contained within the invalidated key?
if (invalidKey.x + kbdPaddingLeft - 1 <= clipRegion.left
&& invalidKey.y + kbdPaddingTop - 1 <= clipRegion.top
&& invalidKey.x + invalidKey.width + kbdPaddingLeft + 1 >= clipRegion.right
&& invalidKey.y + invalidKey.height + kbdPaddingTop + 1 >= clipRegion.bottom) {
drawSingleKey = true;
}
}
for (Key keyBase : keys) {
final AnyKey key = (AnyKey) keyBase;
final boolean keyIsSpace = isSpaceKey(key);
if (drawSingleKey && (invalidKey != key)) {
continue;
}
if (!mDirtyRect.intersects(key.x + kbdPaddingLeft, key.y
+ kbdPaddingTop, key.x + key.width + kbdPaddingLeft, key.y
+ key.height + kbdPaddingTop)) {
continue;
}
int[] drawableState = key.getCurrentDrawableState(mDrawableStatesProvider);
if (keyIsSpace) {
paint.setColor(mKeyboardNameTextColor);
} else {
paint.setColor(keyTextColor.getColorForState(drawableState, 0xFF000000));
}
keyBackground.setState(drawableState);
// Switch the character to uppercase if shift is pressed
CharSequence label = key.label == null ? null : adjustLabelToShiftState(key);
final Rect bounds = keyBackground.getBounds();
if ((key.width != bounds.right) || (key.height != bounds.bottom)) {
keyBackground.setBounds(0, 0, key.width, key.height);
}
canvas.translate(key.x + kbdPaddingLeft, key.y + kbdPaddingTop);
keyBackground.draw(canvas);
if (TextUtils.isEmpty(label)) {
Drawable iconToDraw = getIconToDrawForKey(key, false);
if (iconToDraw != null/* && shouldDrawIcon */) {
//http://developer.android.com/reference/android/graphics/drawable/Drawable.html#getCurrent()
//http://stackoverflow.com/a/103600/1324235
final boolean is9Patch = iconToDraw.getCurrent() instanceof NinePatchDrawable;
// Special handing for the upper-right number hint icons
final int drawableWidth;
final int drawableHeight;
final int drawableX;
final int drawableY;
drawableWidth = is9Patch ? key.width : iconToDraw.getIntrinsicWidth();
drawableHeight = is9Patch ? key.height : iconToDraw.getIntrinsicHeight();
drawableX = (key.width + mKeyBackgroundPadding.left
- mKeyBackgroundPadding.right - drawableWidth) / 2;
drawableY = (key.height + mKeyBackgroundPadding.top
- mKeyBackgroundPadding.bottom - drawableHeight) / 2;
canvas.translate(drawableX, drawableY);
iconToDraw.setBounds(0, 0, drawableWidth, drawableHeight);
iconToDraw.draw(canvas);
canvas.translate(-drawableX, -drawableY);
if (keyIsSpace && drawKeyboardNameText) {
// now a little hack, I'll set the label now, so it get
// drawn.
label = mKeyboardName;
}
} else {
// ho... no icon.
// I'll try to guess the text
label = guessLabelForKey(key.getPrimaryCode());
}
}
if (label != null) {
// For characters, use large font. For labels like "Done", use
// small font.
final FontMetrics fm;
if (keyIsSpace) {
paint.setTextSize(mKeyboardNameTextSize);
paint.setTypeface(Typeface.DEFAULT_BOLD);
if (mKeyboardNameFontMetrics == null) {
mKeyboardNameFontMetrics = paint.getFontMetrics();
}
fm = mKeyboardNameFontMetrics;
} else if (label.length() > 1 && key.getCodesCount() < 2) {
setPaintForLabelText(paint);
if (mLabelFontMetrics == null) mLabelFontMetrics = paint.getFontMetrics();
fm = mLabelFontMetrics;
} else {
setPaintToKeyText(paint);
if (mTextFontMetrics == null) mTextFontMetrics = paint.getFontMetrics();
fm = mTextFontMetrics;
}
if (EmojiUtils.isLabelOfEmoji(label)) {
paint.setTextSize(2f * paint.getTextSize());
}
final float labelHeight = -fm.top;
// Draw a drop shadow for the text
paint.setShadowLayer(mShadowRadius, mShadowOffsetX,
mShadowOffsetY, mShadowColor);
final float textWidth = adjustTextSizeForLabel(paint, label, key.width);
// the center of the drawable space, which is value used
// previously for vertically
// positioning the key label
final float centerY = mKeyBackgroundPadding.top
+ ((key.height - mKeyBackgroundPadding.top - mKeyBackgroundPadding.bottom) / (keyIsSpace ? 3
: 2));// the label on the space is a bit higher
// the X coordinate for the center of the main label text is
// unaffected by the hints
final float textX = mKeyBackgroundPadding.left + (key.width - mKeyBackgroundPadding.left - mKeyBackgroundPadding.right) / 2;
final float textY;
// Some devices (mostly pre-Honeycomb, have issues with RTL text
// drawing.
// Of course, there is no issue with a single character :)
// so, we'll use the RTL secured drawing (via StaticLayout) for
// labels.
if (label.length() > 1 && !mAlwaysUseDrawText) {
// calculate Y coordinate of top of text based on center
// location
textY = centerY - ((labelHeight - paint.descent()) / 2);
canvas.translate(textX, textY);
// RTL fix. But it costs, let do it when in need (more than
// 1 character)
StaticLayout labelText = new StaticLayout(label,
new TextPaint(paint), (int) textWidth,
Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
labelText.draw(canvas);
} else {
// to get Y coordinate of baseline from center of text,
// first add half the height (to get to
// bottom of text), then subtract the part below the
// baseline. Note that fm.top is negative.
textY = centerY + ((labelHeight - paint.descent()) / 2);
canvas.translate(textX, textY);
canvas.drawText(label, 0, label.length(), 0, 0, paint);
}
canvas.translate(-textX, -textY);
// (-)
// Turn off drop shadow
paint.setShadowLayer(0, 0, 0, 0);
}
if (drawHintText) {
if ((key.popupCharacters != null && key.popupCharacters
.length() > 0)
|| (key.popupResId != 0)
|| (key.longPressCode != 0)) {
Align oldAlign = paint.getTextAlign();
String hintText = "";
if (key.hintLabel != null && key.hintLabel.length() > 0) {
hintText = key.hintLabel.toString();
// it is the responsibility of the keyboard layout
// designer to ensure that they do
// not put too many characters in the hint label...
} else if (key.longPressCode != 0) {
if (Character.isLetterOrDigit(key.longPressCode)) {
hintText = Character.toString((char) key.longPressCode);
}
} else if (key.popupCharacters != null) {
final String hintString = key.popupCharacters.toString();
final int hintLength = hintString.length();
if (hintLength <= 3) {
hintText = hintString;
} else {
hintText = hintString.substring(0, 3);
}
}
if (mKeyboard.isShifted()) {
hintText = hintText.toUpperCase(getKeyboard().getLocale());
}
// now draw hint
paint.setTypeface(Typeface.DEFAULT);
paint.setColor(mHintTextColor.getColorForState(drawableState, 0xFF000000));
paint.setTextSize(mHintTextSize);
// get the hint text font metrics so that we know the size
// of the hint when
// we try to position the main label (to try to make sure
// they don't overlap)
if (mHintTextFontMetrics == null) {
mHintTextFontMetrics = paint.getFontMetrics();
}
final float hintX;
final float hintY;
// the (float) 0.5 value is added or subtracted to just give
// a little more room
// in case the theme designer didn't account for the hint
// label location
if (hintAlign == Gravity.LEFT) {
paint.setTextAlign(Align.LEFT);
hintX = mKeyBackgroundPadding.left + 0.5f;
} else if (hintAlign == Gravity.CENTER_HORIZONTAL) {
// center
paint.setTextAlign(Align.CENTER);
hintX = mKeyBackgroundPadding.left
+ (key.width - mKeyBackgroundPadding.left - mKeyBackgroundPadding.right) / 2;
} else {
// right
paint.setTextAlign(Align.RIGHT);
hintX = key.width - mKeyBackgroundPadding.right - 0.5f;
}
if (hintVAlign == Gravity.TOP) {
// above
hintY = mKeyBackgroundPadding.top - mHintTextFontMetrics.top + 0.5f;
} else {
// below
hintY = key.height - mKeyBackgroundPadding.bottom - mHintTextFontMetrics.bottom - 0.5f;
}
canvas.drawText(hintText, hintX, hintY, paint);
paint.setTextAlign(oldAlign);
}
}
canvas.translate(-key.x - kbdPaddingLeft, -key.y - kbdPaddingTop);
}
mInvalidatedKey = null;
mDirtyRect.setEmpty();
}
private float adjustTextSizeForLabel(final Paint paint, final CharSequence label, final int width) {
TextWidthCacheKey cacheKey = new TextWidthCacheKey(label, width);
if (mTextWidthCache.containsKey(cacheKey)) {
return mTextWidthCache.get(cacheKey).setCachedValues(paint);
}
float textSize = paint.getTextSize();
float textWidth = paint.measureText(label, 0, label.length());
// I'm going to try something if the key is too small for the
// text:
// 1) divide the text size by 1.5
// 2) if still too large, divide by 2.5
// 3) show no text
if (textWidth > width) {
textSize = mKeyTextSize / 1.5f;
paint.setTextSize(textSize);
textWidth = paint.measureText(label, 0, label.length());
if (textWidth > width) {
textSize = mKeyTextSize / 2.5f;
paint.setTextSize(textSize);
textWidth = paint.measureText(label, 0, label.length());
if (textWidth > width) {
textSize = 0f;
paint.setTextSize(textSize);
textWidth = paint.measureText(label, 0, label.length());
}
}
}
mTextWidthCache.put(cacheKey, new TextWidthCacheValue(textSize, textWidth));
return textWidth;
}
protected void setPaintForLabelText(Paint paint) {
paint.setTextSize(mLabelTextSize);
paint.setTypeface(Typeface.DEFAULT_BOLD);
}
public void setPaintToKeyText(final Paint paint) {
paint.setTextSize(mKeyTextSize);
paint.setTypeface(mKeyTextStyle);
}
@Override
public void setKeyboardActionType(final int imeOptions) {
if ((imeOptions & EditorInfo.IME_FLAG_NO_ENTER_ACTION) != 0)
//IME_FLAG_NO_ENTER_ACTION:
// Flag of imeOptions: used in conjunction with one of the actions masked by IME_MASK_ACTION.
// If this flag is not set, IMEs will normally replace the "enter" key with the action supplied.
// This flag indicates that the action should not be available in-line as a replacement for the "enter" key.
// Typically this is because the action has such a significant impact or is not recoverable enough
// that accidentally hitting it should be avoided, such as sending a message.
// Note that TextView will automatically set this flag for you on multi-line text views.
{
mKeyboardActionType = EditorInfo.IME_ACTION_NONE;
} else {
mKeyboardActionType = (imeOptions & EditorInfo.IME_MASK_ACTION);
}
// setting the icon/text
setSpecialKeysIconsAndLabels();
}
private void setSpecialKeysIconsAndLabels() {
Key enterKey = findKeyByPrimaryKeyCode(KeyCodes.ENTER);
if (enterKey != null) {
enterKey.icon = null;
enterKey.iconPreview = null;
enterKey.label = null;
((AnyKey) enterKey).shiftedKeyLabel = null;
Drawable icon = getIconToDrawForKey(enterKey, false);
if (icon != null) {
enterKey.icon = icon;
enterKey.iconPreview = icon;
} else {
CharSequence label = guessLabelForKey(enterKey.getPrimaryCode());
enterKey.label = label;
((AnyKey) enterKey).shiftedKeyLabel = label;
}
// making sure something is shown
if (enterKey.icon == null && TextUtils.isEmpty(enterKey.label)) {
Logger.i(TAG, "Wow. Unknown ACTION ID " + mKeyboardActionType
+ ". Will default to ENTER icon.");
// I saw devices (Galaxy Tab 10") which say the action
// type is 255...
// D/ASKKbdViewBase( 3594): setKeyboardActionType
// imeOptions:33554687 action:255
// which means it is not a known ACTION
Drawable enterIcon = getIconForKeyCode(KeyCodes.ENTER);
enterIcon.setState(mDrawableStatesProvider.DRAWABLE_STATE_ACTION_NORMAL);
enterKey.icon = enterIcon;
enterKey.iconPreview = enterIcon;
}
}
//these are dynamic keys
setSpecialKeyIconOrLabel(KeyCodes.MODE_ALPHABET);
setSpecialKeyIconOrLabel(KeyCodes.MODE_SYMOBLS);
setSpecialKeyIconOrLabel(KeyCodes.KEYBOARD_MODE_CHANGE);
mTextWidthCache.clear();
}
private void setSpecialKeyIconOrLabel(int keyCode) {
Key key = findKeyByPrimaryKeyCode(keyCode);
if (key != null) {
if (TextUtils.isEmpty(key.label)) {
if (key.dynamicEmblem == Keyboard.KEY_EMBLEM_TEXT) {
key.label = guessLabelForKey(keyCode);
} else {
key.icon = getIconForKeyCode(keyCode);
}
}
}
}
@NonNull
private CharSequence guessLabelForKey(int keyCode) {
switch (keyCode) {
case KeyCodes.ENTER:
switch (mKeyboardActionType) {
case EditorInfo.IME_ACTION_DONE:
return getContext().getText(R.string.label_done_key);
case EditorInfo.IME_ACTION_GO:
return getContext().getText(R.string.label_go_key);
case EditorInfo.IME_ACTION_NEXT:
return getContext().getText(R.string.label_next_key);
case 0x00000007:// API 11: EditorInfo.IME_ACTION_PREVIOUS:
return getContext().getText(R.string.label_previous_key);
case EditorInfo.IME_ACTION_SEARCH:
return getContext().getText(R.string.label_search_key);
case EditorInfo.IME_ACTION_SEND:
return getContext().getText(R.string.label_send_key);
default:
return "";
}
case KeyCodes.KEYBOARD_MODE_CHANGE:
if (mKeyboard instanceof GenericKeyboard) {
return guessLabelForKey(KeyCodes.MODE_ALPHABET);
} else {
return guessLabelForKey(KeyCodes.MODE_SYMOBLS);
}
case KeyCodes.MODE_ALPHABET:
return mNextAlphabetKeyboardName;
case KeyCodes.MODE_SYMOBLS:
return mNextSymbolsKeyboardName;
case KeyCodes.TAB:
return getContext().getText(R.string.label_tab_key);
case KeyCodes.MOVE_HOME:
return getContext().getText(R.string.label_home_key);
case KeyCodes.MOVE_END:
return getContext().getText(R.string.label_end_key);
case KeyCodes.ARROW_DOWN:
return "▼";
case KeyCodes.ARROW_LEFT:
return "◀";
case KeyCodes.ARROW_RIGHT:
return "▶";
case KeyCodes.ARROW_UP:
return "▲";
default:
return "";
}
}
private Drawable getIconToDrawForKey(Key key, boolean feedback) {
if (key.dynamicEmblem == Keyboard.KEY_EMBLEM_TEXT) {
return null;
}
if (feedback && key.iconPreview != null) {
return key.iconPreview;
}
if (key.icon != null) {
return key.icon;
}
return getIconForKeyCode(key.getPrimaryCode());
}
@Nullable
public Drawable getDrawableForKeyCode(int keyCode) {
Drawable icon = mKeysIcons.get(keyCode);
if (icon == null) {
DrawableBuilder builder = mKeysIconBuilders.get(keyCode);
if (builder == null) {
return null;//no builder assigned to the key-code
}
// building needed icon
Logger.d(TAG, "Building icon for key-code %d", keyCode);
icon = builder.buildDrawable();
if (icon != null) {
mKeysIcons.put(keyCode, icon);
Logger.v(TAG, "Current drawable cache size is %d", mKeysIcons.size());
} else {
Logger.w(TAG, "Can not find drawable for keyCode %d. Context lost?", keyCode);
}
}
return icon;
}
@Nullable
private Drawable getIconForKeyCode(int keyCode) {
Drawable icon = getDrawableForKeyCode(keyCode);
// maybe a drawable state is required
if (icon != null) {
//CHECKSTYLE:OFF: missingswitchdefault
switch (keyCode) {
case KeyCodes.ENTER:
Logger.d(TAG, "Action key action ID is %d", mKeyboardActionType);
switch (mKeyboardActionType) {
case EditorInfo.IME_ACTION_DONE:
icon.setState(mDrawableStatesProvider.DRAWABLE_STATE_ACTION_DONE);
break;
case EditorInfo.IME_ACTION_GO:
icon.setState(mDrawableStatesProvider.DRAWABLE_STATE_ACTION_GO);
break;
case EditorInfo.IME_ACTION_SEARCH:
icon.setState(mDrawableStatesProvider.DRAWABLE_STATE_ACTION_SEARCH);
break;
case EditorInfo.IME_ACTION_NONE:
case EditorInfo.IME_ACTION_UNSPECIFIED:
default:
icon.setState(mDrawableStatesProvider.DRAWABLE_STATE_ACTION_NORMAL);
break;
}
break;
case KeyCodes.SHIFT:
if (mKeyboard.isShiftLocked()) {
icon.setState(mDrawableStatesProvider.DRAWABLE_STATE_MODIFIER_LOCKED);
} else if (mKeyboard.isShifted()) {
icon.setState(mDrawableStatesProvider.DRAWABLE_STATE_MODIFIER_PRESSED);
} else {
icon.setState(mDrawableStatesProvider.DRAWABLE_STATE_MODIFIER_NORMAL);
}
break;
case KeyCodes.CTRL:
if (mKeyboard.isControl()) {
icon.setState(mDrawableStatesProvider.DRAWABLE_STATE_MODIFIER_PRESSED);
} else {
icon.setState(mDrawableStatesProvider.DRAWABLE_STATE_MODIFIER_NORMAL);
}
break;
}
//CHECKSTYLE:ON: missingswitchdefault
}
return icon;
}
void dismissAllKeyPreviews() {
/*for (int trackerIndex = 0, trackersCount = mPointerTrackers.size(); trackerIndex < trackersCount; trackerIndex++) {
PointerTracker tracker = mPointerTrackers.valueAt(trackerIndex);
tracker.updateKey(NOT_A_KEY);
}*/
mKeyPreviewsManager.cancelAllPreviews();
}
@Override
public void hidePreview(int keyIndex, PointerTracker tracker) {
final Key key = tracker.getKey(keyIndex);
if (keyIndex != NOT_A_KEY && key != null) {
mKeyPreviewsManager.hidePreviewForKey(key);
}
}
@Override
public void showPreview(int keyIndex, PointerTracker tracker) {
// We should re-draw popup preview when 1) we need to hide the preview,
// 2) we will show
// the space key preview and 3) pointer moves off the space key to other
// letter key, we
// should hide the preview of the previous key.
final boolean hidePreviewOrShowSpaceKeyPreview = (tracker == null);
// If key changed and preview is on or the key is space (language switch
// is enabled)
final Key key = hidePreviewOrShowSpaceKeyPreview ? null : tracker.getKey(keyIndex);
//this will ensure that in case the key is marked as NO preview, we will just dismiss the previous popup.
if (keyIndex != NOT_A_KEY && key != null) {
Drawable iconToDraw = getIconToDrawForKey(key, true);
// Should not draw hint icon in key preview
if (iconToDraw != null) {
mKeyPreviewsManager.showPreviewForKey(key, iconToDraw);
} else {
CharSequence label = tracker.getPreviewText(key);
if (TextUtils.isEmpty(label)) {
label = guessLabelForKey(key.getPrimaryCode());
}
mKeyPreviewsManager.showPreviewForKey(key, label);
}
}
}
/**
* Requests a redraw of the entire keyboard. Calling {@link #invalidate} is
* not sufficient because the keyboard renders the keys to an off-screen
* buffer and an invalidate() only draws the cached buffer.
*
* @see #invalidateKey(Key)
*/
public void invalidateAllKeys() {
mDirtyRect.union(0, 0, getWidth(), getHeight());
invalidate();
}
/**
* Invalidates a key so that it will be redrawn on the next repaint. Use
* this method if only one key is changing it's content. Any changes that
* affect the position or size of the key may not be honored.
*
* @param key key in the attached {@link Keyboard}.
* @see #invalidateAllKeys
*/
@Override
public void invalidateKey(Key key) {
if (key == null) {
return;
}
mInvalidatedKey = key;
// TODO we should clean up this and record key's region to use in
// onBufferDraw.
mDirtyRect.union(key.x + getPaddingLeft(), key.y + getPaddingTop(),
key.x + key.width + getPaddingLeft(), key.y + key.height
+ getPaddingTop());
// doOnBufferDrawWithMemProtection(mCanvas);
invalidate(key.x + getPaddingLeft(), key.y + getPaddingTop(), key.x
+ key.width + getPaddingLeft(), key.y + key.height
+ getPaddingTop());
}
@NonNull
@Override
public KeyboardDimens getThemedKeyboardDimens() {
return mKeyboardDimens;
}
public float getLabelTextSize() {
return mLabelTextSize;
}
public ColorStateList getKeyTextColor() {
return mKeyTextColor;
}
/**
* Called when a key is long pressed. By default this will open any popup
* keyboard associated with this key through the attributes popupLayout and
* popupCharacters.
*
* @param keyboardAddOn the owning keyboard that starts this long-press operation
* @param key the key that was long pressed
* @return true if the long press is handled, false otherwise. Subclasses
* should call the method on the base class if the subclass doesn't
* wish to handle the call.
*/
protected boolean onLongPress(AddOn keyboardAddOn, Key key, boolean isSticky, @NonNull PointerTracker tracker) {
if (key instanceof AnyKey) {
AnyKey anyKey = (AnyKey) key;
if (anyKey.getKeyTags().size() > 0) {
Object[] tags = anyKey.getKeyTags().toArray();
for (int tagIndex = 0; tagIndex < tags.length; tagIndex++) {
tags[tagIndex] = ":" + tags[tagIndex];
}
String joinedTags = TextUtils.join(", ", tags);
final Toast tagsToast = Toast.makeText(getContext().getApplicationContext(), joinedTags, Toast.LENGTH_SHORT);
tagsToast.setGravity(Gravity.CENTER, 0, 0);
tagsToast.show();
}
if (anyKey.longPressCode != 0) {
getOnKeyboardActionListener().onKey(anyKey.longPressCode, key, 0/*not multi-tap*/, null, true);
if (!anyKey.repeatable) {
onCancelEvent(tracker);
}
return true;
}
}
return false;
}
@SuppressFBWarnings("EI_EXPOSE_REP")
public int[] getLocationInWindow() {
getLocationInWindow(mThisWindowOffset);
return mThisWindowOffset;
}
protected PointerTracker getPointerTracker(@NonNull final MotionEvent motionEvent) {
final int index = MotionEventCompat.getActionIndex(motionEvent);
final int id = motionEvent.getPointerId(index);
return getPointerTracker(id);
}
protected PointerTracker getPointerTracker(final int id) {
final Key[] keys = mKeys;
final OnKeyboardActionListener listener = mKeyboardActionListener;
if (mPointerTrackers.get(id) == null) {
final PointerTracker tracker = new PointerTracker(id, mKeyPressTimingHandler, mKeyDetector, this, mSharedPointerTrackersData);
if (keys != null) {
tracker.setKeyboard(keys, mKeyHysteresisDistance);
}
if (listener != null) {
tracker.setOnKeyboardActionListener(listener);
}
mPointerTrackers.put(id, tracker);
}
return mPointerTrackers.get(id);
}
@Override
public boolean onTouchEvent(@NonNull MotionEvent nativeMotionEvent) {
if (mKeyboard == null)//I mean, if there isn't any keyboard I'm handling, what's the point?
{
return false;
}
final int action = MotionEventCompat.getActionMasked(nativeMotionEvent);
final int pointerCount = nativeMotionEvent.getPointerCount();
if (pointerCount > 1) {
mLastTimeHadTwoFingers = SystemClock.elapsedRealtime();//marking the time. Read isAtTwoFingersState()
}
if (mTouchesAreDisabledTillLastFingerIsUp) {
if (!areTouchesDisabled(nativeMotionEvent)/*this means it was just reset*/) {
mTouchesAreDisabledTillLastFingerIsUp = false;
//continue with onTouchEvent flow.
if (action != MotionEvent.ACTION_DOWN) {
//swallowing the event.
//in case this is a DOWN event, we do want to pass it
return true;
}
} else {
//swallowing touch event until we reset mTouchesAreDisabledTillLastFingerIsUp
return true;
}
}
final long eventTime = nativeMotionEvent.getEventTime();
final int index = MotionEventCompat.getActionIndex(nativeMotionEvent);
final int id = nativeMotionEvent.getPointerId(index);
final int x = (int) nativeMotionEvent.getX(index);
final int y = (int) nativeMotionEvent.getY(index);
if (mKeyPressTimingHandler.isInKeyRepeat()) {
// It will keep being in the key repeating mode while the key is
// being pressed.
if (action == MotionEvent.ACTION_MOVE) {
return true;
}
final PointerTracker tracker = getPointerTracker(id);
// Key repeating timer will be canceled if 2 or more keys are in
// action, and current
// event (UP or DOWN) is non-modifier key.
if (pointerCount > 1 && !tracker.isModifier()) {
mKeyPressTimingHandler.cancelKeyRepeatTimer();
}
// Up event will pass through.
}
if (action == MotionEvent.ACTION_MOVE) {
for (int i = 0; i < pointerCount; i++) {
PointerTracker tracker = getPointerTracker(nativeMotionEvent.getPointerId(i));
tracker.onMoveEvent((int) nativeMotionEvent.getX(i), (int) nativeMotionEvent.getY(i), eventTime);
}
} else {
PointerTracker tracker = getPointerTracker(id);
sendOnXEvent(action, eventTime, x, y, tracker);
}
return true;
}
@NonNull
public final KeyDetector getKeyDetector() {
return mKeyDetector;
}
protected boolean isFirstDownEventInsideSpaceBar() {
return false;
}
private void sendOnXEvent(final int action, final long eventTime,
final int x, final int y, PointerTracker tracker) {
//CHECKSTYLE:OFF: missingswitchdefault
switch (action) {
case MotionEvent.ACTION_DOWN:
case 0x00000005:// MotionEvent.ACTION_POINTER_DOWN:
onDownEvent(tracker, x, y, eventTime);
break;
case MotionEvent.ACTION_UP:
case 0x00000006:// MotionEvent.ACTION_POINTER_UP:
onUpEvent(tracker, x, y, eventTime);
break;
case MotionEvent.ACTION_CANCEL:
onCancelEvent(tracker);
break;
}
//CHECKSTYLE:ON: missingswitchdefault
}
protected void onDownEvent(PointerTracker tracker, int x, int y,
long eventTime) {
if (tracker.isOnModifierKey(x, y)) {
// Before processing a down event of modifier key, all pointers
// already being tracked
// should be released.
mPointerQueue.releaseAllPointersExcept(tracker, eventTime);
}
tracker.onDownEvent(x, y, eventTime);
mPointerQueue.add(tracker);
}
protected void onUpEvent(PointerTracker tracker, int x, int y,
long eventTime) {
if (tracker.isModifier()) {
// Before processing an up event of modifier key, all pointers
// already being tracked
// should be released.
mPointerQueue.releaseAllPointersExcept(tracker, eventTime);
} else {
int index = mPointerQueue.lastIndexOf(tracker);
if (index >= 0) {
mPointerQueue.releaseAllPointersOlderThan(tracker, eventTime);
} else {
Logger.w(TAG, "onUpEvent: corresponding down event not found for pointer %d", tracker.mPointerId);
return;
}
}
tracker.onUpEvent(x, y, eventTime);
mPointerQueue.remove(tracker);
}
protected void onCancelEvent(PointerTracker tracker) {
tracker.onCancelEvent();
mPointerQueue.remove(tracker);
}
@Nullable
protected Key findKeyByPrimaryKeyCode(int keyCode) {
if (getKeyboard() == null) {
return null;
}
for (Key key : getKeyboard().getKeys()) {
if (key.getPrimaryCode() == keyCode) return key;
}
return null;
}
@CallSuper
@Override
public boolean resetInputView() {
mKeyPreviewsManager.cancelAllPreviews();
mKeyPressTimingHandler.cancelAllMessages();
mPointerQueue.cancelAllPointers();
return false;
}
@Override
public void onStartTemporaryDetach() {
mKeyPreviewsManager.cancelAllPreviews();
mKeyPressTimingHandler.cancelAllMessages();
super.onStartTemporaryDetach();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
// releasing some memory
for (int i = 0; i < mKeysIcons.size(); i++) {
Drawable d = mKeysIcons.valueAt(i);
CompatUtils.unbindDrawable(d);
}
mKeysIcons.clear();
}
@Override
public void onViewNotRequired() {
mDisposables.dispose();
resetInputView();
// cleaning up memory
CompatUtils.unbindDrawable(getBackground());
for (int i = 0; i < mKeysIcons.size(); i++) {
Drawable d = mKeysIcons.valueAt(i);
CompatUtils.unbindDrawable(d);
}
mKeysIcons.clear();
mKeysIconBuilders.clear();
CompatUtils.unbindDrawable(mKeyBackground);
mKeyPreviewsManager.destroy();
mKeyboardActionListener = null;
mKeyboard = null;
}
@Override
public void setWatermark(@Nullable String text) {
}
private void updatePrefSettings(final String overrideValue) {
switch (overrideValue) {
case "auto":
mTextCaseForceOverrideType = 0;
break;
case "lower":
mTextCaseForceOverrideType = 1;
break;
case "upper":
mTextCaseForceOverrideType = 2;
break;
default:
mTextCaseForceOverrideType = -1;
break;
}
}
protected static class KeyPressTimingHandler extends Handler {
private static final int MSG_REPEAT_KEY = 3;
private static final int MSG_LONG_PRESS_KEY = 4;
private final WeakReference<AnyKeyboardViewBase> mKeyboard;
private boolean mInKeyRepeat;
KeyPressTimingHandler(AnyKeyboardViewBase keyboard) {
mKeyboard = new WeakReference<>(keyboard);
}
@Override
public void handleMessage(Message msg) {
AnyKeyboardViewBase keyboard = mKeyboard.get();
if (keyboard == null) {
return;
}
final PointerTracker tracker = (PointerTracker) msg.obj;
Key keyForLongPress = tracker.getKey(msg.arg1);
switch (msg.what) {
case MSG_REPEAT_KEY:
if (keyForLongPress != null && keyForLongPress instanceof AnyKey && ((AnyKey) keyForLongPress).longPressCode != 0) {
keyboard.onLongPress(keyboard.getKeyboard().getKeyboardAddOn(), keyForLongPress, false, tracker);
} else {
tracker.repeatKey(msg.arg1);
}
startKeyRepeatTimer(keyboard.mKeyRepeatInterval, msg.arg1, tracker);
break;
case MSG_LONG_PRESS_KEY:
if (keyForLongPress != null) {
keyboard.onLongPress(keyboard.getKeyboard().getKeyboardAddOn(), keyForLongPress, false, tracker);
}
break;
default:
super.handleMessage(msg);
break;
}
}
public void startKeyRepeatTimer(long delay, int keyIndex, PointerTracker tracker) {
mInKeyRepeat = true;
sendMessageDelayed(
obtainMessage(MSG_REPEAT_KEY, keyIndex, 0, tracker), delay);
}
void cancelKeyRepeatTimer() {
mInKeyRepeat = false;
removeMessages(MSG_REPEAT_KEY);
}
boolean isInKeyRepeat() {
return mInKeyRepeat;
}
public void startLongPressTimer(long delay, int keyIndex, PointerTracker tracker) {
removeMessages(MSG_LONG_PRESS_KEY);
sendMessageDelayed(obtainMessage(MSG_LONG_PRESS_KEY, keyIndex, 0, tracker), delay);
}
public void cancelLongPressTimer() {
removeMessages(MSG_LONG_PRESS_KEY);
}
public void cancelAllMessages() {
cancelKeyRepeatTimer();
cancelLongPressTimer();
}
}
static class PointerQueue {
private ArrayList<PointerTracker> mQueue = new ArrayList<>();
public void add(PointerTracker tracker) {
mQueue.add(tracker);
}
int lastIndexOf(PointerTracker tracker) {
ArrayList<PointerTracker> queue = mQueue;
for (int index = queue.size() - 1; index >= 0; index--) {
PointerTracker t = queue.get(index);
if (t == tracker) {
return index;
}
}
return -1;
}
void releaseAllPointersOlderThan(final PointerTracker tracker, final long eventTime) {
//doing a copy to prevent ConcurrentModificationException
PointerTracker[] trackers = mQueue.toArray(new PointerTracker[mQueue.size()]);
for (PointerTracker t : trackers) {
if (t == tracker) break;
if (!t.isModifier()) {
t.onUpEvent(t.getLastX(), t.getLastY(), eventTime);
t.setAlreadyProcessed();
mQueue.remove(t);
}
}
}
void cancelAllPointers() {
for (PointerTracker t : mQueue) {
t.onCancelEvent();
}
mQueue.clear();
}
void releaseAllPointersExcept(@Nullable PointerTracker tracker, long eventTime) {
for (PointerTracker t : mQueue) {
if (t == tracker) {
continue;
}
t.onUpEvent(t.getLastX(), t.getLastY(), eventTime);
t.setAlreadyProcessed();
}
mQueue.clear();
if (tracker != null) mQueue.add(tracker);
}
public void remove(PointerTracker tracker) {
mQueue.remove(tracker);
}
public int size() {
return mQueue.size();
}
}
private static class KeyboardDrawOperation implements MemRelatedOperation {
private final AnyKeyboardViewBase mView;
private final Paint mPaint;
private Canvas mCanvas;
KeyboardDrawOperation(AnyKeyboardViewBase keyboard) {
mView = keyboard;
mPaint = keyboard.mPaint;
}
public void setCanvas(Canvas canvas) {
mCanvas = canvas;
}
@Override
public void operation() {
mView.onBufferDraw(mCanvas, mPaint);
}
}
private static class TextWidthCacheValue {
private final float mTextSize;
private final float mTextWidth;
private TextWidthCacheValue(float textSize, float textWidth) {
mTextSize = textSize;
mTextWidth = textWidth;
}
float setCachedValues(Paint paint) {
paint.setTextSize(mTextSize);
return mTextWidth;
}
}
private static class TextWidthCacheKey {
private final CharSequence mLabel;
private final int mKeyWidth;
private TextWidthCacheKey(CharSequence label, int keyWidth) {
mLabel = label;
mKeyWidth = keyWidth;
}
@Override
public int hashCode() {
return mLabel.hashCode() + mKeyWidth;
}
@Override
public boolean equals(Object o) {
return (o instanceof TextWidthCacheKey
&& ((TextWidthCacheKey) o).mKeyWidth == mKeyWidth
&& ((TextWidthCacheKey) o).mLabel.equals(mLabel));
}
}
private static class NullKeyPreviewsManager implements KeyPreviewsController {
@Override
public void hidePreviewForKey(Key key) {
}
@Override
public void showPreviewForKey(Key key, Drawable icon) {
}
@Override
public void showPreviewForKey(Key key, CharSequence label) {
}
@Override
public void cancelAllPreviews() {
}
@Override
public void destroy() {
}
}
}
|
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The contents of this file are subject to the terms of either the Universal Permissive License
* v 1.0 as shown at http://oss.oracle.com/licenses/upl
*
* or the following license:
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions
* and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmc.agent.converters.test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.instrument.IllegalClassFormatException;
import java.util.concurrent.atomic.AtomicInteger;
import javax.xml.stream.XMLStreamException;
import org.junit.Test;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Type;
import org.objectweb.asm.util.CheckClassAdapter;
import org.objectweb.asm.util.TraceClassVisitor;
import org.openjdk.jmc.agent.TransformRegistry;
import org.openjdk.jmc.agent.Transformer;
import org.openjdk.jmc.agent.impl.DefaultTransformRegistry;
import org.openjdk.jmc.agent.test.util.TestToolkit;
public class TestConverterTransforms {
private static AtomicInteger runCount = new AtomicInteger(0);
public static String getTemplate() throws IOException {
return TestToolkit.readTemplate(TestConverterTransforms.class, TestToolkit.DEFAULT_TEMPLATE_NAME);
}
@Test
public void testRunConverterTransforms() throws XMLStreamException, IllegalClassFormatException, IOException {
TransformRegistry registry = DefaultTransformRegistry.from(TestToolkit.getProbesXMLFromTemplate(getTemplate(),
"testRunConverterTransforms" + runCount.getAndIncrement())); //$NON-NLS-1$
assertTrue(registry.hasPendingTransforms(Type.getInternalName(InstrumentMeConverter.class)));
Transformer jfrTransformer = new Transformer(registry);
byte[] transformedClass = jfrTransformer.transform(InstrumentMeConverter.class.getClassLoader(),
Type.getInternalName(InstrumentMeConverter.class), InstrumentMeConverter.class, null,
TestToolkit.getByteCode(InstrumentMeConverter.class));
assertNotNull(transformedClass);
assertFalse(registry.hasPendingTransforms(Type.getInternalName(InstrumentMeConverter.class)));
TraceClassVisitor visitor = new TraceClassVisitor(
new PrintWriter(new BufferedOutputStream(new ByteArrayOutputStream())));
CheckClassAdapter checkAdapter = new CheckClassAdapter(visitor);
ClassReader reader = new ClassReader(transformedClass);
reader.accept(checkAdapter, 0);
}
public static void main(String[] args) throws XMLStreamException, IOException, IllegalClassFormatException {
TransformRegistry registry = DefaultTransformRegistry.from(TestToolkit.getProbesXMLFromTemplate(getTemplate(),
"testRunConverterTransforms" + runCount.getAndIncrement())); //$NON-NLS-1$
assertTrue(registry.hasPendingTransforms(Type.getInternalName(InstrumentMeConverter.class)));
Transformer jfrTransformer = new Transformer(registry);
byte[] transformedClass = jfrTransformer.transform(InstrumentMeConverter.class.getClassLoader(),
Type.getInternalName(InstrumentMeConverter.class), InstrumentMeConverter.class, null,
TestToolkit.getByteCode(InstrumentMeConverter.class));
assertNotNull(transformedClass);
assertFalse(registry.hasPendingTransforms(Type.getInternalName(InstrumentMeConverter.class)));
TraceClassVisitor visitor = new TraceClassVisitor(new PrintWriter(System.out));
CheckClassAdapter checkAdapter = new CheckClassAdapter(visitor);
ClassReader reader = new ClassReader(transformedClass);
reader.accept(checkAdapter, 0);
System.out.println(registry);
}
}
|
package com.shynieke.coupons.items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
public class CouponItem extends Item {
public CouponItem(Properties properties) {
super(properties);
}
@Override
public int getBurnTime(ItemStack itemStack) {
return 200;
}
}
|
package com.hrdzkj.optional;
public interface Predicate<T> {
boolean test(T subject);
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.ml.common.datastream;
import org.apache.flink.api.common.functions.MapPartitionFunction;
import org.apache.flink.api.common.functions.RichMapPartitionFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.ExecutionCheckpointingOptions;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;
import org.apache.flink.util.NumberSequenceIterator;
import org.apache.commons.collections.IteratorUtils;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertNotNull;
/** Tests the {@link DataStreamUtils}. */
public class DataStreamUtilsTest {
private StreamExecutionEnvironment env;
@Before
public void before() {
Configuration config = new Configuration();
config.set(ExecutionCheckpointingOptions.ENABLE_CHECKPOINTS_AFTER_TASKS_FINISH, true);
env = StreamExecutionEnvironment.getExecutionEnvironment(config);
env.setParallelism(4);
env.enableCheckpointing(100);
env.setRestartStrategy(RestartStrategies.noRestart());
}
@Test
public void testMapPartition() throws Exception {
DataStream<Long> dataStream =
env.fromParallelCollection(new NumberSequenceIterator(0L, 19L), Types.LONG);
DataStream<Integer> countsPerPartition =
DataStreamUtils.mapPartition(dataStream, new TestMapPartitionFunc());
List<Integer> counts = IteratorUtils.toList(countsPerPartition.executeAndCollect());
assertArrayEquals(
new int[] {5, 5, 5, 5}, counts.stream().mapToInt(Integer::intValue).toArray());
}
/** A simple implementation for a {@link MapPartitionFunction}. */
private static class TestMapPartitionFunc extends RichMapPartitionFunction<Long, Integer> {
public void mapPartition(Iterable<Long> values, Collector<Integer> out) {
assertNotNull(getRuntimeContext());
int cnt = 0;
for (long ignored : values) {
cnt++;
}
out.collect(cnt);
}
}
}
|
/*
* Copyright 2015 Martynas Jusevičius <martynas@atomgraph.com>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.atomgraph.processor.exception;
/**
*
* @author Martynas Jusevičius <martynas@atomgraph.com>
*/
public class OntologyException extends RuntimeException
{
public OntologyException()
{
}
public OntologyException(String message)
{
super(message);
}
public OntologyException(String message, Throwable cause)
{
super(message, cause);
}
public OntologyException(Throwable cause)
{
super(cause);
}
public OntologyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace)
{
super(message, cause, enableSuppression, writableStackTrace);
}
}
|
/*
* Copyright (C) 2014-2021 Philip Helger (www.helger.com)
* philip[at]helger[dot]com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.helger.xml.microdom.convert;
import javax.annotation.Nonnull;
/**
* This is the callback interface implemented by
* {@link MicroTypeConverterRegistry} for registration via the SPI interface.
*
* @author Philip Helger
*/
public interface IMicroTypeConverterRegistry
{
/**
* Register a new type converter.
*
* @param aClass
* The class for which the converter is meant. May not be
* <code>null</code>.
* @param aConverter
* The converter to be registered. May not be <code>null</code>.
* @param <T>
* Data type
*/
<T> void registerMicroElementTypeConverter (@Nonnull Class <T> aClass, @Nonnull IMicroTypeConverter <T> aConverter);
}
|
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.rest.repository.patch.factories.impl;
import org.dspace.app.rest.exception.DSpaceBadRequestException;
import org.dspace.app.rest.model.EPersonRest;
import org.dspace.app.rest.model.patch.Operation;
import org.springframework.stereotype.Component;
/**
* Implementation for EPerson canLogin patches.
*
* Example: <code>
* curl -X PATCH http://${dspace.server.url}/api/epersons/eperson/<:id-eperson> -H "
* Content-Type: application/json" -d '[{ "op": "replace", "path": "
* /canLogin", "value": true|false]'
* </code>
*
* @author Michael Spalti
*/
@Component
public class EPersonLoginReplaceOperation extends ReplacePatchOperation<EPersonRest, Boolean>
implements ResourcePatchOperation<EPersonRest> {
@Override
public EPersonRest replace(EPersonRest eperson, Operation operation) {
Boolean canLogin = getBooleanOperationValue(operation.getValue());
eperson.setCanLogIn(canLogin);
return eperson;
}
@Override
void checkModelForExistingValue(EPersonRest resource, Operation operation) {
if ((Object) resource.isCanLogIn() == null) {
throw new DSpaceBadRequestException("Attempting to replace a non-existent value.");
}
}
@Override
protected Class<Boolean[]> getArrayClassForEvaluation() {
return Boolean[].class;
}
@Override
protected Class<Boolean> getClassForEvaluation() {
return Boolean.class;
}
}
|
package elasta.orm.query.read.builder.impl;
import elasta.orm.entity.core.Field;
import elasta.orm.query.expression.PathExpression;
import elasta.orm.query.read.builder.ex.ObjectReaderException;
import elasta.orm.query.read.impl.FieldAndIndexPair;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import static elasta.commons.Utils.not;
/**
* Created by sohan on 5/1/2017.
*/
final class ReaderBuilder {
private final ObjectReaderBuilderImpl objectReaderBuilder;
final Map<PathExpression, ObjectReaderBuilderImpl.PathInfo> map = new HashMap<>();
ReaderBuilder(ObjectReaderBuilderImpl objectReaderBuilder) {
Objects.requireNonNull(objectReaderBuilder);
this.objectReaderBuilder = objectReaderBuilder;
}
public Map<PathExpression, ObjectReaderBuilderImpl.PathInfo> build() {
for (int index = 0; index < objectReaderBuilder.fieldExpressions.size(); index++) {
final PathExpression pathExpression = toFullPathExp(
objectReaderBuilder.fieldExpressions.get(index).toPathExpression()
);
process(pathExpression, index);
}
return map;
}
private void process(PathExpression pathExpression, int index) {
List<String> parts = pathExpression.parts();
String entity = objectReaderBuilder.rootEntity;
for (int i = 1, end = parts.size() - 1; i < end; i++) {
String fieldName = parts.get(i);
Field field = objectReaderBuilder.helper.getField(entity, fieldName);
final ObjectReaderBuilderImpl.PathInfo pathInfo = getOrCreatePathInfo(pathExpression.subPath(0, i));
switch (field.getJavaType()) {
case OBJECT: {
pathInfo.directRelationsBuilder.add(
pathExpression.subPath(0, i + 1)
);
}
break;
case ARRAY: {
pathInfo.indirectRelationsBuilder.add(
pathExpression.subPath(0, i + 1)
);
}
break;
}
entity = field.getRelationship().get().getEntity();
}
Field field = objectReaderBuilder.helper.getField(entity, pathExpression.last());
ObjectReaderBuilderImpl.PathInfo pathInfo = getOrCreatePathInfo(pathExpression.subPath(0, pathExpression.size() - 1));
if (Objects.equals(objectReaderBuilder.helper.getPrimaryKey(entity), field.getName())) {
pathInfo.setPrimaryKeyIndex(index);
}
pathInfo
.fieldAndIndexPairsBuilder
.add(
new FieldAndIndexPair(field.getName(), index)
)
;
}
private PathExpression toFullPathExp(PathExpression pathExpression) {
if (not(pathExpression.startsWith(objectReaderBuilder.rootAlias))) {
PathExpression fullPath = objectReaderBuilder.aliasToFullPathExpressionMap.get(pathExpression.root());
if (fullPath == null) {
throw new ObjectReaderException("Invalid path expression '" + pathExpression + "' not found in the aliasToFullPathExpressionMap");
}
return fullPath.concat(
pathExpression.subPath(1, pathExpression.size())
);
}
return pathExpression;
}
private ObjectReaderBuilderImpl.PathInfo getOrCreatePathInfo(PathExpression pathExpression) {
ObjectReaderBuilderImpl.PathInfo pathInfo = map.get(pathExpression);
if (pathInfo == null) {
map.put(pathExpression, pathInfo = new ObjectReaderBuilderImpl.PathInfo(objectReaderBuilder.helper, objectReaderBuilder.rootEntity));
}
return pathInfo;
}
}
|
import java.util.Scanner;
public class StaticBlock {
static int B;
static int H ;
static boolean flag = true;
static {
Scanner sc=new Scanner(System.in);
boolean flag=true;
int B = sc.nextInt();
int H = sc.nextInt();
if(B>0 && H>0) {
flag=true;
}
else {
flag=false;
System.out.println("java.lang.Exception: Breadth and height must be positive");
}
}
public static void main(String[] args){
if(flag){
int area=B*H;
System.out.print(area);
}
}//end of main
}//end of class
|
package com.example.aop.dto;
public class User {
private String id;
private String pw;
private String email;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPw() {
return pw;
}
public void setPw(String pw) {
this.pw = pw;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"id='" + id + '\'' +
", pw='" + pw + '\'' +
", email='" + email + '\'' +
'}';
}
}
|
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author sajid
*/
public class ResumeBuilder extends javax.swing.JFrame {
/**
* Creates new form ResumeBuildedr
*/
public ResumeBuilder() {
initComponents();
BackgroundProceed1.setVisible(false);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
ProceedFirst = new javax.swing.JButton();
Github = new javax.swing.JTextField();
Linkedin = new javax.swing.JTextField();
PhoneNum = new javax.swing.JTextField();
Email = new javax.swing.JTextField();
Name = new javax.swing.JTextField();
BackgroundProceed1 = new javax.swing.JLabel();
BackgroundMain = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
ProceedFirst.setText("jButton1");
ProceedFirst.setBorderPainted(false);
ProceedFirst.setContentAreaFilled(false);
ProceedFirst.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
ProceedFirstMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
ProceedFirstMouseExited(evt);
}
});
ProceedFirst.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProceedFirstActionPerformed(evt);
}
});
getContentPane().add(ProceedFirst, new org.netbeans.lib.awtextra.AbsoluteConstraints(850, 670, 150, 160));
Github.setFont(new java.awt.Font("Segoe UI Black", 0, 24)); // NOI18N
Github.setBorder(null);
getContentPane().add(Github, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 713, 650, 40));
Linkedin.setFont(new java.awt.Font("Segoe UI Black", 0, 24)); // NOI18N
Linkedin.setBorder(null);
getContentPane().add(Linkedin, new org.netbeans.lib.awtextra.AbsoluteConstraints(870, 560, 650, 40));
PhoneNum.setFont(new java.awt.Font("Segoe UI Black", 0, 24)); // NOI18N
PhoneNum.setBorder(null);
PhoneNum.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PhoneNumActionPerformed(evt);
}
});
getContentPane().add(PhoneNum, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 560, 650, 40));
Email.setFont(new java.awt.Font("Segoe UI Black", 0, 24)); // NOI18N
Email.setBorder(null);
getContentPane().add(Email, new org.netbeans.lib.awtextra.AbsoluteConstraints(870, 400, 650, 40));
Name.setFont(new java.awt.Font("Segoe UI Black", 0, 24)); // NOI18N
Name.setBorder(null);
Name.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
NameActionPerformed(evt);
}
});
getContentPane().add(Name, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 402, 650, 40));
BackgroundProceed1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/resume_proceed1.png"))); // NOI18N
getContentPane().add(BackgroundProceed1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1));
BackgroundMain.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/resume_main.png"))); // NOI18N
getContentPane().add(BackgroundMain, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1));
pack();
}// </editor-fold>//GEN-END:initComponents
private void PhoneNumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PhoneNumActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_PhoneNumActionPerformed
private void NameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NameActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_NameActionPerformed
private void ProceedFirstActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProceedFirstActionPerformed
try {
StoreInfoFirst();
} catch (FileNotFoundException ex) {
Logger.getLogger(ResumeBuilder.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(ResumeBuilder.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_ProceedFirstActionPerformed
private void ProceedFirstMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ProceedFirstMouseEntered
BackgroundProceed1.setVisible(true);
}//GEN-LAST:event_ProceedFirstMouseEntered
private void ProceedFirstMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ProceedFirstMouseExited
BackgroundProceed1.setVisible(false);
}//GEN-LAST:event_ProceedFirstMouseExited
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ResumeBuilder.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ResumeBuilder.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ResumeBuilder.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ResumeBuilder.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ResumeBuilder().setVisible(true);
}
});
}
void StoreInfoFirst() throws FileNotFoundException, UnsupportedEncodingException {
PrintWriter writer = new PrintWriter("data/info.txt", "UTF-8");
writer.println(Name.getText());
writer.println(Email.getText());
writer.println(PhoneNum.getText());
writer.println(Linkedin.getText());
writer.println(Github.getText());
writer.close();
}
void StoreInfoSecond() throws FileNotFoundException, UnsupportedEncodingException {
PrintWriter writer = new PrintWriter("data/info.txt", "UTF-8");
writer.println(Name.getText());
writer.println(Email.getText());
writer.println(PhoneNum.getText());
writer.println(Linkedin.getText());
writer.println(Github.getText());
writer.close();
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel BackgroundMain;
private javax.swing.JLabel BackgroundProceed1;
private javax.swing.JTextField Email;
private javax.swing.JTextField Github;
private javax.swing.JTextField Linkedin;
private javax.swing.JTextField Name;
private javax.swing.JTextField PhoneNum;
private javax.swing.JButton ProceedFirst;
// End of variables declaration//GEN-END:variables
}
|
package com.example.sagar.helpthem;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
|
/*
* Copyright (c) 2017-2021 Nitrite author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dizitart.no2.integration.repository.data;
import org.dizitart.no2.collection.Document;
import org.dizitart.no2.common.mapper.Mappable;
import org.dizitart.no2.common.mapper.NitriteMapper;
import org.dizitart.no2.repository.annotations.Id;
/**
* @author Anindya Chatterjee.
*/
public class WithPublicField implements Mappable {
@Id
public String name;
public long number;
@Override
public Document write(NitriteMapper mapper) {
return Document.createDocument("name", name)
.put("number", number);
}
@Override
public void read(NitriteMapper mapper, Document document) {
name = document.get("name", String.class);
number = document.get("number", Long.class);
}
}
|
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.android.voicemail.impl.sync;
import android.annotation.TargetApi;
import android.content.Context;
import android.net.Network;
import android.net.Uri;
import android.os.Build.VERSION_CODES;
import android.support.v4.os.BuildCompat;
import android.telecom.PhoneAccountHandle;
import android.text.TextUtils;
import android.util.ArrayMap;
import com.android.dialer.logging.DialerImpression;
import com.android.voicemail.VoicemailComponent;
import com.android.voicemail.impl.ActivationTask;
import com.android.voicemail.impl.Assert;
import com.android.voicemail.impl.OmtpEvents;
import com.android.voicemail.impl.OmtpVvmCarrierConfigHelper;
import com.android.voicemail.impl.Voicemail;
import com.android.voicemail.impl.VoicemailStatus;
import com.android.voicemail.impl.VvmLog;
import com.android.voicemail.impl.fetch.VoicemailFetchedCallback;
import com.android.voicemail.impl.imap.ImapHelper;
import com.android.voicemail.impl.imap.ImapHelper.InitializingException;
import com.android.voicemail.impl.mail.store.ImapFolder.Quota;
import com.android.voicemail.impl.scheduling.BaseTask;
import com.android.voicemail.impl.settings.VisualVoicemailSettingsUtil;
import com.android.voicemail.impl.sync.VvmNetworkRequest.NetworkWrapper;
import com.android.voicemail.impl.sync.VvmNetworkRequest.RequestFailedException;
import com.android.voicemail.impl.utils.LoggerUtils;
import com.android.voicemail.impl.utils.VoicemailDatabaseUtil;
import java.util.List;
import java.util.Map;
/** Sync OMTP visual voicemail. */
@TargetApi(VERSION_CODES.O)
public class OmtpVvmSyncService {
private static final String TAG = OmtpVvmSyncService.class.getSimpleName();
/** Signifies a sync with both uploading to the server and downloading from the server. */
public static final String SYNC_FULL_SYNC = "full_sync";
/** Only upload to the server. */
public static final String SYNC_UPLOAD_ONLY = "upload_only";
/** Only download from the server. */
public static final String SYNC_DOWNLOAD_ONLY = "download_only";
/** Only download single voicemail transcription. */
public static final String SYNC_DOWNLOAD_ONE_TRANSCRIPTION = "download_one_transcription";
/** Threshold for whether we should archive and delete voicemails from the remote VM server. */
private static final float AUTO_DELETE_ARCHIVE_VM_THRESHOLD = 0.75f;
private final Context mContext;
private VoicemailsQueryHelper mQueryHelper;
public OmtpVvmSyncService(Context context) {
mContext = context;
mQueryHelper = new VoicemailsQueryHelper(mContext);
}
public void sync(
BaseTask task,
String action,
PhoneAccountHandle phoneAccount,
Voicemail voicemail,
VoicemailStatus.Editor status) {
Assert.isTrue(phoneAccount != null);
VvmLog.v(TAG, "Sync requested: " + action + " - for account: " + phoneAccount);
setupAndSendRequest(task, phoneAccount, voicemail, action, status);
}
private void setupAndSendRequest(
BaseTask task,
PhoneAccountHandle phoneAccount,
Voicemail voicemail,
String action,
VoicemailStatus.Editor status) {
if (!VisualVoicemailSettingsUtil.isEnabled(mContext, phoneAccount)) {
VvmLog.v(TAG, "Sync requested for disabled account");
return;
}
if (!VvmAccountManager.isAccountActivated(mContext, phoneAccount)) {
ActivationTask.start(mContext, phoneAccount, null);
return;
}
OmtpVvmCarrierConfigHelper config = new OmtpVvmCarrierConfigHelper(mContext, phoneAccount);
LoggerUtils.logImpressionOnMainThread(mContext, DialerImpression.Type.VVM_SYNC_STARTED);
// DATA_IMAP_OPERATION_STARTED posting should not be deferred. This event clears all data
// channel errors, which should happen when the task starts, not when it ends. It is the
// "Sync in progress..." status.
config.handleEvent(
VoicemailStatus.edit(mContext, phoneAccount), OmtpEvents.DATA_IMAP_OPERATION_STARTED);
try (NetworkWrapper network = VvmNetworkRequest.getNetwork(config, phoneAccount, status)) {
if (network == null) {
VvmLog.e(TAG, "unable to acquire network");
task.fail();
return;
}
doSync(task, network.get(), phoneAccount, voicemail, action, status);
} catch (RequestFailedException e) {
config.handleEvent(status, OmtpEvents.DATA_NO_CONNECTION_CELLULAR_REQUIRED);
task.fail();
}
}
private void doSync(
BaseTask task,
Network network,
PhoneAccountHandle phoneAccount,
Voicemail voicemail,
String action,
VoicemailStatus.Editor status) {
try (ImapHelper imapHelper = new ImapHelper(mContext, phoneAccount, network, status)) {
boolean success;
if (voicemail == null) {
success = syncAll(action, imapHelper, phoneAccount);
} else {
success = syncOne(imapHelper, voicemail, phoneAccount);
}
if (success) {
// TODO: b/30569269 failure should interrupt all subsequent task via exceptions
imapHelper.updateQuota();
autoDeleteAndArchiveVM(imapHelper, phoneAccount);
imapHelper.handleEvent(OmtpEvents.DATA_IMAP_OPERATION_COMPLETED);
LoggerUtils.logImpressionOnMainThread(mContext, DialerImpression.Type.VVM_SYNC_COMPLETED);
} else {
task.fail();
}
} catch (InitializingException e) {
VvmLog.w(TAG, "Can't retrieve Imap credentials.", e);
return;
}
}
/**
* If the VM quota exceeds {@value AUTO_DELETE_ARCHIVE_VM_THRESHOLD}, we should archive the VMs
* and delete them from the server to ensure new VMs can be received.
*/
private void autoDeleteAndArchiveVM(
ImapHelper imapHelper, PhoneAccountHandle phoneAccountHandle) {
if (!isArchiveAllowedAndEnabled(mContext, phoneAccountHandle)) {
VvmLog.i(TAG, "autoDeleteAndArchiveVM is turned off");
LoggerUtils.logImpressionOnMainThread(
mContext, DialerImpression.Type.VVM_ARCHIVE_AUTO_DELETE_TURNED_OFF);
return;
}
Quota quotaOnServer = imapHelper.getQuota();
if (quotaOnServer == null) {
LoggerUtils.logImpressionOnMainThread(
mContext, DialerImpression.Type.VVM_ARCHIVE_AUTO_DELETE_FAILED_DUE_TO_FAILED_QUOTA_CHECK);
VvmLog.e(TAG, "autoDeleteAndArchiveVM failed - Can't retrieve Imap quota.");
return;
}
if ((float) quotaOnServer.occupied / (float) quotaOnServer.total
> AUTO_DELETE_ARCHIVE_VM_THRESHOLD) {
deleteAndArchiveVM(imapHelper, quotaOnServer);
imapHelper.updateQuota();
LoggerUtils.logImpressionOnMainThread(
mContext, DialerImpression.Type.VVM_ARCHIVE_AUTO_DELETED_VM_FROM_SERVER);
} else {
VvmLog.i(TAG, "no need to archive and auto delete VM, quota below threshold");
}
}
private static boolean isArchiveAllowedAndEnabled(
Context context, PhoneAccountHandle phoneAccountHandle) {
if (!VoicemailComponent.get(context)
.getVoicemailClient()
.isVoicemailArchiveAvailable(context)) {
VvmLog.i("isArchiveAllowedAndEnabled", "voicemail archive is not available");
return false;
}
if (!VisualVoicemailSettingsUtil.isArchiveEnabled(context, phoneAccountHandle)) {
VvmLog.i("isArchiveAllowedAndEnabled", "voicemail archive is turned off");
return false;
}
if (!VisualVoicemailSettingsUtil.isEnabled(context, phoneAccountHandle)) {
VvmLog.i("isArchiveAllowedAndEnabled", "voicemail is turned off");
return false;
}
return true;
}
private void deleteAndArchiveVM(ImapHelper imapHelper, Quota quotaOnServer) {
// Archive column should only be used for 0 and above
Assert.isTrue(BuildCompat.isAtLeastO());
// The number of voicemails that exceed our threshold and should be deleted from the server
int numVoicemails =
quotaOnServer.occupied - (int) (AUTO_DELETE_ARCHIVE_VM_THRESHOLD * quotaOnServer.total);
List<Voicemail> oldestVoicemails = mQueryHelper.oldestVoicemailsOnServer(numVoicemails);
VvmLog.w(TAG, "number of voicemails to delete " + numVoicemails);
if (!oldestVoicemails.isEmpty()) {
mQueryHelper.markArchivedInDatabase(oldestVoicemails);
imapHelper.markMessagesAsDeleted(oldestVoicemails);
VvmLog.i(
TAG,
String.format(
"successfully archived and deleted %d voicemails", oldestVoicemails.size()));
} else {
VvmLog.w(TAG, "remote voicemail server is empty");
}
}
private boolean syncAll(String action, ImapHelper imapHelper, PhoneAccountHandle account) {
boolean uploadSuccess = true;
boolean downloadSuccess = true;
if (SYNC_FULL_SYNC.equals(action) || SYNC_UPLOAD_ONLY.equals(action)) {
uploadSuccess = upload(account, imapHelper);
}
if (SYNC_FULL_SYNC.equals(action) || SYNC_DOWNLOAD_ONLY.equals(action)) {
downloadSuccess = download(imapHelper, account);
}
VvmLog.v(
TAG,
"upload succeeded: ["
+ String.valueOf(uploadSuccess)
+ "] download succeeded: ["
+ String.valueOf(downloadSuccess)
+ "]");
return uploadSuccess && downloadSuccess;
}
private boolean syncOne(ImapHelper imapHelper, Voicemail voicemail, PhoneAccountHandle account) {
if (shouldPerformPrefetch(account, imapHelper)) {
VoicemailFetchedCallback callback =
new VoicemailFetchedCallback(mContext, voicemail.getUri(), account);
imapHelper.fetchVoicemailPayload(callback, voicemail.getSourceData());
}
return imapHelper.fetchTranscription(
new TranscriptionFetchedCallback(mContext, voicemail), voicemail.getSourceData());
}
private boolean upload(PhoneAccountHandle phoneAccountHandle, ImapHelper imapHelper) {
List<Voicemail> readVoicemails = mQueryHelper.getReadVoicemails(phoneAccountHandle);
List<Voicemail> deletedVoicemails = mQueryHelper.getDeletedVoicemails(phoneAccountHandle);
boolean success = true;
if (deletedVoicemails.size() > 0) {
if (imapHelper.markMessagesAsDeleted(deletedVoicemails)) {
// We want to delete selectively instead of all the voicemails for this provider
// in case the state changed since the IMAP query was completed.
mQueryHelper.deleteFromDatabase(deletedVoicemails);
} else {
success = false;
}
}
if (readVoicemails.size() > 0) {
VvmLog.i(TAG, "Marking voicemails as read");
if (imapHelper.markMessagesAsRead(readVoicemails)) {
VvmLog.i(TAG, "Marking voicemails as clean");
mQueryHelper.markCleanInDatabase(readVoicemails);
} else {
success = false;
}
}
return success;
}
private boolean download(ImapHelper imapHelper, PhoneAccountHandle account) {
List<Voicemail> serverVoicemails = imapHelper.fetchAllVoicemails();
List<Voicemail> localVoicemails = mQueryHelper.getAllVoicemails(account);
if (localVoicemails == null || serverVoicemails == null) {
// Null value means the query failed.
return false;
}
Map<String, Voicemail> remoteMap = buildMap(serverVoicemails);
// Go through all the local voicemails and check if they are on the server.
// They may be read or deleted on the server but not locally. Perform the
// appropriate local operation if the status differs from the server. Remove
// the messages that exist both locally and on the server to know which server
// messages to insert locally.
// Voicemails that were removed automatically from the server, are marked as
// archived and are stored locally. We do not delete them, as they were removed from the server
// by design (to make space).
for (int i = 0; i < localVoicemails.size(); i++) {
Voicemail localVoicemail = localVoicemails.get(i);
Voicemail remoteVoicemail = remoteMap.remove(localVoicemail.getSourceData());
// Do not delete voicemails that are archived marked as archived.
if (remoteVoicemail == null) {
mQueryHelper.deleteNonArchivedFromDatabase(localVoicemail);
} else {
if (remoteVoicemail.isRead() && !localVoicemail.isRead()) {
mQueryHelper.markReadInDatabase(localVoicemail);
}
if (!TextUtils.isEmpty(remoteVoicemail.getTranscription())
&& TextUtils.isEmpty(localVoicemail.getTranscription())) {
LoggerUtils.logImpressionOnMainThread(
mContext, DialerImpression.Type.VVM_TRANSCRIPTION_DOWNLOADED);
mQueryHelper.updateWithTranscription(localVoicemail, remoteVoicemail.getTranscription());
}
}
}
// The leftover messages are messages that exist on the server but not locally.
boolean prefetchEnabled = shouldPerformPrefetch(account, imapHelper);
for (Voicemail remoteVoicemail : remoteMap.values()) {
if (!TextUtils.isEmpty(remoteVoicemail.getTranscription())) {
LoggerUtils.logImpressionOnMainThread(
mContext, DialerImpression.Type.VVM_TRANSCRIPTION_DOWNLOADED);
}
Uri uri = VoicemailDatabaseUtil.insert(mContext, remoteVoicemail);
if (prefetchEnabled) {
VoicemailFetchedCallback fetchedCallback =
new VoicemailFetchedCallback(mContext, uri, account);
imapHelper.fetchVoicemailPayload(fetchedCallback, remoteVoicemail.getSourceData());
}
}
return true;
}
private boolean shouldPerformPrefetch(PhoneAccountHandle account, ImapHelper imapHelper) {
OmtpVvmCarrierConfigHelper carrierConfigHelper =
new OmtpVvmCarrierConfigHelper(mContext, account);
return carrierConfigHelper.isPrefetchEnabled() && !imapHelper.isRoaming();
}
/** Builds a map from provider data to message for the given collection of voicemails. */
private Map<String, Voicemail> buildMap(List<Voicemail> messages) {
Map<String, Voicemail> map = new ArrayMap<String, Voicemail>();
for (Voicemail message : messages) {
map.put(message.getSourceData(), message);
}
return map;
}
/** Callback for {@link ImapHelper#fetchTranscription(TranscriptionFetchedCallback, String)} */
public static class TranscriptionFetchedCallback {
private Context mContext;
private Voicemail mVoicemail;
public TranscriptionFetchedCallback(Context context, Voicemail voicemail) {
mContext = context;
mVoicemail = voicemail;
}
public void setVoicemailTranscription(String transcription) {
VoicemailsQueryHelper queryHelper = new VoicemailsQueryHelper(mContext);
queryHelper.updateWithTranscription(mVoicemail, transcription);
}
}
}
|
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableZuulProxy
@RestController
public class ZuulProxyApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulProxyApplication.class, args);
}
@RequestMapping("/good")
public String good(@RequestParam(required = false) String value) {
return "GOOD" + (value == null ? "" : " " + value) + "!";
}
@RequestMapping("/good/stuff")
public String stuff() {
return "STUFF!";
}
}
|
package org.chy.anubis.testengine.junit.executioner;
import org.chy.anubis.exception.InterruptException;
import org.chy.anubis.log.Logger;
import org.chy.anubis.testengine.junit.descriptor.AbstractTestDescriptor;
import org.junit.platform.engine.EngineExecutionListener;
import org.junit.platform.engine.TestDescriptor;
import org.junit.platform.engine.TestExecutionResult;
import java.util.Set;
import java.util.function.Consumer;
public class CommonExecutioner<T extends AbstractTestDescriptor> {
protected EngineExecutionListener listener;
protected T testDescriptor;
public CommonExecutioner(EngineExecutionListener listener, T testDescriptor) {
this.testDescriptor = testDescriptor;
this.listener = listener;
}
public void run(Consumer<T> consumer) {
listener.executionStarted(testDescriptor);
try {
consumer.accept(testDescriptor);
listener.executionFinished(testDescriptor, TestExecutionResult.successful());
} catch (Throwable e) {
Logger.error(e.getMessage());
Set<TestDescriptor> children = testDescriptor.getChildren();
if (children != null && children.size() != 0) {
children.forEach(descriptor -> fail(descriptor, e));
}
fail(testDescriptor, e);
}
}
private void fail(TestDescriptor testDescriptor, Throwable e) {
if (e instanceof InterruptException) {
e.setStackTrace(new StackTraceElement[0]);
listener.executionFinished(testDescriptor, TestExecutionResult.failed(e));
return;
}
listener.executionFinished(testDescriptor, TestExecutionResult.failed(e));
}
}
|
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.elasticbeanstalk.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.elasticbeanstalk.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;
/**
* UpdateApplicationResourceLifecycleRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UpdateApplicationResourceLifecycleRequestMarshaller implements
Marshaller<Request<UpdateApplicationResourceLifecycleRequest>, UpdateApplicationResourceLifecycleRequest> {
public Request<UpdateApplicationResourceLifecycleRequest> marshall(UpdateApplicationResourceLifecycleRequest updateApplicationResourceLifecycleRequest) {
if (updateApplicationResourceLifecycleRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
Request<UpdateApplicationResourceLifecycleRequest> request = new DefaultRequest<UpdateApplicationResourceLifecycleRequest>(
updateApplicationResourceLifecycleRequest, "AWSElasticBeanstalk");
request.addParameter("Action", "UpdateApplicationResourceLifecycle");
request.addParameter("Version", "2010-12-01");
request.setHttpMethod(HttpMethodName.POST);
if (updateApplicationResourceLifecycleRequest.getApplicationName() != null) {
request.addParameter("ApplicationName", StringUtils.fromString(updateApplicationResourceLifecycleRequest.getApplicationName()));
}
{
ApplicationResourceLifecycleConfig resourceLifecycleConfig = updateApplicationResourceLifecycleRequest.getResourceLifecycleConfig();
if (resourceLifecycleConfig != null) {
if (resourceLifecycleConfig.getServiceRole() != null) {
request.addParameter("ResourceLifecycleConfig.ServiceRole", StringUtils.fromString(resourceLifecycleConfig.getServiceRole()));
}
{
ApplicationVersionLifecycleConfig versionLifecycleConfig = resourceLifecycleConfig.getVersionLifecycleConfig();
if (versionLifecycleConfig != null) {
{
MaxCountRule maxCountRule = versionLifecycleConfig.getMaxCountRule();
if (maxCountRule != null) {
if (maxCountRule.getEnabled() != null) {
request.addParameter("ResourceLifecycleConfig.VersionLifecycleConfig.MaxCountRule.Enabled",
StringUtils.fromBoolean(maxCountRule.getEnabled()));
}
if (maxCountRule.getMaxCount() != null) {
request.addParameter("ResourceLifecycleConfig.VersionLifecycleConfig.MaxCountRule.MaxCount",
StringUtils.fromInteger(maxCountRule.getMaxCount()));
}
if (maxCountRule.getDeleteSourceFromS3() != null) {
request.addParameter("ResourceLifecycleConfig.VersionLifecycleConfig.MaxCountRule.DeleteSourceFromS3",
StringUtils.fromBoolean(maxCountRule.getDeleteSourceFromS3()));
}
}
}
{
MaxAgeRule maxAgeRule = versionLifecycleConfig.getMaxAgeRule();
if (maxAgeRule != null) {
if (maxAgeRule.getEnabled() != null) {
request.addParameter("ResourceLifecycleConfig.VersionLifecycleConfig.MaxAgeRule.Enabled",
StringUtils.fromBoolean(maxAgeRule.getEnabled()));
}
if (maxAgeRule.getMaxAgeInDays() != null) {
request.addParameter("ResourceLifecycleConfig.VersionLifecycleConfig.MaxAgeRule.MaxAgeInDays",
StringUtils.fromInteger(maxAgeRule.getMaxAgeInDays()));
}
if (maxAgeRule.getDeleteSourceFromS3() != null) {
request.addParameter("ResourceLifecycleConfig.VersionLifecycleConfig.MaxAgeRule.DeleteSourceFromS3",
StringUtils.fromBoolean(maxAgeRule.getDeleteSourceFromS3()));
}
}
}
}
}
}
}
return request;
}
}
|
package mage.player.ai;
import mage.abilities.Ability;
import mage.constants.RangeOfInfluence;
import mage.game.Game;
import org.apache.log4j.Logger;
import java.util.Date;
import java.util.LinkedList;
import java.util.UUID;
/**
* @author ayratn
*/
public class ComputerPlayer7 extends ComputerPlayer6 {
private static final Logger logger = Logger.getLogger(ComputerPlayer7.class);
private boolean allowBadMoves;
public ComputerPlayer7(String name, RangeOfInfluence range, int skill) {
this(name, range, skill, UUID.randomUUID());
}
public ComputerPlayer7(String name, RangeOfInfluence range, int skill, UUID playerId) {
super(name, range, skill, playerId);
}
public ComputerPlayer7(final ComputerPlayer7 player) {
super(player);
this.allowBadMoves = player.allowBadMoves;
}
@Override
public ComputerPlayer7 copy() {
return new ComputerPlayer7(this);
}
@Override
public boolean priority(Game game) {
game.resumeTimer(getTurnControlledBy());
boolean result = priorityPlay(game);
game.pauseTimer(getTurnControlledBy());
return result;
}
private boolean priorityPlay(Game game) {
if (lastLoggedTurn != game.getTurnNum()) {
lastLoggedTurn = game.getTurnNum();
logger.info("======================= Turn: " + game.getTurnNum() + " [" + game.getPlayer(game.getActivePlayerId()).getName() + "] =========================================");
}
logState(game);
logger.debug("Priority -- Step: " + (game.getTurn().getStepType() + " ").substring(0, 25) + " ActivePlayer-" + game.getPlayer(game.getActivePlayerId()).getName() + " PriorityPlayer-" + name);
game.getState().setPriorityPlayerId(playerId);
game.firePriorityEvent(playerId);
switch (game.getTurn().getStepType()) {
case UPKEEP:
case DRAW:
pass(game);
return false;
case PRECOMBAT_MAIN:
// 09.03.2020:
// in old version it passes opponent's pre-combat step (game.isActivePlayer(playerId) -> pass(game))
// why?!
printOutState(game);
if (actions.isEmpty()) {
logger.info("Sim Calculate pre combat main actions ----------------------------------------------------- ");
calculateActions(game);
}
act(game);
return true;
case BEGIN_COMBAT:
pass(game);
return false;
case DECLARE_ATTACKERS:
printOutState(game);
if (actions.isEmpty()) {
logger.info("Sim Calculate declare attackers actions ----------------------------------------------------- ");
calculateActions(game);
}
act(game);
return true;
case DECLARE_BLOCKERS:
printOutState(game);
if (actions.isEmpty()) {
calculateActions(game);
}
act(game);
return true;
case FIRST_COMBAT_DAMAGE:
case COMBAT_DAMAGE:
case END_COMBAT:
pass(game);
return false;
case POSTCOMBAT_MAIN:
printOutState(game);
if (actions.isEmpty()) {
calculateActions(game);
}
act(game);
return true;
case END_TURN:
case CLEANUP:
actionCache.clear();
pass(game);
return false;
}
return false;
}
protected void calculateActions(Game game) {
if (!getNextAction(game)) {
Date startTime = new Date();
currentScore = GameStateEvaluator2.evaluate(playerId, game).getTotalScore();
Game sim = createSimulation(game);
SimulationNode2.resetCount();
root = new SimulationNode2(null, sim, maxDepth, playerId);
addActionsTimed(); // TODO: root can be null again after addActionsTimed O_o need to research (it's a CPU AI problem?)
if (root != null && root.children != null && !root.children.isEmpty()) {
logger.trace("After add actions timed: root.children.size = " + root.children.size());
root = root.children.get(0);
// prevent repeating always the same action with no cost
boolean doThis = true;
if (root.abilities.size() == 1) {
for (Ability ability : root.abilities) {
if (ability.getManaCosts().manaValue() == 0
&& ability.getCosts().isEmpty()) {
if (actionCache.contains(ability.getRule() + '_' + ability.getSourceId())) {
doThis = false; // don't do it again
}
}
}
}
if (doThis) {
actions = new LinkedList<>(root.abilities);
combat = root.combat;
for (Ability ability : actions) {
actionCache.add(ability.getRule() + '_' + ability.getSourceId());
}
}
} else {
logger.info('[' + game.getPlayer(playerId).getName() + "][pre] Action: skip");
}
Date endTime = new Date();
this.setLastThinkTime((endTime.getTime() - startTime.getTime()));
/*
logger.warn("Last think time: " + this.getLastThinkTime()
+ "; actions: " + actions.size()
+ "; hand: " + this.getHand().size()
+ "; permanents: " + game.getBattlefield().getAllPermanents().size());
*/
} else {
logger.debug("Next Action exists!");
}
}
@Override
public void setAllowBadMoves(boolean allowBadMoves) {
this.allowBadMoves = allowBadMoves;
}
}
|
package br.senac.tads3.CRUDFuncionario;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "PesquisarFuncionario", urlPatterns = {"/PesquisarFuncionario"})
public class PesquisarFuncionario extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServicoFuncionario sf = new ServicoFuncionario();
if (request.getParameter("palavra").equals("") || request.getParameter("palavra") == null) {
try {
List<Funcionario> resultado = sf.ListarFuncionarios();
request.setAttribute("resultado", resultado);
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/consultaFuncionario.jsp");
dispatcher.forward(request, response);
} catch (Exception e) {
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/mensagemErro.jsp");
dispatcher.forward(request, response);
}
} else {
try {
List<Funcionario> resultado = sf.pesquisarFuncionario(request.getParameter("palavra"));
if (resultado == null){
request.setAttribute("palavra", request.getParameter("palavra"));
} else {
request.setAttribute("palavra", request.getParameter("palavra"));
request.setAttribute("resultado", resultado);
}
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/consultaFuncionario.jsp");
dispatcher.forward(request, response);
} catch (Exception e) {
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/mensagemErro.jsp");
dispatcher.forward(request, response);
}
}
}
}
|
package com.mucheng.objects;
/**
* Created by Administrator on 2017/9/17.
*/
public class Background {
}
|
/*
* Copyright 1999-2019 Seata.io Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.seata.rm.datasource.sql.struct.cache;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.util.JdbcConstants;
import io.seata.common.exception.ShouldNeverHappenException;
import io.seata.rm.datasource.DataSourceProxy;
import io.seata.rm.datasource.mock.MockDriver;
import io.seata.rm.datasource.sql.struct.ColumnMeta;
import io.seata.rm.datasource.sql.struct.IndexMeta;
import io.seata.rm.datasource.sql.struct.IndexType;
import io.seata.rm.datasource.sql.struct.TableMeta;
import io.seata.rm.datasource.sql.struct.TableMetaCache;
import io.seata.rm.datasource.sql.struct.TableMetaCacheFactory;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Collections;
/**
* The table meta fetch test.
*
* @author hanwen created at 2019-02-01
*/
public class MysqlTableMetaCacheTest {
private static Object[][] columnMetas =
new Object[][] {
new Object[] {"", "", "t1", "id", Types.INTEGER, "INTEGER", 64, 0, 10, 1, "", "", 0, 0, 64, 1, "NO", "YES"},
new Object[] {"", "", "t1", "name1", Types.VARCHAR, "VARCHAR", 64, 0, 10, 0, "", "", 0, 0, 64, 2, "YES",
"NO"},
new Object[] {"", "", "t1", "name2", Types.VARCHAR, "VARCHAR", 64, 0, 10, 0, "", "", 0, 0, 64, 3, "YES",
"NO"},
new Object[] {"", "", "t1", "name3", Types.VARCHAR, "VARCHAR", 64, 0, 10, 0, "", "", 0, 0, 64, 4, "YES",
"NO"}
};
private static Object[][] indexMetas =
new Object[][] {
new Object[] {"PRIMARY", "id", false, "", 3, 0, "A", 34},
new Object[] {"name1", "name1", false, "", 3, 1, "A", 34},
new Object[] {"name2", "name2", true, "", 3, 2, "A", 34},
};
@Test
public void testTableMeta() {
TableMetaCache tableMetaCache = getTableMetaCache();
Assertions.assertNotNull(tableMetaCache);
Assertions.assertThrows(IllegalArgumentException.class, () -> {
tableMetaCache.getTableMeta(null, null, null);
});
}
private TableMetaCache getTableMetaCache() {
return TableMetaCacheFactory.getTableMetaCache(JdbcConstants.MYSQL);
}
/**
* The table meta fetch test.
*/
@Test
public void getTableMetaTest_0() throws SQLException {
MockDriver mockDriver = new MockDriver(columnMetas, indexMetas);
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl("jdbc:mock:xxx");
dataSource.setDriver(mockDriver);
DataSourceProxy proxy = new DataSourceProxy(dataSource);
TableMeta tableMeta = getTableMetaCache().getTableMeta(proxy.getPlainConnection(), "t1", proxy.getResourceId());
Assertions.assertEquals("t1", tableMeta.getTableName());
Assertions.assertEquals("id", tableMeta.getPkName());
Assertions.assertEquals("id", tableMeta.getColumnMeta("id").getColumnName());
Assertions.assertEquals("id", tableMeta.getAutoIncreaseColumn().getColumnName());
Assertions.assertEquals(1, tableMeta.getPrimaryKeyMap().size());
Assertions.assertEquals(Collections.singletonList("id"), tableMeta.getPrimaryKeyOnlyName());
Assertions.assertEquals(columnMetas.length, tableMeta.getAllColumns().size());
assertColumnMetaEquals(columnMetas[0], tableMeta.getAllColumns().get("id"));
assertColumnMetaEquals(columnMetas[1], tableMeta.getAllColumns().get("name1"));
assertColumnMetaEquals(columnMetas[2], tableMeta.getAllColumns().get("name2"));
assertColumnMetaEquals(columnMetas[3], tableMeta.getAllColumns().get("name3"));
Assertions.assertEquals(indexMetas.length, tableMeta.getAllIndexes().size());
assertIndexMetaEquals(indexMetas[0], tableMeta.getAllIndexes().get("PRIMARY"));
Assertions.assertEquals(IndexType.PRIMARY, tableMeta.getAllIndexes().get("PRIMARY").getIndextype());
assertIndexMetaEquals(indexMetas[1], tableMeta.getAllIndexes().get("name1"));
Assertions.assertEquals(IndexType.UNIQUE, tableMeta.getAllIndexes().get("name1").getIndextype());
indexMetas =
new Object[][] {
};
mockDriver.setMockIndexMetasReturnValue(indexMetas);
Assertions.assertThrows(ShouldNeverHappenException.class, () -> {
getTableMetaCache().getTableMeta(proxy.getPlainConnection(), "t2", proxy.getResourceId());
});
mockDriver.setMockColumnsMetasReturnValue(null);
Assertions.assertThrows(ShouldNeverHappenException.class, () -> {
getTableMetaCache().getTableMeta(proxy.getPlainConnection(), "t2", proxy.getResourceId());
});
}
@Test
public void refreshTest_0() throws SQLException {
MockDriver mockDriver = new MockDriver(columnMetas, indexMetas);
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUrl("jdbc:mock:xxx");
druidDataSource.setDriver(mockDriver);
DataSourceProxy dataSourceProxy = new DataSourceProxy(druidDataSource);
TableMeta tableMeta = getTableMetaCache().getTableMeta(dataSourceProxy.getPlainConnection(), "t1",
dataSourceProxy.getResourceId());
//change the columns meta
columnMetas =
new Object[][] {
new Object[] {"", "", "t1", "id", Types.INTEGER, "INTEGER", 64, 0, 10, 1, "", "", 0, 0, 64, 1, "NO", "YES"},
new Object[] {"", "", "t1", "name1", Types.VARCHAR, "VARCHAR", 65, 0, 10, 0, "", "", 0, 0, 64, 2, "YES",
"NO"},
new Object[] {"", "", "t1", "name2", Types.VARCHAR, "VARCHAR", 64, 0, 10, 0, "", "", 0, 0, 64, 3, "YES",
"NO"},
new Object[] {"", "", "t1", "name3", Types.VARCHAR, "VARCHAR", 64, 0, 10, 0, "", "", 0, 0, 64, 4, "YES",
"NO"}
};
mockDriver.setMockColumnsMetasReturnValue(columnMetas);
getTableMetaCache().refresh(dataSourceProxy.getPlainConnection(), dataSourceProxy.getResourceId());
}
private void assertColumnMetaEquals(Object[] expected, ColumnMeta actual) {
Assertions.assertEquals(expected[0], actual.getTableCat());
Assertions.assertEquals(expected[3], actual.getColumnName());
Assertions.assertEquals(expected[4], actual.getDataType());
Assertions.assertEquals(expected[5], actual.getDataTypeName());
Assertions.assertEquals(expected[6], actual.getColumnSize());
Assertions.assertEquals(expected[7], actual.getDecimalDigits());
Assertions.assertEquals(expected[8], actual.getNumPrecRadix());
Assertions.assertEquals(expected[9], actual.getNullAble());
Assertions.assertEquals(expected[10], actual.getRemarks());
Assertions.assertEquals(expected[11], actual.getColumnDef());
Assertions.assertEquals(expected[12], actual.getSqlDataType());
Assertions.assertEquals(expected[13], actual.getSqlDatetimeSub());
Assertions.assertEquals(expected[14], actual.getCharOctetLength());
Assertions.assertEquals(expected[15], actual.getOrdinalPosition());
Assertions.assertEquals(expected[16], actual.getIsNullAble());
Assertions.assertEquals(expected[17], actual.getIsAutoincrement());
}
private void assertIndexMetaEquals(Object[] expected, IndexMeta actual) {
Assertions.assertEquals(expected[0], actual.getIndexName());
Assertions.assertEquals(expected[3], actual.getIndexQualifier());
Assertions.assertEquals(expected[4], (int)actual.getType());
Assertions.assertEquals(expected[5], actual.getOrdinalPosition());
Assertions.assertEquals(expected[6], actual.getAscOrDesc());
Assertions.assertEquals(expected[7], actual.getCardinality());
}
}
|
/*******************************************************************************
* Copyright (c) 2020 Northrop Grumman Systems Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.zeligsoft.ddk.zdl.zdlgen.internal.impl;
import com.zeligsoft.ddk.zdl.zdlgen.GenDomainObject;
import com.zeligsoft.ddk.zdl.zdlgen.GenDomainPackage;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.util.EcoreUtil;
import com.zeligsoft.ddk.zdl.zdlgen.GenDomainPackageableElement;
import com.zeligsoft.ddk.zdl.zdlgen.ZDLGenPackage;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Gen Domain Packageable Element</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link com.zeligsoft.ddk.zdl.zdlgen.internal.impl.GenDomainPackageableElementImpl#getOwner <em>Owner</em>}</li>
* <li>{@link com.zeligsoft.ddk.zdl.zdlgen.internal.impl.GenDomainPackageableElementImpl#getPackage <em>Package</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public abstract class GenDomainPackageableElementImpl extends
GenDomainNamedElementImpl implements GenDomainPackageableElement {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected GenDomainPackageableElementImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return ZDLGenPackage.Literals.GEN_DOMAIN_PACKAGEABLE_ELEMENT;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public GenDomainObject getOwner() {
GenDomainObject owner = basicGetOwner();
return owner != null && owner.eIsProxy() ? (GenDomainObject) eResolveProxy((InternalEObject) owner)
: owner;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public GenDomainObject basicGetOwner() {
GenDomainPackage package_ = getPackage();
if (package_ != null) {
return package_;
}
return super.basicGetOwner();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public GenDomainPackage getPackage() {
if (eContainerFeatureID() != ZDLGenPackage.GEN_DOMAIN_PACKAGEABLE_ELEMENT__PACKAGE)
return null;
return (GenDomainPackage) eContainer();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetPackage(GenDomainPackage newPackage,
NotificationChain msgs) {
msgs = eBasicSetContainer((InternalEObject) newPackage,
ZDLGenPackage.GEN_DOMAIN_PACKAGEABLE_ELEMENT__PACKAGE, msgs);
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setPackage(GenDomainPackage newPackage) {
if (newPackage != eInternalContainer()
|| (eContainerFeatureID() != ZDLGenPackage.GEN_DOMAIN_PACKAGEABLE_ELEMENT__PACKAGE && newPackage != null)) {
if (EcoreUtil.isAncestor(this, newPackage))
throw new IllegalArgumentException(
"Recursive containment not allowed for " + toString()); //$NON-NLS-1$
NotificationChain msgs = null;
if (eInternalContainer() != null)
msgs = eBasicRemoveFromContainer(msgs);
if (newPackage != null)
msgs = ((InternalEObject) newPackage).eInverseAdd(this,
ZDLGenPackage.GEN_DOMAIN_PACKAGE__ELEMENT,
GenDomainPackage.class, msgs);
msgs = basicSetPackage(newPackage, msgs);
if (msgs != null)
msgs.dispatch();
} else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET,
ZDLGenPackage.GEN_DOMAIN_PACKAGEABLE_ELEMENT__PACKAGE,
newPackage, newPackage));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd,
int featureID, NotificationChain msgs) {
switch (featureID) {
case ZDLGenPackage.GEN_DOMAIN_PACKAGEABLE_ELEMENT__PACKAGE:
if (eInternalContainer() != null)
msgs = eBasicRemoveFromContainer(msgs);
return basicSetPackage((GenDomainPackage) otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd,
int featureID, NotificationChain msgs) {
switch (featureID) {
case ZDLGenPackage.GEN_DOMAIN_PACKAGEABLE_ELEMENT__PACKAGE:
return basicSetPackage(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eBasicRemoveFromContainerFeature(
NotificationChain msgs) {
switch (eContainerFeatureID()) {
case ZDLGenPackage.GEN_DOMAIN_PACKAGEABLE_ELEMENT__PACKAGE:
return eInternalContainer().eInverseRemove(this,
ZDLGenPackage.GEN_DOMAIN_PACKAGE__ELEMENT,
GenDomainPackage.class, msgs);
}
return super.eBasicRemoveFromContainerFeature(msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case ZDLGenPackage.GEN_DOMAIN_PACKAGEABLE_ELEMENT__PACKAGE:
return getPackage();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case ZDLGenPackage.GEN_DOMAIN_PACKAGEABLE_ELEMENT__PACKAGE:
setPackage((GenDomainPackage) newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case ZDLGenPackage.GEN_DOMAIN_PACKAGEABLE_ELEMENT__PACKAGE:
setPackage((GenDomainPackage) null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case ZDLGenPackage.GEN_DOMAIN_PACKAGEABLE_ELEMENT__PACKAGE:
return getPackage() != null;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean isSetOwner() {
return super.isSetOwner()
|| eIsSet(ZDLGenPackage.GEN_DOMAIN_PACKAGEABLE_ELEMENT__PACKAGE);
}
} //GenDomainPackageableElementImpl
|
/**
* Bloom Filter
*/
package com.jn.langx.util.bloom;
|
package com.gof.behavioral.command;
public class ConcreteCommand implements Command {
public Receiver Receiver;
public ConcreteCommand(Receiver Receiver) {
this.Receiver = Receiver;
}
@Override
public void execute() {
this.Receiver.action();
}
}
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jee.as.quickstart.deltaspike.beanbuilder.util;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
* This class uses CDI to alias Java EE resources, such as the persistence context, to CDI beans
*
* <p>
* Example injection on a managed bean field:
* </p>
*
* <pre>
* @Inject
* private EntityManager em;
* </pre>
*/
public class Resources {
@Produces
@PersistenceContext
private EntityManager em;
}
|
package hurrycaneblurryname.ryde;
import android.content.Context;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Type;
import java.util.ArrayList;
/**
* Loads and saves commands from an arraylist and file.
*/
public class CommandFileManager<Command>{
protected Context context;
CommandFileManager(Context context){
this.context = context;
}
protected ArrayList<Command> loadFromFile(String FILENAME){
ArrayList<Command> list = new ArrayList<Command>();
try {
FileInputStream fis = context.openFileInput(FILENAME);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
GsonBuilder gb = new GsonBuilder();
gb.registerTypeAdapter(new TypeToken<ArrayList<Command>>(){}.getType(), new CommandDeserializer());
Gson gson = gb.create();
// Code from http://stackoverflow.com/questions/12384064/gson-convert-from-json-to-a-typed-arraylistt
Type listType = new TypeToken<ArrayList<Command>>(){}.getType();
list = gson.fromJson(in,listType);
if(list == null){
list = new ArrayList<Command>();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
list = new ArrayList<Command>();
} catch (IOException e) {
// TODO Auto-generated catch block
throw new RuntimeException();
}
return list;
}
protected void saveInFile(ArrayList<Command> list, String FILENAME) {
try {
FileOutputStream fos = context.openFileOutput(FILENAME, 0);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));
GsonBuilder gb = new GsonBuilder();
gb.registerTypeAdapter(new TypeToken<ArrayList<Command>>(){}.getType(), new CommandSerializer());
Gson gson = gb.create();
gson.toJson(list, out);
out.flush();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
throw new RuntimeException();
} catch (IOException e) {
// TODO Auto-generated catch block
throw new RuntimeException();
}
}
}
|
package com.jbm.framework.service.mybatis;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jbm.framework.dao.mybatis.sqlInjector.MasterDataSqlInjector;
import com.jbm.framework.exceptions.DataServiceException;
import com.jbm.framework.masterdata.service.IMasterDataCodeService;
import com.jbm.framework.masterdata.usage.entity.MasterDataCodeEntity;
import com.jbm.framework.masterdata.usage.form.PageRequestBody;
import com.jbm.framework.usage.paging.DataPaging;
import com.jbm.util.CollectionUtils;
import com.jbm.util.MapUtils;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.session.SqlSession;
import org.springframework.transaction.annotation.Transactional;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
public class MasterDataCodeServiceImpl<Entity extends MasterDataCodeEntity> extends MasterDataServiceImpl<Entity> implements IMasterDataCodeService<Entity> {
public MasterDataCodeServiceImpl() {
super();
}
@Override
public DataPaging<Entity> findListPage(PageRequestBody pageRequestBody) {
Entity query = pageRequestBody.tryGet(super.currentModelClass());
return this.selectEntitys(query, pageRequestBody.getPageForm());
}
@Override
public Entity selectByCode(String code) throws DataServiceException {
return super.getOne(buildWrapperByCode(code));
}
@Override
public List<Entity> selectByCodes(Collection<String> codes) throws DataServiceException {
return super.list(buildWrapperByCodes(codes));
}
@Override
public Map<String, Entity> selectEntityMapByCodes(Collection<String> codes) throws DataServiceException {
try {
List<Entity> list = this.selectByCodes(codes);
return MapUtils.fromList(list, IMasterDataCodeService.CODE_COLUMN, String.class);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
return Maps.newHashMap();
}
}
@Transactional(rollbackFor = Exception.class)
@Override
public int deleteByCodes(Collection<String> codes) throws DataServiceException {
return this.baseMapper.delete(this.buildWrapperByCodes(codes));
}
@Transactional(rollbackFor = Exception.class)
@Override
public boolean deleteByCode(String code) throws DataServiceException {
return super.remove(this.buildWrapperByCode(code));
}
@Transactional(rollbackFor = Exception.class)
@Override
public boolean updateByCode(Entity entity) {
return this.updateBatchByCode(Lists.newArrayList(entity));
}
@Transactional(rollbackFor = Exception.class)
@Override
public boolean updateBatchByCode(Collection<Entity> entityList) {
return this.updateBatchByCode(entityList, 30);
}
@Transactional(rollbackFor = Exception.class)
private boolean updateBatchByCode(Collection<Entity> entityList, int batchSize) {
if (CollectionUtils.isEmpty(entityList)) {
throw new IllegalArgumentException("Error: entityList must not be empty");
}
int i = 0;
String sqlStatement = sqlStatement(MasterDataSqlInjector.UPDATE_BY_CODE);
try (SqlSession batchSqlSession = sqlSessionBatch()) {
for (Entity anEntityList : entityList) {
MapperMethod.ParamMap<Entity> param = new MapperMethod.ParamMap<>();
param.put(Constants.ENTITY, anEntityList);
batchSqlSession.update(sqlStatement, param);
if (i >= 1 && i % batchSize == 0) {
batchSqlSession.flushStatements();
}
i++;
}
batchSqlSession.flushStatements();
}
return true;
}
@Transactional(rollbackFor = Exception.class)
@Override
public boolean saveOrUpdateBatchByCode(Collection<Entity> entityList) {
return this.saveOrUpdateBatchByCode(entityList, 30);
}
@Transactional(rollbackFor = Exception.class)
private boolean saveOrUpdateBatchByCode(Collection<Entity> entityList, int batchSize) {
if (CollectionUtils.isEmpty(entityList)) {
throw new IllegalArgumentException("Error: entityList must not be empty");
}
Class<?> cls = null;
TableInfo tableInfo = null;
int i = 0;
try (SqlSession batchSqlSession = sqlSessionBatch()) {
for (Entity anEntityList : entityList) {
if (i == 0) {
cls = anEntityList.getClass();
tableInfo = TableInfoHelper.getTableInfo(cls);
}
if (null != tableInfo && StringUtils.isNotEmpty(tableInfo.getKeyProperty())) {
Object codeVal = ReflectionKit.getMethodValue(cls, anEntityList, IMasterDataCodeService.CODE_COLUMN);
if (StringUtils.checkValNull(codeVal)) {
String sqlStatement = sqlStatement(SqlMethod.INSERT_ONE);
batchSqlSession.insert(sqlStatement, anEntityList);
} else {
String sqlStatement = sqlStatement(MasterDataSqlInjector.UPDATE_BY_CODE);
MapperMethod.ParamMap<Entity> param = new MapperMethod.ParamMap<>();
param.put(Constants.ENTITY, anEntityList);
batchSqlSession.update(sqlStatement, param);
// 不知道以后会不会有人说更新失败了还要执行插入 😂😂😂
}
if (i >= 1 && i % batchSize == 0) {
batchSqlSession.flushStatements();
}
i++;
} else {
throw ExceptionUtils.mpe("Error: Can not execute. Could not find @TableId.");
}
batchSqlSession.flushStatements();
}
}
return true;
}
// ---------------------------------------------------------build转换方法----------------------------------------------------------------------
private QueryWrapper<Entity> buildWrapperByCode(String code) {
QueryWrapper<Entity> queryWrapper = new QueryWrapper<>();
queryWrapper.eq(IMasterDataCodeService.CODE_COLUMN, code);
return queryWrapper;
}
private QueryWrapper<Entity> buildWrapperByCodes(Collection<String> codes) {
QueryWrapper<Entity> queryWrapper = new QueryWrapper<>();
queryWrapper.in(IMasterDataCodeService.CODE_COLUMN, codes);
return queryWrapper;
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.management;
import org.apache.camel.CamelExecutionException;
import org.apache.camel.builder.RouteBuilder;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import static org.junit.jupiter.api.Assertions.fail;
@DisabledOnOs(OS.AIX)
public class ManagedRouteWithOnExceptionTest extends ManagementTestSupport {
@Test
public void testShouldBeInstrumentedOk() throws Exception {
getMockEndpoint("mock:error").expectedMessageCount(0);
getMockEndpoint("mock:result").expectedMessageCount(1);
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
}
@Test
public void testShouldBeInstrumentedKabom() throws Exception {
getMockEndpoint("mock:error").expectedMessageCount(1);
getMockEndpoint("mock:result").expectedMessageCount(0);
try {
template.sendBody("direct:start", "Kabom");
fail("Should have thrown an exception");
} catch (CamelExecutionException e) {
// expected
}
assertMockEndpointsSatisfied();
}
@Test
public void testShouldBeInstrumentedOkAndKabom() throws Exception {
getMockEndpoint("mock:error").expectedMessageCount(1);
getMockEndpoint("mock:result").expectedMessageCount(1);
template.sendBody("direct:start", "Hello World");
try {
template.sendBody("direct:start", "Kabom");
fail("Should have thrown an exception");
} catch (CamelExecutionException e) {
// expected
}
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start")
.onException(Exception.class)
.to("mock:error")
.end()
.delay(100)
.choice()
.when(body().isEqualTo("Kabom")).throwException(new IllegalArgumentException("Kabom"))
.otherwise().to("mock:result")
.end();
}
};
}
}
|
/*
* Copyright 2018, Strimzi authors.
* License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
*/
package io.strimzi.api.kafka.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import io.strimzi.crdgenerator.annotations.Description;
import io.sundr.builder.annotations.Buildable;
import lombok.EqualsAndHashCode;
import java.util.List;
/**
* Configures the broker authorization
*/
@Buildable(
editableEnabled = false,
generateBuilderPackage = false,
builderPackage = "io.fabric8.kubernetes.api.builder"
)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"type", "acls"})
@EqualsAndHashCode
public class KafkaUserAuthorizationSimple extends KafkaUserAuthorization {
private static final long serialVersionUID = 1L;
public static final String TYPE_SIMPLE = "simple";
private List<AclRule> acls;
@Description("Must be `" + TYPE_SIMPLE + "`")
@Override
public String getType() {
return TYPE_SIMPLE;
}
@Description("List of ACL rules which should be applied to this user.")
@JsonProperty(required = true)
public List<AclRule> getAcls() {
return acls;
}
public void setAcls(List<AclRule> acls) {
this.acls = acls;
}
}
|
package org.cloudfoundry.samples.music.domain;
import static org.junit.Assert.*;
import org.junit.Test;
public class ApplicationInfoTest {
ApplicationInfo ai = new ApplicationInfo(null, null);
@Test
public void test() {
ai.setI("2");
System.out.println("output2: "+ai.getI());
assertEquals("",ai.getI());
}
}
|
package nl.tudelft.jpacman.npc.ghost;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import nl.tudelft.jpacman.board.Board;
import nl.tudelft.jpacman.board.Direction;
import nl.tudelft.jpacman.board.Square;
import nl.tudelft.jpacman.board.Unit;
/**
* Navigation provides utility to navigate on {@link Square}s.
*
* @author Jeroen Roosen
*/
public final class Navigation {
private Navigation() {
}
/**
* Calculates the shortest path. This is done by BFS. This search ensures
* the traveller is allowed to occupy the squares on the way, or returns the
* shortest path to the square regardless of terrain if no traveller is
* specified.
*
* @param from
* The starting square.
* @param to
* The destination.
* @param traveller
* The traveller attempting to reach the destination. If
* traveller is set to <code>null</code>, this method will ignore
* terrain and find the shortest path whether it can actually be
* reached or not.
* @return The shortest path to the destination or <code>null</code> if no
* such path could be found. When the destination is the current
* square, an empty list is returned.
*/
public static List<Direction> shortestPath(Square from, Square to,
Unit traveller) {
if (from.equals(to)) {
return new ArrayList<>();
}
List<Node> targets = new ArrayList<>();
Set<Square> visited = new HashSet<>();
targets.add(new Node(null, from, null));
while (!targets.isEmpty()) {
Node node = targets.remove(0);
Square square = node.getSquare();
if (square.equals(to)) {
return node.getPath();
}
visited.add(square);
addNewTargets(traveller, targets, visited, node, square);
}
return null;
}
private static void addNewTargets(Unit traveller, List<Node> targets,
Set<Square> visited, Node node, Square square) {
for (Direction direction : Direction.values()) {
Square target = square.getSquareAt(direction);
if (!visited.contains(target)
&& (traveller == null || target.isAccessibleTo(traveller))) {
targets.add(new Node(direction, target, node));
}
}
}
/**
* Finds the nearest unit of the given type and returns its location. This
* method will perform a breadth first search starting from the given
* square.
*
* @param type
* The type of unit to search for.
* @param currentLocation
* The starting location for the search.
* @return The nearest unit of the given type, or <code>null</code> if no
* such unit could be found.
*/
public static Unit findNearest(Class<? extends Unit> type,
Square currentLocation) {
List<Square> toDo = new ArrayList<>();
Set<Square> visited = new HashSet<>();
toDo.add(currentLocation);
while (!toDo.isEmpty()) {
Square square = toDo.remove(0);
Unit unit = findUnit(type, square);
if (unit != null) {
assert unit.hasSquare();
return unit;
}
visited.add(square);
for (Direction direction : Direction.values()) {
Square newTarget = square.getSquareAt(direction);
if (!visited.contains(newTarget) && !toDo.contains(newTarget)) {
toDo.add(newTarget);
}
}
}
return null;
}
/**
* Finds a subtype of Unit in a level.
* This method is very useful for finding the ghosts in the parsed map.
*
* @param clazz the type to search for.
* @param board the board to find the unit in.
* @param <T> the return type, same as the type in clazz.
*
* @return the first unit found of type clazz, or null.
*/
public static <T extends Unit> T findUnitInBoard(Class<T> clazz, Board board) {
for (int y = 0; y < board.getHeight(); y++) {
for (int x = 0; x < board.getWidth(); x++) {
final T ghost = Navigation.findUnit(clazz, board.squareAt(x, y));
if (ghost != null) {
return ghost;
}
}
}
return null;
}
/**
* Determines whether a square has an occupant of a certain type.
*
* @param type
* The type to search for.
* @param square
* The square to search.
* @param <T>
* the type of unit we searched for.
*
* @return A unit of type T, iff such a unit occupies this square, or
* <code>null</code> of none does.
*/
@SuppressWarnings("unchecked")
public static <T extends Unit> T findUnit(Class<T> type, Square square) {
for (Unit unit : square.getOccupants()) {
if (type.isInstance(unit)) {
assert unit.hasSquare();
return (T) unit;
}
}
return null;
}
/**
* Helper class to keep track of the path.
*
* @author Jeroen Roosen
*/
private static final class Node {
/**
* The direction for this node, which is <code>null</code> for the root
* node.
*/
private final Direction direction;
/**
* The parent node, which is <code>null</code> for the root node.
*/
private final Node parent;
/**
* The square associated with this node.
*/
private final Square square;
/**
* Creates a new node.
*
* @param direction
* The direction, which is <code>null</code> for the root
* node.
* @param square
* The square.
* @param parent
* The parent node, which is <code>null</code> for the root
* node.
*/
Node(Direction direction, Square square, Node parent) {
this.direction = direction;
this.square = square;
this.parent = parent;
}
/**
* @return The direction for this node, or <code>null</code> if this
* node is a root node.
*/
private Direction getDirection() {
return direction;
}
/**
* @return The square for this node.
*/
private Square getSquare() {
return square;
}
/**
* @return The parent node, or <code>null</code> if this node is a root
* node.
*/
private Node getParent() {
return parent;
}
/**
* Returns the list of values from the root of the tree to this node.
*
* @return The list of values from the root of the tree to this node.
*/
private List<Direction> getPath() {
if (parent == null) {
return new ArrayList<>();
}
List<Direction> path = parent.getPath();
path.add(getDirection());
return path;
}
}
}
|
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.submit.lookup;
import gr.ekt.bte.core.Record;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dspace.app.util.XMLUtils;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.jdom.JDOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/**
* @author Andrea Bollini
* @author Kostas Stamatis
* @author Luigi Andrea Pascarelli
* @author Panagiotis Koutsourakis
*/
public class CrossRefService
{
private static final Logger log = Logger.getLogger(CrossRefService.class);
private int timeout = 1000;
public void setTimeout(int timeout)
{
this.timeout = timeout;
}
public List<Record> search(Context context, Set<String> dois)
throws HttpException, IOException, JDOMException,
ParserConfigurationException, SAXException
{
List<Record> results = new ArrayList<Record>();
if (dois != null && dois.size() > 0)
{
for (String record : dois)
{
try
{
if (!ConfigurationManager
.getBooleanProperty(SubmissionLookupService.CFG_MODULE, "remoteservice.demo"))
{
GetMethod method = null;
try
{
String apiKey = ConfigurationManager
.getProperty(SubmissionLookupService.CFG_MODULE, "crossref.api-key");
HttpClient client = new HttpClient();
client.setConnectionTimeout(timeout);
method = new GetMethod(
"http://www.crossref.org/openurl/");
NameValuePair pid = new NameValuePair("pid", apiKey);
NameValuePair noredirect = new NameValuePair(
"noredirect", "true");
NameValuePair id = new NameValuePair("id", record);
method.setQueryString(new NameValuePair[] { pid,
noredirect, id });
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK)
{
throw new RuntimeException("Http call failed: "
+ method.getStatusLine());
}
Record crossitem;
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
factory.setValidating(false);
factory.setIgnoringComments(true);
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder db = factory
.newDocumentBuilder();
Document inDoc = db.parse(method
.getResponseBodyAsStream());
Element xmlRoot = inDoc.getDocumentElement();
Element queryResult = XMLUtils.getSingleElement(xmlRoot, "query_result");
Element body = XMLUtils.getSingleElement(queryResult, "body");
Element dataRoot = XMLUtils.getSingleElement(body, "query");
crossitem = CrossRefUtils
.convertCrossRefDomToRecord(dataRoot);
results.add(crossitem);
}
catch (Exception e)
{
log.warn(LogManager
.getHeader(
context,
"retrieveRecordDOI",
record
+ " DOI is not valid or not exist: "
+ e.getMessage()));
}
}
finally
{
if (method != null)
{
method.releaseConnection();
}
}
}
}
catch (RuntimeException rt)
{
log.error(rt.getMessage(), rt);
}
}
}
return results;
}
public NameValuePair[] buildQueryPart(String title, String author,
int year, int count)
{
StringBuffer sb = new StringBuffer();
if (StringUtils.isNotBlank(title))
{
sb.append(title);
}
sb.append(" ");
if (StringUtils.isNotBlank(author))
{
sb.append(author);
}
String q = sb.toString().trim();
NameValuePair qParam = new NameValuePair("q", title);
NameValuePair yearParam = new NameValuePair("year",
year != -1 ? String.valueOf(year) : "");
NameValuePair countParam = new NameValuePair("rows",
count != -1 ? String.valueOf(count) : "");
NameValuePair[] query = new NameValuePair[] { qParam, yearParam,
countParam };
return query;
}
public List<Record> search(Context context, String title, String authors,
int year, int count) throws IOException, HttpException
{
GetMethod method = null;
try
{
NameValuePair[] query = buildQueryPart(title, authors, year, count);
HttpClient client = new HttpClient();
client.setTimeout(timeout);
method = new GetMethod("http://search.labs.crossref.org/dois");
method.setQueryString(query);
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK)
{
throw new RuntimeException("Http call failed:: "
+ method.getStatusLine());
}
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<Map>>()
{
}.getType();
List<Map> json = gson.fromJson(method.getResponseBodyAsString(),
listType);
Set<String> dois = new HashSet<String>();
for (Map r : json)
{
dois.add(SubmissionLookupUtils.normalizeDOI((String) r
.get("doi")));
}
method.releaseConnection();
return search(context, dois);
}
catch (Exception e)
{
throw new RuntimeException(e.getMessage(), e);
}
finally
{
if (method != null)
{
method.releaseConnection();
}
}
}
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE134_Uncontrolled_Format_String__Environment_printf_04.java
Label Definition File: CWE134_Uncontrolled_Format_String.label.xml
Template File: sources-sinks-04.tmpl.java
*/
/*
* @description
* CWE: 134 Uncontrolled Format String
* BadSource: Environment Read data from an environment variable
* GoodSource: A hardcoded string
* Sinks: printf
* GoodSink: dynamic printf format with string defined
* BadSink : dynamic printf without validation
* Flow Variant: 04 Control flow: if(PRIVATE_STATIC_FINAL_TRUE) and if(PRIVATE_STATIC_FINAL_FALSE)
*
* */
package testcases.CWE134_Uncontrolled_Format_String.s01;
import testcasesupport.*;
public class CWE134_Uncontrolled_Format_String__Environment_printf_04 extends AbstractTestCase
{
/* The two variables below are declared "final", so a tool should
* be able to identify that reads of these will always return their
* initialized values.
*/
private static final boolean PRIVATE_STATIC_FINAL_TRUE = true;
private static final boolean PRIVATE_STATIC_FINAL_FALSE = false;
public void bad() throws Throwable
{
String data;
if (PRIVATE_STATIC_FINAL_TRUE)
{
/* get environment variable ADD */
/* POTENTIAL FLAW: Read data from an environment variable */
data = System.getenv("ADD");
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run
* but ensure data is inititialized before the Sink to avoid compiler errors */
data = null;
}
if (PRIVATE_STATIC_FINAL_TRUE)
{
if (data != null)
{
/* POTENTIAL FLAW: uncontrolled string formatting */
System.out.printf(data);
}
}
}
/* goodG2B1() - use goodsource and badsink by changing first PRIVATE_STATIC_FINAL_TRUE to PRIVATE_STATIC_FINAL_FALSE */
private void goodG2B1() throws Throwable
{
String data;
if (PRIVATE_STATIC_FINAL_FALSE)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run
* but ensure data is inititialized before the Sink to avoid compiler errors */
data = null;
}
else
{
/* FIX: Use a hardcoded string */
data = "foo";
}
if (PRIVATE_STATIC_FINAL_TRUE)
{
if (data != null)
{
/* POTENTIAL FLAW: uncontrolled string formatting */
System.out.printf(data);
}
}
}
/* goodG2B2() - use goodsource and badsink by reversing statements in first if */
private void goodG2B2() throws Throwable
{
String data;
if (PRIVATE_STATIC_FINAL_TRUE)
{
/* FIX: Use a hardcoded string */
data = "foo";
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run
* but ensure data is inititialized before the Sink to avoid compiler errors */
data = null;
}
if (PRIVATE_STATIC_FINAL_TRUE)
{
if (data != null)
{
/* POTENTIAL FLAW: uncontrolled string formatting */
System.out.printf(data);
}
}
}
/* goodB2G1() - use badsource and goodsink by changing second PRIVATE_STATIC_FINAL_TRUE to PRIVATE_STATIC_FINAL_FALSE */
private void goodB2G1() throws Throwable
{
String data;
if (PRIVATE_STATIC_FINAL_TRUE)
{
/* get environment variable ADD */
/* POTENTIAL FLAW: Read data from an environment variable */
data = System.getenv("ADD");
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run
* but ensure data is inititialized before the Sink to avoid compiler errors */
data = null;
}
if (PRIVATE_STATIC_FINAL_FALSE)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
IO.writeLine("Benign, fixed string");
}
else
{
if (data != null)
{
/* FIX: explicitly defined string formatting */
System.out.printf("%s%n", data);
}
}
}
/* goodB2G2() - use badsource and goodsink by reversing statements in second if */
private void goodB2G2() throws Throwable
{
String data;
if (PRIVATE_STATIC_FINAL_TRUE)
{
/* get environment variable ADD */
/* POTENTIAL FLAW: Read data from an environment variable */
data = System.getenv("ADD");
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run
* but ensure data is inititialized before the Sink to avoid compiler errors */
data = null;
}
if (PRIVATE_STATIC_FINAL_TRUE)
{
if (data != null)
{
/* FIX: explicitly defined string formatting */
System.out.printf("%s%n", data);
}
}
}
public void good() throws Throwable
{
goodG2B1();
goodG2B2();
goodB2G1();
goodB2G2();
}
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException
{
mainFromParent(args);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.