hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
6f86df6cff4c2edab43572ea2025290a91d6587b | 318 | package com.zbw.fame.model.query;
import com.zbw.fame.model.enums.ArticleStatus;
import lombok.Data;
import lombok.ToString;
/**
* 文章查询条件
*
* @author zbw
* @since 2019/5/1 12:33
*/
@Data
public class ArticleQuery {
private String title;
private ArticleStatus status;
private Integer priority;
}
| 13.826087 | 46 | 0.707547 |
51a58c8f143fcab9d1ce58c52592c53e77b577b5 | 604 | package com.st.faceplusplus.utils;
import android.text.TextUtils;
import android.widget.TextView;
/**
* Created by dell on 2017/3/8.
*/
public class JTextUtils {
public static boolean isEmpty(String ... args){
for (String str : args){
if(TextUtils.isEmpty(str)){
return true;
}
}
return false;
}
public static boolean isEmpty(TextView... args){
for (TextView tv : args){
if(TextUtils.isEmpty(tv.getText().toString())){
return true;
}
}
return false;
}
}
| 20.827586 | 59 | 0.544702 |
203ea9d5ff00d5f9d5bde44070dc2fccb9135bd7 | 1,773 | package com.dfintech.nem.apps.utils;
import org.nem.core.crypto.KeyPair;
import org.nem.core.crypto.PrivateKey;
import org.nem.core.crypto.PublicKey;
import org.nem.core.model.Address;
import net.sf.json.JSONObject;
/**
* @Description: address, public key, private key converter
* @author lu
* @date 2017.03.21
*/
public class KeyConvertor {
/**
* get address from private key
* @param privateKeyString
* @return
*/
public static String getAddressFromPrivateKey(String privateKeyString) {
PrivateKey privateKey = PrivateKey.fromHexString(privateKeyString);
KeyPair keyPair = new KeyPair(privateKey);
return Address.fromPublicKey(keyPair.getPublicKey()).toString();
}
/**
* get public key from private key
* @param privateKeyString
* @return
*/
public static String getPublicFromPrivateKey(String privateKeyString) {
PrivateKey privateKey = PrivateKey.fromHexString(privateKeyString);
KeyPair keyPair = new KeyPair(privateKey);
return keyPair.getPublicKey().toString();
}
/**get address from public key
* @param publicKeyString
* @return
*/
public static String getAddressFromPublicKey(String publicKeyString) {
PublicKey publicKey = PublicKey.fromHexString(publicKeyString);
Address address = Address.fromPublicKey(publicKey);
return address.toString();
}
/**
* get public Key from address
* @param addressString
* @return
*/
public static String getPublicKeyFromAddress(String addressString) {
String queryResult = HttpClientUtils.get(Constants.URL_ACCOUNT_GET + "?address=" + addressString);
JSONObject queryAccount = JSONObject.fromObject(queryResult);
return queryAccount.getJSONObject("account").getString("publicKey");
}
}
| 29.065574 | 101 | 0.728708 |
ab0217640dc86f9cd1584913a14436a659170f05 | 12,666 | package selectorexample.androidapp.com.selectorviewexample;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import com.emcy.selector.ObjectSelectorBuilder;
import com.emcy.selector.OnObjectSelectorListener;
import com.emcy.selector.OnValuesSelectorListener;
import com.emcy.selector.SelectorActivityAttributes;
import com.emcy.selector.SelectorBDFragmentAttributes;
import com.emcy.selector.ValuesSelectorBuilder;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements OnValuesSelectorListener, OnObjectSelectorListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onSingleObjectActivity(View view) {
ObjectSelectorBuilder.with(this)
.setClass(Dummy.class)
.setSelectedObject(3)
.startActivityForResult(this, getSelectorAttrsForActivity());
}
public void onSingleObjectActivitySearch(View view) {
ObjectSelectorBuilder.with(this)
.setClass(Dummy.class)
.setSelectedObject(3)
.startActivityForResult(this, getSelectorAttrsForActivitySearch());
}
public void onMultipleObjectActivity(View view) {
ObjectSelectorBuilder.with(this)
.setClass(Dummy.class)
.multipleSelection()
.setSelectedObjects(getSelectedObjects())
.startActivityForResult(this, getSelectorAttrsForActivity());
}
public void onMultipleObjectActivitySearch(View view) {
ObjectSelectorBuilder.with(this)
.setClass(Dummy.class)
.multipleSelection()
.setSelectedObjects(getSelectedObjects())
.startActivityForResult(this, getSelectorAttrsForActivitySearch());
}
public void onSingleValueActivity(View view) {
ValuesSelectorBuilder.with(this)
.setDisplayValues(getDisplayedValues())
.setSelectedValue("Value 3")
.startActivityForResult(this, getSelectorAttrsForActivity());
}
public void onSingleValueActivitySearch(View view) {
ValuesSelectorBuilder.with(this)
.setDisplayValues(getDisplayedValues())
.setSelectedValue("Value 3")
.startActivityForResult(this, getSelectorAttrsForActivitySearch());
}
public void onMultipleValuesActivity(View view) {
ValuesSelectorBuilder.with(this)
.setDisplayValues(getDisplayedValues())
.multipleSelection()
.setSelectedValues(getSelectedValues())
.startActivityForResult(this, getSelectorAttrsForActivity());
}
public void onMultipleValuesActivitySearch(View view) {
ValuesSelectorBuilder.with(this)
.setDisplayValues(getDisplayedValues())
.multipleSelection()
.setSelectedValues(getSelectedValues())
.startActivityForResult(this, getSelectorAttrsForActivitySearch());
}
public void onSingleObjectFragment(View view) {
ObjectSelectorBuilder.with(this)
.setClass(Dummy.class)
.setSelectedObject(3)
.showBottomDialogFragment(this, getSelectorAttrsForBottom());
}
public void onSingleObjectFragmentSearch(View view) {
ObjectSelectorBuilder.with(this)
.setClass(Dummy.class)
.setSelectedObject(3)
.showBottomDialogFragment(this, getSelectorAttrsForBottomSearch());
}
public void onMultipleObjectFragment(View view) {
ObjectSelectorBuilder.with(this)
.setClass(Dummy.class)
.multipleSelection()
.setSelectedObjects(getSelectedObjects())
.showBottomDialogFragment(this, getSelectorAttrsForBottom());
}
public void onMultipleObjectFragmentSearch(View view) {
ObjectSelectorBuilder.with(this)
.setClass(Dummy.class)
.multipleSelection()
.setSelectedObjects(getSelectedObjects())
.showBottomDialogFragment(this, getSelectorAttrsForBottomSearch());
}
public void onSingleValueFragment(View view) {
ValuesSelectorBuilder.with(this)
.setDisplayValues(getDisplayedValues())
.setSelectedValue("Value 3")
.showBottomDialogFragment(this, getSelectorAttrsForBottom());
}
public void onSingleValueFragmentSearch(View view) {
ValuesSelectorBuilder.with(this)
.setDisplayValues(getDisplayedValues())
.setSelectedValue("Value 3")
.showBottomDialogFragment(this, getSelectorAttrsForBottomSearch());
}
public void onMultipleValuesFragment(View view) {
ValuesSelectorBuilder.with(this)
.setDisplayValues(getDisplayedValues())
.multipleSelection()
.setSelectedValues(getSelectedValues())
.showBottomDialogFragment(this, getSelectorAttrsForBottom());
}
public void onMultipleValuesFragmentSearch(View view) {
ValuesSelectorBuilder.with(this)
.setDisplayValues(getDisplayedValues())
.multipleSelection()
.setSelectedValues(getSelectedValues())
.showBottomDialogFragment(this, getSelectorAttrsForBottomSearch());
}
public void onSingleObjectSelectorView(View view) {
Intent intent = new Intent(this, SelectorViewTest.class);
intent.putExtra("type", 0);
startActivity(intent);
}
public void onSingleObjectSelectorViewSearch(View view) {
Intent intent = new Intent(this, SelectorViewTest.class);
intent.putExtra("type", 1);
startActivity(intent);
}
public void onMultipleObjectSelectorView(View view) {
Intent intent = new Intent(this, SelectorViewTest.class);
intent.putExtra("type", 2);
startActivity(intent);
}
public void onMultipleObjectSelectorViewSearch(View view) {
Intent intent = new Intent(this, SelectorViewTest.class);
intent.putExtra("type", 3);
startActivity(intent);
}
public void onSingleValueSelectorView(View view) {
Intent intent = new Intent(this, SelectorViewTest.class);
intent.putExtra("type", 4);
startActivity(intent);
}
public void onSingleValueSelectorViewSearch(View view) {
Intent intent = new Intent(this, SelectorViewTest.class);
intent.putExtra("type", 5);
startActivity(intent);
}
public void onMultipleValuesSelectorView(View view) {
Intent intent = new Intent(this, SelectorViewTest.class);
intent.putExtra("type", 6);
startActivity(intent);
}
public void onMultipleValuesSelectorViewSearch(View view) {
Intent intent = new Intent(this, SelectorViewTest.class);
intent.putExtra("type", 7);
startActivity(intent);
}
private List<Long> getSelectedObjects() {
List<Long> selectedObjects = new ArrayList<>();
selectedObjects.add(2L);
selectedObjects.add(4L);
return selectedObjects;
}
private List<String> getSelectedValues() {
List<String> stringList = new ArrayList<>();
stringList.add("Value 2");
stringList.add("Value 4");
return stringList;
}
private SelectorActivityAttributes getSelectorAttrsForActivity() {
return SelectorActivityAttributes.instance()
.setTextNormalColor(R.color.black)
.setNormalTickColor(R.color.black)
.setBackArrowColor(R.color.blue)
.setToolbarColor(R.color.blue)
.setListItemBackgroundColor(R.color.pink)
.setBackArrowColor(R.color.pink)
.setSearchFont("fonts/Roboto-ThinItalic.ttf")
.setTitleFont("fonts/Roboto-BoldItalic.ttf")
.setTextFont("fonts/Roboto-BoldItalic.ttf")
.setActionButtonsFont("fonts/Roboto-BoldItalic.ttf")
.enableSelectedItemsCount()
.setTextMarginStartPercent(0.04f)
.setTickMarginEndPercent(0.96f);
}
private SelectorActivityAttributes getSelectorAttrsForActivitySearch() {
return SelectorActivityAttributes.instance()
.setTextNormalColor(R.color.black)
.setNormalTickColor(R.color.black)
.setBackArrowColor(R.color.blue)
.enableSelectedItemsCount()
.setEnableSearchView(true)
.setSearchFont("fonts/Roboto-ThinItalic.ttf")
.setTitleFont("fonts/Roboto-BoldItalic.ttf")
.setTextFont("fonts/Roboto-BoldItalic.ttf")
.setActionButtonsFont("fonts/Roboto-BoldItalic.ttf")
.setSearchCornerRadius(R.dimen.searchViewCornerRadius)
.setSearchBackgroundColor(R.color.searchViewColor)
.setTextMarginStartPercent(0.04f)
.setTickMarginEndPercent(0.96f);
}
private SelectorBDFragmentAttributes getSelectorAttrsForBottom() {
return SelectorBDFragmentAttributes.instance()
.setTextNormalColor(R.color.black)
.setNormalTickColor(R.color.black)
.setDoneButtonTextColor(R.color.pink)
.setListItemBackgroundColor(R.color.blue)
.enableSelectedItemsCount()
.setTitleFont("fonts/Roboto-BoldItalic.ttf")
.setActionButtonsFont("fonts/Roboto-BoldItalic.ttf")
.setTextFont("fonts/Roboto-BoldItalic.ttf")
.setToolbarColor(R.color.colorAccent)
.setTextMarginStartPercent(0.04f)
.setTickMarginEndPercent(0.96f);
}
private SelectorBDFragmentAttributes getSelectorAttrsForBottomSearch() {
return SelectorBDFragmentAttributes.instance()
.setTextNormalColor(R.color.black)
.setNormalTickColor(R.color.black)
.enableSelectedItemsCount()
.setEnableSearchView(true)
.setTitleFont("fonts/Roboto-Thin.ttf")
.setActionButtonsFont("fonts/Roboto-BoldItalic.ttf")
.setSearchFont("fonts/Roboto-ThinItalic.ttf")
.setTextFont("fonts/Roboto-BoldItalic.ttf")
.setTextMarginStartPercent(0.04f)
.setTickMarginEndPercent(0.96f);
}
private List<String> getDisplayedValues() {
List<String> array = new ArrayList<>();
for (int x = 0; x < 4; x++) {
array.add("Value " + x);
}
return array;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ValuesSelectorBuilder.with(this).registerActivityResult(requestCode, resultCode, data);
ObjectSelectorBuilder.with(this).registerActivityResult(requestCode, resultCode, data);
}
@Override
public void onValueClick(String value) {
if (value != null)
Toast.makeText(this, " " + value, Toast.LENGTH_SHORT).show();
}
@Override
public void onValuesSelected(List<String> selectedValues) {
if (selectedValues != null && selectedValues.size() != 0)
Toast.makeText(this, " " + selectedValues, Toast.LENGTH_SHORT).show();
}
@Override
public void onValuesUpdated(List<String> selectedValues) {
if (selectedValues != null && selectedValues.size() != 0)
Toast.makeText(this, " " + selectedValues, Toast.LENGTH_SHORT).show();
}
@Override
public void onObjectClick(long id) {
if (id != -1)
Toast.makeText(this, " " + id, Toast.LENGTH_SHORT).show();
}
@Override
public void onObjectsSelected(List<Long> selectedIds) {
if (selectedIds != null && selectedIds.size() != 0)
Toast.makeText(this, " " + selectedIds, Toast.LENGTH_SHORT).show();
}
@Override
public void onObjectsUpdated(List<Long> selectedIds) {
if (selectedIds != null && selectedIds.size() != 0)
Toast.makeText(this, " " + selectedIds, Toast.LENGTH_SHORT).show();
}
@Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}
| 38.49848 | 115 | 0.644639 |
e730bcaf0f07447996221dbd3eb5414e14f9a273 | 589 | package net.mh.kafkabrowser.resource;
import net.mh.kafkabrowser.resource.error.ErrorMessage;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
/**
* Created by markus on 09.04.17.
*/
public class AbstractResource {
@ExceptionHandler({IllegalArgumentException.class})
public ResponseEntity<ErrorMessage> handleException(IllegalArgumentException exception) {
return new ResponseEntity<>(new ErrorMessage(exception.getMessage()), HttpStatus.BAD_REQUEST);
}
}
| 32.722222 | 102 | 0.797963 |
44fde608e2314f1f89519ced68a8e6d148b376da | 820 | package net.thedocruby.mimicraft.block;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
import net.minecraft.block.Material;
import net.minecraft.sound.BlockSoundGroup;
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry;
public class MimicraftBlocks {
public static final MimicreamBlock MIMICREAM_BLOCK = new MimicreamBlock(
FabricBlockSettings
.of(Material.ORGANIC_PRODUCT)
.strength(0.2f, 2.5f)
.jumpVelocityMultiplier(0.2f)
.slipperiness(1.2f)
.sounds(BlockSoundGroup.SLIME)
);
public static void registerBlocks(){
Registry.register(Registry.BLOCK, new Identifier("mimicraft", "mimicream_block"), MIMICREAM_BLOCK);
}
}
| 35.652174 | 107 | 0.685366 |
c487caa1905c2436a7943a49c94af0e311d5d02a | 4,376 | import net.runelite.mapping.Export;
import net.runelite.mapping.Implements;
import net.runelite.mapping.ObfuscatedGetter;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
@ObfuscatedName("ak")
@Implements("AbstractWorldMapIcon")
public abstract class AbstractWorldMapIcon {
@ObfuscatedName("qj")
@ObfuscatedGetter(
intValue = -1942470229
)
@Export("__ak_qj")
static int __ak_qj;
@ObfuscatedName("ka")
@ObfuscatedGetter(
intValue = -1734004743
)
@Export("menuHeight")
static int menuHeight;
@ObfuscatedName("g")
@ObfuscatedSignature(
signature = "Lhu;"
)
@Export("coord2")
public final TileLocation coord2;
@ObfuscatedName("l")
@ObfuscatedSignature(
signature = "Lhu;"
)
@Export("coord1")
public final TileLocation coord1;
@ObfuscatedName("e")
@ObfuscatedGetter(
intValue = -521086143
)
@Export("__e")
int __e;
@ObfuscatedName("x")
@ObfuscatedGetter(
intValue = -1065362217
)
@Export("__x")
int __x;
@ObfuscatedSignature(
signature = "(Lhu;Lhu;)V"
)
AbstractWorldMapIcon(TileLocation var1, TileLocation var2) {
this.coord1 = var1;
this.coord2 = var2;
}
@ObfuscatedName("m")
@ObfuscatedSignature(
signature = "(I)I",
garbageValue = "1990181988"
)
public abstract int __m_15();
@ObfuscatedName("f")
@ObfuscatedSignature(
signature = "(I)Laj;",
garbageValue = "1159446036"
)
abstract WorldMapLabel __f_16();
@ObfuscatedName("q")
@ObfuscatedSignature(
signature = "(B)I",
garbageValue = "75"
)
abstract int __q_17();
@ObfuscatedName("w")
@ObfuscatedSignature(
signature = "(I)I",
garbageValue = "-1558233611"
)
abstract int __w_18();
@ObfuscatedName("y")
@ObfuscatedSignature(
signature = "(IIB)Z",
garbageValue = "-63"
)
@Export("__y_66")
boolean __y_66(int var1, int var2) {
return this.__b_68(var1, var2)?true:this.__c_69(var1, var2);
}
@ObfuscatedName("h")
@ObfuscatedSignature(
signature = "(I)Z",
garbageValue = "1150380891"
)
@Export("__h_67")
boolean __h_67() {
return this.__m_15() >= 0;
}
@ObfuscatedName("b")
@ObfuscatedSignature(
signature = "(III)Z",
garbageValue = "484201257"
)
@Export("__b_68")
boolean __b_68(int var1, int var2) {
if(!this.__h_67()) {
return false;
} else {
WorldMapElement var3 = ViewportMouse.getWorldMapElement(this.__m_15());
int var4 = this.__q_17();
int var5 = this.__w_18();
switch(var3.field3287.field3528) {
case 0:
if(var1 < this.__e - var4 / 2 || var1 > var4 / 2 + this.__e) {
return false;
}
break;
case 1:
if(var1 >= this.__e && var1 < var4 + this.__e) {
break;
}
return false;
case 2:
if(var1 <= this.__e - var4 || var1 > this.__e) {
return false;
}
}
switch(var3.field3301.field3275) {
case 0:
if(var2 <= this.__x - var5 || var2 > this.__x) {
return false;
}
break;
case 1:
if(var2 < this.__x - var5 / 2 || var2 > var5 / 2 + this.__x) {
return false;
}
break;
case 2:
if(var2 < this.__x || var2 >= var5 + this.__x) {
return false;
}
}
return true;
}
}
@ObfuscatedName("c")
@ObfuscatedSignature(
signature = "(III)Z",
garbageValue = "1201712205"
)
@Export("__c_69")
boolean __c_69(int var1, int var2) {
WorldMapLabel var3 = this.__f_16();
return var3 == null?false:(var1 >= this.__e - var3.width / 2 && var1 <= var3.width / 2 + this.__e?var2 >= this.__x && var2 <= var3.height + this.__x:false);
}
@ObfuscatedName("es")
@ObfuscatedSignature(
signature = "(Lit;Ljava/lang/String;I)V",
garbageValue = "-1018878027"
)
static void method625(IndexCache var0, String var1) {
IndexCacheLoader var2 = new IndexCacheLoader(var0, var1);
Client.indexCacheLoaders.add(var2);
Client.__client_sx += var2.__q;
}
}
| 24.723164 | 162 | 0.572212 |
8ded0a934bfb251e2867cd795631434906937172 | 231 | package com.demidovn.fruitbounty.server.exceptions;
public class RequestOperationValidationException extends AbstractGameServerException {
public RequestOperationValidationException(String message) {
super(message);
}
}
| 23.1 | 86 | 0.82684 |
5e66c574a89eec68475e613222f4f00077ff2567 | 1,501 | package com.rsoft.app.services.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.rsoft.app.domain.Purchase;
import com.rsoft.app.repositories.PurchaseRepository;
import com.rsoft.app.services.IPurchaseService;
@Service
public class PurchaseServiceImpl implements IPurchaseService {
@Autowired
private PurchaseRepository purchaseRepository;
@Override
public List<Purchase> getPurchases() {
List<Purchase> purchases = new ArrayList<Purchase>();
Iterator<Purchase> itr = purchaseRepository.findAll().iterator();
while(itr.hasNext())
purchases.add(itr.next());
return purchases;
}
@Transactional
@Override
public Purchase savePurchase(Purchase purchasse) {
return purchaseRepository.save(purchasse);
}
@Override
public Purchase getPurchase(Long id) {
return purchaseRepository.findOne(id);
}
@Transactional
@Override
public Purchase delePurchase(Long id) {
Purchase purchase = getPurchase(id);
purchaseRepository.delete(purchase);
return purchase;
}
@Override
public List<Purchase> fetchByPurchaseDate(Date purchaseDate) {
// TODO Auto-generated method stub
return null;
}
@Transactional
@Override
public Purchase updatePurchase(Purchase purchase) {
return purchaseRepository.save(purchase);
}
}
| 23.453125 | 67 | 0.785476 |
0ec0675b075a9ef7ae8d7afbf59c58b77e6b5f96 | 2,957 | package blockChainProgram;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;
import java.lang.String;
public class BlockChainDriver {
public BlockChainDriver() {
}
public static void printBlockChain(PrintWriter pen, BlockChain chain) {
pen.println(chain.toString());
}
//Credits: "Simple Java for C Programmers" reading from class
public static void main (String[] args) throws NumberFormatException, NoSuchAlgorithmException {
//initialize ouput and input
PrintWriter pen = new PrintWriter(System.out, true);
Scanner in = new Scanner(System.in);
//initialize helper variables
boolean done = false;
String input = "";
//initialize BlockChain
BlockChain chain = new BlockChain(Integer.parseInt(args[0]));
while (!done) {
//print blockChain
pen.println(chain.toString());
//prompt for input
pen.println("Command? ");
input = in.next();
//run command
//Mine
if (input.contentEquals("mine")) {
pen.println("Amount Transferred? ");
input = in.next();
//print transfer amount and mined nonce
Block newBlock = chain.mine(Integer.parseInt(input));
pen.println("Amount = " + input + ", nonce = " + newBlock.getNonce() + "Resultant Hash: " + newBlock.getHash().toString());
//pen.println("Amount = " + input + ", nonce = " + chain.mine(Integer.parseInt(input)).getNonce() + "Resultant Hash: " + );
pen.flush();
//Append
} else if (input.contentEquals("append")) {
pen.println("Amount Transferred? ");
input = in.next();
pen.println("Nonce? ");
long nonceInput = Long.parseLong(in.next());
//append new block
chain.append(new Block(chain.getSize(), Integer.parseInt(input), chain.getHash(), nonceInput));
pen.flush();
//Remove
} else if (input.contentEquals("remove")) {
chain.removeLast();
pen.flush();
//Check
}else if (input.contentEquals("check")) {
pen.println("Checking...");
//print isValidBlockChain results
if (chain.isValidBlockChain()) {
pen.println("Chain is valid!");
pen.flush();
} else {
pen.println("Chain is invalid!");
pen.flush();
}
//Report
}else if (input.contentEquals("report")) {
chain.printBalances(pen);
pen.flush();
//Help
} else if (input.contentEquals("help")) {
pen.println("Valid commands:\n" +
" mine: discovers the nonce for a given transaction\n" +
" append: appends a new block onto the end of the chain\n" +
" remove: removes the last block from the end of the chain\n" +
" check: checks that the block chain is valid\n" +
" report: reports the balances of Alice and Bob\n" +
" help: prints this list of commands\n" +
" quit: quits the program");
pen.flush();
} else if (input.contentEquals("quit")) {
done = true;
}
}//end while
in.close();
}//end main
}//end class
| 29.868687 | 127 | 0.641867 |
e869e5ce413cdaafda2225286f723568b4d6bdd6 | 459 | package com.appyhome.appyproduct.mvvm.data.model.api.product;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class DeleteWishListRequest {
@Expose
@SerializedName("product_id")
public long product_id;
@Expose
@SerializedName("variant_id")
public int variant_id;
public DeleteWishListRequest(long idP, int idV) {
product_id = idP;
variant_id = idV;
}
}
| 21.857143 | 61 | 0.716776 |
e77f1cd054978307ec6012ae50f2834d8e6d0c1a | 1,756 | /**
* Copyright 2013 Daniel Valcarce Silva
*
* 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 es.udc.fi.dc.irlab.rm;
import java.io.IOException;
import org.apache.hadoop.io.FloatWritable;
import org.apache.mahout.common.IntPairWritable;
import es.udc.fi.dc.irlab.common.AbstractByClusterAndCountMapper;
import es.udc.fi.dc.irlab.util.IntDoubleOrPrefWritable;
import es.udc.fi.dc.irlab.util.StringIntPairWritable;
/**
* Emit <(k, 1), (i, j, A_{i,j})> from HDFS ratings (<(i, j), A_{i,j}>) where
* j is a user from the cluster k.
*/
public class ScoreByClusterHDFSMapper extends
AbstractByClusterAndCountMapper<IntPairWritable, FloatWritable, StringIntPairWritable, IntDoubleOrPrefWritable> {
@Override
protected void map(final IntPairWritable key, final FloatWritable column, final Context context)
throws IOException, InterruptedException {
final float score = column.get();
if (score > 0) {
final int user = key.getFirst();
for (final String split : getSplits(user)) {
context.write(new StringIntPairWritable(split, 1),
new IntDoubleOrPrefWritable(user, key.getSecond(), score));
}
}
}
}
| 34.431373 | 121 | 0.701595 |
f91a4ec030c1a5d064f475efb5fee329413303d1 | 900 | package com.example.apch9.takepizza.Model;
/**
* Created by Marek on 2018-02-15.
*/
public class Restaurant {
private String Name, City, Address, Image;
public Restaurant() {
}
public Restaurant(String name, String city, String address, String image) {
Name = name;
City = city;
Address = address;
Image = image;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getCity() {
return City;
}
public void setCity(String city) {
City = city;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
}
| 16.981132 | 79 | 0.566667 |
ad18b61c481bbbe7d72b69240c2916b45bf2939e | 3,164 | package zephyr.guava;
import com.google.common.collect.*;
import com.google.common.primitives.Ints;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Slf4j
public class CollectionUtilitiesDemo {
public static void main(String[] args) {
// Static constructors
final List<String> list = Lists.newArrayList("alpha", "beta", "gamma");
log.info("{}", list);
// 精确100
List<String> exactly100 = Lists.newArrayListWithCapacity(100);
// 大约100
List<String> approx100 = Lists.newArrayListWithExpectedSize(100);
// Iterables
Iterable<Integer> concatenated = Iterables.concat(
Ints.asList(1, 2, 3),
Ints.asList(4, 5, 6)
);
log.info("{}", concatenated);
log.info("{}", Iterables.getLast(concatenated));
log.info("{}", Iterables.getOnlyElement(Lists.newArrayList("a")));
List<Integer> countUp = Ints.asList(1, 2, 3, 4, 5);
List<Integer> countDown = Lists.reverse(countUp); // {5, 4, 3, 2, 1}
List<List<Integer>> parts = Lists.partition(countUp, 2); // {{1, 2}, {3, 4}, {5}}
log.info("");
log.info("Lists");
log.info("{}", countUp);
log.info("{}", countDown);
log.info("{}", parts);
Set<String> wordsWithPrimeLength = ImmutableSet.of("one", "two", "three", "six", "seven", "eight");
Set<String> primes = ImmutableSet.of("two", "three", "five", "seven");
// 交集
Sets.SetView<String> intersection = Sets.intersection(primes, wordsWithPrimeLength);
log.info("");
log.info("Sets");
log.info("{}", wordsWithPrimeLength);
log.info("{}", primes);
log.info("{}", intersection);
Set<String> animals = ImmutableSet.of("gerbil", "hamster");
Set<String> fruits = ImmutableSet.of("apple", "orange", "banana");
// 笛卡尔积
Set<List<String>> product = Sets.cartesianProduct(animals, fruits);
// {{"gerbil", "apple"}, {"gerbil", "orange"}, {"gerbil", "banana"},
// {"hamster", "apple"}, {"hamster", "orange"}, {"hamster", "banana"}}
// 所有子集
Set<Set<String>> animalSets = Sets.powerSet(animals);
// {{}, {"gerbil"}, {"hamster"}, {"gerbil", "hamster"}}
log.info("");
log.info("{}", product);
log.info("{}", animalSets);
// uniqueIndex
ImmutableMap<Integer, String> stringsByIndex = Maps.uniqueIndex(animals, s -> s != null ? s.length() : 0);
log.info("");
log.info("{}", stringsByIndex);
// difference
Map<String, Integer> left = ImmutableMap.of("a", 1, "b", 2, "c", 3);
Map<String, Integer> right = ImmutableMap.of("b", 2, "c", 4, "d", 5);
MapDifference<String, Integer> diff = Maps.difference(left, right);
log.info("");
log.info("{}", diff.entriesInCommon()); // {"b" => 2}
log.info("{}", diff.entriesDiffering()); // {"c" => (3, 4)}
log.info("{}", diff.entriesOnlyOnLeft()); // {"a" => 1}
log.info("{}", diff.entriesOnlyOnRight()); // {"d" => 5}
}
}
| 36.790698 | 114 | 0.557838 |
3d8a17081697f2b1a7bbbcfef184d671cd037fbe | 300 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.mskcc.shenkers.control.track.fasta;
/**
*
* @author sol
*/
public enum Frame {
p0, p1, p2;
};
| 18.75 | 79 | 0.69 |
36fd500a715910d43cf4c43b8f9ab824783c29eb | 845 | package com.test.quartz;
import com.kaka.notice.Facade;
import com.kaka.notice.FacadeFactory;
import com.kaka.notice.Message;
import org.quartz.*;
public class MessageJob implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
JobDetail jobDetail = jobExecutionContext.getJobDetail();
JobKey jobKey = jobDetail.getKey();
String jobName = jobKey.getName(); //对应Message.what
JobDataMap jobDataMap = jobDetail.getJobDataMap();
Object obj = jobDataMap.get(jobName);
if (!(obj instanceof Message)) {
return;
}
Message msg = (Message) obj;
String facadeName = jobDataMap.getString("facade");
Facade facade = FacadeFactory.getFacade(facadeName);
facade.sendMessage(msg);
}
}
| 33.8 | 95 | 0.687574 |
fb89ee70f9e2eb452b2c967b937f0b8a042a918c | 2,868 | //
// Pythagoras - a collection of geometry classes
// http://github.com/samskivert/pythagoras
package pythagoras.f;
/**
* {@link Transform} related utility methods.
*/
public class Transforms
{
/**
* Creates and returns a new shape that is the supplied shape transformed by this transform's
* matrix.
*/
public static IShape createTransformedShape (Transform t, IShape src) {
if (src == null) {
return null;
}
if (src instanceof Path) {
return ((Path)src).createTransformedShape(t);
}
PathIterator path = src.pathIterator(t);
Path dst = new Path(path.windingRule());
dst.append(path, false);
return dst;
}
/**
* Multiplies the supplied two affine transforms, storing the result in {@code into}. {@code
* into} may refer to the same instance as {@code a} or {@code b}.
* @return {@code into} for chaining.
*/
public static <T extends Transform> T multiply (AffineTransform a, AffineTransform b, T into) {
return multiply(a.m00, a.m01, a.m10, a.m11, a.tx, a.ty,
b.m00, b.m01, b.m10, b.m11, b.tx, b.ty, into);
}
/**
* Multiplies the supplied two affine transforms, storing the result in {@code into}. {@code
* into} may refer to the same instance as {@code a}.
* @return {@code into} for chaining.
*/
public static <T extends Transform> T multiply (
AffineTransform a, float m00, float m01, float m10, float m11, float tx, float ty, T into) {
return multiply(a.m00, a.m01, a.m10, a.m11, a.tx, a.ty, m00, m01, m10, m11, tx, ty, into);
}
/**
* Multiplies the supplied two affine transforms, storing the result in {@code into}. {@code
* into} may refer to the same instance as {@code b}.
* @return {@code into} for chaining.
*/
public static <T extends Transform> T multiply (
float m00, float m01, float m10, float m11, float tx, float ty, AffineTransform b, T into) {
return multiply(m00, m01, m10, m11, tx, ty, b.m00, b.m01, b.m10, b.m11, b.tx, b.ty, into);
}
/**
* Multiplies the supplied two affine transforms, storing the result in {@code into}.
* @return {@code into} for chaining.
*/
public static <T extends Transform> T multiply (
float am00, float am01, float am10, float am11, float atx, float aty,
float bm00, float bm01, float bm10, float bm11, float btx, float bty, T into) {
into.setTransform(am00 * bm00 + am10 * bm01,
am01 * bm00 + am11 * bm01,
am00 * bm10 + am10 * bm11,
am01 * bm10 + am11 * bm11,
am00 * btx + am10 * bty + atx,
am01 * btx + am11 * bty + aty);
return into;
}
}
| 38.24 | 100 | 0.581241 |
02e20be21dc3baf28c3eef0ecb7998658eee65dc | 1,455 | package com.hjq.toast;
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
/**
* author : Android 轮子哥
* github : https://github.com/getActivity/ToastUtils
* time : 2021/04/07
* desc : Activity 生命周期监控
*/
final class ActivityStack implements Application.ActivityLifecycleCallbacks {
/**
* 注册
*/
static ActivityStack register(Application application) {
ActivityStack lifecycle = new ActivityStack();
application.registerActivityLifecycleCallbacks(lifecycle);
return lifecycle;
}
/** 前台 Activity 对象 */
private Activity mForegroundActivity;
public Activity getForegroundActivity() {
return mForegroundActivity;
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {}
@Override
public void onActivityStarted(Activity activity) {}
@Override
public void onActivityResumed(Activity activity) {
mForegroundActivity = activity;
}
@Override
public void onActivityPaused(Activity activity) {
if (mForegroundActivity != activity) {
return;
}
mForegroundActivity = null;
}
@Override
public void onActivityStopped(Activity activity) {}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}
@Override
public void onActivityDestroyed(Activity activity) {}
} | 25.086207 | 82 | 0.68866 |
9104bf20f3f4c87790d192b8ae79b376c22231f2 | 2,559 | package de.cinovo.cloudconductor.api.model;
import java.util.Date;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
import de.cinovo.cloudconductor.api.interfaces.INamed;
/**
* Copyright 2017 Cinovo AG<br>
* <br>
*
* @author mweise
*
*/
@JsonTypeInfo(include = As.PROPERTY, use = Id.CLASS)
public class SSHKey implements INamed {
private String owner;
private String username;
private String key;
private Date lastChanged;
private List<String> templates;
/**
* Create a new ssh key.
*/
public SSHKey() {
}
/**
*
* @param owner the name of the key owner
* @param key the content of the key
*/
public SSHKey(String owner, String key) {
this.owner = owner;
this.key = key;
this.lastChanged = new Date();
}
/**
* @param owner the owner of the ssh key
* @param key the content of the ssh key
* @param lastChangedDate the timestamp of the last change
*/
public SSHKey(String owner, String key, Long lastChangedDate) {
this.owner = owner;
this.key = key;
this.lastChanged = new Date(lastChangedDate);
}
/**
* @return owner of the ssh key
*/
public String getOwner() {
return this.owner;
}
/**
* @param owner the name of the owner to set
*/
public void setOwner(String owner) {
this.owner = owner;
}
/**
* @return the user name for the ssh key
*/
public String getUsername() {
return this.username;
}
/**
* @param username the user name to set
*/
public void setUsername(String username) {
this.username = username;
}
/**
* @return the content of the ssh key
*/
public String getKey() {
return this.key;
}
/**
* @param key the key to set
*/
public void setKey(String key) {
this.key = key;
}
/**
* @return the last date when this key was created or changed
*/
public Date getLastChanged() {
return this.lastChanged;
}
/**
* @param lastChanged the change date to set
*/
public void setLastChanged(Date lastChanged) {
this.lastChanged = lastChanged;
}
/**
* @return set of template names this ssh key belongs to
*/
public List<String> getTemplates() {
return this.templates;
}
/**
* @param templates the template names to set
*/
public void setTemplates(List<String> templates) {
this.templates = templates;
}
@JsonIgnore
@Override
public String getName() {
return this.owner;
}
}
| 18.678832 | 64 | 0.676045 |
7c4efc5d01ef6da65f2f7091b4a9f73c538d262f | 1,275 | package br.com.marcos.zupacademy.mercadolivre.produto.modelo;
import br.com.marcos.zupacademy.mercadolivre.usuario.modelo.Usuario;
import javax.persistence.*;
@Entity
public class OpiniaoDoProduto {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Integer nota;
@Column(nullable = false)
private String titulo;
@Column(nullable = false)
private String descricao;
@ManyToOne
private Usuario usuarioQueOpinou;
@ManyToOne
private Produto produto;
@Deprecated
public OpiniaoDoProduto() {
}
public OpiniaoDoProduto(Integer nota,
String titulo,
String descricao,
Usuario usuarioQueOpinou,
Produto produto) {
this.nota = nota;
this.titulo = titulo;
this.descricao = descricao;
this.usuarioQueOpinou = usuarioQueOpinou;
this.produto = produto;
}
public Integer getNota() {
return nota;
}
public String getTitulo() {
return titulo;
}
public String getDescricao() {
return descricao;
}
public Usuario getUsuarioQueOpinou() {
return usuarioQueOpinou;
}
}
| 21.25 | 68 | 0.612549 |
4bd96c72f183f230b94a1ac7947a32a7a51946b4 | 3,237 | /*
* $Id$
*
* 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.struts2.rest.handler;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.Collection;
import com.opensymphony.xwork2.ActionInvocation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.struts2.StrutsConstants;
import com.opensymphony.xwork2.inject.Inject;
/**
* Handles JSON content using json-lib
*/
public class JsonLibHandler extends AbstractContentTypeHandler {
private static final String DEFAULT_CONTENT_TYPE = "application/json";
private String defaultEncoding = "ISO-8859-1";
public void toObject(ActionInvocation invocation, Reader in, Object target) throws IOException {
StringBuilder sb = new StringBuilder();
char[] buffer = new char[1024];
int len = 0;
while ((len = in.read(buffer)) > 0) {
sb.append(buffer, 0, len);
}
if (target != null && sb.length() > 0 && sb.charAt(0) == '[') {
JSONArray jsonArray = JSONArray.fromObject(sb.toString());
if (target.getClass().isArray()) {
JSONArray.toArray(jsonArray, target, new JsonConfig());
} else {
JSONArray.toList(jsonArray, target, new JsonConfig());
}
} else {
JSONObject jsonObject = JSONObject.fromObject(sb.toString());
JSONObject.toBean(jsonObject, target, new JsonConfig());
}
}
public String fromObject(ActionInvocation invocation, Object obj, String resultCode, Writer stream) throws IOException {
if (obj != null) {
if (isArray(obj)) {
JSONArray jsonArray = JSONArray.fromObject(obj);
stream.write(jsonArray.toString());
} else {
JSONObject jsonObject = JSONObject.fromObject(obj);
stream.write(jsonObject.toString());
}
}
return null;
}
private boolean isArray(Object obj) {
return obj instanceof Collection || obj.getClass().isArray();
}
public String getContentType() {
return DEFAULT_CONTENT_TYPE+";charset=" + this.defaultEncoding;
}
public String getExtension() {
return "json";
}
@Inject(StrutsConstants.STRUTS_I18N_ENCODING)
public void setDefaultEncoding(String val) {
this.defaultEncoding = val;
}
}
| 32.69697 | 124 | 0.660179 |
f6fd04b3ed8dc041b86173eb3b9d5c091ea02cfb | 38,355 | /*
* Copyright 2017-2020 original 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 io.micronaut.data.runtime.mapper.sql;
import java.sql.Array;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.StringJoiner;
import java.util.function.BiFunction;
import io.micronaut.core.annotation.AnnotationMetadata;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.core.annotation.Internal;
import io.micronaut.core.beans.BeanIntrospection;
import io.micronaut.core.beans.BeanProperty;
import io.micronaut.core.beans.BeanWrapper;
import io.micronaut.core.convert.ConversionService;
import io.micronaut.core.reflect.exception.InstantiationException;
import io.micronaut.core.type.Argument;
import io.micronaut.core.util.ArgumentUtils;
import io.micronaut.core.util.ArrayUtils;
import io.micronaut.core.util.CollectionUtils;
import io.micronaut.data.annotation.Embeddable;
import io.micronaut.data.annotation.EmbeddedId;
import io.micronaut.data.annotation.Relation;
import io.micronaut.data.annotation.TypeDef;
import io.micronaut.data.exceptions.DataAccessException;
import io.micronaut.data.model.Association;
import io.micronaut.data.model.DataType;
import io.micronaut.data.model.Embedded;
import io.micronaut.data.model.PersistentProperty;
import io.micronaut.data.model.naming.NamingStrategy;
import io.micronaut.data.model.query.JoinPath;
import io.micronaut.data.model.runtime.RuntimeAssociation;
import io.micronaut.data.model.runtime.RuntimePersistentEntity;
import io.micronaut.data.model.runtime.RuntimePersistentProperty;
import io.micronaut.data.runtime.mapper.ResultReader;
import io.micronaut.http.codec.MediaTypeCodec;
import javax.validation.constraints.NotNull;
/**
* A {@link io.micronaut.data.runtime.mapper.TypeMapper} that can take a {@link RuntimePersistentEntity} and a {@link ResultReader} and materialize an instance using
* using column naming conventions mapped by the entity.
*
* @param <RS> The result set type
* @param <R> The result type
*/
@Internal
public final class SqlResultEntityTypeMapper<RS, R> implements SqlTypeMapper<RS, R> {
private final RuntimePersistentEntity<R> entity;
private final ResultReader<RS, String> resultReader;
private final Map<String, JoinPath> joinPaths;
private final String startingPrefix;
private final MediaTypeCodec jsonCodec;
private final BiFunction<RuntimePersistentEntity<Object>, Object, Object> eventListener;
private boolean callNext = true;
/**
* Default constructor.
* @param prefix The prefix to startup from.
* @param entity The entity
* @param resultReader The result reader
* @param jsonCodec The JSON codec
*/
public SqlResultEntityTypeMapper(
String prefix,
@NonNull RuntimePersistentEntity<R> entity,
@NonNull ResultReader<RS, String> resultReader,
@Nullable MediaTypeCodec jsonCodec) {
this(entity, resultReader, Collections.emptySet(), prefix, jsonCodec, null);
}
/**
* Constructor used to customize the join paths.
* @param entity The entity
* @param resultReader The result reader
* @param joinPaths The join paths
* @param jsonCodec The JSON codec
*/
public SqlResultEntityTypeMapper(
@NonNull RuntimePersistentEntity<R> entity,
@NonNull ResultReader<RS, String> resultReader,
@Nullable Set<JoinPath> joinPaths,
@Nullable MediaTypeCodec jsonCodec) {
this(entity, resultReader, joinPaths, null, jsonCodec, null);
}
/**
* Constructor used to customize the join paths.
* @param entity The entity
* @param resultReader The result reader
* @param joinPaths The join paths
* @param jsonCodec The JSON codec
* @param loadListener The event listener
*/
public SqlResultEntityTypeMapper(
@NonNull RuntimePersistentEntity<R> entity,
@NonNull ResultReader<RS, String> resultReader,
@Nullable Set<JoinPath> joinPaths,
@Nullable MediaTypeCodec jsonCodec,
@Nullable BiFunction<RuntimePersistentEntity<Object>, Object, Object> loadListener) {
this(entity, resultReader, joinPaths, null, jsonCodec, loadListener);
}
/**
* Constructor used to customize the join paths.
* @param entity The entity
* @param resultReader The result reader
* @param joinPaths The join paths
*/
private SqlResultEntityTypeMapper(
@NonNull RuntimePersistentEntity<R> entity,
@NonNull ResultReader<RS, String> resultReader,
@Nullable Set<JoinPath> joinPaths,
String startingPrefix,
@Nullable MediaTypeCodec jsonCodec,
@Nullable BiFunction<RuntimePersistentEntity<Object>, Object, Object> eventListener) {
ArgumentUtils.requireNonNull("entity", entity);
ArgumentUtils.requireNonNull("resultReader", resultReader);
this.entity = entity;
this.jsonCodec = jsonCodec;
this.resultReader = resultReader;
this.eventListener = eventListener;
if (CollectionUtils.isNotEmpty(joinPaths)) {
this.joinPaths = new HashMap<>(joinPaths.size());
for (JoinPath joinPath : joinPaths) {
this.joinPaths.put(joinPath.getPath(), joinPath);
}
} else {
this.joinPaths = Collections.emptyMap();
}
this.startingPrefix = startingPrefix;
}
/**
* @return The entity to be materialized
*/
public @NonNull RuntimePersistentEntity<R> getEntity() {
return entity;
}
/**
* @return The result reader instance.
*/
public @NonNull ResultReader<RS, String> getResultReader() {
return resultReader;
}
@NonNull
@Override
public R map(@NonNull RS rs, @NonNull Class<R> type) throws DataAccessException {
R entityInstance = readEntity(rs, MappingContext.of(entity, startingPrefix), null, null);
if (entityInstance == null) {
throw new DataAccessException("Unable to map result to entity of type [" + type.getName() + "]. Missing result data.");
}
return triggerPostLoad(entity, entityInstance);
}
@Nullable
@Override
public Object read(@NonNull RS resultSet, @NonNull String name) {
RuntimePersistentProperty<R> property = entity.getPropertyByName(name);
if (property == null) {
throw new DataAccessException("DTO projection defines a property [" + name + "] that doesn't exist on root entity: " + entity.getName());
}
DataType dataType = property.getDataType();
String columnName = property.getPersistedName();
return resultReader.readDynamic(resultSet, columnName, dataType);
}
@Nullable
@Override
public Object read(@NonNull RS resultSet, @NonNull Argument<?> argument) {
RuntimePersistentProperty<R> property = entity.getPropertyByName(argument.getName());
DataType dataType;
String columnName;
if (property == null) {
dataType = argument.getAnnotationMetadata()
.enumValue(TypeDef.class, "type", DataType.class)
.orElseGet(() -> DataType.forType(argument.getType()));
columnName = argument.getName();
} else {
dataType = property.getDataType();
columnName = property.getPersistedName();
}
return resultReader.readDynamic(resultSet, columnName, dataType);
}
@Override
public boolean hasNext(RS resultSet) {
if (callNext) {
return resultReader.next(resultSet);
} else {
try {
return true;
} finally {
callNext = true;
}
}
}
/**
* Read one entity with a pushing mapper.
*
* @return The pushing mapper
*/
public PushingMapper<RS, R> readOneWithJoins() {
return new PushingMapper<RS, R>() {
final MappingContext<R> ctx = MappingContext.of(entity, startingPrefix);
R entityInstance;
@Override
public void processRow(RS row) {
if (entityInstance == null) {
Object id = readEntityId(row, ctx);
entityInstance = readEntity(row, ctx, null, id);
} else {
readChildren(row, entityInstance, null, ctx);
}
}
@Override
public R getResult() {
if (entityInstance == null) {
return null;
}
if (!joinPaths.isEmpty()) {
entityInstance = (R) setChildrenAndTriggerPostLoad(entityInstance, ctx);
} else {
return triggerPostLoad(entity, entityInstance);
}
return entityInstance;
}
};
}
/**
* Read multiple entities with a pushing mapper.
*
* @return The pushing mapper
*/
public PushingMapper<RS, List<R>> readAllWithJoins() {
return new PushingMapper<RS, List<R>>() {
final Map<Object, MappingContext<R>> processed = new LinkedHashMap<>();
@Override
public void processRow(RS row) {
MappingContext<R> ctx = MappingContext.of(entity, startingPrefix);
Object id = readEntityId(row, ctx);
if (id == null) {
throw new IllegalStateException("Entity doesn't have an id!");
}
MappingContext<R> prevCtx = processed.get(id);
if (prevCtx != null) {
readChildren(row, prevCtx.entity, null, prevCtx);
} else {
ctx.entity = readEntity(row, ctx, null, id);
processed.put(id, ctx);
}
}
@Override
public List<R> getResult() {
List<R> values = new ArrayList<>(processed.size());
for (Map.Entry<Object, MappingContext<R>> e : processed.entrySet()) {
MappingContext<R> ctx = e.getValue();
R entityInstance = (R) setChildrenAndTriggerPostLoad(ctx.entity, ctx);
values.add(entityInstance);
}
return values;
}
};
}
private void readChildren(RS rs, Object instance, Object parent, MappingContext<R> ctx) {
if (ctx.manyAssociations != null) {
Object id = readEntityId(rs, ctx);
MappingContext associatedCtx = ctx.manyAssociations.get(id);
if (associatedCtx == null) {
associatedCtx = ctx.copy();
R entity = (R) readEntity(rs, associatedCtx, parent, id);
ctx.associate(associatedCtx, id, entity);
} else {
readChildren(rs, instance, parent, associatedCtx);
}
return;
}
if (ctx.associations != null) {
for (Map.Entry<Association, MappingContext> e : ctx.associations.entrySet()) {
MappingContext associationCtx = e.getValue();
RuntimeAssociation runtimeAssociation = (RuntimeAssociation) e.getKey();
Object in = instance == null || !runtimeAssociation.getKind().isSingleEnded() ? null : runtimeAssociation.getProperty().get(instance);
readChildren(rs, in, instance, associationCtx);
}
}
}
private Object setChildrenAndTriggerPostLoad(Object instance, MappingContext<?> ctx) {
if (ctx.manyAssociations != null) {
List<Object> values = new ArrayList<>(ctx.manyAssociations.size());
for (MappingContext associationCtx : ctx.manyAssociations.values()) {
values.add(setChildrenAndTriggerPostLoad(associationCtx.entity, associationCtx));
}
return values;
} else if (ctx.associations != null) {
for (Map.Entry<Association, MappingContext> e : ctx.associations.entrySet()) {
MappingContext associationCtx = e.getValue();
RuntimeAssociation runtimeAssociation = (RuntimeAssociation) e.getKey();
BeanProperty beanProperty = runtimeAssociation.getProperty();
if (runtimeAssociation.getKind().isSingleEnded() && (associationCtx.manyAssociations == null || associationCtx.manyAssociations.isEmpty())) {
Object value = beanProperty.get(instance);
Object newValue = setChildrenAndTriggerPostLoad(value, associationCtx);
if (newValue != value) {
instance = setProperty(beanProperty, instance, newValue);
}
} else {
Object newValue = setChildrenAndTriggerPostLoad(null, associationCtx);
newValue = resultReader.convertRequired(newValue == null ? new ArrayList<>() : newValue, beanProperty.getType());
instance = setProperty(beanProperty, instance, newValue);
}
}
}
if (instance != null && (ctx.association == null || ctx.jp != null)) {
triggerPostLoad(ctx.persistentEntity, instance);
}
return instance;
}
private <X, Y> X setProperty(BeanProperty<X, Y> beanProperty, X x, Y y) {
if (beanProperty.isReadOnly()) {
return beanProperty.withValue(x, y);
}
beanProperty.set(x, y);
return x;
}
@Nullable
private <K> K readEntity(RS rs, MappingContext<K> ctx, @Nullable Object parent, @Nullable Object resolveId) {
RuntimePersistentEntity<K> persistentEntity = ctx.persistentEntity;
BeanIntrospection<K> introspection = persistentEntity.getIntrospection();
RuntimePersistentProperty<K>[] constructorArguments = persistentEntity.getConstructorArguments();
try {
RuntimePersistentProperty<K> identity = persistentEntity.getIdentity();
final boolean isAssociation = ctx.association != null;
final boolean isEmbedded = ctx.association instanceof Embedded;
final boolean nullableEmbedded = isEmbedded && ctx.association.isOptional();
Object id = resolveId == null ? readEntityId(rs, ctx) : resolveId;
if (id == null && !isEmbedded && isAssociation) {
return null;
}
K entity;
if (ArrayUtils.isEmpty(constructorArguments)) {
entity = introspection.instantiate();
} else {
int len = constructorArguments.length;
Object[] args = new Object[len];
for (int i = 0; i < len; i++) {
RuntimePersistentProperty<K> prop = constructorArguments[i];
if (prop != null) {
if (prop instanceof Association) {
RuntimeAssociation entityAssociation = (RuntimeAssociation) prop;
if (prop instanceof Embedded) {
args[i] = readEntity(rs, ctx.embedded((Embedded) prop), null, null);
} else {
final Relation.Kind kind = entityAssociation.getKind();
final boolean isInverse = parent != null && isAssociation && ctx.association.getOwner() == entityAssociation.getAssociatedEntity();
if (isInverse && kind.isSingleEnded()) {
args[i] = parent;
} else {
MappingContext<K> joinCtx = ctx.join(joinPaths, entityAssociation);
Object resolvedId = null;
if (!entityAssociation.isForeignKey()) {
resolvedId = readEntityId(rs, ctx.path(entityAssociation));
}
if (kind.isSingleEnded()) {
if (joinCtx.jp == null || resolvedId == null && !entityAssociation.isForeignKey()) {
args[i] = buildIdOnlyEntity(rs, ctx.path(entityAssociation), resolvedId);
} else {
args[i] = readEntity(rs, joinCtx, null, resolvedId);
}
} else if (entityAssociation.getProperty().isReadOnly()) {
// For constructor-only properties (records) always set empty collection and replace later
args[i] = ConversionService.SHARED.convertRequired(new ArrayList<>(0), entityAssociation.getProperty().getType());
if (joinCtx.jp != null) {
MappingContext<K> associatedCtx = joinCtx.copy();
if (resolvedId == null) {
resolvedId = readEntityId(rs, associatedCtx);
}
Object associatedEntity = null;
if (resolvedId != null || entityAssociation.isForeignKey()) {
associatedEntity = readEntity(rs, associatedCtx, null, resolvedId);
}
if (associatedEntity != null) {
joinCtx.associate(associatedCtx, resolvedId, associatedEntity);
}
}
}
}
}
} else {
Object v;
if (resolveId != null && prop.equals(identity)) {
v = resolveId;
} else {
v = readProperty(rs, ctx, prop);
if (v == null) {
AnnotationMetadata entityAnnotationMetadata = ctx.persistentEntity.getAnnotationMetadata();
if (entityAnnotationMetadata.hasAnnotation(Embeddable.class) || entityAnnotationMetadata.hasAnnotation(EmbeddedId.class)) {
return null;
} else if (!prop.isOptional() && !nullableEmbedded) {
throw new DataAccessException("Null value read for non-null constructor argument [" + prop.getName() + "] of type: " + persistentEntity.getName());
} else {
args[i] = null;
continue;
}
}
}
if (prop.getType().isInstance(v)) {
args[i] = v;
} else if (prop.getDataType() == DataType.JSON && jsonCodec != null) {
try {
args[i] = jsonCodec.decode(prop.getArgument(), v.toString());
} catch (Exception e) {
// Fallback to reading and converting if decoding failed.
args[i] = resultReader.convertRequired(v, prop.getArgument());
}
} else {
args[i] = resultReader.convertRequired(v, prop.getArgument());
}
}
} else {
throw new DataAccessException("Constructor argument [" + constructorArguments[i].getName() + "] must have an associated getter.");
}
}
if (nullableEmbedded && args.length > 0 && Arrays.stream(args).allMatch(Objects::isNull)) {
return null;
} else {
entity = introspection.instantiate(args);
}
}
if (id != null && identity != null) {
@SuppressWarnings("unchecked")
BeanProperty<K, Object> idProperty = (BeanProperty<K, Object>) identity.getProperty();
entity = (K) convertAndSetWithValue(entity, identity, idProperty, id, identity.getDataType());
}
RuntimePersistentProperty<K> version = persistentEntity.getVersion();
if (version != null) {
Object v = readProperty(rs, ctx, version);
if (v != null) {
entity = (K) convertAndSetWithValue(entity, version, version.getProperty(), v, version.getDataType());
}
}
for (RuntimePersistentProperty<K> rpp : persistentEntity.getPersistentProperties()) {
if (rpp.isReadOnly()) {
continue;
} else if (rpp.isConstructorArgument()) {
if (rpp instanceof Association) {
Association a = (Association) rpp;
final Relation.Kind kind = a.getKind();
if (kind.isSingleEnded()) {
continue;
}
} else {
continue;
}
}
@SuppressWarnings("unchecked")
BeanProperty<K, Object> property = (BeanProperty<K, Object>) rpp.getProperty();
if (rpp instanceof Association) {
Association entityAssociation = (Association) rpp;
if (rpp instanceof Embedded) {
Object value = readEntity(rs, ctx.embedded((Embedded) rpp), parent == null ? entity : parent, null);
entity = setProperty(property, entity, value);
} else {
final boolean isInverse = parent != null && entityAssociation.getKind().isSingleEnded() && isAssociation && ctx.association.getOwner() == entityAssociation.getAssociatedEntity();
if (isInverse) {
entity = setProperty(property, entity, parent);
} else {
MappingContext<K> joinCtx = ctx.join(joinPaths, entityAssociation);
Object associatedId = null;
if (!entityAssociation.isForeignKey()) {
associatedId = readEntityId(rs, ctx.path(entityAssociation));
if (associatedId == null) {
continue;
}
}
if (joinCtx.jp != null) {
if (entityAssociation.getKind().isSingleEnded()) {
Object associatedEntity = readEntity(rs, joinCtx, entity, associatedId);
entity = setProperty(property, entity, associatedEntity);
} else {
MappingContext<K> associatedCtx = joinCtx.copy();
if (associatedId == null) {
associatedId = readEntityId(rs, associatedCtx);
}
Object associatedEntity = readEntity(rs, associatedCtx, entity, associatedId);
if (associatedEntity != null) {
joinCtx.associate(associatedCtx, associatedId, associatedEntity);
}
}
} else if (entityAssociation.getKind().isSingleEnded() && !entityAssociation.isForeignKey()) {
Object value = buildIdOnlyEntity(rs, ctx.path(entityAssociation), associatedId);
entity = setProperty(property, entity, value);
}
}
}
} else {
Object v = readProperty(rs, ctx, rpp);
if (v != null) {
entity = (K) convertAndSetWithValue(entity, rpp, property, v, rpp.getDataType());
}
}
}
return entity;
} catch (InstantiationException e) {
throw new DataAccessException("Error instantiating entity [" + persistentEntity.getName() + "]: " + e.getMessage(), e);
}
}
private <K> Object readProperty(RS rs, MappingContext<K> ctx, RuntimePersistentProperty<K> prop) {
String columnName = ctx.namingStrategy.mappedName(ctx.embeddedPath, prop);
if (ctx.prefix != null && ctx.prefix.length() != 0) {
columnName = ctx.prefix + columnName;
}
return resultReader.readDynamic(rs, columnName, prop.getDataType());
}
private <K> K triggerPostLoad(RuntimePersistentEntity<?> persistentEntity, K entity) {
K finalEntity;
if (eventListener != null && persistentEntity.hasPostLoadEventListeners()) {
finalEntity = (K) eventListener.apply((RuntimePersistentEntity<Object>) persistentEntity, entity);
} else {
finalEntity = entity;
}
return finalEntity;
}
private @Nullable <K> Object readEntityId(RS rs, MappingContext<K> ctx) {
RuntimePersistentProperty<K> identity = ctx.persistentEntity.getIdentity();
if (identity == null) {
return null;
}
if (identity instanceof Embedded) {
return readEntity(rs, ctx.embedded((Embedded) identity), null, null);
}
return readProperty(rs, ctx, identity);
}
private Object convertAndSetWithValue(Object entity, RuntimePersistentProperty rpp, BeanProperty property, Object v, DataType dataType) {
Class<?> propertyType = rpp.getType();
final Object r;
if (v instanceof Array) {
try {
v = ((Array) v).getArray();
} catch (SQLException e) {
throw new DataAccessException("Error getting an array value: " + e.getMessage(), e);
}
}
if (propertyType.isInstance(v)) {
r = v;
} else {
if (dataType == DataType.JSON && jsonCodec != null) {
r = jsonCodec.decode(rpp.getArgument(), v.toString());
} else {
r = resultReader.convertRequired(v, rpp.getArgument());
}
}
return setProperty(property, entity, r);
}
private <K> K buildIdOnlyEntity(RS rs, MappingContext<K> ctx, Object resolvedId) {
RuntimePersistentProperty<K> identity = ctx.persistentEntity.getIdentity();
if (identity != null) {
BeanIntrospection<K> associatedIntrospection = ctx.persistentEntity.getIntrospection();
Argument<?>[] constructorArgs = associatedIntrospection.getConstructorArguments();
if (constructorArgs.length == 0) {
Object associated = associatedIntrospection.instantiate();
if (resolvedId == null) {
resolvedId = readEntityId(rs, ctx);
}
BeanWrapper.getWrapper(associated).setProperty(identity.getName(), resolvedId);
return (K) associated;
} else {
if (constructorArgs.length == 1) {
Argument<?> arg = constructorArgs[0];
if (arg.getName().equals(identity.getName()) && arg.getType() == identity.getType()) {
if (resolvedId == null) {
resolvedId = readEntityId(rs, ctx);
}
return associatedIntrospection.instantiate(resultReader.convertRequired(resolvedId, identity.getType()));
}
}
}
}
return null;
}
public RuntimePersistentEntity<R> getPersistentEntity() {
return entity;
}
private static final class MappingContext<E> {
private final RuntimePersistentEntity<E> rootPersistentEntity;
private final RuntimePersistentEntity<E> persistentEntity;
private final NamingStrategy namingStrategy;
private final String prefix;
private final JoinPath jp;
private final List<Association> joinPath;
private final List<Association> embeddedPath;
private final Association association;
private Map<Object, MappingContext> manyAssociations;
private Map<Association, MappingContext> associations;
private E entity;
private MappingContext(RuntimePersistentEntity rootPersistentEntity,
RuntimePersistentEntity persistentEntity,
NamingStrategy namingStrategy,
String prefix,
JoinPath jp,
List<Association> joinPath,
List<Association> embeddedPath,
Association association) {
this.rootPersistentEntity = rootPersistentEntity;
this.persistentEntity = persistentEntity;
this.namingStrategy = namingStrategy;
this.prefix = prefix;
this.jp = jp;
this.joinPath = joinPath;
this.embeddedPath = embeddedPath;
this.association = association;
}
public static <K> MappingContext<K> of(RuntimePersistentEntity<K> persistentEntity, String prefix) {
return new MappingContext<>(
persistentEntity,
persistentEntity,
persistentEntity.getNamingStrategy(),
prefix,
null,
Collections.emptyList(),
Collections.emptyList(),
null);
}
public <K> MappingContext<K> embedded(Embedded embedded) {
if (associations == null) {
associations = new LinkedHashMap<>();
}
return associations.computeIfAbsent(embedded, e -> embeddedAssociation(embedded));
}
public <K> MappingContext<K> path(Association association) {
RuntimePersistentEntity<K> associatedEntity = (RuntimePersistentEntity) association.getAssociatedEntity();
return new MappingContext<>(
rootPersistentEntity,
associatedEntity,
namingStrategy,
prefix,
jp,
joinPath,
associated(embeddedPath, association),
association
);
}
public <K> MappingContext<K> join(Map<String, JoinPath> joinPaths, Association association) {
if (associations == null) {
associations = new LinkedHashMap<>();
}
return associations.computeIfAbsent(association, a -> joinAssociation(joinPaths, association));
}
public <K> MappingContext<K> associate(MappingContext<K> ctx, @NotNull Object associationId, @NotNull Object entity) {
ctx.entity = (K) entity;
if (manyAssociations == null) {
manyAssociations = new LinkedHashMap<>();
}
manyAssociations.put(associationId, ctx);
return ctx;
}
private <K> MappingContext<K> copy() {
MappingContext ctx = new MappingContext<>(
rootPersistentEntity,
persistentEntity,
namingStrategy,
prefix,
jp,
joinPath,
embeddedPath,
association
);
return ctx;
}
private <K> MappingContext<K> joinAssociation(Map<String, JoinPath> joinPaths, Association association) {
JoinPath jp = findJoinPath(joinPaths, association);
RuntimePersistentEntity<K> associatedEntity = (RuntimePersistentEntity<K>) association.getAssociatedEntity();
return new MappingContext<>(
rootPersistentEntity,
associatedEntity,
associatedEntity.getNamingStrategy(),
jp == null ? prefix : jp.getAlias().orElse(prefix),
jp,
associated(this.joinPath, association),
Collections.emptyList(), // Reset path,
association
);
}
private <K> MappingContext<K> embeddedAssociation(Embedded embedded) {
RuntimePersistentEntity<K> associatedEntity = (RuntimePersistentEntity) embedded.getAssociatedEntity();
return new MappingContext<>(
rootPersistentEntity,
associatedEntity,
associatedEntity.findNamingStrategy().orElse(namingStrategy),
prefix,
jp,
joinPath,
associated(embeddedPath, embedded),
embedded
);
}
private JoinPath findJoinPath(Map<String, JoinPath> joinPaths, Association association) {
JoinPath jp = null;
if (!joinPaths.isEmpty()) {
String path = asPath(joinPath, embeddedPath, association);
jp = joinPaths.get(path);
if (jp == null) {
path = asPath(joinPath, association);
jp = joinPaths.get(path);
if (jp == null) {
RuntimePersistentProperty<E> identity = rootPersistentEntity.getIdentity();
if (identity instanceof Embedded) {
path = identity.getName() + "." + path;
}
jp = joinPaths.get(path);
}
}
}
if (jp == null) {
return null;
}
String alias = jp.getAlias().orElse(null);
if (alias == null) {
alias = association.getAliasName();
if (!embeddedPath.isEmpty()) {
StringBuilder sb = prefix == null ? new StringBuilder() : new StringBuilder(prefix);
for (Association embedded : embeddedPath) {
sb.append(embedded.getName());
sb.append('_');
}
sb.append(alias);
alias = sb.toString();
} else {
alias = prefix == null ? alias : prefix + alias;
}
}
return new JoinPath(jp.getPath(), jp.getAssociationPath(), jp.getJoinType(), alias);
}
private String asPath(List<Association> joinPath, List<Association> embeddedPath, PersistentProperty property) {
if (joinPath.isEmpty() && embeddedPath.isEmpty()) {
return property.getName();
}
StringJoiner joiner = new StringJoiner(".");
for (Association association : joinPath) {
joiner.add(association.getName());
}
for (Association association : embeddedPath) {
joiner.add(association.getName());
}
joiner.add(property.getName());
return joiner.toString();
}
private String asPath(List<Association> associations, PersistentProperty property) {
if (associations.isEmpty()) {
return property.getName();
}
StringJoiner joiner = new StringJoiner(".");
for (Association association : associations) {
joiner.add(association.getName());
}
joiner.add(property.getName());
return joiner.toString();
}
private static List<Association> associated(List<Association> associations, Association association) {
List<Association> newAssociations = new ArrayList<>(associations.size() + 1);
newAssociations.addAll(associations);
newAssociations.add(association);
return newAssociations;
}
}
/**
* The pushing mapper helper interface.
*
* @param <RS> The row type
* @param <R> The result type
*/
public interface PushingMapper<RS, R> {
/**
* Process row.
*
* @param row The row
*/
void processRow(RS row);
/**
* The result created by pushed rows.
*
* @return the result
*/
R getResult();
}
}
| 44.754959 | 202 | 0.543084 |
760c512c19bc7e26ad6baf2f6653681fbbbaf6a3 | 4,233 | /**
* 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.apex.malhar.contrib.memcache;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.apex.malhar.lib.db.KeyValueStore;
import net.spy.memcached.MemcachedClient;
/**
* Provides the implementation of a Memcache store.
*
* @since 0.9.3
*/
public class MemcacheStore implements KeyValueStore
{
private static final Logger LOG = LoggerFactory.getLogger(MemcacheStore.class);
protected transient MemcachedClient memcacheClient;
private List<InetSocketAddress> serverAddresses = new ArrayList<InetSocketAddress>();
protected int keyExpiryTime = 0;
/**
* Adds a server address
*
* @param addr the address
*/
public void addServer(InetSocketAddress addr)
{
serverAddresses.add(addr);
}
public List<InetSocketAddress> getServerAddresses()
{
return serverAddresses;
}
public void setServerAddresses(List<InetSocketAddress> serverAddresses)
{
this.serverAddresses = serverAddresses;
}
/**
* Gets the key expiry time.
*
* @return The key expiry time.
*/
public int getKeyExpiryTime()
{
return keyExpiryTime;
}
/**
* Sets the key expiry time.
*
* @param keyExpiryTime
*/
public void setKeyExpiryTime(int keyExpiryTime)
{
this.keyExpiryTime = keyExpiryTime;
}
@Override
public void connect() throws IOException
{
if (serverAddresses.isEmpty()) {
memcacheClient = new MemcachedClient(new InetSocketAddress("localhost", 11211));
} else {
memcacheClient = new MemcachedClient(serverAddresses);
}
}
@Override
public void disconnect() throws IOException
{
memcacheClient.shutdown();
}
@Override
public boolean isConnected()
{
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* Gets the value given the key.
* Note that it does NOT work with hash values or list values
*
* @param key
* @return The value.
*/
@Override
public Object get(Object key)
{
return memcacheClient.get(key.toString());
}
/**
* Gets all the values given the keys.
* Note that it does NOT work with hash values or list values
*
* @param keys
* @return All values for the given keys.
*/
@SuppressWarnings("unchecked")
@Override
public List<Object> getAll(List<Object> keys)
{
List<Object> results = new ArrayList<Object>();
for (Object key : keys) {
results.add(memcacheClient.get(key.toString()));
}
return results;
}
@Override
public void put(Object key, Object value)
{
try {
memcacheClient.set(key.toString(), keyExpiryTime, value).get();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
@Override
public void putAll(Map<Object, Object> m)
{
List<Future<?>> futures = new ArrayList<Future<?>>();
for (Map.Entry<Object, Object> entry : m.entrySet()) {
futures.add(memcacheClient.set(entry.getKey().toString(), keyExpiryTime, entry.getValue()));
}
for (Future<?> future : futures) {
try {
future.get();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
@Override
public void remove(Object key)
{
memcacheClient.delete(key.toString());
}
}
| 24.188571 | 98 | 0.689346 |
6e4057cff287eed2b8c3959f8e4a8b8d043b65c2 | 2,699 | package spring.model;
import model.account.Action;
import model.account.Permission;
import model.account.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Billie Devolder on 6/04/2017.
*/
public class RESTPermission {
private long id;
private String resource;
private String action;
public RESTPermission(Resource resource, Action action) {
this.id = (resource.ordinal()) * 987152 + action.ordinal();
this.resource = resource.name();
this.action = action.name();
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
/**
* Translate a list of Permissions into a list of RESTPermissions.
* A Permission can have multiple actions but a RESTPermission can have only 1,
* so we have to create multiple RESTPermissions of 1 Permission.
* These RESTPermissions have the same resource field, but a different action field.
* @param permissions a collection of Permissions.
* @return a collection of RESTPermissions
*/
public static Collection<RESTPermission> translate(Collection<Permission> permissions) {
Collection<RESTPermission> restPermissions = new ArrayList<>();
for (Permission permission: permissions) {
Resource resource = permission.getResource();
for (Action action: permission.getActions()) {
RESTPermission restPermission = new RESTPermission(resource, action);
restPermissions.add(restPermission);
}
}
return restPermissions;
}
/**
* @return a Map that contains all possible combinations of RESTPermissions.
* The map projects an id of a RESTPermission to the object itself.
*/
public static Map<Long, RESTPermission> getAllRESTPermissions() {
Map<Long, RESTPermission> allPermissions = new HashMap<>();
for (Resource resource : Resource.values()) {
for (Action action : Action.values()) {
RESTPermission permission = new RESTPermission(resource, action);
allPermissions.put(permission.getId(), permission);
}
}
return allPermissions;
}
}
| 31.022989 | 93 | 0.626899 |
ff5305ca8612dd1594d4f066dde7e12a474a6a44 | 839 | package dev.yavuztas.samples;
import java.util.LinkedList;
import java.util.List;
/**
* Solution for Train Composition implementation
*
* @author Yavuz Tas
*
*/
public class TrainComposition {
private List<Integer> chain = new LinkedList<>();
public void attachWagonFromLeft(int wagonId) {
chain.add(0, wagonId);
}
public void attachWagonFromRight(int wagonId) {
chain.add(chain.size(), wagonId);
}
public int detachWagonFromLeft() {
return chain.remove(0);
}
public int detachWagonFromRight() {
return chain.remove(chain.size() - 1);
}
public static void main(String[] args) {
TrainComposition tree = new TrainComposition();
tree.attachWagonFromLeft(7);
tree.attachWagonFromLeft(13);
System.out.println(tree.detachWagonFromRight()); // 7
System.out.println(tree.detachWagonFromLeft()); // 13
}
} | 21.512821 | 55 | 0.722288 |
60cd739e246dc6a1fb99b01e1aeac9d0a7fb6eaa | 583 | package org.swtk.eng.stanford.dto.adapter;
import org.swtk.eng.stanford.dto.EngGrammarSer;
import com.trimc.blogger.commons.exception.AdapterValidationException;
import com.trimc.blogger.commons.type.EngGrammar;
public final class EngGrammarSerAdapter {
public static EngGrammarSer transform(EngGrammar type) throws AdapterValidationException {
EngGrammarSer ser = new EngGrammarSer();
ser.setLongName(type.getLabel());
ser.setMetaType(type.getMetaType().toString());
ser.setUpperType(type.getUpperType().toString());
ser.setTags(type.getTags());
return ser;
}
}
| 27.761905 | 91 | 0.789022 |
915d7382cee90cb1a3570f1b6cf5d947dae3a1b7 | 6,652 | package ch.so.agi.gretl.steps;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TemporaryFolder;
import ch.so.agi.gretl.logging.GretlLogger;
import ch.so.agi.gretl.logging.LogEnvironment;
import ch.so.agi.gretl.testutil.S3Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.ListObjectsRequest;
import software.amazon.awssdk.services.s3.model.ListObjectsResponse;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.model.S3Object;
public class S3UploadStepTest {
private String s3AccessKey = System.getProperty("s3AccessKey");
private String s3SecretKey = System.getProperty("s3SecretKey");
private String s3BucketName = System.getProperty("s3BucketName");
public S3UploadStepTest() {
this.log = LogEnvironment.getLogger(this.getClass());
}
@Rule
public TemporaryFolder folder = new TemporaryFolder();
private GretlLogger log;
@Test
@Category(S3Test.class)
public void uploadDirectory_Ok() throws Exception {
File sourceObject = new File("src/test/resources/data/s3upload/");
String s3EndPoint = "https://s3.eu-central-1.amazonaws.com";
String s3Region = "eu-central-1";
String acl = "public-read";
Map<String,String> metaData = new HashMap<String,String>();
metaData.put("lastModified", "2020-08-28");
AwsCredentialsProvider creds = StaticCredentialsProvider.create(AwsBasicCredentials.create(s3AccessKey, s3SecretKey));
Region region = Region.of(s3Region);
S3Client s3client = S3Client.builder()
.credentialsProvider(creds)
.region(region)
.endpointOverride(URI.create(s3EndPoint))
.build();
s3client.deleteObject(DeleteObjectRequest.builder().bucket(s3BucketName).key("foo.txt").build());
s3client.deleteObject(DeleteObjectRequest.builder().bucket(s3BucketName).key("bar.txt").build());
// Upload files from a directory.
S3UploadStep s3UploadStep = new S3UploadStep();
s3UploadStep.execute(s3AccessKey, s3SecretKey, sourceObject, s3BucketName, s3EndPoint, s3Region, acl, null, metaData);
// Check result.
ListObjectsRequest listObjects = ListObjectsRequest
.builder()
.bucket(s3BucketName)
.build();
ListObjectsResponse res = s3client.listObjects(listObjects);
List<S3Object> objects = res.contents();
List<String> keyList = new ArrayList<String>();
for (ListIterator<S3Object> iterVals = objects.listIterator(); iterVals.hasNext(); ) {
S3Object myValue = iterVals.next();
keyList.add(myValue.key());
}
assertTrue(keyList.contains("foo.txt"));
assertTrue(keyList.contains("bar.txt"));
// Remove uploaded files from bucket.
s3client.deleteObject(DeleteObjectRequest.builder().bucket(s3BucketName).key("foo.txt").build());
s3client.deleteObject(DeleteObjectRequest.builder().bucket(s3BucketName).key("bar.txt").build());
}
@Test
@Category(S3Test.class)
public void uploadFile_Ok() throws Exception {
File sourceObject = new File("src/test/resources/data/s3upload/foo.txt");
String s3EndPoint = "https://s3.eu-central-1.amazonaws.com";
String s3Region = "eu-central-1";
String acl = "public-read";
Map<String,String> metaData = new HashMap<String,String>();
AwsCredentialsProvider creds = StaticCredentialsProvider.create(AwsBasicCredentials.create(s3AccessKey, s3SecretKey));
Region region = Region.of(s3Region);
S3Client s3client = S3Client.builder()
.credentialsProvider(creds)
.region(region)
.endpointOverride(URI.create(s3EndPoint))
.build();
s3client.deleteObject(DeleteObjectRequest.builder().bucket(s3BucketName).key("foo.txt").build());
// Upload a single file.
S3UploadStep s3UploadStep = new S3UploadStep();
s3UploadStep.execute(s3AccessKey, s3SecretKey, sourceObject, s3BucketName, s3EndPoint, s3Region, acl, null, metaData);
// Check result.
GetObjectRequest getObjectRequest = GetObjectRequest.builder()
.bucket(s3BucketName)
.key("foo.txt")
.build();
ResponseInputStream<GetObjectResponse> is = s3client.getObject(getObjectRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
assertTrue(reader.readLine().equalsIgnoreCase("foo"));
// Remove uploaded files from bucket.
s3client.deleteObject(DeleteObjectRequest.builder().bucket(s3BucketName).key("foo.txt").build());
}
@Test
@Category(S3Test.class)
public void uploadFile_Fail() throws Exception {
File sourceObject = new File("src/test/resources/data/s3upload/foo.txt");
String s3EndPoint = "https://s3.eu-central-1.amazonaws.com";
String s3Region = "eu-central-1";
String acl = "public-read";
Map<String,String> metaData = new HashMap<String,String>();
// Upload a single file.
try {
S3UploadStep s3UploadStep = new S3UploadStep();
s3UploadStep.execute("login", "secret", sourceObject, s3BucketName, s3EndPoint, s3Region, acl, null, metaData);
} catch (S3Exception e) {
assertTrue(e.getMessage().contains("The AWS Access Key Id you provided does not exist in our records"));
}
}
}
| 42.369427 | 126 | 0.681299 |
64fb4dc058dd35f51be6bf3e38b8408a964b9b14 | 715 | package io.smallrye.reactive.messaging.kafka.commit;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import io.smallrye.reactive.messaging.kafka.IncomingKafkaRecord;
/**
* Ignores an ACK and does not commit any offsets.
*
* This handler is the default when `enable.auto.commit` is `true`.
*
* When `enable.auto.commit` is `true` this strategy DOES NOT guarantee at-least-once delivery.
*
* To use set `commit-strategy` to `ignore`.
*/
public class KafkaIgnoreCommit implements KafkaCommitHandler {
@Override
public <K, V> CompletionStage<Void> handle(IncomingKafkaRecord<K, V> record) {
return CompletableFuture.completedFuture(null);
}
}
| 29.791667 | 95 | 0.752448 |
9d292e7199467c4e353cdda930699e91f9080f84 | 2,474 | /*
* Copyright (C) 2017 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.layoutlib.bridge.remote.server.adapters;
import com.android.ide.common.rendering.api.RenderSession;
import com.android.ide.common.rendering.api.Result;
import com.android.layout.remote.api.RemoteRenderSession;
import com.android.layout.remote.util.SerializableImage;
import com.android.layout.remote.util.SerializableImageImpl;
import com.android.tools.layoutlib.annotations.NotNull;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class RemoteRenderSessionAdapter implements RemoteRenderSession {
private final RenderSession mDelegate;
private RemoteRenderSessionAdapter(@NotNull RenderSession delegate) {
mDelegate = delegate;
}
public static RemoteRenderSession create(@NotNull RenderSession delegate)
throws RemoteException {
return (RemoteRenderSession) UnicastRemoteObject.exportObject(
new RemoteRenderSessionAdapter(delegate), 0);
}
@NotNull
@Override
public Result getResult() throws RemoteException {
return mDelegate.getResult();
}
@Override
public Result render(long timeout, boolean forceMeasure) {
return mDelegate.render(timeout, forceMeasure);
}
@NotNull
@Override
public SerializableImage getSerializableImage() throws RemoteException {
return new SerializableImageImpl(mDelegate.getImage());
}
@Override
public void setSystemTimeNanos(long nanos) {
mDelegate.setSystemTimeNanos(nanos);
}
@Override
public void setSystemBootTimeNanos(long nanos) {
mDelegate.setSystemBootTimeNanos(nanos);
}
@Override
public void setElapsedFrameTimeNanos(long nanos) {
mDelegate.setElapsedFrameTimeNanos(nanos);
}
@Override
public void dispose() {
mDelegate.dispose();
}
}
| 31.316456 | 77 | 0.736055 |
da9479c183a2128c2904b89af3d0dc6000330d3d | 12,022 | /*
Copyright (c) 2003, Dennis M. Sosnoski
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 JargP 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.
*/
package org.jargp;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.util.List;
/**
* Command line parameter processing handler. Organizes all the parameter
* information, including the data object to which parameter values defined
* by the command line are stored. Provides specialized processing for the
* argument strings, including recognizing the '-' character at the start of
* an argument as indicating that the argument provides control information
* (flags and possibly embedded values) as opposed to data.
*
* @author Dennis M. Sosnoski
* @version 1.0
*/
public class ArgumentProcessor
{
/** Head of parameter set chain. */
private final ParameterSet m_parameterSet;
/** Character tracker for current argument. */
private CharTracker m_currentArg;
/** Current argument position in list. */
private int m_currentIndex;
/** String tracker for full set of arguments. */
private StringTracker m_remainingArgs;
/** Argument data object. */
private Object m_targetObject;
/**
* Constructor from parameter set definition.
*
* @param set head parameter set in possible chain of sets defined
*/
public ArgumentProcessor(ParameterSet set) {
m_parameterSet = set;
}
/**
* Constructor from array of parameter definitions.
*
* @param defs head parameter set in possible chain of sets defined
*/
public ArgumentProcessor(ParameterDef[] defs) {
this(new ParameterSet(defs, null));
}
/**
* Bind parameter definitions to target object class. This goes through the
* set of defined parameters, binding each to the class of the supplied
* target object and finding the associated field information. Rather than
* doing this binding of all parameter definitions prior to processing the
* command line information, it'd also be possible (and even more efficient)
* to just lookup the field information for each parameter actually present
* in the list. The only advantage of doing this lookup in advance is that
* it insures that configuration errors are reported whether the parameter
* in error is used or not.
*
* @param parm data object for parameter values
* @throws ArgumentErrorException on error in data
* @throws IllegalArgumentException on error in processing
*/
private void bindDefinitions(Object parm) {
int index = 0;
Class clas = parm.getClass();
ParameterDef def;
while ((def = m_parameterSet.indexDef(index++)) != null) {
def.bindToClass(clas);
}
}
/**
* Process argument list control information. Processes control flags
* present in the supplied argument list, setting the associated parameter
* values. Arguments not consumed in the control flag processing are
* available for access using other methods after the return from this
* call.
*
* @param args command line argument string array
* @param target application object defining parameter fields
* @throws ArgumentErrorException on error in data
* @throws IllegalArgumentException on error in processing
*/
public Object processArgs(String[] args, Object target) {
// verify field definitions for all parameters
bindDefinitions(target);
// clean up argument text (may have CR-LF line ends, confusing Linux)
String[] trims = new String[args.length];
for (int i = 0; i < args.length; i++) {
trims[i] = args[i].trim();
}
// initialize argument list information
m_currentArg = new CharTracker("", 0);
m_remainingArgs = new StringTracker(trims, 0);
m_targetObject = target;
// loop for processing all argument values present
while (true) {
if (m_currentArg.hasNext()) {
// find the parameter definition for current flag character
char flag = m_currentArg.next();
ParameterDef def = m_parameterSet.findDef(flag);
if (def != null) {
// process the argument
def.handle(this);
} else if (flag == ' ') {
break; // preserve old functionality
} else {
throw new IllegalArgumentException("Control flag '" +
flag + "' in argument " + m_currentIndex +
" is not defined");
}
} else if (m_remainingArgs.hasNext()) {
// check if more control flags in next argument
String next = m_remainingArgs.peek();
if (next.length() > 0 && next.charAt(0) == '-') {
m_remainingArgs.next();
m_currentIndex = m_remainingArgs.nextOffset();
m_currentArg = new CharTracker(next, 1);
} else if (next.length() > 0) {
m_currentArg = new CharTracker("- ", 1);
} else {
break;
}
} else {
break;
}
}
return m_targetObject;
}
/**
* Get current control argument character information. The caller can
* consume characters from the current argument as needed.
*
* @return argument string tracking information
*/
/*package*/ CharTracker getChars() {
return m_currentArg;
}
/**
* Get current argument position in list.
*
* @return offset in argument list of current flag argument
*/
/*package*/ int getIndex() {
return m_currentIndex;
}
/**
* Get argument list information. The caller can comsume arguments
* from the list as needed.
*
* @return argument list information
*/
public StringTracker getArgs() {
return m_remainingArgs;
}
/**
* Set parameter value. Uses reflection to set a value within the
* target data object.
*
* @param value value to be set for parameter
* @param field target field for parameter value
* @throws IllegalArgumentException on error in setting parameter value
*/
/*package*/ void setValue(Object value, Field field) {
try {
field.setAccessible(true);
field.set(m_targetObject, value);
} catch (IllegalAccessException ex) {
throw new IllegalArgumentException("Field " + field.getName() +
" is not accessible in object of class " +
m_targetObject.getClass().getName());
}
}
/**
* Add parameter value to list. Uses reflection to retrieve the list object
* and add a value to those present in the list.
*
* @param value value to be added to list
* @param field target list field
* @throws IllegalArgumentException on error in adding parameter value
*/
/*package*/ void addValue(Object value, Field field) {
try {
field.setAccessible(true);
List list = (List)field.get(m_targetObject);
if (list == null) {
list = (List)field.getType().newInstance();
field.set(m_targetObject, list);
}
list.add(value);
} catch (IllegalAccessException ex) {
throw new IllegalArgumentException("Field " + field.getName() +
" is not accessible in object of class " +
m_targetObject.getClass().getName());
} catch (InstantiationException ex) {
throw new IllegalArgumentException("Unable to create instance of " +
field.getType().getName() + " for storing to list field " +
field.getName() + " in object of class " +
m_targetObject.getClass().getName());
}
}
/**
* Report argument error. Generates an exception with information about
* the argument causing the problem.
*
* @param flag argument flag character
* @param text error message text
* @throws ArgumentErrorException reporting the error
*/
public void reportArgumentError(char flag, String text) {
throw new ArgumentErrorException(text + " for parameter '" +
flag + "' in argument " + m_currentIndex);
}
/**
* List known parameter definitions. This lists all known parameter
* definitions in fixed maximum width format.
*
* @param width maximum number of columns in listing
* @param print print stream destination for listing definitions
*/
public void listParameters(int width, PrintStream print) {
// scan once to find maximum parameter abbreviation length
int count = 0;
int maxlen = 0;
ParameterDef def = null;
while ((def = m_parameterSet.indexDef(count)) != null) {
int length = def.getAbbreviation().length();
if (maxlen < length) {
maxlen = length;
}
count++;
}
// initialize for handling text generation
StringBuffer line = new StringBuffer(width);
int lead = maxlen + 2;
char[] blanks = new char[lead];
for (int i = 0; i < lead; i++) {
blanks[i] = ' ';
}
// scan again to print text of definitions
for (int i = 0; i < count; i++) {
// set up lead parameter abbreviation for first line
line.setLength(0);
def = m_parameterSet.indexDef(i);
line.append(' ');
line.append(def.getAbbreviation());
line.append(blanks, 0, lead-line.length());
// format description text in as many lines as needed
String text = def.getDescription();
while (line.length()+text.length() > width) {
// scan for first line break position (even if beyond limit)
int limit = width - line.length();
int mark = text.indexOf(' ');
if (mark >= 0) {
// find break position closest to limit
int split = mark;
while (mark >= 0 && mark <= limit) {
split = mark;
mark = text.indexOf(' ', mark+1);
}
// split the description for printing line
line.append(text.substring(0, split));
print.println(line.toString());
line.setLength(0);
line.append(blanks);
text = text.substring(split+1);
} else {
break;
}
}
// print remainder of description in single line
line.append(text);
print.println(line.toString());
}
}
/**
* Process argument list directly. Creates and initializes an instance of
* this class, then processes control flags present in the supplied argument
* list, setting the associated parameter values in the target object.
* Arguments not consumed in the control flag processing are available for
* access using other methods after the return from this call.
*
* @param args command line argument string array
* @param parms data object for parameter values
* @param target application object defining parameter fields
* @return index of first command line argument not consumed by processing
* @throws ArgumentErrorException on error in data
* @throws IllegalArgumentException on error in processing
*/
public static int processArgs(String[] args, ParameterDef[] parms,
Object target) {
ArgumentProcessor inst = new ArgumentProcessor(parms);
inst.processArgs(args, target);
return inst.m_remainingArgs.nextOffset();
}
} | 32.491892 | 80 | 0.692813 |
d59a8581f364cd01946e638d6e285564301c502d | 203 | package dev.gustavoteixeira.votingsession.exception;
public class CreatingAgendaException extends RuntimeException {
public CreatingAgendaException(String message) {
super(message);
}
}
| 25.375 | 63 | 0.778325 |
3c4e1a9c4b5bb1653e8d34de3850e478216ac925 | 11,852 | package org.jboss.da.common.version;
import org.jboss.da.common.CommunicationException;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
*
* @author Jakub Bartecek <jbartece@redhat.com>
*
*/
public class VersionAnalyzerTest {
private VersionAnalyzer versionFinder = new VersionAnalyzer(new VersionParser("redhat"));
private static final String NO_BUILT_VERSION = "1.1.3";
private static final String NO_BUILT_VERSION_2 = "1.0.20";
private static final String BUILT_VERSION = "1.1.4";
private static final String BUILT_VERSION_RH = BUILT_VERSION + "-redhat-20";
private static final String BUILT_VERSION_2 = "1.1.4.Final";
private static final String BUILT_VERSION_2_RH = BUILT_VERSION_2 + "-redhat-10";
private static final String MULTI_BUILT_VERSION = "1.1.5";
private static final String MULTI_BUILT_VERSION_RH1 = MULTI_BUILT_VERSION + ".redhat-5";
private static final String MULTI_BUILT_VERSION_RH2 = MULTI_BUILT_VERSION + ".redhat-3";
private static final String MULTI_BUILT_VERSION_RH_BEST = MULTI_BUILT_VERSION + ".redhat-18";
private static final String MULTI_BUILT_VERSION_RH4 = MULTI_BUILT_VERSION + ".redhat-16";
private static final String OTHER_RH_VERSION_1 = "1.0.0.redhat-1";
private static final String OTHER_RH_VERSION_2 = "1.0.0.redhat-18";
private static final String OTHER_RH_VERSION_3 = "1.1.1.redhat-15";
private static final String NON_OSGI_VERSION = "1.3";
private static final String NON_OSGI_VERSION_RHT = "1.3.redhat-4";
private static final String NON_OSGI_VERSION_2 = "1.3-Final";
private static final String NON_OSGI_VERSION_2_RHT = "1.3.0.Final-redhat-7";
private static final String NON_OSGI_VERSION_3 = "1.2.3.foo.bar.baz";
private static final String NON_OSGI_VERSION_3_RHT = "1.2.3.foo-bar-baz-redhat-5";
private static final String NON_OSGI_VERSION_4 = "1.5.9.foo,bar,baz";
private static final String NON_OSGI_VERSION_4_RHT = "1.5.9.foo-bar-baz-redhat-8";
private static final List<String> All_VERSIONS = Arrays.asList(
OTHER_RH_VERSION_1,
OTHER_RH_VERSION_2,
NO_BUILT_VERSION_2,
NO_BUILT_VERSION,
OTHER_RH_VERSION_3,
MULTI_BUILT_VERSION_RH2,
BUILT_VERSION_RH,
MULTI_BUILT_VERSION_RH1,
BUILT_VERSION_2_RH,
MULTI_BUILT_VERSION_RH_BEST,
MULTI_BUILT_VERSION_RH4,
NON_OSGI_VERSION,
NON_OSGI_VERSION_RHT,
BUILT_VERSION_2,
NON_OSGI_VERSION_2,
NON_OSGI_VERSION_2_RHT,
NON_OSGI_VERSION_3,
NON_OSGI_VERSION_3_RHT,
NON_OSGI_VERSION_4,
NON_OSGI_VERSION_4_RHT);
private static final List<String> BUILT_VERSIONS = Arrays.asList(
OTHER_RH_VERSION_1,
OTHER_RH_VERSION_2,
OTHER_RH_VERSION_3,
MULTI_BUILT_VERSION_RH2,
BUILT_VERSION_RH,
MULTI_BUILT_VERSION_RH1,
BUILT_VERSION_2_RH,
MULTI_BUILT_VERSION_RH_BEST,
MULTI_BUILT_VERSION_RH4,
NON_OSGI_VERSION_RHT,
NON_OSGI_VERSION_2_RHT,
NON_OSGI_VERSION_3_RHT,
NON_OSGI_VERSION_4_RHT);
@Test
public void getBestMatchVersionForNonExistingGAV() throws CommunicationException {
VersionAnalyzer.VersionAnalysisResult result = versionFinder.analyseVersions("0.0.1", Collections.EMPTY_LIST);
Optional<String> bmv = result.getBestMatchVersion();
assertFalse("Best match version expected to not be present", bmv.isPresent());
}
@Test
public void getBestMatchVersionForNotBuiltGAV() throws CommunicationException {
VersionAnalyzer.VersionAnalysisResult result = versionFinder.analyseVersions(NO_BUILT_VERSION, All_VERSIONS);
Optional<String> bmv = result.getBestMatchVersion();
assertFalse("Best match version expected to not be present", bmv.isPresent());
}
@Test
public void getBestMatchVersionForBuiltGAV() throws CommunicationException {
checkBMV(BUILT_VERSION_RH, BUILT_VERSION, All_VERSIONS.toArray(new String[All_VERSIONS.size()]));
checkBMV(BUILT_VERSION_2_RH, BUILT_VERSION_2, All_VERSIONS.toArray(new String[All_VERSIONS.size()]));
}
@Test
public void getBestMatchVersionForMultipleBuiltGAV() throws CommunicationException {
checkBMV(
MULTI_BUILT_VERSION_RH_BEST,
MULTI_BUILT_VERSION,
All_VERSIONS.toArray(new String[All_VERSIONS.size()]));
}
@Test
public void getBestMatchVersionForNoOSGIGAV() throws CommunicationException {
checkBMV(NON_OSGI_VERSION_RHT, NON_OSGI_VERSION, All_VERSIONS.toArray(new String[All_VERSIONS.size()]));
checkBMV(NON_OSGI_VERSION_2_RHT, NON_OSGI_VERSION_2, All_VERSIONS.toArray(new String[All_VERSIONS.size()]));
checkBMV(NON_OSGI_VERSION_3_RHT, NON_OSGI_VERSION_3, All_VERSIONS.toArray(new String[All_VERSIONS.size()]));
checkBMV(NON_OSGI_VERSION_4_RHT, NON_OSGI_VERSION_4, All_VERSIONS.toArray(new String[All_VERSIONS.size()]));
}
@Test
public void NCL2931ReproducerTest() {
String[] avaliableVersions = {
"1.4.0.redhat-4",
"1.4.redhat-3",
"1.4-redhat-2",
"1.4-redhat-1",
"1.6.0.redhat-5",
"1.6.0.redhat-4",
"1.6.0.redhat-3",
"1.6.redhat-2",
"1.6.redhat-1",
"1.9.0.redhat-1",
"1.10.0.redhat-5",
"1.10.0.redhat-4",
"1.10.0.redhat-3",
"1.10.0.redhat-2",
"1.10.0.redhat-1" };
checkBMV("1.4.0.redhat-4", "1.4", avaliableVersions);
}
@Test
public void ambiguousNonOSGIVersionsTest() {
String[] avaliableVersionsWithOSGI = { "1.0.0.redhat-1", "1.0.redhat-1", "1.redhat-1" };
checkBMV("1.0.0.redhat-1", "1.0.0", avaliableVersionsWithOSGI);
checkBMV("1.0.0.redhat-1", "1.0", avaliableVersionsWithOSGI);
checkBMV("1.0.0.redhat-1", "1", avaliableVersionsWithOSGI);
String[] avaliableVersionsWithOSGIRev = { "1.redhat-1", "1.0.redhat-1", "1.0.0.redhat-1" };
checkBMV("1.0.0.redhat-1", "1.0.0", avaliableVersionsWithOSGIRev);
checkBMV("1.0.0.redhat-1", "1.0", avaliableVersionsWithOSGIRev);
checkBMV("1.0.0.redhat-1", "1", avaliableVersionsWithOSGIRev);
String[] avaliableVersionsWithoutOSGI = { "1.0.redhat-1", "1.redhat-1" };
checkBMV("1.0.redhat-1", "1.0.0", avaliableVersionsWithoutOSGI);
checkBMV("1.0.redhat-1", "1.0", avaliableVersionsWithoutOSGI);
checkBMV("1.0.redhat-1", "1", avaliableVersionsWithoutOSGI);
String[] avaliableVersionsWithoutOSGI2 = { "1.redhat-1" };
checkBMV("1.redhat-1", "1.0.0", avaliableVersionsWithoutOSGI2);
checkBMV("1.redhat-1", "1.0", avaliableVersionsWithoutOSGI2);
checkBMV("1.redhat-1", "1", avaliableVersionsWithoutOSGI2);
}
@Test
public void nonOSGIVersionsTest() {
String[] avaliableVersions1 = { "1.0.0.redhat-1", "1.0.redhat-2", "1.redhat-3" };
checkBMV("1.redhat-3", "1.0.0", avaliableVersions1);
checkBMV("1.redhat-3", "1.0", avaliableVersions1);
checkBMV("1.redhat-3", "1", avaliableVersions1);
String[] avaliableVersions10 = { "1.0.0.redhat-1", "1.0.redhat-3", "1.redhat-2" };
checkBMV("1.0.redhat-3", "1.0.0", avaliableVersions10);
checkBMV("1.0.redhat-3", "1.0", avaliableVersions10);
checkBMV("1.0.redhat-3", "1", avaliableVersions10);
String[] avaliableVersions100 = { "1.0.0.redhat-3", "1.0.redhat-2", "1.redhat-1" };
checkBMV("1.0.0.redhat-3", "1.0.0", avaliableVersions100);
checkBMV("1.0.0.redhat-3", "1.0", avaliableVersions100);
checkBMV("1.0.0.redhat-3", "1", avaliableVersions100);
}
@Test
public void NCL4266ReproducerTest() {
String[] avaliableVersions1 = {
"2.2.3.redhat-00001",
"2.2.0.temporary-redhat-00001",
"2.2.0.redhat-00001",
"2.1.16.redhat-00001",
"2.1.9.redhat-1",
"2.1.9.redhat-001",
"2.1.3.redhat-001" };
checkBMV(
new VersionAnalyzer(new VersionParser("temporary-redhat")),
"2.2.3.redhat-00001",
"2.2.3",
avaliableVersions1);
}
@Test
public void preferOSGiVersionFormatTest() {
// as 3.0.0-redhat-2 and 3.0.0.redhat-2 are the same version then ordering in the array matters
// (if they were in opposite direction test would pass even without OSGi preference)
String[] availableVersions = {
"3-redhat-2",
"3.0.0-redhat-2",
"3.0.0.redhat-2",
"3.0.0.redhat-1",
"2.1.1.redhat-3",
"2.1.16-redhat-9",
"2.9.9-redhat-00001" };
checkBMV("3.0.0.redhat-2", "3", availableVersions);
}
private void checkBMV(String expectedVersion, String version, String[] versions) {
checkBMV(versionFinder, expectedVersion, version, versions);
}
private void checkBMV(VersionAnalyzer versionAnalyzer, String expectedVersion, String version, String[] versions) {
VersionAnalyzer.VersionAnalysisResult result = versionAnalyzer
.analyseVersions(version, Arrays.asList(versions));
Optional<String> bmv = result.getBestMatchVersion();
assertTrue("Best match version expected to be present", bmv.isPresent());
assertEquals(expectedVersion, bmv.get());
}
@Test
public void testDifferentSuffix() {
VersionAnalyzer versionAnalyzer = new VersionAnalyzer(new VersionParser("temporary-redhat"));
String version = "1.4.0";
String expectedVersion = "1.4.0.temporary-redhat-1";
String[] avaliableVersionsOrder1 = { "1.4.0.redhat-1", "1.4.0.temporary-redhat-1" };
checkBMV(versionAnalyzer, expectedVersion, version, avaliableVersionsOrder1);
String[] avaliableVersionsOrder2 = { "1.4.0.temporary-redhat-1", "1.4.0.redhat-1" };
checkBMV(versionAnalyzer, expectedVersion, version, avaliableVersionsOrder2);
String[] avaliableVersionsMultiple = {
"1.4.0.redhat-4",
"1.4.0.redhat-3",
"1.4.0.redhat-2",
"1.4.0.redhat-1",
"1.4.0.temporary-redhat-1", };
checkBMV(versionAnalyzer, expectedVersion, version, avaliableVersionsMultiple);
}
@Test
public void testDifferentSuffixWithOnlyDefaultVersions() {
VersionAnalyzer versionAnalyzer = new VersionAnalyzer(new VersionParser("t20180522-115319-991-redhat"));
String version = "1.4.0";
String[] avaliableVersionsOrder1 = { "1.4.0.redhat-1", "1.4.0.temporary-redhat-1" };
checkBMV(versionAnalyzer, "1.4.0.redhat-1", version, avaliableVersionsOrder1);
String[] avaliableVersionsOrder2 = { "1.4.0.temporary-redhat-1", "1.4.0.redhat-1" };
checkBMV(versionAnalyzer, "1.4.0.redhat-1", version, avaliableVersionsOrder2);
String[] avaliableVersionsMultiple = {
"1.4.0.redhat-4",
"1.4.0.redhat-3",
"1.4.0.redhat-2",
"1.4.0.redhat-1",
"1.4.0.temporary-redhat-1", };
checkBMV(versionAnalyzer, "1.4.0.redhat-4", version, avaliableVersionsMultiple);
}
}
| 40.868966 | 119 | 0.640061 |
75e457a865fc2764f03f5089bf856eabd526b92c | 75 | package com.gpaganini;
public class Num {
int i, limite, incr;
}
| 12.5 | 25 | 0.626667 |
c2a982e31a19e45615a4aa5f8673f77b6cdc98ab | 1,287 | // Autogenerated from development/flavors/type_flavor_impl.i
package ideal.development.flavors;
import ideal.library.elements.*;
import ideal.runtime.elements.*;
import ideal.runtime.logs.*;
import ideal.development.elements.*;
import ideal.development.names.*;
public class type_flavor_impl extends debuggable implements type_flavor, readonly_displayable {
private final simple_name the_name;
private final flavor_profile profile;
private final immutable_list<type_flavor> superflavors;
public final hash_dictionary<principal_type, type> types = new hash_dictionary<principal_type, type>();
public type_flavor_impl(final string the_name, final flavor_profile profile, final readonly_list<type_flavor> declared_superflavors) {
this.the_name = simple_name.make(the_name);
this.profile = profile;
this.superflavors = declared_superflavors.frozen_copy();
}
public @Override simple_name name() {
return this.the_name;
}
public @Override flavor_profile get_profile() {
return this.profile;
}
public @Override immutable_list<type_flavor> get_superflavors() {
return this.superflavors;
}
public @Override string to_string() {
return this.the_name.to_string();
}
public @Override string display() {
return this.to_string();
}
}
| 34.783784 | 136 | 0.773893 |
67757f3c324d91f6dbc556ab329b94cb013a848c | 658 | package org.ovirt.engine.core.bll;
import org.ovirt.engine.core.bll.context.EngineContext;
import org.ovirt.engine.core.common.queries.VdcQueryParametersBase;
public class GetAllVmPoolsAttachedToUserQuery<P extends VdcQueryParametersBase> extends QueriesCommandBase<P> {
public GetAllVmPoolsAttachedToUserQuery(P parameters, EngineContext engineContext) {
super(parameters, engineContext);
}
public GetAllVmPoolsAttachedToUserQuery(P parameters) {
this(parameters, null);
}
@Override
protected void executeQueryCommand() {
setReturnValue(getDbFacade().getVmPoolDao().getAllForUser(getUserID()));
}
}
| 29.909091 | 111 | 0.762918 |
9195d6896d8461fc731cf436a5d9653823b17c0e | 7,469 | package stowage;
import java.util.Iterator;
import java.lang.Iterable;
import java.util.ConcurrentModificationException;
import java.util.NoSuchElementException;
public class SphericInterlinkedDirectory<T> implements Iterable<T> {
public int modeEnumerate;
public int figures;
public final stowage.Nucleus<T> scout;
static double depressShackled = 0.8766011844615584;
public SphericInterlinkedDirectory() {
this.scout = new stowage.Nucleus<T>(null, null, null);
this.scout.solidifyingThe(this.scout);
this.scout.situatedLatest(this.scout);
this.figures = 0;
this.modeEnumerate = 0;
}
public synchronized void addPremiere(T findings) {
double matt;
matt = 0.9470291200000294;
this.introduceSubsequentlyClient(findings, this.scout);
}
public synchronized void insertionFinally(T study) {
String frownObligated;
frownObligated = "atYFTT9HWEH4csTt";
this.incorporatedNeverIssue(study, this.scout);
}
public synchronized void incorporatedBackArgue(T results, T goal) throws ArrayStoreException {
String fukkianese;
RosterInitialise date;
fukkianese = "nQv4aRIs9cqRAJiV";
date = new RosterInitialise();
while (date.hasNext()) {
if (date.next() == goal) {
this.introduceSubsequentlyClient(results, date.former);
return;
}
}
throw new java.lang.ArrayStoreException("Target " + goal + " is not in the list");
}
public synchronized void embeddedUnlessOpposes(T database, T limit) throws ArrayStoreException {
double restrictions;
RosterInitialise prove;
restrictions = 0.07251789172642531;
prove = new RosterInitialise();
while (prove.hasNext()) {
if (prove.next() == limit) {
this.incorporatedNeverIssue(database, prove.former);
return;
}
}
throw new java.lang.ArrayStoreException("Target " + limit + " is not in the list");
}
public synchronized void introduceSubsequentlyClient(T stats, stowage.Nucleus<T> objective) {
double fundamental;
stowage.Nucleus<T> newfangledNodal;
fundamental = 0.27281813406164734;
newfangledNodal = new stowage.Nucleus<T>(stats, objective.takeLater(), objective);
objective.takeLater().situatedLatest(newfangledNodal);
objective.solidifyingThe(newfangledNodal);
this.figures++;
this.modeEnumerate++;
}
public synchronized void incorporatedNeverIssue(T databases, stowage.Nucleus<T> benchmark) {
double bottomConfine;
stowage.Nucleus<T> untestedScn;
bottomConfine = 0.18496969776165828;
untestedScn = new stowage.Nucleus<T>(databases, benchmark, benchmark.beatElapsed());
benchmark.beatElapsed().solidifyingThe(untestedScn);
benchmark.situatedLatest(untestedScn);
this.figures++;
this.modeEnumerate++;
}
public synchronized T reinstallLow() {
double numbers;
stowage.Nucleus<T> objectives;
numbers = 0.9364552630780253;
objectives = this.scout.takeLater();
this.scout.solidifyingThe(objectives.takeLater());
objectives.takeLater().situatedLatest(this.scout);
if (this.figures > 0) this.figures--;
this.modeEnumerate++;
return objectives.comeDatabases();
}
public synchronized T takePast() {
int list;
stowage.Nucleus<T> point;
list = -368164480;
point = this.scout.beatElapsed();
this.scout.situatedLatest(point.beatElapsed());
point.beatElapsed().solidifyingThe(this.scout);
if (this.figures > 0) this.figures--;
this.modeEnumerate++;
return point.comeDatabases();
}
public synchronized void takeObjective(T computer) {
double weigh;
RosterInitialise bool;
weigh = 0.6215378900692976;
bool = new RosterInitialise();
while (bool.hasNext()) {
if (bool.next() == computer) {
bool.remove();
return;
}
}
throw new java.lang.ArrayStoreException("Object " + computer + " was not found");
}
public synchronized T maidenItem() {
int widening;
widening = -401915596;
return this.scout.takeLater().comeDatabases();
}
public synchronized T seniorPreclude() {
double elevatedEnchained;
elevatedEnchained = 0.510267907764225;
return this.scout.beatElapsed().comeDatabases();
}
public synchronized boolean isEmpty() {
int breadth;
breadth = 1062771422;
return (this.scout.takeLater() == this.scout);
}
public synchronized int census() {
String highWidening;
highWidening = "6TSIPna";
return this.figures;
}
public synchronized String toString() {
double minimum;
java.lang.StringBuffer separating;
RosterInitialise battologize;
int i;
minimum = 0.5633529543639026;
separating = new java.lang.StringBuffer(this.hashCode() + " {\n");
battologize = new RosterInitialise();
i = 0;
while (battologize.hasNext()) {
separating.append("[" + i + "]\t" + battologize.next() + "\n");
i++;
}
separating.append("}\n");
return separating.toString();
}
public synchronized Iterator<T> iterator() {
double nungWeighting;
nungWeighting = 0.4201028414923237;
return new RosterInitialise();
}
public class RosterInitialise implements Iterator<T> {
public boolean newOffersEnduredSuggested;
public int heartFrequency;
public stowage.Nucleus<T> former;
public RosterInitialise() {
this.former = stowage.SphericInterlinkedDirectory.this.scout;
this.heartFrequency = stowage.SphericInterlinkedDirectory.this.modeEnumerate;
this.newOffersEnduredSuggested = false;
}
public synchronized boolean hasNext() {
double maximizeWide;
maximizeWide = 0.07139330556718027;
return (this.former.takeLater() != stowage.SphericInterlinkedDirectory.this.scout);
}
public synchronized T next() throws ConcurrentModificationException, NoSuchElementException {
double glowerSure;
glowerSure = 0.5244459458393694;
if (this.heartFrequency != stowage.SphericInterlinkedDirectory.this.modeEnumerate)
throw new java.util.ConcurrentModificationException(
"Iterator " + this.hashCode() + " is out of sync");
if (!this.hasNext())
throw new java.util.NoSuchElementException(
"List "
+ stowage.SphericInterlinkedDirectory.this.hashCode()
+ " has no more elements");
this.newOffersEnduredSuggested = true;
this.former = this.former.takeLater();
return this.former.comeDatabases();
}
public synchronized void remove() throws ConcurrentModificationException {
double reduceConstrain;
stowage.Nucleus<T> reach;
reduceConstrain = 0.3557362782605348;
if (this.heartFrequency != stowage.SphericInterlinkedDirectory.this.modeEnumerate)
throw new java.util.ConcurrentModificationException(
"Iterator " + this.hashCode() + " is out of sync");
if (!this.newOffersEnduredSuggested)
throw new java.util.ConcurrentModificationException(
"Next has not been called on iterator " + this.hashCode());
this.newOffersEnduredSuggested = false;
reach = this.former;
this.former = this.former.beatElapsed();
this.former.solidifyingThe(reach.takeLater());
reach.takeLater().situatedLatest(this.former);
this.heartFrequency++;
stowage.SphericInterlinkedDirectory.this.modeEnumerate++;
stowage.SphericInterlinkedDirectory.this.figures--;
}
}
}
| 31.120833 | 98 | 0.695408 |
b4f5b463ded58f8457c312438ede30c0b084d922 | 207 | public class Gen {
public static void main(String[] args){
int N = 100000;
System.out.println(N);
for(int i = N; i > 0; i--){
System.out.printf("%d %d", i, 1000);
System.out.println();
}
}
}
| 18.818182 | 40 | 0.57971 |
f0ed8d099749c131b1809caa084c443a9c110701 | 1,626 | package com.ley.springboot.commons.tree;
import com.ley.springboot.commons.utils.CollectionUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* tree utils
**/
public abstract class BaseTreeUtils<T extends BaseTreeNode> {
/**
* 建树
*
* @param nodes 节点集合
**/
public List<T> buildTree(List<T> nodes) {
List<T> rootNodes = new ArrayList<>(16);
//获取根节点集合
for (T node : nodes) {
if (isRootNode(node)) {
rootNodes.add(node);
}
}
//为根节点设置子节点
for (T rootNode : rootNodes) {
//获取根节点下的所有子节点,使用getChildren()
List<T> children = getChildren(rootNode, nodes);
rootNode.setChildren(children);
}
return rootNodes;
}
/**
* 获取子节点
**/
private List<T> getChildren(T rootNode, List<T> nodes) {
List<T> children = new ArrayList<>(256);
for (T node : nodes) {
// 遍历所有节点,将所有父id与传过来的根节点的id比较
//相等说明:为该根节点的子节点
if (rootNode.getId().equals(node.getPid())) {
children.add(node);
}
}
// 递归设置子节点集合
for (T child : children) {
child.setChildren(getChildren(child, nodes));
}
// 结束递归
if (CollectionUtils.isEmpty(children)) {
return Collections.emptyList();
}
return children;
}
/**
* 判断一个节点是否是根节点
*
* @return return {@code true} when node is root node.
**/
protected abstract boolean isRootNode(T treeNode);
}
| 20.582278 | 61 | 0.537515 |
ba2806a1d325fe551386e2c3c4642205c02603fc | 46,743 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|javascript
package|;
end_package
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|ByteArrayInputStream
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|ByteArrayOutputStream
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|IOException
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|InputStream
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|OutputStream
import|;
end_import
begin_import
import|import
name|java
operator|.
name|lang
operator|.
name|reflect
operator|.
name|InvocationTargetException
import|;
end_import
begin_import
import|import
name|java
operator|.
name|net
operator|.
name|HttpURLConnection
import|;
end_import
begin_import
import|import
name|java
operator|.
name|net
operator|.
name|MalformedURLException
import|;
end_import
begin_import
import|import
name|java
operator|.
name|net
operator|.
name|ProtocolException
import|;
end_import
begin_import
import|import
name|java
operator|.
name|net
operator|.
name|URI
import|;
end_import
begin_import
import|import
name|java
operator|.
name|net
operator|.
name|URISyntaxException
import|;
end_import
begin_import
import|import
name|java
operator|.
name|net
operator|.
name|URL
import|;
end_import
begin_import
import|import
name|java
operator|.
name|net
operator|.
name|URLConnection
import|;
end_import
begin_import
import|import
name|java
operator|.
name|nio
operator|.
name|ByteBuffer
import|;
end_import
begin_import
import|import
name|java
operator|.
name|nio
operator|.
name|CharBuffer
import|;
end_import
begin_import
import|import
name|java
operator|.
name|nio
operator|.
name|charset
operator|.
name|Charset
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|HashMap
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|HashSet
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|List
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Map
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Set
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|logging
operator|.
name|Level
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|logging
operator|.
name|Logger
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|xml
operator|.
name|parsers
operator|.
name|DocumentBuilder
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|xml
operator|.
name|parsers
operator|.
name|DocumentBuilderFactory
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|xml
operator|.
name|parsers
operator|.
name|ParserConfigurationException
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|xml
operator|.
name|transform
operator|.
name|TransformerException
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|xml
operator|.
name|transform
operator|.
name|TransformerFactory
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|xml
operator|.
name|transform
operator|.
name|TransformerFactoryConfigurationError
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|xml
operator|.
name|transform
operator|.
name|dom
operator|.
name|DOMSource
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|xml
operator|.
name|transform
operator|.
name|stream
operator|.
name|StreamResult
import|;
end_import
begin_import
import|import
name|org
operator|.
name|w3c
operator|.
name|dom
operator|.
name|Document
import|;
end_import
begin_import
import|import
name|org
operator|.
name|w3c
operator|.
name|dom
operator|.
name|Node
import|;
end_import
begin_import
import|import
name|org
operator|.
name|xml
operator|.
name|sax
operator|.
name|InputSource
import|;
end_import
begin_import
import|import
name|org
operator|.
name|xml
operator|.
name|sax
operator|.
name|SAXException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|common
operator|.
name|logging
operator|.
name|LogUtils
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|helpers
operator|.
name|HttpHeaderHelper
import|;
end_import
begin_import
import|import
name|org
operator|.
name|mozilla
operator|.
name|javascript
operator|.
name|Context
import|;
end_import
begin_import
import|import
name|org
operator|.
name|mozilla
operator|.
name|javascript
operator|.
name|ContextFactory
import|;
end_import
begin_import
import|import
name|org
operator|.
name|mozilla
operator|.
name|javascript
operator|.
name|Function
import|;
end_import
begin_import
import|import
name|org
operator|.
name|mozilla
operator|.
name|javascript
operator|.
name|JavaScriptException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|mozilla
operator|.
name|javascript
operator|.
name|ScriptableObject
import|;
end_import
begin_import
import|import static
name|java
operator|.
name|nio
operator|.
name|charset
operator|.
name|StandardCharsets
operator|.
name|UTF_8
import|;
end_import
begin_comment
comment|/** * Implementation of XMLHttpRequest for Rhino. This might be given knowledge of * CXF 'local' URLs if the author is feeling frisky. */
end_comment
begin_class
specifier|public
class|class
name|JsXMLHttpRequest
extends|extends
name|ScriptableObject
block|{
specifier|private
specifier|static
specifier|final
name|long
name|serialVersionUID
init|=
literal|6993486986900120981L
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|Logger
name|LOG
init|=
name|LogUtils
operator|.
name|getL7dLogger
argument_list|(
name|JsXMLHttpRequest
operator|.
name|class
argument_list|)
decl_stmt|;
specifier|private
specifier|static
name|Set
argument_list|<
name|String
argument_list|>
name|validMethods
decl_stmt|;
static|static
block|{
name|validMethods
operator|=
operator|new
name|HashSet
argument_list|<>
argument_list|()
expr_stmt|;
name|validMethods
operator|.
name|add
argument_list|(
literal|"GET"
argument_list|)
expr_stmt|;
name|validMethods
operator|.
name|add
argument_list|(
literal|"POST"
argument_list|)
expr_stmt|;
name|validMethods
operator|.
name|add
argument_list|(
literal|"HEAD"
argument_list|)
expr_stmt|;
name|validMethods
operator|.
name|add
argument_list|(
literal|"PUT"
argument_list|)
expr_stmt|;
name|validMethods
operator|.
name|add
argument_list|(
literal|"OPTIONS"
argument_list|)
expr_stmt|;
name|validMethods
operator|.
name|add
argument_list|(
literal|"DELETE"
argument_list|)
expr_stmt|;
block|}
specifier|private
specifier|static
name|String
index|[]
name|invalidHeaders
init|=
block|{
literal|"Accept-Charset"
block|,
literal|"Accept-Encoding"
block|,
literal|"Connection"
block|,
literal|"Content-Length"
block|,
literal|"Content-Transfer-Encoding"
block|,
literal|"Date"
block|,
literal|"Expect"
block|,
literal|"Host"
block|,
literal|"Keep-Alive"
block|,
literal|"Referer"
block|,
literal|"TE"
block|,
literal|"Trailer"
block|,
literal|"Transfer-Encoding"
block|,
literal|"Upgrade"
block|,
literal|"Via"
block|}
decl_stmt|;
specifier|private
name|int
name|readyState
init|=
name|jsGet_UNSENT
argument_list|()
decl_stmt|;
specifier|private
name|Object
name|readyStateChangeListener
decl_stmt|;
specifier|private
name|Map
argument_list|<
name|String
argument_list|,
name|String
argument_list|>
name|requestHeaders
decl_stmt|;
specifier|private
name|String
name|storedMethod
decl_stmt|;
specifier|private
name|String
name|storedUser
decl_stmt|;
specifier|private
name|String
name|storedPassword
decl_stmt|;
specifier|private
name|boolean
name|sendFlag
decl_stmt|;
specifier|private
name|URI
name|uri
decl_stmt|;
specifier|private
name|URL
name|url
decl_stmt|;
specifier|private
name|boolean
name|storedAsync
decl_stmt|;
specifier|private
name|URLConnection
name|connection
decl_stmt|;
specifier|private
name|HttpURLConnection
name|httpConnection
decl_stmt|;
specifier|private
name|Map
argument_list|<
name|String
argument_list|,
name|List
argument_list|<
name|String
argument_list|>
argument_list|>
name|responseHeaders
decl_stmt|;
specifier|private
name|int
name|httpResponseCode
decl_stmt|;
specifier|private
name|String
name|httpResponseText
decl_stmt|;
specifier|private
name|String
name|responseText
decl_stmt|;
specifier|private
name|JsSimpleDomNode
name|responseXml
decl_stmt|;
specifier|private
name|boolean
name|errorFlag
decl_stmt|;
specifier|public
name|JsXMLHttpRequest
parameter_list|()
block|{
name|requestHeaders
operator|=
operator|new
name|HashMap
argument_list|<>
argument_list|()
expr_stmt|;
name|storedMethod
operator|=
literal|null
expr_stmt|;
block|}
specifier|public
specifier|static
name|void
name|register
parameter_list|(
name|ScriptableObject
name|scope
parameter_list|)
block|{
try|try
block|{
name|ScriptableObject
operator|.
name|defineClass
argument_list|(
name|scope
argument_list|,
name|JsXMLHttpRequest
operator|.
name|class
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|IllegalAccessException
decl||
name|InstantiationException
decl||
name|InvocationTargetException
name|e
parameter_list|)
block|{
throw|throw
operator|new
name|RuntimeException
argument_list|(
name|e
argument_list|)
throw|;
block|}
block|}
annotation|@
name|Override
specifier|public
name|String
name|getClassName
parameter_list|()
block|{
return|return
literal|"XMLHttpRequest"
return|;
block|}
specifier|private
name|void
name|notifyReadyStateChangeListener
parameter_list|()
block|{
if|if
condition|(
name|readyStateChangeListener
operator|instanceof
name|Function
condition|)
block|{
name|LOG
operator|.
name|fine
argument_list|(
literal|"notify "
operator|+
name|readyState
argument_list|)
expr_stmt|;
comment|// for now, call with no args.
name|Function
name|listenerFunction
init|=
operator|(
name|Function
operator|)
name|readyStateChangeListener
decl_stmt|;
name|listenerFunction
operator|.
name|call
argument_list|(
name|Context
operator|.
name|getCurrentContext
argument_list|()
argument_list|,
name|getParentScope
argument_list|()
argument_list|,
literal|null
argument_list|,
operator|new
name|Object
index|[]
block|{}
argument_list|)
expr_stmt|;
block|}
block|}
specifier|private
name|void
name|doOpen
parameter_list|(
name|String
name|method
parameter_list|,
name|String
name|urlString
parameter_list|,
name|boolean
name|async
parameter_list|,
name|String
name|user
parameter_list|,
name|String
name|password
parameter_list|)
block|{
comment|// ignoring auth for now.
name|LOG
operator|.
name|fine
argument_list|(
literal|"doOpen "
operator|+
name|method
operator|+
literal|" "
operator|+
name|urlString
operator|+
literal|" "
operator|+
name|Boolean
operator|.
name|toString
argument_list|(
name|async
argument_list|)
argument_list|)
expr_stmt|;
name|storedAsync
operator|=
name|async
expr_stmt|;
name|responseText
operator|=
literal|null
expr_stmt|;
name|responseXml
operator|=
literal|null
expr_stmt|;
comment|// see 4
name|method
operator|=
name|method
operator|.
name|toUpperCase
argument_list|()
expr_stmt|;
comment|// 1 check method
if|if
condition|(
operator|!
name|validMethods
operator|.
name|contains
argument_list|(
name|method
argument_list|)
condition|)
block|{
name|LOG
operator|.
name|fine
argument_list|(
literal|"Invalid method syntax error."
argument_list|)
expr_stmt|;
name|throwError
argument_list|(
literal|"SYNTAX_ERR"
argument_list|)
expr_stmt|;
block|}
comment|// 2 security check (we don't have any)
comment|// 3 store method
name|storedMethod
operator|=
name|method
expr_stmt|;
comment|// 4 we already mapped it to upper case.
comment|// 5 make a URL, dropping any fragment.
name|uri
operator|=
literal|null
expr_stmt|;
try|try
block|{
name|URI
name|tempUri
init|=
operator|new
name|URI
argument_list|(
name|urlString
argument_list|)
decl_stmt|;
if|if
condition|(
name|tempUri
operator|.
name|isOpaque
argument_list|()
condition|)
block|{
name|LOG
operator|.
name|fine
argument_list|(
literal|"Relative URL syntax error."
argument_list|)
expr_stmt|;
name|throwError
argument_list|(
literal|"SYNTAX_ERR"
argument_list|)
expr_stmt|;
block|}
name|uri
operator|=
operator|new
name|URI
argument_list|(
name|tempUri
operator|.
name|getScheme
argument_list|()
argument_list|,
name|tempUri
operator|.
name|getUserInfo
argument_list|()
argument_list|,
name|tempUri
operator|.
name|getHost
argument_list|()
argument_list|,
name|tempUri
operator|.
name|getPort
argument_list|()
argument_list|,
name|tempUri
operator|.
name|getPath
argument_list|()
argument_list|,
name|tempUri
operator|.
name|getQuery
argument_list|()
argument_list|,
literal|null
comment|/* * no * fragment */
argument_list|)
expr_stmt|;
name|url
operator|=
name|uri
operator|.
name|toURL
argument_list|()
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|URISyntaxException
name|e
parameter_list|)
block|{
name|LOG
operator|.
name|log
argument_list|(
name|Level
operator|.
name|SEVERE
argument_list|,
literal|"URI syntax error"
argument_list|,
name|e
argument_list|)
expr_stmt|;
name|throwError
argument_list|(
literal|"SYNTAX_ERR"
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|MalformedURLException
name|e
parameter_list|)
block|{
name|LOG
operator|.
name|log
argument_list|(
name|Level
operator|.
name|SEVERE
argument_list|,
literal|"URI isn't URL"
argument_list|,
name|e
argument_list|)
expr_stmt|;
name|throwError
argument_list|(
literal|"SYNTAX_ERR"
argument_list|)
expr_stmt|;
block|}
comment|// 6 deal with relative URLs. We don't have a base. This is a limitation
comment|// on browser compatibility.
if|if
condition|(
operator|!
name|uri
operator|.
name|isAbsolute
argument_list|()
condition|)
block|{
name|throwError
argument_list|(
literal|"SYNTAX_ERR"
argument_list|)
expr_stmt|;
block|}
comment|// 7 scheme check. Well, for now ...
if|if
condition|(
operator|!
literal|"http"
operator|.
name|equals
argument_list|(
name|uri
operator|.
name|getScheme
argument_list|()
argument_list|)
operator|&&
operator|!
literal|"https"
operator|.
name|equals
argument_list|(
name|uri
operator|.
name|getScheme
argument_list|()
argument_list|)
condition|)
block|{
name|LOG
operator|.
name|severe
argument_list|(
literal|"Not http "
operator|+
name|uri
operator|.
name|toString
argument_list|()
argument_list|)
expr_stmt|;
name|throwError
argument_list|(
literal|"NOT_SUPPORTED_ERR"
argument_list|)
expr_stmt|;
block|}
comment|// 8 user:password is OK for HTTP.
comment|// 9, 10 user/password parsing
if|if
condition|(
name|uri
operator|.
name|getUserInfo
argument_list|()
operator|!=
literal|null
condition|)
block|{
name|String
index|[]
name|userAndPassword
init|=
name|uri
operator|.
name|getUserInfo
argument_list|()
operator|.
name|split
argument_list|(
literal|":"
argument_list|)
decl_stmt|;
name|storedUser
operator|=
name|userAndPassword
index|[
literal|0
index|]
expr_stmt|;
if|if
condition|(
name|userAndPassword
operator|.
name|length
operator|==
literal|2
condition|)
block|{
name|storedPassword
operator|=
name|userAndPassword
index|[
literal|1
index|]
expr_stmt|;
block|}
block|}
comment|// 11 cross-scripting check. We don't implement it.
comment|// 12 default async. Already done.
comment|// 13 check user for syntax. Not Our Job.
comment|// 14 encode the user. We think we can leave this for the Http code we
comment|// use below
comment|// 15, 16, 17, 18 more user/password glop.
comment|// 19: abort any pending activity.
comment|// TODO: abort
comment|// 20 cancel network activity.
comment|// TODO: cancel
comment|// 21 set state to OPENED and fire the listener.
name|readyState
operator|=
name|jsGet_OPENED
argument_list|()
expr_stmt|;
name|sendFlag
operator|=
literal|false
expr_stmt|;
name|notifyReadyStateChangeListener
argument_list|()
expr_stmt|;
block|}
specifier|private
name|void
name|doSetRequestHeader
parameter_list|(
name|String
name|header
parameter_list|,
name|String
name|value
parameter_list|)
block|{
comment|// 1 check state
if|if
condition|(
name|readyState
operator|!=
name|jsGet_OPENED
argument_list|()
condition|)
block|{
name|LOG
operator|.
name|severe
argument_list|(
literal|"setRequestHeader invalid state "
operator|+
name|readyState
argument_list|)
expr_stmt|;
name|throwError
argument_list|(
literal|"INVALID_STATE_ERR"
argument_list|)
expr_stmt|;
block|}
comment|// 2 check flag
if|if
condition|(
name|sendFlag
condition|)
block|{
name|LOG
operator|.
name|severe
argument_list|(
literal|"setRequestHeader send flag set."
argument_list|)
expr_stmt|;
name|throwError
argument_list|(
literal|"INVALID_STATE_ERR"
argument_list|)
expr_stmt|;
block|}
comment|// 3 check field-name production.
comment|// 4 ignore null values.
if|if
condition|(
name|value
operator|==
literal|null
condition|)
block|{
return|return;
block|}
comment|// 5 check value
comment|// 6 check for bad headers
for|for
control|(
name|String
name|invalid
range|:
name|invalidHeaders
control|)
block|{
if|if
condition|(
name|header
operator|.
name|equalsIgnoreCase
argument_list|(
name|invalid
argument_list|)
condition|)
block|{
name|LOG
operator|.
name|severe
argument_list|(
literal|"setRequestHeader invalid header."
argument_list|)
expr_stmt|;
name|throwError
argument_list|(
literal|"SECURITY_ERR"
argument_list|)
expr_stmt|;
block|}
block|}
comment|// 7 check for proxy
name|String
name|headerLower
init|=
name|header
operator|.
name|toLowerCase
argument_list|()
decl_stmt|;
if|if
condition|(
name|headerLower
operator|.
name|startsWith
argument_list|(
literal|"proxy-"
argument_list|)
condition|)
block|{
name|LOG
operator|.
name|severe
argument_list|(
literal|"setRequestHeader proxy header."
argument_list|)
expr_stmt|;
name|throwError
argument_list|(
literal|"SECURITY_ERR"
argument_list|)
expr_stmt|;
block|}
comment|// 8, 9, handle appends.
name|String
name|previous
init|=
name|requestHeaders
operator|.
name|get
argument_list|(
name|header
argument_list|)
decl_stmt|;
if|if
condition|(
name|previous
operator|!=
literal|null
condition|)
block|{
name|value
operator|=
name|previous
operator|+
literal|", "
operator|+
name|value
expr_stmt|;
block|}
name|requestHeaders
operator|.
name|put
argument_list|(
name|header
argument_list|,
name|value
argument_list|)
expr_stmt|;
block|}
specifier|private
name|void
name|doSend
parameter_list|(
name|byte
index|[]
name|dataToSend
parameter_list|,
name|boolean
name|xml
parameter_list|)
block|{
comment|// avoid warnings on stuff we arent using yet.
if|if
condition|(
name|storedUser
operator|!=
literal|null
operator|||
name|storedPassword
operator|!=
literal|null
condition|)
block|{
comment|//
block|}
comment|// 1 check state
if|if
condition|(
name|readyState
operator|!=
name|jsGet_OPENED
argument_list|()
condition|)
block|{
name|LOG
operator|.
name|severe
argument_list|(
literal|"send state != OPENED."
argument_list|)
expr_stmt|;
name|throwError
argument_list|(
literal|"INVALID_STATE_ERR"
argument_list|)
expr_stmt|;
block|}
comment|// 2 check flag
if|if
condition|(
name|sendFlag
condition|)
block|{
name|LOG
operator|.
name|severe
argument_list|(
literal|"send sendFlag set."
argument_list|)
expr_stmt|;
name|throwError
argument_list|(
literal|"INVALID_STATE_ERR"
argument_list|)
expr_stmt|;
block|}
comment|// 3
name|sendFlag
operator|=
name|storedAsync
expr_stmt|;
comment|// 4 preprocess data. Handled on the way in here, we're called with
comment|// UTF-8 bytes.
if|if
condition|(
name|xml
operator|&&
operator|!
name|requestHeaders
operator|.
name|containsKey
argument_list|(
literal|"Content-Type"
argument_list|)
condition|)
block|{
name|requestHeaders
operator|.
name|put
argument_list|(
literal|"Content-Type"
argument_list|,
literal|"application/xml;charset=utf-8"
argument_list|)
expr_stmt|;
block|}
comment|// 5 talk to the server.
try|try
block|{
name|connection
operator|=
name|url
operator|.
name|openConnection
argument_list|()
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|IOException
name|e
parameter_list|)
block|{
name|LOG
operator|.
name|log
argument_list|(
name|Level
operator|.
name|SEVERE
argument_list|,
literal|"send connection failed."
argument_list|,
name|e
argument_list|)
expr_stmt|;
name|throwError
argument_list|(
literal|"CONNECTION_FAILED"
argument_list|)
expr_stmt|;
block|}
name|connection
operator|.
name|setDoInput
argument_list|(
literal|true
argument_list|)
expr_stmt|;
name|connection
operator|.
name|setUseCaches
argument_list|(
literal|false
argument_list|)
expr_stmt|;
comment|// Enable tunneling.
name|boolean
name|post
init|=
literal|false
decl_stmt|;
name|httpConnection
operator|=
literal|null
expr_stmt|;
if|if
condition|(
name|connection
operator|instanceof
name|HttpURLConnection
condition|)
block|{
name|httpConnection
operator|=
operator|(
name|HttpURLConnection
operator|)
name|connection
expr_stmt|;
try|try
block|{
name|httpConnection
operator|.
name|setRequestMethod
argument_list|(
name|storedMethod
argument_list|)
expr_stmt|;
if|if
condition|(
literal|"POST"
operator|.
name|equalsIgnoreCase
argument_list|(
name|storedMethod
argument_list|)
condition|)
block|{
name|httpConnection
operator|.
name|setDoOutput
argument_list|(
literal|true
argument_list|)
expr_stmt|;
name|post
operator|=
literal|true
expr_stmt|;
block|}
for|for
control|(
name|Map
operator|.
name|Entry
argument_list|<
name|String
argument_list|,
name|String
argument_list|>
name|headerEntry
range|:
name|requestHeaders
operator|.
name|entrySet
argument_list|()
control|)
block|{
name|httpConnection
operator|.
name|setRequestProperty
argument_list|(
name|headerEntry
operator|.
name|getKey
argument_list|()
argument_list|,
name|headerEntry
operator|.
name|getValue
argument_list|()
argument_list|)
expr_stmt|;
block|}
block|}
catch|catch
parameter_list|(
name|ProtocolException
name|e
parameter_list|)
block|{
name|LOG
operator|.
name|log
argument_list|(
name|Level
operator|.
name|SEVERE
argument_list|,
literal|"send http protocol exception."
argument_list|,
name|e
argument_list|)
expr_stmt|;
name|throwError
argument_list|(
literal|"HTTP_PROTOCOL_ERROR"
argument_list|)
expr_stmt|;
block|}
block|}
if|if
condition|(
name|post
condition|)
block|{
name|OutputStream
name|outputStream
init|=
literal|null
decl_stmt|;
try|try
block|{
name|outputStream
operator|=
name|connection
operator|.
name|getOutputStream
argument_list|()
expr_stmt|;
comment|// implicitly connects?
if|if
condition|(
name|dataToSend
operator|!=
literal|null
condition|)
block|{
name|outputStream
operator|.
name|write
argument_list|(
name|dataToSend
argument_list|)
expr_stmt|;
name|outputStream
operator|.
name|flush
argument_list|()
expr_stmt|;
block|}
name|outputStream
operator|.
name|close
argument_list|()
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|IOException
name|e
parameter_list|)
block|{
name|errorFlag
operator|=
literal|true
expr_stmt|;
name|LOG
operator|.
name|log
argument_list|(
name|Level
operator|.
name|SEVERE
argument_list|,
literal|"send output error."
argument_list|,
name|e
argument_list|)
expr_stmt|;
name|throwError
argument_list|(
literal|"NETWORK_ERR"
argument_list|)
expr_stmt|;
try|try
block|{
name|outputStream
operator|.
name|close
argument_list|()
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|IOException
name|e1
parameter_list|)
block|{
comment|//
block|}
block|}
block|}
comment|// 6
name|notifyReadyStateChangeListener
argument_list|()
expr_stmt|;
if|if
condition|(
name|storedAsync
condition|)
block|{
operator|new
name|Thread
argument_list|()
block|{
specifier|public
name|void
name|run
parameter_list|()
block|{
try|try
block|{
name|Context
name|cx
init|=
name|ContextFactory
operator|.
name|getGlobal
argument_list|()
operator|.
name|enterContext
argument_list|()
decl_stmt|;
name|communicate
argument_list|(
name|cx
argument_list|)
expr_stmt|;
block|}
finally|finally
block|{
name|Context
operator|.
name|exit
argument_list|()
expr_stmt|;
block|}
block|}
block|}
operator|.
name|start
argument_list|()
expr_stmt|;
block|}
else|else
block|{
name|communicate
argument_list|(
name|Context
operator|.
name|getCurrentContext
argument_list|()
argument_list|)
expr_stmt|;
block|}
block|}
specifier|private
name|void
name|communicate
parameter_list|(
name|Context
name|cx
parameter_list|)
block|{
try|try
block|{
name|InputStream
name|is
init|=
name|connection
operator|.
name|getInputStream
argument_list|()
decl_stmt|;
name|httpResponseCode
operator|=
operator|-
literal|1
expr_stmt|;
comment|// this waits, I hope, for a response.
name|responseHeaders
operator|=
name|connection
operator|.
name|getHeaderFields
argument_list|()
expr_stmt|;
name|readyState
operator|=
name|jsGet_HEADERS_RECEIVED
argument_list|()
expr_stmt|;
name|notifyReadyStateChangeListener
argument_list|()
expr_stmt|;
if|if
condition|(
name|httpConnection
operator|!=
literal|null
condition|)
block|{
name|httpResponseCode
operator|=
name|httpConnection
operator|.
name|getResponseCode
argument_list|()
expr_stmt|;
name|httpResponseText
operator|=
name|httpConnection
operator|.
name|getResponseMessage
argument_list|()
expr_stmt|;
block|}
name|ByteArrayOutputStream
name|baos
init|=
operator|new
name|ByteArrayOutputStream
argument_list|()
decl_stmt|;
name|byte
index|[]
name|buffer
init|=
operator|new
name|byte
index|[
literal|1024
index|]
decl_stmt|;
name|int
name|read
decl_stmt|;
name|boolean
name|notified
init|=
literal|false
decl_stmt|;
while|while
condition|(
operator|(
name|read
operator|=
name|is
operator|.
name|read
argument_list|(
name|buffer
argument_list|)
operator|)
operator|!=
operator|-
literal|1
condition|)
block|{
if|if
condition|(
operator|!
name|notified
condition|)
block|{
name|readyState
operator|=
name|jsGet_LOADING
argument_list|()
expr_stmt|;
name|notifyReadyStateChangeListener
argument_list|()
expr_stmt|;
block|}
name|baos
operator|.
name|write
argument_list|(
name|buffer
argument_list|,
literal|0
argument_list|,
name|read
argument_list|)
expr_stmt|;
block|}
name|is
operator|.
name|close
argument_list|()
expr_stmt|;
comment|// For a one-way message or whatever, there may not be a content type.
comment|// throw away any encoding modifier.
name|String
name|contentType
init|=
literal|""
decl_stmt|;
name|String
name|connectionContentType
init|=
name|connection
operator|.
name|getContentType
argument_list|()
decl_stmt|;
name|String
name|contentEncoding
init|=
literal|null
decl_stmt|;
if|if
condition|(
name|connectionContentType
operator|!=
literal|null
condition|)
block|{
name|contentEncoding
operator|=
name|HttpHeaderHelper
operator|.
name|mapCharset
argument_list|(
name|HttpHeaderHelper
operator|.
name|findCharset
argument_list|(
name|connectionContentType
argument_list|)
argument_list|)
expr_stmt|;
name|contentType
operator|=
name|connectionContentType
operator|.
name|split
argument_list|(
literal|";"
argument_list|)
index|[
literal|0
index|]
expr_stmt|;
block|}
if|if
condition|(
name|contentEncoding
operator|==
literal|null
operator|||
name|contentEncoding
operator|.
name|length
argument_list|()
operator|==
literal|0
condition|)
block|{
name|contentEncoding
operator|=
literal|"iso-8859-1"
expr_stmt|;
block|}
name|byte
index|[]
name|responseBytes
init|=
name|baos
operator|.
name|toByteArray
argument_list|()
decl_stmt|;
comment|/* We need all the text in a string, independent of the * XML parse. */
name|Charset
name|contentCharset
init|=
name|Charset
operator|.
name|forName
argument_list|(
name|contentEncoding
argument_list|)
decl_stmt|;
name|byte
index|[]
name|contentBytes
init|=
name|baos
operator|.
name|toByteArray
argument_list|()
decl_stmt|;
name|CharBuffer
name|contentChars
init|=
name|contentCharset
operator|.
name|decode
argument_list|(
name|ByteBuffer
operator|.
name|wrap
argument_list|(
name|contentBytes
argument_list|)
argument_list|)
decl_stmt|;
comment|// not the most efficient way.
name|responseText
operator|=
name|contentChars
operator|.
name|toString
argument_list|()
expr_stmt|;
name|LOG
operator|.
name|fine
argument_list|(
name|responseText
argument_list|)
expr_stmt|;
if|if
condition|(
name|responseBytes
operator|.
name|length
operator|>
literal|0
operator|&&
operator|(
literal|"text/xml"
operator|.
name|equals
argument_list|(
name|contentType
argument_list|)
operator|||
literal|"application/xml"
operator|.
name|equals
argument_list|(
name|contentType
argument_list|)
operator|||
name|contentType
operator|.
name|endsWith
argument_list|(
literal|"+xml"
argument_list|)
operator|)
condition|)
block|{
try|try
block|{
name|DocumentBuilderFactory
name|documentBuilderFactory
init|=
name|DocumentBuilderFactory
operator|.
name|newInstance
argument_list|()
decl_stmt|;
name|documentBuilderFactory
operator|.
name|setNamespaceAware
argument_list|(
literal|true
argument_list|)
expr_stmt|;
name|DocumentBuilder
name|builder
init|=
name|documentBuilderFactory
operator|.
name|newDocumentBuilder
argument_list|()
decl_stmt|;
name|ByteArrayInputStream
name|bais
init|=
operator|new
name|ByteArrayInputStream
argument_list|(
name|responseBytes
argument_list|)
decl_stmt|;
name|InputSource
name|inputSource
init|=
operator|new
name|InputSource
argument_list|(
name|bais
argument_list|)
decl_stmt|;
name|inputSource
operator|.
name|setEncoding
argument_list|(
name|contentEncoding
argument_list|)
expr_stmt|;
name|Document
name|xmlDoc
init|=
name|builder
operator|.
name|parse
argument_list|(
name|inputSource
argument_list|)
decl_stmt|;
name|responseXml
operator|=
name|JsSimpleDomNode
operator|.
name|wrapNode
argument_list|(
name|getParentScope
argument_list|()
argument_list|,
name|xmlDoc
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|ParserConfigurationException
name|e
parameter_list|)
block|{
name|LOG
operator|.
name|log
argument_list|(
name|Level
operator|.
name|SEVERE
argument_list|,
literal|"ParserConfigurationError"
argument_list|,
name|e
argument_list|)
expr_stmt|;
name|responseXml
operator|=
literal|null
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|SAXException
name|e
parameter_list|)
block|{
name|LOG
operator|.
name|log
argument_list|(
name|Level
operator|.
name|SEVERE
argument_list|,
literal|"Error parsing XML response"
argument_list|,
name|e
argument_list|)
expr_stmt|;
name|responseXml
operator|=
literal|null
expr_stmt|;
block|}
block|}
name|readyState
operator|=
name|jsGet_DONE
argument_list|()
expr_stmt|;
name|notifyReadyStateChangeListener
argument_list|()
expr_stmt|;
if|if
condition|(
name|httpConnection
operator|!=
literal|null
condition|)
block|{
name|httpConnection
operator|.
name|disconnect
argument_list|()
expr_stmt|;
block|}
block|}
catch|catch
parameter_list|(
name|IOException
name|ioException
parameter_list|)
block|{
name|errorFlag
operator|=
literal|true
expr_stmt|;
name|readyState
operator|=
name|jsGet_DONE
argument_list|()
expr_stmt|;
if|if
condition|(
operator|!
name|storedAsync
condition|)
block|{
name|LOG
operator|.
name|log
argument_list|(
name|Level
operator|.
name|SEVERE
argument_list|,
literal|"IO error reading response"
argument_list|,
name|ioException
argument_list|)
expr_stmt|;
name|throwError
argument_list|(
literal|"NETWORK_ERR"
argument_list|)
expr_stmt|;
name|notifyReadyStateChangeListener
argument_list|()
expr_stmt|;
block|}
block|}
block|}
specifier|private
name|void
name|throwError
parameter_list|(
name|String
name|errorName
parameter_list|)
block|{
name|LOG
operator|.
name|info
argument_list|(
literal|"Javascript throw: "
operator|+
name|errorName
argument_list|)
expr_stmt|;
throw|throw
operator|new
name|JavaScriptException
argument_list|(
name|Context
operator|.
name|javaToJS
argument_list|(
name|errorName
argument_list|,
name|getParentScope
argument_list|()
argument_list|)
argument_list|,
literal|"XMLHttpRequest"
argument_list|,
literal|0
argument_list|)
throw|;
block|}
specifier|private
name|byte
index|[]
name|utf8Bytes
parameter_list|(
name|String
name|data
parameter_list|)
block|{
name|ByteBuffer
name|bb
init|=
name|UTF_8
operator|.
name|encode
argument_list|(
name|data
argument_list|)
decl_stmt|;
name|byte
index|[]
name|val
init|=
operator|new
name|byte
index|[
name|bb
operator|.
name|limit
argument_list|()
index|]
decl_stmt|;
name|bb
operator|.
name|get
argument_list|(
name|val
argument_list|)
expr_stmt|;
return|return
name|val
return|;
block|}
specifier|private
name|byte
index|[]
name|domToUtf8
parameter_list|(
name|JsSimpleDomNode
name|xml
parameter_list|)
block|{
name|Node
name|node
init|=
name|xml
operator|.
name|getWrappedNode
argument_list|()
decl_stmt|;
comment|// entire document.
comment|// if that's an issue, we could code something more complex.
name|ByteArrayOutputStream
name|baos
init|=
operator|new
name|ByteArrayOutputStream
argument_list|()
decl_stmt|;
name|StreamResult
name|result
init|=
operator|new
name|StreamResult
argument_list|(
name|baos
argument_list|)
decl_stmt|;
name|DOMSource
name|source
init|=
operator|new
name|DOMSource
argument_list|(
name|node
argument_list|)
decl_stmt|;
try|try
block|{
name|TransformerFactory
name|transformerFactory
init|=
name|TransformerFactory
operator|.
name|newInstance
argument_list|()
decl_stmt|;
name|transformerFactory
operator|.
name|setFeature
argument_list|(
name|javax
operator|.
name|xml
operator|.
name|XMLConstants
operator|.
name|FEATURE_SECURE_PROCESSING
argument_list|,
literal|true
argument_list|)
expr_stmt|;
name|transformerFactory
operator|.
name|newTransformer
argument_list|()
operator|.
name|transform
argument_list|(
name|source
argument_list|,
name|result
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|TransformerException
decl||
name|TransformerFactoryConfigurationError
name|e
parameter_list|)
block|{
throw|throw
operator|new
name|RuntimeException
argument_list|(
name|e
argument_list|)
throw|;
block|}
return|return
name|baos
operator|.
name|toByteArray
argument_list|()
return|;
block|}
specifier|public
name|void
name|doAbort
parameter_list|()
block|{
comment|// this is messy.
block|}
specifier|public
name|String
name|doGetAllResponseHeaders
parameter_list|()
block|{
comment|// 1 check state.
if|if
condition|(
name|readyState
operator|==
name|jsGet_UNSENT
argument_list|()
operator|||
name|readyState
operator|==
name|jsGet_OPENED
argument_list|()
condition|)
block|{
name|LOG
operator|.
name|severe
argument_list|(
literal|"Invalid state"
argument_list|)
expr_stmt|;
name|throwError
argument_list|(
literal|"INVALID_STATE_ERR"
argument_list|)
expr_stmt|;
block|}
comment|// 2 check error flag
if|if
condition|(
name|errorFlag
condition|)
block|{
name|LOG
operator|.
name|severe
argument_list|(
literal|"error flag set"
argument_list|)
expr_stmt|;
return|return
literal|null
return|;
block|}
comment|// 3 pile up the headers.
name|StringBuilder
name|builder
init|=
operator|new
name|StringBuilder
argument_list|()
decl_stmt|;
for|for
control|(
name|Map
operator|.
name|Entry
argument_list|<
name|String
argument_list|,
name|List
argument_list|<
name|String
argument_list|>
argument_list|>
name|headersEntry
range|:
name|responseHeaders
operator|.
name|entrySet
argument_list|()
control|)
block|{
if|if
condition|(
name|headersEntry
operator|.
name|getKey
argument_list|()
operator|==
literal|null
condition|)
block|{
comment|// why does the HTTP connection return a null key with the response code and text?
continue|continue;
block|}
name|builder
operator|.
name|append
argument_list|(
name|headersEntry
operator|.
name|getKey
argument_list|()
argument_list|)
expr_stmt|;
name|builder
operator|.
name|append
argument_list|(
literal|": "
argument_list|)
expr_stmt|;
for|for
control|(
name|String
name|value
range|:
name|headersEntry
operator|.
name|getValue
argument_list|()
control|)
block|{
name|builder
operator|.
name|append
argument_list|(
name|value
argument_list|)
expr_stmt|;
name|builder
operator|.
name|append
argument_list|(
literal|", "
argument_list|)
expr_stmt|;
block|}
name|builder
operator|.
name|setLength
argument_list|(
name|builder
operator|.
name|length
argument_list|()
operator|-
literal|2
argument_list|)
expr_stmt|;
comment|// trim extra comma/space
name|builder
operator|.
name|append
argument_list|(
literal|"\r\n"
argument_list|)
expr_stmt|;
block|}
return|return
name|builder
operator|.
name|toString
argument_list|()
return|;
block|}
specifier|public
name|String
name|doGetResponseHeader
parameter_list|(
name|String
name|header
parameter_list|)
block|{
comment|// 1 check state.
if|if
condition|(
name|readyState
operator|==
name|jsGet_UNSENT
argument_list|()
operator|||
name|readyState
operator|==
name|jsGet_OPENED
argument_list|()
condition|)
block|{
name|LOG
operator|.
name|severe
argument_list|(
literal|"invalid state"
argument_list|)
expr_stmt|;
name|throwError
argument_list|(
literal|"INVALID_STATE_ERR"
argument_list|)
expr_stmt|;
block|}
comment|// 2 check header format, we don't do it.
comment|// 3 check error flag
if|if
condition|(
name|errorFlag
condition|)
block|{
name|LOG
operator|.
name|severe
argument_list|(
literal|"error flag"
argument_list|)
expr_stmt|;
return|return
literal|null
return|;
block|}
comment|//4 -- oh, it's CASE-INSENSITIVE. Well, we do it the hard way.
for|for
control|(
name|Map
operator|.
name|Entry
argument_list|<
name|String
argument_list|,
name|List
argument_list|<
name|String
argument_list|>
argument_list|>
name|headersEntry
range|:
name|responseHeaders
operator|.
name|entrySet
argument_list|()
control|)
block|{
if|if
condition|(
name|header
operator|.
name|equalsIgnoreCase
argument_list|(
name|headersEntry
operator|.
name|getKey
argument_list|()
argument_list|)
condition|)
block|{
name|StringBuilder
name|builder
init|=
operator|new
name|StringBuilder
argument_list|()
decl_stmt|;
for|for
control|(
name|String
name|value
range|:
name|headersEntry
operator|.
name|getValue
argument_list|()
control|)
block|{
name|builder
operator|.
name|append
argument_list|(
name|value
argument_list|)
expr_stmt|;
name|builder
operator|.
name|append
argument_list|(
literal|", "
argument_list|)
expr_stmt|;
block|}
name|builder
operator|.
name|setLength
argument_list|(
name|builder
operator|.
name|length
argument_list|()
operator|-
literal|2
argument_list|)
expr_stmt|;
comment|// trim extra comma/space
return|return
name|builder
operator|.
name|toString
argument_list|()
return|;
block|}
block|}
return|return
literal|null
return|;
block|}
specifier|public
name|String
name|doGetResponseText
parameter_list|()
block|{
comment|// 1 check state.
if|if
condition|(
name|readyState
operator|==
name|jsGet_UNSENT
argument_list|()
operator|||
name|readyState
operator|==
name|jsGet_OPENED
argument_list|()
condition|)
block|{
name|LOG
operator|.
name|severe
argument_list|(
literal|"invalid state "
operator|+
name|readyState
argument_list|)
expr_stmt|;
name|throwError
argument_list|(
literal|"INVALID_STATE_ERR"
argument_list|)
expr_stmt|;
block|}
comment|// 2 return what we have.
return|return
name|responseText
return|;
block|}
specifier|public
name|Object
name|doGetResponseXML
parameter_list|()
block|{
comment|// 1 check state.
if|if
condition|(
name|readyState
operator|==
name|jsGet_UNSENT
argument_list|()
operator|||
name|readyState
operator|==
name|jsGet_OPENED
argument_list|()
condition|)
block|{
name|LOG
operator|.
name|severe
argument_list|(
literal|"invalid state"
argument_list|)
expr_stmt|;
name|throwError
argument_list|(
literal|"INVALID_STATE_ERR"
argument_list|)
expr_stmt|;
block|}
return|return
name|responseXml
return|;
block|}
specifier|public
name|int
name|doGetStatus
parameter_list|()
block|{
if|if
condition|(
name|httpResponseCode
operator|==
operator|-
literal|1
condition|)
block|{
name|LOG
operator|.
name|severe
argument_list|(
literal|"invalid state"
argument_list|)
expr_stmt|;
name|throwError
argument_list|(
literal|"INVALID_STATE_ERR"
argument_list|)
expr_stmt|;
block|}
return|return
name|httpResponseCode
return|;
block|}
specifier|public
name|String
name|doGetStatusText
parameter_list|()
block|{
if|if
condition|(
name|httpResponseText
operator|==
literal|null
condition|)
block|{
name|LOG
operator|.
name|severe
argument_list|(
literal|"invalid state"
argument_list|)
expr_stmt|;
name|throwError
argument_list|(
literal|"INVALID_STATE_ERR"
argument_list|)
expr_stmt|;
block|}
return|return
name|httpResponseText
return|;
block|}
comment|// CHECKSTYLE:OFF
specifier|public
name|Object
name|jsGet_onreadystatechange
parameter_list|()
block|{
return|return
name|readyStateChangeListener
return|;
block|}
specifier|public
name|void
name|jsSet_onreadystatechange
parameter_list|(
name|Object
name|listener
parameter_list|)
block|{
name|readyStateChangeListener
operator|=
name|listener
expr_stmt|;
block|}
specifier|public
name|int
name|jsGet_UNSENT
parameter_list|()
block|{
return|return
literal|0
return|;
block|}
specifier|public
name|int
name|jsGet_OPENED
parameter_list|()
block|{
return|return
literal|1
return|;
block|}
specifier|public
name|int
name|jsGet_HEADERS_RECEIVED
parameter_list|()
block|{
return|return
literal|2
return|;
block|}
specifier|public
name|int
name|jsGet_LOADING
parameter_list|()
block|{
return|return
literal|3
return|;
block|}
specifier|public
name|int
name|jsGet_DONE
parameter_list|()
block|{
return|return
literal|4
return|;
block|}
specifier|public
name|int
name|jsGet_readyState
parameter_list|()
block|{
return|return
name|readyState
return|;
block|}
specifier|public
name|void
name|jsFunction_open
parameter_list|(
name|String
name|method
parameter_list|,
name|String
name|url
parameter_list|,
name|Object
name|asyncObj
parameter_list|,
name|Object
name|user
parameter_list|,
name|Object
name|password
parameter_list|)
block|{
name|Boolean
name|async
decl_stmt|;
if|if
condition|(
name|asyncObj
operator|==
name|Context
operator|.
name|getUndefinedValue
argument_list|()
condition|)
block|{
name|async
operator|=
name|Boolean
operator|.
name|TRUE
expr_stmt|;
block|}
else|else
block|{
name|async
operator|=
operator|(
name|Boolean
operator|)
name|Context
operator|.
name|jsToJava
argument_list|(
name|asyncObj
argument_list|,
name|Boolean
operator|.
name|class
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|user
operator|==
name|Context
operator|.
name|getUndefinedValue
argument_list|()
condition|)
block|{
name|user
operator|=
literal|null
expr_stmt|;
block|}
else|else
block|{
name|user
operator|=
name|Context
operator|.
name|jsToJava
argument_list|(
name|user
argument_list|,
name|String
operator|.
name|class
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|password
operator|==
name|Context
operator|.
name|getUndefinedValue
argument_list|()
condition|)
block|{
name|password
operator|=
literal|null
expr_stmt|;
block|}
else|else
block|{
name|password
operator|=
name|Context
operator|.
name|jsToJava
argument_list|(
name|password
argument_list|,
name|String
operator|.
name|class
argument_list|)
expr_stmt|;
block|}
name|doOpen
argument_list|(
name|method
argument_list|,
name|url
argument_list|,
name|async
argument_list|,
operator|(
name|String
operator|)
name|user
argument_list|,
operator|(
name|String
operator|)
name|password
argument_list|)
expr_stmt|;
block|}
specifier|public
name|void
name|jsFunction_setRequestHeader
parameter_list|(
name|String
name|header
parameter_list|,
name|String
name|value
parameter_list|)
block|{
name|doSetRequestHeader
argument_list|(
name|header
argument_list|,
name|value
argument_list|)
expr_stmt|;
block|}
specifier|public
name|void
name|jsFunction_send
parameter_list|(
name|Object
name|arg
parameter_list|)
block|{
if|if
condition|(
name|arg
operator|==
name|Context
operator|.
name|getUndefinedValue
argument_list|()
condition|)
block|{
name|doSend
argument_list|(
literal|null
argument_list|,
literal|false
argument_list|)
expr_stmt|;
block|}
elseif|else
if|if
condition|(
name|arg
operator|instanceof
name|String
condition|)
block|{
name|doSend
argument_list|(
name|utf8Bytes
argument_list|(
operator|(
name|String
operator|)
name|arg
argument_list|)
argument_list|,
literal|false
argument_list|)
expr_stmt|;
block|}
elseif|else
if|if
condition|(
name|arg
operator|instanceof
name|JsSimpleDomNode
condition|)
block|{
name|doSend
argument_list|(
name|domToUtf8
argument_list|(
operator|(
name|JsSimpleDomNode
operator|)
name|arg
argument_list|)
argument_list|,
literal|true
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|throwError
argument_list|(
literal|"INVALID_ARG_TO_SEND"
argument_list|)
expr_stmt|;
block|}
block|}
specifier|public
name|void
name|jsFunction_abort
parameter_list|()
block|{
name|doAbort
argument_list|()
expr_stmt|;
block|}
specifier|public
name|String
name|jsFunction_getAllResponseHeaders
parameter_list|()
block|{
return|return
name|doGetAllResponseHeaders
argument_list|()
return|;
block|}
specifier|public
name|String
name|jsFunction_getResponseHeader
parameter_list|(
name|String
name|header
parameter_list|)
block|{
return|return
name|doGetResponseHeader
argument_list|(
name|header
argument_list|)
return|;
block|}
specifier|public
name|String
name|jsGet_responseText
parameter_list|()
block|{
return|return
name|doGetResponseText
argument_list|()
return|;
block|}
specifier|public
name|Object
name|jsGet_responseXML
parameter_list|()
block|{
return|return
name|doGetResponseXML
argument_list|()
return|;
block|}
specifier|public
name|int
name|jsGet_status
parameter_list|()
block|{
return|return
name|doGetStatus
argument_list|()
return|;
block|}
specifier|public
name|String
name|jsGet_statusText
parameter_list|()
block|{
return|return
name|doGetStatusText
argument_list|()
return|;
block|}
block|}
end_class
end_unit
| 14.087703 | 810 | 0.792953 |
f6f9f500d846d714b9141ee689a384db55e52110 | 699 | package com.qdw.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author qdw
* @since 2020-05-30
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("m_type")
public class Type implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String name;
// 对应blog的数量
private Integer c;
}
| 19.416667 | 53 | 0.731044 |
1197b575ceef6b8a7598ac8c910264b1f12e9c72 | 11,303 | package org.narrative.network.core.content.base;
import org.narrative.common.persistence.OID;
import org.narrative.common.persistence.OIDGenerator;
import org.narrative.common.persistence.ObjectPair;
import org.narrative.common.util.IPIOUtil;
import org.narrative.common.util.UnexpectedError;
import org.narrative.common.util.posting.HtmlTextMassager;
import org.narrative.network.core.composition.files.FilePointer;
import org.narrative.network.core.fileondisk.base.AggregateFileType;
import org.narrative.network.core.fileondisk.base.FileBase;
import org.narrative.network.core.fileondisk.base.FileMetaData;
import org.narrative.network.core.fileondisk.base.FileOnDisk;
import org.narrative.network.core.fileondisk.base.FileType;
import org.narrative.network.core.fileondisk.base.FileUsageType;
import org.narrative.network.shared.util.NetworkCoreUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;
import static org.narrative.common.util.CoreUtils.*;
/**
* Created by IntelliJ IDEA.
* User: barry
* Date: Feb 2, 2006
* Time: 11:43:20 AM
*/
public class UploadedFileData<T extends FileMetaData> implements FileData<T> {
private File tempFile;
private int byteSize;
protected String mimeType;
private final String filename;
private String title;
private String description;
private int order;
private boolean include;
private T fileMetaData;
private final OID fileUploadProcessOid;
private FileUsageType fileUsageType;
private OID fileOnDiskOid;
protected final OID uniqueOid;
protected String errorMessage;
private FilePointer filePointer;
private Set<File> oldTempFiles = new HashSet<File>();
private boolean isValid;
private boolean isProperType = true;
private UploadedFileStatus status = UploadedFileStatus.PROCESSING;
public UploadedFileData(OID fileUploadProcessOid, FileUsageType fileUsageType, File file, String mimeType, String filename) {
this(fileUploadProcessOid, fileUsageType, file, mimeType, filename, null);
}
protected UploadedFileData(OID fileUploadProcessOid, FileUsageType fileUsageType, File file, String mimeType, String filename, OID uniqueOid) {
setTempFile(file);
this.mimeType = mimeType;
Integer intVal;
try {
intVal = Integer.parseInt(filename);
} catch (NumberFormatException nfe) {
intVal = null;
}
if (intVal == null) {
this.filename = filename;
} else {
this.filename = getFileType().name().toLowerCase() + intVal + "." + getFileType().getDefaultExtension();
}
this.fileUploadProcessOid = fileUploadProcessOid;
this.fileUsageType = fileUsageType;
this.include = true;
this.title = getFileType().isRegularFile() ? filename : FileOnDisk.getDefaultTitleFromFilename(filename);
// set the file meta data to null explicitly. this will ensure isValid is set accordingly.
setFileMetaData(null);
this.uniqueOid = uniqueOid != null ? uniqueOid : OIDGenerator.getNextOID();
}
public static UploadedFileData getNewUploadedFileData(OID fileUploadProcessOid, FileUsageType fileUsageType, File file, String mimeType, String filename) {
// bl: don't filter by allowed type here. instead, rely on the caller to do security to make sure that the
// user can upload a file of this type. this way, if you can upload regular files, but not images, we won't
// treat uploaded images as regular files (which was just weird).
AggregateFileType aggregateFileType = fileUsageType.getAllowedUploadFileType();
// jw: if we are only allowing a single explicit file type then just return the data for that.
if (aggregateFileType.isSingleFileType() && !aggregateFileType.getLoneFileType().isRegularFile()) {
return aggregateFileType.getLoneFileType().getNewInstance(fileUploadProcessOid, fileUsageType, file, mimeType, filename);
}
// jw: lets process all file types here and assume that the consuming code will handle if the type does not match.
for (FileType fileType : FileType.ALL_FILE_TYPES_ORDERED) {
UploadedFileData ret = fileType.getNewInstance(fileUploadProcessOid, fileUsageType, file, mimeType, filename);
// jw: if the file data is valid, or the fileType is regular then return it. Regular is always last so this
// should ensure that we are always providing file data from this method.
if (ret.isValid() || fileType.isRegularFile()) {
return ret;
}
}
throw UnexpectedError.getRuntimeException("Should have returned REGULAR file data above!");
}
public final void postUploadProcess(OID fileUploadProcessOid) {
if (status == null || status == UploadedFileStatus.PROCESSING) {
try {
postUploadSubProcess(fileUploadProcessOid);
status = UploadedFileStatus.SUCCESS;
} catch (Throwable t) {
status = UploadedFileStatus.ERROR;
throw UnexpectedError.getRuntimeException("Failed processing file/" + getTempFile().getAbsolutePath(), t);
}
}
}
public UploadedFileStatus getStatus() {
return status;
}
protected void postUploadSubProcess(OID fileUploadProcessOid) {
File outFile = NetworkCoreUtils.createTempFile(getTempFilenameForFileUploadProcessOid(fileUploadProcessOid), getTempFileExtension(), true);
try {
if (!IPIOUtil.doCopyFile(getTempFile(), outFile, false)) {
throw UnexpectedError.getRuntimeException("Failed copying uploaded tempFile to temp directory! file/" + getTempFile().getAbsolutePath() + " outFile/" + outFile.getAbsolutePath(), true);
}
} catch (IOException ioe) {
throw UnexpectedError.getRuntimeException("Failed copying uploaded tempFile to temp directory! file/" + getTempFile().getAbsolutePath() + " outFile/" + outFile.getAbsolutePath(), ioe, true);
}
setTempFile(outFile);
}
protected String getTempFileExtension() {
return "tmp";
}
@Override
public void scrub() {
title = HtmlTextMassager.sanitizePlainTextString(title, false);
description = HtmlTextMassager.sanitizePlainTextString(description, false);
}
public boolean isNew() {
// uploaded files are always considered new
return true;
}
public boolean isCharsChanged() {
// uploaded files can't have any chars changed
return false;
}
public boolean isValid() {
return isValid;
}
protected void markInvalid() {
this.isValid = false;
}
public final void deleteAllTempFiles() {
deleteAllTempFilesSub();
FileDataUtil.safeDeleteFile(tempFile);
FileDataUtil.safeDeleteFileIterator(oldTempFiles.iterator());
}
protected void deleteAllTempFilesSub() {
}
public File getTempFile() {
return tempFile;
}
protected void setTempFile(File tempFile) {
if (this.tempFile != null && this.tempFile.exists()) {
oldTempFiles.add(this.tempFile);
}
this.tempFile = tempFile;
this.byteSize = (int) tempFile.length();
}
public String getErrorMessage() {
return errorMessage;
}
protected void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public String getFilename() {
return filename;
}
public String getFilenameAsJpg() {
return FileBase.getFilenameAsJpg(filename);
}
public String getMimeType() {
return mimeType;
}
public int getByteSize() {
return byteSize;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getOrder() {
return order;
}
public void setOrder(int threadingOrder) {
this.order = threadingOrder;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isInclude() {
return include;
}
public void setInclude(boolean include) {
this.include = include;
}
public FileType getFileType() {
return FileType.REGULAR;
}
public T getFileMetaData() {
return fileMetaData;
}
protected void setFileMetaData(T fileMetaData) {
this.fileMetaData = fileMetaData;
Class<? extends FileMetaData> fileMetaDataClass = getFileType().getFileMetaDataClass();
// if there isn't a specialized file meta data class, then assume the file is valid.
// if there is a specialized file meta data class, then the file data is only valid
// if the meta data was non-null.
isValid = fileMetaDataClass == null || fileMetaData != null;
}
@Override
public FileUsageType getFileUsageType() {
return fileUsageType;
}
public void setFileUsageType(FileUsageType fileUsageType) {
this.fileUsageType = fileUsageType;
}
public FilePointer getFilePointer() {
return filePointer;
}
public void doSetFilePointer(FilePointer filePointer) {
this.filePointer = filePointer;
}
public OID getFileOnDiskOid() {
return fileOnDiskOid;
}
public void setFileOnDiskOid(OID fileOnDiskOid) {
this.fileOnDiskOid = fileOnDiskOid;
}
public FileOnDisk getFileOnDisk() {
return FileOnDisk.dao().get(fileOnDiskOid);
}
public OID getUniqueOid() {
return uniqueOid;
}
public String getTempFilenameForFileUploadProcessOid(OID fileUploadProcessOid) {
return getTempFilenameForFileUploadProcessOid(fileUploadProcessOid, uniqueOid);
}
public static String getTempFilenameForFileUploadProcessOid(OID fileUploadProcessOid, OID uniqueFileOid) {
return newString(fileUploadProcessOid, "_", uniqueFileOid);
}
public ObjectPair<InputStream, Integer> getFileInputStreamAndByteSize() {
try {
return new ObjectPair<InputStream, Integer>(new FileInputStream(getTempFile()), (int) getTempFile().length());
} catch (FileNotFoundException fnfe) {
throw UnexpectedError.getRuntimeException("Failed lookup of uploaded file! file/" + getTempFile().getAbsolutePath(), fnfe, true);
}
}
public boolean isProperType() {
return isProperType;
}
public void setProperType(boolean properType) {
isProperType = properType;
}
public boolean isExistingFile() {
return false;
}
public final OID getFileUploadProcessOid() {
return fileUploadProcessOid;
}
public boolean isTooBig() {
return tempFile.length() > getFileUsageType().getMaxFileSize(getFileType());
}
public static enum UploadedFileStatus {
PROCESSING,
SUCCESS,
ERROR;
}
}
| 33.740299 | 202 | 0.6815 |
80c5fdbea50eede4d6b74604a4ad2cfde6ad703b | 9,375 | /*
* Copyright (C) 2016 Ordnance Survey
*
* 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 uk.os.vt.filesystem;
import com.google.common.primitives.Ints;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.reactivex.Observable;
import io.reactivex.Single;
import io.reactivex.disposables.Disposable;
import io.reactivex.exceptions.Exceptions;
import io.reactivex.functions.BiFunction;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.AbstractFileFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.os.vt.Entry;
import uk.os.vt.Metadata;
import uk.os.vt.MetadataProvider;
import uk.os.vt.Storage;
import uk.os.vt.StorageResult;
public final class StorageImpl implements Storage, MetadataProvider {
private static final int[] UNDEFINED_ZXY = new int[]{};
private final File directory;
private final boolean gzipEnabled;
private static final Logger LOG = LoggerFactory.getLogger(StorageImpl.class);
@Override
public Single<Metadata> generateDefault() {
final int[] zMinMax = getMaxMin(tileFilenames(directory));
return FilesystemUtil
.getTiles(new File(directory, String.valueOf(zMinMax[1])).getAbsolutePath(), 2)
.map(FilesystemUtil::toZxy).reduce(UNDEFINED_ZXY, new BiFunction<int[], int[], int[]>() {
@Override
public int[] apply(int[] aa, int[] bb) throws Exception {
return aa == UNDEFINED_ZXY ? (bb == UNDEFINED_ZXY ? UNDEFINED_ZXY : bb)
: new int[] {Math.max(aa[0], bb[0]), Math.max(aa[1], bb[1]),
Math.max(aa[2], bb[2])};
}
}).map(zxy -> {
if (zxy == UNDEFINED_ZXY) {
return new Metadata.Builder().build();
}
// TODO should be able to translate tile coordinates to
// bounds shortly!
return new Metadata.Builder().setMinZoom(zMinMax[0]).setMaxZoom(zMinMax[1]).build();
}).toObservable().singleOrError();
}
@Override
public Disposable putMetadata(Single<Metadata> metadata) {
return metadata.subscribe(m -> {
final File file = new File(directory, "config.json");
try {
FileUtils.writeStringToFile(file, m.getTileJson().toString(), "UTF-8");
} catch (final IOException ex) {
LOG.error("problem writing metadata", ex);
}
});
}
private StorageImpl(File directory, boolean gzipEnabled) {
this.directory = directory;
this.gzipEnabled = gzipEnabled;
}
@Override
public void close() throws Exception {
// no resources to free
}
@Override
public Observable<Entry> getEntries() {
return getEntries(directory);
}
private static Observable<Entry> getEntries(File directory) {
return FilesystemUtil.getTiles(directory.getPath()).map(file -> {
try {
return FilesystemUtil.toEntry(file);
} catch (final IOException ex) {
throw Exceptions.propagate(ex);
}
});
}
@Override
public Observable<Entry> getEntries(int zoom) {
return FilesystemUtil.getTiles(directory.getPath() + File.separator + zoom, 2).map(file -> {
try {
return FilesystemUtil.toEntry(file);
} catch (final IOException ex) {
throw Exceptions.propagate(ex);
}
});
}
@Override
public Observable<Entry> getEntry(int zoom, int col, int row) {
return FilesystemUtil.getTiles(
directory.getPath() + File.separator + zoom + File.separator + col + File.separator + row,
4).map(file -> {
try {
return FilesystemUtil.toEntry(file);
} catch (final IOException ex) {
throw Exceptions.propagate(ex);
}
});
}
@Override
public Observable<Integer> getMaxZoomLevel() {
return Observable.defer(() -> {
final int[] zoomLevels = getZoomLevels();
return zoomLevels.length > 0 ? Observable.just(zoomLevels[zoomLevels.length - 1])
: Observable.empty();
});
}
@Override
public Observable<Integer> getMinZoomLevel() {
return Observable.defer(() -> {
final int[] zoomLevels = getZoomLevels();
return zoomLevels.length > 0 ? Observable.just(zoomLevels[0]) : Observable.empty();
});
}
@Override
@SuppressFBWarnings("RV_RETURN_VALUE_IGNORED")
public void putEntries(Observable<Entry> entries) {
entries.subscribe(entry -> {
try {
FilesystemUtil.addEntry(directory, entry, gzipEnabled);
} catch (final IOException ex) {
throw Exceptions.propagate(ex);
}
});
}
@Override
public Observable<StorageResult> put(Observable<Entry> entries) {
return entries.map(entry -> {
try {
FilesystemUtil.addEntry(directory, entry, gzipEnabled);
return new StorageResult(entry);
} catch (final IOException ex) {
return new StorageResult(entry, new IOException("cannot put entry", ex));
}
});
}
@Override
public Observable<Metadata> getMetadata() {
return Observable.defer(() -> {
final File metadata = new File(directory, "config.json");
try {
if (metadata.exists()) {
final String raw = FileUtils.readFileToString(metadata, "UTF-8");
final Metadata result = new Metadata.Builder().setTileJson(raw).build();
return Observable.just(result);
}
} catch (final IOException ex) {
throw Exceptions.propagate(ex);
}
return Observable.empty();
});
}
@Override
public Observable<StorageResult> delete(Observable<Entry> entries) {
return entries.map(entry -> {
try {
FilesystemUtil.removeEntry(directory, entry);
return new StorageResult(entry);
} catch (final IOException ex) {
return new StorageResult(entry, new IOException("cannot delete entry", ex));
}
});
}
private int[] getMaxMin(String[] value) {
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int i = 0; i < value.length; i++) {
final int d = Integer.parseInt(value[i]);
max = Math.max(max, d);
min = Math.min(min, d);
}
return new int[] {min, max};
}
private int[] toIntArray(String[] value) {
final int[] result = new int[value.length];
for (int i = 0; i < value.length; i++) {
result[i] = Integer.parseInt(value[i]);
}
return result;
}
private static String[] tileFilenames(File directory) {
return directory.list(new AbstractFileFilter() {
@Override
public boolean accept(File dir, String name) {
return name.matches("\\d*");
}
});
}
private int[] getZoomLevels() {
final List<Integer> zoomLevels = new ArrayList<>();
final File[] files = directory.listFiles();
if (files == null) {
return new int[]{};
}
final Pattern pattern = Pattern.compile("^([0-9]|1[0-9]|2[0-2])$");
for (final File file : files) {
final String fileName = file.getName();
final Matcher matcher = pattern.matcher(fileName);
if (matcher.matches()) {
final int value = Integer.parseInt(matcher.group());
zoomLevels.add(value);
}
}
final int[] result = Ints.toArray(zoomLevels);
Arrays.sort(result);
return result;
}
public static final class Builder {
private final File directory;
private boolean createIfNotExist;
private boolean gzipEnabled = true;
public Builder(String directory) throws IOException {
this.directory = new File(directory);
}
public Builder(File directory) throws IOException {
this.directory = directory;
}
public Builder createIfNotExist() {
createIfNotExist = true;
return this;
}
/**
* Set gzip compression.
*
* @param gzipEnabled set true if individual files should be gzipped, default.
* @return this builder
*/
public Builder setGzipCompression(boolean gzipEnabled) {
this.gzipEnabled = gzipEnabled;
return this;
}
/**
* Build the storage.
*
* @return the tile storage
* @throws IOException thrown on IO error
*/
public StorageImpl build() throws IOException {
if (createIfNotExist && !directory.exists()) {
LOG.info(String.format("making directory '%s'", directory));
boolean isSuccess = directory.mkdirs();
if (!isSuccess) {
throw new IOException(String.format("could not create directory: '%s'", directory));
}
}
if (!directory.isDirectory()) {
throw new IOException(String.format("not a directory: '%s'", directory));
}
return new StorageImpl(directory, gzipEnabled);
}
}
}
| 30.048077 | 98 | 0.645867 |
b62f60e92baf667836892bbaea71be56e52ac2cb | 4,015 | package io.dockstore.tooltester.helper;
import java.util.ArrayList;
import io.swagger.client.ApiException;
import io.swagger.client.api.ContainersApi;
import io.swagger.client.api.WorkflowsApi;
import io.swagger.client.model.DockstoreTool;
import io.swagger.client.model.Tag;
import io.swagger.client.model.Tool;
import io.swagger.client.model.Workflow;
import io.swagger.client.model.WorkflowVersion;
import static io.dockstore.tooltester.helper.ExceptionHandler.API_ERROR;
import static io.dockstore.tooltester.helper.ExceptionHandler.exceptionMessage;
/**
* @author gluu
* @since 03/04/19
*/
public final class DockstoreEntryHelper {
public static String generateLaunchEntryCommand(Workflow workflow, WorkflowVersion workflowVersion, String parameterFilePath) {
String fileTypeFlag = "--json";
if (parameterFilePath.endsWith(".yml") || parameterFilePath.endsWith(".yaml")) {
fileTypeFlag = "--yaml";
}
String entryPath = String.join(":", workflow.getFullWorkflowPath(), workflowVersion.getName());
ArrayList<String> commandList = new ArrayList<>();
commandList.add("dockstore");
commandList.add("workflow");
commandList.add("launch");
commandList.add("--entry");
commandList.add(entryPath);
commandList.add(fileTypeFlag);
commandList.add(parameterFilePath);
commandList.add("--script");
return String.join(" ", commandList);
}
public static String generateLaunchEntryCommand(DockstoreTool tool, Tag tag, String parameterFilePath) {
String fileTypeFlag = "--json";
if (parameterFilePath.endsWith(".yml") || parameterFilePath.endsWith(".yaml")) {
fileTypeFlag = "--yaml";
}
String entryPath = String.join(":", tool.getToolPath(), tag.getName());
ArrayList<String> commandList = new ArrayList<>();
commandList.add("dockstore");
commandList.add("tool");
commandList.add("launch");
commandList.add("--entry");
commandList.add(entryPath);
commandList.add(fileTypeFlag);
commandList.add(parameterFilePath);
commandList.add("--script");
return String.join(" ", commandList);
}
public static Workflow convertTRSToolToDockstoreEntry(Tool tool, WorkflowsApi workflowsApi) {
String toolId = tool.getId();
String path = toolId.replace("#workflow/", "");
try {
return workflowsApi.getPublishedWorkflowByPath(path, null, false);
} catch (ApiException e) {
exceptionMessage(e, "Could not get " + path + " using the workflowsApi API", API_ERROR);
}
return null;
}
public static DockstoreTool convertTRSToolToDockstoreEntry(Tool tool, ContainersApi containersApi) {
try {
return containersApi.getPublishedContainerByToolPath(tool.getId(), null);
} catch (ApiException e) {
exceptionMessage(e, "Could not get published containers using the container API", API_ERROR);
}
return null;
}
/**
* Converts the "Clone with SSH" Git URL to the "Clone with HTTPS" Git URL so Jenkins can actually clone it
* @param gitSSHUrl The "Clone with SSH" Git URL
* @return The "Clone with HTTPS" Git URL
*/
public static String convertGitSSHUrlToGitHTTPSUrl(String gitSSHUrl) {
return gitSSHUrl != null ? gitSSHUrl.replace("git@github.com:", "https://github.com/") : null;
}
/**
* Removes the leading slash from the absolute path because it is absolute within the Git repository but not the
* Jenkins file system. Jenkins will need a relative path.
* @param uncleanDockerfilePath Example: "/Dockerfile"
* @return Example: "Dockerfile"
*/
public static String convertDockstoreAbsolutePathToJenkinsRelativePath(String uncleanDockerfilePath) {
return uncleanDockerfilePath.replaceFirst("^/", "");
}
}
| 41.391753 | 131 | 0.671233 |
684adaa306b7c92e48dba15de4c1f27e83583fd6 | 1,500 | /*
* Copyright (c) 2019 by Andrew Charneski.
*
* The author 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 com.simiacryptus.mindseye.opt.orient;
import com.simiacryptus.mindseye.eval.Trainable;
import com.simiacryptus.mindseye.lang.PointSample;
import com.simiacryptus.mindseye.opt.TrainingMonitor;
import com.simiacryptus.mindseye.opt.line.LineSearchCursor;
import com.simiacryptus.ref.lang.ReferenceCounting;
/**
* The interface Orientation strategy.
*
* @param <T> the type parameter
*/
public interface OrientationStrategy<T extends LineSearchCursor> extends ReferenceCounting {
/**
* Orient t.
*
* @param subject the subject
* @param measurement the measurement
* @param monitor the monitor
* @return the t
*/
T orient(Trainable subject, PointSample measurement, TrainingMonitor monitor);
/**
* Reset.
*/
void reset();
/**
* Free.
*/
void _free();
OrientationStrategy<T> addRef();
}
| 26.315789 | 92 | 0.722667 |
f04ae90921573a55f95c7cb43c0b22e038d1bef0 | 1,517 | package com.omnisport.hello.model;
public class Product {
private int idProducto;
private String nombre;
private String descipcion;
private double precio;
public Product() {
}
public Product(int idProducto, String nombre, String descipcion, double precio) {
super();
this.idProducto = idProducto;
this.nombre = nombre;
this.descipcion = descipcion;
this.precio = precio;
}
public int getIdProducto() {
return idProducto;
}
public void setIdProducto(int idProducto) {
this.idProducto = idProducto;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getDescipcion() {
return descipcion;
}
public void setDescipcion(String descipcion) {
this.descipcion = descipcion;
}
public double getPrecio() {
return precio;
}
public void setPrecio(double precio) {
this.precio = precio;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + idProducto;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Product other = (Product) obj;
if (idProducto != other.idProducto)
return false;
return true;
}
@Override
public String toString() {
return "Product [idProducto=" + idProducto + ", nombre=" + nombre + ", descipcion=" + descipcion + ", precio="
+ precio + "]";
}
}
| 18.728395 | 112 | 0.675676 |
6c62e0bceacff108fd16518a8662dcb2304945dd | 1,745 | /*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. 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.elasticsearch.client;
/**
* Listener to be provided when calling async performRequest methods provided by {@link RestClient}.
* Those methods that do accept a listener will return immediately, execute asynchronously, and notify
* the listener whenever the request yielded a response, or failed with an exception.
*
* <p>
* Note that it is <strong>not</strong> safe to call {@link RestClient#close()} from either of these
* callbacks.
*/
public interface ResponseListener {
/**
* Method invoked if the request yielded a successful response
*/
void onSuccess(Response response);
/**
* Method invoked if the request failed. There are two main categories of failures: connection failures (usually
* {@link java.io.IOException}s, or responses that were treated as errors based on their error response code
* ({@link ResponseException}s).
*/
void onFailure(Exception exception);
}
| 38.777778 | 116 | 0.736963 |
1b2d066c25975af8f0ff56b89380c7ce9ecd9159 | 546 | package com.jayfella.launcher.settings;
public class ScreenConfig {
private boolean fullscreen = false;
private int displayModeIndex;
public ScreenConfig() {
}
public int getDisplayModeIndex() {
return displayModeIndex;
}
public void setDisplayModeIndex(int displayModeIndex) {
this.displayModeIndex = displayModeIndex;
}
public boolean isFullscreen() {
return fullscreen;
}
public void setFullscreen(boolean fullscreen) {
this.fullscreen = fullscreen;
}
}
| 18.827586 | 59 | 0.675824 |
c886f3a43e28feeec48fdc5124c3221d929a8ce6 | 1,021 | package com.hp.contaSoft.hibernate.dao.repositories;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.hp.contaSoft.hibernate.entities.PayBookInstance;
@Repository
public interface PayBookInstanceRepository extends CrudRepository<PayBookInstance, Long>{
//@Query("SELECT version FROM PayBookInstance p WHERE p.rut = :rut")
//public int findVersion(@Param("rut") String rut);
@Query("select p from PayBookInstance p where p.rut =:rut and p.month=:month ORDER BY id desc")
List<PayBookInstance> getVersionByRutAndMonth(@Param("rut") String rut,@Param("month") String month);
public List<PayBookInstance> findAllByTaxpayerId(Long id);
public List<PayBookInstance> findAllByTaxpayerIdOrderByVersionDesc(Long id);
public List<PayBookInstance> findAllByRut(String rut);
}
| 35.206897 | 103 | 0.780607 |
e5e84a3f33a2524709a22600bc33ce3c60f39077 | 1,634 | import java.util.*;
public class powerset {
class Solution {
public ArrayList<ArrayList<Integer>> subsets(ArrayList<Integer> A) {
Collections.sort(A);
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
powerSet(0, 0, A, res);
Collections.sort(res, new Comparator<ArrayList<Integer>>() {
public int compare(ArrayList<Integer> a, ArrayList<Integer> b) {
int i = 0, j = 0;
while (i < a.size() && j < b.size() && a.get(i) == b.get(j)) {
i++;
j++;
}
if (i == a.size() && j == b.size())
return 0;
if (i == a.size())
return -1;
if (j == b.size())
return 1;
return a.get(i) > b.get(j) ? 1 : -1;
}
});
return res;
}
void powerSet(int at, int bits, ArrayList<Integer> A,
ArrayList<ArrayList<Integer>> res)
{
if (at == A.size()) {
ArrayList<Integer> curr = new ArrayList<Integer>();
for (int i = 0; i < A.size(); i++)
if ((bits & (1 << i)) != 0)
curr.add(A.get(i));
res.add(curr);
return;
}
bits |= (1 << at);
powerSet(at + 1, bits, A, res);
bits &= ~(1 << at);
powerSet(at + 1, bits, A, res);
}
}
}
| 30.830189 | 84 | 0.378825 |
08ef6132081a0d45f9bb9da77ef9b88ddbe00627 | 1,953 | package cn.cstube.service.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import cn.cstube.dao.CheckItemDao;
import cn.cstube.entity.PageResult;
import cn.cstube.entity.QueryPageBean;
import cn.cstube.pojo.CheckItem;
import cn.cstube.service.CheckItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* 检查项服务
*/
@Service(interfaceClass = CheckItemService.class)
@Transactional
public class CheckItemServiceImpl implements CheckItemService {
//注入DAO对象
@Autowired
private CheckItemDao checkItemDao;
public void add(CheckItem checkItem) {
checkItemDao.add(checkItem);
}
//检查项分页查询
public PageResult pageQuery(QueryPageBean queryPageBean) {
Integer currentPage = queryPageBean.getCurrentPage();
Integer pageSize = queryPageBean.getPageSize();
String queryString = queryPageBean.getQueryString();
//完成分页查询,基于mybatis框架提供的分页助手插件完成
PageHelper.startPage(currentPage,pageSize);
Page<CheckItem> page = checkItemDao.selectByCondition(queryString);
long total = page.getTotal();
List<CheckItem> rows = page.getResult();
return new PageResult(total,rows);
}
//根据id来删除检查项
public void deleteById(Integer id) {
//判断一下当前检查项是否已经关联到检查组
long count = checkItemDao.findCountByCheckItemId(id);
if(count > 0){
//当前检查项已经被关联到检查组,不允许删除
new RuntimeException();
}
checkItemDao.deleteById(id);
}
public void edit(CheckItem checkItem) {
checkItemDao.edit(checkItem);
}
public CheckItem findById(Integer id) {
return checkItemDao.findById(id);
}
@Override
public List<CheckItem> findAll() {
return checkItemDao.findAll();
}
}
| 25.363636 | 75 | 0.705069 |
920d753a32e953b59112967b508e39f7a3a6eb2c | 2,597 | /*
* Copyright (C) 2015 The Dagger 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 dagger.functional.producers;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class DependentTest {
@Test public void dependentComponent() throws Exception {
DependentComponent dependentComponent =
DaggerDependentComponent.builder()
.dependedProductionComponent(DaggerDependedProductionComponent.create())
.dependedComponent(DaggerDependedComponent.create())
.build();
assertThat(dependentComponent).isNotNull();
assertThat(dependentComponent.greetings().get()).containsExactly(
"2", "Hello world!", "HELLO WORLD!");
}
@Test public void reuseBuilderWithDependentComponent() throws Exception {
DaggerDependentComponent.Builder dependentComponentBuilder = DaggerDependentComponent.builder();
DependentComponent componentUsingComponents =
dependentComponentBuilder
.dependedProductionComponent(DaggerDependedProductionComponent.create())
.dependedComponent(DaggerDependedComponent.create())
.build();
DependentComponent componentUsingJavaImpls = dependentComponentBuilder
.dependedProductionComponent(new DependedProductionComponent() {
@Override public ListenableFuture<Integer> numGreetings() {
return Futures.immediateFuture(3);
}
})
.dependedComponent(new DependedComponent() {
@Override public String getGreeting() {
return "Goodbye world!";
}
})
.build();
assertThat(componentUsingJavaImpls.greetings().get()).containsExactly(
"3", "Goodbye world!", "GOODBYE WORLD!");
assertThat(componentUsingComponents.greetings().get()).containsExactly(
"2", "Hello world!", "HELLO WORLD!");
}
}
| 37.637681 | 100 | 0.719677 |
363f040e2264a95844cdcc997bdbabc86861c4de | 20,886 | /*
* ====================================================================
* 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.protocol;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.apache.http.ConnectionClosedException;
import org.apache.http.ExceptionLogger;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.ProtocolException;
import org.apache.http.ProtocolVersion;
import org.apache.http.annotation.Immutable;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.NHttpClientConnection;
import org.apache.http.nio.NHttpClientEventHandler;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.Args;
import org.apache.http.util.Asserts;
/**
* {@code HttpAsyncRequestExecutor} is a fully asynchronous HTTP client side
* protocol handler based on the NIO (non-blocking) I/O model.
* {@code HttpAsyncRequestExecutor} translates individual events fired through
* the {@link NHttpClientEventHandler} interface into logically related HTTP
* message exchanges.
* <p> The caller is expected to pass an instance of
* {@link HttpAsyncClientExchangeHandler} to be used for the next series
* of HTTP message exchanges through the connection context using
* {@link #HTTP_HANDLER} attribute. HTTP exchange sequence is considered
* complete when the {@link HttpAsyncClientExchangeHandler#isDone()} method
* returns {@code true}. The {@link HttpAsyncRequester} utility class can
* be used to facilitate initiation of asynchronous HTTP request execution.
* <p>
* Individual {@code HttpAsyncClientExchangeHandler} are expected to make use of
* a {@link org.apache.http.protocol.HttpProcessor} to generate mandatory protocol
* headers for all outgoing messages and apply common, cross-cutting message
* transformations to all incoming and outgoing messages.
* {@code HttpAsyncClientExchangeHandler}s can delegate implementation of
* application specific content generation and processing to
* a {@link HttpAsyncRequestProducer} and a {@link HttpAsyncResponseConsumer}.
*
* @see HttpAsyncClientExchangeHandler
*
* @since 4.2
*/
@Immutable
public class HttpAsyncRequestExecutor implements NHttpClientEventHandler {
public static final int DEFAULT_WAIT_FOR_CONTINUE = 3000;
public static final String HTTP_HANDLER = "http.nio.exchange-handler";
private final int waitForContinue;
private final ExceptionLogger exceptionLogger;
/**
* Creates new instance of {@code HttpAsyncRequestExecutor}.
* @param waitForContinue wait for continue time period.
* @param exceptionLogger Exception logger. If {@code null}
* {@link ExceptionLogger#NO_OP} will be used. Please note that the exception
* logger will be only used to log I/O exception thrown while closing
* {@link java.io.Closeable} objects (such as {@link org.apache.http.HttpConnection}).
*
* @since 4.4
*/
public HttpAsyncRequestExecutor(
final int waitForContinue,
final ExceptionLogger exceptionLogger) {
super();
this.waitForContinue = Args.positive(waitForContinue, "Wait for continue time");
this.exceptionLogger = exceptionLogger != null ? exceptionLogger : ExceptionLogger.NO_OP;
}
/**
* Creates new instance of HttpAsyncRequestExecutor.
*
* @since 4.3
*/
public HttpAsyncRequestExecutor(final int waitForContinue) {
this(waitForContinue, null);
}
public HttpAsyncRequestExecutor() {
this(DEFAULT_WAIT_FOR_CONTINUE, null);
}
@Override
public void connected(
final NHttpClientConnection conn,
final Object attachment) throws IOException, HttpException {
final State state = new State();
final HttpContext context = conn.getContext();
context.setAttribute(HTTP_EXCHANGE_STATE, state);
requestReady(conn);
}
@Override
public void closed(final NHttpClientConnection conn) {
final State state = getState(conn);
final HttpAsyncClientExchangeHandler handler = getHandler(conn);
if (state != null) {
if (state.getRequestState() != MessageState.READY || state.getResponseState() != MessageState.READY) {
if (handler != null) {
handler.failed(new ConnectionClosedException("Connection closed unexpectedly"));
}
}
}
if (state == null || (handler != null && handler.isDone())) {
closeHandler(handler);
}
}
@Override
public void exception(
final NHttpClientConnection conn, final Exception cause) {
shutdownConnection(conn);
final HttpAsyncClientExchangeHandler handler = getHandler(conn);
if (handler != null) {
handler.failed(cause);
} else {
log(cause);
}
}
@Override
public void requestReady(
final NHttpClientConnection conn) throws IOException, HttpException {
final State state = getState(conn);
Asserts.notNull(state, "Connection state");
Asserts.check(state.getRequestState() == MessageState.READY ||
state.getRequestState() == MessageState.COMPLETED,
"Unexpected request state %s", state.getRequestState());
if (state.getRequestState() == MessageState.COMPLETED) {
conn.suspendOutput();
return;
}
final HttpContext context = conn.getContext();
final HttpAsyncClientExchangeHandler handler;
synchronized (context) {
handler = getHandler(conn);
if (handler == null || handler.isDone()) {
conn.suspendOutput();
return;
}
}
final boolean pipelined = handler.getClass().getAnnotation(Pipelined.class) != null;
final HttpRequest request = handler.generateRequest();
if (request == null) {
conn.suspendOutput();
return;
}
final ProtocolVersion version = request.getRequestLine().getProtocolVersion();
if (pipelined && version.lessEquals(HttpVersion.HTTP_1_0)) {
throw new ProtocolException(version + " cannot be used with request pipelining");
}
state.setRequest(request);
if (pipelined) {
state.getRequestQueue().add(request);
}
if (request instanceof HttpEntityEnclosingRequest) {
final boolean expectContinue = ((HttpEntityEnclosingRequest) request).expectContinue();
if (expectContinue && pipelined) {
throw new ProtocolException("Expect-continue handshake cannot be used with request pipelining");
}
conn.submitRequest(request);
if (expectContinue) {
final int timeout = conn.getSocketTimeout();
state.setTimeout(timeout);
conn.setSocketTimeout(this.waitForContinue);
state.setRequestState(MessageState.ACK_EXPECTED);
} else {
final HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
if (entity != null) {
state.setRequestState(MessageState.BODY_STREAM);
} else {
handler.requestCompleted();
state.setRequestState(pipelined ? MessageState.READY : MessageState.COMPLETED);
}
}
} else {
conn.submitRequest(request);
handler.requestCompleted();
state.setRequestState(pipelined ? MessageState.READY : MessageState.COMPLETED);
}
}
@Override
public void outputReady(
final NHttpClientConnection conn,
final ContentEncoder encoder) throws IOException, HttpException {
final State state = getState(conn);
Asserts.notNull(state, "Connection state");
Asserts.check(state.getRequestState() == MessageState.BODY_STREAM ||
state.getRequestState() == MessageState.ACK_EXPECTED,
"Unexpected request state %s", state.getRequestState());
final HttpAsyncClientExchangeHandler handler = getHandler(conn);
Asserts.notNull(handler, "Client exchange handler");
if (state.getRequestState() == MessageState.ACK_EXPECTED) {
conn.suspendOutput();
return;
}
handler.produceContent(encoder, conn);
if (encoder.isCompleted()) {
handler.requestCompleted();
final boolean pipelined = handler.getClass().getAnnotation(Pipelined.class) != null;
state.setRequestState(pipelined ? MessageState.READY : MessageState.COMPLETED);
}
}
@Override
public void responseReceived(
final NHttpClientConnection conn) throws HttpException, IOException {
final State state = getState(conn);
Asserts.notNull(state, "Connection state");
Asserts.check(state.getResponseState() == MessageState.READY,
"Unexpected request state %s", state.getResponseState());
final HttpAsyncClientExchangeHandler handler = getHandler(conn);
Asserts.notNull(handler, "Client exchange handler");
final boolean pipelined = handler.getClass().getAnnotation(Pipelined.class) != null;
final HttpRequest request;
if (pipelined) {
request = state.getRequestQueue().poll();
Asserts.notNull(request, "HTTP request");
} else {
request = state.getRequest();
if (request == null) {
throw new HttpException("Out of sequence response");
}
}
final HttpResponse response = conn.getHttpResponse();
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode < HttpStatus.SC_OK) {
// 1xx intermediate response
if (statusCode != HttpStatus.SC_CONTINUE) {
throw new ProtocolException(
"Unexpected response: " + response.getStatusLine());
}
if (state.getRequestState() == MessageState.ACK_EXPECTED) {
final int timeout = state.getTimeout();
conn.setSocketTimeout(timeout);
conn.requestOutput();
state.setRequestState(MessageState.BODY_STREAM);
}
return;
}
state.setResponse(response);
if (state.getRequestState() == MessageState.ACK_EXPECTED) {
final int timeout = state.getTimeout();
conn.setSocketTimeout(timeout);
conn.resetOutput();
state.setRequestState(MessageState.COMPLETED);
} else if (state.getRequestState() == MessageState.BODY_STREAM) {
// Early response
conn.resetOutput();
conn.suspendOutput();
state.setRequestState(MessageState.COMPLETED);
state.invalidate();
}
handler.responseReceived(response);
state.setResponseState(MessageState.BODY_STREAM);
if (!canResponseHaveBody(request, response)) {
response.setEntity(null);
conn.resetInput();
processResponse(conn, state, handler);
}
}
@Override
public void inputReady(
final NHttpClientConnection conn,
final ContentDecoder decoder) throws IOException, HttpException {
final State state = getState(conn);
Asserts.notNull(state, "Connection state");
Asserts.check(state.getResponseState() == MessageState.BODY_STREAM,
"Unexpected request state %s", state.getResponseState());
final HttpAsyncClientExchangeHandler handler = getHandler(conn);
Asserts.notNull(handler, "Client exchange handler");
handler.consumeContent(decoder, conn);
if (decoder.isCompleted()) {
processResponse(conn, state, handler);
}
}
@Override
public void endOfInput(final NHttpClientConnection conn) throws IOException {
final State state = getState(conn);
if (state != null) {
if (state.getRequestState().compareTo(MessageState.READY) != 0) {
state.invalidate();
}
final HttpAsyncClientExchangeHandler handler = getHandler(conn);
if (handler != null) {
if (state.isValid()) {
handler.inputTerminated();
} else {
handler.failed(new ConnectionClosedException("Connection closed"));
}
}
}
// Closing connection in an orderly manner and
// waiting for output buffer to get flushed.
// Do not want to wait indefinitely, though, in case
// the opposite end is not reading
if (conn.getSocketTimeout() <= 0) {
conn.setSocketTimeout(1000);
}
conn.close();
}
@Override
public void timeout(
final NHttpClientConnection conn) throws IOException {
final State state = getState(conn);
if (state != null) {
if (state.getRequestState() == MessageState.ACK_EXPECTED) {
final int timeout = state.getTimeout();
conn.setSocketTimeout(timeout);
conn.requestOutput();
state.setRequestState(MessageState.BODY_STREAM);
state.setTimeout(0);
return;
} else {
state.invalidate();
final HttpAsyncClientExchangeHandler handler = getHandler(conn);
if (handler != null) {
handler.failed(new SocketTimeoutException());
handler.close();
}
}
}
if (conn.getStatus() == NHttpConnection.ACTIVE) {
conn.close();
if (conn.getStatus() == NHttpConnection.CLOSING) {
// Give the connection some grace time to
// close itself nicely
conn.setSocketTimeout(250);
}
} else {
conn.shutdown();
}
}
/**
* This method can be used to log I/O exception thrown while closing
* {@link java.io.Closeable} objects (such as
* {@link org.apache.http.HttpConnection}}).
*
* @param ex I/O exception thrown by {@link java.io.Closeable#close()}
*/
protected void log(final Exception ex) {
this.exceptionLogger.log(ex);
}
private State getState(final NHttpConnection conn) {
return (State) conn.getContext().getAttribute(HTTP_EXCHANGE_STATE);
}
private HttpAsyncClientExchangeHandler getHandler(final NHttpConnection conn) {
return (HttpAsyncClientExchangeHandler) conn.getContext().getAttribute(HTTP_HANDLER);
}
private void shutdownConnection(final NHttpConnection conn) {
try {
conn.shutdown();
} catch (final IOException ex) {
log(ex);
}
}
private void closeHandler(final HttpAsyncClientExchangeHandler handler) {
if (handler != null) {
try {
handler.close();
} catch (final IOException ioex) {
log(ioex);
}
}
}
private void processResponse(
final NHttpClientConnection conn,
final State state,
final HttpAsyncClientExchangeHandler handler) throws IOException, HttpException {
if (!state.isValid()) {
conn.close();
}
handler.responseCompleted();
final boolean pipelined = handler.getClass().getAnnotation(Pipelined.class) != null;
if (!pipelined) {
state.setRequestState(MessageState.READY);
state.setRequest(null);
}
state.setResponseState(MessageState.READY);
state.setResponse(null);
if (!handler.isDone() && conn.isOpen()) {
conn.requestOutput();
}
}
private boolean canResponseHaveBody(final HttpRequest request, final HttpResponse response) {
final String method = request.getRequestLine().getMethod();
final int status = response.getStatusLine().getStatusCode();
if (method.equalsIgnoreCase("HEAD")) {
return false;
}
if (method.equalsIgnoreCase("CONNECT") && status < 300) {
return false;
}
return status >= HttpStatus.SC_OK
&& status != HttpStatus.SC_NO_CONTENT
&& status != HttpStatus.SC_NOT_MODIFIED
&& status != HttpStatus.SC_RESET_CONTENT;
}
static final String HTTP_EXCHANGE_STATE = "http.nio.http-exchange-state";
static class State {
private final Queue<HttpRequest> requestQueue;
private volatile MessageState requestState;
private volatile MessageState responseState;
private volatile HttpRequest request;
private volatile HttpResponse response;
private volatile boolean valid;
private volatile int timeout;
State() {
super();
this.requestQueue = new ConcurrentLinkedQueue<HttpRequest>();
this.valid = true;
this.requestState = MessageState.READY;
this.responseState = MessageState.READY;
}
public MessageState getRequestState() {
return this.requestState;
}
public void setRequestState(final MessageState state) {
this.requestState = state;
}
public MessageState getResponseState() {
return this.responseState;
}
public void setResponseState(final MessageState state) {
this.responseState = state;
}
public HttpRequest getRequest() {
return this.request;
}
public void setRequest(final HttpRequest request) {
this.request = request;
}
public HttpResponse getResponse() {
return this.response;
}
public void setResponse(final HttpResponse response) {
this.response = response;
}
public Queue<HttpRequest> getRequestQueue() {
return this.requestQueue;
}
public int getTimeout() {
return this.timeout;
}
public void setTimeout(final int timeout) {
this.timeout = timeout;
}
public boolean isValid() {
return this.valid;
}
public void invalidate() {
this.valid = false;
}
@Override
public String toString() {
final StringBuilder buf = new StringBuilder();
buf.append("request state: ");
buf.append(this.requestState);
buf.append("; request: ");
if (this.request != null) {
buf.append(this.request.getRequestLine());
}
buf.append("; response state: ");
buf.append(this.responseState);
buf.append("; response: ");
if (this.response != null) {
buf.append(this.response.getStatusLine());
}
buf.append("; valid: ");
buf.append(this.valid);
buf.append(";");
return buf.toString();
}
}
}
| 37.363148 | 114 | 0.620224 |
d3d986054669bd0fe11e571bf75c087e38498fcc | 4,157 | //package RSA;
// Koden er hentet fra http://trondal.com/rsakryptering/rsa.html
// Noen modifiseringer i metoder med støtte for BigInteger
import java.io.*;
import java.math.BigInteger;
class Verktoy {
// gcd finner st?rste felles faktor av u og v
// ved hjelp av Euklid's algoritme
static long gcd(long u, long v) {
long temp;
while (v != 0) {
temp = u % v;
u = v;
v = temp;
}
return u;
}
// gcd finner st?rste felles faktor av u og v
// ved hjelp av Euklid's algoritme
static BigInteger gcd(BigInteger u, BigInteger v) {
BigInteger temp;
while (!v.equals(BigInteger.ZERO)) {
temp = u.mod(v);
u = v;
v = temp;
}
return u;
}
// Finner e p? grunnlag av phi.
// e m? v?re innbyrdes primisk med phi
public static long finnE(long phi){
long sff=0, e=2;
while (sff != 1){
e++;
sff = gcd(e, phi);
}
return e;
}
// Finner e p? grunnlag av phi.
// e m? v?re innbyrdes primisk med phi
public static BigInteger finnE(BigInteger phi){
BigInteger sff=BigInteger.ZERO;
BigInteger e=BigInteger.ONE;
e = e.add(BigInteger.ONE);
while (sff.longValue() != 1){
e = e.add(BigInteger.ONE);
sff = gcd(e, phi);
}
return e;
}
// Finner d (den private n?kkelen) p? grunnlag av
// e og phi ved ? l?se kongruensen e*d=1(mod phi)
public static long finnD(long e, long phi) {
long u1=1, u2=0, u3=phi, v1=0, v2=1, v3=e;
long q, d, t1, t2, t3, uu, vv;
while (v3 != 0) {
q = u3/v3;
t1 = u1-q*v1;
t2 = u2-q*v2;
t3 = u3-q*v3;
u1=v1; u2=v2; u3=v3;
v1=t1; v2=t2; v3=t3;
}
uu = u1;
vv = u2;
if (vv < 0) d = vv+phi;
else d = vv;
return d;
}
// Finner d (den private n?kkelen) p? grunnlag av
// e og phi ved ? l?se kongruensen e*d=1(mod phi)
public static BigInteger finnD(BigInteger e, BigInteger phi) {
BigInteger u1=BigInteger.valueOf(1), u2=BigInteger.valueOf(0), u3=phi, v1=BigInteger.valueOf(0), v2=BigInteger.valueOf(1), v3=e;
BigInteger q, d, t1, t2, t3, uu, vv, q11, q12, q13;
while (v3.longValue() != 0) {
q = u3.divide(v3);
t1 = u1.subtract(q);
q11 = q.multiply(v1);
q12 = q.multiply(v2);
q13 = q.multiply(v3);
t1 = u1.subtract(q11);
t2 = u2.subtract(q12);
t3 = u3.subtract(q13);
u1=v1; u2=v2; u3=v3;
v1=t1; v2=t2; v3=t3;
}
uu = u1;
vv = u2;
if (vv.longValue() < 0) d = vv.add(phi);
else d = vv;
return d;
}
// Regner ut a opph?yd i x modulus m
public static long modPow(long a, long x, long m){
BigInteger A = new BigInteger(new Long(a).toString());
BigInteger X = new BigInteger(new Long(x).toString());
BigInteger M = new BigInteger(new Long(m).toString());
return A.modPow(X,M).longValue();
}
// Regner ut a opph?yd i x modulus m
public static BigInteger modPow(BigInteger a, BigInteger x, BigInteger m){
/*BigInteger A = new BigInteger(new Long(a).toString());
BigInteger X = new BigInteger(new Long(x).toString());
BigInteger M = new BigInteger(new Long(m).toString());
return A.modPow(X,M).longValue();
*/
return a.modPow(x,m);
}
// Skriver et tall til en angitt tekstfil
public static void skriv(long tall, String filnavn){
try{
System.out.println("skriver til "+filnavn);
FileWriter tekstFilSkriver = new FileWriter(filnavn, false);
PrintWriter tekstSkriver = new PrintWriter(tekstFilSkriver);
tekstSkriver.print(tall);
tekstSkriver.close();
}
catch (IOException unntak) {
System.out.print("error: Feil ved skriving til fil! " + unntak);
}
}
// Leser et tall fra en angitt tekstfil
public static long les(String filnavn){
String tallStreng;
tallStreng="-1";
try{
System.out.println("leser fra "+filnavn);
FileReader tekstFilLeser = new FileReader(filnavn);
BufferedReader tekstLeser = new BufferedReader(tekstFilLeser);
tallStreng = tekstLeser.readLine();
}
catch (IOException unntak) {
System.out.print("error: Feil ved lesing av fil! " + unntak);
}
return new Long(tallStreng).longValue();
}
} | 28.668966 | 131 | 0.612942 |
df3e00c45bebb5fd8f12fee93bc48c06265019db | 4,409 | package com.itachi1706.cheesecakeutilities.modules.vehicleMileageTracker;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import com.google.firebase.database.DatabaseReference;
import com.itachi1706.helperlib.helpers.PrefHelper;
import com.itachi1706.cheesecakeutilities.modules.vehicleMileageTracker.fragments.VehicleMileageDateStatsFragment;
import com.itachi1706.cheesecakeutilities.modules.vehicleMileageTracker.fragments.VehicleMileageGeneralStatsFragment;
import com.itachi1706.cheesecakeutilities.modules.vehicleMileageTracker.fragments.VehicleMileageMonthStatsFragment;
import com.itachi1706.cheesecakeutilities.modules.vehicleMileageTracker.fragments.VehicleMileageVNumberStatsFragment;
import com.itachi1706.cheesecakeutilities.modules.vehicleMileageTracker.fragments.VehicleMileageVTypeStatsFragment;
import com.itachi1706.cheesecakeutilities.R;
import com.itachi1706.cheesecakeutilities.ViewPagerAdapter;
import static com.itachi1706.cheesecakeutilities.modules.vehicleMileageTracker.VehMileageFirebaseUtils.FB_REC_STATS;
import static com.itachi1706.cheesecakeutilities.modules.vehicleMileageTracker.VehMileageFirebaseUtils.FB_REC_USER;
public class VehicleMileageStatisticsActivity extends AppCompatActivity {
Toolbar toolbar;
ViewPager pager;
TabLayout tabLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu_tabbed);
toolbar = findViewById(R.id.toolbar);
((AppBarLayout.LayoutParams) toolbar.getLayoutParams())
.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null && getSupportActionBar().isShowing()) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
pager = findViewById(R.id.main_viewpager);
tabLayout = findViewById(R.id.main_tablayout);
((AppBarLayout.LayoutParams) tabLayout.getLayoutParams()).setScrollFlags(0);
setupViewPager(pager);
tabLayout.setupWithViewPager(pager);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
// Keep Firebase synced
SharedPreferences sp = PrefHelper.getDefaultSharedPreferences(this);
String user_id = VehMileageFirebaseUtils.getFirebaseUIDFromSharedPref(sp);
if (!user_id.equals("nien")) {
DatabaseReference dbRef = VehMileageFirebaseUtils.getVehicleMileageDatabase();
dbRef.child(FB_REC_USER).child(user_id).child(FB_REC_STATS).keepSynced(true);
dbRef.child("stat-legend").keepSynced(true);
dbRef.child("vehicles").keepSynced(true);
}
}
private void setupViewPager(ViewPager viewPager)
{
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new VehicleMileageGeneralStatsFragment(), "General");
adapter.addFrag(new VehicleMileageDateStatsFragment(), "Date");
adapter.addFrag(new VehicleMileageMonthStatsFragment(), "Month");
adapter.addFrag(new VehicleMileageVNumberStatsFragment(), "Vehicle Number");
adapter.addFrag(new VehicleMileageVTypeStatsFragment(), "Vehicle Type");
viewPager.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.modules_veh_mileage_stats, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.generateReport:
startActivity(new Intent(this, GenerateMileageRecordActivity.class));
return true;
case android.R.id.home:
case R.id.exit:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
| 44.09 | 131 | 0.750964 |
3bba17fe8e2e617d07e0349db0cd8c06245fdca5 | 738 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Model.Interface;
import Exception.*;
import Model.Person;
import java.util.List;
/**
*
* @author Samuel
*/
public interface PersonInterface {
public boolean inert (Person person) throws RegistrationSuccessfullyRegistredException;
public boolean update (Person person) throws UpdateErrorException;
public boolean delete (Person person) throws DeletedRecordException;
public List<Person> selectAll () throws EmptyDatabaseException;
public Person select (int id) throws ElementNotFoundException;
}
| 26.357143 | 91 | 0.745257 |
afa1194fbec1f2283b11ff3f7b181e71904767e5 | 948 | package com.example.animation;
import android.app.Activity;
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
public class ScaleAnimationActivity extends Activity {
ImageView m_img;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(com.example.R.layout.com_example_animation_scale);
m_img=(ImageView)findViewById(com.example.R.id.scaleanimation_imageView1);
//Animation anim=new ScaleAnimation(1f,0.4f,1f,0.3f );
//anim.setDuration(2000);
//anim.setRepeatCount(100);
//m_img.setAnimation(anim);
//anim.start();
Animation anim=AnimationUtils.loadAnimation(getApplicationContext(), com.example.R.anim.scale);
m_img.startAnimation(anim);
}
}
| 30.580645 | 98 | 0.762658 |
3810984fc21ffb53ca202b049402b965b08bae21 | 769 | /*
* Copyright (c) 2014-2021, MiLaboratories Inc. All Rights Reserved
*
* BEFORE DOWNLOADING AND/OR USING THE SOFTWARE, WE STRONGLY ADVISE
* AND ASK YOU TO READ CAREFULLY LICENSE AGREEMENT AT:
*
* https://github.com/milaboratory/mixcr/blob/develop/LICENSE
*/
package com.milaboratory.mixcr.basictypes;
import com.milaboratory.mixcr.vdjaligners.ClonalGeneAlignmentParameters;
/**
* Created by poslavsky on 01/03/2017.
*/
public interface ClonalUpdatableParameters {
/**
* Set absent parameters from ClonalGeneAlignmentParameters object
*
* @param alignerParameters
*/
void updateFrom(ClonalGeneAlignmentParameters alignerParameters);
/**
* Returns true if all parameters are defined
*/
boolean isComplete();
}
| 26.517241 | 72 | 0.729519 |
89e3b4db5755b6b55da76179eff30f9792ba8790 | 4,489 | /*
* Copyright 2016 Alejandro Alcalde
*
* 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.
*/
/**
* Created by Alejandro Alcalde <contacto@elbauldelprogramador.com> on 2/26/16.
*/
import java.util.Random;
import java.util.stream.IntStream;
/**
* Demostración de operaciones sobre flujo con valores enteros
*/
public class IntStreamOperations {
private int valores[];
public IntStreamOperations(int numeroValores) {
this.valores = new int[numeroValores];
Random generator = new Random();
for (int i = 0; i < numeroValores; i++) {
valores[i] = generator.nextInt(101);
}
}
/**
* Muestra los valores usando funciones lambda
*/
public void mostrarValoresFuncional() {
// IntStream.of(this.valores).forEach(value -> System.out.printf("%d%n", value));
// Equivalente, referencia a método
IntStream.of(this.valores)
.forEach(System.out::println); // Final, no da como salida flujo, da resultado
}
public long contarValoresFuncional() {
return IntStream.of(this.valores)
.count();
}
public int obtenerMinimo() {
return IntStream.of(this.valores)
.min()
.getAsInt();
}
public int obtenerMaximo() {
return IntStream.of(this.valores).max().getAsInt();
}
public long obtenerSuma() {
return IntStream.of(this.valores).sum();
}
public long obtenerSumaReduce() {
// 0 es el valor inicial
// luego expresión lambda con dos argumentos, y los suma.
// Primera iter:
// x=0, y=this.valores[0]
// x=pasoanterior, y=this.valores[1]
return IntStream.of(this.valores)
.reduce(0, (x, y) -> (x + y));
}
public long obtenerSumaReduceCuadrado() {
return IntStream.of(this.valores)
.reduce(0, (x, y) -> (x + y * y));
}
public long obtenerProducto() {
return IntStream.of(this.valores)
.reduce(1, (x, y) -> (x * y));
}
/**
* SUma de cuadrados con map
*/
public long obtenerSumaCuadradosMap() {
return IntStream.of(this.valores)
.map(x -> x * x)
.sum();
}
public void ordenarPares() {
IntStream.of(this.valores)
.filter(value -> (value & 1) == 0)
.sorted()
.forEach(System.out::println);
}
public void multiplicaFactorObtenParesOrdenarMostrar(int factor) {
IntStream.of(this.valores)
.map(x -> x * factor)
.filter(value -> (value & 1) == 0)
.sorted()
.forEach(System.out::println);
}
// DEbe ser valores Integer, no int
// public List<Integer> obtenerMayor4() {
//
// return Arrays.stream(this.valores)
// .filter(value -> value > 4)
// .collect(Collectors.toList());
// }
public static void main(String[] args) {
long numeroValores, suma;
int min, max;
double media, sumaCuadrados, producto;
IntStreamOperations objeto = new IntStreamOperations(10000);
objeto.mostrarValoresFuncional();
System.out.printf("%nNúmero de elementos: %d%n", objeto.contarValoresFuncional());
System.out.printf("Mínimo: %d%n", objeto.obtenerMinimo());
System.out.printf("Mínimo: %d%n", objeto.obtenerMaximo());
System.out.printf("Suma: %d%n", objeto.obtenerSuma());
System.out.printf("Suma Reduce: %d%n", objeto.obtenerSumaReduce());
System.out.printf("Suma Reduce cuadrada: %d%n", objeto.obtenerSumaReduceCuadrado());
System.out.printf("Producto Reduce: %d%n", objeto.obtenerProducto());
System.out.printf("Suma Cuadrado con MAp: %d%n", objeto.obtenerSumaCuadradosMap());
objeto.ordenarPares();
objeto.multiplicaFactorObtenParesOrdenarMostrar(2);
}
}
| 31.391608 | 94 | 0.600134 |
12991ed32777e0cc32e8f8d90a7284f26aeaa614 | 3,287 | package tdt4140.gr1812.app.ui.controllers;
import javafx.fxml.FXML;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.MenuButton;
import javafx.scene.control.RadioMenuItem;
import javafx.scene.control.TextField;
import javafx.scene.text.Text;
import tdt4140.gr1812.app.core.dataClasses.Sport;
import tdt4140.gr1812.app.core.models.workoutRegistration.WorkoutRegistrationModel;
import tdt4140.gr1812.app.ui.FxApp;
public class WorkoutRegistrationController {
@FXML
TextField lengdePaaOkt;
@FXML
TextField extraField;
@FXML
TextField maal;
@FXML
TextField puls;
@FXML
Hyperlink registrer;
@FXML
Hyperlink kryssUt;
@FXML
MenuButton idrett;
@FXML
RadioMenuItem basket;
@FXML
RadioMenuItem langrenn;
@FXML
RadioMenuItem fotball;
@FXML
CheckBox privatOkt;
@FXML
Text feedback;
protected String currentUser;
//initiates a new WorkoutRegistrationModel
WorkoutRegistrationModel model = new WorkoutRegistrationModel();
FxApp app;
//specifies the name of the sport field to the sport we choose
//also sets the prompt text for the "extraField", defined in the model
@FXML
public String setField() {
boolean b = basket.isSelected();
boolean f = fotball.isSelected();
boolean l = langrenn.isSelected();
String bas = basket.getText();
String lang = langrenn.getText();
String fot = fotball.getText();
if (b) {
extraField.setPromptText(model.valueForExtraField(bas));
return bas;
}
if (f) {
extraField.setPromptText(model.valueForExtraField(fot));
return fot;
}if (l) {
extraField.setPromptText(model.valueForExtraField(lang));
return lang;
}
return "Idrett";
}
//sets the name of the sport field to the sport we choose
@FXML
public void initialize() {
idrett.setText(setField());
}
//updates the feedback text in the FXMLfile
@FXML
public void update() {
feedback.setText(model.getText());
}
//method to handle a workout registration
@FXML
public boolean handleRegistrer() {
boolean b = basket.isSelected(); //returns true if the basket field is selected
boolean f = fotball.isSelected();
boolean l = langrenn.isSelected();
boolean c = privatOkt.isPressed();
String lengde = lengdePaaOkt.getText(); //sets the value of "lengde" to the text written in the "lengde"-field in the view
String eF = extraField.getText();
String m = maal.getText();
String p = puls.getText();
Sport s = null;
if (b) {
s = new Sport("basket");
}
if (f) {
s = new Sport("fotball");
}
if (l) {
s = new Sport("langrenn");
}
boolean action = model.WorkoutRegistrationModelInit(currentUser, p, eF, lengde, s, m, c); //WorkoutRegistrationModelInit() returns true if a register is handled
if (action) {
app.goToLoggedIn();
return true;
}
else {
update();
return false;
}
}
//sets the String "currentUser" to a chosen user
public void setCurrentUser(String user) {
this.currentUser = user;
}
//returns the current user
public String getCurrentUser() {
return this.currentUser;
}
//method to handle exit from site
@FXML
public void handleKryssUt() {
app.goToLoggedIn();
}
//method to communicate with the FxApp
public void setApplication(FxApp app) {
this.app = app;
}
}
| 23.478571 | 162 | 0.718284 |
26cd207180b8efcaaccd5cf3cd3c1fb3d91fd62d | 1,197 | package com.lambdaschool.airbnbbuildweek.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* The application turns off any automatic web page generate done by Spring. This is done to improve exception handling.
* However, we do need some web page generate done for Swagger, so we do that here.
*/
@Configuration
public class SwaggerWebMVC
implements WebMvcConfigurer
{
/**
* Adds the Swagger web pages to Spring.
* This still gives the following warning
* <p>
* No mapping for GET /
* No mapping for GET /csrf
* <p>
* All works though
*
* @param registry the place that holds the web pages for Spring
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
} | 34.2 | 120 | 0.716792 |
86e23a9a6db4cd3f5891c86142281384d780efb5 | 9,449 | /**
* 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.component.netty4.http;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpMethod;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.RuntimeExchangeException;
import org.apache.camel.converter.IOConverter;
import org.apache.camel.util.IOHelper;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.URISupport;
import org.apache.camel.util.UnsafeUriCharactersEncoder;
/**
* Helpers.
*/
public final class NettyHttpHelper {
private NettyHttpHelper() {
}
@SuppressWarnings("deprecation")
public static void setCharsetFromContentType(String contentType, Exchange exchange) {
String charset = getCharsetFromContentType(contentType);
if (charset != null) {
exchange.setProperty(Exchange.CHARSET_NAME, IOConverter.normalizeCharset(charset));
}
}
public static String getCharsetFromContentType(String contentType) {
if (contentType != null) {
// find the charset and set it to the Exchange
int index = contentType.indexOf("charset=");
if (index > 0) {
String charset = contentType.substring(index + 8);
// there may be another parameter after a semi colon, so skip that
if (charset.contains(";")) {
charset = ObjectHelper.before(charset, ";");
}
return IOHelper.normalizeCharset(charset);
}
}
return null;
}
/**
* Appends the key/value to the headers.
* <p/>
* This implementation supports keys with multiple values. In such situations the value
* will be a {@link java.util.List} that contains the multiple values.
*
* @param headers headers
* @param key the key
* @param value the value
*/
@SuppressWarnings("unchecked")
public static void appendHeader(Map<String, Object> headers, String key, Object value) {
if (headers.containsKey(key)) {
Object existing = headers.get(key);
List<Object> list;
if (existing instanceof List) {
list = (List<Object>) existing;
} else {
list = new ArrayList<Object>();
list.add(existing);
}
list.add(value);
value = list;
}
headers.put(key, value);
}
/**
* Creates the {@link HttpMethod} to use to call the remote server, often either its GET or POST.
*
* @param message the Camel message
* @return the created method
*/
public static HttpMethod createMethod(Message message, boolean hasPayload) {
// use header first
HttpMethod m = message.getHeader(Exchange.HTTP_METHOD, HttpMethod.class);
if (m != null) {
return m;
}
String name = message.getHeader(Exchange.HTTP_METHOD, String.class);
if (name != null) {
return HttpMethod.valueOf(name);
}
if (hasPayload) {
// use POST if we have payload
return HttpMethod.POST;
} else {
// fallback to GET
return HttpMethod.GET;
}
}
public static Exception populateNettyHttpOperationFailedException(Exchange exchange, String url, FullHttpResponse response, int responseCode, boolean transferException) {
String uri = url;
String statusText = response.getStatus().reasonPhrase();
if (responseCode >= 300 && responseCode < 400) {
String redirectLocation = response.headers().get("location");
if (redirectLocation != null) {
return new NettyHttpOperationFailedException(uri, responseCode, statusText, redirectLocation, response);
} else {
// no redirect location
return new NettyHttpOperationFailedException(uri, responseCode, statusText, null, response);
}
}
if (transferException) {
String contentType = response.headers().get(Exchange.CONTENT_TYPE);
if (NettyHttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType)) {
// if the response was a serialized exception then use that
InputStream is = exchange.getContext().getTypeConverter().convertTo(InputStream.class, response);
if (is != null) {
try {
Object body = deserializeJavaObjectFromStream(is);
if (body instanceof Exception) {
return (Exception) body;
}
} catch (Exception e) {
return e;
} finally {
IOHelper.close(is);
}
}
}
}
// internal server error (error code 500)
return new NettyHttpOperationFailedException(uri, responseCode, statusText, null, response);
}
public static Object deserializeJavaObjectFromStream(InputStream is) throws ClassNotFoundException, IOException {
if (is == null) {
return null;
}
Object answer = null;
ObjectInputStream ois = new ObjectInputStream(is);
try {
answer = ois.readObject();
} finally {
IOHelper.close(ois);
}
return answer;
}
/**
* Creates the URL to invoke.
*
* @param exchange the exchange
* @param endpoint the endpoint
* @return the URL to invoke
*/
public static String createURL(Exchange exchange, NettyHttpEndpoint endpoint) throws URISyntaxException {
String uri = endpoint.getEndpointUri();
// resolve placeholders in uri
try {
uri = exchange.getContext().resolvePropertyPlaceholders(uri);
} catch (Exception e) {
throw new RuntimeExchangeException("Cannot resolve property placeholders with uri: " + uri, exchange, e);
}
// append HTTP_PATH to HTTP_URI if it is provided in the header
String path = exchange.getIn().getHeader(Exchange.HTTP_PATH, String.class);
// NOW the HTTP_PATH is just related path, we don't need to trim it
if (path != null) {
if (path.startsWith("/")) {
path = path.substring(1);
}
if (path.length() > 0) {
// make sure that there is exactly one "/" between HTTP_URI and
// HTTP_PATH
if (!uri.endsWith("/")) {
uri = uri + "/";
}
uri = uri.concat(path);
}
}
// ensure uri is encoded to be valid
uri = UnsafeUriCharactersEncoder.encodeHttpURI(uri);
return uri;
}
/**
* Creates the URI to invoke.
*
* @param exchange the exchange
* @param url the url to invoke
* @param endpoint the endpoint
* @return the URI to invoke
*/
public static URI createURI(Exchange exchange, String url, NettyHttpEndpoint endpoint) throws URISyntaxException {
URI uri = new URI(url);
// is a query string provided in the endpoint URI or in a header (header overrules endpoint)
String queryString = exchange.getIn().getHeader(Exchange.HTTP_QUERY, String.class);
if (queryString == null) {
// use raw as we encode just below
queryString = uri.getRawQuery();
}
if (queryString != null) {
// need to encode query string
queryString = UnsafeUriCharactersEncoder.encodeHttpURI(queryString);
uri = URISupport.createURIWithQuery(uri, queryString);
}
return uri;
}
/**
* Checks whether the given http status code is within the ok range
*
* @param statusCode the status code
* @param okStatusCodeRange the ok range (inclusive)
* @return <tt>true</tt> if ok, <tt>false</tt> otherwise
*/
public static boolean isStatusCodeOk(int statusCode, String okStatusCodeRange) {
int from = Integer.valueOf(ObjectHelper.before(okStatusCodeRange, "-"));
int to = Integer.valueOf(ObjectHelper.after(okStatusCodeRange, "-"));
return statusCode >= from && statusCode <= to;
}
}
| 36.766537 | 174 | 0.611599 |
a20e848312d4d9a457741aedba52b7dc95f3db92 | 2,229 | package com.blankj.utilcode.common;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import java.util.Stack;
/**
* 应用程序Activity管理工具类,用于Activity的管理和应用程序的退出
*/
public class AppManger {
private static Stack<Activity> activityStack;
private AppManger() {
if(Inner.appManger != null){
throw new RuntimeException();
}
}
private static class Inner{
private static AppManger appManger = new AppManger();
}
public static AppManger getAppManager() {
return Inner.appManger;
}
/**
* 添加Activity 到栈
*
* @param activity
*/
public void addActivity(Activity activity) {
if (activityStack == null) {
activityStack = new Stack<>();
}
activityStack.add(activity);
}
/**
* 获取当前的Activity(堆栈中最后一个压入的)
*/
public Activity currentActivity() {
Activity activity = activityStack.lastElement();
return activity;
}
/**
* 结束指定的Activity
*/
public void finishActivity(Activity activityOne,Class<?>... clsList) {
if (activityOne != null) {
activityStack.remove(activityOne);
activityOne.finish();
}
if(clsList.length>0){
for(Activity activity : activityStack){
for(Class<?> cls : clsList){
if(activity.getClass().equals(cls)){
activity.finish();
}
}
}
}
}
/**
* 结束所有的Activity、
*/
public void finishAllActivity() {
int size = activityStack.size();
for (int i = 0; i < size; i++) {
if (null != activityStack.get(i)) {
activityStack.get(i).finish();
}
}
activityStack.clear();
}
public void appExit(Context context) {
try {
finishAllActivity();
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
activityManager.restartPackage(context.getPackageName());
System.exit(0);
} catch (Exception e) {
}
}
}
| 24.228261 | 115 | 0.555855 |
2673e3c0a5228ab3728a7ac4d9072f57324ca6f8 | 856 | package com.georgebindragon.base.function;
/**
* 创建人:George
* 类名称:FunctionProxy
* 类概述:
* 详细描述:
*
* 修改人:
* 修改时间:
* 修改备注:
*/
public class FunctionProxy
{
public static void registerFunction(Class functionClass, Object functionImpl)
{
if (null == functionClass || null == functionImpl) return;
FunctionManager.getInstance().registerService(functionClass.getCanonicalName(), functionImpl);
}
public static <T> T getFunction(Class functionClass)
{
if (null == functionClass) return null;
try
{
return (T) FunctionManager.getInstance().getLocalService(functionClass.getCanonicalName());
} catch (Exception e)
{
return null;
}
}
public static void unregisterFunction(Class functionClass)
{
if (null == functionClass) return;
FunctionManager.getInstance().unregisterService(functionClass.getCanonicalName());
}
}
| 19.906977 | 96 | 0.725467 |
689e688d60ebb3e7c850b2f1c4473884ab93a2c2 | 242 | package org.dreamcat.rita.view;
import lombok.Getter;
import lombok.Setter;
/**
* Create by tuke on 2020/3/22
*/
@Getter
@Setter
public class ImageCodeView {
private String source;
private long timestamp;
private int nonce;
}
| 15.125 | 31 | 0.714876 |
423ebc3ad9d454816aeff11ad06650a53eef324e | 3,479 | /**
* blackduck-docker-inspector
*
* Copyright (c) 2021 Synopsys, Inc.
*
* Use subject to the terms and conditions of the Synopsys End User Software License and Maintenance Agreement. All rights reserved worldwide.
*/
package com.synopsys.integration.blackduck.dockerinspector.output;
import java.io.File;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.synopsys.integration.blackduck.dockerinspector.config.Config;
@Component
public class ContainerFilesystemFilename {
private static final String CONTAINER_FILESYSTEM_IDENTIFIER = "containerfilesystem";
private static final String APP_ONLY_HINT = "app";
private static final String TWO_PART_STRING_FORMAT = "%s_%s";
private static final String THREE_PART_STRING_FORMAT = "%s_%s_%s";
private Config config;
@Autowired
public void setConfig(final Config config) {
this.config = config;
}
public String deriveContainerFilesystemFilename(final String repo, final String tag) {
final String containerFileSystemFilename;
if (StringUtils.isBlank(config.getDockerPlatformTopLayerId())) {
containerFileSystemFilename = getContainerFileSystemTarFilename(repo, tag, config.getDockerTar());
} else {
containerFileSystemFilename = getContainerFileSystemAppLayersTarFilename(repo, tag, config.getDockerTar());
}
return containerFileSystemFilename;
}
private String getContainerFileSystemTarFilename(final String repo, final String tag, final String tarPath) {
return getContainerOutputTarFileNameUsingBase(CONTAINER_FILESYSTEM_IDENTIFIER, repo, tag, tarPath);
}
private String getContainerFileSystemAppLayersTarFilename(final String repo, final String tag, final String tarPath) {
final String contentHint = String.format(TWO_PART_STRING_FORMAT, APP_ONLY_HINT, CONTAINER_FILESYSTEM_IDENTIFIER);
return getContainerOutputTarFileNameUsingBase(contentHint, repo, tag, tarPath);
}
private static String getContainerOutputTarFileNameUsingBase(final String contentHint, final String repo, final String tag, final String tarPath) {
final String containerFilesystemFilenameSuffix = String.format("%s.tar.gz", contentHint);
if (StringUtils.isNotBlank(repo)) {
return String.format(THREE_PART_STRING_FORMAT, slashesToUnderscore(repo), slashesToUnderscore(tag), containerFilesystemFilenameSuffix);
} else {
final File tarFile = new File(tarPath);
final String tarFilename = tarFile.getName();
if (tarFilename.contains(".")) {
final int finalPeriodIndex = tarFilename.lastIndexOf('.');
return String.format(TWO_PART_STRING_FORMAT, tarFilename.substring(0, finalPeriodIndex), containerFilesystemFilenameSuffix);
}
return String.format(TWO_PART_STRING_FORMAT, cleanImageName(tarFilename), containerFilesystemFilenameSuffix);
}
}
private static String cleanImageName(final String imageName) {
return colonsToUnderscores(slashesToUnderscore(imageName));
}
private static String colonsToUnderscores(final String imageName) {
return imageName.replace(":", "_");
}
private static String slashesToUnderscore(final String givenString) {
return givenString.replace("/", "_");
}
}
| 44.602564 | 151 | 0.74188 |
07355692211760a9b01b4bdc6fed1d7eeee898d4 | 287 | package org.prebid.pg.delstats.model.dto;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
@AllArgsConstructor
public class PlanDataSummary {
private String lineItemId;
private String planData;
}
| 15.944444 | 41 | 0.794425 |
eae0465dae7f133752f06f614421751e1f8215e8 | 840 | package main.com.neptune8.juc;
import java.util.Random;
import java.util.concurrent.CyclicBarrier;
/**
* @author zhou
*/
public class TestCyclicBarrier {
private static CyclicBarrier cyclicBarrier;
private static final Integer SIZE = 5;
public static void main(String[] args) {
cyclicBarrier = new CyclicBarrier(SIZE, new Runnable() {
@Override
public void run() {
System.out.println("let's begin!");
}
});
for (int i = 0; i < SIZE; i++) {
new Thread(new Task()).start();
}
}
static class Task implements Runnable {
@Override
public void run() {
Random random = new Random();
Integer rand = random.nextInt(1000);
System.out.println("let's wait " + rand + " !");
try {
Thread.sleep(rand);
cyclicBarrier.await();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
| 19.090909 | 58 | 0.645238 |
5ec1f174b55a6fb888b666b640dbdd1069c85eb1 | 7,256 | /**
* Copyright 2015 Palantir Technologies
*
* Licensed under the BSD-3 License (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/BSD-3-Clause
*
* 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.palantir.atlasdb.table.description;
import java.util.Set;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.apache.commons.lang.Validate;
import com.google.common.collect.Sets;
import com.palantir.atlasdb.protos.generated.TableMetadataPersistence;
import com.palantir.atlasdb.protos.generated.TableMetadataPersistence.NameComponentDescription.Builder;
import com.palantir.atlasdb.protos.generated.TableMetadataPersistence.ValueByteOrder;
@Immutable
public class NameComponentDescription {
final String componentName;
final ValueType type;
final ValueByteOrder order;
@Nullable final UniformRowNamePartitioner uniformPartitioner;
@Nullable final ExplicitRowNamePartitioner explicitPartitioner;
public NameComponentDescription() {
this("name", ValueType.BLOB);
}
public NameComponentDescription(String componentName, ValueType type) {
this(componentName, type, ValueByteOrder.ASCENDING, new UniformRowNamePartitioner(type), null);
}
@Deprecated
public NameComponentDescription(String componentName, ValueType type, boolean reverseOrder) {
this.componentName = componentName;
this.type = type;
this.order = reverseOrder ? ValueByteOrder.DESCENDING : ValueByteOrder.ASCENDING;
this.uniformPartitioner = new UniformRowNamePartitioner(type);
this.explicitPartitioner = null;
}
public NameComponentDescription(String componentName,
ValueType type,
ValueByteOrder order) {
this(componentName, type, order, new UniformRowNamePartitioner(type), null);
}
public NameComponentDescription(String componentName,
ValueType type,
ValueByteOrder order,
UniformRowNamePartitioner uniform,
ExplicitRowNamePartitioner explicit) {
Validate.notNull(componentName);
Validate.notNull(type);
Validate.notNull(order);
this.componentName = componentName;
this.type = type;
this.order = order;
this.uniformPartitioner = uniform;
this.explicitPartitioner = explicit;
}
public String getComponentName() {
return componentName;
}
public ValueType getType() {
return type;
}
public boolean isReverseOrder() {
return order == ValueByteOrder.DESCENDING;
}
public ValueByteOrder getOrder() {
return order;
}
public TableMetadataPersistence.NameComponentDescription.Builder persistToProto() {
Builder builder = TableMetadataPersistence.NameComponentDescription.newBuilder();
builder.setComponentName(componentName);
builder.setType(type.persistToProto());
builder.setOrder(getOrder());
builder.setHasUniformPartitioner(uniformPartitioner != null);
if (explicitPartitioner != null) {
builder.addAllExplicitPartitions(explicitPartitioner.values);
}
return builder;
}
public static NameComponentDescription hydrateFromProto(TableMetadataPersistence.NameComponentDescription message) {
ValueType type = ValueType.hydrateFromProto(message.getType());
UniformRowNamePartitioner u = new UniformRowNamePartitioner(type);
if (message.hasHasUniformPartitioner()) {
u = message.getHasUniformPartitioner() ? new UniformRowNamePartitioner(type) : null;
}
ExplicitRowNamePartitioner e = null;
if (message.getExplicitPartitionsCount() > 0) {
e = new ExplicitRowNamePartitioner(type, message.getExplicitPartitionsList());
}
return new NameComponentDescription(message.getComponentName(), type, message.getOrder(), u, e);
}
/**
* NB: a component can have both a uniform partitioner and an explicit partitioner
*/
public boolean hasUniformPartitioner() {
return uniformPartitioner != null;
}
/**
* NB: a component can have both an explicit partitioner and a uniform partitioner
*/
@Nullable
public ExplicitRowNamePartitioner getExplicitPartitioner() {
return explicitPartitioner;
}
public NameComponentDescription withPartitioners(RowNamePartitioner... partitioners) {
Set<String> explicit = Sets.newHashSet();
boolean hasUniform = false;
for (RowNamePartitioner p : partitioners) {
hasUniform |= p instanceof UniformRowNamePartitioner;
if (p instanceof ExplicitRowNamePartitioner) {
explicit.addAll(((ExplicitRowNamePartitioner) p).values);
}
}
UniformRowNamePartitioner u = null;
if (hasUniform) {
u = new UniformRowNamePartitioner(type);
}
ExplicitRowNamePartitioner e = null;
if (!explicit.isEmpty()) {
e = new ExplicitRowNamePartitioner(type, explicit);
}
return new NameComponentDescription(componentName, type, order, u, e);
}
@Override
public String toString() {
return "NameComponentDescription [componentName=" + componentName
+ ", order=" + order + ", type=" + type + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (componentName == null ? 0 : componentName.hashCode());
result = prime * result + (type == null ? 0 : type.hashCode());
result = prime * result + (order == null ? 0 : order.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
NameComponentDescription other = (NameComponentDescription) obj;
if (componentName == null) {
if (other.getComponentName() != null) {
return false;
}
} else if (!componentName.equals(other.getComponentName())) {
return false;
}
if (type == null) {
if (other.getType() != null) {
return false;
}
} else if (!type.equals(other.getType())) {
return false;
}
if (order == null) {
if (other.getOrder() != null) {
return false;
}
} else if (!order.equals(other.getOrder())) {
return false;
}
return true;
}
}
| 35.920792 | 120 | 0.644294 |
1916f000ccf36d74fb0103ec985858f2abb970eb | 308 | // Test case for Issue 1984
// https://github.com/typetools/checker-framework/issues/1984
import org.checkerframework.common.value.qual.IntRange;
public class Issue1984 {
public int m(int[] a, @IntRange(from = 0, to = 12) int i) {
// :: error: (array.access.unsafe.high.range)
return a[i];
}
}
| 25.666667 | 61 | 0.685065 |
77fe03c76711ffa92386e53cbf6affcd9d7bd404 | 2,350 | /*
* 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.
*
* Copyright 2007-2010 SSAC(Systems of Social Accounting Consortium)
* <author> Yasunari Ishizuka (PieCake,Inc.)
* <author> Hiroshi Deguchi (TOKYO INSTITUTE OF TECHNOLOGY)
* <author> Yuji Onuki (Statistics Bureau)
* <author> Shungo Sakaki (Tokyo University of Technology)
* <author> Akira Sasaki (HOSEI UNIVERSITY)
* <author> Hideki Tanuma (TOKYO INSTITUTE OF TECHNOLOGY)
*/
/*
* @(#)APrimExBasePatternSet.java 1.40 2010/02/19
* - modified by Y.Ishizuka(PieCake.inc,)
* @(#)APrimExBasePatternSet.java 1.30 2009/12/02
* - created by Y.Ishizuka(PieCake.inc,)
*/
package ssac.aadlc.analysis.type.prim;
import ssac.aadlc.analysis.type.AADLPrimitive;
import ssac.aadlc.analysis.type.AADLSetType;
/**
* AADL : ExBasePatternSet
*
* @version 1.40 2010/02/19
*
* @since 1.30
*/
public class APrimExBasePatternSet extends AADLSetType implements AADLPrimitive
{
//------------------------------------------------------------
// Definitions
//------------------------------------------------------------
static public final APrimExBasePatternSet instance = new APrimExBasePatternSet();
//------------------------------------------------------------
// Fields
//------------------------------------------------------------
//------------------------------------------------------------
// Constructions
//------------------------------------------------------------
protected APrimExBasePatternSet() {
//super("ExBasePatternSet", exalge2.ExBasePatternSet.class, new APrimExBasePattern());
super("ExBasePatternSet", exalge2.ExBasePatternSet.class, APrimExBasePattern.instance);
}
//------------------------------------------------------------
// Public interfaces
//------------------------------------------------------------
}
| 36.153846 | 89 | 0.574894 |
0995a75d76f0d4bc9babcf7c01219f0c899402b9 | 162 | package com.cdc.test;
import com.cdc.layout.AbsoluteLayoutDemo;
public class Main {
public static void main(String[] args) {
new AbsoluteLayoutDemo();
}
}
| 14.727273 | 41 | 0.734568 |
bd33fd6227a955309b7178c44fc9b7ece845bc27 | 6,828 | /*
* This file is part of fabric-loom, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 FabricMC
*
* 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.fabricmc.loom.extension;
import java.util.List;
import java.util.function.Consumer;
import org.gradle.api.Action;
import org.gradle.api.NamedDomainObjectContainer;
import org.gradle.api.artifacts.Dependency;
import org.gradle.api.file.ConfigurableFileCollection;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.provider.ListProperty;
import org.gradle.api.provider.Property;
import org.gradle.api.provider.Provider;
import org.gradle.api.publish.maven.MavenPublication;
import net.fabricmc.loom.api.ForgeExtensionAPI;
import net.fabricmc.loom.api.LoomGradleExtensionAPI;
import net.fabricmc.loom.api.MixinExtensionAPI;
import net.fabricmc.loom.api.decompilers.LoomDecompiler;
import net.fabricmc.loom.api.decompilers.architectury.ArchitecturyLoomDecompiler;
import net.fabricmc.loom.api.mappings.layered.spec.LayeredMappingSpecBuilder;
import net.fabricmc.loom.configuration.ide.RunConfig;
import net.fabricmc.loom.configuration.ide.RunConfigSettings;
import net.fabricmc.loom.configuration.launch.LaunchProviderSettings;
import net.fabricmc.loom.configuration.processors.JarProcessor;
import net.fabricmc.loom.util.DeprecationHelper;
import net.fabricmc.loom.util.ModPlatform;
public class MinecraftGradleExtension implements LoomGradleExtensionAPI {
private final LoomGradleExtensionAPI parent;
private boolean deprecationReported = false;
public MinecraftGradleExtension(LoomGradleExtensionAPI parent) {
this.parent = parent;
}
private void reportDeprecation() {
if (!deprecationReported) {
getDeprecationHelper().replaceWithInLoom0_11("minecraft", "loom");
deprecationReported = true;
}
}
@Override
public DeprecationHelper getDeprecationHelper() {
return parent.getDeprecationHelper();
}
@Override
public RegularFileProperty getAccessWidenerPath() {
reportDeprecation();
return parent.getAccessWidenerPath();
}
@Override
public Property<Boolean> getShareRemapCaches() {
reportDeprecation();
return parent.getShareRemapCaches();
}
@Override
public ListProperty<LoomDecompiler> getGameDecompilers() {
reportDeprecation();
return parent.getGameDecompilers();
}
@Override
public ListProperty<JarProcessor> getGameJarProcessors() {
reportDeprecation();
return parent.getGameJarProcessors();
}
@Override
public ConfigurableFileCollection getLog4jConfigs() {
reportDeprecation();
return parent.getLog4jConfigs();
}
@Override
public Dependency layered(Action<LayeredMappingSpecBuilder> action) {
reportDeprecation();
return parent.layered(action);
}
@Override
public Property<Boolean> getRemapArchives() {
reportDeprecation();
return parent.getRemapArchives();
}
@Override
public void runs(Action<NamedDomainObjectContainer<RunConfigSettings>> action) {
reportDeprecation();
parent.runs(action);
}
@Override
public NamedDomainObjectContainer<RunConfigSettings> getRunConfigs() {
reportDeprecation();
return parent.getRunConfigs();
}
@Override
public void mixin(Action<MixinExtensionAPI> action) {
reportDeprecation();
parent.mixin(action);
}
@Override
public MixinExtensionAPI getMixin() {
reportDeprecation();
return parent.getMixin();
}
@Override
public Property<String> getCustomMinecraftManifest() {
reportDeprecation();
return parent.getCustomMinecraftManifest();
}
@Override
public Property<Boolean> getSetupRemappedVariants() {
reportDeprecation();
return parent.getSetupRemappedVariants();
}
@Override
public void disableDeprecatedPomGeneration(MavenPublication publication) {
reportDeprecation();
parent.disableDeprecatedPomGeneration(publication);
}
@Override
public String getModVersion() {
reportDeprecation();
throw new UnsupportedOperationException("Use loom extension");
}
@Override
public Property<Boolean> getEnableTransitiveAccessWideners() {
reportDeprecation();
throw new UnsupportedOperationException();
}
@Override
public Property<String> getIntermediaryUrl() {
reportDeprecation();
return parent.getIntermediaryUrl();
}
@Override
public ListProperty<ArchitecturyLoomDecompiler> getArchGameDecompilers() {
reportDeprecation();
return parent.getArchGameDecompilers();
}
@Override
public void silentMojangMappingsLicense() {
reportDeprecation();
parent.silentMojangMappingsLicense();
}
@Override
public boolean isSilentMojangMappingsLicenseEnabled() {
reportDeprecation();
return parent.isSilentMojangMappingsLicenseEnabled();
}
@Override
public Provider<ModPlatform> getPlatform() {
reportDeprecation();
return parent.getPlatform();
}
@Override
public void setGenerateSrgTiny(Boolean generateSrgTiny) {
reportDeprecation();
parent.setGenerateSrgTiny(generateSrgTiny);
}
@Override
public boolean shouldGenerateSrgTiny() {
reportDeprecation();
return parent.shouldGenerateSrgTiny();
}
@Override
public void launches(Action<NamedDomainObjectContainer<LaunchProviderSettings>> action) {
reportDeprecation();
parent.launches(action);
}
@Override
public NamedDomainObjectContainer<LaunchProviderSettings> getLaunchConfigs() {
reportDeprecation();
return parent.getLaunchConfigs();
}
@Override
public List<String> getTasksBeforeRun() {
reportDeprecation();
return parent.getTasksBeforeRun();
}
@Override
public List<Consumer<RunConfig>> getSettingsPostEdit() {
reportDeprecation();
return parent.getSettingsPostEdit();
}
@Override
public ForgeExtensionAPI getForge() {
reportDeprecation();
return parent.getForge();
}
@Override
public void forge(Action<ForgeExtensionAPI> action) {
reportDeprecation();
parent.forge(action);
}
}
| 27.643725 | 90 | 0.78471 |
daf70b7742e15e1af2453849caa8c449b86852cc | 803 | package com.pan.blog.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class FileUploadConfig extends WebMvcConfigurationSupport {
@Value("${web.upload-path}")
private String uploadPath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("images/**").addResourceLocations("file:" + this.uploadPath + "/images/");
registry.addResourceHandler("files/**").addResourceLocations("file:" + this.uploadPath + "/files/");
super.addResourceHandlers(registry);
}
}
| 38.238095 | 106 | 0.798257 |
05e5ac427541aa6d53d9dc5d92f818b64a135f4d | 892 | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.download.dialogs;
import androidx.annotation.IntDef;
/**
* Defines the selection in download later dialog. Used in histograms, don't reuse or remove items.
* Keep in sync with DownloadLaterDialogChoice in enums.xml.
*/
@IntDef({DownloadLaterDialogChoice.DOWNLOAD_NOW, DownloadLaterDialogChoice.ON_WIFI,
DownloadLaterDialogChoice.DOWNLOAD_LATER})
public @interface DownloadLaterDialogChoice {
/**
* Download will be started right away.
*/
int DOWNLOAD_NOW = 0;
/**
* Download will be started only on WIFI.
*/
int ON_WIFI = 1;
/**
* Download will be started in the future..
*/
int DOWNLOAD_LATER = 2;
int COUNT = 3;
}
| 28.774194 | 100 | 0.705157 |
cb5c4d90eaac893c9cd5ebe1e4ad99ab34fcb919 | 5,717 | /* Generated by camel build tools - do NOT edit this file! */
package org.apache.camel.component.redis;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.spi.GeneratedPropertyConfigurer;
import org.apache.camel.spi.PropertyConfigurerGetter;
import org.apache.camel.util.CaseInsensitiveMap;
import org.apache.camel.support.component.PropertyConfigurerSupport;
/**
* Generated by camel build tools - do NOT edit this file!
*/
@SuppressWarnings("unchecked")
public class RedisEndpointConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
private static final Map<String, Object> ALL_OPTIONS;
static {
Map<String, Object> map = new CaseInsensitiveMap();
map.put("host", java.lang.String.class);
map.put("port", java.lang.Integer.class);
map.put("channels", java.lang.String.class);
map.put("command", org.apache.camel.component.redis.Command.class);
map.put("connectionFactory", org.springframework.data.redis.connection.RedisConnectionFactory.class);
map.put("redisTemplate", org.springframework.data.redis.core.RedisTemplate.class);
map.put("serializer", org.springframework.data.redis.serializer.RedisSerializer.class);
map.put("bridgeErrorHandler", boolean.class);
map.put("exceptionHandler", org.apache.camel.spi.ExceptionHandler.class);
map.put("exchangePattern", org.apache.camel.ExchangePattern.class);
map.put("listenerContainer", org.springframework.data.redis.listener.RedisMessageListenerContainer.class);
map.put("lazyStartProducer", boolean.class);
map.put("basicPropertyBinding", boolean.class);
map.put("synchronous", boolean.class);
ALL_OPTIONS = map;
}
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
RedisEndpoint target = (RedisEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "basicpropertybinding":
case "basicPropertyBinding": target.setBasicPropertyBinding(property(camelContext, boolean.class, value)); return true;
case "bridgeerrorhandler":
case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true;
case "channels": target.getConfiguration().setChannels(property(camelContext, java.lang.String.class, value)); return true;
case "command": target.getConfiguration().setCommand(property(camelContext, org.apache.camel.component.redis.Command.class, value)); return true;
case "connectionfactory":
case "connectionFactory": target.getConfiguration().setConnectionFactory(property(camelContext, org.springframework.data.redis.connection.RedisConnectionFactory.class, value)); return true;
case "exceptionhandler":
case "exceptionHandler": target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value)); return true;
case "exchangepattern":
case "exchangePattern": target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
case "listenercontainer":
case "listenerContainer": target.getConfiguration().setListenerContainer(property(camelContext, org.springframework.data.redis.listener.RedisMessageListenerContainer.class, value)); return true;
case "redistemplate":
case "redisTemplate": target.getConfiguration().setRedisTemplate(property(camelContext, org.springframework.data.redis.core.RedisTemplate.class, value)); return true;
case "serializer": target.getConfiguration().setSerializer(property(camelContext, org.springframework.data.redis.serializer.RedisSerializer.class, value)); return true;
case "synchronous": target.setSynchronous(property(camelContext, boolean.class, value)); return true;
default: return false;
}
}
@Override
public Map<String, Object> getAllOptions(Object target) {
return ALL_OPTIONS;
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
RedisEndpoint target = (RedisEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "basicpropertybinding":
case "basicPropertyBinding": return target.isBasicPropertyBinding();
case "bridgeerrorhandler":
case "bridgeErrorHandler": return target.isBridgeErrorHandler();
case "channels": return target.getConfiguration().getChannels();
case "command": return target.getConfiguration().getCommand();
case "connectionfactory":
case "connectionFactory": return target.getConfiguration().getConnectionFactory();
case "exceptionhandler":
case "exceptionHandler": return target.getExceptionHandler();
case "exchangepattern":
case "exchangePattern": return target.getExchangePattern();
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
case "listenercontainer":
case "listenerContainer": return target.getConfiguration().getListenerContainer();
case "redistemplate":
case "redisTemplate": return target.getConfiguration().getRedisTemplate();
case "serializer": return target.getConfiguration().getSerializer();
case "synchronous": return target.isSynchronous();
default: return null;
}
}
}
| 57.17 | 202 | 0.730453 |
b9f65952c772fdb82ea981ca09cda627614296e6 | 141 | package org.min.watergap.common.exception;
/**
* 记录所有的异常信息
*
* @Create by metaX.h on 2022/2/14 23:28
*/
public class ErrorCode {
}
| 9.4 | 42 | 0.652482 |
e8afdcf4dd5f46f25ec972201d4ee9d477b679b5 | 2,758 | import javax.media.opengl.*;
import com.jogamp.opengl.util.*;
import java.nio.*;
public class BezierPatch extends Object3D{
private static final float ctrlpoints[][][] = new float[][][] {
/*
{ { -1.5f, -1.5f, 0.0f }, { -0.5f, -1.5f, 3.0f },
{ 0.5f, -1.5f, 3.0f }, { 1.5f, -1.5f, 0.0f } },
{ { -1.5f, -0.5f, 1.0f }, { -0.5f, -0.5f, 3.0f },
{ 0.5f, -0.5f, 3.0f }, { 1.5f, -0.5f, 1.0f } },
{ { -1.5f, 0.5f, 2.0f }, { -0.5f, 0.5f, 3.0f },
{ 0.5f, 0.5f, 3.0f }, { 1.5f, 0.5f, 2.0f } },
{ { -1.5f, 1.5f, -1.0f }, { -0.5f, 1.5f, 2.0f },
{ 0.5f, 1.5f, 3.0f }, { 1.5f, 1.5f, 0.0f } } };
*/
{ { -0.5f, 0.5f, 2.0f }, { -0.5f, 0.5f, 1.0f },
{ 0.5f, 0.5f, 0.0f }, { 0.5f, 0.2f, 0.8f } },
{ { -0.5f, -0.5f, 0.3f }, { -0.5f, -0.5f, 1.0f },
{ 0.5f, -0.5f, 0.0f }, { 0.5f, -0.5f, 0.3f } },
{ { -0.5f, -0.5f, 0.0f }, { -0.5f, -0.5f, 1.0f },
{ 0.5f, -1.5f, 1.0f }, { 0.5f, -0.5f, 0.0f } },
{ { -0.5f, 0.5f, -0.3f }, { -0.2f, 0.5f, 0.8f },
{ 0.5f, 0.5f, 1.0f }, { 0.5f, 0.5f, 0.0f } } };
// need float buffer instead of n-dimensional array above
private static final float[] ctrlpointsColor = new float[4*16];
private FloatBuffer ctrlpointsColorBuf;
private FloatBuffer ctrlpointsBuf =
FloatBuffer.allocate(ctrlpoints.length*ctrlpoints[0].length
*ctrlpoints[0][0].length);
{// SO copy 4x4x3 array above to float buffer
for (int i = 0; i < ctrlpoints.length; i++) {
// System.out.print(ctrlpoints.length+ " ");
for (int j = 0; j < ctrlpoints[0].length; j++) {
// System.out.println(ctrlpoints[0][0].length+" ");
for (int k = 0; k < ctrlpoints[0][0].length; k++) {
ctrlpointsBuf.put(ctrlpoints[i][j][k]);
System.out.print(ctrlpoints[i][j][k] + " ");
}
System.out.println();
}
}
// THEN rewind it before use
ctrlpointsBuf.rewind();
for (int i = 0; i < ctrlpointsColor.length/4; i++) {
ctrlpointsColor[i*4] = 1f;
ctrlpointsColor[i*4+1] = 1f;
ctrlpointsColor[i*4+2] = 0f;
ctrlpointsColor[i*4+3] = 1f;
}
ctrlpointsColorBuf = FloatBuffer.wrap(ctrlpointsColor);
}
public void init(GL2 gl, PMVMatrix mat, int programID){
initCommon(mat, programID);
gl.glEnable(GL2.GL_MAP2_VERTEX_3);
// gl.glEnable(GL2.GL_MAP2_COLOR_4);
gl.glEnable(GL2.GL_AUTO_NORMAL);
gl.glEnable(GL2.GL_NORMALIZE);
}
public void display(GL2 gl, PMVMatrix mats){
gl.glMap2f(GL2.GL_MAP2_VERTEX_3, 0, 1, 3, 4, 0, 1, 12, 4, ctrlpointsBuf);
//gl.glMap2f(GL2.GL_MAP2_COLOR_4, 0, 1, 4, 2, 0, 1, 16, 2,ctrlpointsColorBuf);
gl.glMapGrid2f(30, 0.0f, 0.2f, 30, 0.0f, 1.0f);
gl.glEvalMesh2(GL2.GL_FILL, 0, 30, 0, 30);
}
} | 39.4 | 82 | 0.536258 |
2a420640292d6d3f24099cdb5039f102c80e8c8a | 1,721 | package org.dew.fhir.model;
import java.io.Serializable;
/**
*
* The MeasureReport resource contains the results of the calculation of a measure; and optionally a reference to the resources involved in that calculation.
*
* @see <a href="https://www.hl7.org/fhir">MeasureReport_Stratum</a>
*/
public
class MeasureReportStratum extends BackboneElement implements Serializable
{
private static final long serialVersionUID = 1L;
protected MeasureReportComponent[] component;
protected CodeableConcept value;
protected Quantity measureScore;
protected MeasureReportPopulation1[] population;
public MeasureReportStratum()
{
}
public MeasureReportComponent[] getComponent() {
return component;
}
public void setComponent(MeasureReportComponent[] component) {
this.component = component;
}
public CodeableConcept getValue() {
return value;
}
public void setValue(CodeableConcept value) {
this.value = value;
}
public Quantity getMeasureScore() {
return measureScore;
}
public void setMeasureScore(Quantity measureScore) {
this.measureScore = measureScore;
}
public MeasureReportPopulation1[] getPopulation() {
return population;
}
public void setPopulation(MeasureReportPopulation1[] population) {
this.population = population;
}
@Override
public boolean equals(Object object) {
if(object instanceof MeasureReportStratum) {
return this.hashCode() == object.hashCode();
}
return false;
}
@Override
public int hashCode() {
if(id == null) return 0;
return id.hashCode();
}
@Override
public String toString() {
return "MeasureReportStratum(" + id + ")";
}
}
| 22.644737 | 157 | 0.70889 |
a275435efd28bd1c7edb5e66ba7453330be58035 | 3,593 | package com.zizhizhan.legacies.lang;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import lombok.extern.slf4j.Slf4j;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
public class PrintStreamTests {
public static void main(String[] args) throws FileNotFoundException {
System.out.println(Pattern.matches("^[.\\w]+(Exception|Error)\\:.+", "java.lang.RuntimeException: " +
"java.lang.reflect.UndeclaredThrowableException"));
PrintStream ps = new MyPrintStream(new FileOutputStream("/tmp/test.txt"));
Throwable tx = null;
try {
a();
} catch (Throwable t) {
t.printStackTrace(ps);
tx = t;
}
ps.println("Hello World");
ps.println("You");
ps.println(tx);
}
public static void a() throws Exception {
throw new RuntimeException("Unknow exception");
//b();
}
public static void b() throws Exception {
try{
c();
}catch(Exception e){
throw new RuntimeException(e);
}
}
public static void c() throws Exception {
try{
d();
}catch(Exception e){
throw new UndeclaredThrowableException(e);
}
}
public static void d() throws Exception {
throw new RuntimeException();
}
public static Document string2Document(String xmlContent) throws Exception
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xmlContent)));
return doc;
}
@Slf4j
private static class MyPrintStream extends PrintStream {
private int count;
private final static String[] THROWABLE_EXPRESSION = {
"^[.\\w]+(Exception|Error)(\\:.+)?",
"^at\\s[^(]+\\([^:]+\\:\\d+\\)$",
"^Caused\\sby\\:\\s*.+?(Exception|Error)(\\:.+)?$",
"^\\.\\.\\.\\s*\\d+\\s*more$"
};
private AtomicBoolean m_logThrowableMode = new AtomicBoolean();
public void println(Object o){
if(o instanceof Throwable){
m_logThrowableMode.set(true);
log.error(getThrowableString((Throwable)o));
}
super.println(o);
}
public void write(byte[] buffer, int offset, int length) {
String message = new String(buffer, offset, length);
message = message.trim();
if ((message.length() > 0) && !".".equalsIgnoreCase(message)) {
if(!isThrowableString(message)){
log.error(++count + ":" + message);
m_logThrowableMode.compareAndSet(true, false);
}
}
super.write(buffer, offset, length);
}
public MyPrintStream(OutputStream out) {
super(out);
}
private boolean isThrowableString(String s){
if(!m_logThrowableMode.get()){
return false;
}
boolean flag = false;
for(String regex : THROWABLE_EXPRESSION){
if(Pattern.matches(regex, s)){
flag = true;
break;
}
}
return flag;
}
public String getThrowableString(Throwable throwable) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
throwable.printStackTrace(pw);
pw.flush();
return sw.toString();
}
}
}
| 25.125874 | 104 | 0.655719 |
dc94b2a5f9fc9169dcfd4cd1004df3b44905c31f | 48 | package com.github.shoothzj.pf.producer.common;
| 24 | 47 | 0.833333 |
412d955cef92de8e3091a473d76edb7babcb3d24 | 1,492 | /*
* 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.nifi.util;
import org.apache.nifi.web.api.dto.PortDTO;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class FlowInfo {
private final String rootGroupId;
private final List<PortDTO> ports;
public FlowInfo(final String rootGroupId, final List<PortDTO> ports) {
this.rootGroupId = rootGroupId;
this.ports = (ports == null ? Collections.unmodifiableList(Collections.EMPTY_LIST) :
Collections.unmodifiableList(new ArrayList<>(ports)) );
}
public String getRootGroupId() {
return rootGroupId;
}
public List<PortDTO> getPorts() {
return ports;
}
}
| 32.434783 | 92 | 0.723861 |
eb5d1793344b7f76ce9f1e41cd533adcdf7e7be5 | 406 | /*
* Copyright 2014 Guidewire Software, Inc.
*/
package gw.lang.function;
public abstract class Procedure0 extends AbstractBlock implements IProcedure0 {
public Object invokeWithArgs(Object[] args) {
if(args.length != 0) {
throw new IllegalArgumentException("You must pass 0 args to this block, but you passed" + args.length);
} else {
invoke();
return null;
}
}
}
| 21.368421 | 109 | 0.674877 |
9b78074996c005727bd7e35605441beb5bcdb307 | 1,244 | package it.unipi.hadoop.Rank;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import java.io.IOException;
public class RankReducer extends Reducer<LongWritable, RankWritable, LongWritable, RankWritable> {
//private Text result = new Text();
private final RankWritable result = new RankWritable();
private double alpha;
private long N;
private boolean isFirst;
@Override
public void setup(Context ctx){
alpha = ctx.getConfiguration().getDouble("alpha",0.1);
N = ctx.getConfiguration().getLong("Nodes", 1000000);
}
@Override
public void reduce(LongWritable key, Iterable<RankWritable> list, Context ctx) throws IOException, InterruptedException {
double res = 0, rank;
RankNode n = new RankNode();
for(RankWritable value : list){
if(value.isNode()){
n = value.getNode();
}else{
res += value.getProbability();
}
}
res = res * (1 - alpha) + ((double)1 / N) * alpha;
n.setRank(res);
result.setNode(n);
ctx.write(key, result);
}
}
| 31.1 | 125 | 0.630225 |
1f1b3b91a566ac2588e509d702fd5b8fc7695620 | 5,943 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.02.25 at 04:54:23 PM PST
//
package org.pesc.core.coremain.v1_14;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* Ref. Graduate Level Indiicators Type in Core Componenets
*
* <p>Java class for GraduateLevelCreditAllocationType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="GraduateLevelCreditAllocationType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="HoursAppliedOtherProgram" type="{urn:org:pesc:core:CoreMain:v1.14.0}HoursAppliedOtherProgramType" minOccurs="0"/>
* <element name="HoursAppliedOtherProgramType" type="{urn:org:pesc:core:CoreMain:v1.14.0}HoursAppliedOtherProgramTypeType" minOccurs="0"/>
* <element name="SpecialProgramAdmissionIndicator" type="{urn:org:pesc:core:CoreMain:v1.14.0}SpecialProgramAdmissionIndicatorType" minOccurs="0"/>
* <element name="UndergradHoursInGradDegree" type="{urn:org:pesc:core:CoreMain:v1.14.0}UndergradHoursInGradDegreeType" minOccurs="0"/>
* <element name="NoteMessage" type="{urn:org:pesc:core:CoreMain:v1.14.0}NoteMessageType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "GraduateLevelCreditAllocationType", propOrder = {
"hoursAppliedOtherProgram",
"hoursAppliedOtherProgramType",
"specialProgramAdmissionIndicator",
"undergradHoursInGradDegree",
"noteMessage"
})
public class GraduateLevelCreditAllocationType {
@XmlElement(name = "HoursAppliedOtherProgram")
protected BigDecimal hoursAppliedOtherProgram;
@XmlElement(name = "HoursAppliedOtherProgramType")
protected String hoursAppliedOtherProgramType;
@XmlElement(name = "SpecialProgramAdmissionIndicator")
protected String specialProgramAdmissionIndicator;
@XmlElement(name = "UndergradHoursInGradDegree")
protected BigDecimal undergradHoursInGradDegree;
@XmlElement(name = "NoteMessage")
protected List<String> noteMessage;
/**
* Gets the value of the hoursAppliedOtherProgram property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getHoursAppliedOtherProgram() {
return hoursAppliedOtherProgram;
}
/**
* Sets the value of the hoursAppliedOtherProgram property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setHoursAppliedOtherProgram(BigDecimal value) {
this.hoursAppliedOtherProgram = value;
}
/**
* Gets the value of the hoursAppliedOtherProgramType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHoursAppliedOtherProgramType() {
return hoursAppliedOtherProgramType;
}
/**
* Sets the value of the hoursAppliedOtherProgramType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHoursAppliedOtherProgramType(String value) {
this.hoursAppliedOtherProgramType = value;
}
/**
* Gets the value of the specialProgramAdmissionIndicator property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSpecialProgramAdmissionIndicator() {
return specialProgramAdmissionIndicator;
}
/**
* Sets the value of the specialProgramAdmissionIndicator property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSpecialProgramAdmissionIndicator(String value) {
this.specialProgramAdmissionIndicator = value;
}
/**
* Gets the value of the undergradHoursInGradDegree property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getUndergradHoursInGradDegree() {
return undergradHoursInGradDegree;
}
/**
* Sets the value of the undergradHoursInGradDegree property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setUndergradHoursInGradDegree(BigDecimal value) {
this.undergradHoursInGradDegree = value;
}
/**
* Gets the value of the noteMessage property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the noteMessage property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getNoteMessage().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getNoteMessage() {
if (noteMessage == null) {
noteMessage = new ArrayList<String>();
}
return this.noteMessage;
}
}
| 30.953125 | 158 | 0.656739 |
6d40830dbbe85ed8f13d739ad3492f0b178462ab | 7,060 | /**
* IUT de Nice / Departement informatique / Module APO-Java
* Annee 2009_2010 - Package SWING
*
* @Edition A : Cours_10
*
* @version 1.0.0 :
*
* version initiale
*
* @version 1.1.0 :
*
* ajout de la possibilite d'ajout de texte ; ajout
* de la possibilite de retrait de texte ; ajout de
* gestion de bordure ;
*
* @version 1.2.0
*
* ajout d'un methode controlant la presence d'un
* texte dans une cellule
*/
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.BorderFactory;
/**
* Element de la partition d'une mosaique generique
*
* @author Alain Thuaire, Charles Fouco, Cedric Hulin
* @version 1.2.0
*/
public class CelluleG extends PanneauG {
/**
* Hamecon du panneau parent
*
* @since 1.0.0
*/
private Object mosaique;
/**
* Position de la cellule dans le panneau
*
* @since 1.0.0
*/
private Dimension position;
/**
* Etat de la cellule
*
* @since 1.0.0
*/
private boolean etatCellule;
/**
* Demons attacher a la cellule
*
* @since 1.0.0
*/
private Object[] demons;
/**
* Constructeur normal
*
* @param hamecon
* @param config
* @param position
* @since 1.1.0
*/
public CelluleG(Object hamecon, Object config, Dimension position) {
super(hamecon, config);
// Controler la validite des parametres
//
if (hamecon == null) return;
if (config == null) return;
if (position == null) return;
// Memoriser les attributs transmis par parametre
//
mosaique = hamecon;
this.position = position;
// Fixer l'etat par defaut de la cellule
//
etatCellule = false;
// Bordure par defaut
//
setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLoweredBevelBorder(), BorderFactory.createMatteBorder(3, 3, 0, 0, Color.black)));
// Ajouter le panneau sous jacent au panneau
// principal
//
((PanneauG) mosaique).add(this);
}
/**
* Obtention de la position de la cellule
*
* @return position
* @since 1.0.0
*/
public Dimension obtenirPosition() {
return position;
}
/**
* Obtention du chemin de l'image
*
* @return chemin
* @since 1.0.0
*/
public String obtenirCheminImage() {
return super.obtenirCheminImage();
}
/**
* Obtention du texte faisant office de titre
*
* @return titre
* @since 1.0.0
*/
public String obtenirTexteTitre() {
return super.obtenirTexteTitre();
}
/**
* Obtention de la couleur du titre
*
* @return couleur
* @since 1.0.0
*/
public Color obtenirCouleurTitre() {
return super.obtenirCouleurTitre();
}
/**
* Obtention de la police du titre
*
* @return police
* @since 1.0.0
*/
public Font obtenirPoliceTitre() {
return super.obtenirPoliceTitre();
}
/**
* Obtention de l'etat de la cellule
*
* @return etat
* @since 1.0.0
*/
public boolean obtenirEtat() {
return etatCellule;
}
/**
* Obtention de la totalite des demons de la cellule
*
* @return demons
* @since 1.0.0
*/
public Object[] obtenirDemons() {
return demons;
}
/**
* Modification de l'etat de la cellule
*
* @param etat
* @since 1.0.0
*/
public void fixerEtat(boolean etat) {
etatCellule = etat;
}
/**
* Ajout d'une image a une cellule
*
* @param cheminImage
* @since 1.0.0
*/
public void ajouterImage(String cheminImage) {
// Controler la validite du parametre
//
if (cheminImage == null) return;
// Ajouter l'image au panneau sous jacent
//
super.ajouterImage(cheminImage);
}
/**
* Retrait de l'image d'une cellule
*
* @since 1.0.0
*/
public void retirerImage() {
super.retirerImage();
}
/**
* Ajout d'un texte a une cellule
*
* @param texte
* @param couleur
* @param police
* @return flag de reussite
* @since 1.1.0
*/
public boolean ajouterTexte(String texte, Color couleur, Font police) {
// Controler la validite des parametres
//
if (texte == null) return false;
if (couleur == null) return false;
if (police == null) return false;
return super.ajouterTitre(texte, couleur, police);
}
/**
* Retrait du texte d'une cellule
*
* @since 1.1.0
*/
public void retirerTexte() {
super.retirerTitre();
}
/**
* Ajout d'un demon a une cellule
*
* @return flag reussite
* @since 1.0.0
*/
public boolean _ajouterDemon() {
return true;
}
/**
* Retrait d'un demon d'une cellule
*
* @return flag reussite
* @since 1.0.0
*/
public boolean _retirerDemon() {
return true;
}
/**
* Controle la presence d'un demon sur une cellule
*
* @return flag de presence
* @since 1.0.0
*/
public boolean _presenceDemon() {
if (demons.length != 0) return true;
return false;
}
/**
* Controle la presence d'un texte dans une cellule
*
* @return
* @since 1.2.0
*/
public boolean presenceTexte() {
return super.presenceTitre();
}
/**
* Ajout d'une image a une cellule
*
* @param cheminImage
* @since 1.3.0
*/
public void ajouterImage(String cheminImage, int index, int decalageEntreImages, int decalageHauteur, int decalageCoter) {
// Controler la validite du parametre
//
if (cheminImage == null) return;
// Ajouter l'image au panneau sous jacent
//
super.ajouterImage(cheminImage, index, decalageEntreImages, decalageHauteur, decalageCoter);
}
/**
* Modifier le nombre d'images de la cellule
*
* @param nombreImages
*/
public boolean modifierNombreImages(int nombreImages) {
// Verifier la validite du parametre
//
if (nombreImages <= 0) return false;
super.modifierNombreImages(nombreImages);
return true;
}
} | 22.847896 | 155 | 0.512465 |
7294373c920eaf538a37f4fe13eaa0325264605f | 2,713 | package com.sequenceiq.freeipa.service.polling.usersync;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.sequenceiq.cloudbreak.common.exception.CloudbreakServiceException;
import com.sequenceiq.cloudbreak.polling.StatusCheckerTask;
import com.sequenceiq.sdx.api.endpoint.SdxEndpoint;
import com.sequenceiq.sdx.api.model.RangerCloudIdentitySyncStatus;
@Component
public class CloudIdSyncStatusListenerTask implements StatusCheckerTask<CloudIdSyncPollerObject> {
private static final Logger LOGGER = LoggerFactory.getLogger(CloudIdSyncStatusListenerTask.class);
@Inject
private SdxEndpoint sdxEndpoint;
@Override
public boolean checkStatus(CloudIdSyncPollerObject pollerObject) {
RangerCloudIdentitySyncStatus syncStatus = sdxEndpoint.getRangerCloudIdentitySyncStatus(pollerObject.getEnvironmentCrn(), pollerObject.getCommandId());
LOGGER.info("syncStatus = {}", syncStatus);
switch (syncStatus.getState()) {
case SUCCESS:
LOGGER.info("Successfully synced cloud identity, envCrn = {}", pollerObject.getEnvironmentCrn());
return true;
case NOT_APPLICABLE:
LOGGER.info("Cloud identity sync not applicable, envCrn = {}", pollerObject.getEnvironmentCrn());
return true;
case FAILED:
LOGGER.error("Failed to sync cloud identity, envCrn = {}", pollerObject.getEnvironmentCrn());
throw new CloudbreakServiceException("Failed to sync cloud identity");
case ACTIVE:
LOGGER.info("Sync is still in progress");
return false;
default:
LOGGER.error("Encountered unknown cloud identity sync state");
throw new CloudbreakServiceException("Failed to sync cloud identity");
}
}
@Override
public void handleTimeout(CloudIdSyncPollerObject pollerObject) {
String message = String.format("Operation timed out. Failed to sync cloud identity for environment = %s.", pollerObject.getEnvironmentCrn());
throw new CloudbreakServiceException(message);
}
@Override
public String successMessage(CloudIdSyncPollerObject pollerObject) {
return String.format("Successfully synced cloud identity for envCrn = %s", pollerObject.getEnvironmentCrn());
}
@Override
public boolean exitPolling(CloudIdSyncPollerObject pollerObject) {
return false;
}
@Override
public void handleException(Exception e) {
throw new CloudbreakServiceException("Failed to sync cloud identity", e);
}
}
| 40.492537 | 159 | 0.711021 |
d57b8023ff3302df8448734459e49c2a46384e3f | 4,648 | package com.example.yueguo.myhw9;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.view.*;
import android.app.*;
/**
* Created by YueGuo on 16/11/29.
*/
public class DisplayCommDetail extends AppCompatActivity {
private String cmark = "1";
private ImageView commstar;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//actionBar.setDisplayHomeAsUpEnabled(true);
//getActionBar().setDisplayHomeAsUpEnabled(true);
return true;
//return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.comm_detail);
Intent intent = getIntent();
SharedPreferences favcommdetail = getSharedPreferences("commdata", Context.MODE_PRIVATE);
final String commid = intent.getStringExtra("commid");
TextView text = (TextView)findViewById(R.id.comm_id);
text.setText(commid);
final String commname = intent.getStringExtra("commname");
TextView text1 = (TextView)findViewById(R.id.comm_name);
text1.setText(commname);
final String commchamber = intent.getStringExtra("commchamber");
TextView text2 = (TextView)findViewById(R.id.comm_chamber);
text2.setText(commchamber);
//Log.d("guoyue",commchamber);
ImageView image = (ImageView)findViewById(R.id.comm_chamberimage);
if(commchamber == "House"){
image.setImageDrawable(getResources().getDrawable(R.drawable.h));
}else{
image.setImageDrawable(getResources().getDrawable(R.drawable.sv));
}
final String commparent = intent.getStringExtra("commparent");
TextView text3 = (TextView)findViewById(R.id.comm_parent);
text3.setText(commparent);
final String commcontact = intent.getStringExtra("commcontact");
TextView text4 = (TextView)findViewById(R.id.comm_contact);
text4.setText(commcontact);
final String commoffice = intent.getStringExtra("commoffice");
TextView text5 = (TextView)findViewById(R.id.comm_office);
text5.setText(commoffice);
commstar = (ImageView)findViewById(R.id.comm_star);
String commID = favcommdetail.getString("commid","");
if(commID.equals(commid)){
commstar.setImageDrawable(getResources().getDrawable(R.drawable.fav_selected));
commstar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
commstar.setImageDrawable(getResources().getDrawable(R.drawable.fav));
SharedPreferences.Editor prefc = getSharedPreferences("commdata",MODE_PRIVATE).edit();
prefc.clear();
prefc.commit();
}
});
}else{
commstar.setImageDrawable(getResources().getDrawable(R.drawable.fav));
commstar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
cmark = "2";
commstar.setImageDrawable(getResources().getDrawable(R.drawable.fav_selected));
SharedPreferences.Editor ceditor = getSharedPreferences("commdata", MODE_PRIVATE).edit();
ceditor.putString("commid",commid);
ceditor.putString("commname",commname);
ceditor.putString("commchamber",commchamber);
ceditor.putString("commparent",commparent);
ceditor.putString("commcontact",commcontact);
ceditor.putString("commoffice",commoffice);
ceditor.commit();
}
});
}
}
}
| 36.598425 | 109 | 0.638769 |
e2ed694b79ffee19c2017e5a03eacee4a092765b | 314 | package com.example.chenpan.library.model.interfaces;
import com.example.chenpan.library.holder.StringHolder;
/**
* Created by mikepenz on 03.02.15.
*/
public interface Nameable<T> {
T withName(String name);
T withName(int nameRes);
T withName(StringHolder name);
StringHolder getName();
}
| 17.444444 | 55 | 0.716561 |
a6744045d3a982082eacd0d758dfa3ff4ad9e0ad | 9,393 | /*-
* ============LICENSE_START=======================================================
* openECOMP : SDN-C
* ================================================================================
* Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights
* reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.onap.ccsdk.sli.northbound.dmaapclient;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* java.net based client to build message router consumers
*/
public class MessageRouterHttpClientJdk implements SdncDmaapConsumer {
private static final Logger Log = LoggerFactory.getLogger(MessageRouterHttpClientJdk.class);
protected Boolean isReady = false;
protected Boolean isRunning = false;
protected URL url;
protected Integer fetchPause;
protected Properties properties;
protected final String DEFAULT_CONNECT_TIMEOUT = "30000";
protected final String DEFAULT_READ_TIMEOUT = "180000";
protected final String DEFAULT_TIMEOUT_QUERY_PARAM_VALUE = "15000";
protected final String DEFAULT_LIMIT = null;
protected final String DEFAULT_FETCH_PAUSE = "5000";
private String authorizationString;
protected Integer connectTimeout;
protected Integer readTimeout;
protected String topic;
public MessageRouterHttpClientJdk() {}
@Override
public void run() {
if (isReady) {
isRunning = true;
while (isRunning) {
HttpURLConnection httpUrlConnection = null;
try {
httpUrlConnection = buildHttpURLConnection();
httpUrlConnection.connect();
int status = httpUrlConnection.getResponseCode();
Log.info("GET " + url + " returned http status " + status);
if (status < 300) {
BufferedReader br =
new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
String responseBody = sb.toString();
if (responseBody.contains("{")) {
// Get rid of opening [" entity =
responseBody = responseBody.substring(2);
// Get rid of closing "]
responseBody = responseBody.substring(0, responseBody.length() - 2);
// Split the json array into individual elements to process
for (String message : responseBody.split("\",\"")) {
// unescape the json
message = message.replace("\\\"", "\"");
// Topic names cannot contain periods
processMsg(message);
}
} else {
Log.info("Entity doesn't appear to contain JSON elements, logging body");
Log.info(responseBody);
}
}
} catch (Exception e) {
Log.error("GET " + url + " failed.", e);
} finally {
if (httpUrlConnection != null) {
httpUrlConnection.disconnect();
}
Log.info("Pausing " + fetchPause + " milliseconds before fetching from " + url + " again.");
try {
Thread.sleep(fetchPause);
} catch (InterruptedException e) {
Log.error("Could not sleep thread", e);
Thread.currentThread().interrupt();
}
}
}
}
}
@Override
public void init(Properties baseProperties, String consumerPropertiesPath) {
try {
baseProperties.load(new FileInputStream(new File(consumerPropertiesPath)));
processProperties(baseProperties);
} catch (FileNotFoundException e) {
Log.error("FileNotFoundException while reading consumer properties", e);
} catch (IOException e) {
Log.error("IOException while reading consumer properties", e);
}
}
protected void processProperties(Properties properties) throws MalformedURLException {
this.properties = properties;
String username = properties.getProperty("username");
String password = properties.getProperty("password");
topic = properties.getProperty("topic");
String group = properties.getProperty("group");
String host = properties.getProperty("host");
String id = properties.getProperty("id");
String filter = properties.getProperty("filter");
if (filter != null) {
if (filter.length() > 0) {
try {
filter = URLEncoder.encode(filter, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
Log.error("Couldn't encode filter string", e);
}
} else {
filter = null;
}
}
String limitString = properties.getProperty("limit", DEFAULT_LIMIT);
Integer limit = null;
if (limitString != null && limitString.length() > 0) {
limit = Integer.valueOf(limitString);
}
Integer timeoutQueryParamValue =
Integer.valueOf(properties.getProperty("timeout", DEFAULT_TIMEOUT_QUERY_PARAM_VALUE));
connectTimeout = Integer.valueOf(properties.getProperty("connectTimeoutSeconds", DEFAULT_CONNECT_TIMEOUT));
readTimeout = Integer.valueOf(properties.getProperty("readTimeoutMinutes", DEFAULT_READ_TIMEOUT));
if (username != null && password != null && username.length() > 0 && password.length() > 0) {
authorizationString = buildAuthorizationString(username, password);
}
String urlString = buildlUrlString(topic, group, id, host, timeoutQueryParamValue, limit, filter);
this.url = new URL(urlString);
this.fetchPause = Integer.valueOf(properties.getProperty("fetchPause", DEFAULT_FETCH_PAUSE));
this.isReady = true;
}
public void processMsg(String msg) {
Log.info(msg);
}
protected String buildAuthorizationString(String userName, String password) {
String basicAuthString = userName + ":" + password;
basicAuthString = Base64.getEncoder().encodeToString(basicAuthString.getBytes());
return "Basic " + basicAuthString;
}
protected String buildlUrlString(String topic, String consumerGroup, String consumerId, String host,
Integer timeout, Integer limit, String filter) {
StringBuilder sb = new StringBuilder();
sb.append("http://" + host + "/events/" + topic + "/" + consumerGroup + "/" + consumerId);
sb.append("?timeout=" + timeout);
if (limit != null) {
sb.append("&limit=" + limit);
}
if (filter != null) {
sb.append("&filter=" + filter);
}
return sb.toString();
}
@Override
public boolean isReady() {
return isReady;
}
@Override
public boolean isRunning() {
return isRunning;
}
protected HttpURLConnection buildHttpURLConnection() throws IOException {
HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
if (authorizationString != null) {
httpUrlConnection.setRequestProperty("Authorization", authorizationString);
}
httpUrlConnection.setRequestMethod("GET");
httpUrlConnection.setRequestProperty("Accept", "application/json");
httpUrlConnection.setUseCaches(false);
httpUrlConnection.setConnectTimeout(connectTimeout);
httpUrlConnection.setReadTimeout(readTimeout);
return httpUrlConnection;
}
}
| 42.121076 | 115 | 0.578729 |
158ccf6620dce06b4ae4029efad82517196549bd | 4,314 | package ru.intertrust.cm.globalcache.api;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import ru.intertrust.cm.core.business.api.dto.Filter;
import ru.intertrust.cm.core.business.api.dto.SortOrder;
import ru.intertrust.cm.core.business.api.dto.Value;
import ru.intertrust.cm.core.business.api.dto.util.ListValue;
import ru.intertrust.cm.core.dao.access.UserSubject;
import ru.intertrust.cm.core.dao.api.DomainEntitiesCloner;
/**
* @author Denis Mitavskiy Date: 13.08.2015 Time: 17:06
*/
public class NamedCollectionSubKey extends CollectionSubKey {
public final Set<? extends Filter> filterValues;
public final SortOrder sortOrder;
public NamedCollectionSubKey(UserSubject subject, List<? extends Filter> filterValues, SortOrder sortOrder, int offset, int limit) {
super(subject, offset, limit);
this.filterValues = filterValues == null ? null : new HashSet<>(filterValues);
this.sortOrder = sortOrder;
}
public NamedCollectionSubKey(UserSubject subject, Set<? extends Filter> filterValues, SortOrder sortOrder, int offset, int limit) {
super(subject, offset, limit);
this.filterValues = filterValues;
this.sortOrder = sortOrder;
}
@Override
public int getKeyEntriesQty() {
if (filterValues == null) {
return 0;
}
int qty = 0;
for (Filter filter : filterValues) {
if (filter != null) {
final Collection<List<Value>> values = filter.getParameterMap().values();
if (values == null || values.isEmpty()) {
++qty;
continue;
}
for (List<Value> value : values) {
if (value != null) {
if (value instanceof ListValue) {
ListValue listValue = (ListValue) value;
List<Value<?>> listValueValues = listValue.getUnmodifiableValuesList();
if (listValueValues != null) {
qty += listValueValues.size();
} else {
++qty;
}
} else {
++qty;
}
} else {
++qty;
}
}
} else {
++qty;
}
}
return qty;
}
@Override
public CollectionSubKey getCopy(DomainEntitiesCloner cloner) {
final HashSet<Filter> filtersClone;
if (filterValues == null) {
filtersClone = null;
} else {
filtersClone = new HashSet<>(filterValues.size() * 3 / 2);
for (Filter filter : filterValues) {
filtersClone.add(cloner.fastCloneFilter(filter));
}
}
return new NamedCollectionSubKey(subject, filtersClone, cloner.fastCloneSortOrder(sortOrder), offset, limit);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || !(o instanceof NamedCollectionSubKey)) {
return false;
}
NamedCollectionSubKey that = (NamedCollectionSubKey) o;
if (offset != that.offset) {
return false;
}
if (limit != that.limit) {
return false;
}
if (filterValues != null ? !filterValues.equals(that.filterValues) : that.filterValues != null) {
return false;
}
if (sortOrder != null ? !sortOrder.equals(that.sortOrder) : that.sortOrder != null) {
return false;
}
if (subject != null ? !subject.equals(that.subject) : that.subject != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = filterValues != null ? filterValues.hashCode() : 0;
result = 31 * result + (sortOrder != null ? sortOrder.hashCode() : 0);
result = 31 * result + (subject != null ? subject.hashCode() : 0);
result = 31 * result + offset;
result = 31 * result + limit;
return result;
}
}
| 34.512 | 136 | 0.544506 |
b1e117bea0706841dcb3f0b992bf9de3253a908d | 216 | package org.xsierra.translator;
import java.util.Locale;
import java.util.Properties;
public interface PropertiesTranslator {
Properties translate(Properties properties, Locale source, Locale target);
}
| 21.6 | 76 | 0.782407 |
1fe118288c167fc5a3d3c94a7ffba57d675ba741 | 543 | package com.example.componentlibs.base;
@Deprecated
public class Plugins {
public static final String PLUGIN_UP = "com.example.upcomponent.appInject.UpIPlugin";
public static final String PLUGIN_LIB = "com.example.componentlibs.base.LibIPlugin";
public static final String PLUGIN_SERVICE = "com.example.componentservice.base.ServiceIPlugin";
public static final String PLUGIN_GAME = "com.example.gamecomponent.appInject.GameIPlugin";
public static final String PLUGIN_ME = "com.example.mecomponent.applicatio.MeIPlugin";
}
| 54.3 | 99 | 0.797422 |
408a4b94f62f564041e22de05507acbeca6fc9a7 | 6,280 | // ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.daikon.multitenant.context;
import java.lang.reflect.Constructor;
import java.lang.reflect.UndeclaredThrowableException;
/**
* Associates a given {@link TenancyContext} with the current execution.
* <p>
* This class provides a series of static methods that delegate to an instance of {@link TenancyContextHolderStrategy}.
* The purpose of the class is to provide a convenient way to specify the strategy that should be used for a given JVM.
* This is a JVM-wide setting, since everything in this class is <code>static</code> to facilitate ease of use in
* calling code.
* <p>
* To specify which strategy should be used, you must provide a mode setting. A mode
* setting is one of the three valid <code>MODE_</code> settings defined as
* <code>static final</code> fields, or a fully qualified classname to a concrete
* implementation of
* {@link TenancyContextHolderStrategy} that provides a public no-argument constructor.
* <p>
* There are two ways to specify the desired strategy mode <code>String</code>. The first
* is to specify it via the system property keyed on {@link #SYSTEM_PROPERTY}. The second
* is to call {@link #setStrategyName(String)} before using the class. If neither approach
* is used, the class will default to using {@link #MODE_THREADLOCAL}, which is backwards
* compatible, has fewer JVM incompatibilities and is appropriate on servers (whereas
* {@link #MODE_GLOBAL} is definitely inappropriate for server use).
*
* @author Clint Morgan (Tasktop Technologies Inc.)
*
*/
public class TenancyContextHolder {
public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL";
public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL";
public static final String MODE_GLOBAL = "MODE_GLOBAL";
public static final String SYSTEM_PROPERTY = "talend.tenancy.strategy";
private static TenancyContextHolderStrategy strategy = new ThreadLocalTenancyContextHolderStrategy();
private static String strategyName = System.getProperty(SYSTEM_PROPERTY);
private static int initializeCount;
static {
initialize();
}
/**
* Explicitly clear the tenacy context.
*
*/
public static void clearContext() {
strategy.clearContext();
}
/**
* Obtain the current <code>TenancyContext</code>.
*
* @return the tenancy context (never <code>null</code>)
*/
public static TenancyContext getContext() {
return strategy.getContext();
}
/**
* Associates a new <code>TenancyContext</code> with the current context of execution.
*
* @param context
* the new <code>TenancyContext</code> (may not be <code>null</code>)
*/
public static void setContext(TenancyContext context) {
strategy.setContext(context);
}
/**
* Delegates the creation of a new, empty context to the configured strategy.
*/
public static TenancyContext createEmptyContext() {
return strategy.createEmptyContext();
}
/**
* Allows retrieval of the context strategy.
*
* @return the configured strategy for storing the tenancy context.
*/
public static TenancyContextHolderStrategy getStrategy() {
return strategy;
}
/**
* Set the context strategy.
*
* @param strategy
* the configured strategy for storing the tenancy context.
*/
public static void setStrategy(TenancyContextHolderStrategy strategy) {
if (strategy == null) {
throw new IllegalArgumentException();
}
TenancyContextHolder.strategy = strategy;
}
/**
* Primarily for troubleshooting purposes, this method shows how many times the class
* has re-initialized its <code>TenancyContextHolderStrategy</code>.
*
* @return the count (should be one unless you've called
* {@link #setStrategyName(String)} to switch to an alternate strategy.
*/
public static int getInitializeCount() {
return initializeCount;
}
private static void initialize() {
if (strategyName == null || "".equals(strategyName)) {
// Set default
strategyName = MODE_THREADLOCAL;
}
if (strategyName.equals(MODE_THREADLOCAL)) {
strategy = new ThreadLocalTenancyContextHolderStrategy();
} else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) {
strategy = new InheritableThreadLocalTenancyContextHolderStrategy();
} else if (strategyName.equals(MODE_GLOBAL)) {
strategy = new GlobalTenancyContextHolderStrategy();
} else {
// Try to load a custom strategy
try {
Class<?> clazz = Class.forName(strategyName);
Constructor<?> customStrategy = clazz.getConstructor();
strategy = (TenancyContextHolderStrategy) customStrategy.newInstance();
} catch (Exception ex) {
throw new UndeclaredThrowableException(ex);
}
}
initializeCount++;
}
/**
* Changes the preferred strategy. Do <em>NOT</em> call this method more than once for
* a given JVM, as it will re-initialize the strategy and adversely affect any
* existing threads using the old strategy.
*
* @param strategyName the fully qualified class name of the strategy that should be
* used.
*/
public static void setStrategyName(String strategyName) {
TenancyContextHolder.strategyName = strategyName;
initialize();
}
public String toString() {
return "TenancyContextHolder[strategy='" + strategyName + "'; initializeCount=" + initializeCount + "]";
}
}
| 36.300578 | 119 | 0.663694 |
2658009f214bd95a341edc0032110fbf2d1de9a2 | 415 | package io.renren.modules.sys.service;
import com.baomidou.mybatisplus.service.IService;
import io.renren.common.utils.PageUtils;
import io.renren.modules.sys.entity.AgentIpEntity;
import java.util.Map;
/**
*
*
* @author wdh
* @email 594340717@qq.com
* @date 2018-12-24 00:29:21
*/
public interface AgentIpService extends IService<AgentIpEntity> {
PageUtils queryPage(Map<String, Object> params);
}
| 19.761905 | 65 | 0.749398 |
312bc63b8ba92ae521b0c69544e4d1703c6a84ec | 756 | package org.fog.utils;
public class CanBeSentResult {
private double cpuLoad;
private double nwLoad;
private boolean canBeSent;
public CanBeSentResult(double cpuLoad, double nwLoad, boolean canBeSent){
this.cpuLoad = cpuLoad;
this.nwLoad = nwLoad;
this.canBeSent = canBeSent;
}
public CanBeSentResult() {
// TODO Auto-generated constructor stub
}
public double getCpuLoad() {
return cpuLoad;
}
public void setCpuLoad(double cpuLoad) {
this.cpuLoad = cpuLoad;
}
public double getNwLoad() {
return nwLoad;
}
public void setNwLoad(double nwLoad) {
this.nwLoad = nwLoad;
}
public boolean isCanBeSent() {
return canBeSent;
}
public void setCanBeSent(boolean canBeSent) {
this.canBeSent = canBeSent;
}
}
| 16.085106 | 74 | 0.716931 |
4db4e7ed054b328560a4353805c65bf4923956a0 | 1,289 | package com.twa.flights.api.clusters.configuration;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.twa.flights.api.clusters.enums.CacheName;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
@Configuration
@EnableCaching
public class CacheManagerConfiguration {
@Autowired
private CacheConfiguration cacheConfiguration;
@Bean
public CacheManager cacheManager() {
CaffeineCacheManager catalogCacheManager = new CaffeineCacheManager();
catalogCacheManager.setCacheNames(Arrays.asList(CacheName.Constants.CITY_CACHE_VALUE));
catalogCacheManager.setCaffeine(caffeineConfig());
return catalogCacheManager;
}
@Bean
public Caffeine caffeineConfig() {
return Caffeine.newBuilder().expireAfterWrite(cacheConfiguration.getCache().getDuration(), TimeUnit.MINUTES)
.maximumSize(cacheConfiguration.getCache().getMaxElements());
}
}
| 34.837838 | 116 | 0.791311 |
8a9adae4352cceb3df20c1ef049859a0e6a7bc8e | 11,106 | /*******************************************************************************
* Copyright (c) 2005, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.ltk.internal.core.refactoring;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import com.ibm.icu.text.Collator;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.ltk.core.refactoring.IRefactoringCoreStatusCodes;
import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
/**
* Transformer for XML-based refactoring histories.
*
* @since 3.2
*/
public final class RefactoringSessionTransformer {
/** Comparator for attributes */
private static final class AttributeComparator implements Comparator {
/**
* {@inheritDoc}
*/
public int compare(final Object first, final Object second) {
final Attr predecessor= (Attr) first;
final Attr successor= (Attr) second;
return Collator.getInstance().compare(predecessor.getName(), successor.getName());
}
}
/** The current document, or <code>null</code> */
private Document fDocument= null;
/** Should project information be included? */
private final boolean fProjects;
/** The current refactoring node, or <code>null</code> */
private Node fRefactoring= null;
/** The current refactoring arguments, or <code>null</code> */
private List fRefactoringArguments= null;
/** The current session node, or <code>null</code> */
private Node fSession= null;
/** The current session arguments, or <code>null</code> */
private List fSessionArguments= null;
/**
* Creates a new refactoring session transformer.
*
* @param projects
* <code>true</code> to include project information,
* <code>false</code> otherwise
*/
public RefactoringSessionTransformer(final boolean projects) {
fProjects= projects;
}
/**
* Adds the attributes specified in the list to the node, in ascending order
* of their names.
*
* @param node
* the node
* @param list
* the list of attributes
*/
private void addArguments(final Node node, final List list) {
final NamedNodeMap map= node.getAttributes();
if (map != null) {
Collections.sort(list, new AttributeComparator());
for (final Iterator iterator= list.iterator(); iterator.hasNext();) {
final Attr attribute= (Attr) iterator.next();
map.setNamedItem(attribute);
}
}
}
/**
* Begins the transformation of a refactoring specified by the given
* arguments.
* <p>
* Calls to
* {@link RefactoringSessionTransformer#beginRefactoring(String, long, String, String, String, int)}
* must be balanced with calls to
* {@link RefactoringSessionTransformer#endRefactoring()}. If the
* transformer is already processing a refactoring, nothing happens.
* </p>
*
* @param id
* the unique identifier of the refactoring
* @param stamp
* the time stamp of the refactoring, or <code>-1</code>
* @param project
* the non-empty name of the project this refactoring is
* associated with, or <code>null</code>
* @param description
* a human-readable description of the refactoring
* @param comment
* the comment associated with the refactoring, or
* <code>null</code>
* @param flags
* the flags associated with refactoring
* @throws CoreException
* if an error occurs while creating a new refactoring
*/
public void beginRefactoring(final String id, long stamp, final String project, final String description, final String comment, final int flags) throws CoreException {
Assert.isNotNull(id);
Assert.isNotNull(description);
Assert.isTrue(flags >= RefactoringDescriptor.NONE);
try {
if (fDocument == null)
fDocument= DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
} catch (ParserConfigurationException exception) {
throw new CoreException(new Status(IStatus.ERROR, RefactoringCorePlugin.getPluginId(), IRefactoringCoreStatusCodes.REFACTORING_HISTORY_IO_ERROR, exception.getLocalizedMessage(), null));
} catch (FactoryConfigurationError exception) {
throw new CoreException(new Status(IStatus.ERROR, RefactoringCorePlugin.getPluginId(), IRefactoringCoreStatusCodes.REFACTORING_HISTORY_IO_ERROR, exception.getLocalizedMessage(), null));
}
if (fRefactoring == null) {
try {
fRefactoringArguments= new ArrayList(16);
fRefactoring= fDocument.createElement(IRefactoringSerializationConstants.ELEMENT_REFACTORING);
Attr attribute= fDocument.createAttribute(IRefactoringSerializationConstants.ATTRIBUTE_ID);
attribute.setValue(id);
fRefactoringArguments.add(attribute);
if (stamp >= 0) {
attribute= fDocument.createAttribute(IRefactoringSerializationConstants.ATTRIBUTE_STAMP);
attribute.setValue(new Long(stamp).toString());
fRefactoringArguments.add(attribute);
}
if (flags != RefactoringDescriptor.NONE) {
attribute= fDocument.createAttribute(IRefactoringSerializationConstants.ATTRIBUTE_FLAGS);
attribute.setValue(String.valueOf(flags));
fRefactoringArguments.add(attribute);
}
attribute= fDocument.createAttribute(IRefactoringSerializationConstants.ATTRIBUTE_DESCRIPTION);
attribute.setValue(description);
fRefactoringArguments.add(attribute);
if (comment != null && !"".equals(comment)) { //$NON-NLS-1$
attribute= fDocument.createAttribute(IRefactoringSerializationConstants.ATTRIBUTE_COMMENT);
attribute.setValue(comment);
fRefactoringArguments.add(attribute);
}
if (project != null && fProjects) {
attribute= fDocument.createAttribute(IRefactoringSerializationConstants.ATTRIBUTE_PROJECT);
attribute.setValue(project);
fRefactoringArguments.add(attribute);
}
if (fSession == null)
fDocument.appendChild(fRefactoring);
else
fSession.appendChild(fRefactoring);
} catch (DOMException exception) {
throw new CoreException(new Status(IStatus.ERROR, RefactoringCorePlugin.getPluginId(), IRefactoringCoreStatusCodes.REFACTORING_HISTORY_FORMAT_ERROR, exception.getLocalizedMessage(), null));
}
}
}
/**
* Begins the transformation of a refactoring session.
* <p>
* Calls to
* {@link RefactoringSessionTransformer#beginSession(String, String)} must
* be balanced with calls to
* {@link RefactoringSessionTransformer#endSession()}. If the transformer
* is already processing a session, nothing happens.
* </p>
*
* @param comment
* the comment associated with the refactoring session, or
* <code>null</code>
* @param version
* the non-empty version tag
* @throws CoreException
* if an error occurs while creating a new session
*/
public void beginSession(final String comment, final String version) throws CoreException {
if (fDocument == null) {
try {
fDocument= DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
fSession= fDocument.createElement(IRefactoringSerializationConstants.ELEMENT_SESSION);
fSessionArguments= new ArrayList(2);
Attr attribute= fDocument.createAttribute(IRefactoringSerializationConstants.ATTRIBUTE_VERSION);
attribute.setValue(version);
fSessionArguments.add(attribute);
if (comment != null && !"".equals(comment)) { //$NON-NLS-1$
attribute= fDocument.createAttribute(IRefactoringSerializationConstants.ATTRIBUTE_COMMENT);
attribute.setValue(comment);
fSessionArguments.add(attribute);
}
fDocument.appendChild(fSession);
} catch (DOMException exception) {
throw new CoreException(new Status(IStatus.ERROR, RefactoringCorePlugin.getPluginId(), IRefactoringCoreStatusCodes.REFACTORING_HISTORY_FORMAT_ERROR, exception.getLocalizedMessage(), null));
} catch (ParserConfigurationException exception) {
throw new CoreException(new Status(IStatus.ERROR, RefactoringCorePlugin.getPluginId(), IRefactoringCoreStatusCodes.REFACTORING_HISTORY_IO_ERROR, exception.getLocalizedMessage(), null));
}
}
}
/**
* Creates a refactoring argument with the specified name and value.
* <p>
* If no refactoring is currently processed, this call has no effect.
* </p>
*
* @param name
* the non-empty name of the argument
* @param value
* the value of the argument
*
* @throws CoreException
* if an error occurs while creating a new argument
*/
public void createArgument(final String name, final String value) throws CoreException {
Assert.isNotNull(name);
Assert.isTrue(!"".equals(name)); //$NON-NLS-1$
Assert.isNotNull(value);
if (fDocument != null && fRefactoringArguments != null && value != null) {
try {
final Attr attribute= fDocument.createAttribute(name);
attribute.setValue(value);
fRefactoringArguments.add(attribute);
} catch (DOMException exception) {
throw new CoreException(new Status(IStatus.ERROR, RefactoringCorePlugin.getPluginId(), IRefactoringCoreStatusCodes.REFACTORING_HISTORY_FORMAT_ERROR, exception.getLocalizedMessage(), null));
}
}
}
/**
* Ends the transformation of the current refactoring.
* <p>
* If no refactoring is currently processed, this call has no effect.
* </p>
*/
public void endRefactoring() {
if (fRefactoring != null && fRefactoringArguments != null)
addArguments(fRefactoring, fRefactoringArguments);
fRefactoringArguments= null;
fRefactoring= null;
}
/**
* Ends the transformation of the current refactoring session.
* <p>
* If no refactoring session is currently processed, this call has no
* effect.
* </p>
*/
public void endSession() {
if (fSession != null && fSessionArguments != null)
addArguments(fSession, fSessionArguments);
fSessionArguments= null;
fSession= null;
}
/**
* Returns the result of the transformation process.
* <p>
* This method must only be called once during the life time of a
* transformer.
* </p>
*
* @return the object representing the refactoring session, or
* <code>null</code> if no session has been transformed
*/
public Document getResult() {
final Document document= fDocument;
fDocument= null;
return document;
}
}
| 36.89701 | 193 | 0.71682 |
36151cb5caef402eb4826c3573ddd46739cd30d0 | 13,100 | /*
* Copyright (C) 2019 Parrot Drones SAS
*
* 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 Parrot Company 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
* PARROT COMPANY 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 com.parrot.drone.groundsdk.arsdkengine.http;
import androidx.annotation.NonNull;
import com.parrot.drone.groundsdk.internal.http.HttpClient;
import com.parrot.drone.groundsdk.internal.http.HttpRequest;
import com.parrot.drone.groundsdk.internal.http.HttpSession;
import com.parrot.drone.groundsdk.internal.io.Files;
import com.parrot.drone.groundsdk.internal.io.IoStreams;
import com.parrot.drone.groundsdk.internal.tasks.Executor;
import com.parrot.drone.groundsdk.internal.tasks.Task;
import com.parrot.drone.sdkcore.ulog.ULog;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.concurrent.Callable;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Streaming;
import retrofit2.http.Url;
import static com.parrot.drone.groundsdk.arsdkengine.Logging.TAG_HTTP;
/** Client of PUD HTTP service. */
public class HttpPudClient extends HttpClient {
/**
* Size of chunk of downloaded data. When a report is being downloaded, data is read from the network in chunks of
* {@code CHUNK_SIZE} bytes and written to the file system.
*/
private static final int CHUNK_SIZE = 8192; // we use the same size as Okio segments, for consistency
/** Implementation of PUD REST API. */
@NonNull
private final ReportService mService;
/**
* Constructor.
*
* @param session HTTP session
*/
@SuppressWarnings("WeakerAccess") // Accessed by introspection
public HttpPudClient(@NonNull HttpSession session) {
mService = session.create(new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()),
ReportService.class);
}
/**
* Lists available PUDs on device.
*
* @param callback listener for request completion
*
* @return a cancellable request
*/
@NonNull
public HttpRequest listPuds(@NonNull HttpRequest.ResultCallback<List<HttpPudInfo>> callback) {
Call<List<HttpPudInfo>> listReportsCall = mService.getPuds();
listReportsCall.enqueue(new Callback<List<HttpPudInfo>>() {
@Override
public void onResponse(Call<List<HttpPudInfo>> call, Response<List<HttpPudInfo>> response) {
int code = response.code();
if (response.isSuccessful()) {
callback.onRequestComplete(HttpRequest.Status.SUCCESS, code, response.body());
} else {
if (ULog.e(TAG_HTTP)) {
ULog.e(TAG_HTTP, "Failed to get PUD list [code: " + code + "]");
}
callback.onRequestComplete(HttpRequest.Status.FAILED, code, null);
}
}
@Override
public void onFailure(Call<List<HttpPudInfo>> call, Throwable error) {
if (call.isCanceled()) {
callback.onRequestComplete(HttpRequest.Status.CANCELED, HttpRequest.STATUS_CODE_UNKNOWN, null);
} else {
if (ULog.e(TAG_HTTP)) {
ULog.e(TAG_HTTP, "Failed to get PUD list", error);
}
callback.onRequestComplete(HttpRequest.Status.FAILED, HttpRequest.STATUS_CODE_UNKNOWN, null);
}
}
});
return bookRequest(listReportsCall::cancel);
}
/** Allows to adapt received PUD to some custom format. */
public interface PudAdapter {
/**
* Transfers PUD data while adapting it on-the-fly.
*
* @param input input to read PUD data from
* @param output output to write adapted content to
*
* @throws IOException in case the operation fails for any reason
* @throws InterruptedException in case the current thread was interrupted during the operation
*/
void adapt(@NonNull InputStream input, @NonNull OutputStream output) throws IOException, InterruptedException;
}
/**
* Downloads a PUD.
* <p>
* This method downloads to a temporary file named by post-fixing {@code dest} with {@code '.tmp'} that is renamed
* to {@code dest} once the download is successful.
* <p>
* Received PUD data is written as-is to {@code dest}.
*
* @param url relative url of the PUD, as returned by {@link HttpPudInfo#getUrl()}
* @param dest destination file of the downloaded PUD
* @param callback listener for request completion
*
* @return a cancellable request
*
* @see #downloadPud(String, File, PudAdapter, HttpRequest.StatusCallback)
*/
@NonNull
public HttpRequest downloadPud(@NonNull String url, @NonNull File dest,
@NonNull HttpRequest.StatusCallback callback) {
return downloadPud(url, dest, (input, output) -> IoStreams.transfer(input, output, CHUNK_SIZE), callback);
}
/**
* Downloads a PUD.
* <p>
* This method downloads to a temporary file named by post-fixing {@code dest} with {@code '.tmp'} that is renamed
* to {@code dest} once the download is successful.
* <p>
* This method allows to adapt received PUD content to a custom format before writing to {@code dest}. Adapt process
* occurs on a background thread.
*
* @param url relative url of the PUD, as returned by {@link HttpPudInfo#getUrl()}
* @param dest destination file of the downloaded PUD
* @param adapter adapts received PUD content to some custom format
* @param callback listener for request completion
*
* @return a cancellable request
*
* @see #deletePud(String, HttpRequest.StatusCallback)
*/
@NonNull
public HttpRequest downloadPud(@NonNull String url, @NonNull File dest,
@NonNull PudAdapter adapter,
@NonNull HttpRequest.StatusCallback callback) {
Call<ResponseBody> downloadCall = mService.downloadPud(url);
Task<Void> downloadTask = Executor.runInBackground((Callable<Void>) () -> {
Response<ResponseBody> response = downloadCall.execute();
if (downloadCall.isCanceled()) {
// retrofit call.execute silently eats InterruptedException, so we rely on the call canceled flag
// to restore the interruption status after the call
throw new InterruptedException("Canceled retrofit call");
}
ResponseBody body = response.body();
if (!response.isSuccessful()) {
throw new HttpException(response.message(), response.code());
}
assert body != null;
try {
Files.makeDirectories(dest.getParentFile());
File tmpDest = new File(dest.getAbsolutePath() + ".tmp");
try (OutputStream output = new FileOutputStream(tmpDest)) {
adapter.adapt(body.byteStream(), output);
output.flush();
}
if (!tmpDest.renameTo(dest)) {
throw new IOException("Failed to rename PUD file [tmpDest: " + tmpDest
+ ", dest: " + dest + "]");
}
return null;
} catch (IOException | InterruptedException e) {
// ensure we cleanup the file before getting out of the background task
if (dest.exists() && !dest.delete() && ULog.w(TAG_HTTP)) {
ULog.w(TAG_HTTP, "Could not clean up partially downloaded PUD: " + dest);
}
throw e;
} finally {
body.close();
}
}).whenComplete((result, error, canceled) -> {
if (error != null) {
if (ULog.e(TAG_HTTP)) {
ULog.e(TAG_HTTP, "PUD download request failed [url:" + url + ", dest: " + dest + "]", error);
}
callback.onRequestComplete(HttpRequest.Status.FAILED, error instanceof HttpException ?
((HttpException) error).getCode() : HttpRequest.STATUS_CODE_UNKNOWN);
} else if (canceled) {
callback.onRequestComplete(HttpRequest.Status.CANCELED, HttpRequest.STATUS_CODE_UNKNOWN);
} else {
callback.onRequestComplete(HttpRequest.Status.SUCCESS, 200);
}
});
return bookRequest(() -> {
downloadCall.cancel();
downloadTask.cancel();
});
}
/**
* Deletes a PUD.
*
* @param name PUD name, as returned by {@link HttpPudInfo#getName()}
* @param callback listener for request completion
*
* @return a cancellable request
*/
@NonNull
public HttpRequest deletePud(@NonNull String name, @NonNull HttpRequest.StatusCallback callback) {
Call<Void> deleteReportCall = mService.deletePud(name);
deleteReportCall.enqueue(new Callback<Void>() {
@Override
public void onResponse(Call<Void> call, Response<Void> response) {
int code = response.code();
if (response.isSuccessful()) {
callback.onRequestComplete(HttpRequest.Status.SUCCESS, code);
} else {
if (ULog.e(TAG_HTTP)) {
ULog.e(TAG_HTTP, "Failed to delete PUD [code: " + code + "]");
}
callback.onRequestComplete(HttpRequest.Status.FAILED, code);
}
}
@Override
public void onFailure(Call<Void> call, Throwable error) {
if (call.isCanceled()) {
callback.onRequestComplete(HttpRequest.Status.CANCELED, HttpRequest.STATUS_CODE_UNKNOWN);
} else {
if (ULog.e(TAG_HTTP)) {
ULog.e(TAG_HTTP, "Failed to delete PUD", error);
}
callback.onRequestComplete(HttpRequest.Status.FAILED, HttpRequest.STATUS_CODE_UNKNOWN);
}
}
});
return bookRequest(deleteReportCall::cancel);
}
/** REST API. */
private interface ReportService {
/**
* Retrieves the list of available PUDs on the device.
*
* @return report list
*/
@GET("api/v1/pud/puds")
Call<List<HttpPudInfo>> getPuds();
/**
* Downloads a PUD.
*
* @param url url of the PUD, as returned by {@link HttpPudInfo#getUrl()}
*
* @return a retrofit call with a response body containing report data
*/
@Streaming
@GET
Call<ResponseBody> downloadPud(@Url String url);
/**
* Deletes a PUD.
*
* @param name name of the PUD, as returned by {@link HttpPudInfo#getName()}
*
* @return a retrofit call for the request
*/
@DELETE("api/v1/pud/puds/{name}")
Call<Void> deletePud(@Path("name") String name);
}
}
| 40.809969 | 120 | 0.609466 |
f1aa8aeca16eb8157663467ca8b50748c8a8d5fd | 6,077 | package cepl.motor;
import java.util.*;
public class MatchGrouping implements Iterable<Match> {
private LinkedList<ExtensibleList> final_lists;
private NXTNode final_node;
private long totalMatches;
private Semantic semantic;
private Hashtable<Integer, Event> usefulValues;
private Event lastEvent;
protected MatchGrouping(Semantic semantic, Hashtable<Integer, Event> usefulValues, int i){
this.semantic = semantic;
this.usefulValues = usefulValues;
this.lastEvent = usefulValues.get(i);
totalMatches = 0;
if (semantic == Semantic.NXT || semantic == Semantic.LAST) {
final_node = NXTNode.Empty;
}
else if (semantic == Semantic.ANY || semantic == Semantic.MAX || semantic == Semantic.STRICT){
final_lists = new LinkedList<ExtensibleList>();
}
}
protected void addFinal(ExtensibleList final_list){
final_lists.add(final_list);
totalMatches += final_list.totalMatches;
}
protected void addFinal(NXTNode final_node){
this.final_node = final_node;
this.totalMatches = 1;
}
public long size(){
return totalMatches;
}
public Event lastEvent(){
return lastEvent;
}
public Iterator<Match> iterator(){
if (semantic == Semantic.NXT || semantic == Semantic.LAST){
return new MatchGroupingIterator(final_node, usefulValues);
}
else if (semantic == Semantic.ANY || semantic == Semantic.MAX || semantic == Semantic.STRICT ){
return new MatchGroupingIterator(final_lists, usefulValues);
}
// this should not be happening ever
return null;
}
}
class MatchGroupingIterator implements Iterator<Match> {
private Match matchStack;
private Semantic semantic;
private Hashtable<Integer, Event> usefulValues;
private NXTNode final_node;
private Iterator<ExtensibleList> final_list_iter;
private Iterator<Node> curr_final_list;
private Stack<Iterator<Node>> nodeStack;
private Stack<LLNode<Event>> jumpStack;
private LLNode<Event> lastEv;
private Node aux, current;
private Iterator<Node> it;
private boolean first_part;
protected MatchGroupingIterator(NXTNode final_node, Hashtable<Integer, Event> usefulValues){
this.usefulValues = usefulValues;
this.final_node = final_node;
matchStack = new Match();
semantic = Semantic.NXT;
}
protected MatchGroupingIterator(LinkedList<ExtensibleList> final_lists, Hashtable<Integer, Event> usefulValues){
this.usefulValues = usefulValues;
final_list_iter = final_lists.iterator();
curr_final_list = final_list_iter.next().iterator();
semantic = Semantic.ANY;
matchStack = new Match();
nodeStack = new Stack<Iterator<Node>>();
jumpStack = new Stack<LLNode<Event>>();
}
public boolean hasNext(){
if (semantic == semantic.NXT){
return !final_node.isEmpty();
}
if (semantic == Semantic.ANY){
return !nodeStack.isEmpty() || curr_final_list.hasNext() || final_list_iter.hasNext() ;
}
return false;
}
public Match next(){
if (semantic == Semantic.ANY) {
// Any enumeration algorithm
if (nodeStack.empty()){
if (!curr_final_list.hasNext()){
curr_final_list = final_list_iter.next().iterator();
}
current = curr_final_list.next();
matchStack.clear();
jumpStack.clear();
lastEv = matchStack.push(usefulValues.get(current.i));
first_part = true;
}
if (!first_part){
matchStack.popUntil(lastEv);
while (!nodeStack.empty()){
it = nodeStack.pop();
lastEv = jumpStack.pop();
current = it.next();
if (current.isEmpty()){
return matchStack;
}
if (it.hasNext()){
nodeStack.push(it);
jumpStack.push(lastEv);
lastEv = matchStack.push(usefulValues.get(current.i));
}
else {
matchStack.push(usefulValues.get(current.i));
}
while (true){
it = current.next.iterator();
current = it.next();
if (current.isEmpty()){
return matchStack;
}
if (it.hasNext()){
nodeStack.push(it);
jumpStack.push(lastEv);
lastEv = matchStack.push(usefulValues.get(current.i));
}
else {
matchStack.push(usefulValues.get(current.i));
}
}
}
}
while (first_part){
it = current.next.iterator();
current = it.next();
if (current.isEmpty()){
first_part = false;
return matchStack;
}
if (it.hasNext()){
nodeStack.push(it);
jumpStack.push(lastEv);
lastEv = matchStack.push(usefulValues.get(current.i));
}
else {
matchStack.push(usefulValues.get(current.i));
}
}
}
else if (semantic == Semantic.NXT){
// Nxt enumeration algorithm
for (; !final_node.isEmpty(); final_node = final_node.next() ){
matchStack.push(usefulValues.get(final_node.i));
}
}
return matchStack;
}
}
| 33.574586 | 116 | 0.529373 |
b0ed333852d9d1e4530400013a481d8ebd5780cb | 644 | package com.direwolf20.logisticslasers.common.container.customslot;
import com.direwolf20.logisticslasers.common.items.logiccards.BaseCard;
import net.minecraft.item.ItemStack;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.SlotItemHandler;
import javax.annotation.Nonnull;
public class CardSlot extends SlotItemHandler {
public CardSlot(IItemHandler itemHandler, int index, int xPosition, int yPosition) {
super(itemHandler, index, xPosition, yPosition);
}
@Override
public boolean isItemValid(@Nonnull ItemStack stack) {
return (stack.getItem() instanceof BaseCard);
}
}
| 32.2 | 88 | 0.781056 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.